블로그 이미지
Magic_kit
study 관련자료를 한곳으로 자기 개발 목적으로 재태크 재무 관리 목적으로 일상생활의 팁을 공유 하기 위하여 블로그를 개설 하였습니다.

calendar

1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31

Category

Recent Post

Recent Comment

Archive

2009. 10. 13. 09:09 .Net Project/ASP.NET 3.5 Sp1
반응형
 FrmRequire FieldValidator.aspx




입력 확인 유효성 검사 컨트롤 
<%@ Page Language="C#" AutoEventWireup="true" 
                   CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
                           "
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>입력 확인 유효성 검사</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    아이디 : <asp:TextBox ID="txtUserID" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator ID="VarUserID" runat="server"
                ControlToValidate="txtUserID"
                ErrorMessage="아이디 입력하세요" Display="Dynamic"
                ValidationGroup="btnResult" ></asp:RequiredFieldValidator>
        <br />
   
    비밀번호 : <asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator ID="VarPassWord" runat="server"
                 ControlToValidate="txtPassword"
                 ErrorMessage="비밀번호 입력하세요" Display="Static"  
                 ValidationGroup="btnResult"></asp:RequiredFieldValidator>
        <br />
    <asp:Button ID="btnResult" runat="server" Text="확인"
    ValidationGroup="btnResult" />
    &nbsp;</div>
    </form>
</body>
</html> 


 FrmRequire FieldValidator.실행화면
 


1. 입력확인 유효성 검사 컨트롤
                  아이디 : 텍스트박스
                  암    호 : 텍스트박스 그리고 로그인버튼 디지인 하도록 한다.
 
2.  도구상자에서 RequireFieldValidator 2개 추가 하도록 한다. (VarUserID, VarPassWord)

3.  로그인 버튼 클릭하였을 경우 유효성 검사 컨트롤을 사용하고 싶을 때, 
               디자인 속성에 ValidationGroup="grpLogin" 각각 속성을 지정하여 주면 된다. 

4. [RequireFieldValidator] 묶고 "Display=Dynamic" "Display=Static" 속성 지정하여
               실행 공간의 차이를 보여주고 있다.
               고정된 공간에 에러메시지 출력해주고 싶을때는 Static 사용하하는 것이 좋다. 

5. RequireFieldValidator 컨트롤 ControlToValidate="txtUserID",
    ControlToValidate="txtPassWord"  속성 추가

6.  위의 내용을 확실하기 위해서 자바스크립트를 사용하여 유효성검사의 예를 해보겠습니다.
     - 위와 동일하게 디자인
     - var userID = document.getElementById("txtUserID"); 
     - fucction CheckLogin(userID.value == " ")
       {
         alert("아이디 입력하세요") ;
         userID.Focus() ;  userID.Select(); 
       }   


    

반응형
posted by Magic_kit
2009. 10. 12. 21:53 .Net Project/ASP.NET 3.5 Sp1
반응형
UploadUtil.cs 

using System;
using System.IO;

public class UploadUtil
{
 // HTTP GET을 사용하여 [WebGet] 특성을 추가합니다.
 [OperationContract]
 public void DoWork()
 {
  // 여기에 작업 구현을 추가합니다.
  return;
 }

 // 여기에 작업을 추가하고 해당 작업을 [OperationContract]로 표시합니다.

    public static string GetFilePath
                                (string strBaseDirTemp, string strFileNameTemp)
    {
     string strName = //순수파일명 : Test
     Path.GetFileNameWithoutExtension(strFileNameTemp); //[1] 순수 파일명만 반환
     string strExt =  // 확장자 : .txt
     Path.GetExtension(strFileNameTemp); //[2] 순수 확장자만 : . 포함
        bool blnExists = true;
        int i = 0;
        while (blnExists)
        {
            //[3] Path.Combine(경로, 파일명) = 경로 + 파일명
            if (File.Exists(Path.Combine(strBaseDirTemp, strFileNameTemp)))
            {
                strFileNameTemp =
                  strName + "(" + ++i + ")" + strExt; // Test(3).txt
            }
            else
            {
                blnExists = false;
            }
        }
        return strFileNameTemp;
    }
}


 UploadBiz.cs

 using System;
using System.Transactions;
using System.Data;
using System.Collections.Generic; //참조추가 : System.Transactions

public class UploadBiz
{
    //입력메서드
    public int WriteUpload(string name, string email, string title,
                                     string PostIp, string content
        , string password, string encoding, string homepage,
                                    string fileName, int fileSize)
    {
        //using 구문에 있는 여러개 메서드들을 트랜잭션으로 처리
        //첫번재 메서드로 처리한 후 두번째 메서드에서 에러가 발생하면,
        //첫번째 메서드로 롤백시킨다

        int result = 0;
        using(TransactionScope scope = new
                 TransactionScope(TransactionScopeOption.RequiresNew))
        {
          UploadDac ud = new UploadDac();

            result = ud.AddUpload(name, email, title, PostIp, content, password
                      ,encoding, homepage, fileName, fileSize);
           
            scope.Complete();                    
        }
            return result; //UI영역으로 반환
    }

    //출력 메서드
    public DataSet ListUpload()
    {
        return (new UploadDac()).GetUploads();
    }

    //출력된 결과값을 백업해주고 싶다
    //백업 매서드
    //public void BackupUpload()
    //{
    //    UploadDac ud = new UploadDac();
    //    ud.GetUploads().WriteXml("Backup.xml");
    //}

    //상세메서드
    public UploadEntity ViewUpload(int num)
    {
        UploadEntity entity = new UploadEntity();
        using (IDataReader dr = (new UploadDac()).GetUploadByNum(num))
        {
            while (dr.Read())
            {
                entity.Num = num;
                entity.Name = dr["Name"].ToString(); //문자열 인덱서
                entity.Email = dr[2].ToString(); //정수형 인덱서
                entity.Title = dr.GetString(3); //GEtXXX()메서드
                entity.PostDate = dr.GetDateTime(4);
                entity.PostIP = dr["PostIp"].ToString();
                entity.Content = dr[6].ToString();
                entity.Password = dr.GetString(7);
                entity.ReadCount = dr.GetInt32(8);
                entity.Encoding = dr.GetString(9);
               
                if (dr["Homepage"] != null)
                {
                    entity.Homepage = dr["Homepage"].ToString();
                }

                if (dr[11] != null)
                {
                    entity.ModifyDate = dr.GetDateTime(11);
                }

                if (dr[12] != null)
                {
                    entity.ModifyIP = dr["ModifyIP"].ToString();
                }

                if (dr[13] != null)
                {
                    entity.FileName = dr.GetString(13);
                }

                entity.FileSize = Convert.ToInt32(dr["FileSize"]);
                entity.DownCount = int.Parse(dr["DownCount"].ToString());
            }
        }

        return entity;
    }

    //수정 메서드
    public int ModifyUpload(UploadEntity entity)
    {
        UploadDac ud = new UploadDac();
        return ud.UpdateUpload(entity);
    }

    //삭제 메서드
    public int DeleteUpload(int num, string password)
    {
        return (new UploadDac()).DeleteUpload(num, password);       
    }

    //검색 메서드
    public List<UploadEntity> SearchUpload
                                         (string searchField, string searchQentityry)
    {
        List<UploadEntity> lst = new List<UploadEntity>(); //컬렉션
        UploadEntity entity = new UploadEntity(); //한개 레코드

        UploadDac ud = new UploadDac();
        using (IDataReader dr = ud.GetUploadByWord
                                           (searchField, searchQentityry))
        {
            while (dr.Read())
            {
                #region 레코드 가져오기
                entity.Num = Convert.ToInt32(dr["Num"]);
                entity.Name = dr["Name"].ToString(); //문자열 인덱서
                entity.Email = dr[2].ToString(); //정수형 인덱서
                entity.Title = dr.GetString(3); //GEtXXX()메서드
                entity.PostDate = dr.GetDateTime(4);
                entity.PostIP = dr["PostIp"].ToString();
                entity.Content = dr[6].ToString();
                entity.Password = dr.GetString(7);
                entity.ReadCount = dr.GetInt32(8);
                entity.Encoding = dr.GetString(9);
                if (dr["Homepage"] != null)
                {
                    entity.Homepage = dr["Homepage"].ToString();
                }

                if (dr[11] != null)
                {
                    entity.ModifyDate = dr.GetDateTime(11);
                }

                if (dr[12] != null)
                {
                    entity.ModifyIP = dr["ModifyIP"].ToString();
                }

                if (dr[13] != null)
                {
                    entity.FileName = dr.GetString(13);
                }

                entity.FileSize = Convert.ToInt32(dr["FileSize"]);
                entity.DownCount = int.Parse(dr["DownCount"].ToString());
                #endregion
               
                lst.Add(entity);
            }
        }
        return lst; //전체 담겨진 리스트제네릭클래스(레코드셋)을 반환
    }

    //다운 메서드
    public void UpdateDownCount(string fileName)
    {
        //Biz단에서 Dac단 호출
        //Biz단에서 TransactionScope
        //클래스 사용하여 묶어서 구현하는 것을 권장하여 사용
        using (TransactionScope scope = new TransactionScope
                                              (TransactionScopeOption.RequiresNew))
        {
            (new UploadDac()).UpdateDownCount(fileName);
            //(new UploadDac()).UpdateDownCount(num);

            scope.Complete();
        }
    }
}


 UploadDac.cs

 using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class UploadDac
{
    private string _ConnectionString; //연결문자열 보관
    //ConnectionString 보관하여 사용
    public UploadDac()
    {
        //Web.Config의 ConnectionString 을 딱 한번만 보관하여 사용....
        _ConnectionString =
                ConfigurationManager.ConnectionStrings
                                   ["ConnectionString"].ConnectionString;
    }

    //메서드 : 저장 프로시저만큼 ..
   
    public int AddUpload
     (string name, string email, string title, string PostIp, string content
       , string password, string encoding, string homepage, string fileName,
         int fileSize)
    {
        SqlConnection con = new SqlConnection(_ConnectionString);
       

        SqlCommand cmd = new SqlCommand("WriteUpload",con);
        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Parameters.AddWithValue("@name",name);
        cmd.Parameters.AddWithValue("@email",email);
        cmd.Parameters.AddWithValue("@title",title);
        cmd.Parameters.AddWithValue("@PostIp",PostIp);
        cmd.Parameters.AddWithValue("@content",content);
        cmd.Parameters.AddWithValue("@password",password);
        cmd.Parameters.AddWithValue("@encoding",encoding);
        cmd.Parameters.AddWithValue("@homepage",homepage);
        cmd.Parameters.AddWithValue("@fileName",fileName);
        cmd.Parameters.AddWithValue("@fileSize",fileSize);

        con.Open();
        int result = cmd.ExecuteNonQuery();

        con.Close();

        return result;       
    }

    public DataSet GetUploads()
    {
        SqlConnection conn = new SqlConnection(_ConnectionString);

        SqlCommand cmd = new SqlCommand("ListUpload" ,conn);
        cmd.CommandType= CommandType.StoredProcedure;

        SqlDataAdapter da = new SqlDataAdapter(cmd);
       
        DataSet ds = new DataSet();

        da.Fill(ds,"Upload");
        return ds;
      
    }

    //수정
    public int UpdateUpload(UploadEntity entity)
    {
        SqlConnection con = new SqlConnection(_ConnectionString);

        SqlCommand cmd = new SqlCommand("ModifyUpload", con);
        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Parameters.AddWithValue("@Name",entity.Name);
        cmd.Parameters.AddWithValue("@Email",entity.Email);
        cmd.Parameters.AddWithValue("@Title",entity.Title);
        cmd.Parameters.AddWithValue("@ModifyIP",entity.ModifyIP);
        cmd.Parameters.AddWithValue("@Content",entity.Content);
        cmd.Parameters.AddWithValue("@Encoding", entity.Encoding);
        cmd.Parameters.AddWithValue("@Homepage", entity.Homepage);
        cmd.Parameters.AddWithValue("@Password", entity.Password);
        cmd.Parameters.AddWithValue("@FileName", entity.FileName);
        cmd.Parameters.AddWithValue("@FileSize", entity.FileSize);
        cmd.Parameters.AddWithValue("@Num", entity.Num);

        con.Open();
        int result = cmd.ExecuteNonQuery();
        con.Close();

        return result;
    }

    //상세
    public SqlDataReader GetUploadByNum(int num)
    {
        SqlConnection  conn = new SqlConnection(_ConnectionString);

        SqlCommand cmd = new SqlCommand("ViewUpload",conn);

        cmd.Parameters.AddWithValue("@Num",num);

        SqlDataReader dr = cmd.ExecuteReader();

        return dr; //Close() =-> Using사용해서 Close 처리
               
    }

    //삭제
    public int DeleteUpload(int num, string password)
    {
        SqlConnection con = new SqlConnection(_ConnectionString);

        SqlCommand cmd = new SqlCommand("DeleteUpload", con);
       
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@Password", password);
        cmd.Parameters.AddWithValue("@Num", num);
       
      
        con.Open();
        int result = cmd.ExecuteNonQuery();

        con.Close();
         return result;
    }

    //검색
    public IDataReader GetUploadByWord
                                 (string searchField, string searchQuery)
    {
        SqlConnection conn = new SqlConnection(_ConnectionString);

        SqlCommand cmd = new SqlCommand("SearchUpload", conn);
        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Parameters.AddWithValue("@SearchField", searchField);
        cmd.Parameters.AddWithValue("@SearchQuery", searchQuery);

        SqlDataReader dr = cmd.ExecuteReader();
       
        return dr;      
      
    }

    //다운 증가
    public void UpdateDownCount(string fileName)
    {
        SqlConnection conn = new SqlConnection(_ConnectionString);
        SqlCommand cmd = new SqlCommand("IncreaseDownCountUpload", conn);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@fileName", fileName);
        conn.Open();
       
        cmd.ExecuteNonQuery();
        conn.Close();
   }
}


 UploadEntity.cs

using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;

[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class UploadEntity
{
      public int Num { get; set; }
      public string Name { get; set; }
      public string Email { get; set; }
      public string Title { get; set; }
      public DateTime PostDate { get; set; }
      public string PostIP { get; set; }
      public string Content { get; set; }
      public string Password { get; set; }
      public int ReadCount { get; set; }
      public string Encoding { get; set; }
      public string Homepage { get; set; }
      public DateTime ModifyDate { get; set; }
      public string ModifyIP { get; set; }
      public string FileName { get; set; }
      public int FileSize { get; set; }
      public int DownCount { get; set; }
}




반응형
posted by Magic_kit
2009. 10. 12. 21:39 .Net Project/ASP.NET 3.5 Sp1
반응형
Upload/Down.aspx 






 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Down.aspx.cs" Inherits="Upload_Down" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>다운로드</title>
</head>
<body>
    <form id="form1" runat="server">
    <h3>Down.aspx UI가 없는 페이지 </h3>
    <div>
     Down.aspx?FileName=??? 로 넘겨오는 파일명이 files 폴더에 있으면
      강제 다운로드 시켜주는 페이지
   
    </div>
    </form>
</body>
</html>


 Upload/Down.Cs

using System;
using System.IO;

public partial class Upload_Down : System.Web.UI.Page
{

    private string strFileName = String.Empty; //넘겨져온 파일명 저장 
    private string strBaseDir = String.Empty; //어디에 저장할 폴더명

    protected void Page_Load(object sender, EventArgs e)
    {
      strFileName = Request.QueryString["FileName"].ToString();
      strBaseDir = Server.MapPath(".") + @"\files";
     
      if (strFileName == null) //넘겨져온 파일명이 없다면
      {
          Response.End();
      }
      else
      {
          //강제 다운로드 :  아래 로직이 강제 다운로드 로직입니다
          UpdateDownCount(); //다운 카운트 증가
         
          Response.Clear(); //버퍼지우기
         
          Response.ContentType = "application/octet-stream";
         
          Response.AddHeader("Content-Disposition", "attachment;filename=" +
                      Server.UrlPathEncode(strFileName));
         
          Response.WriteFile(
              Path.Combine(strBaseDir, strFileName));

          Response.End(); //버퍼 지우고 종료
      }
    }
    private void UpdateDownCount()
    {   
        //UploadBiz ub = new UploadBiz();
        //ub.UpdateDownCount(Convert.ToInt32());
    }
}




반응형
posted by Magic_kit
2009. 10. 12. 21:35 .Net Project/ASP.NET 3.5 Sp1
반응형
 Upload/List.aspx



 <%@ Page Language="C#" AutoEventWireup="true"
         CodeFile="List.aspx.cs" Inherits="Upload_List" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
       "
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>자료실리스트 </title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <img src="images/가인.png" style="height: 163px; width: 173px" />
    <asp:GridView ID="ctlUploadList" runat="server"
        AutoGenerateColumns ="false" AllowPaging="true"
       
        PageSize="3">
        <Columns>
            <asp:BoundField DataField="Num" HeaderText="번호" />
            <asp:HyperLinkField DataTextField="Title" HeaderText="제목"
                DataNavigateUrlFormatString="View.aspx?Num={0}"
                DataNavigateUrlFields="Num" />
            <asp:TemplateField HeaderText="파일">
                <ItemTemplate>
                        <a href= 'files/<%# Eval("FileName") %>'>
                        <%# Eval("FileName") %>
                        </a>                    
                                           
                        <asp:HyperLink ID="HyperLink1" runat="server"  
                            NavigateUrl='<%# "~/Upload/files/" + Eval("FileName") %>' >
                            <%# Eval("FileName") %>
                        </asp:HyperLink>
                        
                    <asp:HyperLink ID="HyperLink2" runat="server" 
                     NavigateUrl='<%# "Down.aspx?FileName=" + Eval("FileName") %>'>
                      <img src="images/윤아.png" border="0" alt="다운로드"
                                                                width="30px" height="30px" />       
                      </asp:HyperLink>
                        
                      <%# FuncFileLink(Eval("FileName")) %>            
               
                </ItemTemplate>                      
            </asp:TemplateField>                        
        </Columns>  
    </asp:GridView>
    <asp:DropDownList ID="SearchField" runat="server">
        <asp:ListItem Value="Name">이름</asp:ListItem>
        <asp:ListItem Value="Title">제목</asp:ListItem>
        <asp:ListItem Value="Content">내용</asp:ListItem>
    </asp:DropDownList>
   
    <asp:TextBox ID="SearchQuery" runat="server"></asp:TextBox> <br />
    <asp:Button ID="btnSearch" runat="server" Text="검색" 
                           onclick="btnSearch_Click" /> &nbsp
    <asp:Button ID="btnWrite" runat="server" Text="글쓰기" 
                           onclick="btnWrite_Click" /> <br />
      </div>
    </form>
</body>
</html>


 Upload.List.Cs

using System;

public partial class Upload_List : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            Display();
        }
    }

    private void Display()
    {
        UploadBiz ub = new UploadBiz();
        this.ctlUploadList.DataSource = ub.ListUpload();
        this.ctlUploadList.DataBind();
      
    }
   
    /// <summary>
    /// 검색관련
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
   
protected void btnSearch_Click(object sender, EventArgs e)
    {
        Response.Redirect(
                String.Format(
                    "Search.aspx?SearchField={0}&SearchQuery={1}"
                    , SearchField.SelectedValue
                    , SearchQuery.Text));
    }

    /// <summary>
    /// 쓰기관련
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
   
protected void btnWrite_Click(object sender, EventArgs e)
    {
        Response.Redirect("Write.aspx");
    }

    //코드 비하인트 페이지에서 링크 만들기
    protected string FuncFileLink(object fileName)
    {
        string name = Convert.ToString(fileName);
        if (!String.IsNullOrEmpty(name))
        {
            return "<a href='Down.aspx?FileName=" + name + "'>다운</a>";
        }
        else
        {
            return "-"; //파일이 첨부되지 않았다면...
        }
    }
}



반응형
posted by Magic_kit