2010-12-02 4 views
0

사용자 아이디와 비밀번호를 가져 와서 로컬 서버에서 사용할 수있는 데이터베이스 목록을 표시하는 양식을 개발했습니다. 이제 하드 코딩 된 형식으로 처리했습니다. 이app.config 파일에 하드 코딩 된 값 제거

public void BindDBDropDown() 
{ 
    //Create the connection object 
    SqlConnection sConnection = new SqlConnection(
     ConfigurationSettings.AppSettings["ConnectionString"]); 

    //To Open the connection. 
    sConnection.Open(); 

    //Query to select the list of databases. 
    string selectDatabaseNames = 
     @"SELECT NAME FROM MASTER..SYSDATABASES"; 

    //Create the command object 
    SqlCommand sCommand = 
     new SqlCommand(selectDatabaseNames, sConnection); 

    try 
    { 
     //Create the data set 
     DataSet sDataset = new DataSet("master..sysdatabases"); 

     //Create the dataadapter object 
     SqlDataAdapter sDataAdapter = 
      new SqlDataAdapter(selectDatabaseNames, sConnection); 
     sDataAdapter.TableMappings.Add("Table", 
      "master..sysdatabases"); 

     //Fill the dataset 
     sDataAdapter.Fill(sDataset); 

     //Bind the database names in combobox 
     DataViewManager dsv = sDataset.DefaultViewManager; 

     //Provides the master mapping between the sourcr table 
     //and system.data.datatable 
     cmbDatabases.DataSource = 
      sDataset.Tables["master..sysdatabases"]; 
     cmbDatabases.DisplayMember = "NAME"; 
     cmbDatabases.ValueMember = ("NAME"); 
    } 
    catch(Exception ex) 
    { 
     //All the exceptions are handled and written in the EventLog. 
     EventLog logException = new EventLog("Application"); 
     logException.Source = "MFDBAnalyser"; 
     logException.WriteEntry(ex.Message); 
    } 
    finally 
    { 
     //If connection is not closed then close the connection 
     if(sConnection.State != ConnectionState.Closed) 
     { 
      sConnection.Close(); 
     } 
    } 
} 

/// <summary> 
///This function binds the names of all the tables with primary 
///keys in a dropdown cmbResults. 
/// </summary> 
public void GetPrimaryKeyTable() 
{ 
    //An instance of the connection string is created to manage 
    //the contents of the connection string. 
    var sqlConnection = new SqlConnectionStringBuilder(); 
    sqlConnection.DataSource = "192.168.10.3"; 
    sqlConnection.UserID = "gp"; 
    sqlConnection.Password = "gp"; 
    sqlConnection.InitialCatalog = 
     Convert.ToString(cmbDatabases.SelectedValue); 
    string connectionString = sqlConnection.ConnectionString; 

    SqlConnection sConnection = new SqlConnection(connectionString); 

    //To Open the connection. 
    sConnection.Open(); 

    //Query to select the table_names that have PRIMARY_KEYS. 
    string selectPrimaryKeys = @" 
     SELECT TABLE_NAME 
     FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
     WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' 
     AND  TABLE_NAME <> 'dtProperties' 
     ORDER BY TABLE_NAME"; 

    //Create the command object 
    SqlCommand sCommand = 
     new SqlCommand(selectPrimaryKeys, sConnection); 

    try 
    { 
     //Create the dataset 
     DataSet dsListOfPrimaryKeys = 
      new DataSet("INFORMATION_SCHEMA.TABLE_CONSTRAINTS"); 

     //Create the dataadapter object 
     SqlDataAdapter sDataAdapter = 
      new SqlDataAdapter(selectPrimaryKeys, sConnection); 

     //Provides the master mapping between the sourcr table 
     //and system.data.datatable 
     sDataAdapter.TableMappings.Add("Table", 
      "INFORMATION_SCHEMA.TABLE_CONSTRAINTS"); 

     //Fill the dataset 
     sDataAdapter.Fill(dsListOfPrimaryKeys); 

     //Bind the result combobox with primary key tables 
     DataViewManager dvmListOfPrimaryKeys = 
      dsListOfPrimaryKeys.DefaultViewManager; 
     dgResultView.DataSource = dsListOfPrimaryKeys 
      .Tables["INFORMATION_SCHEMA.TABLE_CONSTRAINTS"]; 
    } 
    catch(Exception ex) 
    { 
     //All the exceptions are handled and written in the EventLog. 
     EventLog log = new EventLog("Application"); 
     log.Source = "MFDBAnalyser"; 
     log.WriteEntry(ex.Message); 
    } 
    finally 
    { 
     //If connection is not closed then close the connection 
     if(sConnection.State != ConnectionState.Closed) 
     { 
      sConnection.Dispose(); 
     } 
    } 
} 

사람이 하드 코딩 된 것들을 제거하고 직접 app.config 파일에서 로컬 서버 주소, 사용자 ID 및 암호를 가지고 나를 도와 줄 수 .like ???

+0

이것은 http : //social.msdn.microsoft.com/Forums/en/adodotnetdataproviders/thread/9a8c9f5a-092e-4c4a-87bb-9f35d8f55da1 – Egalitarian

+1

이미 'ConfigurationSettings.AppSettings [ "ConnectionString"]'줄에서이 작업을 수행하고 있습니다. 다른 하드 코딩 된 것들에 대해 그렇게 할 때의 문제점은 무엇입니까? – Steven

답변

5

확실히.

먼저 app.config 또는 web.config 파일을 엽니 다. 즉 존재하지 않는 경우 다음 섹션

<appSettings> 
    <add key="...." value="....." /> 
    .... 
</appSettings> 

에 대한

이봐, 그것은 추가해야합니다. ...

<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
    <appSettings> 
     <add key="myServer" value="192.168.10.3" /> 
     <add key="myUserId" value="gp" /> 
     <add key="myPassword" value="gp" /> 
    </appSettings> 
</configuration> 

Kewl을

지금 ...

<add key="myServer" value="192.168.10.3" /> 
<add key="myUserId" value="gp" /> 
<add key="myPassword" value="gp" /> 

을 다음 키/값을 추가하고 이것이의 app.config 지금처럼 보일 수있는 예입니다. 이제 코드를 업데이트하십시오. 앱에서 (그 키/값의 값을 변경할 수 있습니다

변화 ...

sqlConnection.DataSource = "192.168.10.3"; 
sqlConnection.UserID = "gp"; 
sqlConnection.Password = "gp"; 

에 .. 이제

sqlConnection.DataSource = ConfiguationManager.AppSettings["myServer"]; 
sqlConnection.UserID = ConfiguationManager.AppSettings["myUserId"]; 
sqlConnection.Password = ConfiguationManager.AppSettings["myPassword"]; 

: - 트릭은 ConfigurationManager.AppSettings 클래스를 사용하는 것입니다 .config 또는 web.config) 코드를 컴파일 할 필요없이 :)

HTH

+0

먼저 System.Configuration을 사용하십시오. 마지막 섹션을 더 간단하게 만들려면 다음과 같이 읽으십시오. 'sqlConnection.DataSource = ConfigurationSettings.AppSettings [ "myServer"];' – nawfal

관련 문제