In this section we will explore how we can use CAS from our
applications programmatically. Here is a sample code.
Listing 1
private void btnConnectDB_Click(object sender, EventArgs e)
{
DataSet dsContact = new DataSet();
SqlConnection dbConnection = new SqlConnection(
"Server=.;Database=Adventureworks;Trusted_Connection=true");
SqlCommand dbCommand = new SqlCommand("SELECT * FROM Person.Contact",
dbConnection);
dbConnection.Open();
SqlDataAdapter dataAdapter = new SqlDataAdapter(dbCommand);
dataAdapter.Fill(dsContact);
dbConnection.Close();
MessageBox.Show(String.Format("{0} Rows fetched from the database.",
dsContact.Tables[0].Rows.Count));
}
private void btnReadFile_Click(object sender, EventArgs e)
{
StreamReader sr = File.OpenText(@"D:\Sample.txt");
string content = sr.ReadToEnd();
MessageBox.Show(content);
sr.Close();
}
private void btnWriteFile_Click(object sender, EventArgs e)
{
StreamWriter sw = new StreamWriter(@"D:\Sample.txt");
sw.WriteLine("Hello World!");
sw.Close();
}
Refer to the code snippet given above. What we are trying to
do is an attempt to connect to the database in the click event of the button
btnConnectDB, and then we are trying to read and write in the subsequent
buttons. Now you need to compile this project with a strong name and then configure
the security permissions using the .NET Configuration Tool. In the section that
follows we will explore how we can use the .NET Configuration Tool to configure
security permissions.