Delete以至导出Excel的点子,自用建设中型小型型网

前二日朋友叫本人模仿一个网址,刚刚以前,小编三个页面一个页面查看源码并复制和保存,花了自己无数岁月,二个字“累”,为了缓慢解决工作量,作者写了个网址“克隆工具”,一键克隆,比起人工操作, 
频率增加了200%上述,正确度也大大进步,即使英特网也比较多网址克隆工具,但自己感到作为三个程序猿,要有点商量精神,哈哈哈,能够依附本身的必要自由编写自身供给的效果与利益。

懒人小工具:T4自动生成Model,Insert,Select,Delete以至导出Excel的主意
在支付的进度中,我们为了节约时间,往往会将大气重新机械的代码封装,考虑代码的复用性,那样大家能够节省非常多岁月来做别的事情。近些日子跳槽到一节webform开辟的商铺,首尽管支付自身集团用的ERP。起先因为有的诱惑进来的,未来以为其实某些后悔吐弃了很好的就学ABP以至新知识点像有些很新颖的前端框架进那个公司。但这段时间换工作亦不是贰个明智之举,倒霉意思扯远了,既来之则安之。近日写了个小工具。主要针对webform开采进度中部分重复的代码管理。
实则未有怎么非常大的技巧难度,其实webform开垦貌似也未曾特意大的技艺难度。
率先新建多少个类库WorkHelper。
下一场新建类Program.cs,这里是作为主程序入口。

前言:此”急忙变化后台“为自个儿仿效discuz开源代码效果组装而成。无高深手艺,只讲究急迅转移,适合建设中型Mini型网址。运用妥贴能够批量生产网址后台。

咱俩的网址日常位于设想空间还是服务器上,图片如若存在本地目录,会据有比较多空大壮流量,还扩大了担任,好的格局是把图片贮存到云积存劳动之中,平常用url去拿

下面小编将自己写的“网站克隆工具”实现格局共享给大家,源码在文末有下载链接,有要求的心上人能够下载来玩,也得以依据自个儿的内需做相应的更换或优化。

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());
        }

    }
}

 

云储存:广泛说又拍云和七牛相比好,看见七牛不收费额度非常大,网络商议也蛮好的,我就选了七牛

一睹为快,先看看界面:

为Main()方法加上STAThread标签。每趟只好运转多个窗口。
new 多少个BaseSqlBuilder实例,BaseSqlBuilder实例是怎样呢,正是我们前几天的大旨了。

以二个资源新闻系统为例子,写出详细建设进度,分享一下,以备后用。涉及工具备:VS2009、PowerDesigner、SQL Server 二零一零、DBBuildCode、ultraedit。

编辑器:小编用的是百度的UEditor编辑器,之后需求修改部分的开放的类和js文件

图片 1

图片 2

 

上边写一下java版本(maven)的修改章程(c#版本在上一篇)

 

1.png

一、设计页面

 

归纳的行事流程:

实际分界面非常轻巧的。正是多少个label、多选框、容器。
看下代码:

 

一、集成UEditor

图片 3

using System;
using System.Resources;
using System.Text;
using System.Windows.Forms;
using DevLogHelper.Resources;

namespace DevLogHelper
{
    public partial class BaseSqlBuilder : Form
    {
        readonly ResourceManager _rm = new ResourceManager(typeof(ResourceDevCode));
        public BaseSqlBuilder()
        {
            InitializeComponent();
        }

        private void BaseSqlBuilder_Load(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// 生成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCreate_Click(object sender, EventArgs e)
        {
            string msg = _rm.GetString("BaseSqlTip");
            try
            {
                BaseSql.BaseSql sq = new BaseSql.BaseSql();
                StringBuilder str = sq.BuilderCode(txtInput.Text, cbIsModel, txt_TableName.Text, ckb_Model.Checked, ckb_Insert.Checked,ckb_Update.Checked,ckb_Select.Checked,ckb_Delete.Checked,ckbExcel.Checked);
                txtResult.Text = str.ToString();
                Clipboard.SetDataObject(str.ToString());
            }
            catch (Exception ex)
            {
                msg = ex.Message;
            }
            labTip.Text = msg;
        }

    }
}

1、展开VS2009,新建三个空网址,保存至News文件夹。

1、在等级次序中投入UEditor

在UEditor的下载页,可以下载到新型的1.4.3.3 Jsp版本(UTF-8),把解压出的文件夹放进项目

 

窗体BaseSqlBuilder承继自Form不必多说。ResourceManager是何许吗,ResourceManager就是二个财富文件,用于拍卖新闻,恐怕路线如何。前面补上海体育场所。
新建二个BaseSql用于拍卖sql。把页面上的控件音信传递过去。封装贰个数据的方式。

 

2、在品种中走入UEditor的后端程序

在UEditor的下载页,下载1.4.3.3 完整源码(里面有jsp版后端的源码),因为上面jsp版里的唯有UEditor的jar包,引用jar包的话就改不了了,所以大家依然把源码放进项目来改

把ueditor1_4_3_3-src.rar -> jsp -> src里的com文件夹拷进项目,然后在maven的pom.xml里引用:

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.9</version>
</dependency>
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
</dependency>
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20160212</version>
</dependency>

类型代码目录结构:

财富文件以至应用方案结构。

图片 4

3、将UEditor嵌入页面

新建一个页面,内容是:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>UEditor上传图片到七牛(java)</title>
    <script type="text/javascript">
        window.UEDITOR_HOME_URL = '/demo/UEditor/';
    </script>
    <script src="/demo/UEditor/ueditor.config.js" type="text/javascript"></script>
    <script src="/demo/UEditor/ueditor.all.js" type="text/javascript"></script>
</head>
<body>
    <form id="form1" runat="server">
        <script type="text/plain" id="editor" name="editContent" style="width:600px; height:300px;"></script>
        <script type="text/javascript">
            var ue = UE.getEditor('editor');
        </script>
    </form>
</body>
</html>

图片 5

图片 6

 

4、运维效果

末段的文件目录:

图片 7

页面包车型大巴运作效果:

图片 8

 

 

4R9QU1Y7XFDV43BKKBVDUK3.png

 

二、集成七牛sdk

在maven的pom.xml里引用:

<dependency>
    <groupId>com.qiniu</groupId>
    <artifactId>qiniu-java-sdk</artifactId>
    <version>7.0.8</version>
</dependency>

 

下边一步步兑现程序功用:

跟踪BuilderCode到BaseSql类。

2、增多新项:NewsList.aspx、NewsEdit.aspx2个Web窗体,新建文件夹:Style(main.css、general.css),新建文件夹:Images(分界面所需图片)。

三、上传图片到七牛

 

图片 9

 

1、添加QiniuHelper.cs帮助类

那是为着接下来方便修改写的一个工具类,使用它能够省部分再次代码

package org.xs.demo;

import java.io.File;
import java.util.UUID;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

/**
 * 七牛上传帮助类
 */
public class QiniuHelper {

    /**
     * 空间名
     */
    private static String Scope = "xxxx";

    /**
     * 域名
     */
    private static String Url = "xxxxxxxxx.bkt.clouddn.com";

    /**
     * 公钥
     */
    private static String ACCESS_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

    private static String SECRET_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

    /**
     * 上传附件
     * @throws QiniuException 
     */
    public static String UploadFile(File file) throws QiniuException {

        String key = UUID.randomUUID().toString().replaceAll("-", "");

        try {
            //创建上传对象
            UploadManager uploadManager = new UploadManager();

            //密钥配置
            Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);

            //上传文件
            Response res = uploadManager.put(file, key, auth.uploadToken(Scope, key));
        } catch (Exception e) {
            return "";
        }
        return key;
    }

    /**
     * 获得url地址
     */
    public static String GetUrl(String key)
    {
        return String.format ("http://%s/%s", Url, key);
    }
}

Scope是储存空间的名称

Url是储存空间的域名(也足以用自身的正统域名)

ACCESS_KEY和SECRET_KEY是客户的一对密钥,在个体面板 -> 个人基本 -> 密钥管理 分界面中能够创建、查看

那多少个参数也足以写成从陈设文件读取的

 

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

87C8U$IKXP(%OJ{M~HT2YPA.png

图片 10

2、修改StorageManager.java类

找到com.baidu.ueditor/upload/StorageManager.java类,找到以下代码:

state = saveTmpFile(tmpFile, path);

if (!state.isSuccess()) {
    tmpFile.delete();
}

修改成:

//state = saveTmpFile(tmpFile, path);

//存储文件到七牛
String key= QiniuHelper.UploadFile(tmpFile);

state = new BaseState(true);
state.putInfo("size", tmpFile.length());
state.putInfo("title", tmpFile.getName());
state.putInfo("url", QiniuHelper.GetUrl(key));

//if (!state.isSuccess()) {
    tmpFile.delete();
//}

 

图片 11

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

 

3、修改BinaryUploader.java类

找到com.baidu.ueditor/upload/BinaryUploader.java类,找到以下代码:

storageState.putInfo("url", PathFormat.format(savePath));

讲解掉它

//storageState.putInfo("url", PathFormat.format(savePath));

 

2.新建立模型型类(UrlModel.cs)

            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();

 

4、修改UEditor的配置

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; }
    }

此处假若传递过来的sql语句为空,我们会根据表名自动生成查询SQL。然后依据ado.net 链接数据库生成DataSet 、DataRow 、DataTable 等。当然这里得有SqlHelper。SqlHelper假如须要能够去自身源码上下载,稍后会放上源码。首如果链接数据库。施行SQL了。

3、设计NewsList.aspx(新闻列表)、NewsEdit.aspx(新闻编辑)页面。

(1)、关闭自动本地保存

找到UEditorueditor.all.js文件,查找"'contentchange': function () {",在此个函数内扩展代码:

'contentchange': function () {

    //关闭自动本地保存
    if (!me.getOpt('enableAutoSave')) {
        return;
    }

诸如此比就不会时不经常跳出烦人的指示框了

 

3.新建服务类(瑟维斯s)

     #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

 

5、图片上传运转效果

末段测验一下图形上传是或不是中标

单图片上传:

图片 12

图片 13

剧情里src已经变为了七牛的地方了

再看多图片上传:

图片 14

图片 15

 

UrlParser:

率先大家是浮动Model。有了Model才有下边包车型客车增加和删除改查的不二秘技。
事实上也很轻便,dr.Table.Columns[i].DataType.ToString(),大家就是基于DataRow循环table列,决断字段类型,然后遵照对应的字段类型封装成model.单选框暗中认可勾选的,这里先消除勾选,输入表名,点击生成,然后和数量库表对应,看一下效果。

图片 16 

7、demo下载

新颖的代码地址:

 

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;
        }
    }

图片 17

 

四、别的扩张

图片 18

那是自己的博客里面使用的,设置富有图片尺寸和进入相册功效,其实正是在UEditor里修改几处js,然后扩大二个加入相册服务

措施临时不收拾了,博客的代码在这里地:(c#)

 

WebPageService:

2.png

图片 19

/// <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
                    {
                    }
                }
            }
        }
    }

Model 是最实用的,尽管以往我们在用mvc也许ABP等任何框架底层用codefirst等orm框架的时候,大家也能够用这种措施转变Model.

 

4.网页源码扒取类

    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;
                    }
                }
            }

        }

 

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();
        }
    }

一生我们在疯长多少的时候,就以Agreement_YNSHigh_Authorize为例,平时都以那般超做的,加上业务,参数化传过来的参数,那样写起来也要命辛勤。大家那边了也对INSERT 做一下包装。

二、设计数据库

5.网址克隆主类

    #region 生成插入Insert方法

            #region 生成插入sql语句

            StringBuilder strTmp = new StringBuilder();
            try
            {
                for (int i = 0; i < dr.Table.Columns.Count; i  )//生成insert 
                {
                    if (i == 0)
                    {
                        strTmp.AppendLine("               INSERT "   Table   "(");
                    }
                    if (i == dr.Table.Columns.Count - 1)
                    {
                        strTmp.AppendLine("                 "   dr.Table.Columns[i].ToString()   ")");
                    }
                    else
                    {
                        strTmp.AppendLine("                 "   dr.Table.Columns[i].ToString()   ",");
                    }
                }

                for (int i = 0; i < dr.Table.Columns.Count; i  )
                {
                    if (i == 0)
                    {
                        strTmp.AppendLine("                 VALUES "   "(");
                    }
                    if (i == dr.Table.Columns.Count - 1)
                    {
                        strTmp.AppendLine("                   @"   dr.Table.Columns[i].ToString()   ")");
                    }
                    else
                    {
                        strTmp.AppendLine("                    @"   dr.Table.Columns[i].ToString()   ",");
                    }

                }
            }
            catch (System.Exception ex)
            {

                throw ex;
            }

            #endregion





            strBuilder.AppendLine("   public bool Insert"   Table   "(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.Int32":
                        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

 

接口:

先是是根据sql生成字段和参数字段。这都以很麻烦的工作,何况无法出错。也是对DataRow table的循环和打包管理。供给在乎一下转义字符管理,注意对业务的管理。别的update,select,delete的管理格局与insert类似,不在累述,放上代码。

1、打开PowerDesigner ,建表News。

interface IWebCloneWorker
    {
        void Start();
        void Cancel();
    }
            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();

 

 

if ((bool)inputSql[7])重若是对控件值得判断,是或不是勾选上,也正是是或不是要求生成改方法。导出的法子主要在信用合作社一度封装好的代码上领取重复代码的,日常我们在做成效的时候只要求写那么些代码就可以。

图片 20

 

      #region 导出excel方法

            strBuilder.AppendLine(@"     protected void btnExcel_Click(object sender, System.EventArgs e)
        {
            int intPageNo = 1;
            int intPageSize = 65535;
            int recordCount = 0;
            DataTable dt = GetUnAuthorizeAgreePassedDT( Model model intPageNo, intPageSize, out recordCount); ");
            strBuilder.AppendLine("     string strFileName = ""   "导出Excel"   ""   System.DateTime.Now.ToString(" "   "yyyyMMddHHmmss"   "");");
            strBuilder.AppendLine(@"        ExcelUtility excelUtil = new ExcelUtility(this, strFileName);
            List<ExcelHeader> headerS = new List<ExcelHeader>() { ");

            for (int i = 0; i < dr.Table.Columns.Count; i  )
            {
                string Type = dr.Table.Columns[i].DataType.ToString();
                switch (Type)
                {
                    case "System.DateTime":
                        strBuilder.AppendLine("           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.日期, Width = 15 },");
                        break;
                    default:
                        strBuilder.AppendLine("           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.文本, Width = 15 },");
                        break;
                }
            }
            strBuilder.AppendLine(@"          };
            excelUtil.CreateHeader(headerS);
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    List<string> dataVals = new List<string>() { ");


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

            strBuilder.AppendLine(@"          };       
                    excelUtil.CreateItemRow(dataVals);
                }
            }
            excelUtil.Export();
            }
           "); 
            #endregion

 

实现类:

图片 21

 

public class WebCloneWorker : IWebCloneWorker
    {
        //网站页面克隆深度(如:0-首页,1-分类页,2-详细页面)
        public static int depth = 0;

        //要克隆的网站网址
        public string Url { get; set; }

        //克隆后,保存的路径
        public string SavePath { get; set; }

        private BackgroundWorker backgroundWorker1 = null;
        public event UrlChangedEventHandler UrlChanged;
        public event FileSavedSuccessEventHandler FileSavedSuccess;
        public event FileSavedFailEventHandler FileSavedFail;
        public event DownloadCompletedEventHandler DownloadCompleted;
        public event CollectingUrlEventHandler CollectingUrl;
        public event CollectedUrlEventHandler CollectedUrl;
        public event ProgressChangedEventHandler ProgressChanged;

        //所有页面、文件资源地址集合
        private Dictionary<string, UrlModel> _Hrefs = new Dictionary<string, UrlModel>();

        /// <summary>
        /// 所有页面、文件资源地址集合
        /// </summary>
        public Dictionary<string,UrlModel> Hrefs
        {
            get { return _Hrefs; }
            set { _Hrefs = value; }
        }

        //网站页面请求编码,默认为UTF-8
        private string _Encoding = "utf-8";

        //网站页面请求编码,默认为UTF-8
        public string Encoding
        {
            get { return _Encoding; }
            set { _Encoding = value; }
        }

        public WebCloneWorker() { }

        public WebCloneWorker(string url,string path) 
        {
            //设置网站、保存路径
            this.Url = url;
            this.SavePath = path;

            if (string.IsNullOrEmpty(this.Url))
                throw new Exception("请输入网址");

            if (string.IsNullOrEmpty(this.SavePath))
                throw new Exception("请选择要保存的目录");

            backgroundWorker1 = new BackgroundWorker();

            //设置报告进度更新
            backgroundWorker1.WorkerReportsProgress = true;
            backgroundWorker1.WorkerSupportsCancellation = true;

            //注册线程主体方法
            backgroundWorker1.DoWork  = backgroundWorker1_DoWork;

            //注册更新UI方法
            backgroundWorker1.ProgressChanged  = backgroundWorker1_ProgressChanged;

            //处理完毕
            backgroundWorker1.RunWorkerCompleted  = backgroundWorker1_RunWorkerCompleted;
        }

        void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled) {
                return;
            }

            if (this.DownloadCompleted != null)
            {
                DownloadCompletedEventArgs eventArgs = new DownloadCompletedEventArgs(e.Result, e.Error, e.Cancelled);
                this.DownloadCompleted(this, eventArgs);
            }
        }

        void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            //进度回调
            if (this.ProgressChanged != null) 
                this.ProgressChanged(this, e);

            UrlModel model = (UrlModel)e.UserState;

            if (this.UrlChanged != null)
            {
                //Url改变后,回调
                UrlChangedEventArgs eventArgs = new UrlChangedEventArgs(model);
                this.UrlChanged(this, eventArgs);
            }

            try
            {
                string dir = this.SavePath;
                string url = model.AbsoluteUri;
                string AbsolutePath = url.Substring(url.IndexOf('/', 8));
                string fileName = "";

                if (url.IndexOf('?') > 0)
                {
                    string path = AbsolutePath.Substring(0, model.RelatedPath.IndexOf('?'));
                    fileName = System.IO.Path.GetFileName(path);
                }
                else
                {
                    fileName = System.IO.Path.GetFileName(AbsolutePath);
                }

                //默认首页
                if (string.IsNullOrEmpty(fileName) || fileName.IndexOf(".") < 0)
                {
                    fileName = "index.html";

                    if (!AbsolutePath.EndsWith("/"))
                        AbsolutePath = AbsolutePath   "/";
                }

                fileName = System.Web.HttpUtility.UrlDecode(fileName);

                string localPath = string.Format("{0}{1}", dir, System.IO.Path.GetDirectoryName(AbsolutePath));
                if (!System.IO.Directory.Exists(localPath))
                {
                    System.IO.Directory.CreateDirectory(localPath);
                }

                //判断文件是否存在,存在不再下载
                string path2 = Path.Combine(localPath, fileName);
                if (File.Exists(path2))
                {
                    return;
                }

                //下载网页、图片、资源文件
                HttpTool.DownFile(url, localPath, fileName);

                //保存成功后,回调
                if (this.FileSavedSuccess != null)
                {
                    FileSavedSuccessEventArgs eventArgs = new FileSavedSuccessEventArgs(model);
                    this.FileSavedSuccess(this, eventArgs);
                }
            }
            catch (Exception ex)
            {
                //保存失败后,回调
                if (this.FileSavedFail != null)
                {
                    FileSavedFailEventArgs eventArgs = new FileSavedFailEventArgs(ex);
                    this.FileSavedFail(this, eventArgs);
                }
            }
        }

        void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            //获取资源
            GetResource();

            int index = 1;
            if (this.Hrefs.Keys.Count > 0)
            {
                foreach (var k in this.Hrefs.Keys)
                {
                    //取消操作
                    if (backgroundWorker1.CancellationPending)
                    {
                        e.Cancel = true;
                        return;
                    }

                    backgroundWorker1.ReportProgress(index, this.Hrefs[k]);
                    index  ;

                    //挂起当前线程200毫秒
                    Thread.Sleep(200);
                }
            }
        }

        public void Start()
        {
            if (this.backgroundWorker1.IsBusy)
                return;

            this.backgroundWorker1.RunWorkerAsync();
        }

        public void Cancel()
        {
            if (this.backgroundWorker1.CancellationPending)
                return;

            this.backgroundWorker1.CancelAsync();
        }

        private void GetResource()
        {
            string url = this.Url;
            string referer = this.Url;
            string msg = "";
            string html = HttpTool.HttpGet(url, referer, this.Encoding, out msg);

            //收集页面链接
            GetHrefs(0, url, html);

            //收集完毕
            if (null != CollectedUrl)
            {
                UrlModel urlModel = new UrlModel();
                CollectedUrlEventArgs eventArgs = new CollectedUrlEventArgs(urlModel);
                this.CollectedUrl(this, eventArgs);
            }

        }

        private void GetHrefs(int level,string url,string html)
        {
            #region 添加当前页

            UrlModel currUrl = UrlParser.Parse(url);

            try
            {
                //取消
                if (backgroundWorker1.CancellationPending)
                    return;

                this.Hrefs.Add(currUrl.RelatedPath, currUrl);

                //收集回调
                if (null != CollectingUrl)
                {
                    CollectingUrlEventArgs eventArgs = new CollectingUrlEventArgs(currUrl);
                    this.CollectingUrl(this, eventArgs);
                }
            }
            catch
            {
            }

            #endregion

            //获取相关链接(含有href属性的)
            List<UrlModel> list1 = WebPageService.GetLocalHrefs(url,html);

            //获取图片,文件等资源文件(含有src属性的)
            List<UrlModel> listSrcs = WebPageService.GetLocalSrcs(url,html);

            #region 获取当级资源文件

            if (listSrcs != null)
            {
                for (int i = 0; i < listSrcs.Count; i  )
                {
                    UrlModel urlModel = listSrcs[i];
                    try
                    {
                        //取消
                        if (backgroundWorker1.CancellationPending) 
                            return;

                        this.Hrefs.Add(urlModel.RelatedPath, urlModel);

                        //收集回调
                        if (null != CollectingUrl)
                        {
                            CollectingUrlEventArgs eventArgs = new CollectingUrlEventArgs(urlModel);
                            this.CollectingUrl(this, eventArgs);
                        }
                    }
                    catch
                    { }
                }
            }

            #endregion

            #region 获取子级页面资源

            //获取第二级
            if (list1 != null)
            {
                for (int i = 0; i < list1.Count; i  )
                {
                    UrlModel urlModel = list1[i];

                    try
                    {
                        //取消
                        if (backgroundWorker1.CancellationPending)
                            return;

                        this.Hrefs.Add(urlModel.RelatedPath, urlModel);

                        //收集回调
                        if (null != CollectingUrl)
                        {
                            CollectingUrlEventArgs eventArgs = new CollectingUrlEventArgs(urlModel);
                            this.CollectingUrl(this, eventArgs);
                        }
                    }
                    catch
                    { }

                    string msg = "";
                    html = HttpTool.HttpGet(urlModel.AbsoluteUri, urlModel.AbsoluteUri, this.Encoding, out msg);

                    #region 获取子级资源文件

                    /*
                     * 获取二级资源文件
                     * */
                    listSrcs = WebPageService.GetLocalSrcs(urlModel.AbsoluteUri, html);//资源文件

                    if (listSrcs != null)
                    {
                        for (int j = 0; j < listSrcs.Count; j  )
                        {
                            UrlModel urlModel2 = listSrcs[j];

                            try
                            {
                                //取消
                                if (backgroundWorker1.CancellationPending)
                                    return;

                                this.Hrefs.Add(urlModel2.RelatedPath, urlModel2);

                                //收集回调
                                if (null != CollectingUrl)
                                {
                                    CollectingUrlEventArgs eventArgs = new CollectingUrlEventArgs(urlModel2);
                                    this.CollectingUrl(this, eventArgs);
                                }
                            }
                            catch
                            { }

                            //挂起线程20毫秒
                            Thread.Sleep(20);
                        }
                    }
                    #endregion

                    //挂起线程20毫秒
                    Thread.Sleep(20);

                    //到达指定深度后,退出
                    if (level >= depth)
                        return;

                    //递归
                    GetHrefs(level   1, urlModel.AbsoluteUri, html);
                }
            }

            #endregion
        }
    }

3.png

2、展开SQL Server 二〇一〇,新建数据库News,新建表:News(从PowerDesigner中取建表语句)。

 

图片 22

 

6.局地平地风波、委托类:

4.png

图片 23

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);

图片 24

 

 

5.png

 

public class CollectedUrlEventArgs : EventArgs
public class CollectingUrlEventArgs : EventArgs
public class DownloadCompletedEventArgs : EventArgs
public class FileSavedFailEventArgs : EventArgs
public class FileSavedSuccessEventArgs : EventArgs
public class UrlChangedEventArgs : EventArgs

别的做了多少个效用,不过不是很好用,感兴趣的恋人能够去下载源码看一下。
github地址:https://github.com/Jimmey-Jiang/JWorkHelper

三、自动生成数据库代码

 

下一场看一下变通的代码呈现:

 

代码有一点多,各位有须求的恐怕下载源码查看并运行吧,由于赶时间,没时间留意测量检验程序的一一职能,难免有不足的地点。

        public class Model
        {

            private Int _AYA_Code;
            public Int AYA_Code
            {
                get { return _AYA_Code; }
                set { _AYA_Code = value; }
            }
            private string _AYHA_Code;
            public string AYHA_Code
            {
                get { return _AYHA_Code; }
                set { _AYHA_Code = value; }
            }
            private string _Ctg_ID;
            public string Ctg_ID
            {
                get { return _Ctg_ID; }
                set { _Ctg_ID = value; }
            }
            private string _HospitalCode;
            public string HospitalCode
            {
                get { return _HospitalCode; }
                set { _HospitalCode = value; }
            }
            private string _HospitalName;
            public string HospitalName
            {
                get { return _HospitalName; }
                set { _HospitalName = value; }
            }
            private string _HospitalGrad;
            public string HospitalGrad
            {
                get { return _HospitalGrad; }
                set { _HospitalGrad = value; }
            }
            private string _HospitalRegionID;
            public string HospitalRegionID
            {
                get { return _HospitalRegionID; }
                set { _HospitalRegionID = value; }
            }
            private System.DateTime _DevelopmentLimitTime;
            public System.DateTime DevelopmentLimitTime
            {
                get { return _DevelopmentLimitTime; }
                set { _DevelopmentLimitTime = value; }
            }
            private System.DateTime _EffectiveTime;
            public System.DateTime EffectiveTime
            {
                get { return _EffectiveTime; }
                set { _EffectiveTime = value; }
            }
            private System.Decimal _MarketingManagementFee;
            public System.Decimal MarketingManagementFee
            {
                get { return _MarketingManagementFee; }
                set { _MarketingManagementFee = value; }
            }
            private System.Decimal _BidPrice;
            public System.Decimal BidPrice
            {
                get { return _BidPrice; }
                set { _BidPrice = value; }
            }
            private string _DeliveryCode;
            public string DeliveryCode
            {
                get { return _DeliveryCode; }
                set { _DeliveryCode = value; }
            }
            private string _DeliveryName;
            public string DeliveryName
            {
                get { return _DeliveryName; }
                set { _DeliveryName = value; }
            }
            private string _AgreeAdjuestType;
            public string AgreeAdjuestType
            {
                get { return _AgreeAdjuestType; }
                set { _AgreeAdjuestType = value; }
            }
            private string _ChangeContent;
            public string ChangeContent
            {
                get { return _ChangeContent; }
                set { _ChangeContent = value; }
            }
            private string _Status;
            public string Status
            {
                get { return _Status; }
                set { _Status = value; }
            }
            private System.Decimal _DeliveryPrice;
            public System.Decimal DeliveryPrice
            {
                get { return _DeliveryPrice; }
                set { _DeliveryPrice = value; }
            }
            private System.Decimal _BasePrice;
            public System.Decimal BasePrice
            {
                get { return _BasePrice; }
                set { _BasePrice = value; }
            }
            private string _CategoryCommodityName;
            public string CategoryCommodityName
            {
                get { return _CategoryCommodityName; }
                set { _CategoryCommodityName = value; }
            }
            private string _CategorySystemName;
            public string CategorySystemName
            {
                get { return _CategorySystemName; }
                set { _CategorySystemName = value; }
            }
            private string _CategoryCommName;
            public string CategoryCommName
            {
                get { return _CategoryCommName; }
                set { _CategoryCommName = value; }
            }
            private string _CategorySpec;
            public string CategorySpec
            {
                get { return _CategorySpec; }
                set { _CategorySpec = value; }
            }
            private string _Formulation;
            public string Formulation
            {
                get { return _Formulation; }
                set { _Formulation = value; }
            }
            private string _BusinessModel;
            public string BusinessModel
            {
                get { return _BusinessModel; }
                set { _BusinessModel = value; }
            }

        }


        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.Int),
                     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;
                    }
                }
            }

        }

        public bool UpdateAgreement_YNSHigh_AuthorizeById(Model model)
        {

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

                     ";
            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;
                    }
                }
            }

        }

        public DataTable GetDataByAgreement_YNSHigh_Authorize(Model model, int pageNo, int pageSize, ref int iRecordCount)
        {
            List<SqlParameter> parameters = new List<SqlParameter>();
            StringBuilder sqlWhere = new StringBuilder();
            if (!string.IsNullOrEmpty(model.AYA_Code.ToString()))
            {
                sqlWhere.Append(" AND AYA_Code=@AYA_Code");
                parameters.Add(new SqlParameter("@AYA_Code", SqlDbType.NVarChar, 255) { SqlValue = model.AYA_Code });
            }
            if (!string.IsNullOrEmpty(model.AYHA_Code.ToString()))
            {
                sqlWhere.Append(" AND AYHA_Code=@AYHA_Code");
                parameters.Add(new SqlParameter("@AYHA_Code", SqlDbType.NVarChar, 255) { SqlValue = model.AYHA_Code });
            }
            if (!string.IsNullOrEmpty(model.Ctg_ID.ToString()))
            {
                sqlWhere.Append(" AND Ctg_ID=@Ctg_ID");
                parameters.Add(new SqlParameter("@Ctg_ID", SqlDbType.NVarChar, 255) { SqlValue = model.Ctg_ID });
            }
            if (!string.IsNullOrEmpty(model.HospitalCode.ToString()))
            {
                sqlWhere.Append(" AND HospitalCode=@HospitalCode");
                parameters.Add(new SqlParameter("@HospitalCode", SqlDbType.NVarChar, 255) { SqlValue = model.HospitalCode });
            }
            if (!string.IsNullOrEmpty(model.HospitalName.ToString()))
            {
                sqlWhere.Append(" AND HospitalName=@HospitalName");
                parameters.Add(new SqlParameter("@HospitalName", SqlDbType.NVarChar, 255) { SqlValue = model.HospitalName });
            }
            if (!string.IsNullOrEmpty(model.HospitalGrad.ToString()))
            {
                sqlWhere.Append(" AND HospitalGrad=@HospitalGrad");
                parameters.Add(new SqlParameter("@HospitalGrad", SqlDbType.NVarChar, 255) { SqlValue = model.HospitalGrad });
            }
            if (!string.IsNullOrEmpty(model.HospitalRegionID.ToString()))
            {
                sqlWhere.Append(" AND HospitalRegionID=@HospitalRegionID");
                parameters.Add(new SqlParameter("@HospitalRegionID", SqlDbType.NVarChar, 255) { SqlValue = model.HospitalRegionID });
            }
            if (!string.IsNullOrEmpty(model.DevelopmentLimitTime.ToString()))
            {
                sqlWhere.Append(" AND DevelopmentLimitTime=@DevelopmentLimitTime");
                parameters.Add(new SqlParameter("@DevelopmentLimitTime", SqlDbType.NVarChar, 255) { SqlValue = model.DevelopmentLimitTime });
            }
            if (!string.IsNullOrEmpty(model.EffectiveTime.ToString()))
            {
                sqlWhere.Append(" AND EffectiveTime=@EffectiveTime");
                parameters.Add(new SqlParameter("@EffectiveTime", SqlDbType.NVarChar, 255) { SqlValue = model.EffectiveTime });
            }
            if (!string.IsNullOrEmpty(model.MarketingManagementFee.ToString()))
            {
                sqlWhere.Append(" AND MarketingManagementFee=@MarketingManagementFee");
                parameters.Add(new SqlParameter("@MarketingManagementFee", SqlDbType.NVarChar, 255) { SqlValue = model.MarketingManagementFee });
            }
            if (!string.IsNullOrEmpty(model.BidPrice.ToString()))
            {
                sqlWhere.Append(" AND BidPrice=@BidPrice");
                parameters.Add(new SqlParameter("@BidPrice", SqlDbType.NVarChar, 255) { SqlValue = model.BidPrice });
            }
            if (!string.IsNullOrEmpty(model.DeliveryCode.ToString()))
            {
                sqlWhere.Append(" AND DeliveryCode=@DeliveryCode");
                parameters.Add(new SqlParameter("@DeliveryCode", SqlDbType.NVarChar, 255) { SqlValue = model.DeliveryCode });
            }
            if (!string.IsNullOrEmpty(model.DeliveryName.ToString()))
            {
                sqlWhere.Append(" AND DeliveryName=@DeliveryName");
                parameters.Add(new SqlParameter("@DeliveryName", SqlDbType.NVarChar, 255) { SqlValue = model.DeliveryName });
            }
            if (!string.IsNullOrEmpty(model.AgreeAdjuestType.ToString()))
            {
                sqlWhere.Append(" AND AgreeAdjuestType=@AgreeAdjuestType");
                parameters.Add(new SqlParameter("@AgreeAdjuestType", SqlDbType.NVarChar, 255) { SqlValue = model.AgreeAdjuestType });
            }
            if (!string.IsNullOrEmpty(model.ChangeContent.ToString()))
            {
                sqlWhere.Append(" AND ChangeContent=@ChangeContent");
                parameters.Add(new SqlParameter("@ChangeContent", SqlDbType.NVarChar, 255) { SqlValue = model.ChangeContent });
            }
            if (!string.IsNullOrEmpty(model.Status.ToString()))
            {
                sqlWhere.Append(" AND Status=@Status");
                parameters.Add(new SqlParameter("@Status", SqlDbType.NVarChar, 255) { SqlValue = model.Status });
            }
            if (!string.IsNullOrEmpty(model.DeliveryPrice.ToString()))
            {
                sqlWhere.Append(" AND DeliveryPrice=@DeliveryPrice");
                parameters.Add(new SqlParameter("@DeliveryPrice", SqlDbType.NVarChar, 255) { SqlValue = model.DeliveryPrice });
            }
            if (!string.IsNullOrEmpty(model.BasePrice.ToString()))
            {
                sqlWhere.Append(" AND BasePrice=@BasePrice");
                parameters.Add(new SqlParameter("@BasePrice", SqlDbType.NVarChar, 255) { SqlValue = model.BasePrice });
            }
            if (!string.IsNullOrEmpty(model.CategoryCommodityName.ToString()))
            {
                sqlWhere.Append(" AND CategoryCommodityName=@CategoryCommodityName");
                parameters.Add(new SqlParameter("@CategoryCommodityName", SqlDbType.NVarChar, 255) { SqlValue = model.CategoryCommodityName });
            }
            if (!string.IsNullOrEmpty(model.CategorySystemName.ToString()))
            {
                sqlWhere.Append(" AND CategorySystemName=@CategorySystemName");
                parameters.Add(new SqlParameter("@CategorySystemName", SqlDbType.NVarChar, 255) { SqlValue = model.CategorySystemName });
            }
            if (!string.IsNullOrEmpty(model.CategoryCommName.ToString()))
            {
                sqlWhere.Append(" AND CategoryCommName=@CategoryCommName");
                parameters.Add(new SqlParameter("@CategoryCommName", SqlDbType.NVarChar, 255) { SqlValue = model.CategoryCommName });
            }
            if (!string.IsNullOrEmpty(model.CategorySpec.ToString()))
            {
                sqlWhere.Append(" AND CategorySpec=@CategorySpec");
                parameters.Add(new SqlParameter("@CategorySpec", SqlDbType.NVarChar, 255) { SqlValue = model.CategorySpec });
            }
            if (!string.IsNullOrEmpty(model.Formulation.ToString()))
            {
                sqlWhere.Append(" AND Formulation=@Formulation");
                parameters.Add(new SqlParameter("@Formulation", SqlDbType.NVarChar, 255) { SqlValue = model.Formulation });
            }
            if (!string.IsNullOrEmpty(model.BusinessModel.ToString()))
            {
                sqlWhere.Append(" AND BusinessModel=@BusinessModel");
                parameters.Add(new SqlParameter("@BusinessModel", SqlDbType.NVarChar, 255) { SqlValue = model.BusinessModel });
            }
            string strSql = string.Format(@"
WITH temp AS ( SELECT rn =  ROW_NUMBER() OVER (ORDER BY AYA_Code  desc), *FROM  Agreement_YNSHigh_Authorize WHERE 1=1 {0} )
SELECT *,rc=(select count(1) from temp) FROM temp WHERE rn BETWEEN {1} AND {2}

                     ", sqlWhere.ToString(), (pageNo - 1) * pageSize   1, pageNo * pageSize);


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

        public bool DeleteAgreement_YNSHigh_Authorize(string AYA_Code)
   {
        List<SqlParameter> parameters = new List<SqlParameter>();
                    string strSql = string.Format(@"
DELETE Agreement_YNSHigh_Authorize WHERE AYA_Code=AYA_Code

                     ";
     int rowAffect =SqlHelper.Query(strSql, parameters.ToArray()).ToInt();;
      return rowAffect > 0 ? true : false;
      }

        protected void btnExcel_Click(object sender, System.EventArgs e)
        {
            int intPageNo = 1;
            int intPageSize = 65535;
            int recordCount = 0;
            DataTable dt = GetUnAuthorizeAgreePassedDT( Model model intPageNo, intPageSize, out recordCount); 
     string strFileName = "导出Excel"   System.DateTime.Now.ToString(" yyyyMMddHHmmss");
        ExcelUtility excelUtil = new ExcelUtility(this, strFileName);
            List<ExcelHeader> headerS = new List<ExcelHeader>() { 
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.文本, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.文本, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.文本, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.文本, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.文本, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.文本, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.文本, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.日期, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.日期, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.文本, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.文本, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.文本, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.文本, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.文本, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.文本, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.文本, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.文本, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.文本, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.文本, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.文本, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.文本, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.文本, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.文本, Width = 15 },
           new ExcelHeader() { Name = "字段名称自行补全", DataType = EnumColumnDataType.文本, Width = 15 },
          };
            excelUtil.CreateHeader(headerS);
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    List<string> dataVals = new List<string>() { 
                            dr[" AYA_Code"].ToString()  
                            dr[" AYHA_Code"].ToString()  
                            dr[" Ctg_ID"].ToString()  
                            dr[" HospitalCode"].ToString()  
                            dr[" HospitalName"].ToString()  
                            dr[" HospitalGrad"].ToString()  
                            dr[" HospitalRegionID"].ToString()  
                            dr[" DevelopmentLimitTime"].ToString()  
                            dr[" EffectiveTime"].ToString()  
                            dr[" MarketingManagementFee"].ToString()  
                            dr[" BidPrice"].ToString()  
                            dr[" DeliveryCode"].ToString()  
                            dr[" DeliveryName"].ToString()  
                            dr[" AgreeAdjuestType"].ToString()  
                            dr[" ChangeContent"].ToString()  
                            dr[" Status"].ToString()  
                            dr[" DeliveryPrice"].ToString()  
                            dr[" BasePrice"].ToString()  
                            dr[" CategoryCommodityName"].ToString()  
                            dr[" CategorySystemName"].ToString()  
                            dr[" CategoryCommName"].ToString()  
                            dr[" CategorySpec"].ToString()  
                            dr[" Formulation"].ToString()  
                            dr[" BusinessModel"].ToString()  
          };       
                    excelUtil.CreateItemRow(dataVals);
                }
            }
            excelUtil.Export();
            }

1、新建App_Code,加个八个文件夹(DataBase、DBEntity、DBInterface),插足已有个别多个公文(CDbBaseSqlServer.cs、CDbHelper、IDbBase.cs)至DataBase。

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

 

 

图片 25

 

 

 

2、张开自动生成工具(本身本人用C 写的)。

 

图片 26

 

 

3、从PowerDesigner中抽取News表的字段音讯。

 

图片 27

 

 

4、填入DBBuildCode工具,点击“生成”开关,在工具目录生成2个公文(CNewsInfo.cs、CNews.cs)。注:表结构中剧情能够依靠于ultraedit来拍卖。

 

图片 28

 

 

5、把转换的2个文件(CNewsInfo.cs、CNews.cs)分别新增增加至DBEntity、DBInterface文件夹,发掘数据库操作的代码都曾经更改。

 

图片 29

 

 

6、设置Web.config中数据库连接串等消息。

 

<?xml version="1.0"?>
<!--
  有关如何配置 ASP.NET 应用程序的详细信息,请访问
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
    <system.web>
        <compilation debug="true" targetFramework="4.0"/>
    </system.web>
    <appSettings>
        <add key="DatabasePre" value=""/>
        <add key="mssql" value="1"/>
    </appSettings>
    <connectionStrings>
        <add name="Conn" connectionString="server=local;database=news;User Id=sa;pwd=sa;"/>
    </connectionStrings>
</configuration>

 

四、完结前台C#操作代码。

 

在NewsList.aspx.cs、NewsEdit.aspx.cs实现对应的控件响应操作代码。

珍视代码如下:

 

 private void InitDataGrid()
    {
        DataTable dt = new DataTable();
        if (this.txtSearch.Text != "")
        {
            dt = oNews.GetInfoForSearch(this.txtSearch.Text.Trim());
        }
        else
            dt = oNews.GetInfo();

        for (int i = 0; i < dt.Rows.Count; i  )
        {
            string sFlagRecomTemp = "";
            //推荐标记
            string sFlagRecom = dt.Rows[i]["FlagRecom"].ToString();
            {
                if (sFlagRecom == "0")
                {
                    sFlagRecomTemp = "否";
                }
                if (sFlagRecom == "1")
                {
                    sFlagRecomTemp = "是";
                }
            }
            dt.Rows[i]["FlagRecom"] = sFlagRecomTemp;
        }
        int cup = Convert.ToInt32(this.lbCurrentPage.Text);
        PagedDataSource ps = new PagedDataSource();
        ps.DataSource = dt.DefaultView;
        ps.AllowPaging = true;
        ps.PageSize = 24;
        ps.CurrentPageIndex = cup - 1;
        this.lbPage.Text = ps.PageCount.ToString();

        this.ddlPage.Items.Clear();
        for (int i = 1; i < ps.PageCount   1; i  )
        {
            ListItem li = new ListItem(i.ToString(), i.ToString());
            this.ddlPage.Items.Add(i.ToString());
        }
        this.LinkUp.Enabled = true;
        this.LinkDown.Enabled = true;
        this.ddlPage.SelectedValue = cup.ToString();
        if (Convert.ToInt16(this.lbCurrentPage.Text) < 2)
        {
            this.LinkFirst.Enabled = false;
            this.LinkUp.Enabled = false;
        }
        else
        {
            this.LinkFirst.Enabled = true;
            this.LinkUp.Enabled = true;
        }
        if (Convert.ToInt16(this.lbCurrentPage.Text) >= Convert.ToInt16(this.lbPage.Text))
        {
            this.LinkDown.Enabled = false;
            this.LinkLast.Enabled = false;
        }
        else
        {
            this.LinkDown.Enabled = true;
            this.LinkLast.Enabled = true;
        }

        this.dgList.DataSource = ps;
        this.dgList.DataBind();

        if (dt.Rows.Count < 1)
        {
            this.currentPage.Style.Add("display", "none");
            this.currentPageError.Style.Add("display", "");
        }
        else
        {
            this.currentPage.Style.Add("display", "");
            this.currentPageError.Style.Add("display", "none");
        }
    }

 private void InitNewsEdit()
    {
        int iId = 0;
        string sEdit = "";
        if (Request.Params["edit"] != null)
        {
            sEdit = Request.Params["edit"].ToString().ToLower();
            ViewState["flagedit"] = sEdit;
        }
        if (Request.Params["id"] != null)
        {
            iId = Convert.ToInt32(Request.Params["id"].ToString());
            ViewState["id"] = iId;
        }
        switch (sEdit)
        {
            case "add":
                {
                    this.lbTitle.Text = "添加新闻";
                    sFlagMsg = "fail";
                }
                break;
            case "edit":
                {
                    this.lbTitle.Text = "修改新闻";
                    sFlagMsg = "ok";

                    CNewsInfo oNewsInfo = new CNewsInfo();
                    oNewsInfo = oNews.GetInfo(iId);

                    int iSid = 0;
                    iSid = oNewsInfo.Nid;

                    this.txtTitle.Text = oNewsInfo.Title;
                    this.txtCreator.Text = oNewsInfo.Creator;
                    this.ddlFlagRecom.SelectedValue = oNewsInfo.FlagRecom;
                    this.txtContent.Text = oNewsInfo.Content;
                }
                break;
            default:
                break;
        }
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        int iId = 0;
        iId = CTypeConverter.StrToInt(ViewState["id"].ToString());

        string sTitle = "";
        string sCreator = "";
        string sContent = "";
        int iHits = 0;
        string sFlagRecom = "";

        sTitle = this.txtTitle.Text.Trim();
        sCreator = this.txtCreator.Text.Trim();
        sContent = this.txtContent.Text.Trim();
        sFlagRecom = this.ddlFlagRecom.SelectedValue;

        string sFlagEdit = ViewState["flagedit"].ToString();
        switch (sFlagEdit)
        {
            case "add":
                {
                    CNewsInfo oNewsInfo = new CNewsInfo();
                    oNewsInfo.Title = sTitle;
                    oNewsInfo.Creator = sCreator;
                    oNewsInfo.Content = sContent;
                    oNewsInfo.Hits = iHits;
                    oNewsInfo.FlagRecom = sFlagRecom;

                    oNews.Insert(oNewsInfo);
                    Response.Redirect("SystemInfo.aspx?msgname="   Server.UrlEncode("新闻添加成功!")   "&backpage=NewsEdit.aspx?edit=add&backname="   Server.UrlEncode("继续添加新闻"));
                }
                break;
            case "edit":
                {
                    CNewsInfo oNewsInfo = new CNewsInfo();
                    oNewsInfo = oNews.GetInfo(iId);

                    oNewsInfo.Title = sTitle;
                    oNewsInfo.Creator = sCreator;
                    oNewsInfo.Content = sContent;
                    oNewsInfo.FlagRecom = sFlagRecom;

                    oNews.Update(iId, oNewsInfo);
                    Response.Redirect("SystemInfo.aspx?msgname="   Server.UrlEncode("新闻修改成功!")   "&backpage=NewsList.aspx&backname="   Server.UrlEncode("返回新闻列表"));
                }
                break;
            default:
                break;
        }
    }

 

五、运行NewsList.aspx效果图。

  有呈现、查询、增添、修改、删除、分页作用。

图片 30

 PS:原型是那样,能够依靠各个网址的品格去定制效果。源码。

 

本文由星彩网app下载发布于计算机编程,转载请注明出处:Delete以至导出Excel的点子,自用建设中型小型型网

TAG标签: 星彩网app下载
Ctrl+D 将本页面保存为书签,全面了解最新资讯,方便快捷。