图片 8

如何打造网站克隆、仿站工具(C#版)

Posted by
/// <summary>
    /// 网页处理服务工具
    /// </summary>
    public class WebPageService
    {
        private static string[] excludekeys = { "http:", "https:", "//", "#", "javascript:", "?", "tel:", "mailto:" };
        /// <summary>
        /// 获取所有html元素的href属性值,只获取站点本地的链接,站外的不获取
        /// </summary>
        /// <param name="html">页面的html源码</param>
        /// <returns></returns>
        public static List<UrlModel> GetLocalHrefs(string url,string html)
        {
            if (string.IsNullOrEmpty(html))
                return new List<UrlModel>();

            Dictionary<string, UrlModel> urls = GetHrefs(url,html);
            List<UrlModel> newUrls = new List<UrlModel>();

            if (null != urls)
            {
                foreach (string key in urls.Keys)
                {
                    string newkey = key.ToLower();
                    bool iscontained = false;
                    foreach (var exkey in excludekeys)
                    {
                        if (newkey.IndexOf(exkey) == 0)
                        {
                            iscontained = true;
                            break;
                        }
                    }

                    if (!iscontained) {
                        //只获取本地路径
                        newUrls.Add(urls[key]);
                    }
                }
            }

            return newUrls;
        }

        /// <summary>
        /// 获取所有html元素的src属性值,只获取站点本地的链接,站外的不获取
        /// </summary>
        /// <param name="html">页面的html源码</param>
        /// <returns></returns>
        public static List<UrlModel> GetLocalSrcs(string url,string html)
        {
            if (string.IsNullOrEmpty(html))
                return new List<UrlModel>();

            Dictionary<string, UrlModel> urls = GetSrc(url, html);
            List<UrlModel> newUrls = new List<UrlModel>();

            if (null != urls)
            {
                foreach (string key in urls.Keys)
                {
                    string newkey = key.ToLower();
                    bool iscontained = false;
                    foreach (var exkey in excludekeys)
                    {
                        if (newkey.IndexOf(exkey) == 0)
                        {
                            iscontained = true;
                            break;
                        }
                    }

                    if (!iscontained)
                    {
                        //只获取本地路径
                        newUrls.Add(urls[key]);
                    }
                }
            }

            return newUrls;
        }

        private static Dictionary<string, UrlModel> GetHrefs(string url,string html)
        {
            if (string.IsNullOrEmpty(html))
                return null;

            UrlModel currUrl = UrlParser.Parse(url);
            Dictionary<string, UrlModel> urls = new Dictionary<string, UrlModel>();
            Regex reg = new Regex("href="(?<Url>.+?)"", RegexOptions.IgnoreCase);

            if (currUrl != null)
            {
                AddUrlModel(html, currUrl, urls, reg);
            }

            return urls;
        }

        private static Dictionary<string, UrlModel> GetSrc(string url,string html)
        {
            if (string.IsNullOrEmpty(html))
                return null;

            UrlModel currUrl = UrlParser.Parse(url);
            Dictionary<string, UrlModel> urls = new Dictionary<string, UrlModel>();
            Regex reg = new Regex("(src="(?<Url>.+?)"|url\((?<Url>.+?)\))", RegexOptions.IgnoreCase);

            if (currUrl != null)
            {
                AddUrlModel(html, currUrl, urls, reg);
            }

            return urls;
        }

        private static void AddUrlModel(string html, UrlModel currUrl, Dictionary<string, UrlModel> urls, Regex reg)
        {
            if (reg.IsMatch(html))
            {
                MatchCollection matchs = reg.Matches(html);
                foreach (Match item in matchs)
                {
                    try
                    {
                        string strUrl = item.Groups["Url"].Value;
                        UrlModel model = new UrlModel();
                        model.RelatedPath = strUrl;
                        model.CurrPath = currUrl.CurrPath;
                        model.RootPath = currUrl.RootPath;
                        model.Scheme = currUrl.Scheme;
                        model.Port = currUrl.Port;
                        model.Host = currUrl.Host;

                        if (strUrl.StartsWith("/"))
                        {
                            //绝对目录情况下
                            model.AbsoluteUri = string.Format("{0}{1}", model.RootPath, model.RelatedPath);
                        }
                        else
                        {
                            //相对目录情况下
                            string currPath = model.CurrPath;
                            int depth = 0;
                            string path = model.RelatedPath;

                            if (path.StartsWith(".."))
                            {
                                try
                                {
                                    while (path.StartsWith(".."))
                                    {
                                        depth++;
                                        path = path.Substring(3);
                                        currPath = currPath.Substring(0, currPath.LastIndexOf("/"));
                                    }

                                    model.AbsoluteUri = string.Format("{0}/{1}", currPath, path);
                                }
                                catch
                                {

                                }
                            }
                            else
                            {
                                model.AbsoluteUri = string.Format("{0}/{1}", currPath, path);
                            }

                        }

                        strUrl = strUrl.Trim().ToLower();

                        urls.Add(strUrl, model);
                    }
                    catch
                    {
                    }
                }
            }
        }
    }
            string Table = inputSql[2].ToString();
            if (string.IsNullOrWhiteSpace(inputCode))
            {
                inputCode = "select *from " + Table;
            }
            StringBuilder returnstr = new StringBuilder();
            StringBuilder strBuilder = new StringBuilder();
            DataSet ds = SqlHelper.Query(inputCode);
            DataRow dr = null;
            DataTable dt = new DataTable();
public class HttpTool
    {
        public static string HttpGet(string url, string referer, string encoding, out string msg)
        {
            msg = string.Empty;
            string result = string.Empty;
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

                //request.ContentType = "application/x-www-form-urlencoded";
                request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
                request.Referer = referer;
                request.Method = "GET";
                request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.122 Safari/537.36";
                //request.Headers.Add("Accept-Language", "zh-cn");
                //request.Headers.Add("Accept-Encoding", "gzip,deflate");

                request.Timeout = 60000;//一分钟

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream responseStream = response.GetResponseStream();
                if (responseStream != null)
                {
                    StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding(encoding));
                    result = reader.ReadToEnd();
                    reader.Close();
                    responseStream.Close();
                    request.Abort();
                    response.Close();
                    return result.Trim();
                }
            }
            catch (Exception ex)
            {
                msg = ex.Message + ex.StackTrace;
            }

            return result;
        }

        public static void DownFile(string uRLAddress, string localPath, string filename)
        {
            WebClient client = new WebClient();
            Stream str = client.OpenRead(uRLAddress);
            StreamReader reader = new StreamReader(str);
            byte[] mbyte = new byte[1000000];
            int allmybyte = (int)mbyte.Length;
            int startmbyte = 0;

            while (allmybyte > 0)
            {
                int m = str.Read(mbyte, startmbyte, allmybyte);
                if (m == 0)
                {
                    break;
                }
                startmbyte += m;
                allmybyte -= m;
            }

            reader.Dispose();
            str.Dispose();

            string path = Path.Combine(localPath, filename);
            FileStream fstr = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
            fstr.Write(mbyte, 0, startmbyte);
            fstr.Flush();
            fstr.Close();
        }
    }

图片 1

 

4R9QU1Y7XFDV43BKKBVDUK3.png

6.一些事件、委托类:

5.png

接口:

     #region 封装实体Model

   #region 封装实体Model

            strBuilder.AppendLine(@"
               public class Model
            {
               ");
            for (int i = 0; i < dr.Table.Columns.Count; i++)
            {
                if (i == 0)
                {
                    Id = dr.Table.Columns[0].ToString();//一般情况第一个字段是主键,当然如果第一个字段不是主键,那就需要修改了
                }
                string Type = dr.Table.Columns[i].DataType.ToString();
                switch (Type)
                {
                    case "System.String":
                        strBuilder.AppendLine("       private string " + "_" + dr.Table.Columns[i] + ";");
                        strBuilder.AppendLine("       public string " + dr.Table.Columns[i] + "");
                        strBuilder.AppendLine("         {");
                        strBuilder.AppendLine("            get { return " + "_" + dr.Table.Columns[i] + "; }");
                        strBuilder.AppendLine("            set { " + "_" + dr.Table.Columns[i] + " = value; }");
                        strBuilder.AppendLine("          }");
                        break;
                    case "System.Int":
                        strBuilder.AppendLine("       private Int " + "_" + dr.Table.Columns[i] + ";");
                        strBuilder.AppendLine("       public Int " + dr.Table.Columns[i] + "");
                        strBuilder.AppendLine("         {");
                        strBuilder.AppendLine("            get { return " + "_" + dr.Table.Columns[i] + "; }");
                        strBuilder.AppendLine("             set { " + "_" + dr.Table.Columns[i] + " = value; }");
                        strBuilder.AppendLine("         }");
                        break;
                    case "System.Int32":
                        strBuilder.AppendLine("       private Int " + "_" + dr.Table.Columns[i] + ";");
                        strBuilder.AppendLine("       public Int " + dr.Table.Columns[i] + "");
                        strBuilder.AppendLine("         {");
                        strBuilder.AppendLine("            get { return " + "_" + dr.Table.Columns[i] + "; }");
                        strBuilder.AppendLine("             set { " + "_" + dr.Table.Columns[i] + " = value; }");
                        strBuilder.AppendLine("         }");
                        break;
                    case "System.DateTime":
                        strBuilder.AppendLine("       private System.DateTime " + "_" + dr.Table.Columns[i] + ";");
                        strBuilder.AppendLine("       public System.DateTime " + dr.Table.Columns[i] + "");
                        strBuilder.AppendLine("          {");
                        strBuilder.AppendLine("             get { return " + "_" + dr.Table.Columns[i] + "; }");
                        strBuilder.AppendLine("             set { " + "_" + dr.Table.Columns[i] + " = value; }");
                        strBuilder.AppendLine("          }");
                        break;
                    case "System.Decimal":
                        strBuilder.AppendLine("       private System.Decimal " + "_" + dr.Table.Columns[i] + ";");
                        strBuilder.AppendLine("       public System.Decimal " + dr.Table.Columns[i] + "");
                        strBuilder.AppendLine("        {");
                        strBuilder.AppendLine("            get { return " + "_" + dr.Table.Columns[i] + "; }");
                        strBuilder.AppendLine("            set { " + "_" + dr.Table.Columns[i] + " = value; }");
                        strBuilder.AppendLine("         }");
                        break;
                    default:
                        strBuilder.AppendLine("       private string " + "_" + dr.Table.Columns[i] + ";");
                        strBuilder.AppendLine("       public string " + dr.Table.Columns[i] + "");
                        strBuilder.AppendLine("        {");
                        strBuilder.AppendLine("             get { return " + "_" + dr.Table.Columns[i] + "; }");
                        strBuilder.AppendLine("             set { " + "_" + dr.Table.Columns[i] + " = value; }");
                        strBuilder.AppendLine("         }");
                        break;
                }
            }
            strBuilder.AppendLine(@"
              }
               ");

            #endregion

下面我将我写的“网站克隆工具”实现方法分享给大家,源码在文末有下载链接,有需要的朋友可以下载来玩,也可以根据自己的需要做相应的修改或优化。

1.png

图片 2

    public bool InsertAgreement_YNSHigh_Authorize(Model model)
        {

            string strSql = @"
               INSERT Agreement_YNSHigh_Authorize(
                 AYA_Code,
                 AYHA_Code,
                 Ctg_ID,
                 HospitalCode,
                 HospitalName,
                 HospitalGrad,
                 HospitalRegionID,
                 DevelopmentLimitTime,
                 EffectiveTime,
                 MarketingManagementFee,
                 BidPrice,
                 DeliveryCode,
                 DeliveryName,
                 AgreeAdjuestType,
                 ChangeContent,
                 Status,
                 DeliveryPrice,
                 BasePrice,
                 CategoryCommodityName,
                 CategorySystemName,
                 CategoryCommName,
                 CategorySpec,
                 Formulation,
                 BusinessModel)
                 VALUES (
                    @AYA_Code,
                    @AYHA_Code,
                    @Ctg_ID,
                    @HospitalCode,
                    @HospitalName,
                    @HospitalGrad,
                    @HospitalRegionID,
                    @DevelopmentLimitTime,
                    @EffectiveTime,
                    @MarketingManagementFee,
                    @BidPrice,
                    @DeliveryCode,
                    @DeliveryName,
                    @AgreeAdjuestType,
                    @ChangeContent,
                    @Status,
                    @DeliveryPrice,
                    @BasePrice,
                    @CategoryCommodityName,
                    @CategorySystemName,
                    @CategoryCommName,
                    @CategorySpec,
                    @Formulation,
                   @BusinessModel)

                     ";
            SqlParameter[] parameters = new SqlParameter[]
                                                  {
                      new SqlParameter("@AYA_Code", SqlDbType.NVarChar, 255),
                     new SqlParameter("@AYHA_Code", SqlDbType.NVarChar, 255),
                     new SqlParameter("@Ctg_ID", SqlDbType.NVarChar, 255),
                     new SqlParameter("@HospitalCode", SqlDbType.NVarChar, 255),
                     new SqlParameter("@HospitalName", SqlDbType.NVarChar, 255),
                     new SqlParameter("@HospitalGrad", SqlDbType.NVarChar, 255),
                     new SqlParameter("@HospitalRegionID", SqlDbType.NVarChar, 255),
                     new SqlParameter("@DevelopmentLimitTime", SqlDbType.DateTime),
                     new SqlParameter("@EffectiveTime", SqlDbType.DateTime),
                      new SqlParameter("@MarketingManagementFee", SqlDbType.Decimal),
                      new SqlParameter("@BidPrice", SqlDbType.Decimal),
                     new SqlParameter("@DeliveryCode", SqlDbType.NVarChar, 255),
                     new SqlParameter("@DeliveryName", SqlDbType.NVarChar, 255),
                     new SqlParameter("@AgreeAdjuestType", SqlDbType.NVarChar, 255),
                     new SqlParameter("@ChangeContent", SqlDbType.NVarChar, 255),
                     new SqlParameter("@Status", SqlDbType.NVarChar, 255),
                      new SqlParameter("@DeliveryPrice", SqlDbType.Decimal),
                      new SqlParameter("@BasePrice", SqlDbType.Decimal),
                     new SqlParameter("@CategoryCommodityName", SqlDbType.NVarChar, 255),
                     new SqlParameter("@CategorySystemName", SqlDbType.NVarChar, 255),
                     new SqlParameter("@CategoryCommName", SqlDbType.NVarChar, 255),
                     new SqlParameter("@CategorySpec", SqlDbType.NVarChar, 255),
                     new SqlParameter("@Formulation", SqlDbType.NVarChar, 255),
                     new SqlParameter("@BusinessModel", SqlDbType.NVarChar, 255),
                            };
            parameters[0].Value = model.AYA_Code;
            parameters[1].Value = model.AYHA_Code;
            parameters[2].Value = model.Ctg_ID;
            parameters[3].Value = model.HospitalCode;
            parameters[4].Value = model.HospitalName;
            parameters[5].Value = model.HospitalGrad;
            parameters[6].Value = model.HospitalRegionID;
            parameters[7].Value = model.DevelopmentLimitTime;
            parameters[8].Value = model.EffectiveTime;
            parameters[9].Value = model.MarketingManagementFee;
            parameters[10].Value = model.BidPrice;
            parameters[11].Value = model.DeliveryCode;
            parameters[12].Value = model.DeliveryName;
            parameters[13].Value = model.AgreeAdjuestType;
            parameters[14].Value = model.ChangeContent;
            parameters[15].Value = model.Status;
            parameters[16].Value = model.DeliveryPrice;
            parameters[17].Value = model.BasePrice;
            parameters[18].Value = model.CategoryCommodityName;
            parameters[19].Value = model.CategorySystemName;
            parameters[20].Value = model.CategoryCommName;
            parameters[21].Value = model.CategorySpec;
            parameters[22].Value = model.Formulation;
            parameters[23].Value = model.BusinessModel;

            using (SqlConnection conn = new SqlConnection(SqlHelper.ConnectionString))
            {
                conn.Open();
                using (SqlTransaction trans = conn.BeginTransaction())
                {
                    try
                    {
                        int i = SqlHelper.ExecuteNonQuery(trans, CommandType.Text, strSql, parameters);
                        if (i > 0)
                        {
                            trans.Commit();
                            return i > 0;
                        }
                        else
                        {
                            trans.Rollback();
                            return false;
                        }
                    }
                    catch (System.Exception e)
                    {
                        return false;
                        trans.Rollback();
                        throw e;
                    }
                }
            }

        }

WebPageService:

图片 3

百度网盘:链接:
密码:7s6r

然后看一下生成的代码展示:

public class UrlParser
    {
        public static UrlModel Parse(string url)
        {
            UrlModel model = new UrlModel();

            //默认
            if (url.Length < 8)
                throw new Exception("url参数不正确");
            else if (!url.ToLower().StartsWith("http:") && !url.ToLower().StartsWith("https:"))
                throw new Exception("url格式有误");

            if (url.LastIndexOf('/') < 8)
                url = url + "/";

            Regex reg = new Regex("(?<scheme>(http|https))://(?<host>.+?)/", RegexOptions.Singleline);

            if (reg.IsMatch(url))
            {
                string scheme = reg.Match(url).Groups["scheme"].Value;
                string host = reg.Match(url).Groups["host"].Value;
                if (host.Contains(":"))
                {
                    var aa = host.Split(':');
                    if (aa.Length == 2)
                    {
                        model.Host = aa[0];
                        model.Port = int.Parse(aa[1]);
                    }
                }
                else
                {
                    model.Host = host;
                    model.Port = 80;
                }

                int index = url.IndexOf('/', 8);

                model.RelatedPath = url.Substring(index);
                model.AbsoluteUri = url;
                model.Scheme = scheme;
                model.CurrPath = url.Substring(0, url.LastIndexOf("/"));

                if (80 == model.Port)
                {
                    model.RootPath = string.Format("{0}://{1}", model.Scheme, model.Host);
                }
                else
                {
                    model.RootPath = string.Format("{0}://{1}:{2", model.Scheme, model.Host, model.Port);
                }
            }
            else
            {
                throw new Exception("url解析失败!");
            }

            return model;
        }
    }

图片 4

4.网页源码扒取类

其实界面特别简单的。就是几个label、多选框、容器。
看下代码:

 

图片 5

5.网站克隆主类

首先是对控件传递过来值得检查,参数是否为空等。

图片 6

using System;
using System.Windows.Forms;

namespace DevLogHelper
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new BaseSqlBuilder());
        }

    }
}
public class UrlModel
    {
        public string RelatedPath { get; set; }
        public string AbsoluteUri { get; set; }
        public string CurrPath { get; set; }
        public string RootPath { get; set; }

        public string Host { get; set; }
        public int Port { get; set; }
        public string Scheme { get; set; }
    }

窗体BaseSqlBuilder继承自Form不必多说。ResourceManager是什么呢,ResourceManager就是一个资源文件,用于处理消息,或者路径什么。后面补上图。
新建一个BaseSql用于处理sql。把页面上的控件消息传递过去。封装一个数据的形式。

图片 7

            if ((bool)inputSql[4])
            {
                returnstr.AppendLine(strBuilder.ToString());
            }
            strBuilder = new StringBuilder();
            #region 生成更新Update 方法

            #region 生成更新Update sql语句

            strTmp = new StringBuilder(); //sql 
            try
            {
                for (int i = 0; i < dr.Table.Columns.Count; i++)//生成Update 
                {
                    if (i == 0)
                    {
                        strTmp.AppendLine("               Update " + Table + "  SET ");
                    }
                    if (i == dr.Table.Columns.Count - 1)
                    {


                        strTmp.AppendLine("                 " + dr.Table.Columns[i].ToString() + "=" + "@" + dr.Table.Columns[i].ToString() + " where " + Id + "=" + "@" + Id + "  ");
                    }
                    else
                    {
                        strTmp.AppendLine("                  " + dr.Table.Columns[i].ToString() + "=" + "@" + dr.Table.Columns[i].ToString() + ",");
                    }
                }
            }
            catch (System.Exception ex)
            {

                throw ex;
            }

            #endregion




            strBuilder.AppendLine("   public bool Update" + Table + "ById(Model model)");
            strBuilder.AppendLine(@"    {   
           ");
            strBuilder.AppendLine("                    string strSql = @"");
            strBuilder.AppendLine(strTmp.ToString());
            strBuilder.AppendLine("                     ";");

            strBuilder.AppendLine(@"                 SqlParameter[] parameters = new SqlParameter[]
                                                  {");
            //参数类型
            for (int i = 0; i < dr.Table.Columns.Count; i++)
            {
                string Type = dr.Table.Columns[i].DataType.ToString();
                switch (Type)
                {
                    case "System.String":
                        strBuilder.AppendLine("                     new SqlParameter("" + "@" + dr.Table.Columns[i] + "", SqlDbType.NVarChar, 255),");
                        break;
                    case "System.Int":
                        strBuilder.AppendLine("                     new SqlParameter("" + "@" + dr.Table.Columns[i] + "", SqlDbType.Int),");
                        break;
                    case "System.DateTime":
                        strBuilder.AppendLine("                     new SqlParameter("" + "@" + dr.Table.Columns[i] + "", SqlDbType.DateTime),");
                        break;
                    case "System.Decimal":
                        strBuilder.AppendLine("                      new SqlParameter("" + "@" + dr.Table.Columns[i] + "", SqlDbType.Decimal),");
                        break;
                    default:
                        strBuilder.AppendLine("                      new SqlParameter("" + "@" + dr.Table.Columns[i] + "", SqlDbType.NVarChar, 255),");
                        break;
                }
            }
            strBuilder.AppendLine(@"                            };");

            for (int i = 0; i < dr.Table.Columns.Count; i++)
            {
                strBuilder.AppendLine("                        parameters[" + i + "].Value =" + "model." + dr.Table.Columns[i] + ";");
            }

            strBuilder.AppendLine(@"
            using (SqlConnection conn = new SqlConnection(SqlHelper.ConnectionString))
            {
                conn.Open();
                using (SqlTransaction trans = conn.BeginTransaction())
                {
                    try
                    {
                        int i = SqlHelper.ExecuteNonQuery(trans, CommandType.Text, strSql, parameters);
                          if (i > 0)
                        {
                            trans.Commit();
                            return i > 0;
                        }
                        else
                        {
                            trans.Rollback();
                            return false;
                        }
                    }
                    catch (System.Exception e)
                    {
                        return false;
                        trans.Rollback();
                        throw e;
                    }
                  }
               }
               ");
            strBuilder.AppendLine("}");

            #endregion

            if ((bool)inputSql[5])
            {
                returnstr.AppendLine(strBuilder.ToString());
            }
            strBuilder = new StringBuilder();
            #region 生成查询方法

            strBuilder.AppendLine("   public DataTable GetDataBy" + Table + "(Model model , int pageNo, int pageSize, ref int iRecordCount)");
            strBuilder.AppendLine(@"    {    ");
            strTmp = new StringBuilder();
            strTmp.AppendLine("WITH temp AS ( SELECT rn =  ROW_NUMBER() OVER (ORDER BY " + Id + "  desc), *FROM  " + Table + " WHERE 1=1 {0} )");
            strTmp.AppendLine("SELECT *,rc=(select count(1) from temp) FROM temp WHERE rn BETWEEN {1} AND {2}");

            strBuilder.AppendLine("        List<SqlParameter> parameters = new List<SqlParameter>();");
            strBuilder.AppendLine("        StringBuilder sqlWhere = new StringBuilder();");
            for (int i = 0; i < dr.Table.Columns.Count; i++)
            {
                strBuilder.AppendLine("       if (!string.IsNullOrEmpty(model." + dr.Table.Columns[i].ToString() + ".ToString())) ");
                strBuilder.AppendLine("       {");
                strBuilder.AppendLine("          sqlWhere.Append(" AND " + dr.Table.Columns[i].ToString() + "=@" + dr.Table.Columns[i].ToString() + "");");
                strBuilder.AppendLine("          parameters.Add(new SqlParameter("@" + dr.Table.Columns[i].ToString() + "", SqlDbType.NVarChar, 255) { SqlValue = model." + dr.Table.Columns[i].ToString() + " });");
                strBuilder.AppendLine("       } ");
            }
            strBuilder.AppendLine("                    string strSql = string.Format(@"");
            strBuilder.AppendLine(strTmp.ToString());
            strBuilder.AppendLine("                     " ,sqlWhere.ToString(), (pageNo - 1) * pageSize + 1, pageNo * pageSize);");

            strBuilder.AppendLine(@"    

                   DataTable dt = SqlHelper.Query(strSql, parameters.ToArray()).Tables[0];
                  if (dt!=null)
                   {");
            strBuilder.AppendLine("        iRecordCount = int.Parse(dt.Rows[0]["" + "rc" + ""].ToString());");
            strBuilder.AppendLine(@"      return dt;
                            }
                           else
                          {
                              iRecordCount = 0;
                            return null;
                        }
                }    ");

            #endregion

            if ((bool)inputSql[6])
            {
                returnstr.AppendLine(strBuilder.ToString());
            }
            strBuilder = new StringBuilder();
            #region 生成删除的方法

            strBuilder.AppendLine("    public bool Delete" + Table + "(string " + Id + ")");
            strBuilder.AppendLine("   {");
            strBuilder.AppendLine("        List<SqlParameter> parameters = new List<SqlParameter>();");
            strTmp = new StringBuilder();
            strTmp.AppendLine("DELETE " + Table + " WHERE " + Id + "=" + Id + "");
            strBuilder.AppendLine("                    string strSql = string.Format(@"");
            strBuilder.AppendLine(strTmp.ToString());
            strBuilder.AppendLine("                     ";");
            strBuilder.AppendLine("     int rowAffect =SqlHelper.Query(strSql, parameters.ToArray()).ToInt();;");
            strBuilder.AppendLine("      return rowAffect > 0 ? true : false;");
            strBuilder.AppendLine("      }");

            #endregion

            if ((bool)inputSql[7])
            {
                returnstr.AppendLine(strBuilder.ToString());
            }
            strBuilder = new StringBuilder();

一睹为快,先看看界面:

跟踪BuilderCode到BaseSql类。

public delegate void UrlChangedEventHandler(object sender, UrlChangedEventArgs e);
    public delegate void FileSavedSuccessEventHandler(object sender, FileSavedSuccessEventArgs e);
    public delegate void FileSavedFailEventHandler(object sender, FileSavedFailEventArgs e);
    public delegate void DownloadCompletedEventHandler(object sender, DownloadCompletedEventArgs e);
    public delegate void CollectingUrlEventHandler(object sender, CollectingUrlEventArgs e);
    public delegate void CollectedUrlEventHandler(object sender, CollectedUrlEventArgs e);
    public delegate void ProgressChangedEventHandler(object sender, ProgressChangedEventArgs e);

懒人小工具:T4自动生成Model,Insert,Select,Delete以及导出Excel的方法
在开发的过程中,我们为了节约时间,往往会将大量重复机械的代码封装,考虑代码的复用性,这样我们可以节约很多时间来做别的事情。最近跳槽到一节webform开发的公司,主要是开发自己公司用的ERP。开始因为一些诱惑进来的,现在感觉其实有些后悔放弃了很好的学习ABP以及新知识点像一些很新颖的前端框架进这个公司。但现在跳槽也不是一个明智之举,不好意思扯远了,既来之则安之。最近写了个小工具。主要针对webform开发过程中一些重复的代码处理。
其实没有什么特别大的技术难度,其实webform开发貌似也没有特别大的技术难度。
首先新建一个类库WorkHelper。
然后新建类Program.cs,这里是作为主程序入口。

 

首先我们是生成Model。有了Model才有下面的增删改查的方法。
其实也很简单,dr.Table.Columns[i].DataType.ToString(),我们就是根据DataRow循环table列,判断字段类型,然后根据对应的字段类型封装成model.单选框默认勾选的,这里先去掉勾选,输入表名,点击生成,然后和数据库表对应,看一下效果。

1.新建主界面窗体(MainForm.cs):

图片 8

相关文章

Leave a Reply

电子邮件地址不会被公开。 必填项已用*标注