using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;
using System.Net;
using System.Text;
using System.Xml;
using System.IO;
using System.Xml.Xsl;

/// <summary>
/// WebClass 的摘要说明
/// </summary>
public class WebClass
{
	public WebClass()
	{
		//
		// TODO: 在此处添加构造函数逻辑
		//
	}

    public static bool CheckLenght(string str, int min, int max)
    {
        int length = Regex.Replace(str, "[一-龥]", "aa").Length;
        return ((length >= min) && (length <= max));
    }

    public static string delHtml(string str)
    {
        if ((str != null) && (str.Trim() != ""))
        {
            return Regex.Replace(str, "<[^>]+>", "");
        }
        return str;
    }

    public static string DelLink(string str)
    {
        if ((str != null) && (str.Trim() != ""))
        {
            return Regex.Replace(str, "(<a[^>]+>)|(</a *>)", "");
        }
        return str;
    }
    public static string delNotTag(string str, string tag, bool isContent)
    {
        return Regex.Replace(str, string.Format("(<(?!{0})[^>]*(>)?)|(</(?!{0})[^>]*>)|", tag), "", RegexOptions.IgnoreCase);
    }
    public static string delOption(string str)
    {
        return Regex.Replace(str, @"(\n)|(\t)|(\r)|(\v)|(\f)", "");
    }
    public static string delSpanTag(string str)
    {
        return Regex.Replace(str, @"[^<]\s", "");
    }
    public static string delTag(string str, string tag, bool isContent)
    {
        if ((tag == null) || (tag == ""))
        {
            return str;
        }
        if (isContent)
        {
            return Regex.Replace(str, string.Format(@"<({0})[^>]*>(.*?)<\/\1>", tag), "", RegexOptions.IgnoreCase);
        }
        return Regex.Replace(str, string.Format("(<{0}[^>]*(>)?)|(</{0}[^>]*>)|", tag), "", RegexOptions.IgnoreCase);
    }
    public static string delTagArray(string str, string tagA, bool isContent)
    {
        foreach (string str2 in tagA.Split(new char[] { ',' }))
        {
            str = delTag(str, str2, isContent);
        }
        return str;
    }
    public static string FormTable(string str, int index, string titleclss, string itemclass)
    {
        str = Replace(str, @"(?<=<table\s*)[^>]*", "");
        str = Replace(str, @"(?<=<tr\s*)[^>]*", "");
        str = Replace(str, @"(?<=<td\s*)[^>]*", "");
        MatchCollection matchs = MatchCollection(str, @"<tr[\s\S]*?</tr>");
        StringBuilder builder = new StringBuilder();
        builder.Append("<table>");
        if (matchs.Count < index)
        {
            return str;
        }
        builder.Append(Replace(matchs[index - 1].Value, "(?<=<td[^>]*)[^>]*", string.Format(" class='{0}'", titleclss)));
        for (int i = index; i < matchs.Count; i++)
        {
            builder.Append(Replace(matchs[i].Value, "(?<=<td[^>]*)[^>]*", string.Format(" class='{0}'", itemclass)));
        }
        builder.Append("</table>");
        return builder.ToString();
    }
    public static string Get(string url)
    {
        Encoding enc = Encoding.GetEncoding("gb2312");
        return Get(UrlEncode(url, enc), enc);
    }

    public static string Get(string url, Encoding enc)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(UrlEncode(url, enc));
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        StreamReader reader = new StreamReader(response.GetResponseStream(), enc);
        string str2 = reader.ReadToEnd();
        reader.Close();
        response.Close();
        return str2;
    }
    public static string Get2(string url)
    {
        Encoding enc = Encoding.GetEncoding("utf-8");
        return Get(UrlEncode(url, enc), enc);
    }
    public static string getApplicationPath()
    {
        string applicationPath = HttpContext.Current.Request.ApplicationPath;
        if (applicationPath.EndsWith("/"))
        {
            return applicationPath;
        }
        return (applicationPath + "/");
    }
    public static string getpage(int sum, int curr, int sumcunt)
    {
        if (((sum == 0) || (curr == 0)) || (sumcunt == 0))
        {
            return "";
        }
        string format = "<a href='javascript:go({0},{2})'>上一页</a> | <a href='javascript:go({1},{2})'>下一页</a> | <a href='javascript:go({2},{2})'>末页</a> | 第{3}页 | 共{4}页 | 共{5}行";
        return string.Format(format, new object[] { curr - 1, curr + 1, sum, curr, sum, sumcunt });
    }

    public static string getpost()
    {
        HttpRequest request = HttpContext.Current.Request;
        StringBuilder builder = new StringBuilder();
        foreach (string str in request.Form.AllKeys)
        {
            builder.AppendFormat("{0}={1}&", str, request.Form[str]);
        }
        if (builder.ToString().EndsWith("&"))
        {
            builder.Remove(builder.Length - 1, 1);
        }
        return builder.ToString();
    }
    public static string getPostItem(string postname)
    {
        return getPostItem(postname, "", "");
    }

    public static string getPostItem(string postname, string patt, string replstr)
    {
        try
        {
            string input = HttpContext.Current.Request[postname];
            if ((patt == null) || (patt.Trim() == ""))
            {
                if (input == null)
                {
                    return "";
                }
                return input;
            }
            return Replace(input, patt, replstr);
        }
        catch
        {
            return "";
        }
    }
    public static Match Match(string input, string patt)
    {
        return Regex.Match(input, patt, RegexOptions.IgnoreCase);
    }
    public static MatchCollection MatchCollection(string input, string patt)
    {
        return Regex.Matches(input, patt, RegexOptions.IgnoreCase);
    }
    public static string Post(string Web, string postData)
    {
        string str2;
        string str = "";
        postData = postData.Replace(" ", "%20");
        try
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Web);
            Stream stream = new MemoryStream();
            StreamWriter writer = new StreamWriter(stream, Encoding.Default);
            writer.Write(postData);
            writer.Flush();
            long length = stream.Length;
            writer.Close();
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = length;
            request.Method = "POST";
            writer = new StreamWriter(request.GetRequestStream(), Encoding.Default);
            writer.Write(postData);
            writer.Close();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream responseStream = response.GetResponseStream();
            Encoding encoding = Encoding.Default;
            StreamReader reader = new StreamReader(responseStream, encoding);
            str = reader.ReadToEnd();
            reader.Close();
            response.Close();
            str2 = str;
        }
        catch (Exception exception)
        {
            throw exception;
        }
        return str2;
    }
    public static string Replace(string input, string patt, string replacetext)
    {
        return Regex.Replace(input, patt, replacetext, RegexOptions.IgnoreCase);
    }
    public static string ToHtml(string str)
    {
        str = str.Replace("&amp;", "&");
        return str;
    }
    private static string UrlEncode(string url, Encoding enc)
    {
        byte[] bytes = enc.GetBytes(url);
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < bytes.Length; i++)
        {
            if (bytes[i] < 0x80)
            {
                builder.Append((char)bytes[i]);
            }
            else
            {
                builder.Append("%" + bytes[i++].ToString("x").PadLeft(2, '0'));
                builder.Append("%" + bytes[i].ToString("x").PadLeft(2, '0'));
            }
        }
        return builder.ToString();
    }
    public static string VirtualPath(string input)
    {
        string str = Regex.Replace(input, @"^(\w+://[^/]+)(.*?)(([^/]+(?=\?))|(([^/]+)$))(.*)", "${1}${2}");
        if ((str != null) && !(str == ""))
        {
            return str;
        }
        return input;
    }

    public static string XmlToString(DataSet ds, string filePath)
    {
        XmlDataDocument input = new XmlDataDocument(ds);
        XmlWriterSettings settings = new XmlWriterSettings();
        settings.OmitXmlDeclaration = true;
        settings.ConformanceLevel = ConformanceLevel.Fragment;
        settings.CloseOutput = false;
        StringBuilder sb = new StringBuilder();
        TextWriter output = new StringWriter(sb);
        XmlWriter results = XmlWriter.Create(output, settings);
        XslCompiledTransform transform = new XslCompiledTransform();
        transform.Load(HttpContext.Current.Server.MapPath(getApplicationPath() + filePath));
        transform.Transform(input, results);
        return sb.ToString();
    }
    public static string XmlToString(XmlDocument xml, string filePath)
    {
        XmlWriterSettings settings = new XmlWriterSettings();
        settings.OmitXmlDeclaration = true;
        settings.ConformanceLevel = ConformanceLevel.Fragment;
        settings.CloseOutput = false;
        StringBuilder sb = new StringBuilder();
        TextWriter output = new StringWriter(sb);
        XmlWriter results = XmlWriter.Create(output, settings);
        XslCompiledTransform transform = new XslCompiledTransform();
        transform.Load(HttpContext.Current.Server.MapPath(getApplicationPath() + filePath));
        transform.Transform(xml, results);
        return sb.ToString();
    }

    public static bool  AddToXML(SiteClass site)
    {
        bool f = false;
        try
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(HttpContext.Current.Server.MapPath("xmlLink.xml"));
            XmlNode root = xmlDoc.SelectSingleNode("Links");
            XmlNodeList node = xmlDoc.SelectNodes("/Links/link[@siteUrl='"+site.SiteUrl+"']");
            if (node.Count > 0)
                return false;
            else
            {
                XmlElement xe1 = xmlDoc.CreateElement("link");
                xe1.SetAttribute("siteKey", site.SiteKey);
                xe1.SetAttribute("siteName", HttpContext.Current.Server.HtmlEncode(site.SiteName));
                xe1.SetAttribute("siteUrl", HttpContext.Current.Server.HtmlEncode(site.SiteUrl));
                xe1.SetAttribute("siteDesc", HttpContext.Current.Server.HtmlEncode(site.SiteDesc));
                xe1.SetAttribute("LinkType", "0");

                root.AppendChild(xe1);

                xmlDoc.Save(HttpContext.Current.Server.MapPath("xmlLink.xml"));
                f = true;
            }
        }
        catch 
        {
            f = false;
        }
        return f;
    }
    /// <summary>
    /// 获取客户端ip
    /// </summary>
    /// <returns></returns>
    public static string GetClientIP()
    {
        string aUseIP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
        if (aUseIP == null || aUseIP == "")
            aUseIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
        if (aUseIP == null || aUseIP == "")
        {
            aUseIP = HttpContext.Current.Request.UserHostAddress;
        }
        if (aUseIP == null)
        {
            aUseIP = "";
        }
        string[] ips = aUseIP.Split(',');
        if (ips.Length > 0)
        {
            aUseIP = ips[0];
        }
        if (aUseIP.Length > 15)
        {
            aUseIP = aUseIP.Substring(0, 15);
        }
        aUseIP = aUseIP.Trim();
        return aUseIP;
    }

     /// <summary>
    /// 获取当前应用程序指定CacheKey的Cache值
    /// </summary>
    /// <param name="CacheKey"></param>
    /// <returns></returns>
    public static object GetCache(string CacheKey)
    {
        System.Web.Caching.Cache objCache = HttpRuntime.Cache;
        return objCache[CacheKey];
    }
    
    /// <summary>
    /// 设置当前应用程序指定CacheKey的Cache值
    /// </summary>
    /// <param name="CacheKey"></param>
    /// <param name="objObject"></param>
    public static void SetCache(string CacheKey, object objObject)
    {
        System.Web.Caching.Cache objCache = HttpRuntime.Cache;
        objCache.Insert(CacheKey, objObject);
    }
    /// <summary>
    /// 删除指定key的Cache
    /// </summary>
    /// <param name="CacheKey"></param>
    public static void ReMoveCacheByKey(string CacheKey)
    {
        System.Web.Caching.Cache objCache = HttpRuntime.Cache;
        objCache.Remove(CacheKey);
    }
    public static string CutString(string inputString, int len)
    {
        ASCIIEncoding ascii = new ASCIIEncoding();
        int tempLen = 0;
        string tempString = "";
        byte[] s = ascii.GetBytes(inputString);
        for (int i = 0; i < s.Length; i++)
        {
            if ((int)s[i] == 63)
            {
                tempLen += 2;
            }
            else
            {
                tempLen += 1;
            }
            if (tempLen > len && i < inputString.Length)
            {
                tempString += "..";
                break;
            }
            tempString += inputString.Substring(i, 1);
        }
        return tempString;
    }

    /// <summary>
    /// 返回字符串的字节长度
    /// </summary>
    /// <param name="Str"></param>
    /// <returns></returns>
    public static int GetBytesLength(string Str)
    {
        return System.Text.Encoding.Default.GetBytes(Str).Length;
    }


    /// <summary>
    /// 截断超长字符串
    /// </summary>
    /// <param name="inputString"></param>
    /// <param name="len"></param>
    /// <returns></returns>
    public static string SubString(string inputString, int len)
    {
        if (inputString.Length < (len / 2))
            return inputString;
        else
        {
            return CutString(inputString, len);
        }
    }
}

public class SiteClass
{
    private string _siteKey;
    private string _siteName;
    private string _siteUrl;
    private string _siteDesc;

    public SiteClass(string _siteName,string _siteUrl,string _siteDesc)
    {
        this._siteName = _siteName;
        this._siteUrl = _siteUrl;
        this._siteDesc = _siteDesc;
    }
    public SiteClass() { }
    public string SiteKey
    {
        get { return this._siteKey; }
        set { this._siteKey = value; }
    }
    public string SiteName
    {
        get { return this._siteName;}
        set { this._siteName = value; }
    }

    public string SiteUrl
    {
        get { return this._siteUrl; }
        set { this._siteUrl = value; }
    }

    public string SiteDesc
    {
        get { return this._siteDesc; }
        set { this._siteDesc = value; }
    }
}
