简体   繁体   English

在ASP.NET Web应用程序中重用代码和变量(C#初学者)

[英]re-using code and variables in asp.net webapp (c# beginner)

Ive created a webapp in VS2012. Ive在VS2012中创建了一个webapp。 The purpose of the app is to update data that is shown on different displays throuhout the company. 该应用程序的目的是更新整个公司范围内不同显示器上显示的数据。 Each display has it's own data to be shown. 每个显示都有自己的数据要显示。 All data is stored in a single SQL table and has a specific column to know what data has to be shown on what display. 所有数据都存储在单个SQL表中,并具有特定的列以了解必须在什么显示上显示哪些数据。 The webapp consist op different aspx pages to update the data on the different screens, so I have UpdateScreen1.aspx, UpdateScreen2.aspx, ... The core of these pages is about 90% the same. 该webapp由不同的aspx页面组成,以更新不同屏幕上的数据,因此我具有UpdateScreen1.aspx,UpdateScreen2.aspx等。这些页面的核心大约有90%相同。 They start with a SQL connection, get a list of data for this specific screen (so, the SQL statement is the same except for the WHERE clause), and of course the create/update/delete functions for the data. 它们从SQL连接开始,获取此特定屏幕的数据列表(因此,除了WHERE子句外,SQL语句是相同的),当然还有数据的创建/更新/删除功能。 If I need to change for example my select statement I have to update all the pages. 例如,如果需要更改我的select语句,则必须更新所有页面。 Also the SQL connection is specified in each page seperately. 另外,在每个页面中分别指定了SQL连接。 I was wondering if I could make this a bit more performant, by re-using for example the select statement (defining it once, and adding only the where clause in the specific page), the sql connection, ... However I can't seem to find where to put them. 我想知道是否可以通过重用例如select语句(定义一次,并仅在特定页面中添加where子句),sql连接来使它性能更高,但是我可以做到这一点。似乎找不到放置它们的位置。 I've already tried global.asax, a seperate class file, ... but nothing seems to work (name xxxxx does not exists in current context...). 我已经尝试过一个单独的类文件global.asax,但是似乎没有任何作用(名称xxxxx在当前上下文中不存在...)。

Here some of my code: UpdateScreen1.aspx: 这里是我的一些代码:UpdateScreen1.aspx:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace RSS_Aankondigingen.UpdateScreen1
{
    public partial class Update_Announcement : System.Web.UI.Page
    {
        private SqlConnection sqlConn = new SqlConnection("Data Source=server;Initial Catalog=db;Persist Security Info=True;User ID=user;Password=password");

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                gvBind();
            }
        }

        protected void gvBind()
        {
            sqlConn.Open();
            string a = sqlSelect;

            SqlCommand sqlCmd = new SqlCommand("SELECT ID, Title,  CONCAT(CONVERT(char(16), Date, 103),CONVERT(char(5), Date, 108)) AS Date, Recurrent FROM tblAnnouncements WHERE Channel = 'SH_ANN' ORDER BY Date", sqlConn);
            SqlDataAdapter sqlDA = new SqlDataAdapter(sqlCmd);
            DataSet ds = new DataSet();
            sqlDA.Fill(ds);
            sqlConn.Close();
            if (ds.Tables[0].Rows.Count > 0)
            {
                GridAnnouncements.DataSource = ds;
                GridAnnouncements.DataBind();
            }
            else
            {
                ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
                GridAnnouncements.DataSource = ds;
                GridAnnouncements.DataBind();
                int colCount = GridAnnouncements.Rows[0].Cells.Count;
                GridAnnouncements.Rows[0].Cells.Clear();
                GridAnnouncements.Rows[0].Cells.Add(new TableCell());
                GridAnnouncements.Rows[0].Cells[0].ColumnSpan = colCount;
                GridAnnouncements.Rows[0].Cells[0].Text = "Geen gegevens gevonden...";
            }

        }
    }
}

Any help would be very much appreciated. 任何帮助将不胜感激。

Michiel. 米歇尔。

EDIT: uncommented sqlConn initiatlization (it was for testing) 编辑:未注释的sqlConn初始化(用于测试)

If you're using ADO, then you could use Stored Procedures with parameters, then your SqlCommand becomes the name of the stored procedure (change CommandType to StoredProcedure) and just add parameters to the command. 如果使用的是ADO,则可以将存储过程与参数一起使用,然后SqlCommand成为存储过程的名称(将CommandType更改为StoredProcedure),然后将参数添加到命令中。

However, also look into more modern options like Entity Framework and you would use Linq against a collection of Announcement objects. 但是,还应研究诸如Entity Framework之类的更现代的选项,您将对一些Announcement对象使用Linq。

to answer your Question, create another class, and use it to wrap the sql code. 回答您的问题,创建另一个类,然后使用它包装sql代码。 (This is all from memory, so if theres mistakes, apologies.) (这全部来自内存,因此,如果有错误,我们深表歉意。)

ie

namespace RSS_Aankondigingen

public class DatbaseHelper
{

public DataSet GetDataSet(string selectOn)
{
        sqlConn.Open();

string sqlQuery = string.format("SELECT ID, Title,  CONCAT(CONVERT(char(16), Date, 103),CONVERT(char(5), Date, 108)) AS Date, Recurrent FROM tblAnnouncements WHERE Channel = '{0}' ORDER BY Date", selectOn);


        SqlCommand sqlCmd = new SqlCommand(sqlQuery, sqlConn);
        SqlDataAdapter sqlDA = new SqlDataAdapter(sqlCmd);
        DataSet ds = new DataSet();
        sqlDA.Fill(ds);
        sqlConn.Close();

        return ds;
}
}

then in your code, when you need to do a select; 然后在您的代码中,当您需要进行选择时;

replace all the code that is above with. 替换上面的所有代码。 (Where SH_ANN is whatever you wish to select on for that page.) (其中SH_ANN是您希望在该页面上选择的内容。)

DataSet ds = GetDataSet("SH_ANN");

This is not an optimal solution, but as a first step, it will let you isolate the SQL code into a single class, to make maintenance easier. 这不是最佳解决方案,但第一步,它将使您可以将SQL代码隔离到单个类中,从而使维护更加容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM