본문 바로가기

   
Programming/ASP.NET(4.0)

ASP.NET 캐쉬를 사용한 게시판

반응형

ASP.NET 캐쉬를 사용한 게시판

게시판 캐싱

1. 속도를 빠르게..

2. DB 서버의 부담을 적게

데이타 베이스를 매번 조회 하지 않기 때문에 속도 향상

캐시 사용용도 : 사용횟수가 엄청나게 많거나, 비용이 엄청나게 많이 들거나. 할때사용

web.config

<?xml version="1.0"?>

<!--

  ASP.NET 응용 프로그램을 구성하는 방법에 대한 자세한 내용을 보려면

  http://go.microsoft.com/fwlink/?LinkId=169433 을 방문하십시오.

  -->

<configuration>

  <connectionStrings>

    <add name="conStr" connectionString="server=localhost;database=ASPNET;uid=sa;pwd=zangna1" providerName="System.Data.SqlClient"/>

  </connectionStrings>

  <system.web>

    <compilation debug="true" targetFramework="4.0"/>

    <httpRuntime requestValidationMode="2.0"/>

    <pages theme="basic"/>

  </system.web>

  <system.webServer>

    <defaultDocument>

      <files>

        <add value="Board.aspx"/>

      </files>

    </defaultDocument>

  </system.webServer>

</configuration>

 

Add.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Board.master" AutoEventWireup="true" CodeFile="Add.aspx.cs" Inherits="Add" ValidateRequest="false" %>

 

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">

       </asp:Content>

 

<asp:Content ID="Content2" runat="server"

       contentplaceholderid="ContentPlaceHolder1">

       <table class="table" style="width:600px;">

             <tr>

                    <td align="center" bgcolor="Silver" width="150">

                           이름</td>

                    <td width="450">

                           &nbsp;<asp:TextBox ID="TextBoxName" runat="server" CssClass="txt" Width="100px"></asp:TextBox>

                           &nbsp;</td>

             </tr>

             <tr>

                    <td align="center" bgcolor="Silver" width="150">

                           이메일</td>

                    <td width="450">

                           &nbsp;<asp:TextBox ID="TextBoxEmail" runat="server" CssClass="txt" Width="250px"></asp:TextBox>

                           &nbsp;</td>

             </tr>

             <tr>

                    <td align="center" bgcolor="Silver" width="150">

                           제목</td>

                    <td width="450">

                           &nbsp;<asp:TextBox ID="TextBoxSubject" runat="server" CssClass="txt" Width="95%"></asp:TextBox>

                           &nbsp;</td>

             </tr>

             <tr>

                    <td align="center" bgcolor="Silver" width="150">

                           내용</td>

                    <td width="450">

                           &nbsp;<asp:TextBox ID="TextBoxContent" runat="server" CssClass="txt" Height="150px"

                                 TextMode="MultiLine" Width="95%"></asp:TextBox>

                           &nbsp;</td>

             </tr>

             <tr>

                    <td align="center" bgcolor="Silver" width="150">

                           태그적용</td>

                    <td width="450">

                           &nbsp;<asp:CheckBox ID="CheckBoxTag" runat="server" Text="HTML 태그 적용함" />

                           &nbsp;</td>

             </tr>

             <tr>

                    <td align="center" bgcolor="Silver" width="150">

                           암호</td>

                    <td width="450">

                           &nbsp;<asp:TextBox ID="TextBoxPwd" runat="server" CssClass="txt" TextMode="Password"

                                 Width="100px"></asp:TextBox>

                           &nbsp;</td>

             </tr>

       </table>

       <div style="text-align:center;margin:10px;">

             <asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/images/list.gif"

                    onclick="ImageButton1_Click" ValidationGroup="list" />

&nbsp;<asp:ImageButton ID="ImageButton2" runat="server" ImageUrl="~/images/write.gif"

                    onclick="ImageButton2_Click" />

             <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"

                    ControlToValidate="TextBoxName" Display="None" ErrorMessage="이름을 입력하세요."

                    SetFocusOnError="True"></asp:RequiredFieldValidator>

             <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"

                    ControlToValidate="TextBoxSubject" Display="None" ErrorMessage="제목을 입력하세요."

                    SetFocusOnError="True"></asp:RequiredFieldValidator>

             <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"

                    ControlToValidate="TextBoxContent" Display="None" ErrorMessage="내용을 입력하세요."

                    SetFocusOnError="True"></asp:RequiredFieldValidator>

             <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server"

                    ControlToValidate="TextBoxPwd" Display="None" ErrorMessage="암호를 입력하세요."

                    SetFocusOnError="True"></asp:RequiredFieldValidator>

             <asp:ValidationSummary ID="ValidationSummary1" runat="server"

                    ShowMessageBox="True" ShowSummary="False" />

       </div>

</asp:Content>

 

Add.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

 

using System.Data;

using System.Data.SqlClient;

using System.Configuration;

 

public partial class Add : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

 

    }

       protected void ImageButton1_Click(object sender, ImageClickEventArgs e)

       {

             //List

             Response.Redirect("List.aspx");

       }

       protected void ImageButton2_Click(object sender, ImageClickEventArgs e)

       {

             //Write

             SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);

 

             SqlCommand cmd = new SqlCommand();

             cmd.Connection = con;

             cmd.CommandText = "insert into Board (name, email, subject, content, tag, pwd, userIP) values (@name, @email, @subject, @content, @tag, @pwd, @userIP)";

 

             //매개변수

             cmd.Parameters.Add("@name", SqlDbType.NVarChar, 20);

             cmd.Parameters.Add("@email", SqlDbType.VarChar, 50);

             cmd.Parameters.Add("@subject", SqlDbType.NVarChar, 100);

             cmd.Parameters.Add("@content", SqlDbType.NVarChar, 3000);

             cmd.Parameters.Add("@tag", SqlDbType.Char, 1);

             cmd.Parameters.Add("@pwd", SqlDbType.VarChar, 20);

             cmd.Parameters.Add("@userIP", SqlDbType.VarChar, 15);

 

             //

             cmd.Parameters["@name"].Value = TextBoxName.Text;

             cmd.Parameters["@email"].Value = TextBoxEmail.Text;

             cmd.Parameters["@subject"].Value = TextBoxSubject.Text;

             cmd.Parameters["@content"].Value = TextBoxContent.Text;

             cmd.Parameters["@tag"].Value = CheckBoxTag.Checked ? "y" : "n";

             cmd.Parameters["@pwd"].Value = TextBoxPwd.Text;

             cmd.Parameters["@userIP"].Value = Request.UserHostAddress;

 

             con.Open();

             cmd.ExecuteNonQuery();

             con.Close();

 

             string script = @"<script type='text/javascript'>

                                              alert('글쓰기 완료!!');

                                              location.href = 'List.aspx';

                                          </script>";

             this.ClientScript.RegisterClientScriptBlock(this.GetType(), "add", script);

 

 

 

 

             //제어가 이곳까지 왔다는것은..

             //기존에 Cache["ds"]와 실제 DB의 게시물 데이터가 다르다.

             // Cache["ds"] : 20  !=  DB : 21

             //기존 캐시의 ds를 폐기하고.. 21건짜리의 ds를 다시 생성

             SqlDataAdapter adapter = new SqlDataAdapter("SELECT [seq], [name], [subject], [readCount], [regDate], [email] FROM [Board] ORDER BY [seq] DESC", ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);

             DataSet ds = new DataSet();

 

             adapter.Fill(ds, "Board");

 

             //데이터 캐시 처리 - 덮어쓰기(20 -> 21)

             //새로운 데이터가 올바르게 반영..

             Cache.Insert("ds", ds);

 

       }

}

 

Del.aspx.

<%@ Page Title="" Language="C#" MasterPageFile="~/Board.master" AutoEventWireup="true" CodeFile="Del.aspx.cs" Inherits="Del" %>

 

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">

</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

       <table class="table" style="width:300px;" align="center">

             <tr>

                    <td align="center" bgcolor="Silver" width="150">

                           암호</td>

                    <td width="150">

                           &nbsp;<asp:TextBox ID="TextBoxPwd" runat="server" CssClass="txt" Width="100px" TextMode="Password"></asp:TextBox>

                           &nbsp;</td>

             </tr>

       </table>

       <div style="text-align:center;margin:10px;">

             <asp:ImageButton ID="ImageButton1" runat="server"

                    ImageUrl="~/images/back.gif" />

&nbsp;<asp:ImageButton ID="ImageButton2" runat="server"

                    ImageUrl="~/images/delete.gif" onclick="ImageButton2_Click" />

&nbsp;</div>

</asp:Content>

 

 

 

Del.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

 

using System.Data;

using System.Data.SqlClient;

using System.Configuration;

 

public partial class Del : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

 

    }

       protected void ImageButton2_Click(object sender, ImageClickEventArgs e)

       {

             //삭제하기

             //1. 암호가 일치?

             //2. 삭제 or 취소

             SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);

 

             SqlCommand cmd = new SqlCommand();

             cmd.Connection = con;

             cmd.CommandText = "select count(*) from Board where seq=@seq and pwd=@pwd";

 

             cmd.Parameters.Add("@seq", SqlDbType.Int);

             cmd.Parameters.Add("@pwd", SqlDbType.VarChar, 20);

 

             cmd.Parameters["@seq"].Value = Request.QueryString["seq"];

             cmd.Parameters["@pwd"].Value = TextBoxPwd.Text;

 

             con.Open();

             int result = (int)cmd.ExecuteScalar();

 

 

             string script = "";

 

             if (result == 1)

             {

                    //암호가 일치하기 때문에.. 게시물 Delete

                    cmd.CommandText = @"delete from Board

                                              where seq=@seq";

 

                    cmd.ExecuteNonQuery();//delete

 

                    script = @"<script type='text/javascript'>

                                        alert('삭제 완료!!');

                                        location.href='List.aspx';

                                    </script>";

             }

             else

             {

                    script = @"<script type='text/javascript'>

                                        alert('암호가 일치하지 않습니다!!');

                                    </script>";

             }

 

             con.Close();

 

             this.ClientScript.RegisterClientScriptBlock(this.GetType(), "edit", script);

 

 

 

             SqlDataAdapter adapter = new SqlDataAdapter("SELECT [seq], [name], [subject], [readCount], [regDate], [email] FROM [Board] ORDER BY [seq] DESC", ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);

             DataSet ds = new DataSet();

 

             adapter.Fill(ds, "Board");

 

             //데이터 캐시 처리 - 덮어쓰기(20 -> 21)

             //새로운 데이터가 올바르게 반영..

             Cache.Insert("ds", ds);

       }

}

 

Edit.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Board.master" AutoEventWireup="true" CodeFile="Edit.aspx.cs" Inherits="Edit" ValidateRequest="false" %>

 

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">

</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

       <table class="table" style="width:600px;">

             <tr>

                    <td align="center" bgcolor="Silver" width="150">

                           이름</td>

                    <td width="450">

                           &nbsp;<asp:TextBox ID="TextBoxName" runat="server" CssClass="txt" Width="100px"></asp:TextBox>

                           &nbsp;</td>

             </tr>

             <tr>

                    <td align="center" bgcolor="Silver" width="150">

                           이메일</td>

                    <td width="450">

                           &nbsp;<asp:TextBox ID="TextBoxEmail" runat="server" CssClass="txt" Width="250px"></asp:TextBox>

                           &nbsp;</td>

             </tr>

             <tr>

                    <td align="center" bgcolor="Silver" width="150">

                           제목</td>

                    <td width="450">

                           &nbsp;<asp:TextBox ID="TextBoxSubject" runat="server" CssClass="txt" Width="95%"></asp:TextBox>

                           &nbsp;</td>

             </tr>

             <tr>

                    <td align="center" bgcolor="Silver" width="150">

                           내용</td>

                    <td width="450">

                           &nbsp;<asp:TextBox ID="TextBoxContent" runat="server" CssClass="txt" Height="150px"

                                 TextMode="MultiLine" Width="95%"></asp:TextBox>

                           &nbsp;</td>

             </tr>

             <tr>

                    <td align="center" bgcolor="Silver" width="150">

                           태그적용</td>

                    <td width="450">

                           &nbsp;<asp:CheckBox ID="CheckBoxTag" runat="server" Text="HTML 태그 적용함" />

                           &nbsp;</td>

             </tr>

             <tr>

                    <td align="center" bgcolor="Silver" width="150">

                           암호</td>

                    <td width="450">

                           &nbsp;<asp:TextBox ID="TextBoxPwd" runat="server" CssClass="txt" TextMode="Password"

                                 Width="100px"></asp:TextBox>

                           &nbsp;</td>

             </tr>

       </table>

       <div style="text-align:center;margin:10px;">

             <asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/images/back.gif"

                    onclick="ImageButton1_Click" ValidationGroup="list" Width="39px" />

&nbsp;<asp:ImageButton ID="ImageButton2" runat="server" ImageUrl="~/images/modify.gif"

                    onclick="ImageButton2_Click" />

             <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"

                    ControlToValidate="TextBoxName" Display="None" ErrorMessage="이름을 입력하세요."

                    SetFocusOnError="True"></asp:RequiredFieldValidator>

             <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"

                    ControlToValidate="TextBoxSubject" Display="None" ErrorMessage="제목을 입력하세요."

                    SetFocusOnError="True"></asp:RequiredFieldValidator>

             <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"

                    ControlToValidate="TextBoxContent" Display="None" ErrorMessage="내용을 입력하세요."

                    SetFocusOnError="True"></asp:RequiredFieldValidator>

             <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server"

                    ControlToValidate="TextBoxPwd" Display="None" ErrorMessage="암호를 입력하세요."

                    SetFocusOnError="True"></asp:RequiredFieldValidator>

             <asp:ValidationSummary ID="ValidationSummary1" runat="server"

                    ShowMessageBox="True" ShowSummary="False" />

       </div>

</asp:Content>

 

 

 

Edit.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

 

using System.Data;

using System.Data.SqlClient;

using System.Configuration;

 

public partial class Edit : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

             if (!IsPostBack)

             {

                    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);

 

                    SqlCommand cmd = new SqlCommand();

                    cmd.Connection = con;

                    cmd.CommandText = "select * from Board where seq=@seq";

 

                    cmd.Parameters.Add("@seq", SqlDbType.Int);

                    cmd.Parameters["@seq"].Value = Request.QueryString["seq"];

 

                    con.Open();

 

                    SqlDataReader reader = cmd.ExecuteReader();

 

                    if (reader.Read())

                    {

                           //출력

                           TextBoxName.Text = reader["name"].ToString();

                           TextBoxEmail.Text = reader["email"].ToString();

                           TextBoxSubject.Text = reader["subject"].ToString();

                           //글내용

                           TextBoxContent.Text = reader["content"].ToString();

                           CheckBoxTag.Checked = reader["tag"].ToString() == "y" ? true : false;

                    }

 

                    reader.Close();

                    con.Close();

             }

    }

       protected void ImageButton1_Click(object sender, ImageClickEventArgs e)

       {

 

       }

       protected void ImageButton2_Click(object sender, ImageClickEventArgs e)

       {

             //수정하기

             //1. 암호가 일치?

             //2. 수정 or 취소

             SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);

 

             SqlCommand cmd = new SqlCommand();

             cmd.Connection = con;

             cmd.CommandText = "select count(*) from Board where seq=@seq and pwd=@pwd";

 

             cmd.Parameters.Add("@seq", SqlDbType.Int);

             cmd.Parameters.Add("@pwd", SqlDbType.VarChar, 20);

 

             cmd.Parameters["@seq"].Value = Request.QueryString["seq"];

             cmd.Parameters["@pwd"].Value = TextBoxPwd.Text;

 

             con.Open();

             int result = (int)cmd.ExecuteScalar();

            

 

             string script = "";

 

             if (result == 1)

             {

                    //암호가 일치하기 때문에.. 게시물 Update

                    cmd.CommandText = @"update Board set

                                                     name=@name,

                                                     email=@email,

                                                     subject=@subject,

                                                     content=@content,

                                                     tag=@tag,

                                                     userIP=@userIP,

                                                     regDate=getdate()

                                              where seq=@seq";

 

                    //매개변수

                    cmd.Parameters.Add("@name", SqlDbType.NVarChar, 20);

                    cmd.Parameters.Add("@email", SqlDbType.VarChar, 50);

                    cmd.Parameters.Add("@subject", SqlDbType.NVarChar, 100);

                    cmd.Parameters.Add("@content", SqlDbType.NVarChar, 3000);

                    cmd.Parameters.Add("@tag", SqlDbType.Char, 1);

                    cmd.Parameters.Add("@userIP", SqlDbType.VarChar, 15);

 

                    //

                    cmd.Parameters["@name"].Value = TextBoxName.Text;

                    cmd.Parameters["@email"].Value = TextBoxEmail.Text;

                    cmd.Parameters["@subject"].Value = TextBoxSubject.Text;

                    cmd.Parameters["@content"].Value = TextBoxContent.Text;

                    cmd.Parameters["@tag"].Value = CheckBoxTag.Checked ? "y" : "n";

                    cmd.Parameters["@userIP"].Value = Request.UserHostAddress;

 

                    cmd.ExecuteNonQuery();//update

 

                    script = @"<script type='text/javascript'>

                                        alert('수정 완료!!');

                                        location.href='List.aspx';

                                    </script>";

             }

             else

             {

                    script = @"<script type='text/javascript'>

                                        alert('암호가 일치하지 않습니다!!');

                                    </script>";

             }

 

             con.Close();

 

             this.ClientScript.RegisterClientScriptBlock(this.GetType(), "edit", script);

 

 

             SqlDataAdapter adapter = new SqlDataAdapter("SELECT [seq], [name], [subject], [readCount], [regDate], [email] FROM [Board] ORDER BY [seq] DESC", ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);

             DataSet ds = new DataSet();

 

             adapter.Fill(ds, "Board");

 

             //데이터 캐시 처리 - 덮어쓰기(20 -> 21)

             //새로운 데이터가 올바르게 반영..

             Cache.Insert("ds", ds);

       }

}

 

List.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Board.master" AutoEventWireup="true" CodeFile="List.aspx.cs" Inherits="List" Trace="true" %>

 

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">

</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

       <asp:GridView ID="GridView1" runat="server" AllowPaging="True"

             AutoGenerateColumns="False" CssClass="table" DataKeyNames="seq" onrowdatabound="GridView1_RowDataBound"

             Width="600px">

             <Columns>

                    <asp:BoundField DataField="seq" HeaderText="번호" InsertVisible="False"

                           ReadOnly="True" SortExpression="seq">

                    <ItemStyle HorizontalAlign="Center" Width="50px" />

                    </asp:BoundField>

                    <asp:HyperLinkField DataNavigateUrlFields="seq"

                           DataNavigateUrlFormatString="View.aspx?seq={0}" DataTextField="subject"

                           HeaderText="제목">

                    <ItemStyle Width="340px" />

                    </asp:HyperLinkField>

                    <asp:BoundField DataField="name" HeaderText="이름" SortExpression="name">

                    <ItemStyle HorizontalAlign="Center" Width="80px" />

                    </asp:BoundField>

                    <asp:BoundField DataField="regDate" DataFormatString="{0:yyyy-MM-dd}"

                           HeaderText="날짜" SortExpression="regDate">

                    <ItemStyle HorizontalAlign="Center" Width="80px" />

                    </asp:BoundField>

                    <asp:BoundField DataField="readCount" HeaderText="읽음"

                           SortExpression="readCount">

                    <ItemStyle HorizontalAlign="Center" Width="50px" />

                    </asp:BoundField>

             </Columns>

             <HeaderStyle BorderStyle="Solid" BorderWidth="1px" />

       </asp:GridView>

      

       <div style="text-align:center;margin:10px;">

             &nbsp;<asp:ImageButton ID="ImageButton1" runat="server"

                    ImageUrl="~/images/write.gif" onclick="ImageButton1_Click" />

       </div>

</asp:Content>

 

 

 

List.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

 

using System.Data;

using System.Data.SqlClient;

using System.Configuration;

 

public partial class List : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

             if (!IsPostBack)

             {

                    //조회수 증가용 쿠키 할당

                    Response.Cookies["read"].Value = "n";

 

                    DataSet ds = null;

 

                    //이전에 누군가 ds를 캐시에 넣어놨다면..?

                    if (Cache["ds"] == null)

                    {//1

                           //데이터 바인딩

                           SqlDataAdapter adapter = new SqlDataAdapter("SELECT [seq], [name], [subject], [readCount], [regDate], [email] FROM [Board] ORDER BY [seq] DESC", ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);

                           ds = new DataSet();

 

                           adapter.Fill(ds, "Board");

 

                           //데이터 캐시 처리

                           Cache.Insert("ds", ds);

                    }

                    else

                    {//99

                           ds = Cache["ds"] as DataSet;

                    }

 

                    GridView1.DataSource = ds.Tables["Board"];

                    GridView1.DataBind();

             }

    }

       protected void ImageButton1_Click(object sender, ImageClickEventArgs e)

       {

             //글쓰기

             Response.Redirect("Add.aspx");

       }

       protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

       {

             if (e.Row.RowType == DataControlRowType.DataRow)

             {

                    //1. 제목이 길면.. 자르기

                    //e.Row <- 한행(GridViewRow) x 5

                    HyperLink subject = e.Row.Cells[1].Controls[0] as HyperLink;

 

                    if (subject.Text.Length > 20)

                    {

                           subject.Text = subject.Text.Substring(0, 20) + "...";

                    }

 

 

                    //2. 글쓴지 일정시간이내면.. new.gif 표시

                    // 30분이내

                    //Response.Write(e.Row.Cells[3].Text + "<br />");

 

                    //현재 바인딩되거나 바인딩된 데이터에 접근하는 방법

                    //A. 출력된 결과값에 접근하는 방법(Cells을 사용)

                    //Response.Write(e.Row.Cells[2].Text);

 

                    //B. (출력과 상관없이)바인딩되는 원본에 접근하는 방법

                    // 조건 : 데이터원본에는 있어야함(select의 대상)

                    //데이터원본(seq, subject, name, regDate, readCount, email)

                    DataRowView row = e.Row.DataItem as DataRowView;

                    //Response.Write(row["email"].ToString());

                    //Response.Write(row["regDate"].ToString());

                    DateTime regDate = (DateTime)row["regDate"];

 

                    TimeSpan gap = DateTime.Now - regDate;

 

                    if (gap.TotalMinutes <= 30)

                    {

                           //30이내에 쓴글

                           //e.Row.Cells[1]

                           LiteralControl img = new LiteralControl("<img src='images/new.gif' alt='새글' style='margin-left:5px;' />");

                           e.Row.Cells[1].Controls.Add(img);

                           //e.Row.Cells[1].Controls.AddAt(0, img);

                    }

             }

       }

}

 

View.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Board.master" AutoEventWireup="true" CodeFile="View.aspx.cs" Inherits="View" %>

 

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">

</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

       <table class="table" style="width:600px;">

             <tr>

                    <td align="center" bgcolor="Silver" width="150">

                           이름</td>

                    <td width="450">

                           &nbsp;<asp:Label ID="LabelName" runat="server"></asp:Label>

                           &nbsp;</td>

             </tr>

             <tr>

                    <td align="center" bgcolor="Silver" width="150">

                           이메일</td>

                    <td width="450">

                           &nbsp;<asp:Label ID="LabelEmail" runat="server"></asp:Label>

                           &nbsp;</td>

             </tr>

             <tr>

                    <td align="center" bgcolor="Silver" width="150">

                           제목</td>

                    <td width="450">

                           &nbsp;<asp:Label ID="LabelSubject" runat="server"></asp:Label>

                           &nbsp;</td>

             </tr>

             <tr>

                    <td align="center" bgcolor="Silver" width="150">

                           내용</td>

                    <td width="450" style="padding:10px;">

                           <asp:Label ID="LabelContent" runat="server"></asp:Label>

                    </td>

             </tr>

             <tr>

                    <td align="center" bgcolor="Silver" width="150">

                           번호</td>

                    <td width="450">

                           &nbsp;<asp:Label ID="LabelSeq" runat="server"></asp:Label>

                           &nbsp;</td>

             </tr>

             <tr>

                    <td align="center" bgcolor="Silver" width="150">

                           읽음</td>

                    <td width="450">

                           &nbsp;<asp:Label ID="LabelReadCount" runat="server"></asp:Label>

                           &nbsp;</td>

             </tr>

             <tr>

                    <td align="center" bgcolor="Silver" width="150">

                           날짜</td>

                    <td width="450">

                           &nbsp;<asp:Label ID="LabelRegDate" runat="server"></asp:Label>

                           &nbsp;</td>

             </tr>

       </table>

       <div style="text-align:center;margin:10px;">

             <asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/images/list.gif"

                    onclick="ImageButton1_Click" ValidationGroup="list" />

&nbsp;<asp:ImageButton ID="ImageButton3" runat="server" ImageUrl="~/images/modify.gif"

                    onclick="ImageButton3_Click" />

&nbsp;<asp:ImageButton ID="ImageButton4" runat="server" ImageUrl="~/images/delete.gif"

                    onclick="ImageButton4_Click" />

       </div>

</asp:Content>

 

 

 

View.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

 

using System.Data;

using System.Data.SqlClient;

using System.Configuration;

 

public partial class View : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

             if (!IsPostBack)

             {

                    //seq의 상세보기

                    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);

 

                    SqlCommand cmd = new SqlCommand();

                    cmd.Connection = con;

                    cmd.CommandText = "update Board set readCount = readCount + 1 where seq=@seq;";

 

                    cmd.Parameters.Add("@seq", SqlDbType.Int);

                    cmd.Parameters["@seq"].Value = Request.QueryString["seq"];

 

                    con.Open();

 

                    //쿠키 확인 작업

                    if (Request.Cookies["read"] == null || Request.Cookies["read"].Value == "n")

                    {

                           cmd.ExecuteNonQuery();//조회수 증가

                           Response.Cookies["read"].Value = "y";

                    }

 

                    cmd.CommandText = "select * from Board where seq=@seq";

                   

                    SqlDataReader reader = cmd.ExecuteReader();

                    if (reader.Read())

                    {

                           //출력

                           LabelName.Text = string.Format("{0} [{1}]", reader["name"].ToString(), reader["userIP"].ToString());

                           LabelEmail.Text = reader["email"].ToString();

                           LabelSubject.Text = reader["subject"].ToString();

 

                           //글내용

                           string content = reader["content"].ToString();

 

                           //태그적용 안함 처리 ( < -> &lt;)

                           if (reader["tag"].ToString() == "n")

                           {

                                 content = Server.HtmlEncode(content);

                           }

 

                           //<script> 무조건 적용안함

                           content = content.Replace("<script", "&lt;script").Replace("</script>", "&lt/script>");

 

                           //엔터값처리  -> <br />

                           content = content.Replace("\r\n", "<br />");

 

                           LabelContent.Text = content;

 

 

                           LabelSeq.Text = reader["seq"].ToString();

                           LabelReadCount.Text = reader["readCount"].ToString();

                           LabelRegDate.Text = reader["regDate"].ToString();

                    }

 

                    reader.Close();

                    con.Close();

             }

    }

       protected void ImageButton1_Click(object sender, ImageClickEventArgs e)

       {

             //List

             Response.Redirect("List.aspx");

       }

       protected void ImageButton3_Click(object sender, ImageClickEventArgs e)

       {

             //수정 Edit.aspx?seq=5

             Response.Redirect("Edit.aspx?seq=" + Request.QueryString["seq"]);

       }

       protected void ImageButton4_Click(object sender, ImageClickEventArgs e)

       {

             //삭제 Del.aspx?seq=5

             Response.Redirect("Del.aspx?seq=" + Request.QueryString["seq"]);

       }

}

 


반응형