Summary of the news publishing system for the first stage of the small project in the first class group of Asp.net

Source: Internet
Author: User

The first small system in soft Zhuo's class is actually the same in soft Zhuo's class as in other software classes. I didn't participate in the teacher's project as well ....

When it really started from 0, it was found at the beginning of the project that it was originally its own. net knowledge is really 0 .. I spent too little time on this .. ah .. at the beginning, we prepared various materials. The first is the three-tier architecture... orz, the most basic things I spent a day reading various online materials, and finally I saw more systematic knowledge in the last project of my Asp.net book .. I really want to vomit blood. online materials may be relatively direct, but they are not systematic .. then there is the code. The three-tier architecture understands a small part and the code can basically be changed. however, I tried to ask people in my group to draw databases, but LOL won't communicate with people on our side ,, the database I wrote is not flattering. It is really "simple "!!! So the WM team had to rebuild the database...
Simple but usable. My requirements are not high-_-... the code is written, starting from the underlying layer.

The data access layer (DAL, IDAL) is the first part. At the beginning, the helper class with Microsoft is not used .. therefore, the database connection part is really long and smelly, that is, to establish a connection string, and then create an SQL Server statement as a command object .. it's easy to use the helper class. At first, my code was like this:

# Region get all published news public static DataSet GetUserNewsListByUserID (string userID) {string connectionString = ConfigurationManager. connectionStrings ["PubsConnectionString"]. toString (); // ConfigurationManage using (SqlConnection dbConnection = new SqlConnection (connectionString) {dbConnection. open (); string queryString = "Select _ title, _ content, _ userName from dbo. news where _ userID = @ userID order by _ date DESC "; SqlCommand dbCommand = new SqlCommand (); dbCommand. connection = dbConnection; dbCommand. commandType = CommandType. text; dbCommand. commandText = queryString; // userID parameter SqlParameter dbParameter_userID = new SqlParameter (); dbParameter_userID.ParameterName = "@ userID"; dbParameter_userID.Value = userID; dbParameter_userID.DbType = DbType. stringFixedLength; dbCommand. parameters. add (dbParameter_userID); // run the SQL server command SqlDataAdapter dataAdapter = new SqlDataAdapter (dbCommand); DataSet ds = new DataSet (); dataAdapter. fill (ds); return ds ;}# endregion

 

But why? This is too troublesome ..

Later, I looked back at the instructor's courseware, and found the usage of the sqlhelper class ..

/// <Summary> /// based on the user ID, obtain the user's published news list /// </summary> /// <param name = "userID"> User ID </param> /// <returns> the user's published news List </returns> public List <NewsModel> GetUserNewsListByUserName (string userName) // The return type is very important, so you can use the object idea {// create a List of news objects <NewsModel> userNewsList = new List <NewsModel> (); // select dbo. in Table_News, this user has published the news Title, author, and release Date string SQL = "select top 10 NewsID, Title, UserName, Date from dbo. table_News where UserName = @ userName order by Date desc "; SqlParameter [] param = new SqlParameter [1] {// new SqlParameter (" @ userName "," @ password ", userName, password) // Note: This @ UserName is the database field, and the above @ userName is the intermediate variable new SqlParameter ("@ UserName", userName )}; sqlDataReader res = sqlhelper. executeReader (SQL, CommandType. text, param); // get the news object while (res. read () {// create a news object NewsModel news = new NewsModel (); // assign a value to the news object attribute // use the GetOrdinal () method of SqlDataReader to obtain the column number, the input parameter is the column name // extract the corresponding column from reader and assign it to the model. that's OK, haha news. newsID = res. getInt32 (res. getOrdinal ("NewsID"); news. title = res. getString (res. getOrdinal ("Title"); news. userName = res. getString (res. getOrdinal ("UserName"); news. date = res. getDateTime (res. getOrdinal ("Date"); // Add the news to userNewsList in the list. add (news);} return userNewsList ;}

 

At the beginning, I have not loaded the parameter to sqlparameter, but I still know how to use it. The specific operating mechanism is still unclear.

This is a key piece of code, and it is also a small hurdle I have encountered.

The next step is to write the BLL code in the business logic layer. Haha, if the DLL code is well written, I will use the return type such as DataSet (this advanced approach) at the beginning ), but I can see it in a blog that generic list is currently the most popular. dataSet is written in the past .. well, I don't know anyone yet. however, because c ++ is familiar with list, use generic. later I learned that the gridview is generally able to receive list-type articles. the entire project was basically successful, and it may be cool to connect to the gridview. It is cut food, but it is really embarrassing for me to explore this dish for so long.

To write this article, let's go back and talk about our three-tier architecture. After all, after a hard day of searching, the extracted summary is just a few words: the data access layer is mainly used to retrieve data from the database and store data. the key database access code is written here. then the business logic layer is responsible for expressing the business logic requested by the customer and accessing the database: That's too abstract .. self-thinking is: if the data obtained from the database still needs logic, it should be regarded as a passed parameter, which has this magical function, because for the database, he does not know who is going to fetch the data. only the business logic layer knows. As for the display layer, the design code of the display layer appears when you click the business effects that can be displayed in the view, I am also confused about this because it occupies the business logic layer. however, I did not understand the rebuttals on the Internet.

In addition to IDLL, DLL, IBLL, and IBLL, a factory is created.

namespace NewsPublish.Factory{    public static class DALFactory    {        public static IUserDAL CreateUserDAL()        {            return new UserDAL();        }        public static INewsDAL CreateNewsDAL()        {            return new NewsDAL();        }    }}

For example, in The BLL layer, we need to establish a DAL instance through the DAL factory in The BLL layer, for example, so that we can call the data in the dal layer in the bll layer:

The following sentence serves this purpose:

Namespace NewsPublish. BLL
{
Public class NewsBLL: INewsBLL
{

INewsDAL _ newsDAL = Factory. DALFactory. CreateNewsDAL (); // a DAL object is created before BLL is started to reference the DAL method.

The advantage of creating a factory is that an object is automatically generated, so we don't have to worry about how it is generated.

The following BLL layer factory will be referenced to generate objects in the Design Code of the display layer.

 

namespace NewsPublish.Factory{    public class BLLFactory    {        public static IUserBLL CreatUserBLL()        {            return new UserBLL();        }        public static INewsBLL CreateNewsBLL()        {            return new NewsBLL();        }    }}

After talking about this, I feel that the key code is almost done .. however, the display layer gridview is not ready yet. ah, the teacher showed me how to behave in class. This is the punishment for me. It is delayed until the day (subclass) as the day (parent class )..

The display layer is a good skill in the class to help:

First, let's take a look at the gridview:

A common gridview:

Then let's take a look at the properties of the front-end gridview and the code of the back-end gridview:

<Asp: gridView ID = "GridView1" runat = "server" AutoGenerateColumns = "False" Height = "599px" Width = "800px" OnSelectedIndexChanged = "GridView1_SelectedIndexChanged"> <Columns> <asp: hyperLinkField DataNavigateUrlFields = "NewsID" DataNavigateUrlFormatString = "~ /Newscontent. aspx? NewsID = {0} "DataTextField =" Title "HeaderText =" Title "NavigateUrl = "~ /Newscontent. aspx "/> <asp: BoundField HeaderText =" author "DataField =" UserName "/> <asp: BoundField HeaderText =" Release Date "DataField =" Date "/> <asp: boundField DataField = "NewsID" HeaderText = "NewsID" Visible = "False"/> </Columns> </asp: GridView>

 

The first is the first column, the column name is the Title, and then the data binding is the "Title" in the database "!! This is a hyperlink, and you need to input parameters, so you need? NewsID.

Then the second column is directly written on the DIV (not very clear, guess), the column name is the author, the bound data is "Date" in the database, and so on.

 

Let's see how the background code connects the gridview and BLL layers.

Public partial class WebForm2: System. web. UI. page {INewsBLL _ iBLL; protected void Page_Load (object sender, EventArgs e) {_ iBLL = BLLFactory. createNewsBLL (); // create a BLL object instance GridView1.DataSource = _ iBLL through The BLL interface. getAllNewsList (); // bind the data source. The return type of The BLL-layer function is List. gridView1.DataBind (); // call the binding, that is, the data that has entered this page will be bound, and the following message is displayed:} protected void GridView1_SelectedIndexChanged (object sender, EventArgs e ){}}

This is almost the same. The last one left is page Jump. A problem occurred during debugging and was used at the beginning:

Next, let's talk about page Jump:

 

That is, the previous published news page jumps to the following published news list page:

 

Next let's take a look at the redirection background code:

 

Protected void Button1_Click (object sender, EventArgs e) {string title = Txt_Title.Text.ToString (); string publisher = Txt_Publish.Text.ToString (); if (true) // judge if the publisher is not a user name, cannot be released. This function is not implemented for the moment {} string content = Txt_Content.Text.ToString (); DateTime date = DateTime. now; bool tmp = _ newsBLL. publishNews (title, date, publisher, content); // it is assumed that the publishing is successful for the moment, so Lima jumps to the published news page Session ["userName"] = publisher; Response. redirect ("personnel. aspx ");}

 

At the beginning, I added it directly in Response? And the parameter type, debugging failed, classmate LX later switched to the Session method, done.

Well, let's look at the receiver's background code:

public partial class personnel : System.Web.UI.Page    {        INewsBLL _newsBLL = NewsPublish.Factory.BLLFactory.CreateNewsBLL();        protected void Page_Load(object sender, EventArgs e)        {           // string userName = Request.QueryString["userName"].ToString();            string userName = Session["userName"].ToString();            GridView1.DataSource = _newsBLL.GetUserNewsListByUserName(userName);            GridView1.DataBind();                               }        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)        {            string userName = Request.QueryString["userName"].ToString();            //DataTable dt=new DataTable();            //dt=_newsBLL.GetUserNewsListByUserID(userName);            GridView1.DataSource = _newsBLL.GetUserNewsListByUserName(userName);            GridView1.DataBind();        }    }

It's hard to figure out the Response + Request at the beginning, and the debugging will be dizzy if it's not in the past. The binding here keeps up with the same content ..

The code for the entire project is almost like this, but the hateful teacher said that this is only the first stage of the demand;

What about the second stage and the third stage? Ah, my Acm time, my postgraduate entrance exam time, orz... but it must be followed up ,,

Although it takes a little time, it cannot be underestimated ....

Come on, come on, and muxi come on !!!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.