public void Add_HtmlObject(bool isVoid)
        {
            HtmlElement parent = new HtmlElement("parent", isVoid);

            // Atribute
            HtmlAttribute attribute = new HtmlAttribute("attribute");
            parent.Add(attribute);
            Assert.Equal(parent, attribute.Parent);
            Assert.Equal(new HtmlAttribute[] { attribute }, parent.Attributes());

            if (!isVoid)
            {
                // Element
                HtmlElement element = new HtmlElement("element");
                parent.Add(element);
                Assert.Equal(parent, element.Parent);
                Assert.Equal(new HtmlElement[] { element }, parent.Elements());

                // Nodes
                HtmlComment comment = new HtmlComment("comment");
                parent.Add(comment);
                Assert.Equal(parent, comment.Parent);
                Assert.Equal(new HtmlObject[] { element, comment }, parent.Nodes());
            }
        }
        public void ReplaceAll_IEnumerableHtmlObject_AttributeToVoidElement()
        {
            HtmlElement parent = new HtmlElement("parent", isVoid: true);
            parent.Add(new HtmlAttribute("attribute"));

            HtmlAttribute[] attributes = new HtmlAttribute[] { new HtmlAttribute("attribute1"), new HtmlAttribute("attribute2") };
            parent.ReplaceAll((IEnumerable<HtmlObject>)attributes);
            Assert.Equal(attributes, parent.Attributes());
        }
        public void Add_ParamsHtmlObject_VoidElement()
        {
            HtmlElement element = new HtmlElement("parent", isVoid: true);
            HtmlAttribute attribute1 = new HtmlAttribute("attribute1");
            HtmlAttribute attribute2 = new HtmlAttribute("attribute2");
            element.Add(new HtmlObject[] { attribute1, attribute2 });

            Assert.Equal(element, attribute1.Parent);
            Assert.Equal(element, attribute2.Parent);
            Assert.Empty(element.Elements());
            Assert.Equal(new HtmlAttribute[] { attribute1, attribute2 }, element.Attributes());
        }
        public void Add_IEnumerableHtmlObject_NonVoidElement()
        {
            HtmlElement parent = new HtmlElement("parent");
            HtmlElement element = new HtmlElement("element");
            HtmlAttribute attribute = new HtmlAttribute("Attribute");
            parent.Add((IEnumerable<HtmlObject>)new HtmlObject[] { element, attribute });

            Assert.Equal(parent, element.Parent);
            Assert.Equal(parent, attribute.Parent);
            Assert.Equal(new HtmlObject[] { element }, parent.Elements());
            Assert.Equal(new HtmlAttribute[] { attribute }, parent.Attributes());
        }
        private static string InternalTextArea(Tk5FieldInfoEx field, DataRow row, HtmlAttribute addition, bool needId)
        {
            TkDebug.AssertArgumentNull(field, "field", null);

            HtmlAttributeBuilder builder = new HtmlAttributeBuilder();
            AddInputAttribute(field, builder);
            AddNormalAttribute(field, builder, field.NickName, needId);
            builder.Add(addition);

            return string.Format(ObjectUtil.SysCulture, "<textarea {0}>{1}</textarea>{2}",
                builder.CreateAttribute(), StringUtil.EscapeHtml(row.GetString(field.NickName)),
                ERROR_LABEL);
        }
        public void Add_ParamsHtmlObject_NonVoidElement()
        {
            HtmlElement parent = new HtmlElement("parent");
            HtmlElement element = new HtmlElement("element");
            HtmlAttribute attribute = new HtmlAttribute("attribute");
            HtmlComment comment = new HtmlComment("comment");
            parent.Add(new HtmlObject[] { element, attribute, comment });

            Assert.Equal(parent, element.Parent);
            Assert.Equal(parent, attribute.Parent);
            Assert.Equal(new HtmlObject[] { element }, parent.Elements());
            Assert.Equal(new HtmlAttribute[] { attribute }, parent.Attributes());
            Assert.Equal(new HtmlObject[] { element, comment }, parent.Nodes());
        }
Exemple #7
0
        //public static Domain.Socioboard.Domain.PluginInfo CreateThumbnail(string Url)
        //{

        //    #region UrlIformation
        //    string description = "";
        //    string imgurl = "";
        //    Domain.Socioboard.Domain.PluginInfo _plugininfo = new Domain.Socioboard.Domain.PluginInfo();

        //        if (!Url.Contains("socioboard"))
        //        {
        //            string pagesource = GetHtml(Url);
        //            if (pagesource.Contains("<img") && !string.IsNullOrEmpty(pagesource))
        //            {

        //                string[] atrr = Regex.Split(pagesource, "<img");
        //                foreach (var item in atrr)
        //                {
        //                    if (item.Contains("src") && !item.Contains("<!DOCTYPE html>"))
        //                    {
        //                        string url = "";
        //                        try
        //                        {
        //                            url = getBetween(item, "src=\"", "alt=").Replace("\"", string.Empty);
        //                        }
        //                        catch (Exception ex)
        //                        {

        //                            url = getBetween(item, "src=\"", "\"").Replace("\"", string.Empty);
        //                        }
        //                        imgurl = url + ":" + imgurl;
        //                    }
        //                }
        //            }
        //            if (pagesource.Contains("<meta"))
        //            {
        //                string[] metatag = Regex.Split(pagesource, "<meta");
        //                foreach (var item in metatag)
        //                {
        //                    if (item.Contains("description"))
        //                    {
        //                        description = getBetween(item, "content=", ">").Replace("\"", "").Replace("/", "");

        //                    }
        //                }
        //            }
        //        }
        //        else
        //        {

        //            string pagesource = GetHtml(Url);
        //            if (pagesource.Contains("<img") && !string.IsNullOrEmpty(pagesource))
        //            {

        //                string[] atrr = Regex.Split(pagesource, "<img");
        //                foreach (var item in atrr)
        //                {
        //                    if (item.Contains("src") && !item.Contains("<!DOCTYPE"))
        //                    {
        //                        string url = "";
        //                        if (item.Contains("/Themes"))
        //                        {
        //                            url = getBetween(item, "src=", "alt=").Replace("\"", string.Empty);
        //                            url = "https://www.socioboard.com" + url;

        //                        }
        //                        else
        //                        {
        //                            url = getBetween(item, "src=", "class=").Replace("\"", string.Empty);
        //                        }

        //                        imgurl = url + ":" + imgurl;
        //                    }
        //                }
        //            }
        //            if (pagesource.Contains("<meta"))
        //            {
        //                string[] metatag = Regex.Split(pagesource, "<meta");
        //                foreach (var item in metatag)
        //                {
        //                    if (item.Contains("description"))
        //                    {
        //                        description = getBetween(item, "content=", ">").Replace("\"", "").Replace("/", "");

        //                    }
        //                }
        //            }

        //        }

        //        _plugininfo.imageurl = imgurl;
        //        _plugininfo.url = Url;
        //        _plugininfo.description = description;

        //        return _plugininfo;

        //    #endregion

        //}

        //public static Chilkat.Http http = new Chilkat.Http();
        //public static string GetHtml(string URL)
        //{
        //    string response = string.Empty;

        //    //ChangeProxy();

        //    if (!http.UnlockComponent("THEBACHttp_b3C9o9QvZQ06"))
        //    {
        //    }

        //    ///Save Cookies...
        //    http.CookieDir = "memory";
        //    //http.CookieDir = Application.StartupPath + "\\cookies";
        //    http.SendCookies = true;
        //    http.SaveCookies = true;

        //    http.SetRequestHeader("Accept-Encoding", "gzip,deflate");
        //    http.SetRequestHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
        //    http.SetRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.107 Safari/537.36");
        //    http.SetRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");

        //    //http.SetRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        //    //http.SetRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        //    http.SetRequestHeader("Connection", "keep-alive");

        //    http.AllowGzip = true;

        //    response = http.QuickGetStr(URL);
        //    if (string.IsNullOrEmpty(response))
        //    {
        //        response = http.QuickGetStr(URL);

        //    }
        //    if (string.IsNullOrEmpty(response))
        //    {
        //        response = http.QuickGetStr(URL);

        //    }

        //    return response;

        //}

        //public static string getBetween(string strSource, string strStart, string strEnd)
        //{
        //    int Start, End;
        //    if (strSource.Contains(strStart) && strSource.Contains(strEnd))
        //    {
        //        Start = strSource.IndexOf(strStart, 0) + strStart.Length;
        //        End = strSource.IndexOf(strEnd, Start);
        //        return strSource.Substring(Start, End - Start);
        //    }
        //    else
        //    {
        //        return "";
        //    }
        //}

        public static Domain.Socioboard.Helpers.ThumbnailDetails CreateThumbnail(string url)
        {
            string        title       = string.Empty;
            string        description = string.Empty;
            string        image       = string.Empty;
            string        _url        = string.Empty;
            List <string> imageurls   = new List <string>();
            HtmlAttribute haDescription;
            HtmlAttribute haTitle;
            HtmlAttribute haImage;
            HtmlAttribute haUrl;
            string        location = HttpUtility.UrlDecode(url);

            Domain.Socioboard.Helpers.ThumbnailDetails _ThumbnailDetails = new Domain.Socioboard.Helpers.ThumbnailDetails();
            string html  = string.Empty;
            string _html = string.Empty;

            _url = location;
            while (!string.IsNullOrWhiteSpace(location))
            {
                if (!_url.Contains("twitter.com/i/notifications"))
                {
                    _url = location;
                    if (_url.Contains("dashboard.unhookme.com"))
                    {
                        _url = _url.Replace("statCounter", "Login");
                    }
                    if (_url.Contains("https://contest.edumongoose.com"))
                    {
                        _url = "https://contest.edumongoose.com/home.htm";
                    }
                }
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_url.Replace("i/notifications", ""));
                request.AllowAutoRedirect = false;
                request.UserAgent         = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36";

                try
                {
                    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                    {
                        location = response.GetResponseHeader("Location");
                        //charset="


                        if (response.StatusCode == HttpStatusCode.OK)
                        {
                            Stream       receiveStream = response.GetResponseStream();
                            StreamReader readStream    = null;

                            if (response.CharacterSet == null)
                            {
                                readStream = new StreamReader(receiveStream);
                            }
                            else
                            {
                                readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet.Replace("\"", "")));
                            }

                            html = readStream.ReadToEnd();

                            readStream.Close();
                        }
                        else if (response.StatusCode == HttpStatusCode.Found)
                        {
                            var uri = new Uri(_url);
                            location = uri.GetLeftPart(System.UriPartial.Authority);
                        }
                    }
                }
                catch (Exception ex)
                {
                    html = "";
                }
            }
            HtmlDocument hdoc = new HtmlDocument();

            if (!string.IsNullOrEmpty(html))
            {
                hdoc.LoadHtml(html);

                HtmlNode nodeDescrption = hdoc.DocumentNode.SelectSingleNode("//meta[@name='description']");
                if (nodeDescrption == null)
                {
                    nodeDescrption = hdoc.DocumentNode.SelectSingleNode("//meta[@property='og:description']");
                    if (nodeDescrption == null)
                    {
                        nodeDescrption = hdoc.DocumentNode.SelectSingleNode("//p");
                        if (nodeDescrption != null)
                        {
                            try
                            {
                                description    = nodeDescrption.InnerText;
                                nodeDescrption = null;
                            }
                            catch (Exception ex)
                            {
                                nodeDescrption = null;
                            }
                        }
                    }
                }
                if (nodeDescrption != null)
                {
                    haDescription = nodeDescrption.Attributes["content"];
                    description   = haDescription.Value;
                }
                else
                {
                }

                HtmlNode nodeTitle = hdoc.DocumentNode.SelectSingleNode("//meta[@name='title']");
                if (nodeTitle == null)
                {
                    nodeTitle = hdoc.DocumentNode.SelectSingleNode("//meta[@property='og:title']");
                    if (nodeTitle == null)
                    {
                        nodeTitle = hdoc.DocumentNode.SelectSingleNode("//title");
                    }
                }
                if (nodeTitle != null)
                {
                    try
                    {
                        haTitle = nodeTitle.Attributes["content"];
                        title   = haTitle.Value;
                        title   = title.Replace(" &amp; ", "&").Replace("nnn#8211", "").Replace("&#39;s", "").Replace("&#8211;", "");
                        //title = Regex.Replace(title, @"(\s+|@|&|'|\(|\)|<|>|#)", "");
                    }
                    catch (Exception ex)
                    {
                        try
                        {
                            title = nodeTitle.InnerText.Replace(" &amp; ", "&").Replace("nnn#8211", "").Replace("&#39;s", "").Replace("&#8211;", "");
                            //title= Regex.Replace(title, @"(\s+|@|&|'|\(|\)|<|>|#)", "");
                        }
                        catch (Exception exx)
                        {
                            title = "";
                        }
                    }
                }
                HtmlNodeCollection nodeimgs = new HtmlNodeCollection(hdoc.DocumentNode.ParentNode);
                nodeimgs = hdoc.DocumentNode.SelectNodes("//img");
                if (nodeimgs != null)
                {
                    foreach (HtmlNode img in nodeimgs)
                    {
                        try
                        {
                            HtmlAttribute src = img.Attributes["src"];
                            if (src.Value.Contains("https") || src.Value.Contains("https"))
                            {
                                bool imStatus = getHtmlfromUrl(src.Value.Replace("&amp;", "&"));
                                if (imStatus)
                                {
                                    imageurls.Add(src.Value);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                }
                HtmlNode nodeImage = hdoc.DocumentNode.SelectSingleNode("//meta[@name='image']");
                if (nodeImage == null)
                {
                    nodeImage = hdoc.DocumentNode.SelectSingleNode("//meta[@property='og:image']");

                    if (nodeImage == null)
                    {
                        try
                        {
                            nodeImage = hdoc.DocumentNode.SelectSingleNode("//img");
                            if (nodeImage != null)
                            {
                                haImage = nodeImage.Attributes["src"];
                                if (haImage.Value.Contains("https") || haImage.Value.Contains("https"))
                                {
                                    bool imStatus = getHtmlfromUrl(haImage.Value.Replace("&amp;", "&"));
                                    if (imStatus)
                                    {
                                        image = haImage.Value;
                                    }
                                }
                                nodeImage = null;
                            }
                        }
                        catch
                        {
                            nodeImage = null;
                        }
                    }
                }
                if (nodeImage != null)
                {
                    haImage = nodeImage.Attributes["content"];
                    bool imStatus = getHtmlfromUrl(haImage.Value.Replace("&amp;", "&"));
                    if (imStatus)
                    {
                        image = haImage.Value;
                    }
                }

                HtmlNode nodeUrl = hdoc.DocumentNode.SelectSingleNode("//meta[@name='url']");
                if (nodeUrl == null)
                {
                    nodeUrl = hdoc.DocumentNode.SelectSingleNode("//meta[@property='og:url']");
                }
                if (nodeUrl != null)
                {
                    haUrl = nodeUrl.Attributes["content"];
                    _url  = haUrl.Value;
                }
                _ThumbnailDetails.description = description;
                _ThumbnailDetails.image       = image;
                _ThumbnailDetails.title       = title;
                _ThumbnailDetails.url         = _url;
                _ThumbnailDetails.imageurls   = imageurls;
            }
            else
            {
                _ThumbnailDetails.description = "";
                _ThumbnailDetails.image       = "";
                _ThumbnailDetails.title       = "";
                _ThumbnailDetails.url         = _url;
                _ThumbnailDetails.imageurls   = new List <string>();
            }

            return(_ThumbnailDetails);
        }
Exemple #8
0
        private bool IsSimpleProperty(HtmlAttribute attr)
        {
            var name = attr.OriginalName;

            return(name.IndexOf(".") == -1);
        }
Exemple #9
0
 /// <summary>
 ///     Selects elements that have the specified <paramref name="attribute" /> with a <paramref name="value" /> containing
 ///     the a given substring.
 /// </summary>
 public JquerySelectorExtend ContainsAttribute(HtmlAttribute attribute, string value)
 {
     return(ContainsAttribute(attribute.ToString(), value));
 }
        public override void Execute() {
  
    NormalEditData pageData = ViewBag.PageData;
    HtmlAttribute retAttr = new HtmlAttribute("data-action", "return");

    Tk5NormalTableData table = ViewBag.MetaData.Table;
    List<Tk5FieldInfoEx> hiddenFields = table.HiddenList;
    List<Tk5FieldInfoEx> normalFields = table.TableList;
    int columnCount = table.ColumnCount;
    int columnWidth = 12 / columnCount;
    int fieldsCount = normalFields.Count;
    int columnFieldCount = fieldsCount / columnCount;
    
     if ((fieldsCount % columnCount) != 0){
        ++columnFieldCount;
    }
     

    ReportObjectData model = Model as ReportObjectData;
    ObjectContainer mainObject = model.Object;// HtmlUtil.GetMainObject(Model, ViewBag);
    ReportInfo rptInfo = model.Info;
    string dateValue = rptInfo.ReportDate == new DateTime() ? string.Empty : rptInfo.ReportDate.ToString("yyyy-MM-dd");
    HtmlAttribute attribute = new HtmlAttribute("data-url", ("Library/WebListXmlPage.tkx?Source=Accounting/ReportData&Company=" + rptInfo.Company).AppVirutalPath());

WriteLiteral("\r\n");

DefineSection("DefaultButtons", () => {

WriteLiteral("\r\n    <div");

WriteLiteral(" class=\"text-center clearfix\"");

WriteLiteral(">\r\n");

WriteLiteral("        ");

   Write(BootcssUtil.Button(pageData.SaveButtonCaption, "btn-submit", BootcssButton.Primary, false));

WriteLiteral("\r\n");

WriteLiteral("        ");

   Write(BootcssUtil.Button(pageData.CancelCaption, "m10", BootcssButton.Default, false, retAttr, attribute));

WriteLiteral("\r\n    </div>\r\n");

});

  

WriteLiteral("\r\n<form");

WriteAttribute("action", Tuple.Create(" action=\"", 2184), Tuple.Create("\"", 2221)
, Tuple.Create(Tuple.Create("", 2193), Tuple.Create<System.Object, System.Int32>(ViewBag.PageData.FormAction
, 2193), false)
);

WriteLiteral(" method=\"POST\"");

WriteLiteral(" id=\"PostForm\"");

WriteLiteral(" class=\"tk-dataform p5 mb15\"");

WriteLiteral(" role=\"form\"");

WriteLiteral(" data-check=\"true\"");

WriteLiteral(" data-post=\"");

                                                                                                                                        Write(GetJson(table));

WriteLiteral("\"");

WriteLiteral(">\r\n    <div");

WriteLiteral(" class=\"row tk-datatable table-row\"");

WriteLiteral(" id=\"Info\"");

WriteLiteral(">\r\n        <div");

WriteLiteral(" class=\"col-sm-4\"");

WriteLiteral(">\r\n            <div");

WriteLiteral(" class=\"row\"");

WriteLiteral(">\r\n                <label");

WriteLiteral(" class=\"col-sm-4\"");

WriteLiteral(" style=\"height:34px;line-height:34px\"");

WriteLiteral(">报表类型:</label>\r\n                <div");

WriteLiteral(" class=\"col-sm-8 \"");

WriteLiteral(">\r\n                    <span");

WriteLiteral(" class=\"tk-control\"");

WriteLiteral(">\r\n                        <select");

WriteLiteral(" id=\"ReportType\"");

WriteLiteral(" name=\"ReportType\"");

WriteLiteral(" class=\"form-control\"");

WriteLiteral(" data-title=\"市场板块\"");

WriteLiteral(">\r\n                            <option");

WriteLiteral(" value=\"01\"");

WriteLiteral(" ");

                                                if (rptInfo.ReportType == "01") { 

WriteLiteral("                                                   ");

WriteLiteral("selected\r\n");

                                     }
WriteLiteral(">合并报表</option>\r\n                            <option");

WriteLiteral(" value=\"02\"");

WriteLiteral(" ");

                                                if (rptInfo.ReportType == "02") { 

WriteLiteral("                                                   ");

WriteLiteral("selected\r\n");

                                     }
WriteLiteral(">母公司报表</option>\r\n                        </select>\r\n                    </span>\r\n" +
"                </div>\r\n               <br />\r\n            </div>\r\n        </div" +
">\r\n        <div");

WriteLiteral(" class=\"col-sm-6\"");

WriteLiteral(">\r\n            <label");

WriteLiteral(" class=\"col-sm-2\"");

WriteLiteral(">日期:</label>\r\n            <span");

WriteLiteral(" class=\"tk-control\"");

WriteLiteral(">\r\n                <div");

WriteLiteral(" class=\"input-group date\"");

WriteLiteral(" data-control=\"Date\"");

WriteLiteral(" data-date-format=\"yyyy-mm-dd\"");

WriteLiteral(" data-date=\"");

                                                                                                      Write(dateValue);

WriteLiteral("\"");

WriteLiteral(">\r\n                    <input");

WriteLiteral(" type=\"text\"");

WriteLiteral(" size=\"10\"");

WriteLiteral(" readonly");

WriteLiteral(" placeholder=\"日期\"");

WriteLiteral(" id=\"ReportDate\"");

WriteLiteral(" name=\"ReportDate\"");

WriteLiteral(" class=\"form-control\"");

WriteLiteral(" data-title=\"日期\"");

WriteAttribute("value", Tuple.Create(" value=\"", 3681), Tuple.Create("\"", 3699)
                                                                         , Tuple.Create(Tuple.Create("", 3689), Tuple.Create<System.Object, System.Int32>(dateValue
, 3689), false)
);

WriteLiteral(">\r\n                    <span");

WriteLiteral(" class=\"input-group-addon\"");

WriteLiteral("><i");

WriteLiteral(" class=\"glyphicon glyphicon-remove\"");

WriteLiteral("></i></span>\r\n                    <span");

WriteLiteral(" class=\"input-group-addon\"");

WriteLiteral("><i");

WriteLiteral(" class=\"glyphicon glyphicon-calendar\"");

WriteLiteral("></i></span>\r\n                </div>\r\n            </span>\r\n            <br />\r\n  " +
"      </div>\r\n        <div");

WriteLiteral(" class=\"col-sm-2\"");

WriteLiteral(">\r\n            <strong>单位:元</strong>\r\n            <input");

WriteLiteral(" id=\"ReportName\"");

WriteLiteral(" type=\"hidden\"");

WriteAttribute("value", Tuple.Create(" value=\"", 4107), Tuple.Create("\"", 4134)
, Tuple.Create(Tuple.Create("", 4115), Tuple.Create<System.Object, System.Int32>(rptInfo.ReportName
, 4115), false)
);

WriteLiteral(">\r\n            <input");

WriteLiteral(" id=\"Company\"");

WriteLiteral(" type=\"hidden\"");

WriteAttribute("value", Tuple.Create(" value=\"", 4183), Tuple.Create("\"", 4207)
, Tuple.Create(Tuple.Create("", 4191), Tuple.Create<System.Object, System.Int32>(rptInfo.Company
, 4191), false)
);

WriteLiteral(">\r\n            <input");

WriteLiteral(" id=\"ReportId\"");

WriteLiteral(" type=\"hidden\"");

WriteAttribute("value", Tuple.Create(" value=\"", 4257), Tuple.Create("\"", 4282)
, Tuple.Create(Tuple.Create("", 4265), Tuple.Create<System.Object, System.Int32>(rptInfo.ReportId
, 4265), false)
);

WriteLiteral(">\r\n        </div>\r\n    </div>\r\n    <br />\r\n    <div");

WriteAttribute("id", Tuple.Create(" id=\"", 4334), Tuple.Create("\"", 4355)
, Tuple.Create(Tuple.Create("", 4339), Tuple.Create<System.Object, System.Int32>(table.TableName
, 4339), false)
);

WriteAttribute("class", Tuple.Create(" class=\"", 4356), Tuple.Create("\"", 4451)
, Tuple.Create(Tuple.Create("", 4364), Tuple.Create<System.Object, System.Int32>(HtmlUtil.MergeClass("tk-datatable table-row", "column" + table.ColumnCount.ToString())
, 4364), false)
);

WriteLiteral(">\r\n        <div");

WriteLiteral(" class=\"hide\"");

WriteLiteral(">\r\n            ");

WriteLiteral("\r\n        </div>\r\n        <div");

WriteLiteral(" class=\"row\"");

WriteLiteral(">\r\n");

            
             for (int i = 0; i < columnCount; ++i)
            {
                
                  
                    int start = i * columnFieldCount;
                    int end = start + columnFieldCount;
                    if (end > fieldsCount){
                       end = fieldsCount;
                    }
                
                 

WriteLiteral("                <div");

WriteAttribute("class", Tuple.Create(" class=\"", 5023), Tuple.Create("\"", 5068)
, Tuple.Create(Tuple.Create("", 5031), Tuple.Create<System.Object, System.Int32>("col-sm-" + columnWidth.ToString()
, 5031), false)
);

WriteLiteral(">\r\n                    <table");

WriteLiteral(" class=\"table\"");

WriteLiteral(">\r\n                        <tr>\r\n                            <th>资产</th>\r\n       " +
"                     <th>行次</th>\r\n                            <th>期末数</th>\r\n    " +
"                    </tr>\r\n");

                        
                         for (int j = start; j < end; ++j)
                        {
                            
                              
                            var field = normalFields[j];

                            Tuple<int, byte, FieldStyle> info = field.Tag as Tuple<int, byte, FieldStyle>;
                            string intendClass = info.Item2 == 0 ? string.Empty : "class=\"pdl-" + info.Item2 + "\"";
                            
                             
                            
                             if (info.Item3 == FieldStyle.Title)
                            {

WriteLiteral("                                <tr");

WriteLiteral(" class=\"info\"");

WriteLiteral(">\r\n                                    <td>");

                                   Write(field.DisplayName);

WriteLiteral("</td>\r\n                                    <td></td>\r\n                           " +
"         <td></td>\r\n                                </tr>\r\n");

                            }
                            else
                            {

WriteLiteral("                            <tr>\r\n                                <td ");

                               Write(intendClass);

WriteLiteral(">");

                                            Write(field.DisplayName);

WriteLiteral("</td>\r\n                                <td>");

                               Write(info.Item1);

WriteLiteral("</td>\r\n                                <td>\r\n                                    " +
"<span");

WriteLiteral(" class=\"tk-control\"");

WriteLiteral(">");

                                                        Write(field.InputByLocalName(mainObject, true));

WriteLiteral("</span>\r\n                                </td>\r\n                            </tr>" +
"\r\n");

                            }
                             
                        }

WriteLiteral("                    </table>\r\n                </div>\r\n");

            }

WriteLiteral("        </div>\r\n    </div>\r\n</form>\r\n");

Write(RenderSectionOrDefault("ModuleButtons", "DefaultButtons"));

WriteLiteral("\r\n");

        }
 private static void VerifyAttribute(HtmlAttribute attribute, string name, string value)
 {
     Assert.Equal(name, attribute.Name);
     Assert.Equal(value, attribute.Value);
     Assert.Equal(value == null, attribute.IsVoid);
     Assert.Null(attribute.Parent);
 }
Exemple #12
0
 private bool IsAttributeWithLink(HtmlAttribute attribute)
 {
     return(attribute.Name == "src" || attribute.Name == "href");
 }
Exemple #13
0
        public override void Process(ref HtmlNode node, HtmlAttribute dynamicAttribute, Dictionary <string, AliasReference> classNameAlias, Dictionary <int, string> classNameAliasdepth, int depth, string websiteId, ExpressionEvaluator evaluator, KEntity entity, dynamic websiteData, Models.Pagination viewDetails, string queryString, Dictionary <string, long> functionLog, bool isDetailsView = false, bool isNFSite = false, string developerId = null)
        {
            Node result = LexerGenerator.Parse(Helper.TrimDelimiters(dynamicAttribute.Value));

            if (result.Token.Value == ACTIONS.Loop)
            {
                string referenceObject = result.Children[0].Children[0].Token.Value;
                string referenceName   = result.Children[2].Children[0].Token.Value?.ToLower();
                var    refObj          = evaluator.EvaluateExpression(referenceObject, entity, viewDetails, classNameAlias, websiteData, websiteData?._system?.kresult, queryString, out bool hasData, functionLog, isDetailsView, isNFSite);
                if (refObj.GetType() == typeof(string) && refObj == "")
                {
                    node = HtmlCommentNode.CreateNode("<!-- skip -->");
                    return;
                }
                string offsetObj = evaluator.EvaluateExpression(result.Children[6], entity, viewDetails, classNameAlias, websiteData, websiteData?._system?.kresult, queryString, out hasData, functionLog, isDetailsView, isNFSite, developerId).ToString();
                int.TryParse(offsetObj, out int offset);
                int iteration    = 0;
                int maxIteration = 0;
                if (dynamicAttribute.Value.IndexOf("offset") > 0)
                {
                    if (int.TryParse(viewDetails.currentpagenumber, out int currentPage) && currentPage > 0)
                    {
                        iteration = offset * (currentPage - 1);
                    }
                }
                else
                {
                    string iterationObj = evaluator.EvaluateExpression(result.Children[4], entity, viewDetails, classNameAlias, websiteData, websiteData?._system?.kresult, queryString, out hasData, functionLog, isDetailsView, isNFSite, developerId).ToString();
                    int.TryParse(iterationObj, out iteration);
                }
                maxIteration = iteration + offset;
                int objSize = (int)evaluator.GetObjectSize(refObj);
                maxIteration = (maxIteration < objSize) ? maxIteration : objSize;
                if (iteration > maxIteration)
                {
                    node = HtmlCommentNode.CreateNode("<!-- skip -->");
                    return;
                }
                else if (objSize == maxIteration && dynamicAttribute.Value.IndexOf("offset") > 0)
                {
                    viewDetails.nextpage.url = "#";
                    viewDetails.pagesize     = maxIteration - iteration + 1;
                }

                AliasReference aliasReference = new AliasReference
                {
                    referenceObject = null,
                    iteration       = iteration,
                    maxIteration    = maxIteration
                };
                if (!classNameAlias.ContainsKey(referenceName))
                {
                    classNameAlias.Add(referenceName, aliasReference);
                    classNameAliasdepth.Add(depth, referenceName);
                }
            }
            else if (result.Token.Value == ACTIONS.InLoop)
            {
                string referenceName   = result.Children[0].Children[0].Token.Value?.ToLower();
                string referenceObject = result.Children[2].Children[0].Token.Value;
                var    obj             = evaluator.EvaluateExpression(referenceObject, entity, viewDetails, classNameAlias, websiteData, websiteData?._system?.kresult, queryString, out bool hasData, functionLog, isDetailsView, isNFSite);
                if (obj.GetType() == typeof(string) && obj == "")
                {
                    node = HtmlCommentNode.CreateNode("<!-- skip -->");
                    return;
                }
                AliasReference aliasReference = new AliasReference();
                aliasReference.referenceObject = referenceObject;
                aliasReference.iteration       = 0;
                aliasReference.maxIteration    = (int)evaluator.GetObjectSize(obj);

                if (!classNameAlias.ContainsKey(referenceName))
                {
                    classNameAlias.Add(referenceName, aliasReference);
                    classNameAliasdepth.Add(depth, referenceName);
                }
            }
        }
Exemple #14
0
        protected void ApproveFormBtn_Click(object sender, EventArgs e)
        {
            FormResult.Visible = false;
            //updating a form not, creating it
            if (Request.QueryString["pfid"] != null)
            {
                int           formId = int.Parse(Request.QueryString["pfid"]);
                Form          f      = FormUtil.GetForm(formId);
                Project       p      = ProjectUtil.GetProject(f.ProjectId);
                WorkflowModel w      = WorkflowUtil.GetWorkflow(p.WorkflowId);

                User user = (User)Session["User"];
                FormUtil.ApproveForm(formId, user.RoleId);
                Log.Info(user.Identity + " approved " + CompanyUtil.GetCompanyName(p.CompanyId) + "'s form " + f.FormName + " - " + p.Name);
                FormResult.CssClass = "success";
                FormResult.Text     = "Approved form " + f.FormName;
                FormResult.Visible  = true;

                //prep html for pdf generation
                HtmlDocument doc     = new HtmlDocument();
                string       pdfName = string.Format("{0} - {1} - {2}", w.WorkflowName, f.FormName, CompanyUtil.GetCompanyName(p.CompanyId));
                string       html    = formViewerData.Value;
                if (html.Contains("user-data"))
                {
                    html = html.Replace("user-data", "value");
                }
                if (html.Contains("\""))
                {
                    html = html.Replace("\"", "'");
                }
                doc.LoadHtml(html);
                doc.Save("PDFGen/" + CompanyUtil.GetCompanyName(p.CompanyId) + "_" + f.FormName + "_" + p.Name + ".html");

                //radiobtns
                foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//input[@type]"))
                {
                    HtmlAttribute type = link.Attributes["type"];
                    if (type.Value.Equals("radio"))
                    {
                        if (link.Attributes.Contains("checked"))
                        {
                        }
                        else
                        {
                            if (link.Attributes.Contains("id"))
                            {
                                string toDelId = link.Attributes["id"].Value;

                                foreach (HtmlNode label in doc.DocumentNode.SelectNodes("//label[@for]"))
                                {
                                    string forId = label.Attributes["for"].Value;
                                    if (forId.Equals(toDelId))
                                    {
                                        label.Remove();
                                    }
                                }
                            }
                        }
                        link.Attributes.Remove("value");
                    }
                }

                //text fields, dates, + similar
                foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//input[@value]"))
                {
                    HtmlAttribute value = link.Attributes["value"];
                    if (link.Attributes.Contains("placeholder"))
                    {
                        link.Attributes.Remove("placeholder");
                    }
                    string val = value.Value;
                    link.InnerHtml = val;
                    link.Attributes.Remove("value");
                }

                //text areas
                foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//textarea[@value]"))
                {
                    HtmlAttribute value = link.Attributes["value"];
                    if (link.Attributes.Contains("placeholder"))
                    {
                        link.Attributes.Remove("placeholder");
                    }
                    string val = value.Value;
                    link.InnerHtml = val;
                    link.Attributes.Remove("value");
                }

                //attached files
                if (f.FilePath.Length > 0)
                {
                    foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//input[@type]"))
                    {
                        HtmlAttribute type = link.Attributes["type"];
                        if (type.Value.Equals("file"))
                        {
                            string fileType = f.FilePath.Split('.')[1];
                            string fileName = string.Format("{0} {1} Attachment.{2}", CompanyUtil.GetCompanyName(p.CompanyId), f.FormName, fileType);
                            link.InnerHtml = "See " + fileName;
                        }
                    }
                }
                doc.Save("PDFGen/" + CompanyUtil.GetCompanyName(p.CompanyId) + "_" + f.FormName + "_" + p.Name + ".html");
                doc.Load("PDFGen/" + CompanyUtil.GetCompanyName(p.CompanyId) + "_" + f.FormName + "_" + p.Name + ".html");
                html = doc.Text;

                //pdf gen
                PDFGen.CreateHTMLPDF(html, pdfName);
                Response.Redirect("Forms.aspx?pfid=" + formId);
            }
        }
        private void recursiveValidateTag(HtmlNode node)
        {
            int maxinputsize = int.Parse(policy.getDirective("maxInputSize"));

            num++;

            HtmlNode parentNode = node.ParentNode;
            HtmlNode tmp        = null;
            string   tagName    = node.Name;

            //check this out
            //might not be robust enough
            if (tagName.ToLower().Equals("#text"))  // || tagName.ToLower().Equals("#comment"))
            {
                return;
            }

            Tag tag = policy.getTagByName(tagName.ToLower());

            if (tag == null || "filter".Equals(tag.Action))
            {
                StringBuilder errBuff = new StringBuilder();
                if (tagName == null || tagName.Trim().Equals(""))
                {
                    errBuff.Append("An unprocessable ");
                }
                else
                {
                    errBuff.Append("The <b>" + HTMLEntityEncoder.htmlEntityEncode(tagName.ToLower()) + "</b> ");
                }

                errBuff.Append("tag has been filtered for security reasons. The contents of the tag will ");
                errBuff.Append("remain in place.");

                errorMessages.Add(errBuff.ToString());

                for (int i = 0; i < node.ChildNodes.Count; i++)
                {
                    tmp = node.ChildNodes[i];
                    recursiveValidateTag(tmp);

                    if (tmp.ParentNode == null)
                    {
                        i--;
                    }
                }
                promoteChildren(node);
                return;
            }
            else if ("validate".Equals(tag.Action))
            {
                if ("style".Equals(tagName.ToLower()) && policy.getTagByName("style") != null)
                {
                    CssScanner styleScanner = new CssScanner(policy);
                    try
                    {
                        CleanResults cr = styleScanner.scanStyleSheet(node.FirstChild.InnerHtml, maxinputsize);

                        foreach (string msg in cr.getErrorMessages())
                        {
                            errorMessages.Add(msg.ToString());
                        }

                        /*
                         * If IE gets an empty style tag, i.e. <style/>
                         * it will break all CSS on the page. I wish I
                         * was kidding. So, if after validation no CSS
                         * properties are left, we would normally be left
                         * with an empty style tag and break all CSS. To
                         * prevent that, we have this check.
                         */

                        if (cr.getCleanHTML() == null || cr.getCleanHTML().Equals(""))
                        {
                            //node.getFirstChild().setNodeValue("/* */");
                            node.FirstChild.InnerHtml = "/* */";
                        }
                        else
                        {
                            //node.getFirstChild().setNodeValue(cr.getCleanHTML());
                            node.FirstChild.InnerHtml = cr.getCleanHTML();
                        }
                    }
                    //    catch (DomException e)
                    //    {
                    //        addError(ErrorMessageUtil.ERROR_CSS_TAG_MALFORMED, new Object[] { HTMLEntityEncoder.htmlEntityEncode(node.getFirstChild().getNodeValue()) });
                    //        parentNode.removeChild(node);
                    //    }
                    catch (ScanException e)
                    {
                        Console.WriteLine("Scan Exception: " + e.Message);

                        //addError(ErrorMessageUtil.ERROR_CSS_TAG_MALFORMED, new Object[] { HTMLEntityEncoder.htmlEntityEncode(node.getFirstChild().getNodeValue()) });
                        parentNode.RemoveChild(node);
                    }
                }

                HtmlAttribute attribute = null;
                for (int currentAttributeIndex = 0; currentAttributeIndex < node.Attributes.Count; currentAttributeIndex++)
                {
                    attribute = node.Attributes[currentAttributeIndex];

                    string name   = attribute.Name;
                    string _value = attribute.Value;

                    Attribute attr = tag.getAttributeByName(name);

                    if (attr == null)
                    {
                        attr = policy.getGlobalAttributeByName(name);
                    }

                    bool isAttributeValid = false;

                    if ("style".Equals(name.ToLower()) && attr != null)
                    {
                        CssScanner styleScanner = new CssScanner(policy);

                        try
                        {
                            CleanResults cr = styleScanner.scanInlineStyle(_value, tagName, maxinputsize);

                            //attribute.setNodeValue(cr.getCleanHTML());
                            attribute.Value = cr.getCleanHTML();

                            ArrayList cssScanErrorMessages = cr.getErrorMessages();

                            foreach (string msg in cr.getErrorMessages())
                            {
                                errorMessages.Add(msg.ToString());
                            }
                        }

                        /*
                         * catch (DOMException e)
                         * {
                         *
                         *  addError(ErrorMessageUtil.ERROR_CSS_ATTRIBUTE_MALFORMED, new Object[] { tagName, HTMLEntityEncoder.htmlEntityEncode(node.getNodeValue()) });
                         *
                         *  ele.removeAttribute(name);
                         *  currentAttributeIndex--;
                         *
                         * }
                         */
                        catch (ScanException ex)
                        {
                            Console.WriteLine(ex.Message);
                            //addError(ErrorMessageUtil.ERROR_CSS_ATTRIBUTE_MALFORMED, new Object[] { tagName, HTMLEntityEncoder.htmlEntityEncode(node.getNodeValue()) });
                            //ele.removeAttribute(name);
                            currentAttributeIndex--;
                        }
                    }
                    else
                    {
                        if (attr != null)
                        {
                            //try to find out how robust this is - do I need to do this in a loop?
                            _value = HtmlEntity.DeEntitize(_value);

                            foreach (string allowedValue in attr.AllowedValues)
                            {
                                if (isAttributeValid)
                                {
                                    break;
                                }

                                if (allowedValue != null && allowedValue.ToLower().Equals(_value.ToLower()))
                                {
                                    isAttributeValid = true;
                                }
                            }

                            foreach (string ptn in attr.AllowedRegExp)
                            {
                                if (isAttributeValid)
                                {
                                    break;
                                }
                                string pattern = "^" + ptn + "$";
                                Match  m       = Regex.Match(_value, pattern);
                                if (m.Success)
                                {
                                    isAttributeValid = true;
                                }
                            }

                            if (!isAttributeValid)
                            {
                                string        onInvalidAction = attr.OnInvalid;
                                StringBuilder errBuff         = new StringBuilder();

                                errBuff.Append("The <b>" + HTMLEntityEncoder.htmlEntityEncode(tagName) + "</b> tag contained an attribute that we couldn't process. ");
                                errBuff.Append("The <b>" + HTMLEntityEncoder.htmlEntityEncode(name) + "</b> attribute had a value of <u>" + HTMLEntityEncoder.htmlEntityEncode(_value) + "</u>. ");
                                errBuff.Append("This value could not be accepted for security reasons. We have chosen to ");

                                //Console.WriteLine(policy);

                                if ("removeTag".Equals(onInvalidAction))
                                {
                                    parentNode.RemoveChild(node);
                                    errBuff.Append("remove the <b>" + HTMLEntityEncoder.htmlEntityEncode(tagName) + "</b> tag and its contents in order to process this input. ");
                                }
                                else if ("filterTag".Equals(onInvalidAction))
                                {
                                    for (int i = 0; i < node.ChildNodes.Count; i++)
                                    {
                                        tmp = node.ChildNodes[i];
                                        recursiveValidateTag(tmp);
                                        if (tmp.ParentNode == null)
                                        {
                                            i--;
                                        }
                                    }

                                    promoteChildren(node);

                                    errBuff.Append("filter the <b>" + HTMLEntityEncoder.htmlEntityEncode(tagName) + "</b> tag and leave its contents in place so that we could process this input.");
                                }
                                else
                                {
                                    node.Attributes.Remove(attr.Name);
                                    currentAttributeIndex--;
                                    errBuff.Append("remove the <b>" + HTMLEntityEncoder.htmlEntityEncode(name) + "</b> attribute from the tag and leave everything else in place so that we could process this input.");
                                }

                                errorMessages.Add(errBuff.ToString());

                                if ("removeTag".Equals(onInvalidAction) || "filterTag".Equals(onInvalidAction))
                                {
                                    return; // can't process any more if we remove/filter the tag
                                }
                            }
                        }
                        else
                        {
                            StringBuilder errBuff = new StringBuilder();

                            errBuff.Append("The <b>" + HTMLEntityEncoder.htmlEntityEncode(name));
                            errBuff.Append("</b> attribute of the <b>" + HTMLEntityEncoder.htmlEntityEncode(tagName) + "</b> tag has been removed for security reasons. ");
                            errBuff.Append("This removal should not affect the display of the HTML submitted.");

                            errorMessages.Add(errBuff.ToString());
                            node.Attributes.Remove(name);
                            currentAttributeIndex--;
                        } // end if attribute is or is not found in policy file
                    }     // end if style.equals("name")
                }         // end while loop through attributes


                for (int i = 0; i < node.ChildNodes.Count; i++)
                {
                    tmp = node.ChildNodes[i];
                    recursiveValidateTag(tmp);
                    if (tmp.ParentNode == null)
                    {
                        i--;
                    }
                }
            }
            else if ("truncate".Equals(tag.Action))
            {
                Console.WriteLine("truncate");
                HtmlAttributeCollection nnmap = node.Attributes;

                while (nnmap.Count > 0)
                {
                    StringBuilder errBuff = new StringBuilder();

                    errBuff.Append("The <b>" + HTMLEntityEncoder.htmlEntityEncode(nnmap[0].Name));
                    errBuff.Append("</b> attribute of the <b>" + HTMLEntityEncoder.htmlEntityEncode(tagName) + "</b> tag has been removed for security reasons. ");
                    errBuff.Append("This removal should not affect the display of the HTML submitted.");
                    node.Attributes.Remove(nnmap[0].Name);
                    errorMessages.Add(errBuff.ToString());
                }

                HtmlNodeCollection cList = node.ChildNodes;

                int i      = 0;
                int j      = 0;
                int length = cList.Count;

                while (i < length)
                {
                    HtmlNode nodeToRemove = cList[j];
                    if (nodeToRemove.NodeType != HtmlNodeType.Text && nodeToRemove.NodeType != HtmlNodeType.Comment)
                    {
                        node.RemoveChild(nodeToRemove);
                    }
                    else
                    {
                        j++;
                    }
                    i++;
                }
            }
            else
            {
                errorMessages.Add("The <b>" + HTMLEntityEncoder.htmlEntityEncode(tagName) + "</b> tag has been removed for security reasons.");
                parentNode.RemoveChild(node);
            }
        }
Exemple #16
0
        private async void OnDownloadClick(object sender, RoutedEventArgs e)
        {
            HttpClient client = new HttpClient();

            for (int index = 0; index < c_list.Items.Count; index++)
            {
                string item = (string)c_list.Items[index];

                int delimIndex = item.IndexOf(" ::");
                if (delimIndex >= 0)
                {
                    item = item.Substring(0, delimIndex);
                    c_list.Items[index] = item;
                }

                c_list.Items[index] = item + " :: Starting to convert";

                string id_process = null;
                string serverId   = null;
                string title      = null;
                string keyHash    = null;
                string serverUrl  = null;
                string dPageId    = null;
                try
                {
                    Dictionary <string, string> entries = new Dictionary <string, string>();
                    entries["function"]              = "validate";
                    entries["args[dummy]"]           = "1";
                    entries["args[urlEntryUser]"]    = item;
                    entries["args[fromConvert]"]     = "urlconverter";
                    entries["args[requestExt]"]      = "mp3";
                    entries["args[nbRetry]"]         = "0";
                    entries["args[videoResolution]"] = "-1";
                    entries["args[audioBitrate]"]    = "0";
                    entries["args[audioFrequency]"]  = "0";
                    entries["args[channel]"]         = "stereo";
                    entries["args[volume]"]          = "0";
                    entries["args[startFrom]"]       = "-1";
                    entries["args[endTo]"]           = "-1";
                    entries["args[custom_resx]"]     = "-1";
                    entries["args[custom_resy]"]     = "-1";
                    entries["args[advSettings]"]     = "false";
                    entries["args[aspectRatio]"]     = "-1";

                    FormUrlEncodedContent content  = new FormUrlEncodedContent(entries);
                    HttpResponseMessage   response = await client.PostAsync("https://www2.onlinevideoconverter.com/webservice", content);

                    string responseString = await response.Content.ReadAsStringAsync();

                    dynamic responseObject = JsonConvert.DeserializeObject(responseString);
                    id_process = responseObject.result.id_process;
                    serverId   = responseObject.result.serverId;
                    title      = responseObject.result.title;
                    keyHash    = responseObject.result.keyHash;
                    serverUrl  = responseObject.result.serverUrl;
                    dPageId    = responseObject.result.dPageId;
                }
                catch (Exception ex)
                {
                }

                if (dPageId == "0")
                {
                    c_list.Items[index] = item + " :: Waiting for conversion";

                    try
                    {
                        Dictionary <string, string> entries = new Dictionary <string, string>();
                        entries["function"]              = "processVideo";
                        entries["args[dummy]"]           = "1";
                        entries["args[urlEntryUser]"]    = item;
                        entries["args[fromConvert]"]     = "urlconverter";
                        entries["args[requestExt]"]      = "mp3";
                        entries["args[serverId]"]        = serverId;
                        entries["args[nbRetry]"]         = "0";
                        entries["args[title]"]           = title;
                        entries["args[keyHash]"]         = keyHash;
                        entries["args[serverUrl]"]       = "http://sv43.onlinevideoconverter.com";
                        entries["args[id_process]"]      = id_process;
                        entries["args[videoResolution]"] = "-1";
                        entries["args[audioBitrate]"]    = "0";
                        entries["args[audioFrequency]"]  = "0";
                        entries["args[channel]"]         = "stereo";
                        entries["args[volume]"]          = "0";
                        entries["args[startFrom]"]       = "-1";
                        entries["args[endTo]"]           = "-1";
                        entries["args[custom_resx]"]     = "-1";
                        entries["args[custom_resy]"]     = "-1";
                        entries["args[advSettings]"]     = "false";
                        entries["args[aspectRatio]"]     = "-1";

                        FormUrlEncodedContent content  = new FormUrlEncodedContent(entries);
                        HttpResponseMessage   response = await client.PostAsync("https://www2.onlinevideoconverter.com/webservice", content);

                        string responseString = await response.Content.ReadAsStringAsync();

                        dynamic responseObject = JsonConvert.DeserializeObject(responseString);
                        dPageId = responseObject.result.dPageId;
                    }
                    catch (Exception ex)
                    {
                    }
                }

                if (string.IsNullOrEmpty(dPageId) || dPageId == "0")
                {
                    c_list.Items[index] = item + " :: Failed to convert";
                    continue;
                }

                c_list.Items[index] = item + " :: Getting download URL";

                string downloadURL = null;
                try
                {
                    Dictionary <string, string> entries = new Dictionary <string, string>();
                    entries["id"] = dPageId;

                    FormUrlEncodedContent content  = new FormUrlEncodedContent(entries);
                    HttpResponseMessage   response = await client.PostAsync("https://www.onlinevideoconverter.com/success", content);

                    string responseString = await response.Content.ReadAsStringAsync();

                    HtmlDocument doc = new HtmlDocument();
                    doc.LoadHtml(responseString);
                    HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//a[@class='download-button']");
                    if (nodes != null)
                    {
                        foreach (HtmlNode node in nodes)
                        {
                            HtmlAttribute href = node.Attributes["href"];
                            if (href.Value.Contains("http"))
                            {
                                downloadURL = href.Value;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                }

                if (string.IsNullOrEmpty(downloadURL))
                {
                    c_list.Items[index] = item + " :: Failed to get download URL";
                    continue;
                }

                c_list.Items[index] = item + " :: Downloading file";
                bool success = false;
                try
                {
                    HttpResponseMessage response = await client.GetAsync(downloadURL);

                    if (response.IsSuccessStatusCode)
                    {
                        string fileName    = response.Content.Headers.ContentDisposition.FileName;
                        string regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
                        Regex  regex       = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch)));
                        fileName = regex.Replace(fileName, "");
                        string filePath       = Path.Combine(c_folder.Text, fileName);
                        Stream responseStream = await response.Content.ReadAsStreamAsync();

                        using (FileStream file = File.Create(filePath))
                        {
                            await responseStream.CopyToAsync(file);

                            success = true;
                        }

                        responseStream.Close();
                    }
                }
                catch (Exception ex)
                {
                }

                if (!success)
                {
                    c_list.Items[index] = item + " :: Failed to download file";
                    continue;
                }
                else
                {
                    c_list.Items[index] = item + " :: DONE";
                }
            }
        }
 /// <summary>
 /// Check attribute as src or href.
 /// </summary>
 /// <param name="attribute"></param>
 /// <returns>True if link has name src or href otherwise false.</returns>
 private bool IsValidLink(HtmlAttribute attribute) => attribute.Name == "src" || attribute.Name == "href";
 private void AnalyzeGoogleBotTag(HtmlAttribute googleBotTag, AnalyzeResult result)
 {
     AnalyzeTag(googleBotTag.Value, result, "googlebot");
 }
 private void AnalyzeRobotTag(HtmlAttribute robotTag, AnalyzeResult result)
 {
     AnalyzeTag(robotTag.Value, result, "robots");
 }
Exemple #20
0
        private static void SanitizeAttribute(HtmlAttribute attribute, List <HtmlAttribute> attrebutes_to_delete,
                                              Uri base_href, bool load_images)
        {
            string new_url;

            switch (attribute.Name)
            {
            case "style":
                var clean_style = ParseStyles(attribute.Value, base_href, load_images);
                if (string.IsNullOrEmpty(clean_style))
                {
                    attrebutes_to_delete.Add(attribute);
                }
                else
                {
                    attribute.Value = clean_style;
                }
                break;

            case "href":
                try
                {
                    var val = attribute.Value.StartsWith("//")
                                      ? "http:" + attribute.Value
                                      : attribute.Value;

                    var url = new Uri(val);
                    if (url.Scheme != Uri.UriSchemeHttp && url.Scheme != Uri.UriSchemeHttps &&
                        url.Scheme != Uri.UriSchemeMailto)
                    {
                        attrebutes_to_delete.Add(attribute);
                    }
                    else
                    {
                        new_url = FixBaseLink(attribute.Value, base_href);
                        if (!string.IsNullOrEmpty(new_url))
                        {
                            attribute.Value = new_url;
                        }
                    }
                }
                catch
                {
                    attrebutes_to_delete.Add(attribute);
                }
                break;

            case "background":
            case "src":
                if (!_embeddedImagesPattern.Match(attribute.Value).Success)
                {
                    try
                    {
                        var val = attribute.Value.StartsWith("//")
                                          ? "http:" + attribute.Value
                                          : attribute.Value;

                        var url = new Uri(val);
                        if (url.Scheme != Uri.UriSchemeHttp && url.Scheme != Uri.UriSchemeHttps)
                        {
                            attrebutes_to_delete.Add(attribute);
                            break;
                        }

                        new_url = FixBaseLink(attribute.Value, base_href);
                        if (!string.IsNullOrEmpty(new_url))
                        {
                            attribute.Value = new_url;
                        }
                    }
                    catch
                    {
                        attrebutes_to_delete.Add(attribute);
                        break;
                    }
                }

                if (!load_images)
                {
                    attribute.Name    = "tl_disabled_" + attribute.Name;
                    _imagesAreBlocked = true;
                }
                break;

            case "class":
                // must change css classes
                var splitted_classes =
                    attribute.Value
                    .Split(new[] { " " },
                           StringSplitOptions.RemoveEmptyEntries)
                    .ToList();

                var new_attr_value = string.Empty;

                splitted_classes
                .ForEach(cls =>
                {
                    var found_new_class_name =
                        _styleClassesNames
                        .Select(t => t)
                        .FirstOrDefault(t => t.Key.Equals(cls));

                    new_attr_value += found_new_class_name.Value ?? cls;
                });

                attribute.Value = new_attr_value;
                break;

            default:
                if (attribute.Name.StartsWith("on"))
                {
                    attrebutes_to_delete.Add(attribute);     // skip all javascript events
                }
                else
                {
                    attribute.Value = EncodeHtml(attribute.Value);
                }
                // by default encodeHtml all properies

                break;
            }
        }
Exemple #21
0
        private static void ConvertTo(HtmlNode node, TextWriter outText)
        {
            string html;

            switch (node.NodeType)
            {
            case HtmlNodeType.Comment:
                // don't output comments
                break;

            case HtmlNodeType.Document:
                ConvertContentTo(node, outText);
                break;

            case HtmlNodeType.Text:
                // script and style must not be output
                string parentName = node.ParentNode.Name;
                if ((parentName == "script") || (parentName == "style"))
                {
                    break;
                }

                // get text
                html = ((HtmlTextNode)node).Text;

                // is it in fact a special closing node output as text?
                if (HtmlNode.IsOverlappedClosingElement(html))
                {
                    break;
                }

                // check the text is meaningful and not a bunch of white spaces
                if (html.Trim().Length > 0)
                {
                    outText.Write(HtmlEntity.DeEntitize(html));
                }
                break;

            case HtmlNodeType.Element:
                switch (node.Name)
                {
                case "p":
                    // treat paragraphs as crlf
                    outText.Write(Environment.NewLine);
                    break;

                case "br":
                    outText.Write(Environment.NewLine);
                    break;

                case "a":
                    HtmlAttribute att = node.Attributes["href"];
                    outText.Write($"<{att.Value}>");
                    break;
                }

                if (node.HasChildNodes)
                {
                    ConvertContentTo(node, outText);
                }
                break;
            }
        }
 public static string RichText(this Tk5FieldInfoEx field, DataRow row, bool needId)
 {
     HtmlAttribute ctrlAttr = new HtmlAttribute("data-control", field.InternalControl.Control);
     return InternalTextArea(field, row, ctrlAttr, needId);
 }
Exemple #23
0
        public String GetURLsAndAttachmentsInfo(MailItem mailItem)
        {
            string urls_and_attachments = "---------- URLs and Attachments ----------";

            var domainsInEmail = new List <string>();

            var emailHTML = mailItem.HTMLBody;
            var doc       = new HtmlAgilityPack.HtmlDocument();

            doc.LoadHtml(emailHTML);

            // extracting all links
            var urlsText = "";
            var urlNodes = doc.DocumentNode.SelectNodes("//a[@href]");

            if (urlNodes != null)
            {
                urlsText = "\n\n # of URLs: " + doc.DocumentNode.SelectNodes("//a[@href]").Count;
                foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//a[@href]"))
                {
                    HtmlAttribute att = link.Attributes["href"];
                    if (att.Value.Contains("a"))
                    {
                        urlsText += "\n --> URL: " + att.Value.Replace(":", "[:]");
                        domainsInEmail.Add(new Uri(att.Value).Host);
                    }
                }
            }
            else
            {
                urlsText = "\n\n # of URLs: 0";
            }

            // Get domains
            domainsInEmail        = domainsInEmail.Distinct().ToList();
            urls_and_attachments += "\n # of unique Domains: " + domainsInEmail.Count;
            foreach (string item in domainsInEmail)
            {
                urls_and_attachments += "\n --> Domain: " + item.Replace(":", "[:]");
            }

            // Add Urls
            urls_and_attachments += urlsText;

            urls_and_attachments += "\n\n # of Attachments: " + mailItem.Attachments.Count;
            foreach (Attachment a in mailItem.Attachments)
            {
                // Save attachment as txt file temporarily to get its hashes (saves under User's Temp folder)
                var filePath = Environment.ExpandEnvironmentVariables(@"%TEMP%\Outlook-Phishaddin-" + a.DisplayName + ".txt");
                a.SaveAsFile(filePath);

                string fileHash_md5    = "";
                string fileHash_sha256 = "";
                if (File.Exists(filePath))
                {
                    fileHash_md5    = CalculateMD5(filePath);
                    fileHash_sha256 = GetHashSha256(filePath);
                    // Delete file after getting the hashes
                    File.Delete(filePath);
                }
                urls_and_attachments += "\n --> Attachment: " + a.FileName + " (" + a.Size + " bytes)\n\t\tMD5: " + fileHash_md5 + "\n\t\tSha256: " + fileHash_sha256 + "\n";
            }
            return(urls_and_attachments);
        }
        public void AddFirst_NonEmptyHtmlObject(bool isVoid)
        {
            HtmlElement parent = new HtmlElement("parent", isVoid);
            HtmlAttribute attribute1 = new HtmlAttribute("attribute1");
            parent.Add(attribute1);

            // Attributes
            HtmlAttribute attribute2 = new HtmlAttribute("attribute2");
            parent.AddFirst(attribute2);
            Assert.Equal(parent, attribute2.Parent);
            Assert.Equal(new HtmlAttribute[] { attribute2, attribute1 }, parent.Attributes());

            if (!isVoid)
            {
                HtmlElement element1 = new HtmlElement("element1");
                parent.Add(element1);

                // Elements
                HtmlElement element2 = new HtmlElement("element2");
                parent.AddFirst(element2);
                Assert.Equal(parent, element2.Parent);
                Assert.Equal(new HtmlElement[] { element2, element1 }, parent.Elements());

                // Nodes
                HtmlComment comment = new HtmlComment("comment");
                parent.AddFirst(comment);
                Assert.Equal(parent, comment.Parent);
                Assert.Equal(new HtmlObject[] { comment, element2, element1 }, parent.Nodes());
            }
        }
 public void ReplaceAttributes_ParamsHtmlAttribute(HtmlAttribute[] attributes)
 {
     HtmlElement parent = new HtmlElement("parent", new HtmlElement("element"), new HtmlAttribute("attribute1"), new HtmlAttribute("attribute2"));
     parent.ReplaceAttributes(attributes);
     Assert.Equal(1, parent.Elements().Count());
     Assert.Equal(attributes, parent.Attributes().ToArray());
     Assert.Equal(1 + attributes.Length, parent.ElementsAndAttributes().Count());
 }
        public void AddFirst_ParamsHtmlObject_NonVoidElement()
        {
            HtmlElement parent = new HtmlElement("parent");
            HtmlElement element1 = new HtmlElement("body");
            HtmlAttribute attribute1 = new HtmlAttribute("attribute1");
            parent.Add(new HtmlObject[] { element1, attribute1 });

            HtmlElement element2 = new HtmlElement("head");
            HtmlAttribute attribute2 = new HtmlAttribute("attribute2");
            parent.AddFirst(new HtmlObject[] { element2, attribute2 });

            Assert.Equal(parent, element2.Parent);
            Assert.Equal(parent, attribute2.Parent);
            Assert.Equal(new HtmlObject[] { element2, element1 }, parent.Elements());
            Assert.Equal(new HtmlAttribute[] { attribute2, attribute1 }, parent.Attributes());
        }
        public override void Execute() {
  
    NormalEditData pageData = ViewBag.PageData;
    HtmlAttribute attribute = pageData.DialogMode ? new HtmlAttribute("data-dialog-action", "close")
        : new HtmlAttribute("data-url", HtmlUtil.GetDynamicRetUrl(Model.CallerInfo));
    HtmlAttribute retAttr = new HtmlAttribute("data-action", "return");
    bool showCaption = pageData.ShowCaption;
    string dataClass = showCaption ? string.Empty : "class=\"nocaption\"";

WriteLiteral("\r\n");

DefineSection("DefaultButtons", () => {

WriteLiteral("\r\n    <div");

WriteLiteral(" class=\"text-center\"");

WriteLiteral(">\r\n");

WriteLiteral("        ");

   Write(BootcssUtil.Button(pageData.SaveButtonCaption, "btn-submit", BootcssButton.Primary, false));

WriteLiteral("\r\n");

WriteLiteral("        ");

   Write(BootcssUtil.Button(pageData.CancelCaption, "m10", BootcssButton.Default, false, attribute, retAttr));

WriteLiteral("\r\n    </div>\r\n");

});

  
    EditObjectModel model = Model as EditObjectModel;
    ObjectContainer mainObject = model.Object;// HtmlUtil.GetMainObject(Model, ViewBag);
    Tk5NormalTableData table = ViewBag.MetaData.Table;
    List<Tk5FieldInfoEx> hiddenFields = table.HiddenList;
    List<Tk5FieldInfoEx> normalFields = table.TableList;

WriteLiteral("\r\n<form");

WriteAttribute("action", Tuple.Create(" action=\"", 1510), Tuple.Create("\"", 1547)
, Tuple.Create(Tuple.Create("", 1519), Tuple.Create<System.Object, System.Int32>(ViewBag.PageData.FormAction
, 1519), false)
);

WriteLiteral(" method=\"POST\"");

WriteLiteral(" id=\"PostForm\"");

WriteLiteral(" class=\"tk-dataform form-horizontal p5 mb15\"");

WriteLiteral(" role=\"form\"");

WriteLiteral(" data-check=\"true\"");

WriteLiteral(" data-post=\"");

                                                                                                                                                        Write(GetJson(table));

WriteLiteral("\"");

WriteLiteral(">\r\n    <div");

WriteAttribute("id", Tuple.Create(" id=\"", 1689), Tuple.Create("\"", 1710)
, Tuple.Create(Tuple.Create("", 1694), Tuple.Create<System.Object, System.Int32>(table.TableName
, 1694), false)
);

WriteAttribute("class", Tuple.Create(" class=\"", 1711), Tuple.Create("\"", 1806)
, Tuple.Create(Tuple.Create("", 1719), Tuple.Create<System.Object, System.Int32>(HtmlUtil.MergeClass("tk-datatable table-row", "column" + table.ColumnCount.ToString())
, 1719), false)
);

WriteLiteral(">\r\n        <div");

WriteLiteral(" class=\"hide\"");

WriteLiteral(">\r\n");

            
             foreach (Tk5FieldInfoEx field in hiddenFields)
            {
                
           Write(RenderHidden(mainObject, field, true));

                                                      
            }

WriteLiteral("        </div>\r\n        <div");

WriteLiteral(" class=\"p10 w100p\"");

WriteLiteral(">\r\n");

            
             foreach (Tk5FieldInfoEx field in normalFields)
            {
                
                  
                    string fieldString = RenderFieldItem(mainObject, field);
                 
                  
                if (fieldString != null)
                {
                
           Write(fieldString);

                            
                }
                else
                {

WriteLiteral("                <div");

WriteAttribute("class", Tuple.Create(" class=\"", 2399), Tuple.Create("\"", 2472)
, Tuple.Create(Tuple.Create("", 2407), Tuple.Create<System.Object, System.Int32>(HtmlUtil.MergeClass("tk-column form-group", field.LayoutClass())
, 2407), false)
);

WriteLiteral(">\r\n                    <dl ");

                   Write(dataClass);

WriteLiteral(">\r\n");

                        
                         if (showCaption)
                         {

WriteLiteral("                            <dt>");

                           Write(field.DisplayName);

WriteLiteral("</dt>\r\n");

                         }

WriteLiteral("                        <dd>\r\n                            <span");

WriteLiteral(" class=\"tk-control\"");

WriteLiteral(">\r\n");

WriteLiteral("                                ");

                           Write(field.Control(mainObject, model.CodeTables, true));

WriteLiteral("\r\n                            </span>\r\n                        </dd>\r\n           " +
"         </dl>\r\n                </div>\r\n");

                }
            }

WriteLiteral("        </div>\r\n    </div>\r\n</form>\r\n");

Write(RenderSectionOrDefault("ModuleButtons", "DefaultButtons"));

WriteLiteral("\r\n");

        }
        public void AddFirst_ParamsHtmlObject_VoidElement()
        {
            HtmlElement parent = new HtmlElement("parent");
            HtmlAttribute newAttribute1 = new HtmlAttribute("attribute1");
            parent.Add(newAttribute1);

            HtmlAttribute newAttribute2 = new HtmlAttribute("attribute2");
            HtmlAttribute newAttribute3 = new HtmlAttribute("attribute3");
            parent.AddFirst(new HtmlObject[] { newAttribute2, newAttribute3 });

            Assert.Equal(parent, newAttribute2.Parent);
            Assert.Equal(parent, newAttribute3.Parent);
            Assert.Empty(parent.Elements());
            Assert.Equal(new HtmlAttribute[] { newAttribute3, newAttribute2, newAttribute1 }, parent.Attributes());
        }
        public override void Execute() {
  
    NormalEditData pageData = ViewBag.PageData;
    //HtmlAttribute attribute = pageData.DialogMode ? new HtmlAttribute("data-dialog-action", "close")
    //    : new HtmlAttribute("data-url", HtmlUtil.GetRetUrl((DataSet)Model));
    HtmlAttribute retAttr = new HtmlAttribute("data-action", "return");

    DataRow dataRow = null; // HtmlUtil.GetMainRow((DataSet)Model, ViewBag);
    Tk5NormalTableData table = ViewBag.MetaData.Table;
    List<Tk5FieldInfoEx> hiddenFields = table.HiddenList;
    List<Tk5FieldInfoEx> normalFields = table.TableList;
    int columnCount = table.ColumnCount;
    int columnWidth = 12 / columnCount;
    int fieldsCount = normalFields.Count;
    int columnFieldCount = fieldsCount / columnCount;
    
     if ((fieldsCount % columnCount) != 0){
        ++columnFieldCount;
    }
     
    //bool showCaption = pageData.ShowCaption;
    //string dataClass = showCaption ? string.Empty : "class=\"nocaption\"";

WriteLiteral("\r\n");

DefineSection("DefaultButtons", () => {

WriteLiteral("\r\n    <div");

WriteLiteral(" class=\"text-center clearfix\"");

WriteLiteral(">\r\n");

WriteLiteral("        ");

   Write(BootcssUtil.Button(pageData.SaveButtonCaption, "btn-submit", BootcssButton.Primary, false));

WriteLiteral("\r\n");

WriteLiteral("        ");

   Write(BootcssUtil.Button(pageData.CancelCaption, "m10", BootcssButton.Default, false, retAttr));

WriteLiteral("\r\n    </div>\r\n");

});

  

WriteLiteral("\r\n<form");

WriteAttribute("action", Tuple.Create(" action=\"", 1992), Tuple.Create("\"", 2029)
, Tuple.Create(Tuple.Create("", 2001), Tuple.Create<System.Object, System.Int32>(ViewBag.PageData.FormAction
, 2001), false)
);

WriteLiteral(" method=\"POST\"");

WriteLiteral(" id=\"PostForm\"");

WriteLiteral(" class=\"tk-dataform p5 mb15\"");

WriteLiteral(" role=\"form\"");

WriteLiteral(" data-check=\"true\"");

WriteLiteral(" data-post=\"");

                                                                                                                                        Write(GetJson(table));

WriteLiteral("\"");

WriteLiteral(">\r\n    <div");

WriteLiteral(" class=\"row tk-datatable table-row\"");

WriteLiteral(" id=\"Info\"");

WriteLiteral(">\r\n        <div");

WriteLiteral(" class=\"col-sm-4\"");

WriteLiteral(">\r\n            <div");

WriteLiteral(" class=\"row\"");

WriteLiteral(">\r\n                <label");

WriteLiteral(" class=\"col-sm-4\"");

WriteLiteral(" style=\"height:34px;line-height:34px\"");

WriteLiteral(">编制单位:</label>\r\n                <div");

WriteLiteral(" class=\"col-sm-8 \"");

WriteLiteral(">\r\n                    <input");

WriteLiteral(" class=\"form-control\"");

WriteLiteral(" id=\"Company\"");

WriteLiteral(" type=\"text\"");

WriteLiteral(">\r\n                </div>\r\n                <br />\r\n            </div>\r\n        </" +
"div>\r\n        <div");

WriteLiteral(" class=\"col-sm-6\"");

WriteLiteral(">\r\n            <label");

WriteLiteral(" class=\"col-sm-2\"");

WriteLiteral(">日期:</label>\r\n            <span");

WriteLiteral(" class=\"tk-control\"");

WriteLiteral(">\r\n                <div");

WriteLiteral(" class=\"input-group date\"");

WriteLiteral(" data-control=\"Date\"");

WriteLiteral(" data-date-format=\"yyyy-mm-dd\"");

WriteLiteral(">\r\n                    <input");

WriteLiteral(" type=\"text\"");

WriteLiteral(" size=\"10\"");

WriteLiteral(" readonly");

WriteLiteral(" placeholder=\"日期\"");

WriteLiteral(" id=\"InputDate\"");

WriteLiteral(" name=\"InputDate\"");

WriteLiteral(" class=\"form-control\"");

WriteLiteral(" data-title=\"日期\"");

WriteLiteral(" value>\r\n                    <span");

WriteLiteral(" class=\"input-group-addon\"");

WriteLiteral("><i");

WriteLiteral(" class=\"glyphicon glyphicon-remove\"");

WriteLiteral("></i></span>\r\n                    <span");

WriteLiteral(" class=\"input-group-addon\"");

WriteLiteral("><i");

WriteLiteral(" class=\"glyphicon glyphicon-calendar\"");

WriteLiteral("></i></span>\r\n                </div>\r\n            </span>\r\n            <br />\r\n  " +
"      </div>\r\n        <div");

WriteLiteral(" class=\"col-sm-2\"");

WriteLiteral(">\r\n            <strong>单位:元</strong>\r\n            <input");

WriteLiteral(" id=\"ReportId\"");

WriteLiteral(" type=\"hidden\"");

WriteAttribute("value", Tuple.Create(" value=\"", 3330), Tuple.Create("\"", 3354)
, Tuple.Create(Tuple.Create("", 3338), Tuple.Create<System.Object, System.Int32>(table.TableName
, 3338), false)
);

WriteLiteral(">\r\n        </div>\r\n    </div>\r\n    <br />\r\n    <div");

WriteAttribute("id", Tuple.Create(" id=\"", 3406), Tuple.Create("\"", 3427)
, Tuple.Create(Tuple.Create("", 3411), Tuple.Create<System.Object, System.Int32>(table.TableName
, 3411), false)
);

WriteAttribute("class", Tuple.Create(" class=\"", 3428), Tuple.Create("\"", 3523)
, Tuple.Create(Tuple.Create("", 3436), Tuple.Create<System.Object, System.Int32>(HtmlUtil.MergeClass("tk-datatable table-row", "column" + table.ColumnCount.ToString())
, 3436), false)
);

WriteLiteral(">\r\n        <div");

WriteLiteral(" class=\"hide\"");

WriteLiteral(">\r\n            ");

WriteLiteral("\r\n        </div>\r\n        <div");

WriteLiteral(" class=\"row\"");

WriteLiteral(">\r\n");

            
             for (int i = 0; i < columnCount; ++i)
            {
                
                  
                    int start = i * columnFieldCount;
                    int end = start + columnFieldCount;
                    if (end > fieldsCount){
                       end = fieldsCount;
                    }
                
                 

WriteLiteral("                <div");

WriteAttribute("class", Tuple.Create(" class=\"", 4095), Tuple.Create("\"", 4140)
, Tuple.Create(Tuple.Create("", 4103), Tuple.Create<System.Object, System.Int32>("col-sm-" + columnWidth.ToString()
, 4103), false)
);

WriteLiteral(">\r\n                    <table");

WriteLiteral(" class=\"table\"");

WriteLiteral(">\r\n                        <tr>\r\n                            <th>资产</th>\r\n       " +
"                     <th>行次</th>\r\n                            <th>期末数</th>\r\n    " +
"                    </tr>\r\n");

                        
                         for (int j = start; j < end; ++j)
                        {
                            
                              
                            var field = normalFields[j];

                            Tuple<int, byte, FieldStyle> info = field.Tag as Tuple<int, byte, FieldStyle>;
                            string intendClass = info.Item2 == 0 ? string.Empty : "class=\"pdl-" + info.Item2 + "\"";
                            
                             
                            
                             if (info.Item3 == FieldStyle.Title)
                            {

WriteLiteral("                                <tr");

WriteLiteral(" class=\"info\"");

WriteLiteral(">\r\n                                    <td>");

                                   Write(field.DisplayName);

WriteLiteral("</td>\r\n                                    <td></td>\r\n                           " +
"         <td></td>\r\n                                </tr>\r\n");

                            }
                            else
                            {

WriteLiteral("                            <tr>\r\n                                <td ");

                               Write(intendClass);

WriteLiteral(">");

                                            Write(field.DisplayName);

WriteLiteral("</td>\r\n                                <td>");

                               Write(info.Item1);

WriteLiteral("</td>\r\n                                <td>\r\n                                    " +
"<span");

WriteLiteral(" class=\"tk-control\"");

WriteLiteral(">");

                                                        Write(field.Control(dataRow, (DataSet)Model, true));

WriteLiteral("</span>\r\n                                </td>\r\n                            </tr>" +
"\r\n");

                            }
                             
                            
                                        
                        }

WriteLiteral("                    </table>\r\n                </div>\r\n");

            }

WriteLiteral("        </div>\r\n    </div>\r\n</form>\r\n");

Write(RenderSectionOrDefault("ModuleButtons", "DefaultButtons"));

WriteLiteral("\r\n");

        }
        public void AddFirst_IEnumerableHtmlObject_NonVoidElement()
        {
            HtmlElement element = new HtmlElement("parent");
            HtmlElement element1 = new HtmlElement("body");
            HtmlAttribute attribute1 = new HtmlAttribute("attribute1");
            element.Add((IEnumerable<HtmlObject>)new HtmlObject[] { element1, attribute1 });

            HtmlElement element2 = new HtmlElement("head");
            HtmlAttribute attribute2 = new HtmlAttribute("attribute2");
            element.AddFirst((IEnumerable<HtmlObject>)new HtmlObject[] { element2, attribute2 });

            Assert.Equal(element, element2.Parent);
            Assert.Equal(element, attribute2.Parent);
            Assert.Equal(new HtmlObject[] { element2, element1 }, element.Elements());
            Assert.Equal(new HtmlAttribute[] { attribute2, attribute1 }, element.Attributes());
        }
Exemple #31
0
        private void htmlElementToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            HtmlNode nd = ctl.node;

            Control[] control = ctl.Controls.Find("checkedListBox1", true);
            document.Load(Application.StartupPath + "/tempHtml.txt");
            CheckedListBox checkedListBox1 = (CheckedListBox)control[0];

            lock (checkedListBox1.CheckedItems)
            {
                foreach (var item in checkedListBox1.CheckedItems)
                {
                    string        displayname = item.ToString();
                    int           index       = checkedListBox1.FindStringExact(displayname);
                    string        name        = "textBox" + (index + 1).ToString();
                    Control[]     c           = checkedListBox1.Controls.Find(name, true);
                    TextBox       tb          = (TextBox)c[0];
                    HtmlAttribute attr        = document.CreateAttribute(displayname, tb.Text);
                    nd.Attributes.Add(attr);
                }
            }
            Control[] ctl1 = ctl.Controls.Find("innerHtmlTextBox", true);
            TextBox   tb1  = (TextBox)ctl1[0];

            Control[] ctl2 = ctl.Controls.Find("pathTextBox", true);
            TextBox   tb2  = (TextBox)ctl2[0];

            nd.InnerHtml = tb1.Text;
            XPathNavigator nav = document.DocumentNode.CreateRootNavigator();

            if (tb2.Text != string.Empty)
            {
                try
                {
                    var ob = (XPathNodeIterator)nav.Evaluate(tb2.Text);
                    if (ob.Count == 0)
                    {
                        MessageBox.Show("The path is not correct"); return;
                    }
                }

                catch (XPathException) { MessageBox.Show("The Path is Not Correct"); return; }
                HtmlNode node = document.DocumentNode.SelectSingleNode(tb2.Text);
                node.AppendChild(nd);
                document.Save(Application.StartupPath + "/tempHtml.txt");
            }
            else if (MessageBox.Show("Please Enter A Path") == DialogResult.OK)
            {
                tb2.Select();
            }
            richTextBox1.LoadFile(Application.StartupPath + "/tempHtml.txt", RichTextBoxStreamType.PlainText);
            toolStripStatusLabel1.Text = "Html Element <" + nd.Name + "> added";
            string filePath = Application.StartupPath;

            using (Document d = Document.FromString(richTextBox1.Text))
            {
                d.IndentBlockElements = AutoBool.Yes;
                d.IndentSpaces        = 2;
                d.AddTidyMetaElement  = false;
                d.CleanAndRepair();
                d.Save(filePath + "/tempHtml.txt");
            }
            document.LoadHtml(richTextBox1.Text);
            richTextBox1.Clear();
            richTextBox1.LoadFile(filePath + "/tempHtml.txt", RichTextBoxStreamType.PlainText);
        }
Exemple #32
0
        /// <summary>
        ///     Select elements that either don't have the specified <paramref name="attribute" />, or do have the specified
        ///     <paramref name="attribute" />
        /// </summary>
        public JquerySelectorExtend NotEqualsAttribute(HtmlAttribute attribute)
        {
            string value = attribute.ToStringLower();

            return(NotEqualsAttribute(value, value));
        }
Exemple #33
0
 /// <summary>
 ///     Selects elements that have the specified <paramref name="attribute" /> with a <paramref name="value" /> beginning
 ///     exactly with a given string.
 /// </summary>
 public JquerySelectorExtend StartWithAttribute(HtmlAttribute attribute, string value)
 {
     return(StartWithAttribute(attribute.ToStringLower(), value));
 }
Exemple #34
0
 /// <summary>
 ///     Selects elements that have the specified <paramref name="attribute" />, with any value.
 ///     <remarks>
 ///         Jquery $('[attribute]')
 ///     </remarks>
 /// </summary>
 public JquerySelectorExtend HasAttribute(HtmlAttribute attribute)
 {
     return(HasAttribute(attribute.ToStringLower()));
 }
Exemple #35
0
 /// <summary>
 ///     Selects elements that have the specified <paramref name="attribute" /> with a <paramref name="value" /> ending
 ///     exactly with a given string. The comparison is case sensitive.
 /// </summary>
 public JquerySelectorExtend EndsWith(HtmlAttribute attribute, string value)
 {
     return(EndsWith(attribute.ToString(), value));
 }
Exemple #36
0
        private void download(string url, string ExamCode, string path)
        {
            if (url != "" && !string.IsNullOrEmpty(url))
            {
                string secondResult = "";
                HtmlAgilityPack.HtmlWeb      web  = new HtmlAgilityPack.HtmlWeb();
                HtmlAgilityPack.HtmlDocument docx = web.Load(url);
                var client = new WebClient();
                var Html   = docx.Text;


                var gettingVideoUrl = docx.DocumentNode.SelectNodes("//*[@id=\"examinfo-url\"]");

                foreach (var node in gettingVideoUrl)
                {
                    var clipurl = node.OuterHtml;
                    var start   = clipurl.IndexOf("value") + 7;
                    secondResult = clipurl.Substring(start);
                    secondResult = secondResult.TrimEnd('>');
                    secondResult = secondResult.TrimEnd('"');

                    secondResult = Convert.ToString(secondResult.ToString());
                }
                if (secondResult != null || string.IsNullOrEmpty(secondResult))
                {
                    XmlDocument doc = new XmlDocument();
                    doc.Load(secondResult);

                    try
                    {
                        XmlNode       fileNode      = doc.FirstChild;
                        var           t             = fileNode.InnerText;
                        List <string> keyValuePairs = t.Split('>').ToList();
                        var           Webcam        = keyValuePairs[6].TrimEnd();
                        var           WebcamClip    = Webcam.Split('<')[0];
                        //path = "D:9b729347-ZZZZ-454e-8e9a-0a5fc03431a1";
                        var savingpath = path + "\\" + ExamCode + "WebcamClip.mp4";
                        client.DownloadFile(WebcamClip, savingpath);
                        backgroundWorker1.ReportProgress(progressBar1.Value + 1);
                        using (w = File.AppendText(Path.Combine(Destinationpath, "log.txt")))
                        {
                            Log(ExamCode + "WebcamClip.mp4" + " " + "Downloaded", w);
                        }
                        savingpath = "";
                        var ScreenCam     = keyValuePairs[11].TrimEnd();
                        var ScreenCamClip = ScreenCam.Split('<')[0];
                        savingpath = path + "\\" + ExamCode + "ScreenCamClip.mp4";
                        client.DownloadFile(ScreenCamClip, savingpath);
                        backgroundWorker1.ReportProgress(progressBar1.Value + 1);
                        using (w = File.AppendText(Path.Combine(Destinationpath, "log.txt")))
                        {
                            Log(ExamCode + "ScreenCamClip.mp4" + " " + "Downloaded", w);
                        }
                    }
                    catch (Exception ex)
                    {
                        using (w = File.AppendText(Path.Combine(Destinationpath, "log.txt")))
                        {
                            Log(ex.Message.ToString(), w);
                        }
                    }
                }

                List <string> imgScrs = new List <string>();
                //var Img_tags = docx.DocumentNode.SelectNodes(@"//img[@src]");

                foreach (HtmlNode img in docx.DocumentNode.SelectNodes("//img"))
                {
                    HtmlAttribute att = img.Attributes["src"];
                    imgScrs.Add(att.Value);
                }
                for (int i = 0; i < imgScrs.Count; i++)
                {
                    var filename = string.Concat(ExamCode, RandomString(2));
                    filename = string.Concat(filename, ".jpg");
                    if (imgScrs[i].Contains("logo.gif") || imgScrs[i].Contains("ajax.gif"))
                    {
                        //at i=0 its logo
                    }
                    else
                    {
                        if (!Uri.IsWellFormedUriString(imgScrs[i], UriKind.Absolute))
                        {
                            imgScrs[i] = imgScrs[i].Split('/')[2];
                            imgScrs[i] = string.Concat("https://www.remoteproctor.com/AdminSite/", imgScrs[i]);
                        }
                        var savePath = path + "\\" + filename;
                        File.WriteAllBytes(savePath, client.DownloadData(imgScrs[i]));
                        backgroundWorker1.ReportProgress(progressBar1.Value + 1);
                        using (w = File.AppendText(Path.Combine(Destinationpath, "log.txt")))
                        {
                            Log(filename + " " + "Downloaded", w);
                        }
                    }
                }
            }
            else
            {
                MessageBox.Show("something went wrong please try again ");
                using (w = File.AppendText(Path.Combine(Destinationpath, "log.txt")))
                {
                    Log("something went wrong please try again", w);
                }
                return;
            }
        }
Exemple #37
0
 /// <summary>
 ///     Selects elements that have the specified <c>attribute</c> with a <c>value</c> exactly equal to a certain
 ///     <c>value</c>.
 /// </summary>
 public JquerySelectorExtend EqualsAttribute(HtmlAttribute attribute, string value)
 {
     return(EqualsAttribute(attribute.ToString(), value));
 }
        public void AddFirst_IEnumerableHtmlObject_VoidElement()
        {
            HtmlElement element = new HtmlElement("parent");
            HtmlAttribute attribute1 = new HtmlAttribute("attribute1");
            element.Add(attribute1);

            HtmlAttribute attribute2 = new HtmlAttribute("attribute2");
            HtmlAttribute attribute3 = new HtmlAttribute("attribute3");
            element.AddFirst((IEnumerable<HtmlObject>)new HtmlObject[] { attribute2, attribute3 });

            Assert.Equal(element, attribute2.Parent);
            Assert.Equal(element, attribute3.Parent);
            Assert.Empty(element.Elements());
            Assert.Equal(new HtmlAttribute[] { attribute3, attribute2, attribute1 }, element.Attributes());
        }
Exemple #39
0
        protected virtual bool HasRelNoFollow(HtmlNode node)
        {
            HtmlAttribute attr = node.Attributes["rel"];

            return(_isRespectAnchorRelNoFollowEnabled && (attr != null && attr.Value.ToLower().Trim() == "nofollow"));
        }
        public void AddFirst_AttributeHasDifferentParent_RemovesFromOldParent()
        {
            HtmlElement parent = new HtmlElement("parent");
            HtmlElement child1 = new HtmlElement("child1");
            HtmlAttribute attribute1 = new HtmlAttribute("attribute1");
            HtmlAttribute attribute2 = new HtmlAttribute("attribute2");
            HtmlAttribute attribute3 = new HtmlAttribute("attribute3");
            HtmlElement child2 = new HtmlElement("child2");

            parent.Add(child1, child2);
            child1.Add(attribute1, attribute2, attribute3);

            child2.Add(attribute1);
            Assert.Equal(child2, attribute1.Parent);
            Assert.Equal(new HtmlAttribute[] { attribute1 }, child2.Attributes());
            Assert.Equal(new HtmlAttribute[] { attribute2, attribute3 }, child1.Attributes());

            child2.Add(attribute2);
            Assert.Equal(child2, attribute2.Parent);
            Assert.Equal(new HtmlAttribute[] { attribute1, attribute2 }, child2.Attributes());
            Assert.Equal(new HtmlAttribute[] { attribute3 }, child1.Attributes());

            child2.Add(attribute3);
            Assert.Equal(child2, attribute3.Parent);
            Assert.Equal(new HtmlAttribute[] { attribute1, attribute2, attribute3 }, child2.Attributes());
            Assert.Empty(child1.Attributes());
        }
Exemple #41
0
        /// <summary>
        /// Moves the CSS embedded in the specified htmlInput to inline style attributes.
        /// </summary>
        /// <param name="htmlInput">The HTML input.</param>
        /// <param name="removeStyleElements">if set to <c>true</c> the style elements are removed.</param>
        /// <returns>Returns the html input, with styles moved to inline attributes.</returns>
        public static string MoveCssInline(string htmlInput, bool removeStyleElements)
        {
            HtmlDocument doc = new HtmlDocument();

            doc.LoadHtml(htmlInput);

            var styleNodes = doc.DocumentNode.SelectNodes("//style");

            if (styleNodes == null)
            {
                return(htmlInput);                    // no styles to move
            }
            foreach (var style in styleNodes)
            {
                if (style.Attributes["id"] != null && !String.IsNullOrWhiteSpace(style.Attributes["id"].Value) && style.Attributes["id"].Value.Equals("mobile", StringComparison.InvariantCultureIgnoreCase))
                {
                    continue;
                }

                CssParser cssParser = new CssParser();
                string    cssBlock  = style.InnerHtml;

                cssParser.AddStyleSheet(cssBlock);

                foreach (var item in cssParser.Styles)
                {
                    //RWM: Just because one style fails to merge doesn't mean they all should.
                    try
                    {
                        var styleClass = item.Value;
                        var elements   = doc.DocumentNode.QuerySelectorAll(styleClass.Name);

                        foreach (var element in elements)
                        {
                            HtmlAttribute styleAttribute = element.Attributes["style"];

                            if (styleAttribute == null)
                            {
                                element.Attributes.Add("style", String.Empty);
                                styleAttribute = element.Attributes["style"];
                            }

                            StyleClass sc = cssParser.ParseStyleClass("dummy", styleAttribute.Value);
                            sc.Merge(styleClass, false);

                            styleAttribute.Value = sc.ToString();
                        }
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Trace.Fail(ex.Message);
                    }
                }

                if (removeStyleElements)
                {
                    style.Remove();
                }
            }

            return(doc.DocumentNode.OuterHtml);
        }
        public void AddFirst_EqualAttribute_ThrowsInvalidOperationException()
        {
            HtmlElement element = new HtmlElement("parent");
            HtmlAttribute attribute = new HtmlAttribute("Attribute");
            element.Add(attribute);
            HtmlAttribute newAttribute = new HtmlAttribute(attribute.Name);

            Assert.Throws<InvalidOperationException>(() => element.AddFirst(newAttribute));
            Assert.Throws<InvalidOperationException>(() => element.AddFirst(new HtmlObject[] { newAttribute }));
            Assert.Throws<InvalidOperationException>(() => element.AddFirst((IEnumerable<HtmlObject>)new HtmlObject[] { newAttribute }));
        }
        /// <summary>
        /// Gets a memory stream representing an image from an explicit favicon location.
        /// </summary>
        /// <param name="fullURI">The URI.</param>
        /// <param name="ms">The memory stream (output).</param>
        /// <param name="message">Any error message is sent back through this string.</param>
        /// <returns></returns>
        private Uri getFromFaviconExplicitLocation(Uri fullURI, ref MemoryStream ms, ref string message)
        {
            HtmlWeb hw = new HtmlWeb();

            hw.UserAgent = "Mozilla/5.0 (Windows 6.1; rv:27.0) Gecko/20100101 Firefox/27.0";
            HtmlAgilityPack.HtmlDocument hdoc = null;
            Uri responseURI = null;

            try
            {
                int counter = 0; // Protection from cyclic redirect
                Uri nextUri = fullURI;
                do
                {
                    // A cookie container is needed for some sites to work
                    hw.PreRequest += PreRequest_EventHandler;

                    // HtmlWeb.Load will follow 302 and 302 redirects to alternate URIs
                    hdoc        = hw.Load(nextUri.AbsoluteUri);
                    responseURI = hw.ResponseUri;

                    // Old school meta refreshes need to parsed
                    nextUri = getMetaRefreshLink(responseURI, hdoc);
                    counter++;
                } while (nextUri != null && counter < 16); // Sixteen redirects would be more than enough.
            }
            catch (Exception)
            {
                return(responseURI);
            }


            if (hdoc == null)
            {
                return(responseURI);
            }

            string faviconLocation = "";

            try
            {
                HtmlNodeCollection links = hdoc.DocumentNode.SelectNodes("/html/head/link");
                for (int i = 0; i < links.Count; i++)
                {
                    HtmlNode node = links[i];
                    try
                    {
                        HtmlAttribute r   = node.Attributes["rel"];
                        string        val = r.Value.ToLower().Replace("shortcut", "").Trim();
                        if (val == "icon")
                        {
                            try
                            {
                                faviconLocation = node.Attributes["href"].Value;
                                // Don't break the loop, because there could be many <link rel="icon"> nodes
                                // We should read the last one, like web browsers do
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
            }
            catch (Exception)
            {
            }
            if (String.IsNullOrEmpty(faviconLocation))
            {
                return(responseURI);
            }

            return((getFavicon(new Uri(responseURI, faviconLocation), ref ms, ref message))?new Uri("http://success"):responseURI);
        }
 public void ReplaceAttributes_IEnumerableHtmlAttribute(HtmlAttribute[] attributes)
 {
     HtmlElement element = new HtmlElement("parent", new HtmlElement("h1"), new HtmlAttribute("attribute1"), new HtmlAttribute("attribute2"));
     element.ReplaceAttributes((IEnumerable<HtmlAttribute>)attributes);
     Assert.Equal(1, element.Elements().Count());
     Assert.Equal(attributes, element.Attributes().ToArray());
     Assert.Equal(1 + attributes.Length, element.ElementsAndAttributes().Count());
 }
 public WebsitePart(HtmlAttribute attribute)
 {
     _attribute = attribute;
 }
Exemple #46
0
        public void WithAttribute_WithAttributes()
        {
            HtmlElement element = new HtmlElement("html");

            HtmlAttribute attribute1 = new HtmlAttribute("Attribute1");
            Assert.Same(element, element.WithAttribute(attribute1));
            Assert.Equal(new HtmlAttribute[] { attribute1 }, element.Attributes());

            HtmlAttribute attribute2 = new HtmlAttribute("Attribute2");
            Assert.Same(element, element.WithAttributes(new HtmlAttribute[] { attribute2 }));
            Assert.Equal(new HtmlAttribute[] { attribute1, attribute2 }, element.Attributes());
        }
        public void ReplaceAttributes_ParamsHtmlAttribute_VoidElement()
        {
            HtmlElement parent = new HtmlElement("parent", isVoid: true);
            parent.Add(new HtmlAttribute("attribute"));

            HtmlAttribute[] attributes = new HtmlAttribute[] { new HtmlAttribute("attribute1"), new HtmlAttribute("attribute2") };
            parent.ReplaceAttributes(attributes);
            Assert.Equal(attributes, parent.Attributes());
        }
Exemple #48
0
 static void ReplaceAttributeValue(HtmlAttribute attribute, Func <string, string> replaceValueWith)
 {
     attribute.Value = replaceValueWith(attribute.Value);
 }
        public void ReplaceAttributes_IEnumerableHtmlAttribute_VoidElement()
        {
            HtmlElement parent = new HtmlElement("br", isVoid: true);
            parent.Add(new HtmlAttribute("attribute1"));

            HtmlAttribute[] attributes = new HtmlAttribute[] { new HtmlAttribute("attribute2"), new HtmlAttribute("c") };
            parent.ReplaceAttributes((IEnumerable<HtmlAttribute>)attributes);
            Assert.Equal(attributes, parent.Attributes());
        }
        public void Add_IEnumerableHtmlObject_VoidElement()
        {
            HtmlElement parent = new HtmlElement("parent", isVoid: true);
            HtmlAttribute attribute1 = new HtmlAttribute("attribute1");
            HtmlAttribute attribute2 = new HtmlAttribute("attribute2");
            parent.Add((IEnumerable<HtmlObject>)new HtmlObject[] { attribute1, attribute2 });

            Assert.Equal(parent, attribute1.Parent);
            Assert.Equal(parent, attribute2.Parent);
            Assert.Empty(parent.Elements());
            Assert.Equal(new HtmlAttribute[] { attribute1, attribute2 }, parent.Attributes());
        }
        public void ReplaceAll_DuplicateAttributeInContents_ThrowsInvalidOperationException()
        {
            HtmlElement parent = new HtmlElement("parent");
            HtmlAttribute attribute = new HtmlAttribute("attribute");
            parent.Add(attribute);

            Assert.Throws<InvalidOperationException>(() => parent.ReplaceAll(new HtmlObject[] { attribute }));
            Assert.Throws<InvalidOperationException>(() => parent.ReplaceAll((IEnumerable<HtmlObject>)new HtmlObject[] { attribute }));
        }
Exemple #52
0
 private HtmlStringBuilder Append(HtmlAttribute attribute) =>
 attribute.Value != null
         ? Append(attribute.Name).Append('=').Append('"').Append(WebUtility.HtmlEncode(attribute.Value)).Append('"')
         : Append(attribute.Name);
        public static HtmlElement Parse(string s)
        {
            if (s == null)
                throw new ArgumentNullException("s");
            if (s.Length == 0)
                return null;

            HtmlElement element = new HtmlElement();

            // Find element name.
            int i = (s[0] == '/') ? 1 : 0;
            while (i < s.Length && Char.IsLetterOrDigit(s[i]))
            {
                i++;
            }
            element.Name = s.Substring(0, i);

            // Shortcut if there are no attributes.
            if (i == s.Length)
                return element;

            // Parse attributes.
            List<HtmlAttribute> attrs = new List<HtmlAttribute>(4);
            while (i < s.Length)
            {
                HtmlAttribute attr = new HtmlAttribute();

                // Skip blanks.
                while (i < s.Length && char.IsWhiteSpace(s[i]))
                    i++;
                if (i == s.Length)
                    break;

                // Find '='.
                int k1 = s.IndexOf('=', i);
                if (k1 < 0)
                    return null;

                // Strip name on the left side of '='.
                attr.Name = s.Substring(i, k1 - i);

                // The next char must be '"'.
                k1++;
                if (k1 >= s.Length || s[k1] != '"')
                    return null;

                // Find closing '"'.
                int k2 = s.IndexOf('"', k1 + 1);
                if (k2 == -1)
                    return null;
                attr.Value = s.Substring(k1 + 1, k2 - k1 - 1).UnescapeXml();

                attrs.Add(attr);
                i = k2 + 1;
            }

            element.Attributes = attrs.ToArray();
            return element;
        }
Exemple #54
0
        private void DoWebRequestInBackgroudInstructorCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                Console.WriteLine("DoWebRequestInBackgroudInstructorCompleted was canceled");
                return;
            }

            if (e.Error != null)
            {
                Console.WriteLine("DoWebRequestInBackgroudInstructorCompleted had error " + e.Error.Message);
                return;
            }

            Console.WriteLine("DoWebRequestInBackgroudInstructorCompleted");
            StringBuilder sb = new StringBuilder();

            sb.Append(HTML_HEADER);

            if (mHtmlDocumentInstructor == null)
            {
                sb.Append(HTML_FOOTER);
                try
                {
                    htmlInstructor.DocumentText = sb.ToString();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception in htmlInstructor WebBrowser control: " + ex.ToString());
                }

                SetSize();
                return;
            }

            HtmlNode htmlNode = mHtmlDocumentInstructor.DocumentNode.SelectSingleNode("//div[@class='userHTML']");

            if (htmlNode != null)
            {
                sb.Append(htmlNode.InnerHtml);
                sb.Append(HTML_FOOTER);
                try
                {
                    htmlInstructor.DocumentText = sb.ToString();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception in htmlInstructor WebBrowser control: " + ex.ToString());
                }
            }

            htmlNode = mHtmlDocumentInstructor.DocumentNode.SelectSingleNode("/div/img");
            if (htmlNode != null)
            {
                HtmlAttribute htmlAttribute = htmlNode.Attributes["src"];
                pictureBoxInstructor.LoadAsync(htmlAttribute.Value);
            }

            htmlInstructor.Visible       = true;
            pictureBoxInstructor.Visible = true;
            SetSize();
        }
        public override void Execute() {
  
    NormalDetailData pageData = ViewBag.PageData;
    DataSet dataSet = Model;
    HtmlAttribute attribute = pageData.DialogMode ? new HtmlAttribute("data-dialog-action", "close")
        : new HtmlAttribute("data-url", HtmlUtil.GetRetUrl(dataSet));
    HtmlAttribute retAttr = new HtmlAttribute("data-action", "return");
    DataTable operators = dataSet.Tables["DetailOperator"];
    
    Tk5NormalTableData table = ViewBag.MetaData.Table;
    DataRow dataRow = HtmlUtil.GetMainRow(Model, ViewBag);
    List<Tk5FieldInfoEx> fields = ViewBag.MetaData.Table.TableList;
    
    int captionCol = pageData.CaptionColumn;
    int dataCol = pageData.DataColumn;
    bool showHint = pageData.AppendHint;
    bool ignoreEmptyField = pageData.IgnoreEmptyField;

WriteLiteral("\r\n");

DefineSection("DefaultButtons", () => {

WriteLiteral("\r\n    <div");

WriteLiteral(" class=\"text-center clearfix mt5\"");

WriteLiteral(">\r\n");

WriteLiteral("        ");

   Write(BootcssUtil.CreateDetailButtons(dataSet, dataRow));

WriteLiteral("\r\n");

WriteLiteral("        ");

   Write(BootcssUtil.Button("<i class='icon-remove mr5'></i>" + pageData.CancelCaption, "", BootcssButton.Default, false, attribute, retAttr));

WriteLiteral("\r\n    </div>\r\n");

});

WriteLiteral("<form");

WriteLiteral(" method=\"POST\"");

WriteLiteral(" id=\"PostForm\"");

WriteLiteral(" class=\"tk-dataform form-horizontal p5 mb15\"");

WriteLiteral(" role=\"form\"");

WriteLiteral(">\r\n    <div");

WriteAttribute("id", Tuple.Create(" id=\"", 1406), Tuple.Create("\"", 1427)
, Tuple.Create(Tuple.Create("", 1411), Tuple.Create<System.Object, System.Int32>(table.TableName
, 1411), false)
);

WriteAttribute("class", Tuple.Create(" class=\"", 1428), Tuple.Create("\"", 1513)
, Tuple.Create(Tuple.Create("", 1436), Tuple.Create<System.Object, System.Int32>(HtmlUtil.MergeClass("tk-datatable", "column" + table.ColumnCount.ToString())
, 1436), false)
);

WriteLiteral(">\r\n        <div");

WriteLiteral(" class=\"p10\"");

WriteLiteral(">\r\n");

            
             foreach (Tk5FieldInfoEx field in fields)
            {
                
                  
                     string fieldString = RenderFieldItem(dataRow, field);
                     string value = dataRow.GetString(field.NickName);
                 
                  
                 if (fieldString != null)
                 {
                
           Write(fieldString);

                            
                 }
                 else
                 {
                
                 if (ignoreEmptyField && string.IsNullOrEmpty(value)) 
                 {
                    continue;
                 }
                  

WriteLiteral("                <div");

WriteAttribute("class", Tuple.Create(" class=\"", 2121), Tuple.Create("\"", 2191)
, Tuple.Create(Tuple.Create("", 2129), Tuple.Create<System.Object, System.Int32>(HtmlUtil.MergeClass("tk-column", field.LayoutClass(), "pt10")
, 2129), false)
);

WriteLiteral(">\r\n                    <dl>\r\n                        <dt>");

                       Write(field.DisplayName);

WriteLiteral("</dt>\r\n                        <dd>\r\n                            <span");

WriteLiteral(" class=\"tk-control\"");

WriteLiteral(">\r\n");

WriteLiteral("                                ");

                           Write(field.Detail(dataRow, showHint, false));

WriteLiteral("\r\n                            </span>\r\n                        </dd>\r\n           " +
"         </dl>\r\n                </div>\r\n");

                 }
            }

WriteLiteral("        </div>\r\n    </div>\r\n</form>\r\n");

Write(RenderSectionOrDefault("ModuleButtons", "DefaultButtons"));

        }
Exemple #56
0
 internal HtmlAttributeXPathElement(HtmlAttribute attribute)
 {
     this.HtmlAttribute = attribute;
 }
 public HtmlElement Attr(HtmlAttribute attributre, string value)
 {
     return Attr(attributre.ToString().ToLower(), value);
 }
Exemple #58
0
        private async Task <PageCrawlResult> CrawlNode(PageModel node)
        {
            try
            {
                var response = await _httpClient.GetAsync(node.Url);

                Uri requestUrl = response.RequestMessage.RequestUri;
                requestUrl = new Uri(requestUrl.GetLeftPart(UriPartial.Path));

                if (requestUrl != node.Url)
                {
                    if (requestUrl.Host.Replace("www.", "") != node.Url.Host.Replace("www.", ""))
                    {
                        return(PageCrawlResult.FAILED);
                    }
                    else if (ShouldAddUrl(requestUrl))
                    {
                        var pageModel = new PageModel(requestUrl, node);
                        OnNewLinkAdded?.Invoke(pageModel);
                        _pages.Enqueue(pageModel);
                    }
                    return(PageCrawlResult.FINISHED);
                }

                if (response.IsSuccessStatusCode)
                {
                    var pageContent = await response.Content.ReadAsStringAsync();

                    var pageDocument = new HtmlDocument();

                    pageDocument.LoadHtml(pageContent);

                    OnPageLoaded?.Invoke(node.Url, pageDocument);

                    foreach (HtmlNode link in pageDocument.DocumentNode.SelectNodes("//a[@href]"))
                    {
                        HtmlAttribute att   = link.Attributes["href"];
                        string        value = att.Value;
                        if (value.StartsWith("#") || value.StartsWith("mailto:"))
                        {
                            continue;
                        }

                        string extension = Path.GetExtension(value);
                        if (extension != string.Empty && extension != ".html")
                        {
                            continue;
                        }

                        Uri linkUri;
                        if (!Uri.TryCreate(requestUrl, value, out linkUri))
                        {
                            continue;
                        }

                        if (linkUri.Host != requestUrl.Host)
                        {
                            continue;
                        }

                        linkUri = new Uri(linkUri.GetLeftPart(UriPartial.Path));

                        if (ShouldAddUrl(linkUri))
                        {
                            var pageModel = new PageModel(linkUri, node);
                            OnNewLinkAdded?.Invoke(pageModel);
                            _pages.Enqueue(pageModel);
                        }
                    }
                }
                else if (response.StatusCode.Equals(HttpStatusCode.Moved))
                {
                    string returnURL = response.Headers.GetValues("Location").FirstOrDefault().ToString();
                    Uri    linkUri   = new Uri(new Uri(returnURL).GetLeftPart(UriPartial.Path));

                    if (linkUri.Host != requestUrl.Host)
                    {
                        return(PageCrawlResult.FAILED);
                    }

                    if (ShouldAddUrl(linkUri))
                    {
                        var pageModel = new PageModel(linkUri, node);
                        OnNewLinkAdded?.Invoke(pageModel);
                        _pages.Enqueue(pageModel);
                    }
                }
                return(PageCrawlResult.FINISHED);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return(PageCrawlResult.ERROR);
            }
        }
        public override void Execute() {
  
    NormalEditData pageData = ViewBag.PageData;
    HtmlAttribute attribute = pageData.DialogMode ? new HtmlAttribute("data-dialog-action", "close")
        : new HtmlAttribute("data-url", HtmlUtil.GetRetUrl((DataSet)Model));
    HtmlAttribute retAttr = new HtmlAttribute("data-action", "return");

WriteLiteral("\r\n");

DefineSection("DefaultButtons", () => {

WriteLiteral("\r\n    <div");

WriteLiteral(" class=\"text-center clearfix\"");

WriteLiteral(">\r\n");

WriteLiteral("        ");

   Write(BootcssUtil.Button(pageData.SaveButtonCaption, "btn-submit", BootcssButton.Primary, false));

WriteLiteral("\r\n");

WriteLiteral("        ");

   Write(BootcssUtil.Button(pageData.CancelCaption, "m10", BootcssButton.Default, false, attribute, retAttr));

WriteLiteral("\r\n    </div>\r\n");

});

  
    DataRow dataRow = HtmlUtil.GetMainRow((DataSet)Model, ViewBag);
    Tk5NormalTableData table = ViewBag.MetaData.Table;
    List<Tk5FieldInfoEx> hiddenFields = table.HiddenList;
    List<Tk5FieldInfoEx> normalFields = table.TableList;
    bool showCaption = pageData.ShowCaption;
    string dataClass = showCaption ? string.Empty : "class=\"nocaption\"";

WriteLiteral("\r\n<form");

WriteAttribute("action", Tuple.Create(" action=\"", 1428), Tuple.Create("\"", 1465)
, Tuple.Create(Tuple.Create("", 1437), Tuple.Create<System.Object, System.Int32>(ViewBag.PageData.FormAction
, 1437), false)
);

WriteLiteral(" method=\"POST\"");

WriteLiteral(" id=\"PostForm\"");

WriteLiteral(" class=\"tk-dataform p5 mb15\"");

WriteLiteral(" role=\"form\"");

WriteLiteral(" data-check=\"true\"");

WriteLiteral(" data-post=\"");

                                                                                                                                        Write(GetJson(table));

WriteLiteral("\"");

WriteLiteral(">\r\n    <div");

WriteAttribute("id", Tuple.Create(" id=\"", 1591), Tuple.Create("\"", 1612)
, Tuple.Create(Tuple.Create("", 1596), Tuple.Create<System.Object, System.Int32>(table.TableName
, 1596), false)
);

WriteAttribute("class", Tuple.Create(" class=\"", 1613), Tuple.Create("\"", 1708)
, Tuple.Create(Tuple.Create("", 1621), Tuple.Create<System.Object, System.Int32>(HtmlUtil.MergeClass("tk-datatable table-row", "column" + table.ColumnCount.ToString())
, 1621), false)
);

WriteLiteral(">\r\n        <div");

WriteLiteral(" class=\"hide\"");

WriteLiteral(">\r\n");

            
             foreach (Tk5FieldInfoEx field in hiddenFields)
            {
                
           Write(RenderHidden(dataRow, field, true));

                                                   
            }

WriteLiteral("        </div>\r\n        <div");

WriteLiteral(" class=\"p10 pull-left w100p\"");

WriteLiteral(">\r\n");

            
             foreach (Tk5FieldInfoEx field in normalFields)
            {
                
                  
                    string fieldString = RenderFieldItem(dataRow, field);
                 
                  
                if (fieldString != null)
                {
                
           Write(fieldString);

                            
                }
                else
                {

WriteLiteral("                <div");

WriteAttribute("class", Tuple.Create(" class=\"", 2305), Tuple.Create("\"", 2378)
, Tuple.Create(Tuple.Create("", 2313), Tuple.Create<System.Object, System.Int32>(HtmlUtil.MergeClass("tk-column form-group", field.LayoutClass())
, 2313), false)
);

WriteLiteral(">\r\n                    <dl ");

                   Write(dataClass);

WriteLiteral(">\r\n");

                        
                         if (showCaption)
                            {

WriteLiteral("                            <dt>");

                           Write(field.DisplayName);

WriteLiteral("</dt>\r\n");

                            }

WriteLiteral("                        <dd>\r\n                            <span");

WriteLiteral(" class=\"tk-control\"");

WriteLiteral(">\r\n");

WriteLiteral("                                ");

                           Write(field.Control(dataRow, (DataSet)Model, true));

WriteLiteral("\r\n                            </span>\r\n                        </dd>\r\n           " +
"         </dl>\r\n                </div>\r\n");

                }
            }

WriteLiteral("        </div>\r\n    </div>\r\n</form>\r\n");

Write(RenderSectionOrDefault("ModuleButtons", "DefaultButtons"));

WriteLiteral("\r\n");

        }
Exemple #60
0
 /// <summary>
 /// Tries the add attribute.
 /// </summary>
 /// <param name="key">The key.</param>
 /// <param name="value">The value.</param>
 /// <returns></returns>
 public bool TryAddAttribute(HtmlAttribute key, out string value)
 {
     var key2 = (int)key;
     if (key2 < HtmlAttributeSplit)
         return TryAddAttribute((HtmlTextWriterAttribute)key2, out value);
     else if (key2 > HtmlAttributeSplit)
         return TryAddStyleAttribute((HtmlTextWriterStyle)(key2 - HtmlAttributeSplit - 1), out value);
     throw new ArgumentException(string.Format("Local.InvalidHtmlAttribA", key.ToString()), "key");
 }