2012-12-06 4 views
1

나는 사용자를 admin의 "A"또는 표준 사용자의 "U"로 분류하는 사용자 이름, 암호 및 사용자 식별자가있는 webform을 가지고 있습니다.데이터베이스에 쓸 수 없음

양식을 제출하면 데이터베이스에 기록해야하며 현재 다른 사용자가있는 Visual Studio에서 설정했습니다.

웹 양식을 테스트 할 때 "NullReferenceException이 사용자 코드에 의해 처리되지 않았습니다.", "개체 참조가 개체의 인스턴스로 설정되지 않았습니다."라는 오류 메시지가 나타납니다. 내 웹 양식 페이지에서이 코드 줄을 가리 킵니다.

clsDataLayer.SaveUser(Server.MapPath("PayrollSystem_DB.mdb"), Session["txtUserName"].ToString(), Session["txtPassword"].ToString(), Session["drpdwnlstSecurityLevel"].ToString()); 

이 코드에는 어떤 문제가 있습니까?

"txtPassword"라는 텍스트 상자, "txtPassword"라는 텍스트 상자 및 "drpdwnlstSecurityLevel"이라는 레이블이 붙은 U 또는 A 옵션이있는 드롭 다운 목록이 있습니다.

당신은 그것이 내 clsDataLayer.cs SaveUser 방법에 전송하도록되어있는 정보를 제출하면 :

public static bool SaveUser(string Database, string UserName, string UserPassword, string SecurityLevel) 
    { 

     bool userSaved; 

     try 
     { 
      // Define SQLConnClass 
      OleDbConnection conn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;" + 
                 "Data Source=" + Database); 
      conn.Open(); 
      OleDbCommand command = conn.CreateCommand(); 
      string strSQL; 

      // this insert data to user table 
      strSQL = "Insert into tblUserLogin " + 
        "(UserName, UserPassword, SecurityLevel) values ('" + 
        UserName + "', '" + UserPassword + "', " + SecurityLevel + "')"; 

      // this gives a command to get or set values 
      command.CommandType = CommandType.Text; 
      command.CommandText = strSQL; 

      // This sql statements brings out the affacted rows 
      command.ExecuteNonQuery(); 

      // closes the connection 
      conn.Close(); 
      userSaved = true; 
     } 

     catch (Exception ex) 
     { 
      userSaved = false; 
     } 

     return userSaved; 
    } 

당신이 어떤 레코드를 생성하지 않습니다 내 웹 양식에 새 사용자를 만들려고, 그것은 내가 언급 한 오류 만 발행합니다.

가 여기에있다이 질문을 기준으로 그 내 모든 코드 :

파일 clsDataLayer.cs :

//이 기능은 사용자 데이터 공공 정적 부울 SaveUser (문자열 데이터베이스, 문자열 사용자 이름을 저장, UserPassword를 문자열, 문자열의 SecurityLevel) {

bool userSaved; 

try 
{ 
    // Define SQLConnClass 
    OleDbConnection conn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;" + 
               "Data Source=" + Database); 
    conn.Open(); 
    OleDbCommand command = conn.CreateCommand(); 
    string strSQL; 

    // this insert data to user table 
    strSQL = "Insert into tblUserLogin " + 
      "(UserName, UserPassword, SecurityLevel) values ('" + 
      UserName + "', '" + UserPassword + "', " + SecurityLevel + "')"; 

    // this gives a command to get or set values 
    command.CommandType = CommandType.Text; 
    command.CommandText = strSQL; 

    // This sql statements brings out the affacted rows 
    command.ExecuteNonQuery(); 

    // closes the connection 
    conn.Close(); 
    userSaved = true; 
} 

catch (Exception ex) 
{ 
    userSaved = false; 
} 

return userSaved; 

}

파일 F rmManageUsers.aspx.cs :

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 

public partial class frmManageUsers : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 

    } 
    protected void btnAddUser_Click(object sender, EventArgs e) 
    { 
     string userName, userPassword; 


     if (txtUserName.Text == "" || txtUserName.Text == null) 
     { 
      lblUserError.Text = ("User Name may not be empty"); 
      lblUserError.ForeColor = System.Drawing.Color.Red; 
      return; 
     } 
     else 

      userName = (txtUserName.Text); 


     if (txtPassword.Text == "" || txtPassword.Text == null) 
     { 
      lblUserError.Text = ("Password may not be empty"); 
      lblUserError.ForeColor = System.Drawing.Color.Red; 
      return; 
     } 
     else 
     { 
      userPassword = (txtPassword.Text); 
     } 

     // clsDataLayer.SaveUser(Server.MapPath("PayrollSystem_DB.mdb"), Session["txtUserName"].ToString(), Session["txtPassword"].ToString(), Session["drpdwnlstSecurityLevel"].ToString()); 
     clsDataLayer.SaveUser(
    Server.MapPath("PayrollSystem_DB.mdb"), 
    txtUserName.Text, 
    txtPassword.Text, 
    drpdwnlstSecurityLevel.SelectedValue 
    ); 
     Server.Transfer("frmManageUsers.aspx");   
    } 
} 

파일 frmManageUsers.aspx :

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

<!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 id="Head1" runat="server"> 
    <title></title> 
</head> 
<body> 
    <form id="form1" runat="server"> 
    <div align="center"> 

     <a href="frmMain.aspx"> 
      <font color="black" size="2" style="text-align: center"><strong> 
      <font color="blue" face="Comic Sans MS" size="4">Cool</font> 
      <font color="#ff6600" face="Comic Sans MS" size="4">Biz</font> 
      <font face="Comic Sans MS" size="4"> <font color="#993366">Productions</font>, 
      Inc.</font></strong></font> 
     </a> 
     <br /> 
     <br /> 
     <asp:Label ID="Label1" runat="server" Text="Manage Users"></asp:Label> 
     <br /> 
     <asp:Label ID="Label2" runat="server" Text="User Name: "></asp:Label> 
     <asp:TextBox ID="txtUserName" runat="server"></asp:TextBox> 
     <br /> 
     <asp:Label ID="Label3" runat="server" Text="Password: "></asp:Label> 
     <asp:TextBox ID="txtPassword" runat="server"></asp:TextBox> 
     <br /> 
     <asp:Label ID="lblUserError" runat="server"></asp:Label> 
     <br /> 
     <asp:Label ID="Label4" runat="server" Text="Security Level: "></asp:Label> 
     <asp:DropDownList ID="drpdwnlstSecurityLevel" runat="server" 
      DataSourceID="SqlDataSource2" DataTextField="SecurityLevel" 
      DataValueField="SecurityLevel"> 
      <asp:ListItem></asp:ListItem> 
      <asp:ListItem></asp:ListItem> 
     </asp:DropDownList> 
     <asp:SqlDataSource ID="SqlDataSource2" runat="server" 
      ConnectionString="<%$ ConnectionStrings:PayrollSystem_DBConnectionString %>" 
      ProviderName="<%$ ConnectionStrings:PayrollSystem_DBConnectionString.ProviderName %>" 
      SelectCommand="SELECT [SecurityLevel] FROM [tblUserLogin]"> 
     </asp:SqlDataSource> 
     <br /> 
     <br /> 

     <asp:Button ID="btnAddUser" runat="server" onclick="btnAddUser_Click" 
      Text="Add User" /> 

     <br /> 
     <br /> 
     <asp:GridView ID="grdUserLogin" runat="server" AutoGenerateColumns="False" 
      DataSourceID="SqlDataSource1"> 
      <Columns> 
       <asp:BoundField DataField="UserID" HeaderText="UserID" InsertVisible="False" 
        SortExpression="UserID" /> 
       <asp:BoundField DataField="UserName" HeaderText="UserName" 
        SortExpression="UserName" /> 
       <asp:BoundField DataField="UserPassword" HeaderText="UserPassword" 
        SortExpression="UserPassword" /> 
       <asp:BoundField DataField="SecurityLevel" HeaderText="SecurityLevel" 
        SortExpression="SecurityLevel" /> 
      </Columns> 
     </asp:GridView> 
     <br /> 
     <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
      ConnectionString="<%$ ConnectionStrings:PayrollSystem_DBConnectionString %>" 
      InsertCommand="INSERT INTO [tblUserLogin] ([UserID], [UserName], [UserPassword], [SecurityLevel]) VALUES (?, ?, ?, ?)" 
      ProviderName="<%$ ConnectionStrings:PayrollSystem_DBConnectionString.ProviderName %>" 
      SelectCommand="SELECT * FROM [tblUserLogin]"> 
      <InsertParameters> 
       <asp:Parameter Name="UserID" Type="Int32" /> 
       <asp:Parameter Name="UserName" Type="String" /> 
       <asp:Parameter Name="UserPassword" Type="String" /> 
       <asp:Parameter Name="SecurityLevel" Type="String" /> 
      </InsertParameters> 
     </asp:SqlDataSource> 

    </div> 
    </form> 
</body> 
</html> 
+3

당신이 거기에 5 개의 다른 객체 참조를 가지고 반환하지 않습니다, 당신의 catch 블록에 어떻게 든 예외 메시지를 표시합니다. null 참조 오류를 던지는 사람이 될 수 있습니다. –

+0

데이터가 Session에 저장되는 위치를 표시하십시오. 문제가 있기 때문에 데이터가 없습니다. – zimdanen

+0

중단 점을 설정하고 단계별로 실행하여 어떤 항목이 null 참조인지 확인하십시오. –

답변

4

당신이 Session에 그 값을 저장하고 있습니까? 당신이 게시 코드가있는 경우 코드 숨김 직접 값을 액세스 할 수 있어야합니다 : 또한

clsDataLayer.SaveUser(
    Server.MapPath("PayrollSystem_DB.mdb"), 
    txtUserName.Text, 
    txtPassword.Text, 
    drpdwnlstSecurityLevel.SelectedValue 
    ); 

당신이 강하게avoid SQL Injection 오히려 연결 이상의 매개 변수를 사용하여 SQL을 사용하는 것이 좋습니다 :

strSQL = "Insert into tblUserLogin " + 
     "(UserName, UserPassword, SecurityLevel) " + 
     "values (@UserName, @UserPassword, @SecurityLevel)"; 
당신이 그것에있는 동안

은뿐만 아니라 다음과 같은 일을 수행

  • 는 랩 당신의 OleDbConnectionOleDbCommandusing에서 블록
  • false
+0

나는 snarky가되어서는 안되지만 D.Stanley는 정확하다. 나는 SQL injection을 탐지하고 그것을 수행하는 모든 웹 사이트에서 "제발 해킹 해주세요"라는 오버레이를 발견 할 수 있었으면 좋겠습니다. – n8wrl

+0

좋아, 나는 참조 할 모든 코드를 포함하도록 내 질문을 업데이트했습니다. 또한, 당신의 clsDataLayer 버전을 시도하고 지금은 제출 및 던져하지 않으며 오류가 있지만 데이터베이스에 쓰지 않습니다. 도와 줘서 고맙다. – Chaddly

+0

그냥 oleDbConnection 사용을 넣을 수 있습니까? OleDbCommand 사용; 페이지 상단에? 그게 당신의 제안 인 @D Stanley – Chaddly

관련 문제