Skip to content

Commit

Permalink
Add samples for ADO.NET documentation (#797)
Browse files Browse the repository at this point in the history
imported documentes from .NET framework.
  • Loading branch information
DavoudEshtehari committed Nov 18, 2020
1 parent 4b73f5e commit d404913
Show file tree
Hide file tree
Showing 11 changed files with 398 additions and 0 deletions.
29 changes: 29 additions & 0 deletions doc/samples/ConnectionStringSettings_RetrieveFromConfig.cs
@@ -0,0 +1,29 @@
using System;
// <Snippet1>
using System.Configuration;

class Program
{
static void Main()
{
GetConnectionStrings();
Console.ReadLine();
}

static void GetConnectionStrings()
{
ConnectionStringSettingsCollection settings =
ConfigurationManager.ConnectionStrings;

if (settings != null)
{
foreach(ConnectionStringSettings cs in settings)
{
Console.WriteLine(cs.Name);
Console.WriteLine(cs.ProviderName);
Console.WriteLine(cs.ConnectionString);
}
}
}
}
// </Snippet1>
31 changes: 31 additions & 0 deletions doc/samples/ConnectionStringSettings_RetrieveFromConfigByName.cs
@@ -0,0 +1,31 @@
using System;
using System.Configuration;

class Program
{
static void Main()
{
string s = GetConnectionStringByName("NorthwindSQL");
Console.WriteLine(s);
Console.ReadLine();
}
// <Snippet1>
// Retrieves a connection string by name.
// Returns null if the name is not found.
static string GetConnectionStringByName(string name)
{
// Assume failure.
string returnValue = null;

// Look for the name in the connectionStrings section.
ConnectionStringSettings settings =
ConfigurationManager.ConnectionStrings[name];

// If found, return the connection string.
if (settings != null)
returnValue = settings.ConnectionString;

return returnValue;
}
// </Snippet1>
}
@@ -0,0 +1,40 @@
using System;
using System.Data;
using Microsoft.Data.SqlClient;
using System.Configuration;

class Program
{
static void Main()
{
string s = GetConnectionStringByProvider("Microsoft.Data.SqlClient");
Console.WriteLine(s);
Console.ReadLine();
}
// <Snippet1>
// Retrieve a connection string by specifying the providerName.
// Assumes one connection string per provider in the config file.
static string GetConnectionStringByProvider(string providerName)
{
// Return null on failure.
string returnValue = null;

// Get the collection of connection strings.
ConnectionStringSettingsCollection settings =
ConfigurationManager.ConnectionStrings;

// Walk through the collection and return the first
// connection string matching the providerName.
if (settings != null)
{
foreach (ConnectionStringSettings cs in settings)
{
if (cs.ProviderName == providerName)
returnValue = cs.ConnectionString;
break;
}
}
return returnValue;
}
// </Snippet1>
}
37 changes: 37 additions & 0 deletions doc/samples/ConnectionStringsWeb_Encrypt.cs
@@ -0,0 +1,37 @@
using System;
using System.Configuration;
using System.Web.Configuration;

class Program
{
static void Main()
{
}
// <Snippet1>
static void ToggleWebEncrypt()
{
// Open the Web.config file.
Configuration config = WebConfigurationManager.
OpenWebConfiguration("~");

// Get the connectionStrings section.
ConnectionStringsSection section =
config.GetSection("connectionStrings")
as ConnectionStringsSection;

// Toggle encryption.
if (section.SectionInformation.IsProtected)
{
section.SectionInformation.UnprotectSection();
}
else
{
section.SectionInformation.ProtectSection(
"DataProtectionConfigurationProvider");
}

// Save changes to the Web.config file.
config.Save();
}
// </Snippet1>
}
48 changes: 48 additions & 0 deletions doc/samples/ConnectionStrings_Encrypt.cs
@@ -0,0 +1,48 @@
using System;
using System.Configuration;

class Program
{
static void Main()
{
}
// <Snippet1>
static void ToggleConfigEncryption(string exeFile)
{
// Takes the executable file name without the
// .config extension.
try
{
// Open the configuration file and retrieve
// the connectionStrings section.
Configuration config = ConfigurationManager.
OpenExeConfiguration(exeConfigName);

ConnectionStringsSection section =
config.GetSection("connectionStrings")
as ConnectionStringsSection;

if (section.SectionInformation.IsProtected)
{
// Remove encryption.
section.SectionInformation.UnprotectSection();
}
else
{
// Encrypt the section.
section.SectionInformation.ProtectSection(
"DataProtectionConfigurationProvider");
}
// Save the current configuration.
config.Save();

Console.WriteLine("Protected={0}",
section.SectionInformation.IsProtected);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
// </Snippet1>
}
55 changes: 55 additions & 0 deletions doc/samples/SqlCommand_StoredProcedure.cs
@@ -0,0 +1,55 @@
using System;
using System.Data;
using Microsoft.Data.SqlClient;
class Program
{
static void Main()
{
// Supply any valid Document ID value.
// The value 7 is supplied for demonstration purposes.
GetSalesByCategory("Data Source=(local);Initial Catalog=Northwind;Integrated Security=true;", "Confections");
Console.ReadLine();
}
// <Snippet1>
static void GetSalesByCategory(string connectionString,
string categoryName)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
// Create the command and set its properties.
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "SalesByCategory";
command.CommandType = CommandType.StoredProcedure;

// Add the input parameter and set its properties.
SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "@CategoryName";
parameter.SqlDbType = SqlDbType.NVarChar;
parameter.Direction = ParameterDirection.Input;
parameter.Value = categoryName;

// Add the parameter to the Parameters collection.
command.Parameters.Add(parameter);

// Open the connection and execute the reader.
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("{0}: {1:C}", reader[0], reader[1]);
}
}
else
{
Console.WriteLine("No rows found.");
}
reader.Close();
}
}
}
// </Snippet1>
}
20 changes: 20 additions & 0 deletions doc/samples/SqlConnectionStringBuilder_InjectionAttack.cs
@@ -0,0 +1,20 @@
using System;
using System.Data;
using Microsoft.Data.SqlClient;

class Program
{
static void Main()
{
// <Snippet1>
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = "(local)";
builder.IntegratedSecurity = true;
builder.InitialCatalog = "AdventureWorks;NewValue=Bad";
Console.WriteLine(builder.ConnectionString);
// </Snippet1>

Console.WriteLine("Press Enter to continue.");
Console.ReadLine();
}
}
42 changes: 42 additions & 0 deletions doc/samples/SqlConnectionStringBuilder_UserNamePwd.cs
@@ -0,0 +1,42 @@
using System;
using System.Data;
using Microsoft.Data.SqlClient;
using System.Configuration;

class Program
{
static void Main()
{
BuildConnectionString("(local)", "Nate", "somepassword");
Console.ReadLine();
}

// <Snippet1>
private static void BuildConnectionString(string dataSource,
string userName, string userPassword)
{
// Retrieve the partial connection string named databaseConnection
// from the application's app.config or web.config file.
ConnectionStringSettings settings =
ConfigurationManager.ConnectionStrings["partialConnectString"];

if (null != settings)
{
// Retrieve the partial connection string.
string connectString = settings.ConnectionString;
Console.WriteLine("Original: {0}", connectString);

// Create a new SqlConnectionStringBuilder based on the
// partial connection string retrieved from the config file.
SqlConnectionStringBuilder builder =
new SqlConnectionStringBuilder(connectString);

// Supply the additional values.
builder.DataSource = dataSource;
builder.UserID = userName;
builder.Password = userPassword;
Console.WriteLine("Modified: {0}", builder.ConnectionString);
}
}
// </Snippet1>
}
44 changes: 44 additions & 0 deletions doc/samples/SqlConnection_InfoMessage_StateChange.cs
@@ -0,0 +1,44 @@
using System;
using System.Data;
using Microsoft.Data.SqlClient;

namespace ClassLibraryTest
{
public class Class1
{
public SqlConnection InitiateConnection(string connectionString)
{
// Assumes that connectionString is a valid SQL Server connection string.
var connection = new SqlConnection(connectionString);

// <Snippet1>
// Assumes that connection represents a SqlConnection object.
connection.InfoMessage +=
(object sender, SqlInfoMessageEventArgs args) =>
{
foreach (SqlError err in args.Errors)
{
Console.WriteLine(
"The {0} has received a severity {1}, state {2} error number {3}\n" +
"on line {4} of procedure {5} on server {6}:\n{7}",
err.Source, err.Class, err.State, err.Number, err.LineNumber,
err.Procedure, err.Server, err.Message);
}
};
// </Snippet1>

// <Snippet2>
// Assumes that connection represents a SqlConnection object.
connection.StateChange +=
(object sender, StateChangeEventArgs args) =>
{
Console.WriteLine(
"The current Connection state has changed from {0} to {1}.",
args.OriginalState, args.CurrentState);
};
// </Snippet2>

return connection;
}
}
}
31 changes: 31 additions & 0 deletions doc/samples/SqlConnection_Pooling.cs
@@ -0,0 +1,31 @@
using System;
using Microsoft.Data.SqlClient;

class Program
{
static void Main()
{
// <Snippet1>
using (SqlConnection connection = new SqlConnection(
"Integrated Security=SSPI;Initial Catalog=Northwind"))
{
connection.Open();
// Pool A is created.
}

using (SqlConnection connection = new SqlConnection(
"Integrated Security=SSPI;Initial Catalog=pubs"))
{
connection.Open();
// Pool B is created because the connection strings differ.
}

using (SqlConnection connection = new SqlConnection(
"Integrated Security=SSPI;Initial Catalog=Northwind"))
{
connection.Open();
// The connection string matches pool A.
}
// </Snippet1>
}
}

0 comments on commit d404913

Please sign in to comment.