diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData SqlDataAdapter.SqlDataAdapter Example/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData SqlDataAdapter.SqlDataAdapter Example/CS/Project.csproj
new file mode 100644
index 0000000000000..9659b3497e484
--- /dev/null
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData SqlDataAdapter.SqlDataAdapter Example/CS/Project.csproj
@@ -0,0 +1,12 @@
+
+
+
+ Library
+ net6.0
+ enable
+
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData SqlDataAdapter.SqlDataAdapter Example/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData SqlDataAdapter.SqlDataAdapter Example/CS/source.cs
index 957a742f0b0f2..ff0c0ff1f8abb 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData SqlDataAdapter.SqlDataAdapter Example/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData SqlDataAdapter.SqlDataAdapter Example/CS/source.cs
@@ -1,8 +1,7 @@
-using System;
-using System.Data;
+using System.Data;
using System.Data.SqlClient;
-class Program
+static class Program
{
static void Main()
{
@@ -10,20 +9,22 @@ static void Main()
//
public static SqlDataAdapter CreateSqlDataAdapter(SqlConnection connection)
{
- SqlDataAdapter adapter = new SqlDataAdapter();
- adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
+ SqlDataAdapter adapter = new()
+ {
+ MissingSchemaAction = MissingSchemaAction.AddWithKey,
- // Create the commands.
- adapter.SelectCommand = new SqlCommand(
- "SELECT CustomerID, CompanyName FROM CUSTOMERS", connection);
- adapter.InsertCommand = new SqlCommand(
+ // Create the commands.
+ SelectCommand = new SqlCommand(
+ "SELECT CustomerID, CompanyName FROM CUSTOMERS", connection),
+ InsertCommand = new SqlCommand(
"INSERT INTO Customers (CustomerID, CompanyName) " +
- "VALUES (@CustomerID, @CompanyName)", connection);
- adapter.UpdateCommand = new SqlCommand(
+ "VALUES (@CustomerID, @CompanyName)", connection),
+ UpdateCommand = new SqlCommand(
"UPDATE Customers SET CustomerID = @CustomerID, CompanyName = @CompanyName " +
- "WHERE CustomerID = @oldCustomerID", connection);
- adapter.DeleteCommand = new SqlCommand(
- "DELETE FROM Customers WHERE CustomerID = @CustomerID", connection);
+ "WHERE CustomerID = @oldCustomerID", connection),
+ DeleteCommand = new SqlCommand(
+ "DELETE FROM Customers WHERE CustomerID = @CustomerID", connection)
+ };
// Create the parameters.
adapter.InsertCommand.Parameters.Add("@CustomerID",
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DP Custom CopyToDataTable Examples/CS/CustomCopyToDataTableCS.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DP Custom CopyToDataTable Examples/CS/CustomCopyToDataTableCS.csproj
index 353b90bed69e9..226721f95dbe3 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DP Custom CopyToDataTable Examples/CS/CustomCopyToDataTableCS.csproj
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DP Custom CopyToDataTable Examples/CS/CustomCopyToDataTableCS.csproj
@@ -8,6 +8,10 @@
DP Custom CopyToDataTable Examples
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DP Custom CopyToDataTable Examples/CS/Program.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DP Custom CopyToDataTable Examples/CS/Program.cs
index fe566c9f4e7e2..eb6a1dd56d1c9 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DP Custom CopyToDataTable Examples/CS/Program.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DP Custom CopyToDataTable Examples/CS/Program.cs
@@ -1,25 +1,23 @@
using System;
using System.Collections.Generic;
-using System.Linq;
-using System.Text;
using System.Data;
-using System.Data.Common;
-using System.Reflection;
using System.Data.SqlClient;
using System.Globalization;
+using System.Linq;
+using System.Reflection;
namespace DP_Custom_CopyToDataTable_Examples
{
- class Program
+ static class Program
{
- static void Main(string[] args)
+ static void Main()
{
//ItemsQueries();
- // JoinQuery();
- // LoadScalarSequence();
- // LoadItemsIntoTable();
- // LoadItemsIntoExistingTable();
+ // JoinQuery();
+ // LoadScalarSequence();
+ // LoadItemsIntoTable();
+ // LoadItemsIntoExistingTable();
LoadItemsExpandSchema();
Console.WriteLine("Hit enter...");
@@ -30,8 +28,10 @@ static void JoinQuery()
{
//
// Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
+ var ds = new DataSet
+ {
+ Locale = CultureInfo.InvariantCulture
+ };
FillDataSet(ds);
DataTable orders = ds.Tables["SalesOrderHeader"];
@@ -42,8 +42,8 @@ from order in orders.AsEnumerable()
join detail in details.AsEnumerable()
on order.Field("SalesOrderID") equals
detail.Field("SalesOrderID")
- where order.Field("OnlineOrderFlag") == true
- && order.Field("OrderDate").Month == 8
+ where order.Field("OnlineOrderFlag")
+ && order.Field("OrderDate").Month == 8
select new
{
SalesOrderID =
@@ -66,17 +66,17 @@ static void LoadItemsIntoTable()
{
//
// Create a sequence.
- Item[] items = new Item[]
+ var items = new Item[]
{ new Book{Id = 1, Price = 13.50, Genre = "Comedy", Author = "Gustavo Achong"},
new Book{Id = 2, Price = 8.50, Genre = "Drama", Author = "Jessie Zeng"},
new Movie{Id = 1, Price = 22.99, Genre = "Comedy", Director = "Marissa Barnes"},
new Movie{Id = 1, Price = 13.40, Genre = "Action", Director = "Emmanuel Fernandez"}};
// Query for items with price greater than 9.99.
- var query = from i in items
- where i.Price > 9.99
- orderby i.Price
- select i;
+ IOrderedEnumerable- query = from i in items
+ where i.Price > 9.99
+ orderby i.Price
+ select i;
// Load the query results into new DataTable.
DataTable table = query.CopyToDataTable();
@@ -88,21 +88,21 @@ static void LoadItemsIntoExistingTable()
{
//
// Create a sequence.
- Item[] items = new Item[]
+ var items = new Item[]
{ new Book{Id = 1, Price = 13.50, Genre = "Comedy", Author = "Gustavo Achong"},
new Book{Id = 2, Price = 8.50, Genre = "Drama", Author = "Jessie Zeng"},
new Movie{Id = 1, Price = 22.99, Genre = "Comedy", Director = "Marissa Barnes"},
new Movie{Id = 1, Price = 13.40, Genre = "Action", Director = "Emmanuel Fernandez"}};
// Create a table with a schema that matches that of the query results.
- DataTable table = new DataTable();
+ var table = new DataTable();
table.Columns.Add("Price", typeof(int));
table.Columns.Add("Genre", typeof(string));
var query = from i in items
- where i.Price > 9.99
- orderby i.Price
- select new { i.Price, i.Genre };
+ where i.Price > 9.99
+ orderby i.Price
+ select new { i.Price, i.Genre };
query.CopyToDataTable(table, LoadOption.PreserveChanges);
//
@@ -113,7 +113,7 @@ static void LoadItemsExpandSchema()
{
//
// Create a sequence.
- Item[] items = new Item[]
+ var items = new Item[]
{ new Book{Id = 1, Price = 13.50, Genre = "Comedy", Author = "Gustavo Achong"},
new Book{Id = 2, Price = 8.50, Genre = "Drama", Author = "Jessie Zeng"},
new Movie{Id = 1, Price = 22.99, Genre = "Comedy", Director = "Marissa Barnes"},
@@ -121,15 +121,15 @@ static void LoadItemsExpandSchema()
// Load into an existing DataTable, expand the schema and
// autogenerate a new Id.
- DataTable table = new DataTable();
+ var table = new DataTable();
DataColumn dc = table.Columns.Add("NewId", typeof(int));
dc.AutoIncrement = true;
table.Columns.Add("ExtraColumn", typeof(string));
var query = from i in items
- where i.Price > 9.99
- orderby i.Price
- select new { i.Price, i.Genre };
+ where i.Price > 9.99
+ orderby i.Price
+ select new { i.Price, i.Genre };
query.CopyToDataTable(table, LoadOption.PreserveChanges);
//
@@ -140,7 +140,7 @@ static void LoadScalarSequence()
{
//
// Create a sequence.
- Item[] items = new Item[]
+ var items = new Item[]
{ new Book{Id = 1, Price = 13.50, Genre = "Comedy", Author = "Gustavo Achong"},
new Book{Id = 2, Price = 8.50, Genre = "Drama", Author = "Jessie Zeng"},
new Movie{Id = 1, Price = 22.99, Genre = "Comedy", Director = "Marissa Barnes"},
@@ -148,9 +148,9 @@ static void LoadScalarSequence()
// load sequence of scalars.
IEnumerable query = from i in items
- where i.Price > 9.99
- orderby i.Price
- select i.Price;
+ where i.Price > 9.99
+ orderby i.Price
+ select i.Price;
DataTable table = query.CopyToDataTable();
//
@@ -159,12 +159,11 @@ orderby i.Price
static void DisplayTable(DataTable table)
{
-
- for (int i = 0; i < table.Rows.Count; i++)
+ for (var i = 0; i < table.Rows.Count; i++)
{
- for (int j = 0; j < table.Columns.Count; j++)
+ for (var j = 0; j < table.Columns.Count; j++)
{
- Console.WriteLine(table.Columns[j].ColumnName + ": " + table.Rows[i][j].ToString());
+ Console.WriteLine(table.Columns[j].ColumnName + ": " + table.Rows[i][j]);
}
Console.WriteLine("");
}
@@ -178,10 +177,10 @@ static void FillDataSet(DataSet ds)
// Create a new adapter and give it a query to fetch sales order, contact,
// address, and product information for sales in the year 2002. Point connection
// information to the configuration setting "AdventureWorks".
- string connectionString = "Data Source=localhost;Initial Catalog=AdventureWorks;"
+ const string connectionString = "Data Source=localhost;Initial Catalog=AdventureWorks;"
+ "Integrated Security=true;";
- SqlDataAdapter da = new SqlDataAdapter(
+ var da = new SqlDataAdapter(
"SELECT SalesOrderID, ContactID, OrderDate, OnlineOrderFlag, " +
"TotalDue, SalesOrderNumber, Status, ShipToAddressID, BillToAddressID " +
"FROM Sales.SalesOrderHeader " +
@@ -227,14 +226,14 @@ static void FillDataSet(DataSet ds)
// Add data relations.
DataTable orderHeader = ds.Tables["SalesOrderHeader"];
DataTable orderDetail = ds.Tables["SalesOrderDetail"];
- DataRelation order = new DataRelation("SalesOrderHeaderDetail",
+ var order = new DataRelation("SalesOrderHeaderDetail",
orderHeader.Columns["SalesOrderID"],
orderDetail.Columns["SalesOrderID"], true);
ds.Relations.Add(order);
DataTable contact = ds.Tables["Contact"];
DataTable orderHeader2 = ds.Tables["SalesOrderHeader"];
- DataRelation orderContact = new DataRelation("SalesOrderContact",
+ var orderContact = new DataRelation("SalesOrderContact",
contact.Columns["ContactID"],
orderHeader2.Columns["ContactID"], true);
ds.Relations.Add(orderContact);
@@ -268,26 +267,22 @@ public class Movie : Item
//
public static class CustomLINQtoDataSetMethods
{
- public static DataTable CopyToDataTable(this IEnumerable source)
- {
- return new ObjectShredder().Shred(source, null, null);
- }
+ public static DataTable CopyToDataTable(this IEnumerable source) =>
+ new ObjectShredder().Shred(source, null, null);
public static DataTable CopyToDataTable(this IEnumerable source,
- DataTable table, LoadOption? options)
- {
- return new ObjectShredder().Shred(source, table, options);
- }
+ DataTable table, LoadOption? options) =>
+ new ObjectShredder().Shred(source, table, options);
}
//
//
public class ObjectShredder
{
- private System.Reflection.FieldInfo[] _fi;
- private System.Reflection.PropertyInfo[] _pi;
- private System.Collections.Generic.Dictionary _ordinalMap;
- private System.Type _type;
+ readonly FieldInfo[] _fi;
+ readonly PropertyInfo[] _pi;
+ readonly Dictionary _ordinalMap;
+ readonly Type _type;
// ObjectShredder constructor.
public ObjectShredder()
@@ -324,18 +319,15 @@ public DataTable Shred(IEnumerable source, DataTable table, LoadOption? optio
// Enumerate the source sequence and load the object values into rows.
table.BeginLoadData();
- using (IEnumerator e = source.GetEnumerator())
+ foreach (T item in source)
{
- while (e.MoveNext())
+ if (options != null)
{
- if (options != null)
- {
- table.LoadDataRow(ShredObject(table, e.Current), (LoadOption)options);
- }
- else
- {
- table.LoadDataRow(ShredObject(table, e.Current), true);
- }
+ table.LoadDataRow(ShredObject(table, item), (LoadOption)options);
+ }
+ else
+ {
+ table.LoadDataRow(ShredObject(table, item), true);
}
}
table.EndLoadData();
@@ -358,7 +350,7 @@ public DataTable ShredPrimitive(IEnumerable source, DataTable table, LoadOpti
table.BeginLoadData();
using (IEnumerator e = source.GetEnumerator())
{
- Object[] values = new object[table.Columns.Count];
+ var values = new object[table.Columns.Count];
while (e.MoveNext())
{
values[table.Columns["Value"].Ordinal] = e.Current;
@@ -381,7 +373,6 @@ public DataTable ShredPrimitive(IEnumerable source, DataTable table, LoadOpti
public object[] ShredObject(DataTable table, T instance)
{
-
FieldInfo[] fi = _fi;
PropertyInfo[] pi = _pi;
@@ -395,7 +386,7 @@ public object[] ShredObject(DataTable table, T instance)
}
// Add the property and field values of the instance to an array.
- Object[] values = new object[table.Columns.Count];
+ var values = new object[table.Columns.Count];
foreach (FieldInfo f in fi)
{
values[_ordinalMap[f.Name]] = f.GetValue(instance);
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DP DataView Samples/CS/DataViewSamplesCS.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DP DataView Samples/CS/DataViewSamplesCS.csproj
index c97e0412c57b5..189ef9c3e26ea 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DP DataView Samples/CS/DataViewSamplesCS.csproj
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DP DataView Samples/CS/DataViewSamplesCS.csproj
@@ -6,6 +6,10 @@
true
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DP DataView Samples/CS/Form1.Designer.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DP DataView Samples/CS/Form1.Designer.cs
index c27eac134da06..bc0307c4a41da 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DP DataView Samples/CS/Form1.Designer.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DP DataView Samples/CS/Form1.Designer.cs
@@ -5,7 +5,7 @@ partial class Form1
///
/// Required designer variable.
///
- private System.ComponentModel.IContainer components = null;
+ System.ComponentModel.IContainer components = null;
///
/// Clean up any resources being used.
@@ -26,7 +26,7 @@ protected override void Dispose(bool disposing)
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
- private void InitializeComponent()
+ void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.dataGridView1 = new System.Windows.Forms.DataGridView();
@@ -88,7 +88,7 @@ private void InitializeComponent()
this.button1.TabIndex = 1;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
- this.button1.Click += new System.EventHandler(this.button1_Click);
+ this.button1.Click += new System.EventHandler(this.Button1_Click);
//
// button2
//
@@ -98,7 +98,7 @@ private void InitializeComponent()
this.button2.TabIndex = 2;
this.button2.Text = "button2";
this.button2.UseVisualStyleBackColor = true;
- this.button2.Click += new System.EventHandler(this.button2_Click);
+ this.button2.Click += new System.EventHandler(this.Button2_Click);
//
// button3
//
@@ -108,7 +108,7 @@ private void InitializeComponent()
this.button3.TabIndex = 3;
this.button3.Text = "button3";
this.button3.UseVisualStyleBackColor = true;
- this.button3.Click += new System.EventHandler(this.button3_Click);
+ this.button3.Click += new System.EventHandler(this.Button3_Click);
//
// label1
//
@@ -127,7 +127,7 @@ private void InitializeComponent()
this.button4.TabIndex = 5;
this.button4.Text = "button4";
this.button4.UseVisualStyleBackColor = true;
- this.button4.Click += new System.EventHandler(this.button4_Click);
+ this.button4.Click += new System.EventHandler(this.Button4_Click);
//
// button5
//
@@ -137,7 +137,7 @@ private void InitializeComponent()
this.button5.TabIndex = 6;
this.button5.Text = "button5";
this.button5.UseVisualStyleBackColor = true;
- this.button5.Click += new System.EventHandler(this.button5_Click);
+ this.button5.Click += new System.EventHandler(this.Button5_Click);
//
// label2
//
@@ -156,7 +156,7 @@ private void InitializeComponent()
this.button6.TabIndex = 8;
this.button6.Text = "button6";
this.button6.UseVisualStyleBackColor = true;
- this.button6.Click += new System.EventHandler(this.button6_Click);
+ this.button6.Click += new System.EventHandler(this.Button6_Click);
//
// label3
//
@@ -184,7 +184,7 @@ private void InitializeComponent()
this.button7.TabIndex = 11;
this.button7.Text = "button7";
this.button7.UseVisualStyleBackColor = true;
- this.button7.Click += new System.EventHandler(this.button7_Click);
+ this.button7.Click += new System.EventHandler(this.Button7_Click);
//
// button8
//
@@ -194,7 +194,7 @@ private void InitializeComponent()
this.button8.TabIndex = 12;
this.button8.Text = "button8";
this.button8.UseVisualStyleBackColor = true;
- this.button8.Click += new System.EventHandler(this.button8_Click);
+ this.button8.Click += new System.EventHandler(this.Button8_Click);
//
// button9
//
@@ -204,7 +204,7 @@ private void InitializeComponent()
this.button9.TabIndex = 13;
this.button9.Text = "button9";
this.button9.UseVisualStyleBackColor = true;
- this.button9.Click += new System.EventHandler(this.button9_Click);
+ this.button9.Click += new System.EventHandler(this.Button9_Click);
//
// button10
//
@@ -214,7 +214,7 @@ private void InitializeComponent()
this.button10.TabIndex = 14;
this.button10.Text = "button10";
this.button10.UseVisualStyleBackColor = true;
- this.button10.Click += new System.EventHandler(this.button10_Click);
+ this.button10.Click += new System.EventHandler(this.Button10_Click);
//
// button11
//
@@ -224,7 +224,7 @@ private void InitializeComponent()
this.button11.TabIndex = 15;
this.button11.Text = "button11";
this.button11.UseVisualStyleBackColor = true;
- this.button11.Click += new System.EventHandler(this.button11_Click);
+ this.button11.Click += new System.EventHandler(this.Button11_Click);
//
// button12
//
@@ -234,7 +234,7 @@ private void InitializeComponent()
this.button12.TabIndex = 16;
this.button12.Text = "button12";
this.button12.UseVisualStyleBackColor = true;
- this.button12.Click += new System.EventHandler(this.button12_Click);
+ this.button12.Click += new System.EventHandler(this.Button12_Click);
//
// button13
//
@@ -244,7 +244,7 @@ private void InitializeComponent()
this.button13.TabIndex = 17;
this.button13.Text = "button13";
this.button13.UseVisualStyleBackColor = true;
- this.button13.Click += new System.EventHandler(this.button13_Click);
+ this.button13.Click += new System.EventHandler(this.Button13_Click);
//
// button14
//
@@ -254,7 +254,7 @@ private void InitializeComponent()
this.button14.TabIndex = 18;
this.button14.Text = "button14";
this.button14.UseVisualStyleBackColor = true;
- this.button14.Click += new System.EventHandler(this.button14_Click);
+ this.button14.Click += new System.EventHandler(this.Button14_Click);
//
// button15
//
@@ -264,7 +264,7 @@ private void InitializeComponent()
this.button15.TabIndex = 19;
this.button15.Text = "button15";
this.button15.UseVisualStyleBackColor = true;
- this.button15.Click += new System.EventHandler(this.button15_Click);
+ this.button15.Click += new System.EventHandler(this.Button15_Click);
//
// button16
//
@@ -274,7 +274,7 @@ private void InitializeComponent()
this.button16.TabIndex = 20;
this.button16.Text = "button16";
this.button16.UseVisualStyleBackColor = true;
- this.button16.Click += new System.EventHandler(this.button16_Click);
+ this.button16.Click += new System.EventHandler(this.Button16_Click);
//
// label5
//
@@ -293,7 +293,7 @@ private void InitializeComponent()
this.button17.TabIndex = 22;
this.button17.Text = "button17";
this.button17.UseVisualStyleBackColor = true;
- this.button17.Click += new System.EventHandler(this.button17_Click);
+ this.button17.Click += new System.EventHandler(this.Button17_Click);
//
// button18
//
@@ -303,7 +303,7 @@ private void InitializeComponent()
this.button18.TabIndex = 23;
this.button18.Text = "button18";
this.button18.UseVisualStyleBackColor = true;
- this.button18.Click += new System.EventHandler(this.button18_Click);
+ this.button18.Click += new System.EventHandler(this.Button18_Click);
//
// button19
//
@@ -313,7 +313,7 @@ private void InitializeComponent()
this.button19.TabIndex = 24;
this.button19.Text = "button19";
this.button19.UseVisualStyleBackColor = true;
- this.button19.Click += new System.EventHandler(this.button19_Click);
+ this.button19.Click += new System.EventHandler(this.Button19_Click);
//
// button20
//
@@ -323,7 +323,7 @@ private void InitializeComponent()
this.button20.TabIndex = 25;
this.button20.Text = "button20";
this.button20.UseVisualStyleBackColor = true;
- this.button20.Click += new System.EventHandler(this.button20_Click);
+ this.button20.Click += new System.EventHandler(this.Button20_Click);
//
// button21
//
@@ -333,7 +333,7 @@ private void InitializeComponent()
this.button21.TabIndex = 26;
this.button21.Text = "button21";
this.button21.UseVisualStyleBackColor = true;
- this.button21.Click += new System.EventHandler(this.button21_Click);
+ this.button21.Click += new System.EventHandler(this.Button21_Click);
//
// label6
//
@@ -352,7 +352,7 @@ private void InitializeComponent()
this.button22.TabIndex = 28;
this.button22.Text = "button22";
this.button22.UseVisualStyleBackColor = true;
- this.button22.Click += new System.EventHandler(this.button22_Click);
+ this.button22.Click += new System.EventHandler(this.Button22_Click);
//
// button23
//
@@ -362,7 +362,7 @@ private void InitializeComponent()
this.button23.TabIndex = 29;
this.button23.Text = "button23";
this.button23.UseVisualStyleBackColor = true;
- this.button23.Click += new System.EventHandler(this.button23_Click);
+ this.button23.Click += new System.EventHandler(this.Button23_Click);
//
// button24
//
@@ -372,7 +372,7 @@ private void InitializeComponent()
this.button24.TabIndex = 30;
this.button24.Text = "button24";
this.button24.UseVisualStyleBackColor = true;
- this.button24.Click += new System.EventHandler(this.button24_Click);
+ this.button24.Click += new System.EventHandler(this.Button24_Click);
//
// button26
//
@@ -382,7 +382,7 @@ private void InitializeComponent()
this.button26.TabIndex = 32;
this.button26.Text = "button26";
this.button26.UseVisualStyleBackColor = true;
- this.button26.Click += new System.EventHandler(this.button26_Click);
+ this.button26.Click += new System.EventHandler(this.Button26_Click);
//
// button25
//
@@ -392,7 +392,7 @@ private void InitializeComponent()
this.button25.TabIndex = 33;
this.button25.Text = "button25";
this.button25.UseVisualStyleBackColor = true;
- this.button25.Click += new System.EventHandler(this.button25_Click);
+ this.button25.Click += new System.EventHandler(this.Button25_Click);
//
// dataGridView2
//
@@ -419,7 +419,7 @@ private void InitializeComponent()
this.button27.TabIndex = 36;
this.button27.Text = "button27";
this.button27.UseVisualStyleBackColor = true;
- this.button27.Click += new System.EventHandler(this.button27_Click);
+ this.button27.Click += new System.EventHandler(this.Button27_Click);
//
// button28
//
@@ -429,7 +429,7 @@ private void InitializeComponent()
this.button28.TabIndex = 37;
this.button28.Text = "button28";
this.button28.UseVisualStyleBackColor = true;
- this.button28.Click += new System.EventHandler(this.button28_Click);
+ this.button28.Click += new System.EventHandler(this.Button28_Click);
//
// Form1
//
@@ -486,44 +486,44 @@ private void InitializeComponent()
#endregion
- private System.Windows.Forms.DataGridView dataGridView1;
- private System.Windows.Forms.BindingSource bindingSource1;
- private System.Windows.Forms.Button button1;
- private System.Windows.Forms.Button button2;
- private System.Windows.Forms.Button button3;
- private System.Windows.Forms.Label label1;
- private System.Windows.Forms.Button button4;
- private System.Windows.Forms.Button button5;
- private System.Windows.Forms.Label label2;
- private System.Windows.Forms.Button button6;
- private System.Windows.Forms.Label label3;
- private System.Windows.Forms.Label label4;
- private System.Windows.Forms.Button button7;
- private System.Windows.Forms.Button button8;
- private System.Windows.Forms.Button button9;
- private System.Windows.Forms.Button button10;
- private System.Windows.Forms.Button button11;
- private System.Windows.Forms.Button button12;
- private System.Windows.Forms.Button button13;
- private System.Windows.Forms.Button button14;
- private System.Windows.Forms.Button button15;
- private System.Windows.Forms.Button button16;
- private System.Windows.Forms.Label label5;
- private System.Windows.Forms.Button button17;
- private System.Windows.Forms.Button button18;
- private System.Windows.Forms.Button button19;
- private System.Windows.Forms.Button button20;
- private System.Windows.Forms.Button button21;
- private System.Windows.Forms.Label label6;
- private System.Windows.Forms.Button button22;
- private System.Windows.Forms.Button button23;
- private System.Windows.Forms.Button button24;
- private System.Windows.Forms.Button button26;
- private System.Windows.Forms.Button button25;
- private System.Windows.Forms.DataGridView dataGridView2;
- private System.Windows.Forms.Label label7;
- private System.Windows.Forms.Button button27;
- private System.Windows.Forms.Button button28;
+ System.Windows.Forms.DataGridView dataGridView1;
+ System.Windows.Forms.BindingSource bindingSource1;
+ System.Windows.Forms.Button button1;
+ System.Windows.Forms.Button button2;
+ System.Windows.Forms.Button button3;
+ System.Windows.Forms.Label label1;
+ System.Windows.Forms.Button button4;
+ System.Windows.Forms.Button button5;
+ System.Windows.Forms.Label label2;
+ System.Windows.Forms.Button button6;
+ System.Windows.Forms.Label label3;
+ System.Windows.Forms.Label label4;
+ System.Windows.Forms.Button button7;
+ System.Windows.Forms.Button button8;
+ System.Windows.Forms.Button button9;
+ System.Windows.Forms.Button button10;
+ System.Windows.Forms.Button button11;
+ System.Windows.Forms.Button button12;
+ System.Windows.Forms.Button button13;
+ System.Windows.Forms.Button button14;
+ System.Windows.Forms.Button button15;
+ System.Windows.Forms.Button button16;
+ System.Windows.Forms.Label label5;
+ System.Windows.Forms.Button button17;
+ System.Windows.Forms.Button button18;
+ System.Windows.Forms.Button button19;
+ System.Windows.Forms.Button button20;
+ System.Windows.Forms.Button button21;
+ System.Windows.Forms.Label label6;
+ System.Windows.Forms.Button button22;
+ System.Windows.Forms.Button button23;
+ System.Windows.Forms.Button button24;
+ System.Windows.Forms.Button button26;
+ System.Windows.Forms.Button button25;
+ System.Windows.Forms.DataGridView dataGridView2;
+ System.Windows.Forms.Label label7;
+ System.Windows.Forms.Button button27;
+ System.Windows.Forms.Button button28;
}
}
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DP DataView Samples/CS/Form1.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DP DataView Samples/CS/Form1.cs
index 274b305f41011..f60f9c9491d0c 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DP DataView Samples/CS/Form1.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DP DataView Samples/CS/Form1.cs
@@ -1,45 +1,41 @@
using System;
using System.Collections.Generic;
-using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
-using System.Data.Common;
-using System.Drawing;
+using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows.Forms;
-using System.Globalization;
namespace DataViewSamples
{
public partial class Form1 : Form
{
- DataSet dataSet;
+ DataSet _dataSet;
- public Form1()
- {
- InitializeComponent();
- }
+ public Form1() => InitializeComponent();
- private void Form1_Load(object sender, EventArgs e)
+ void Form1_Load(object sender, EventArgs e)
{
// Fill the DataSet.
- dataSet = new DataSet();
- dataSet.Locale = CultureInfo.InvariantCulture;
- FillDataSet(dataSet);
+ _dataSet = new DataSet
+ {
+ Locale = CultureInfo.InvariantCulture
+ };
+ FillDataSet(_dataSet);
dataGridView1.DataSource = bindingSource1;
}
- private void FillDataSet(DataSet ds)
+ static void FillDataSet(DataSet ds)
{
// Create a new adapter and give it a query to fetch sales order, contact,
// address, and product information for sales in the year 2002. Point connection
// information to the configuration setting "AdventureWorks".
- string connectionString = "Data Source=localhost;Initial Catalog=AdventureWorks;"
+ const string connectionString = "Data Source=localhost;Initial Catalog=AdventureWorks;"
+ "Integrated Security=true;";
- SqlDataAdapter da = new SqlDataAdapter(
+ var da = new SqlDataAdapter(
"SELECT SalesOrderID, ContactID, OrderDate, OnlineOrderFlag, " +
"TotalDue, SalesOrderNumber, Status, ShipToAddressID, BillToAddressID " +
"FROM Sales.SalesOrderHeader " +
@@ -85,53 +81,55 @@ private void FillDataSet(DataSet ds)
// Add data relations.
DataTable orderHeader = ds.Tables["SalesOrderHeader"];
DataTable orderDetail = ds.Tables["SalesOrderDetail"];
- DataRelation order = new DataRelation("SalesOrderHeaderDetail",
+ var order = new DataRelation("SalesOrderHeaderDetail",
orderHeader.Columns["SalesOrderID"],
orderDetail.Columns["SalesOrderID"], true);
ds.Relations.Add(order);
DataTable contact = ds.Tables["Contact"];
DataTable orderHeader2 = ds.Tables["SalesOrderHeader"];
- DataRelation orderContact = new DataRelation("SalesOrderContact",
+ var orderContact = new DataRelation("SalesOrderContact",
contact.Columns["ContactID"],
orderHeader2.Columns["ContactID"], true);
ds.Relations.Add(orderContact);
}
//
- static private string SoundEx(string word)
+ static string SoundEx(string word)
{
// The length of the returned code.
- int length = 4;
+ const int length = 4;
// Value to return.
- string value = "";
+ var value = "";
// The size of the word to process.
- int size = word.Length;
+ var size = word.Length;
// The word must be at least two characters in length.
if (size > 1)
{
// Convert the word to uppercase characters.
- word = word.ToUpper(System.Globalization.CultureInfo.InvariantCulture);
+ word = word.ToUpper(CultureInfo.InvariantCulture);
// Convert the word to a character array.
- char[] chars = word.ToCharArray();
+ var chars = word.ToCharArray();
// Buffer to hold the character codes.
- StringBuilder buffer = new StringBuilder();
- buffer.Length = 0;
+ var buffer = new StringBuilder
+ {
+ Length = 0
+ };
// The current and previous character codes.
- int prevCode = 0;
- int currCode = 0;
+ var prevCode = 0;
+ var currCode = 0;
// Add the first character to the buffer.
buffer.Append(chars[0]);
// Loop through all the characters and convert them to the proper character code.
- for (int i = 1; i < size; i++)
+ for (var i = 1; i < size; i++)
{
switch (chars[i])
{
@@ -182,19 +180,25 @@ static private string SoundEx(string word)
{
// Check to see if the current code is 0 (a vowel); do not process vowels.
if (currCode != 0)
+ {
buffer.Append(currCode);
+ }
}
// Set the previous character code.
prevCode = currCode;
// If the buffer size meets the length limit, exit the loop.
if (buffer.Length == length)
+ {
break;
+ }
}
// Pad the buffer, if required.
size = buffer.Length;
if (size < length)
- buffer.Append('0', (length - size));
+ {
+ buffer.Append('0', length - size);
+ }
// Set the value to return.
value = buffer.ToString();
@@ -204,14 +208,14 @@ static private string SoundEx(string word)
}
//
- private void button1_Click(object sender, EventArgs e)
+ void Button1_Click(object sender, EventArgs e)
{
//
- DataTable orders = dataSet.Tables["SalesOrderHeader"];
+ DataTable orders = _dataSet.Tables["SalesOrderHeader"];
EnumerableRowCollection query =
from order in orders.AsEnumerable()
- where order.Field("OnlineOrderFlag") == true
+ where order.Field("OnlineOrderFlag")
orderby order.Field("TotalDue")
select order;
@@ -221,15 +225,15 @@ orderby order.Field("TotalDue")
//
}
- private void button2_Click(object sender, EventArgs e)
+ void Button2_Click(object sender, EventArgs e)
{
//
- DataTable orders = dataSet.Tables["SalesOrderDetail"];
+ DataTable orders = _dataSet.Tables["SalesOrderDetail"];
EnumerableRowCollection query =
from order in orders.AsEnumerable()
- where (order.Field("OrderQty") > 2 &&
- order.Field("OrderQty") < 6)
+ where order.Field("OrderQty") > 2 &&
+ order.Field("OrderQty") < 6
select order;
DataView view = query.AsDataView();
@@ -240,10 +244,10 @@ from order in orders.AsEnumerable()
//
}
- private void button3_Click(object sender, EventArgs e)
+ void Button3_Click(object sender, EventArgs e)
{
//
- DataTable contacts = dataSet.Tables["Contact"];
+ DataTable contacts = _dataSet.Tables["Contact"];
EnumerableRowCollection query = from contact in contacts.AsEnumerable()
where contact.Field("LastName").StartsWith("S")
@@ -255,10 +259,10 @@ where contact.Field("LastName").StartsWith("S")
//
}
- private void button4_Click(object sender, EventArgs e)
+ void Button4_Click(object sender, EventArgs e)
{
//
- DataTable orders = dataSet.Tables["SalesOrderHeader"];
+ DataTable orders = _dataSet.Tables["SalesOrderHeader"];
EnumerableRowCollection query = from order in orders.AsEnumerable()
where order.Field("OrderDate") > new DateTime(2002, 9, 15)
@@ -270,11 +274,10 @@ private void button4_Click(object sender, EventArgs e)
//
}
- private void button5_Click(object sender, EventArgs e)
+ void Button5_Click(object sender, EventArgs e)
{
-
//
- DataTable orders = dataSet.Tables["SalesOrderDetail"];
+ DataTable orders = _dataSet.Tables["SalesOrderDetail"];
DataView view = orders.AsDataView();
bindingSource1.DataSource = view;
@@ -283,10 +286,10 @@ private void button5_Click(object sender, EventArgs e)
//
}
- private void button6_Click(object sender, EventArgs e)
+ void Button6_Click(object sender, EventArgs e)
{
//
- DataTable orders = dataSet.Tables["SalesOrderHeader"];
+ DataTable orders = _dataSet.Tables["SalesOrderHeader"];
EnumerableRowCollection query = from order in orders.AsEnumerable()
orderby order.Field("OrderDate")
@@ -298,10 +301,10 @@ orderby order.Field("OrderDate")
//
}
- private void button7_Click(object sender, EventArgs e)
+ void Button7_Click(object sender, EventArgs e)
{
//
- DataTable contacts = dataSet.Tables["Contact"];
+ DataTable contacts = _dataSet.Tables["Contact"];
EnumerableRowCollection query = from contact in contacts.AsEnumerable()
where contact.Field("LastName").StartsWith("S")
@@ -315,13 +318,13 @@ where contact.Field("LastName").StartsWith("S")
//
}
- private void button8_Click(object sender, EventArgs e)
+ void Button8_Click(object sender, EventArgs e)
{
//
- DataTable orders = dataSet.Tables["SalesOrderDetail"];
+ DataTable orders = _dataSet.Tables["SalesOrderDetail"];
EnumerableRowCollection query = from order in orders.AsEnumerable()
- orderby order.Field("OrderQty"), order.Field("SalesOrderID")
+ orderby order.Field("OrderQty"), order.Field("SalesOrderID")
select order;
DataView view = query.AsDataView();
@@ -331,10 +334,10 @@ orderby order.Field("OrderQty"), order.Field("SalesOrderID")
//
}
- private void button9_Click(object sender, EventArgs e)
+ void Button9_Click(object sender, EventArgs e)
{
//
- DataTable orders = dataSet.Tables["SalesOrderHeader"];
+ DataTable orders = _dataSet.Tables["SalesOrderHeader"];
EnumerableRowCollection query =
from order in orders.AsEnumerable()
@@ -348,10 +351,10 @@ orderby order.Field("TotalDue")
//
}
- private void button10_Click(object sender, EventArgs e)
+ void Button10_Click(object sender, EventArgs e)
{
//
- DataTable orders = dataSet.Tables["SalesOrderHeader"];
+ DataTable orders = _dataSet.Tables["SalesOrderHeader"];
EnumerableRowCollection query = from order in orders.AsEnumerable()
orderby order.Field("OrderDate") descending
@@ -363,10 +366,10 @@ orderby order.Field("OrderDate") descending
//
}
- private void button11_Click(object sender, EventArgs e)
+ void Button11_Click(object sender, EventArgs e)
{
//
- DataTable contacts = dataSet.Tables["Contact"];
+ DataTable contacts = _dataSet.Tables["Contact"];
DataView view = contacts.AsDataView();
@@ -377,10 +380,10 @@ private void button11_Click(object sender, EventArgs e)
//
}
- private void button12_Click(object sender, EventArgs e)
+ void Button12_Click(object sender, EventArgs e)
{
//
- DataTable orders = dataSet.Tables["SalesOrderHeader"];
+ DataTable orders = _dataSet.Tables["SalesOrderHeader"];
EnumerableRowCollection query = from order in orders.AsEnumerable()
orderby order.Field("TotalDue")
@@ -394,10 +397,10 @@ orderby order.Field("TotalDue")
//
}
- private void button13_Click(object sender, EventArgs e)
+ void Button13_Click(object sender, EventArgs e)
{
//
- DataTable contacts = dataSet.Tables["Contact"];
+ DataTable contacts = _dataSet.Tables["Contact"];
DataView view = contacts.AsDataView();
@@ -411,10 +414,10 @@ private void button13_Click(object sender, EventArgs e)
//
}
- private void button14_Click(object sender, EventArgs e)
+ void Button14_Click(object sender, EventArgs e)
{
//
- DataTable contacts = dataSet.Tables["Contact"];
+ DataTable contacts = _dataSet.Tables["Contact"];
DataView view = contacts.AsDataView();
@@ -425,12 +428,12 @@ private void button14_Click(object sender, EventArgs e)
//
}
- private void button15_Click(object sender, EventArgs e)
+ void Button15_Click(object sender, EventArgs e)
{
//
- DataTable contacts = dataSet.Tables["Contact"];
+ DataTable contacts = _dataSet.Tables["Contact"];
- string soundExCode = SoundEx("Zhu");
+ var soundExCode = SoundEx("Zhu");
EnumerableRowCollection query = from contact in contacts.AsEnumerable()
where SoundEx(contact.Field("LastName")) == soundExCode
@@ -443,13 +446,13 @@ where SoundEx(contact.Field("LastName")) == soundExCode
//
}
- private void button16_Click(object sender, EventArgs e)
+ void Button16_Click(object sender, EventArgs e)
{
//
- DataTable orders = dataSet.Tables["SalesOrderDetail"];
+ DataTable orders = _dataSet.Tables["SalesOrderDetail"];
EnumerableRowCollection query = from order in orders.AsEnumerable()
- where order.Field("OrderQty") > 2 && order.Field("OrderQty") < 6
+ where order.Field("OrderQty") > 2 && order.Field("OrderQty") < 6
select order;
DataView view = query.AsDataView();
@@ -458,10 +461,10 @@ where order.Field("OrderQty") > 2 && order.Field("OrderQty") < 6
//
}
- private void button17_Click(object sender, EventArgs e)
+ void Button17_Click(object sender, EventArgs e)
{
//
- DataTable contacts = dataSet.Tables["Contact"];
+ DataTable contacts = _dataSet.Tables["Contact"];
EnumerableRowCollection query = from contact in contacts.AsEnumerable()
where contact.Field("LastName") == "Hernandez"
@@ -472,13 +475,13 @@ where contact.Field("LastName") == "Hernandez"
bindingSource1.DataSource = view;
dataGridView1.AutoResizeColumns();
- //
+ //
}
- private void button18_Click(object sender, EventArgs e)
+ void Button18_Click(object sender, EventArgs e)
{
//
- DataTable orders = dataSet.Tables["SalesOrderHeader"];
+ DataTable orders = _dataSet.Tables["SalesOrderHeader"];
EnumerableRowCollection query = from order in orders.AsEnumerable()
where order.Field("OrderDate") > new DateTime(2002, 6, 1)
@@ -490,10 +493,10 @@ private void button18_Click(object sender, EventArgs e)
//
}
- private void button19_Click(object sender, EventArgs e)
+ void Button19_Click(object sender, EventArgs e)
{
//
- DataTable contacts = dataSet.Tables["Contact"];
+ DataTable contacts = _dataSet.Tables["Contact"];
EnumerableRowCollection query = from contact in contacts.AsEnumerable()
where contact.Field("LastName").StartsWith("S")
@@ -508,10 +511,10 @@ orderby contact.Field("LastName"), contact.Field("FirstName")
//
}
- private void button20_Click(object sender, EventArgs e)
+ void Button20_Click(object sender, EventArgs e)
{
//
- DataTable orders = dataSet.Tables["SalesOrderHeader"];
+ DataTable orders = _dataSet.Tables["SalesOrderHeader"];
EnumerableRowCollection query = from order in orders.AsEnumerable()
where order.Field("OrderDate") > new DateTime(2002, 9, 15)
@@ -524,10 +527,10 @@ orderby order.Field("OrderDate"), order.Field("TotalDue")
//
}
- private void button21_Click(object sender, EventArgs e)
+ void Button21_Click(object sender, EventArgs e)
{
//
- DataTable contacts = dataSet.Tables["Contact"];
+ DataTable contacts = _dataSet.Tables["Contact"];
EnumerableRowCollection query = from contact in contacts.AsEnumerable()
orderby contact.Field("LastName")
@@ -536,33 +539,33 @@ orderby contact.Field("LastName")
DataView view = query.AsDataView();
// Find a contact with the last name of Zhu.
- int found = view.Find("Zhu");
+ var found = view.Find("Zhu");
//
}
- private void button22_Click(object sender, EventArgs e)
+ void Button22_Click(object sender, EventArgs e)
{
//
- DataTable products = dataSet.Tables["Product"];
+ DataTable products = _dataSet.Tables["Product"];
EnumerableRowCollection query = from product in products.AsEnumerable()
- orderby product.Field("ListPrice"), product.Field("Color")
+ orderby product.Field("ListPrice"), product.Field("Color")
select product;
DataView view = query.AsDataView();
view.Sort = "Color";
- object[] criteria = new object[] { "Red"};
+ var criteria = new object[] { "Red" };
DataRowView[] foundRowsView = view.FindRows(criteria);
//
}
- private void button23_Click(object sender, EventArgs e)
+ void Button23_Click(object sender, EventArgs e)
{
//
- DataTable contacts = dataSet.Tables["Contact"];
+ DataTable contacts = _dataSet.Tables["Contact"];
EnumerableRowCollection query = from contact in contacts.AsEnumerable()
where contact.Field("LastName") == "Hernandez"
@@ -577,14 +580,14 @@ where contact.Field("LastName") == "Hernandez"
//
}
- private void button24_Click(object sender, EventArgs e)
+ void Button24_Click(object sender, EventArgs e)
{
//
- DataTable orders = dataSet.Tables["SalesOrderHeader"];
+ DataTable orders = _dataSet.Tables["SalesOrderHeader"];
EnumerableRowCollection query = from order in orders.AsEnumerable()
where order.Field("OrderDate") > new DateTime(2002, 11, 20)
- && order.Field("TotalDue") < new Decimal(60.00)
+ && order.Field("TotalDue") < new decimal(60.00)
select order;
DataView view = query.AsDataView();
@@ -595,10 +598,10 @@ private void button24_Click(object sender, EventArgs e)
//
}
- private void button26_Click(object sender, EventArgs e)
+ void Button26_Click(object sender, EventArgs e)
{
//
- DataTable contacts = dataSet.Tables["Contact"];
+ DataTable contacts = _dataSet.Tables["Contact"];
DataView view = contacts.AsDataView();
@@ -612,10 +615,10 @@ private void button26_Click(object sender, EventArgs e)
//
}
- private void button25_Click(object sender, EventArgs e)
+ void Button25_Click(object sender, EventArgs e)
{
//
- DataTable orders = dataSet.Tables["SalesOrderHeader"];
+ DataTable orders = _dataSet.Tables["SalesOrderHeader"];
EnumerableRowCollection query = from order in orders.AsEnumerable()
orderby order.Field("OrderDate").Year
@@ -628,10 +631,9 @@ orderby order.Field("OrderDate").Year
//
}
- private void button27_Click(object sender, EventArgs e)
+ void Button27_Click(object sender, EventArgs e)
{
-
- DataTable products = dataSet.Tables["Product"];
+ DataTable products = _dataSet.Tables["Product"];
// Query for red colored products.
EnumerableRowCollection redProductsQuery =
@@ -645,29 +647,32 @@ orderby product.Field("ListPrice")
//
// Create a table from the bound view representing a query of
// available products.
- DataView view = (DataView)bindingSource1.DataSource;
- DataTable productsTable = (DataTable)view.Table;
+ var view = (DataView)bindingSource1.DataSource;
+ DataTable productsTable = view.Table;
// Set RowStateFilter to display the current rows.
- view.RowStateFilter = DataViewRowState.CurrentRows ;
+ view.RowStateFilter = DataViewRowState.CurrentRows;
// Query the DataView for red colored products ordered by list price.
var productQuery = from DataRowView rowView in view
where rowView.Row.Field("Color") == "Red"
orderby rowView.Row.Field("ListPrice")
- select new { Name = rowView.Row.Field("Name"),
- Color = rowView.Row.Field("Color"),
- Price = rowView.Row.Field("ListPrice")};
+ select new
+ {
+ Name = rowView.Row.Field("Name"),
+ Color = rowView.Row.Field("Color"),
+ Price = rowView.Row.Field("ListPrice")
+ };
// Bind the query results to another DataGridView.
dataGridView2.DataSource = productQuery.ToList();
//
}
- private void button28_Click(object sender, EventArgs e)
+ void Button28_Click(object sender, EventArgs e)
{
//
- DataTable products = dataSet.Tables["Product"];
+ DataTable products = _dataSet.Tables["Product"];
// Query for red colored products.
EnumerableRowCollection redProductsQuery =
@@ -677,8 +682,8 @@ orderby product.Field("ListPrice")
select product;
// Create a table and view from the query.
- DataTable redProducts = redProductsQuery.CopyToDataTable();
- DataView view = new DataView(redProducts);
+ DataTable redProducts = redProductsQuery.CopyToDataTable();
+ var view = new DataView(redProducts);
// Mark a row as deleted.
redProducts.Rows[0].Delete();
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DP DataView Samples/CS/Program.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DP DataView Samples/CS/Program.cs
index ce5538e24a5fa..3fc5ab04c221f 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DP DataView Samples/CS/Program.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DP DataView Samples/CS/Program.cs
@@ -1,6 +1,4 @@
using System;
-using System.Collections.Generic;
-using System.Linq;
using System.Windows.Forms;
namespace DataViewSamples
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DP DataViewWinForms Sample/CS/DataViewWinFormsSample.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DP DataViewWinForms Sample/CS/DataViewWinFormsSample.csproj
index c97e0412c57b5..189ef9c3e26ea 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DP DataViewWinForms Sample/CS/DataViewWinFormsSample.csproj
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DP DataViewWinForms Sample/CS/DataViewWinFormsSample.csproj
@@ -6,6 +6,10 @@
true
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DP DataViewWinForms Sample/CS/Form1.Designer.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DP DataViewWinForms Sample/CS/Form1.Designer.cs
index 04b12700b61f6..10a216a178717 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DP DataViewWinForms Sample/CS/Form1.Designer.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DP DataViewWinForms Sample/CS/Form1.Designer.cs
@@ -5,7 +5,7 @@ partial class Form1
///
/// Required designer variable.
///
- private System.ComponentModel.IContainer components = null;
+ System.ComponentModel.IContainer components = null;
///
/// Clean up any resources being used.
@@ -26,7 +26,7 @@ protected override void Dispose(bool disposing)
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
- private void InitializeComponent()
+ void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.contactDataGridView = new System.Windows.Forms.DataGridView();
@@ -60,8 +60,8 @@ private void InitializeComponent()
#endregion
- private System.Windows.Forms.DataGridView contactDataGridView;
- private System.Windows.Forms.BindingSource contactBindingSource;
+ System.Windows.Forms.DataGridView contactDataGridView;
+ System.Windows.Forms.BindingSource contactBindingSource;
}
}
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DP DataViewWinForms Sample/CS/Form1.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DP DataViewWinForms Sample/CS/Form1.cs
index 4f38229194e00..5b638d28f070b 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DP DataViewWinForms Sample/CS/Form1.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DP DataViewWinForms Sample/CS/Form1.cs
@@ -1,30 +1,22 @@
using System;
-using System.Collections.Generic;
-using System.ComponentModel;
using System.Data;
-using System.Drawing;
-using System.Linq;
-using System.Text;
-using System.Windows.Forms;
-using System.Data.Common;
using System.Data.SqlClient;
using System.Globalization;
+using System.Linq;
+using System.Windows.Forms;
namespace DataViewWinFormsSample
{
public partial class Form1 : Form
{
- private DataSet dataSet;
- private SqlDataAdapter contactsDataAdapter;
- private DataView contactView;
+ DataSet _dataSet;
+ SqlDataAdapter _contactsDataAdapter;
+ DataView _contactView;
- public Form1()
- {
- InitializeComponent();
- }
+ public Form1() => InitializeComponent();
//
- private void Form1_Load(object sender, EventArgs e)
+ void Form1_Load(object sender, EventArgs e)
{
// Connect to the database and fill the DataSet.
GetData();
@@ -33,47 +25,49 @@ private void Form1_Load(object sender, EventArgs e)
// Create a LinqDataView from a LINQ to DataSet query and bind it
// to the Windows forms control.
- EnumerableRowCollection contactQuery = from row in dataSet.Tables["Contact"].AsEnumerable()
+ EnumerableRowCollection contactQuery = from row in _dataSet.Tables["Contact"].AsEnumerable()
where row.Field("EmailAddress") != null
orderby row.Field("LastName")
select row;
- contactView = contactQuery.AsDataView();
+ _contactView = contactQuery.AsDataView();
// Bind the DataGridView to the BindingSource.
- contactBindingSource.DataSource = contactView;
+ contactBindingSource.DataSource = _contactView;
contactDataGridView.AutoResizeColumns();
}
//
//
- private void GetData()
+ void GetData()
{
try
{
// Initialize the DataSet.
- dataSet = new DataSet();
- dataSet.Locale = CultureInfo.InvariantCulture;
+ _dataSet = new DataSet
+ {
+ Locale = CultureInfo.InvariantCulture
+ };
// Create the connection string for the AdventureWorks sample database.
- string connectionString = "Data Source=localhost;Initial Catalog=AdventureWorks;"
+ const string connectionString = "Data Source=localhost;Initial Catalog=AdventureWorks;"
+ "Integrated Security=true;";
// Create the command strings for querying the Contact table.
- string contactSelectCommand = "SELECT ContactID, Title, FirstName, LastName, EmailAddress, Phone FROM Person.Contact";
+ const string contactSelectCommand = "SELECT ContactID, Title, FirstName, LastName, EmailAddress, Phone FROM Person.Contact";
// Create the contacts data adapter.
- contactsDataAdapter = new SqlDataAdapter(
+ _contactsDataAdapter = new SqlDataAdapter(
contactSelectCommand,
connectionString);
// Create a command builder to generate SQL update, insert, and
// delete commands based on the contacts select command. These are used to
// update the database.
- SqlCommandBuilder contactsCommandBuilder = new SqlCommandBuilder(contactsDataAdapter);
+ var contactsCommandBuilder = new SqlCommandBuilder(_contactsDataAdapter);
// Fill the data set with the contact information.
- contactsDataAdapter.Fill(dataSet, "Contact");
+ _contactsDataAdapter.Fill(_dataSet, "Contact");
}
catch (SqlException ex)
{
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DP DataViewWinForms Sample/CS/Program.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DP DataViewWinForms Sample/CS/Program.cs
index f5be2c1857669..d95901d107e2c 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DP DataViewWinForms Sample/CS/Program.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DP DataViewWinForms Sample/CS/Program.cs
@@ -1,6 +1,4 @@
using System;
-using System.Collections.Generic;
-using System.Linq;
using System.Windows.Forms;
namespace DataViewWinFormsSample
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DP LINQ to DataSet Examples/CS/LINQtoDataSetExamplesCS.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DP LINQ to DataSet Examples/CS/LINQtoDataSetExamplesCS.csproj
deleted file mode 100644
index 2ca85bd23b436..0000000000000
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DP LINQ to DataSet Examples/CS/LINQtoDataSetExamplesCS.csproj
+++ /dev/null
@@ -1,15 +0,0 @@
-
-
-
- Exe
- net48
- DP_LINQ_to_DataSet_Examples
- DP LINQ to DataSet Examples
-
-
-
-
-
-
-
-
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DP LINQ to DataSet Examples/CS/Program.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DP LINQ to DataSet Examples/CS/Program.cs
deleted file mode 100644
index bc0a1bdcfe87f..0000000000000
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DP LINQ to DataSet Examples/CS/Program.cs
+++ /dev/null
@@ -1,2703 +0,0 @@
-//
-using System;
-using System.Linq;
-using System.Linq.Expressions;
-using System.Collections.Generic;
-using System.Data;
-using System.Data.SqlClient;
-using System.Data.Common;
-using System.Globalization;
-//
-using System.Windows.Forms;
-
-namespace LINQtoDataSetSamples
-{
- class Program
- {
- static void Main(string[] args)
- {
- // Fill the DataSet.
- //DataSet ds = new DataSet();
- //ds.Locale = CultureInfo.InvariantCulture;
- //FillDataSet(ds);
- //DSInfo(ds);
- //WriteSchemaToXSD(ds);
-
- /*** Select Operators ***/
- //SelectSimple1();
- //SelectSimple2();
- //SelectAnonymousTypes_MQ();
- //SelectManyCompoundFrom();
- //SelectManyCompoundFrom_MQ();
- //SelectManyCompoundFrom2();
- //SelectManyCompoundFrom2_MQ();
- //SelectManyFromAssignment();
-
- /*** Restriction Operators ***/
- //Where1();
- //Where2();
- //Where3();
- //WhereDrilldown();
- //WhereIsNull();
-
- /*** Partitioning Operators ***/
- //TakeSimple();
- //SkipSimple();
- //TakeNested();
- //SkipNested();
- //TakeWhileSimple_MQ();
- //SkipWhileSimple_MQ(); // Need better example...
-
- /*** Ordering Operators ***/
- //OrderBySimple1();
- //OrderBySimple2();
- //OrderByComparer_MQ();
- //OrderByDescendingSimple1();
- //ThenByDescendingSimple();
- //ThenByDescendingComparer_MQ();
- //Reverse();
-
- /*** Grouping Operators ***/
- //GroupBySimple2();
- //GroupBySimple3();
- //GroupByNested();
-
- /*** Set Operators ***/
- //DistinctRows(); // Messy...
- //Distinct2(); // Pathetic...
- //Union2();
- //Intersect2();
- //Except2();
-
- /*** Conversion Operators ***/
- //ToArray();
- //ToArray2();
- //ToList();
- //ToDictionary();
- //OfType();
-
- /*** Element Operators ***/
- //FirstSimple();
- //FirstCondition_MQ();
- //ElementAt();
-
- /*** Generation Operators ***/
- //Range(); // Didn't use Range, couldn't get it to work.
-
- /*** Quantifier Operators ***/
- //AnyGrouped_MQ();
- //AllGrouped_MQ();
-
- /*** Aggregate Operators ***/
- //Aggregate_MQ();
- //Average_MQ();
- //Average2_MQ();
- //Count();
- //CountNested();
- //CountGrouped();
- //LongCountSimple();
- //SumProjection_MQ();
- //SumGrouped_MQ();
- //MinProjection_MQ();
- //MinGrouped_MQ();
- //MinElements_MQ();
- //AverageProjection_MQ();
- //AverageGrouped_MQ();
- //AverageElements_MQ();
- //MaxProjection_MQ();
- //MaxGrouped_MQ();
- MaxElements_MQ();
-
- /*** Join Operators ***/
- //Join();
- //JoinSimple_MQ();
- //JoinWithGroupedResults_MQ();
- //GroupJoin();
- //GroupJoin2();
-
- /*** DataSet Loading examples***/
- //LoadingQueryResultsIntoDataTable(); // Didn't include, need to update
- //LoadDataTableWithQueryResults();
-
- /*** DataRowComparer examples ***/
- //CompareDifferentDataRows();
- //CompareEqualDataRows();
- //CompareNullDataRows();
-
- /*** CopyToDataTable examples ***/
- //CopyToDataTable1();
-
- //*** Misc ***/
- //Composing();
-
- /*** Other stuff ***/
- //OrderBy();
- //OrderByDescending();
- //Sum();
- //GroupBy();
-
- Console.WriteLine("Hit Enter...");
- Console.Read();
- }
-
- #region "Select Operators"
-
- /*[Category("Projection Operators")]
- [Title("Select - Simple 1")]
- [Description("This example uses Select to return all the rows from the Product table and display the product names.")]*/
-
- static void SelectSimple1()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable products = ds.Tables["Product"];
-
- IEnumerable query =
- from product in products.AsEnumerable()
- select product;
-
- Console.WriteLine("Product Names:");
- foreach (DataRow p in query)
- {
- Console.WriteLine(p.Field("Name"));
- }
- //
- }
-
- /*[Category("Projection Operators")]
- [Title("Select - Simple 2")]
- [Description("This example uses Select to return a sequence of only product names.")]*/
- static void SelectSimple2()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable products = ds.Tables["Product"];
-
- IEnumerable query =
- from product in products.AsEnumerable()
- select product.Field("Name");
-
- Console.WriteLine("Product Names:");
- foreach (string productName in query)
- {
- Console.WriteLine(productName);
- }
- //
- }
-
- /*[Category("Projection Operators")]
- [Title("Select - Anonymous Types ")]
- [Description("This example uses Select to project the Name, ProductNumber, and
- ListPrice properties to a sequence of anonymous types. The ListPrice
- property is also renamed to Price in the resulting type.")]*/
- static void SelectAnonymousTypes_MQ()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable products = ds.Tables["Product"];
-
- var query = products.AsEnumerable().
- Select(product => new
- {
- ProductName = product.Field("Name"),
- ProductNumber = product.Field("ProductNumber"),
- Price = product.Field("ListPrice")
- });
-
- Console.WriteLine("Product Info:");
- foreach (var productInfo in query)
- {
- Console.WriteLine("Product name: {0} Product number: {1} List price: ${2} ",
- productInfo.ProductName, productInfo.ProductNumber, productInfo.Price);
- }
- //
- }
-
- /*[Category("Projection Operators")]
- [Title("SelectMany - Compound from")]
- [Description("This example uses a compound From clause to select all orders where " +
- " TotalDue is less than 500.00.")]*/
- static void SelectManyCompoundFrom()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable contacts = ds.Tables["Contact"];
- DataTable orders = ds.Tables["SalesOrderHeader"];
-
- var query =
- from contact in contacts.AsEnumerable()
- from order in orders.AsEnumerable()
- where contact.Field("ContactID") == order.Field("ContactID")
- && order.Field("TotalDue") < 500.00M
- select new
- {
- ContactID = contact.Field("ContactID"),
- LastName = contact.Field("LastName"),
- FirstName = contact.Field("FirstName"),
- OrderID = order.Field("SalesOrderID"),
- Total = order.Field("TotalDue")
- };
-
- foreach (var smallOrder in query)
- {
- Console.WriteLine("Contact ID: {0} Name: {1}, {2} Order ID: {3} Total Due: ${4} ",
- smallOrder.ContactID, smallOrder.LastName, smallOrder.FirstName,
- smallOrder.OrderID, smallOrder.Total);
- }
- //
- }
-
- /*[Category("Projection Operators")]
- [Title("SelectMany - Compound from using method syntax")]
- [Description("This example uses SelectMany to select all orders where " +
- " TotalDue is less than 500.00.")]*/
- static void SelectManyCompoundFrom_MQ()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- var contacts = ds.Tables["Contact"].AsEnumerable();
- var orders = ds.Tables["SalesOrderHeader"].AsEnumerable();
-
- var query =
- contacts.SelectMany(
- contact => orders.Where(order =>
- (contact.Field("ContactID") == order.Field("ContactID"))
- && order.Field("TotalDue") < 500.00M)
- .Select(order => new
- {
- ContactID = contact.Field("ContactID"),
- LastName = contact.Field("LastName"),
- FirstName = contact.Field("FirstName"),
- OrderID = order.Field("SalesOrderID"),
- Total = order.Field("TotalDue")
- }));
-
- foreach (var smallOrder in query)
- {
- Console.WriteLine("Contact ID: {0} Name: {1}, {2} Order ID: {3} Total Due: ${4} ",
- smallOrder.ContactID, smallOrder.LastName, smallOrder.FirstName,
- smallOrder.OrderID, smallOrder.Total);
- }
- //
- }
-
- /*[Category("Projection Operators")]
- [Title("SelectMany - Compound From 2")]
- [Description("This example uses a compound From clause to select all orders where the " +
- "order was made on October 1, 2002 or later.")]*/
- static void SelectManyCompoundFrom2()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable contacts = ds.Tables["Contact"];
- DataTable orders = ds.Tables["SalesOrderHeader"];
-
- var query =
- from contact in contacts.AsEnumerable()
- from order in orders.AsEnumerable()
- where contact.Field("ContactID") == order.Field("ContactID") &&
- order.Field("OrderDate") >= new DateTime(2002, 10, 1)
- select new
- {
- ContactID = contact.Field("ContactID"),
- LastName = contact.Field("LastName"),
- FirstName = contact.Field("FirstName"),
- OrderID = order.Field("SalesOrderID"),
- OrderDate = order.Field("OrderDate")
- };
-
- foreach (var order in query)
- {
- Console.WriteLine("Contact ID: {0} Name: {1}, {2} Order ID: {3} Order date: {4:d} ",
- order.ContactID, order.LastName, order.FirstName,
- order.OrderID, order.OrderDate);
- }
- //
- }
-
- /*[Category("Projection Operators")]
- [Title("SelectMany - Compound from 2, method-based query syntax")]
- [Description("This example uses SelectMany to select all orders where the " +
- "order was made on October 1, 2002 or later.")]*/
- static void SelectManyCompoundFrom2_MQ()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- var contacts = ds.Tables["Contact"].AsEnumerable();
- var orders = ds.Tables["SalesOrderHeader"].AsEnumerable();
-
- var query =
- contacts.SelectMany(
- contact => orders.Where(order =>
- (contact.Field("ContactID") == order.Field("ContactID"))
- && order.Field("OrderDate") >= new DateTime(2002, 10, 1))
- .Select(order => new
- {
- ContactID = contact.Field("ContactID"),
- LastName = contact.Field("LastName"),
- FirstName = contact.Field("FirstName"),
- OrderID = order.Field("SalesOrderID"),
- OrderDate = order.Field("OrderDate")
- }));
-
- foreach (var order in query)
- {
- Console.WriteLine("Contact ID: {0} Name: {1}, {2} Order ID: {3} Order date: {4:d} ",
- order.ContactID, order.LastName, order.FirstName,
- order.OrderID, order.OrderDate);
- }
- //
- }
-
- /*[Category("Projection Operators")]
- [Title("SelectMany - from Assignment")]
- [Description("This example uses a compound From clause to select all orders where the " +
- "order total is greater than 10000.00 and uses From assignment to avoid " +
- "requesting the total twice.")]*/
- static void SelectManyFromAssignment()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable contacts = ds.Tables["Contact"];
- DataTable orders = ds.Tables["SalesOrderHeader"];
-
- var query =
- from contact in contacts.AsEnumerable()
- from order in orders.AsEnumerable()
- let total = order.Field("TotalDue")
- where contact.Field("ContactID") == order.Field("ContactID") &&
- total >= 10000.0M
- select new
- {
- ContactID = contact.Field("ContactID"),
- LastName = contact.Field("LastName"),
- OrderID = order.Field("SalesOrderID"),
- total
- };
- foreach (var order in query)
- {
- Console.WriteLine("Contact ID: {0} Last name: {1} Order ID: {2} Total: {3}",
- order.ContactID, order.LastName, order.OrderID, order.total);
- }
-
- //
- }
- #endregion
-
- #region "Restriction Operators"
-
- /*[Category("Restriction Operators")]
- [Title("Where ")]
- [Description("This example returns all online orders.")]*/
- static void Where1()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable orders = ds.Tables["SalesOrderHeader"];
-
- var query =
- from order in orders.AsEnumerable()
- where order.Field("OnlineOrderFlag") == true
- select new
- {
- SalesOrderID = order.Field("SalesOrderID"),
- OrderDate = order.Field("OrderDate"),
- SalesOrderNumber = order.Field("SalesOrderNumber")
- };
-
- foreach (var onlineOrder in query)
- {
- Console.WriteLine("Order ID: {0} Order date: {1:d} Order number: {2}",
- onlineOrder.SalesOrderID,
- onlineOrder.OrderDate,
- onlineOrder.SalesOrderNumber);
- }
- //
- }
-
- /*[Category("Restriction Operators")]
- [Title("Where ")]
- [Description("This example returns the orders where the order quantity is greater than 2 and less than 6.")]*/
- static void Where2()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable orders = ds.Tables["SalesOrderDetail"];
-
- var query =
- from order in orders.AsEnumerable()
- where order.Field("OrderQty") > 2 &&
- order.Field("OrderQty") < 6
- select new
- {
- SalesOrderID = (int)order.Field("SalesOrderID"),
- OrderQty = order.Field("OrderQty")
- };
-
- foreach (var order in query)
- {
- Console.WriteLine("Order ID: {0} Order quantity: {1}",
- order.SalesOrderID, order.OrderQty);
- }
- //
- }
-
- /*[Category("Restriction Operators")]
- [Title("Where ")]
- [Description("This example returns all red colored products.")]*/
- static void Where3()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable products = ds.Tables["Product"];
-
- var query =
- from product in products.AsEnumerable()
- where product.Field("Color") == "Red"
- select new
- {
- Name = product.Field("Name"),
- ProductNumber = product.Field("ProductNumber"),
- ListPrice = product.Field("ListPrice")
- };
-
- foreach (var product in query)
- {
- Console.WriteLine("Name: {0}", product.Name);
- Console.WriteLine("Product number: {0}", product.ProductNumber);
- Console.WriteLine("List price: ${0}", product.ListPrice);
- Console.WriteLine("");
- }
- //
- }
-
- /*[Category("Restriction Operators")]
- [Title("Where ")]
- [Description("This example returns all red colored products. This query does not used the generic Field
- method, but explicitly checks column values for null.")]*/
- static void WhereIsNull()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable products = ds.Tables["Product"];
-
- var query =
- from product in products.AsEnumerable()
- where !product.IsNull("Color") &&
- (string)product["Color"] == "Red"
- select new
- {
- Name = product["Name"],
- ProductNumber = product["ProductNumber"],
- ListPrice = product["ListPrice"]
- };
-
- foreach (var product in query)
- {
- Console.WriteLine("Name: {0}", product.Name);
- Console.WriteLine("Product number: {0}", product.ProductNumber);
- Console.WriteLine("List price: ${0}", product.ListPrice);
- Console.WriteLine("");
- }
- //
- }
-
- /*[Category("Restriction Operators")]
- [Title("Where - Drilldown")]
- [Description("This example uses Where to find orders that were made after December 1, 2002 " +
- "and then uses the GetChildRows to get the details for each order.")]*/
- static void WhereDrilldown()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable orders = ds.Tables["SalesOrderHeader"];
-
- IEnumerable query =
- from order in orders.AsEnumerable()
- where order.Field("OrderDate") >= new DateTime(2002, 12, 1)
- select order;
-
- Console.WriteLine("Orders that were made after 12/1/2002:");
- foreach (DataRow order in query)
- {
- Console.WriteLine("OrderID {0} Order date: {1:d} ",
- order.Field("SalesOrderID"), order.Field("OrderDate"));
- foreach (DataRow orderDetail in order.GetChildRows("SalesOrderHeaderDetail"))
- {
- Console.WriteLine(" Product ID: {0} Unit Price {1}",
- orderDetail["ProductID"], orderDetail["UnitPrice"]);
- }
- }
- //
- }
- #endregion
-
- #region "Partitioning Operators"
-
- /*[Category("Partitioning Operators")]
- [Title("Take - Nested")]
- [Description("This example uses Take to get the first three addresses " +
- "in Seattle.")]*/
- static void TakeNested()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable addresses = ds.Tables["Address"];
- DataTable orders = ds.Tables["SalesOrderHeader"];
-
- var query = (
- from address in addresses.AsEnumerable()
- from order in orders.AsEnumerable()
- where address.Field("AddressID") == order.Field("BillToAddressID")
- && address.Field("City") == "Seattle"
- select new
- {
- City = address.Field("City"),
- OrderID = order.Field("SalesOrderID"),
- OrderDate = order.Field("OrderDate")
- }).Take(3);
-
- Console.WriteLine("First 3 orders in Seattle:");
- foreach (var order in query)
- {
- Console.WriteLine("City: {0} Order ID: {1} Total Due: {2:d}",
- order.City, order.OrderID, order.OrderDate);
- }
- //
- }
-
- /*[Category("Partitioning Operators")]
- [Title("Skip - Nested")]
- [Description("This example uses Skip to get all but the first two addresses " +
- "in Seattle.")]*/
- static void SkipNested()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable addresses = ds.Tables["Address"];
- DataTable orders = ds.Tables["SalesOrderHeader"];
-
- var query = (
- from address in addresses.AsEnumerable()
- from order in orders.AsEnumerable()
- where address.Field("AddressID") == order.Field("BillToAddressID")
- && address.Field("City") == "Seattle"
- select new
- {
- City = address.Field("City"),
- OrderID = order.Field("SalesOrderID"),
- OrderDate = order.Field("OrderDate")
- }).Skip(2);
-
- Console.WriteLine("All but first 2 orders in Seattle:");
- foreach (var order in query)
- {
- Console.WriteLine("City: {0} Order ID: {1} Total Due: {2:d}",
- order.City, order.OrderID, order.OrderDate);
- }
- //
- }
-
- /*[Category("Partitioning Operators")]
- [Title("Take - Simple")]
- [Description("This example uses Take to get only the first five contacts from the Contact table.")]*/
- static void TakeSimple()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable contacts = ds.Tables["Contact"];
-
- IEnumerable first5Contacts = contacts.AsEnumerable().Take(5);
-
- Console.WriteLine("First 5 contacts:");
- foreach (DataRow contact in first5Contacts)
- {
- Console.WriteLine("Title = {0} \t FirstName = {1} \t Lastname = {2}",
- contact.Field("Title"),
- contact.Field("FirstName"),
- contact.Field("Lastname"));
- }
- //
- }
-
- /*[Category("Partitioning Operators")]
- [Title("Skip - Simple")]
- [Description("This example uses Skip to get all but the first five contacts of the Contact table.")]*/
- static void SkipSimple()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable contacts = ds.Tables["Contact"];
-
- IEnumerable allButFirst5Contacts = contacts.AsEnumerable().Skip(5);
-
- Console.WriteLine("All but first 5 contacts:");
- foreach (DataRow contact in allButFirst5Contacts)
- {
- Console.WriteLine("FirstName = {0} \tLastname = {1}",
- contact.Field("FirstName"),
- contact.Field("Lastname"));
- }
- //
- }
-
- /*[Category("Partitioning Operators")]
- [Title("TakeWhile - Simple")]
- [Description("This example uses OrderBy and TakeWhile to return products from the Product table with a list price less than 300.00.")]*/
- static void TakeWhileSimple_MQ()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable products = ds.Tables["Product"];
-
- IEnumerable takeWhileListPriceLessThan300 =
- products.AsEnumerable()
- .OrderBy(listprice => listprice.Field("ListPrice"))
- .TakeWhile(product => product.Field("ListPrice") < 300.00M);
-
- Console.WriteLine("First ListPrice less than 300:");
- foreach (DataRow product in takeWhileListPriceLessThan300)
- {
- Console.WriteLine(product.Field("ListPrice"));
- }
- //
- }
-
- /*[Category("Partitioning Operators")]
- [Title("SkipWhile - Simple")]
- [Description("This example uses OrderBy and SkipWhile to return products from the Product table with a list price greater than 300.00.")]*/
-
- static void SkipWhileSimple_MQ()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable products = ds.Tables["Product"];
-
- IEnumerable skipWhilePriceLessThan300 =
- products.AsEnumerable()
- .OrderBy(listprice => listprice.Field("ListPrice"))
- .SkipWhile(product => product.Field("ListPrice") < 300.00M);
-
- Console.WriteLine("Skip while ListPrice is less than 300.00:");
- foreach (DataRow product in skipWhilePriceLessThan300)
- {
- Console.WriteLine(product.Field("ListPrice"));
- }
- //
- }
- #endregion
-
- #region "Ordering Operators"
-
- /*[Category("Ordering Operators")]
- [Title("OrderBy - Simple 1")]
- [Description("This example uses OrderBy to return a list of contacts ordered by last name.")]*/
- static void OrderBySimple1()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable contacts = ds.Tables["Contact"];
-
- IEnumerable query =
- from contact in contacts.AsEnumerable()
- orderby contact.Field("LastName")
- select contact;
-
- Console.WriteLine("The sorted list of last names:");
- foreach (DataRow contact in query)
- {
- Console.WriteLine(contact.Field("LastName"));
- }
- //
- }
-
- /*[Category("Ordering Operators")]
- [Title("OrderBy - Simple 2")]
- [Description("This example uses OrderBy to sort a list of contacts by length of last name.")]*/
- static void OrderBySimple2()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable contacts = ds.Tables["Contact"];
-
- IEnumerable query =
- from contact in contacts.AsEnumerable()
- orderby contact.Field("LastName").Length
- select contact;
-
- Console.WriteLine("The sorted list of last names (by length):");
- foreach (DataRow contact in query)
- {
- Console.WriteLine(contact.Field("LastName"));
- }
- //
- }
-
- /*[Category("Ordering Operators")]
- [Title("OrderBy - Comparer")]
- [Description("This example uses an OrderBy clause with a custom comparer to " +
- "do a case-insensitive sort of last names.")]
- [LinkedClass("CaseInsensitiveComparer")]*/
-
- //
- private class CaseInsensitiveComparer : IComparer
- {
- public int Compare(string x, string y)
- {
- return string.Compare(x, y, true, CultureInfo.InvariantCulture);
- }
- }
- //
- static void OrderByComparer_MQ()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable contacts = ds.Tables["Contact"];
-
- IEnumerable query =
- contacts.AsEnumerable().OrderBy(contact => contact.Field("LastName"),
- new CaseInsensitiveComparer());
-
- foreach (DataRow contact in query)
- {
- Console.WriteLine(contact.Field("LastName"));
- }
- //
- }
-
- /*[Category("Ordering Operators")]
- [Title("OrderByDescending - Simple 1")]
- [Description("This example uses OrderBy and Descending to sort the price list " +
- "from highest to lowest.")]*/
- static void OrderByDescendingSimple1()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable products = ds.Tables["Product"];
-
- IEnumerable query =
- from product in products.AsEnumerable()
- orderby product.Field("ListPrice") descending
- select product.Field("ListPrice");
-
- Console.WriteLine("The list price from highest to lowest:");
- foreach (Decimal product in query)
- {
- Console.WriteLine(product);
- }
- //
- }
-
- /*[Category("Ordering Operators")]
- [Title("ThenByDescending - Simple")]
- [Description("This example uses a compound OrderBy to sort a list of products, " +
- "first by name and then by list price, from highest to lowest.")]*/
- static void ThenByDescendingSimple()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable products = ds.Tables["Product"];
-
- IEnumerable query =
- from product in products.AsEnumerable()
- orderby product.Field("Name"),
- product.Field("ListPrice") descending
- select product;
-
- foreach (DataRow product in query)
- {
- Console.WriteLine("Product ID: {0} Product Name: {1} List Price {2}",
- product.Field("ProductID"),
- product.Field("Name"),
- product.Field("ListPrice"));
- }
- //
- }
-
- /*[Category("Ordering Operators")]
- [Title("ThenByDescending - Comparer")]
- [Description("This example uses OrderBy and ThenBy with a custom comparer to " +
- "first sort by list price, and then perform a case-insensitive descending sort " +
- "of the product names.")]
- [LinkedClass("CaseInsensitiveComparer")]*/
- static void ThenByDescendingComparer_MQ()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable products = ds.Tables["Product"];
-
- IEnumerable query =
- products.AsEnumerable().OrderBy(product => product.Field("ListPrice"))
- .ThenBy(product => product.Field("Name"),
- new CaseInsensitiveComparer());
-
- foreach (DataRow product in query)
- {
- Console.WriteLine("Product ID: {0} Product Name: {1} List Price {2}",
- product.Field("ProductID"),
- product.Field("Name"),
- product.Field("ListPrice"));
- }
- //
- }
- /*
- [Category("Ordering Operators")]
- [Title("Reverse")]
- [Description("This example uses Reverse to create a list of orders where OrderDate is earlier than Feb 20, 2002.")]*/
- static void Reverse()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable orders = ds.Tables["SalesOrderHeader"];
-
- IEnumerable query = (
- from order in orders.AsEnumerable()
- where order.Field("OrderDate") < new DateTime(2002, 02, 20)
- select order).Reverse();
-
- Console.WriteLine("A backwards list of orders where OrderDate < Feb 20, 2002");
- foreach (DataRow order in query)
- {
- Console.WriteLine(order.Field("OrderDate"));
- }
- //
- }
-
- #endregion
-
- #region "Grouping Operators"
-
- /*[Category("Grouping Operators")]
- [Title("GroupBy - Simple 2")]
- [Description("This example uses GroupBy to partition a list of contacts by the first letter of their last name.")]*/
- static void GroupBySimple2()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable contacts = ds.Tables["Contact"];
-
- var query = (
- from contact in contacts.AsEnumerable()
- group contact by contact.Field("LastName")[0] into g
- select new { FirstLetter = g.Key, Names = g }).
- OrderBy(letter => letter.FirstLetter);
-
- foreach (var contact in query)
- {
- Console.WriteLine("Last names that start with the letter '{0}':",
- contact.FirstLetter);
- foreach (var name in contact.Names)
- {
- Console.WriteLine(name.Field("LastName"));
- }
- }
- //
- }
-
- /*[Category("Grouping Operators")]
- [Title("GroupBy - Simple 3")]
- [Description("This example uses GroupBy to partition a list of addresses by postal code.")]*/
- static void GroupBySimple3()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable addresses = ds.Tables["Address"];
-
- var query =
- from address in addresses.AsEnumerable()
- group address by address.Field("PostalCode") into g
- select new { PostalCode = g.Key, AddressLine = g };
-
- foreach (var addressGroup in query)
- {
- Console.WriteLine("Postal Code: {0}", addressGroup.PostalCode);
- foreach (var address in addressGroup.AddressLine)
- {
- Console.WriteLine("\t" + address.Field("AddressLine1") +
- address.Field("AddressLine2"));
- }
- }
- //
- }
-
- /*[Category("Grouping Operators")]
- [Title("GroupBy - Nested")]
- [Description("This example uses GroupBy to partition a list of each contact's orders, " +
- "first by year, and then by month.")]*/
- static void GroupByNested()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable contacts = ds.Tables["Contact"];
-
- var query =
- from contact in contacts.AsEnumerable()
- select
- new
- {
- ContactID = contact.Field("ContactID"),
- YearGroups =
- from order in contact.GetChildRows("SalesOrderContact")
- group order by order.Field("OrderDate").Year into yg
- select
- new
- {
- Year = yg.Key,
- MonthGroups =
- from order in yg
- group order by order.Field("OrderDate").
- Month into mg
- select new { Month = mg.Key, Orders = mg }
- }
- };
-
- foreach (var contactGroup in query)
- {
- Console.WriteLine("ContactID = {0}", contactGroup.ContactID);
- foreach (var yearGroup in contactGroup.YearGroups)
- {
- Console.WriteLine("\t Year= {0}", yearGroup.Year);
- foreach (var monthGroup in yearGroup.MonthGroups)
- {
- Console.WriteLine("\t\t Month= {0}", monthGroup.Month);
- foreach (var order in monthGroup.Orders)
- {
- Console.WriteLine("\t\t\t OrderID= {0} ",
- order.Field("SalesOrderID"));
- Console.WriteLine("\t\t\t OrderDate= {0} ",
- order.Field("OrderDate"));
- }
- }
- }
- }
- //
- }
- #endregion
-
- #region "Set Operators"
- /*[Category("Set Operators")]
- [Title("DistinctRows")]
- [Description("This example uses Distinct to remove duplicate elements in a sequence.")]*/
-
- static void DistinctRows()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- List rows = new List();
-
- DataTable contact = ds.Tables["Contact"];
-
- // Get 100 rows from the Contact table.
- IEnumerable query = (from c in contact.AsEnumerable()
- select c).Take(100);
-
- DataTable contactsTableWith100Rows = query.CopyToDataTable();
-
- // Add 100 rows to the list.
- foreach (DataRow row in contactsTableWith100Rows.Rows)
- rows.Add(row);
-
- // Create duplicate rows by adding the same 100 rows to the list.
- foreach (DataRow row in contactsTableWith100Rows.Rows)
- rows.Add(row);
-
- DataTable table =
- System.Data.DataTableExtensions.CopyToDataTable(rows);
-
- // Find the unique contacts in the table.
- IEnumerable uniqueContacts =
- table.AsEnumerable().Distinct(DataRowComparer.Default);
-
- Console.WriteLine("Unique contacts:");
- foreach (DataRow uniqueContact in uniqueContacts)
- {
- Console.WriteLine(uniqueContact.Field("ContactID"));
- }
- //
- }
-
- /*[Category("Set Operators")]
- [Title("Distinct - 2")]
- [Description("This example uses Distinct to remove duplicate contacts.")]*/
- static void Distinct2()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable contacts1 = ds.Tables["Contact"];
-
- IEnumerable query = from contact in contacts1.AsEnumerable()
- where contact.Field("Title") == "Ms."
- select contact;
-
- DataTable contacts2 = query.CopyToDataTable();
-
- IEnumerable distinctContacts =
- contacts2.AsEnumerable().Distinct(DataRowComparer.Default);
-
- foreach (DataRow row in distinctContacts)
- {
- Console.WriteLine("Id: {0} {1} {2} {3}",
- row["ContactID"], row["Title"], row["FirstName"], row["LastName"]);
- }
- //
- }
-
- /*[Category("Set Operators")]
- [Title("Union - 2")]
- [Description("This example uses Union to return unique contacts from either of the two tables.")]*/
- static void Union2()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- // Create two tables.
- DataTable contactTable = ds.Tables["Contact"];
- IEnumerable query1 = from contact in contactTable.AsEnumerable()
- where contact.Field("Title") == "Ms."
- select contact;
-
- IEnumerable query2 = from contact in contactTable.AsEnumerable()
- where contact.Field("FirstName") == "Sandra"
- select contact;
-
- DataTable contacts1 = query1.CopyToDataTable();
- DataTable contacts2 = query2.CopyToDataTable();
-
- // Find the union of the two tables.
- var contacts = contacts1.AsEnumerable().Union(contacts2.AsEnumerable(),
- DataRowComparer.Default);
-
- Console.WriteLine("Union of contacts tables:");
- foreach (DataRow row in contacts)
- {
- Console.WriteLine("Id: {0} {1} {2} {3}",
- row["ContactID"], row["Title"], row["FirstName"], row["LastName"]);
- }
- //
- }
-
- /*[Category("Set Operators")]
- [Title("Intersect - 2")]
- [Description("This example uses Intersect to return contacts that appear in both tables.")]*/
- static void Intersect2()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable contactTable = ds.Tables["Contact"];
-
- // Create two tables.
- IEnumerable query1 = from contact in contactTable.AsEnumerable()
- where contact.Field("Title") == "Ms."
- select contact;
-
- IEnumerable query2 = from contact in contactTable.AsEnumerable()
- where contact.Field("FirstName") == "Sandra"
- select contact;
-
- DataTable contacts1 = query1.CopyToDataTable();
- DataTable contacts2 = query2.CopyToDataTable();
-
- // Find the intersection of the two tables.
- var contacts = contacts1.AsEnumerable().Intersect(contacts2.AsEnumerable(),
- DataRowComparer.Default);
-
- Console.WriteLine("Intersection of contacts tables");
- foreach (DataRow row in contacts)
- {
- Console.WriteLine("Id: {0} {1} {2} {3}",
- row["ContactID"], row["Title"], row["FirstName"], row["LastName"]);
- }
- //
- }
-
- /*[Category("Set Operators")]
- [Title("Except - 2")]
- [Description("This example uses Except to return contacts that appear in the first table but not in the second.")]*/
- static void Except2()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable contactTable = ds.Tables["Contact"];
-
- // Create two tables.
- IEnumerable query1 = from contact in contactTable.AsEnumerable()
- where contact.Field("Title") == "Ms."
- select contact;
-
- IEnumerable query2 = from contact in contactTable.AsEnumerable()
- where contact.Field("FirstName") == "Sandra"
- select contact;
-
- DataTable contacts1 = query1.CopyToDataTable();
- DataTable contacts2 = query2.CopyToDataTable();
-
- // Find the contacts that are in the first
- // table but not the second.
- var contacts = contacts1.AsEnumerable().Except(contacts2.AsEnumerable(),
- DataRowComparer.Default);
-
- Console.WriteLine("Except of employees tables");
- foreach (DataRow row in contacts)
- {
- Console.WriteLine("Id: {0} {1} {2} {3}",
- row["ContactID"], row["Title"], row["FirstName"], row["LastName"]);
- }
- //
- }
-
- #endregion
-
- #region "Conversion Operators"
- /*[Category("Conversion Operators")]
- [Title("ToArray")]
- [Description("This example uses ToArray to immediately evaluate a sequence into an array.")]*/
- static void ToArray()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable products = ds.Tables["Product"];
-
- IEnumerable productsArray = products.AsEnumerable().ToArray();
-
- IEnumerable query =
- from product in productsArray
- orderby product.Field("ListPrice") descending
- select product;
-
- Console.WriteLine("Every price from highest to lowest:");
- foreach (DataRow product in query)
- {
- Console.WriteLine(product.Field("ListPrice"));
- }
- //
- }
-
- /*[Category("Conversion Operators")]
- [Title("ToArray2")]
- [Description("This example uses ToArray to immediately evaluate a sequence into an array.")]*/
- static void ToArray2()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable products = ds.Tables["Product"];
-
- IEnumerable query =
- from product in products.AsEnumerable()
- orderby product.Field("ListPrice") descending
- select product;
-
- // Force immediate execution of the query.
- IEnumerable productsArray = query.ToArray();
-
- Console.WriteLine("Every price from highest to lowest:");
- foreach (DataRow prod in productsArray)
- {
- Console.WriteLine(prod.Field("ListPrice"));
- }
- //
- }
-
- /*[Category("Conversion Operators")]
- [Title("ToList")]
- [Description("This example uses ToList to immediately evaluate a sequence into a List, where T is of type DataRow.")]*/
- static void ToList()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable products = ds.Tables["Product"];
-
- IEnumerable productList = products.AsEnumerable().ToList();
-
- IEnumerable query =
- from product in productList
- orderby product.Field("Name")
- select product;
-
- Console.WriteLine("The product list, ordered by product name:");
- foreach (DataRow product in query)
- {
- Console.WriteLine(product.Field("Name").ToLower(CultureInfo.InvariantCulture));
- }
- //
- }
-
- /*[Category("Conversion Operators")]
- [Title("ToDictionary")]
- [Description("This example uses ToDictionary to immediately evaluate a sequence and a " +
- "related key expression into a dictionary.")]*/
- static void ToDictionary()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable products = ds.Tables["Product"];
-
- var scoreRecordsDict = products.AsEnumerable().
- ToDictionary(record => record.Field("Name"));
- Console.WriteLine("Top Tube's ProductID: {0}",
- scoreRecordsDict["Top Tube"]["ProductID"]);
- //
- }
-
- #endregion
-
- #region "Element Operators"
- /*[Category("Element Operators")]
- [Title("First - Simple")]
- [Description("This example uses First to return the first contact whose first name is 'Brooke'.")]*/
- static void FirstSimple()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable contacts = ds.Tables["Contact"];
-
- DataRow query = (
- from contact in contacts.AsEnumerable()
- where (string)contact["FirstName"] == "Brooke"
- select contact)
- .First();
-
- Console.WriteLine("ContactID: " + query.Field("ContactID"));
- Console.WriteLine("FirstName: " + query.Field("FirstName"));
- Console.WriteLine("LastName: " + query.Field("LastName"));
- //
- }
-
- /*[Category("Element Operators")]
- [Title("First - Condition")]
- [Description("This example uses First to find the first email address that starts with 'caroline'.")]*/
- static void FirstCondition_MQ()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable contacts = ds.Tables["Contact"];
-
- DataRow startsWith = contacts.AsEnumerable().
- First(contact => contact.Field("EmailAddress").StartsWith("caroline"));
-
- Console.WriteLine("An email address starting with 'caroline': {0}",
- startsWith.Field("EmailAddress"));
- //
- }
-
- /*[Category("Element Operators")]
- [Title("ElementAt")]
- [Description("This example uses ElementAt to retrieve the fifth address where PostalCode == "M4B 1V7" .")]*/
- static void ElementAt()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable addresses = ds.Tables["Address"];
-
- var fifthAddress = (
- from address in addresses.AsEnumerable()
- where address.Field("PostalCode") == "M4B 1V7"
- select address.Field("AddressLine1"))
- .ElementAt(5);
-
- Console.WriteLine("Fifth address where PostalCode = 'M4B 1V7': {0}",
- fifthAddress);
- //
- }
-
- #endregion
-
- #region "Quantifiers"
- /*[Category("Quantifiers")]
- [Title("Any - Grouped")]
- [Description("This example uses Any to return a price grouped by color, where list price is 0.")]*/
- static void AnyGrouped_MQ()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable products = ds.Tables["Product"];
-
- var query =
- from product in products.AsEnumerable()
- group product by product.Field("Color") into g
- where g.Any(product => product.Field("ListPrice") == 0)
- select new { Color = g.Key, Products = g };
-
- foreach (var productGroup in query)
- {
- Console.WriteLine(productGroup.Color);
- foreach (var product in productGroup.Products)
- {
- Console.WriteLine("\t {0}, {1}",
- product.Field("Name"),
- product.Field("ListPrice"));
- }
- }
- //
- }
-
- /*[Category("Quantifiers")]
- [Title("All - Grouped")]
- [Description("This example uses All to return all products where list price is greater than 0, grouped by color.")]*/
- static void AllGrouped_MQ()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable products = ds.Tables["Product"];
-
- var query =
- from product in products.AsEnumerable()
- group product by product.Field("Color") into g
- where g.All(product => product.Field("ListPrice") > 0)
- select new { Color = g.Key, Products = g };
-
- foreach (var productGroup in query)
- {
- Console.WriteLine(productGroup.Color);
- foreach (var product in productGroup.Products)
- {
- Console.WriteLine("\t {0}, {1}",
- product.Field("Name"),
- product.Field("ListPrice"));
- }
- }
- //
- }
- #endregion
-
- #region "Aggregate Operators"
-
- /*[Category("Aggregate Operators")]
- [Title("Aggregate")]
- [Description("This example gets the first 5 contacts from the Contact table and builds a comma-delimited list of the last names.")]*/
- static void Aggregate_MQ()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- IEnumerable contacts = ds.Tables["Contact"].AsEnumerable();
-
- string nameList =
- contacts.Take(5).Select(contact => contact.Field("LastName")).Aggregate((workingList, next) => workingList + "," + next);
-
- Console.WriteLine(nameList);
- //
- }
-
- /*[Category("Aggregate Operators")]
- [Title("Average")]
- [Description("This example uses Average to find the average list price of the products.")]*/
- static void Average_MQ()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- var products = ds.Tables["Product"].AsEnumerable();
-
- Decimal averageListPrice =
- products.Average(product => product.Field("ListPrice"));
-
- Console.WriteLine("The average list price of all the products is ${0}",
- averageListPrice);
- //
- }
-
- /*[Category("Aggregate Operators")]
- [Title("Average2")]
- [Description("This example uses Average to find the average list price of the products of each style.")]*/
- static void Average2_MQ()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- var products = ds.Tables["Product"].AsEnumerable();
-
- var query = from product in products
- group product by product.Field("Style") into g
- select new
- {
- Style = g.Key,
- AverageListPrice =
- g.Average(product => product.Field("ListPrice"))
- };
-
- foreach (var product in query)
- {
- Console.WriteLine("Product style: {0} Average list price: {1}",
- product.Style, product.AverageListPrice);
- }
- //
- }
-
- /*[Category("Aggregate Operators")]
- [Title("Count")]
- [Description("This example uses Count to return the number of products in the Product table.")]*/
- static void Count()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- var products = ds.Tables["Product"].AsEnumerable();
-
- int numProducts = products.Count();
-
- Console.WriteLine("There are {0} products.", numProducts);
- //
- }
-
- /*[Category("Aggregate Operators")]
- [Title("Count - Nested")]
- [Description("This example uses Count to return a list of contact IDs and how many orders " +
- "each has.")]*/
- static void CountNested()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable contacts = ds.Tables["Contact"];
-
- var query = from contact in contacts.AsEnumerable()
- select new
- {
- CustomerID = contact.Field("ContactID"),
- OrderCount =
- contact.GetChildRows("SalesOrderContact").Count()
- };
-
- foreach (var contact in query)
- {
- Console.WriteLine("CustomerID = {0} \t OrderCount = {1}",
- contact.CustomerID,
- contact.OrderCount);
- }
- //
- }
-
- /*[Category("Aggregate Operators")]
- [Title("Count - Grouped")]
- [Description("This example groups products by color and uses Count to return the number of products " +
- "in each color group.")]*/
- static void CountGrouped()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable products = ds.Tables["Product"];
-
- var query =
- from product in products.AsEnumerable()
- group product by product.Field("Color") into g
- select new { Color = g.Key, ProductCount = g.Count() };
-
- foreach (var product in query)
- {
- Console.WriteLine("Color = {0} \t ProductCount = {1}",
- product.Color,
- product.ProductCount);
- }
- //
- }
-
- /*[Category("Aggregate Operators")]
- [Title("Long Count Simple")]
- [Description("Gets the contact count as a long integer.")]*/
- static void LongCountSimple()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable contacts = ds.Tables["Contact"];
-
- long numberOfContacts = contacts.AsEnumerable().LongCount();
- Console.WriteLine("There are {0} Contacts", numberOfContacts);
- //
- }
-
- /*[Category("Aggregate Operators")]
- [Title("Sum - Projection")]
- [Description("This example uses Sum to get the total number of order quantities in the SalesOrderDetail table.")]*/
- static void SumProjection_MQ()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable orders = ds.Tables["SalesOrderDetail"];
-
- double totalOrderQty = orders.AsEnumerable().
- Sum(o => o.Field("OrderQty"));
- Console.WriteLine("There are a total of {0} OrderQty.",
- totalOrderQty);
- //
- }
-
- /*[Category("Aggregate Operators")]
- [Title("Sum - Grouped")]
- [Description("This example uses Sum to get the total due for each contact ID.")]*/
- static void SumGrouped_MQ()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable orders = ds.Tables["SalesOrderHeader"];
-
- var query =
- from order in orders.AsEnumerable()
- group order by order.Field("ContactID") into g
- select new
- {
- Category = g.Key,
- TotalDue = g.Sum(order => order.Field("TotalDue")),
- };
- foreach (var order in query)
- {
- Console.WriteLine("ContactID = {0} \t TotalDue sum = {1}",
- order.Category, order.TotalDue);
- }
- //
- }
-
- /*[Category("Aggregate Operators")]
- [Title("Min - Projection")]
- [Description("This example uses Min to get the smallest total due.")]*/
- static void MinProjection_MQ()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable orders = ds.Tables["SalesOrderHeader"];
-
- Decimal smallestTotalDue = orders.AsEnumerable().
- Min(totalDue => totalDue.Field("TotalDue"));
- Console.WriteLine("The smallest TotalDue is {0}.",
- smallestTotalDue);
- //
- }
-
- /*[Category("Aggregate Operators")]
- [Title("Min - Grouped")]
- [Description("This example uses Min to get the smallest total due for each contact ID.")]*/
- static void MinGrouped_MQ()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable orders = ds.Tables["SalesOrderHeader"];
-
- var query =
- from order in orders.AsEnumerable()
- group order by order.Field("ContactID") into g
- select new
- {
- Category = g.Key,
- smallestTotalDue =
- g.Min(order => order.Field("TotalDue"))
- };
-
- foreach (var order in query)
- {
- Console.WriteLine("ContactID = {0} \t Minimum TotalDue = {1}",
- order.Category, order.smallestTotalDue);
- }
- //
- }
-
- /*[Category("Aggregate Operators")]
- [Title("Min - Elements")]
- [Description("This example uses Min to get the orders with the smallest total due for each contact.")]*/
- static void MinElements_MQ()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable orders = ds.Tables["SalesOrderHeader"];
-
- var query =
- from order in orders.AsEnumerable()
- group order by order.Field("ContactID") into g
- let minTotalDue = g.Min(order => order.Field("TotalDue"))
- select new
- {
- Category = g.Key,
- smallestTotalDue =
- g.Where(order => order.Field("TotalDue") ==
- minTotalDue)
- };
-
- foreach (var orderGroup in query)
- {
- Console.WriteLine("ContactID: {0}", orderGroup.Category);
- foreach (var order in orderGroup.smallestTotalDue)
- {
- Console.WriteLine("Minimum TotalDue {0} for SalesOrderID {1}: ",
- order.Field("TotalDue"),
- order.Field("SalesOrderID"));
- }
- Console.WriteLine("");
- }
- //
- }
-
- /*[Category("Aggregate Operators")]
- [Title("Average - Projection")]
- [Description("This example uses Average to find the average total due.")]*/
- static void AverageProjection_MQ()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable orders = ds.Tables["SalesOrderHeader"];
-
- Decimal averageTotalDue = orders.AsEnumerable().
- Average(order => order.Field("TotalDue"));
- Console.WriteLine("The average TotalDue is {0}.",
- averageTotalDue);
- //
- }
-
- /*[Category("Aggregate Operators")]
- [Title("Average - Grouped")]
- [Description("This example uses Average to get the average total due for each contact ID.")]*/
- static void AverageGrouped_MQ()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable orders = ds.Tables["SalesOrderHeader"];
-
- var query =
- from order in orders.AsEnumerable()
- group order by order.Field("ContactID") into g
- select new
- {
- Category = g.Key,
- averageTotalDue =
- g.Average(order => order.Field("TotalDue"))
- };
-
- foreach (var order in query)
- {
- Console.WriteLine("ContactID = {0} \t Average TotalDue = {1}",
- order.Category,
- order.averageTotalDue);
- }
- //
- }
-
- /*[Category("Aggregate Operators")]
- [Title("Average - Elements")]
- [Description("This example uses Average to get the orders with the average TotalDue for each contact.")]*/
- static void AverageElements_MQ()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable orders = ds.Tables["SalesOrderHeader"];
-
- var query =
- from order in orders.AsEnumerable()
- group order by order.Field("ContactID") into g
- let averageTotalDue = g.Average(order => order.Field("TotalDue"))
- select new
- {
- Category = g.Key,
- CheapestProducts =
- g.Where(order => order.Field("TotalDue") ==
- averageTotalDue)
- };
-
- foreach (var orderGroup in query)
- {
- Console.WriteLine("ContactID: {0}", orderGroup.Category);
- foreach (var order in orderGroup.CheapestProducts)
- {
- Console.WriteLine("Average total due for SalesOrderID {1} is: {0}",
- order.Field("TotalDue"),
- order.Field("SalesOrderID"));
- }
- Console.WriteLine("");
- }
- //
- }
-
- /*[Category("Aggregate Operators")]
- [Title("Max - Projection")]
- [Description("This example uses Max to get the largest total due.")]*/
- static void MaxProjection_MQ()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable orders = ds.Tables["SalesOrderHeader"];
-
- Decimal maxTotalDue = orders.AsEnumerable().
- Max(w => w.Field("TotalDue"));
- Console.WriteLine("The maximum TotalDue is {0}.",
- maxTotalDue);
- //
- }
-
- /*[Category("Aggregate Operators")]
- [Title("Max - Grouped")]
- [Description("This example uses Max to get the largest total due for each contact ID.")]*/
- static void MaxGrouped_MQ()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable orders = ds.Tables["SalesOrderHeader"];
-
- var query =
- from order in orders.AsEnumerable()
- group order by order.Field("ContactID") into g
- select new
- {
- Category = g.Key,
- maxTotalDue =
- g.Max(order => order.Field("TotalDue"))
- };
-
- foreach (var order in query)
- {
- Console.WriteLine("ContactID = {0} \t Maximum TotalDue = {1}",
- order.Category, order.maxTotalDue);
- }
- //
- }
-
- /*[Category("Aggregate Operators")]
- [Title("Max - Elements")]
- [Description("This example uses Max to get the orders with the largest TotalDue for each contact ID.")]*/
- static void MaxElements_MQ()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable orders = ds.Tables["SalesOrderHeader"];
-
- var query =
- from order in orders.AsEnumerable()
- group order by order.Field("ContactID") into g
- let maxTotalDue = g.Max(order => order.Field("TotalDue"))
- select new
- {
- Category = g.Key,
- CheapestProducts =
- g.Where(order => order.Field("TotalDue") ==
- maxTotalDue)
- };
-
- foreach (var orderGroup in query)
- {
- Console.WriteLine("ContactID: {0}", orderGroup.Category);
- foreach (var order in orderGroup.CheapestProducts)
- {
- Console.WriteLine("MaxTotalDue {0} for SalesOrderID {1}: ",
- order.Field("TotalDue"),
- order.Field("SalesOrderID"));
- }
- }
- //
- }
- #endregion
-
- #region "Join Operators"
-
- /*[Category("Join Operators")]
- [Title("Join ")]
- [Description("This example performs a join over the SalesOrderHeader and SalesOrderDetail tables to get online orders from the month of August.")]*/
- static void Join()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable orders = ds.Tables["SalesOrderHeader"];
- DataTable details = ds.Tables["SalesOrderDetail"];
-
- var query =
- from order in orders.AsEnumerable()
- join detail in details.AsEnumerable()
- on order.Field("SalesOrderID") equals
- detail.Field("SalesOrderID")
- where order.Field("OnlineOrderFlag") == true
- && order.Field("OrderDate").Month == 8
- select new
- {
- SalesOrderID =
- order.Field("SalesOrderID"),
- SalesOrderDetailID =
- detail.Field("SalesOrderDetailID"),
- OrderDate =
- order.Field("OrderDate"),
- ProductID =
- detail.Field("ProductID")
- };
-
- foreach (var order in query)
- {
- Console.WriteLine("{0}\t{1}\t{2:d}\t{3}",
- order.SalesOrderID,
- order.SalesOrderDetailID,
- order.OrderDate,
- order.ProductID);
- }
- //
- }
-
- /*[Category("Join Operators")]
- [Title("Join - simple")]
- [Description("This example performs a join over the Contact and SalesOrderHeader tables.")]*/
- static void JoinSimple_MQ()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable contacts = ds.Tables["Contact"];
- DataTable orders = ds.Tables["SalesOrderHeader"];
-
- var query =
- contacts.AsEnumerable().Join(orders.AsEnumerable(),
- order => order.Field("ContactID"),
- contact => contact.Field("ContactID"),
- (contact, order) => new
- {
- ContactID = contact.Field("ContactID"),
- SalesOrderID = order.Field("SalesOrderID"),
- FirstName = contact.Field("FirstName"),
- Lastname = contact.Field("Lastname"),
- TotalDue = order.Field("TotalDue")
- });
-
- foreach (var contact_order in query)
- {
- Console.WriteLine("ContactID: {0} "
- + "SalesOrderID: {1} "
- + "FirstName: {2} "
- + "Lastname: {3} "
- + "TotalDue: {4}",
- contact_order.ContactID,
- contact_order.SalesOrderID,
- contact_order.FirstName,
- contact_order.Lastname,
- contact_order.TotalDue);
- }
- //
- }
-
- /*[Category("Join Operators")]
- [Title("Join with grouped results")]
- [Description("This example performs a join over the Contact and SalesOrderHeader tables, grouping the results by contact ID.")]*/
- static void JoinWithGroupedResults_MQ()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable contacts = ds.Tables["Contact"];
- DataTable orders = ds.Tables["SalesOrderHeader"];
-
- var query = contacts.AsEnumerable().Join(orders.AsEnumerable(),
- order => order.Field("ContactID"),
- contact => contact.Field("ContactID"),
- (contact, order) => new
- {
- ContactID = contact.Field("ContactID"),
- SalesOrderID = order.Field("SalesOrderID"),
- FirstName = contact.Field("FirstName"),
- Lastname = contact.Field("Lastname"),
- TotalDue = order.Field("TotalDue")
- })
- .GroupBy(record => record.ContactID);
-
- foreach (var group in query)
- {
- foreach (var contact_order in group)
- {
- Console.WriteLine("ContactID: {0} "
- + "SalesOrderID: {1} "
- + "FirstName: {2} "
- + "Lastname: {3} "
- + "TotalDue: {4}",
- contact_order.ContactID,
- contact_order.SalesOrderID,
- contact_order.FirstName,
- contact_order.Lastname,
- contact_order.TotalDue);
- }
- }
- //
- }
-
- /*[Category("Join Operators")]
- [Title("GroupJoin2")]
- [Description("This example performs a GroupJoin over the SalesOrderHeader and SalesOrderDetail tables to find the number of orders per customer. " +
- "A group join is the equivalent of a left outer join, which returns each element of the first (left) data source, " +
- "even if no correlated elements are in the other data source.")]*/
- static void GroupJoin2()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- var orders = ds.Tables["SalesOrderHeader"].AsEnumerable();
- var details = ds.Tables["SalesOrderDetail"].AsEnumerable();
-
- var query =
- from order in orders
- join detail in details
- on order.Field("SalesOrderID")
- equals detail.Field("SalesOrderID") into ords
- select new
- {
- CustomerID =
- order.Field("SalesOrderID"),
- ords = ords.Count()
- };
-
- foreach (var order in query)
- {
- Console.WriteLine("CustomerID: {0} Orders Count: {1}",
- order.CustomerID,
- order.ords);
- }
- //
- }
- /*[Category("Join Operators")]
- [Title("GroupJoin")]
- [Description("This example performs a group join over the Contact and SalesOrderHeader tables. " +
- "A group join is the equivalent of a left outer join, which returns each element of the first (left) data source, " +
- "even if no correlated elements are in the other data source.")]*/
- static void GroupJoin()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable contacts = ds.Tables["Contact"];
- DataTable orders = ds.Tables["SalesOrderHeader"];
-
- var query =
- from contact in contacts.AsEnumerable()
- join order in orders.AsEnumerable()
- on contact.Field("ContactID") equals
- order.Field("ContactID")
- select new
- {
- ContactID = contact.Field("ContactID"),
- SalesOrderID = order.Field("SalesOrderID"),
- FirstName = contact.Field("FirstName"),
- Lastname = contact.Field("Lastname"),
- TotalDue = order.Field("TotalDue")
- };
-
- foreach (var contact_order in query)
- {
- Console.WriteLine("ContactID: {0} "
- + "SalesOrderID: {1} "
- + "FirstName: {2} "
- + "Lastname: {3} "
- + "TotalDue: {4}",
- contact_order.ContactID,
- contact_order.SalesOrderID,
- contact_order.FirstName,
- contact_order.Lastname,
- contact_order.TotalDue);
- }
- //
- }
- #endregion
-
- #region "DataSet Loading examples"
- /*[Category("DataSet Loading examples")]
- [Title("Loading query results into a DataTable")]
- [Description("This example creates and loads a DataTable from a sequence. A new table is created and filled manually, " +
- "instead of using the CopyToDataTable() method, because of the projection in the query.")]*/
- static void LoadingQueryResultsIntoDataTable()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable contacts = ds.Tables["Contact"];
- DataTable orders = ds.Tables["SalesOrderHeader"];
-
- var query =
- from contact in contacts.AsEnumerable()
- from order in orders.AsEnumerable()
- where contact.Field("ContactID") == order.Field("ContactID") &&
- order.Field("OnlineOrderFlag") == true
- select new
- {
- FirstName = (string)contact["FirstName"],
- LastName = (string)contact["LastName"],
- OrderDate = (DateTime)order["OrderDate"],
- TotalDue = (decimal)order["TotalDue"]
- };
-
- DataTable OnlineOrders = new DataTable();
- OnlineOrders.Locale = CultureInfo.InvariantCulture;
- OnlineOrders.Columns.Add("FirstName", typeof(string));
- OnlineOrders.Columns.Add("LastName", typeof(string));
- OnlineOrders.Columns.Add("OrderDate", typeof(DateTime));
- OnlineOrders.Columns.Add("TotalDue", typeof(decimal));
-
- foreach (var result in query.Take(10))
- {
- OnlineOrders.Rows.Add(new object[] {
- result.FirstName,
- result.LastName,
- result.OrderDate,
- result.TotalDue });
- }
-
- foreach (DataRow row in OnlineOrders.Rows)
- {
- Console.WriteLine("First Name: {0}", row["FirstName"]);
- Console.WriteLine("Last Name: {0}", row["LastName"]);
- Console.WriteLine("Order Date: {0}", row["OrderDate"]);
- Console.WriteLine("Total Due: ${0}", row["TotalDue"]);
- Console.WriteLine("");
- }
- //
- }
-
- /*[Category("DataSet Loading examples")]
- [Title("Using CopyToDataTable")]
- [Description("This example loads a DataTable with query results by using the CopyToDataTable() method.")]*/
- static void LoadDataTableWithQueryResults()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable contacts1 = ds.Tables["Contact"];
-
- IEnumerable query =
- from contact in contacts1.AsEnumerable()
- where contact.Field("Title") == "Ms."
- && contact.Field("FirstName") == "Carla"
- select contact;
-
- DataTable contacts2 = query.CopyToDataTable();
-
- foreach (DataRow contact in contacts2.AsEnumerable())
- {
- Console.WriteLine("ID:{0} Name: {1}, {2}",
- contact.Field("ContactID"),
- contact.Field("LastName"),
- contact.Field("FirstName"));
- }
- //
- }
-
- static void CopyToDataTable1()
- {
- DataGridView dataGridView = new DataGridView();
- BindingSource bindingSource = new BindingSource();
-
- //
- // Bind the System.Windows.Forms.DataGridView object
- // to the System.Windows.Forms.BindingSource object.
- dataGridView.DataSource = bindingSource;
-
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable orders = ds.Tables["SalesOrderHeader"];
-
- // Query the SalesOrderHeader table for orders placed
- // after August 8, 2001.
- IEnumerable query =
- from order in orders.AsEnumerable()
- where order.Field("OrderDate") > new DateTime(2001, 8, 1)
- select order;
-
- // Create a table from the query.
- DataTable boundTable = query.CopyToDataTable();
-
- // Bind the table to a System.Windows.Forms.BindingSource object,
- // which acts as a proxy for a System.Windows.Forms.DataGridView object.
- bindingSource.DataSource = boundTable;
- //
-
- foreach (DataRow row in boundTable.Rows)
- {
- Console.WriteLine(row["SalesOrderNumber"] + " " + row["OrderDate"]);
- }
- }
- #endregion
-
- #region "DataRowComparer examples"
- /*[Category("DataRowComparer examples")]
- [Title("Compare different data rows")]
- [Description("This example compares two different data rows.")]*/
-
- static void CompareDifferentDataRows()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- // Get two rows from the SalesOrderHeader table.
- DataTable table = ds.Tables["SalesOrderHeader"];
- DataRow left = (DataRow)table.Rows[0];
- DataRow right = (DataRow)table.Rows[1];
-
- // Compare the two different rows.
- IEqualityComparer comparer = DataRowComparer.Default;
-
- bool bEqual = comparer.Equals(left, right);
- if (bEqual)
- Console.WriteLine("The two rows are equal");
- else
- Console.WriteLine("The two rows are not equal");
-
- // Get the hash codes of the two rows.
- Console.WriteLine("The hashcodes for the two rows are {0}, {1}",
- comparer.GetHashCode(left),
- comparer.GetHashCode(right));
- //
- }
-
- /*[Category("DataRowComparer examples")]
- [Title("Compare equal data rows")]
- [Description("This example compares two equal data rows.")]*/
- static void CompareEqualDataRows()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- // Get a row from the SalesOrderHeader table.
- DataTable table = ds.Tables["SalesOrderHeader"];
- DataRow left = (DataRow)table.Rows[0];
- DataRow right = (DataRow)table.Rows[0];
-
- // Compare two equal rows.
- IEqualityComparer comparer = DataRowComparer.Default;
-
- bool bEqual = comparer.Equals(left, right);
- if (bEqual)
- Console.WriteLine("The two rows are equal");
- else
- Console.WriteLine("The two rows are not equal");
-
- // Get the hash codes of the two rows.
- Console.WriteLine("The hashcodes for the two rows are {0}, {1}",
- comparer.GetHashCode(left),
- comparer.GetHashCode(right));
- //
- }
-
- /*[Category("DataRowComparer examples")]
- [Title("Compare null data row")]
- [Description("This example compares a data row with a null value.")]*/
- static void CompareNullDataRows()
- {
- //
- // Compare with null.
- DataTable table = new DataTable();
- table.Locale = CultureInfo.InvariantCulture;
- DataRow dr = table.NewRow();
-
- IEqualityComparer comparer = DataRowComparer.Default;
-
- try
- {
- comparer.Equals(null, dr);
- }
- catch (ArgumentNullException)
- {
- Console.WriteLine("ArgumentNullException is thrown if parameter is null");
- }
- //
- }
- #endregion
-
- #region Misc
-
- static void Composing()
- {
- //
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
-
- DataTable products = ds.Tables["Product"];
-
- IEnumerable productsQuery =
- from product in products.AsEnumerable()
- select product;
-
- IEnumerable largeProducts =
- productsQuery.Where(p => p.Field("Size") == "L");
-
- Console.WriteLine("Products of size 'L':");
- foreach (DataRow product in largeProducts)
- {
- Console.WriteLine(product.Field("Name"));
- }
-
- //
- }
-
- #endregion
-
- // Leftovers...
-
- static void OrderBy(DataSet ds)
- {
- //
- DataTable orders = ds.Tables["SalesOrderDetail"];
-
- // Order by unit price.
- var query =
- from order in orders.AsEnumerable()
- where order.Field("OrderQty") > 2 &&
- order.Field("OrderQty") < 6
- orderby order.Field("UnitPrice")
- select new
- {
- SalesOrderID = (int)order.Field("SalesOrderID"),
- OrderQty = order.Field("OrderQty"),
- UnitPrice = order.Field("UnitPrice")
- };
-
- foreach (var order in query)
- {
- Console.WriteLine("{0}\t{1}\t{2}",
- order.SalesOrderID, order.OrderQty, order.UnitPrice);
- }
- //
- }
-
- static void OrderByDescending(DataSet ds)
- {
- //
- DataTable orders = ds.Tables["SalesOrderDetail"];
-
- // Order by unit price.
- var query =
- from order in orders.AsEnumerable()
- where order.Field("OrderQty") > 2 &&
- order.Field("OrderQty") < 6
- orderby order.Field("UnitPrice") descending
- select new
- {
- SalesOrderID = (int)order.Field("SalesOrderID"),
- OrderQty = order.Field("OrderQty"),
- UnitPrice = order.Field("UnitPrice")
- };
-
- foreach (var order in query)
- {
- Console.WriteLine("{0}\t{1}\t{2}",
- order.SalesOrderID, order.OrderQty, order.UnitPrice);
- }
- //
- }
-
- static void GroupBy(DataSet ds)
- {
- DataTable products = ds.Tables["Product"];
-
- // Group by size.
- var query =
- from product in products.AsEnumerable()
- group product by product.Field("Size") into g
- select new
- {
- Category = g.Key,
- Products = g
- };
-
- foreach (var productGroup in query)
- {
- Console.WriteLine("{0}:", productGroup.Category);
- foreach (var product in productGroup.Products)
- {
- Console.WriteLine(" Name: {0} Color: {1}",
- product.Field("Name"),
- product.Field("Color"));
- Console.WriteLine(" List price: {0} Size: {1}",
- product.Field("ListPrice"),
- product.Field("Size"));
- }
- }
- }
-
- static void Sum(DataSet ds)
- {
- var orders = ds.Tables["SalesOrderHeader"].AsEnumerable();
-
- Decimal totalDue = orders.Sum(o => o.Field("TotalDue"));
-
- Console.WriteLine("Sum of order amounts: ${0}", totalDue);
- }
-
- static void Sum2(DataSet ds)
- {
- var employees = ds.Tables["Employee"].AsEnumerable();
-
- var empSickLeaveHours =
- from e in employees
- group e by e.Field("Title") into g
- select new
- {
- Category = g.Key,
- TotalSickLeaveHours =
- g.Sum(p => p.Field("SickLeaveHours"))
- };
-
- foreach (var emp in empSickLeaveHours)
- {
- Console.WriteLine("Category: {0} Units sold: {1}",
- emp.Category, emp.TotalSickLeaveHours);
- }
- }
-
- // Display DataSet info. This will not be used in the docs.
- static void DSInfo(DataSet ds)
- {
- Console.WriteLine("DataSet info:");
- foreach (DataTable t in ds.Tables)
- {
- Console.WriteLine("Table name: {0}", t.TableName);
- Console.WriteLine("Number of rows: {0}", t.Rows.Count);
-
- foreach (DataColumn c in t.Columns)
- {
- Console.WriteLine("Column name: {0}, Type {1}",
- c.ColumnName, c.DataType);
- }
-
- Console.WriteLine("");
- }
- }
-
- static void FillDataSet(DataSet ds)
- {
- //
- try
- {
- // Create a new adapter and give it a query to fetch sales order, contact,
- // address, and product information for sales in the year 2002. Point connection
- // information to the configuration setting "AdventureWorks".
- string connectionString = "Data Source=localhost;Initial Catalog=AdventureWorks;"
- + "Integrated Security=true;";
-
- SqlDataAdapter da = new SqlDataAdapter(
- "SELECT SalesOrderID, ContactID, OrderDate, OnlineOrderFlag, " +
- "TotalDue, SalesOrderNumber, Status, ShipToAddressID, BillToAddressID " +
- "FROM Sales.SalesOrderHeader " +
- "WHERE DATEPART(YEAR, OrderDate) = @year; " +
-
- "SELECT d.SalesOrderID, d.SalesOrderDetailID, d.OrderQty, " +
- "d.ProductID, d.UnitPrice " +
- "FROM Sales.SalesOrderDetail d " +
- "INNER JOIN Sales.SalesOrderHeader h " +
- "ON d.SalesOrderID = h.SalesOrderID " +
- "WHERE DATEPART(YEAR, OrderDate) = @year; " +
-
- "SELECT p.ProductID, p.Name, p.ProductNumber, p.MakeFlag, " +
- "p.Color, p.ListPrice, p.Size, p.Class, p.Style, p.Weight " +
- "FROM Production.Product p; " +
-
- "SELECT DISTINCT a.AddressID, a.AddressLine1, a.AddressLine2, " +
- "a.City, a.StateProvinceID, a.PostalCode " +
- "FROM Person.Address a " +
- "INNER JOIN Sales.SalesOrderHeader h " +
- "ON a.AddressID = h.ShipToAddressID OR a.AddressID = h.BillToAddressID " +
- "WHERE DATEPART(YEAR, OrderDate) = @year; " +
-
- "SELECT DISTINCT c.ContactID, c.Title, c.FirstName, " +
- "c.LastName, c.EmailAddress, c.Phone " +
- "FROM Person.Contact c " +
- "INNER JOIN Sales.SalesOrderHeader h " +
- "ON c.ContactID = h.ContactID " +
- "WHERE DATEPART(YEAR, OrderDate) = @year;",
- connectionString);
-
- // Add table mappings.
- da.SelectCommand.Parameters.AddWithValue("@year", 2002);
- da.TableMappings.Add("Table", "SalesOrderHeader");
- da.TableMappings.Add("Table1", "SalesOrderDetail");
- da.TableMappings.Add("Table2", "Product");
- da.TableMappings.Add("Table3", "Address");
- da.TableMappings.Add("Table4", "Contact");
-
- // Fill the DataSet.
- da.Fill(ds);
-
- // Add data relations.
- DataTable orderHeader = ds.Tables["SalesOrderHeader"];
- DataTable orderDetail = ds.Tables["SalesOrderDetail"];
- DataRelation order = new DataRelation("SalesOrderHeaderDetail",
- orderHeader.Columns["SalesOrderID"],
- orderDetail.Columns["SalesOrderID"], true);
- ds.Relations.Add(order);
-
- DataTable contact = ds.Tables["Contact"];
- DataTable orderHeader2 = ds.Tables["SalesOrderHeader"];
- DataRelation orderContact = new DataRelation("SalesOrderContact",
- contact.Columns["ContactID"],
- orderHeader2.Columns["ContactID"], true);
- ds.Relations.Add(orderContact);
- }
- catch (SqlException ex)
- {
- Console.WriteLine("SQL exception occurred: " + ex.Message);
- }
- //
- }
-
- static void WriteSchemaToXSD(DataSet ds)
- {
- System.IO.StreamWriter writer = new System.IO.StreamWriter("ProductSalesSchema.xsd");
- ds.WriteXmlSchema(writer);
- writer.Close();
- Console.WriteLine("Schema written.");
- }
- }
-}
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks BulkCopy.Single/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks BulkCopy.Single/CS/Project.csproj
new file mode 100644
index 0000000000000..9659b3497e484
--- /dev/null
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks BulkCopy.Single/CS/Project.csproj
@@ -0,0 +1,12 @@
+
+
+
+ Library
+ net6.0
+ enable
+
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks BulkCopy.Single/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks BulkCopy.Single/CS/source.cs
index 59114babed462..bf30b6b95ed40 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks BulkCopy.Single/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks BulkCopy.Single/CS/source.cs
@@ -1,30 +1,29 @@
using System;
-using System.Data;
//
using System.Data.SqlClient;
-class Program
+static class Program
{
static void Main()
{
- string connectionString = GetConnectionString();
+ var connectionString = GetConnectionString();
// Open a sourceConnection to the AdventureWorks database.
using (SqlConnection sourceConnection =
- new SqlConnection(connectionString))
+ new(connectionString))
{
sourceConnection.Open();
// Perform an initial count on the destination table.
- SqlCommand commandRowCount = new SqlCommand(
+ SqlCommand commandRowCount = new(
"SELECT COUNT(*) FROM " +
"dbo.BulkCopyDemoMatchingColumns;",
sourceConnection);
- long countStart = System.Convert.ToInt32(
+ long countStart = Convert.ToInt32(
commandRowCount.ExecuteScalar());
Console.WriteLine("Starting row count = {0}", countStart);
// Get data from the source table as a SqlDataReader.
- SqlCommand commandSourceData = new SqlCommand(
+ SqlCommand commandSourceData = new(
"SELECT ProductID, Name, " +
"ProductNumber " +
"FROM Production.Product;", sourceConnection);
@@ -35,7 +34,7 @@ static void Main()
// not use SqlBulkCopy to move data from one table to the other
// in the same database. This is for demonstration purposes only.
using (SqlConnection destinationConnection =
- new SqlConnection(connectionString))
+ new(connectionString))
{
destinationConnection.Open();
@@ -45,7 +44,7 @@ static void Main()
// the destination table so there is no need to
// map columns.
using (SqlBulkCopy bulkCopy =
- new SqlBulkCopy(destinationConnection))
+ new(destinationConnection))
{
bulkCopy.DestinationTableName =
"dbo.BulkCopyDemoMatchingColumns";
@@ -70,7 +69,7 @@ static void Main()
// Perform a final count on the destination
// table to see how many rows were added.
- long countEnd = System.Convert.ToInt32(
+ long countEnd = Convert.ToInt32(
commandRowCount.ExecuteScalar());
Console.WriteLine("Ending row count = {0}", countEnd);
Console.WriteLine("{0} rows were added.", countEnd - countStart);
@@ -80,9 +79,9 @@ static void Main()
}
}
- private static string GetConnectionString()
- // To avoid storing the sourceConnection string in your code,
- // you can retrieve it from a configuration file.
+ static string GetConnectionString()
+ // To avoid storing the sourceConnection string in your code,
+ // you can retrieve it from a configuration file.
{
return "Data Source=(local); " +
" Integrated Security=true;" +
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfig/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfig/CS/Project.csproj
new file mode 100644
index 0000000000000..5f32e737b1eb5
--- /dev/null
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfig/CS/Project.csproj
@@ -0,0 +1,13 @@
+
+
+
+ Library
+ net6.0
+ enable
+
+
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfig/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfig/CS/source.cs
index 38e2992f164fc..f1abb875c31e2 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfig/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfig/CS/source.cs
@@ -3,7 +3,7 @@
//
using System.Configuration;
-class Program
+static class Program
{
static void Main()
{
@@ -16,14 +16,11 @@ static void GetConnectionStrings()
ConnectionStringSettingsCollection settings =
ConfigurationManager.ConnectionStrings;
- if (settings != null)
+ foreach (ConnectionStringSettings cs in settings)
{
- foreach(ConnectionStringSettings cs in settings)
- {
- Console.WriteLine(cs.Name);
- Console.WriteLine(cs.ProviderName);
- Console.WriteLine(cs.ConnectionString);
- }
+ Console.WriteLine(cs.Name);
+ Console.WriteLine(cs.ProviderName);
+ Console.WriteLine(cs.ConnectionString);
}
}
}
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfigByName/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfigByName/CS/Project.csproj
new file mode 100644
index 0000000000000..18e85e8937019
--- /dev/null
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfigByName/CS/Project.csproj
@@ -0,0 +1,13 @@
+
+
+
+ Library
+ net6.0
+ enable
+
+
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfigByName/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfigByName/CS/source.cs
index 52888b0eca972..25647cfd21316 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfigByName/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfigByName/CS/source.cs
@@ -1,32 +1,26 @@
-
-using System;
+using System;
using System.Configuration;
-class Program
+static class Program
{
static void Main()
{
- string s = GetConnectionStringByName("NorthwindSQL");
+ var s = GetConnectionStringByName("NorthwindSQL");
Console.WriteLine(s);
Console.ReadLine();
}
+
//
// Retrieves a connection string by name.
// Returns null if the name is not found.
- static string GetConnectionStringByName(string name)
+ static string? GetConnectionStringByName(string name)
{
- // Assume failure.
- string returnValue = null;
-
// Look for the name in the connectionStrings section.
- ConnectionStringSettings settings =
+ ConnectionStringSettings? settings =
ConfigurationManager.ConnectionStrings[name];
- // If found, return the connection string.
- if (settings != null)
- returnValue = settings.ConnectionString;
-
- return returnValue;
+ // If found, return the connection string (otherwise return null)
+ return settings?.ConnectionString;
}
//
}
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfigByProvider/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfigByProvider/CS/Project.csproj
new file mode 100644
index 0000000000000..5d6d7339cfcfb
--- /dev/null
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfigByProvider/CS/Project.csproj
@@ -0,0 +1,13 @@
+
+
+
+ net7.0
+ Library
+ enable
+
+
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfigByProvider/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfigByProvider/CS/source.cs
index 9bb6ea7faae3e..505d08b65bd04 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfigByProvider/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringSettings.RetrieveFromConfigByProvider/CS/source.cs
@@ -1,28 +1,22 @@
-
-using System;
-using System.Data;
-using System.Data.SqlClient;
-using System.Data.OleDb;
+using System;
using System.Configuration;
-class Program
+static class Program
{
static void Main()
{
- string s = GetConnectionStringByProvider("System.Data.SqlClient");
+ var s = GetConnectionStringByProvider("System.Data.SqlClient");
Console.WriteLine(s);
Console.ReadLine();
}
+
//
// Retrieve a connection string by specifying the providerName.
// Assumes one connection string per provider in the config file.
- static string GetConnectionStringByProvider(string providerName)
+ static string? GetConnectionStringByProvider(string providerName)
{
- // Return null on failure.
- string returnValue = null;
-
// Get the collection of connection strings.
- ConnectionStringSettingsCollection settings =
+ ConnectionStringSettingsCollection? settings =
ConfigurationManager.ConnectionStrings;
// Walk through the collection and return the first
@@ -32,11 +26,12 @@ static string GetConnectionStringByProvider(string providerName)
foreach (ConnectionStringSettings cs in settings)
{
if (cs.ProviderName == providerName)
- returnValue = cs.ConnectionString;
- break;
+ {
+ return cs.ConnectionString;
+ }
}
}
- return returnValue;
+ return null;
}
//
}
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStrings.Encrypt/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStrings.Encrypt/CS/Project.csproj
new file mode 100644
index 0000000000000..5f32e737b1eb5
--- /dev/null
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStrings.Encrypt/CS/Project.csproj
@@ -0,0 +1,13 @@
+
+
+
+ Library
+ net6.0
+ enable
+
+
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStrings.Encrypt/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStrings.Encrypt/CS/source.cs
index 62f95b172d007..926b6ad0e59f8 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStrings.Encrypt/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStrings.Encrypt/CS/source.cs
@@ -2,7 +2,7 @@
using System;
using System.Configuration;
-class Program
+static class Program
{
static void Main()
{
@@ -10,35 +10,43 @@ static void Main()
//
static void ToggleConfigEncryption(string exeFile)
{
+ // Get the application path needed to obtain
+ // the application configuration file.
+
// Takes the executable file name without the
// .config extension.
+ var exePath = exeFile.Replace(".config", "");
+
try
{
// Open the configuration file and retrieve
// the connectionStrings section.
Configuration config = ConfigurationManager.
- OpenExeConfiguration(exeConfigName);
+ OpenExeConfiguration(exePath);
- ConnectionStringsSection section =
+ var section =
config.GetSection("connectionStrings")
as ConnectionStringsSection;
- if (section.SectionInformation.IsProtected)
- {
- // Remove encryption.
- section.SectionInformation.UnprotectSection();
- }
- else
+ if (section != null)
{
- // Encrypt the section.
- section.SectionInformation.ProtectSection(
- "DataProtectionConfigurationProvider");
+ 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);
+ section?.SectionInformation.IsProtected);
}
catch (Exception ex)
{
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringsWeb.Encrypt/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringsWeb.Encrypt/CS/Project.csproj
new file mode 100644
index 0000000000000..aca2b9b64ccd9
--- /dev/null
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringsWeb.Encrypt/CS/Project.csproj
@@ -0,0 +1,16 @@
+
+
+
+ Library
+ net4.8
+
+
+
+
+
+
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringsWeb.Encrypt/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringsWeb.Encrypt/CS/source.cs
index 1a090ab93a05a..819673e523665 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringsWeb.Encrypt/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStringsWeb.Encrypt/CS/source.cs
@@ -1,9 +1,7 @@
-
-using System;
-using System.Configuration;
+using System.Configuration;
using System.Web.Configuration;
-class Program
+static class Program
{
static void Main()
{
@@ -16,7 +14,7 @@ static void ToggleWebEncrypt()
OpenWebConfiguration("~");
// Get the connectionStrings section.
- ConnectionStringsSection section =
+ var section =
config.GetSection("connectionStrings")
as ConnectionStringsSection;
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks Data.AcceptRejectRule/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks Data.AcceptRejectRule/CS/Project.csproj
new file mode 100644
index 0000000000000..8697cda1d2f1c
--- /dev/null
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks Data.AcceptRejectRule/CS/Project.csproj
@@ -0,0 +1,12 @@
+
+
+
+ Library
+ net6.0
+ enable
+
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks Data.AcceptRejectRule/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks Data.AcceptRejectRule/CS/source.cs
index e67a359708f67..4618ffcbd0a2f 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks Data.AcceptRejectRule/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks Data.AcceptRejectRule/CS/source.cs
@@ -1,35 +1,35 @@
using System;
using System.Data;
-using System.Windows.Forms;
-public class Form1: Form
+public static class Program
{
+ //
+ static void CreateConstraint(DataSet dataSet,
+ string table1, string table2, string column1, string column2)
+ {
+ // Declare parent column and child column variables.
+ DataColumn parentColumn, childColumn;
+ ForeignKeyConstraint foreignKeyConstraint;
-//
- private void CreateConstraint(DataSet dataSet,
- string table1, string table2,string column1, string column2)
- {
- // Declare parent column and child column variables.
- DataColumn parentColumn;
- DataColumn childColumn;
- ForeignKeyConstraint foreignKeyConstraint;
+ // Set parent and child column variables.
+ parentColumn = dataSet.Tables[table1]?.Columns[column1] ??
+ throw new NullReferenceException($"{nameof(CreateConstraint)}: {table1}.{column1} not found");
+ childColumn = dataSet.Tables[table2]?.Columns[column2] ??
+ throw new NullReferenceException($"{nameof(CreateConstraint)}: {table2}.{column2} not found");
+ foreignKeyConstraint = new ForeignKeyConstraint
+ ("SupplierForeignKeyConstraint", parentColumn, childColumn)
+ {
+ // Set null values when a value is deleted.
+ DeleteRule = Rule.SetNull,
+ UpdateRule = Rule.Cascade,
+ AcceptRejectRule = AcceptRejectRule.None
+ };
- // Set parent and child column variables.
- parentColumn = dataSet.Tables[table1].Columns[column1];
- childColumn = dataSet.Tables[table2].Columns[column2];
- foreignKeyConstraint = new ForeignKeyConstraint
- ("SupplierForeignKeyConstraint", parentColumn, childColumn);
-
- // Set null values when a value is deleted.
- foreignKeyConstraint.DeleteRule = Rule.SetNull;
- foreignKeyConstraint.UpdateRule = Rule.Cascade;
- foreignKeyConstraint.AcceptRejectRule = AcceptRejectRule.None;
-
- // Add the constraint, and set EnforceConstraints to true.
- dataSet.Tables[table1].Constraints.Add(foreignKeyConstraint);
- dataSet.EnforceConstraints = true;
- }
-//
+ // Add the constraint, and set EnforceConstraints to true.
+ dataSet.Tables[table1]?.Constraints.Add(foreignKeyConstraint);
+ dataSet.EnforceConstraints = true;
+ }
+ //
}
public class SuppliersProducts : DataSet { }
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks Data.AcceptRejectRule/CS/source.resx b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks Data.AcceptRejectRule/CS/source.resx
new file mode 100644
index 0000000000000..1af7de150c99c
--- /dev/null
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks Data.AcceptRejectRule/CS/source.resx
@@ -0,0 +1,120 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ text/microsoft-resx
+
+
+ 2.0
+
+
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
\ No newline at end of file
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks Data.DataTableAdd/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks Data.DataTableAdd/CS/Project.csproj
index b83f0211b39c5..a3684f75383e5 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks Data.DataTableAdd/CS/Project.csproj
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks Data.DataTableAdd/CS/Project.csproj
@@ -3,5 +3,9 @@
Library
net6.0
-
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks Data.DataTableAdd/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks Data.DataTableAdd/CS/source.cs
index 31a90a539243f..928dc45f0e5a5 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks Data.DataTableAdd/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks Data.DataTableAdd/CS/source.cs
@@ -1,23 +1,21 @@
-using System;
-using System.Data;
-namespace DataTableAddCS
+using System.Data;
+namespace DataTableAddCS;
+
+static class Program
{
- class Program
+ static void Main()
{
- static void Main()
- {
- //
- DataSet customerOrders = new DataSet("CustomerOrders");
+ //
+ DataSet customerOrders = new("CustomerOrders");
- DataTable ordersTable = customerOrders.Tables.Add("Orders");
+ DataTable ordersTable = customerOrders.Tables.Add("Orders");
- DataColumn pkOrderID =
- ordersTable.Columns.Add("OrderID", typeof(Int32));
- ordersTable.Columns.Add("OrderQuantity", typeof(Int32));
- ordersTable.Columns.Add("CompanyName", typeof(string));
+ DataColumn pkOrderID =
+ ordersTable.Columns.Add("OrderID", typeof(int));
+ ordersTable.Columns.Add("OrderQuantity", typeof(int));
+ ordersTable.Columns.Add("CompanyName", typeof(string));
- ordersTable.PrimaryKey = new DataColumn[] { pkOrderID };
- //
- }
+ ordersTable.PrimaryKey = new DataColumn[] { pkOrderID };
+ //
}
}
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks Data.DataTableNavigation/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks Data.DataTableNavigation/CS/Project.csproj
index b83f0211b39c5..a3684f75383e5 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks Data.DataTableNavigation/CS/Project.csproj
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks Data.DataTableNavigation/CS/Project.csproj
@@ -3,5 +3,9 @@
Library
net6.0
-
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks Data.DataTableNavigation/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks Data.DataTableNavigation/CS/source.cs
index ee99eb9c9bc1b..89cd76b8eecd9 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks Data.DataTableNavigation/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks Data.DataTableNavigation/CS/source.cs
@@ -1,47 +1,46 @@
using System;
using System.Data;
-namespace NavigationCS
+namespace NavigationCS;
+
+static class Program
{
- class Program
+ static void Main()
{
- static void Main()
- {
- DataSet customerOrders = new DataSet();
- //
- DataRelation customerOrdersRelation =
- customerOrders.Relations.Add("CustOrders",
- customerOrders.Tables["Customers"].Columns["CustomerID"],
- customerOrders.Tables["Orders"].Columns["CustomerID"]);
+ DataSet customerOrders = new();
+ //
+ DataRelation customerOrdersRelation =
+ customerOrders.Relations.Add("CustOrders",
+ customerOrders.Tables["Customers"].Columns["CustomerID"],
+ customerOrders.Tables["Orders"].Columns["CustomerID"]);
- DataRelation orderDetailRelation =
- customerOrders.Relations.Add("OrderDetail",
- customerOrders.Tables["Orders"].Columns["OrderID"],
- customerOrders.Tables["OrderDetails"].Columns["OrderID"], false);
+ DataRelation orderDetailRelation =
+ customerOrders.Relations.Add("OrderDetail",
+ customerOrders.Tables["Orders"].Columns["OrderID"],
+ customerOrders.Tables["OrderDetails"].Columns["OrderID"], false);
- DataRelation orderProductRelation =
- customerOrders.Relations.Add("OrderProducts",
- customerOrders.Tables["Products"].Columns["ProductID"],
- customerOrders.Tables["OrderDetails"].Columns["ProductID"]);
+ DataRelation orderProductRelation =
+ customerOrders.Relations.Add("OrderProducts",
+ customerOrders.Tables["Products"].Columns["ProductID"],
+ customerOrders.Tables["OrderDetails"].Columns["ProductID"]);
- foreach (DataRow custRow in customerOrders.Tables["Customers"].Rows)
+ foreach (DataRow custRow in customerOrders.Tables["Customers"].Rows)
+ {
+ Console.WriteLine("Customer ID: " + custRow["CustomerID"]);
+
+ foreach (DataRow orderRow in custRow.GetChildRows(customerOrdersRelation))
{
- Console.WriteLine("Customer ID: " + custRow["CustomerID"]);
+ Console.WriteLine(" Order ID: " + orderRow["OrderID"]);
+ Console.WriteLine("\tOrder Date: " + orderRow["OrderDate"]);
- foreach (DataRow orderRow in custRow.GetChildRows(customerOrdersRelation))
+ foreach (DataRow detailRow in orderRow.GetChildRows(orderDetailRelation))
{
- Console.WriteLine(" Order ID: " + orderRow["OrderID"]);
- Console.WriteLine("\tOrder Date: " + orderRow["OrderDate"]);
-
- foreach (DataRow detailRow in orderRow.GetChildRows(orderDetailRelation))
- {
- Console.WriteLine("\t Product: " +
- detailRow.GetParentRow(orderProductRelation)["ProductName"]);
- Console.WriteLine("\t Quantity: " + detailRow["Quantity"]);
- }
+ Console.WriteLine("\t Product: " +
+ detailRow.GetParentRow(orderProductRelation)["ProductName"]);
+ Console.WriteLine("\t Quantity: " + detailRow["Quantity"]);
}
}
- //
}
+ //
}
}
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks Data.DataTableRelation/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks Data.DataTableRelation/CS/Project.csproj
index b83f0211b39c5..a3684f75383e5 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks Data.DataTableRelation/CS/Project.csproj
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks Data.DataTableRelation/CS/Project.csproj
@@ -3,5 +3,9 @@
Library
net6.0
-
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks Data.DataTableRelation/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks Data.DataTableRelation/CS/source.cs
index 19e08ea6aeb7d..af4fc8bd13031 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks Data.DataTableRelation/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks Data.DataTableRelation/CS/source.cs
@@ -1,29 +1,28 @@
using System;
using System.Data;
-namespace NavigationCS
+namespace NavigationCS;
+
+static class Program
{
- class Program
+ static void Main()
{
- static void Main()
+ DataSet customerOrders = new();
+ //
+ DataRelation customerOrdersRelation =
+ customerOrders.Relations.Add("CustOrders",
+ customerOrders.Tables["Customers"].Columns["CustomerID"],
+ customerOrders.Tables["Orders"].Columns["CustomerID"]);
+
+ foreach (DataRow custRow in customerOrders.Tables["Customers"].Rows)
{
- DataSet customerOrders = new DataSet();
- //
- DataRelation customerOrdersRelation =
- customerOrders.Relations.Add("CustOrders",
- customerOrders.Tables["Customers"].Columns["CustomerID"],
- customerOrders.Tables["Orders"].Columns["CustomerID"]);
+ Console.WriteLine(custRow["CustomerID"].ToString());
- foreach (DataRow custRow in customerOrders.Tables["Customers"].Rows)
+ foreach (DataRow orderRow in custRow.GetChildRows(customerOrdersRelation))
{
- Console.WriteLine(custRow["CustomerID"].ToString());
-
- foreach (DataRow orderRow in custRow.GetChildRows(customerOrdersRelation))
- {
- Console.WriteLine(orderRow["OrderID"].ToString());
- }
+ Console.WriteLine(orderRow["OrderID"].ToString());
}
- //
}
+ //
}
}
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataSet.Merge/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataSet.Merge/CS/source.cs
deleted file mode 100644
index 9e53535d8b21e..0000000000000
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataSet.Merge/CS/source.cs
+++ /dev/null
@@ -1,46 +0,0 @@
-using System;
-using System.Data;
-using System.Data.SqlClient;
-
-class Program
-{
- static void Main()
- {
- string connectionString = GetConnectionString();
- ConnectToData(connectionString);
- Console.ReadLine();
- }
- private static void ConnectToData(string connectionString)
- {
- //
- using (SqlConnection connection =
- new SqlConnection(connectionString))
- {
- SqlDataAdapter adapter =
- new SqlDataAdapter(
- "SELECT CustomerID, CompanyName FROM dbo.Customers",
- connection);
-
- connection.Open();
-
- DataSet customers = new DataSet();
- adapter.FillSchema(customers, SchemaType.Source, "Customers");
- adapter.Fill(customers, "Customers");
-
- DataSet orders = new DataSet();
- orders.ReadXml("Orders.xml", XmlReadMode.ReadSchema);
- orders.AcceptChanges();
-
- customers.Merge(orders, true, MissingSchemaAction.AddWithKey);
- //
- }
- }
-
- static private string GetConnectionString()
- {
- // To avoid storing the connection string in your code,
- // you can retrieve it from a configuration file.
- return "Data Source=(local);Initial Catalog=Northwind;"
- + "Integrated Security=SSPI";
- }
-}
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataSet.MergeAcceptChanges/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataSet.MergeAcceptChanges/CS/Project.csproj
new file mode 100644
index 0000000000000..9659b3497e484
--- /dev/null
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataSet.MergeAcceptChanges/CS/Project.csproj
@@ -0,0 +1,12 @@
+
+
+
+ Library
+ net6.0
+ enable
+
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataSet.MergeAcceptChanges/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataSet.MergeAcceptChanges/CS/source.cs
index 7d48e9fd589a1..34ac5a74b3d84 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataSet.MergeAcceptChanges/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataSet.MergeAcceptChanges/CS/source.cs
@@ -6,31 +6,31 @@ class Program
{
static void Main()
{
- string connectionString = GetConnectionString();
+ var connectionString = GetConnectionString();
ConnectToData(connectionString);
Console.ReadLine();
}
- private static void ConnectToData(string connectionString)
+ static void ConnectToData(string connectionString)
{
using (SqlConnection connection =
- new SqlConnection(connectionString))
+ new(connectionString))
{
SqlDataAdapter adapter =
- new SqlDataAdapter(
+ new(
"SELECT CustomerID, CompanyName FROM dbo.Customers",
connection);
- DataSet dataSet = new DataSet();
+ DataSet dataSet = new();
//
- DataTable customers = dataSet.Tables["Customers"];
+ DataTable customers = dataSet.Tables["Customers"]!;
// Make modifications to the Customers table.
// Get changes to the DataSet.
- DataSet dataSetChanges = dataSet.GetChanges();
+ DataSet dataSetChanges = dataSet.GetChanges() ?? new();
// Add an event handler to handle the errors during Update.
- adapter.RowUpdated += new SqlRowUpdatedEventHandler(OnRowUpdated);
+ adapter.RowUpdated += OnRowUpdated;
connection.Open();
adapter.Update(dataSetChanges, "Customers");
@@ -40,7 +40,7 @@ private static void ConnectToData(string connectionString)
dataSet.Merge(dataSetChanges, true, MissingSchemaAction.Add);
// Reject changes on rows with errors and clear the error.
- DataRow[] errRows = dataSet.Tables["Customers"].GetErrors();
+ DataRow[] errRows = dataSet.Tables["Customers"]!.GetErrors();
foreach (DataRow errRow in errRows)
{
errRow.RejectChanges();
@@ -60,17 +60,15 @@ protected static void OnRowUpdated(
{
if (args.Status == UpdateStatus.ErrorsOccurred)
{
- args.Row.RowError = args.Errors.Message;
+ args.Row.RowError = args.Errors!.Message;
args.Status = UpdateStatus.SkipCurrentRow;
}
}
- //
+ //
- static private string GetConnectionString()
- {
+ static string GetConnectionString() =>
// To avoid storing the connection string in your code,
// you can retrieve it from a configuration file.
- return "Data Source=(local);Initial Catalog=Northwind;"
+ "Data Source=(local);Initial Catalog=Northwind;"
+ "Integrated Security=SSPI";
- }
}
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataTable.CreateDataReader/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataTable.CreateDataReader/CS/Project.csproj
index b83f0211b39c5..a3684f75383e5 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataTable.CreateDataReader/CS/Project.csproj
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataTable.CreateDataReader/CS/Project.csproj
@@ -3,5 +3,9 @@
Library
net6.0
-
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataTable.CreateDataReader/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataTable.CreateDataReader/CS/source.cs
index c0ba306318302..0913401d58b48 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataTable.CreateDataReader/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataTable.CreateDataReader/CS/source.cs
@@ -1,7 +1,7 @@
using System;
using System.Data;
-class Program
+static class Program
{
//
static void Main()
@@ -11,7 +11,7 @@ static void Main()
Console.ReadKey();
}
- private static void TestCreateDataReader(DataTable dt)
+ static void TestCreateDataReader(DataTable dt)
{
// Given a DataTable, retrieve a DataTableReader
// allowing access to all the tables' data:
@@ -32,11 +32,11 @@ private static void TestCreateDataReader(DataTable dt)
}
}
- private static DataTable GetCustomers()
+ static DataTable GetCustomers()
{
// Create sample Customers table, in order
// to demonstrate the behavior of the DataTableReader.
- DataTable table = new DataTable();
+ DataTable table = new();
// Create two columns, ID and Name.
DataColumn idColumn = table.Columns.Add("ID", typeof(int));
@@ -52,12 +52,12 @@ private static DataTable GetCustomers()
return table;
}
- private static void PrintColumns(DataTableReader reader)
+ static void PrintColumns(DataTableReader reader)
{
// Loop through all the rows in the DataTableReader
while (reader.Read())
{
- for (int i = 0; i < reader.FieldCount; i++)
+ for (var i = 0; i < reader.FieldCount; i++)
{
Console.Write(reader[i] + " ");
}
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataTable.Events/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataTable.Events/CS/Project.csproj
index b83f0211b39c5..a3684f75383e5 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataTable.Events/CS/Project.csproj
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataTable.Events/CS/Project.csproj
@@ -3,5 +3,9 @@
Library
net6.0
-
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataTable.Events/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataTable.Events/CS/source.cs
index 0eb5ccd511fa6..09d9c8f774e7c 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataTable.Events/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataTable.Events/CS/source.cs
@@ -1,7 +1,7 @@
using System;
using System.Data;
-class Class1
+static class Class1
{
static void Main()
{
@@ -11,7 +11,7 @@ static void Main()
//
static void DataTableEvents()
{
- DataTable table = new DataTable("Customers");
+ DataTable table = new("Customers");
// Add two columns, id and name.
table.Columns.Add("id", typeof(int));
table.Columns.Add("name", typeof(string));
@@ -21,36 +21,36 @@ static void DataTableEvents()
table.PrimaryKey = new DataColumn[] { table.Columns["id"] };
// Add a RowChanged event handler.
- table.RowChanged += new DataRowChangeEventHandler(Row_Changed);
+ table.RowChanged += Row_Changed;
// Add a RowChanging event handler.
- table.RowChanging += new DataRowChangeEventHandler(Row_Changing);
+ table.RowChanging += Row_Changing;
// Add a RowDeleted event handler.
- table.RowDeleted += new DataRowChangeEventHandler(Row_Deleted);
+ table.RowDeleted += Row_Deleted;
// Add a RowDeleting event handler.
- table.RowDeleting += new DataRowChangeEventHandler(Row_Deleting);
+ table.RowDeleting += Row_Deleting;
// Add a ColumnChanged event handler.
- table.ColumnChanged += new
- DataColumnChangeEventHandler(Column_Changed);
+ table.ColumnChanged +=
+ Column_Changed;
// Add a ColumnChanging event handler.
- table.ColumnChanging += new
- DataColumnChangeEventHandler(Column_Changing);
+ table.ColumnChanging +=
+ Column_Changing;
// Add a TableNewRow event handler.
- table.TableNewRow += new
- DataTableNewRowEventHandler(Table_NewRow);
+ table.TableNewRow +=
+ Table_NewRow;
// Add a TableCleared event handler.
- table.TableCleared += new
- DataTableClearEventHandler(Table_Cleared);
+ table.TableCleared +=
+ Table_Cleared;
// Add a TableClearing event handler.
- table.TableClearing += new
- DataTableClearEventHandler(Table_Clearing);
+ table.TableClearing +=
+ Table_Clearing;
// Add a customer.
DataRow row = table.NewRow();
@@ -70,60 +70,42 @@ static void DataTableEvents()
table.Clear();
}
- private static void Row_Changed(object sender, DataRowChangeEventArgs e)
- {
+ static void Row_Changed(object sender, DataRowChangeEventArgs e) =>
Console.WriteLine("Row_Changed Event: name={0}; action={1}",
e.Row["name"], e.Action);
- }
- private static void Row_Changing(object sender, DataRowChangeEventArgs e)
- {
+ static void Row_Changing(object sender, DataRowChangeEventArgs e) =>
Console.WriteLine("Row_Changing Event: name={0}; action={1}",
e.Row["name"], e.Action);
- }
- private static void Row_Deleted(object sender, DataRowChangeEventArgs e)
- {
+ static void Row_Deleted(object sender, DataRowChangeEventArgs e) =>
Console.WriteLine("Row_Deleted Event: name={0}; action={1}",
e.Row["name", DataRowVersion.Original], e.Action);
- }
- private static void Row_Deleting(object sender,
- DataRowChangeEventArgs e)
- {
+ static void Row_Deleting(object sender,
+ DataRowChangeEventArgs e) =>
Console.WriteLine("Row_Deleting Event: name={0}; action={1}",
e.Row["name"], e.Action);
- }
- private static void Column_Changed(object sender, DataColumnChangeEventArgs e)
- {
+ static void Column_Changed(object sender, DataColumnChangeEventArgs e) =>
Console.WriteLine("Column_Changed Event: ColumnName={0}; RowState={1}",
e.Column.ColumnName, e.Row.RowState);
- }
- private static void Column_Changing(object sender, DataColumnChangeEventArgs e)
- {
+ static void Column_Changing(object sender, DataColumnChangeEventArgs e) =>
Console.WriteLine("Column_Changing Event: ColumnName={0}; RowState={1}",
e.Column.ColumnName, e.Row.RowState);
- }
- private static void Table_NewRow(object sender,
- DataTableNewRowEventArgs e)
- {
+ static void Table_NewRow(object sender,
+ DataTableNewRowEventArgs e) =>
Console.WriteLine("Table_NewRow Event: RowState={0}",
e.Row.RowState.ToString());
- }
- private static void Table_Cleared(object sender, DataTableClearEventArgs e)
- {
+ static void Table_Cleared(object sender, DataTableClearEventArgs e) =>
Console.WriteLine("Table_Cleared Event: TableName={0}; Rows={1}",
e.TableName, e.Table.Rows.Count.ToString());
- }
- private static void Table_Clearing(object sender, DataTableClearEventArgs e)
- {
+ static void Table_Clearing(object sender, DataTableClearEventArgs e) =>
Console.WriteLine("Table_Clearing Event: TableName={0}; Rows={1}",
e.TableName, e.Table.Rows.Count.ToString());
- }
//
}
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataTableReader.NextResult/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataTableReader.NextResult/CS/Project.csproj
index b83f0211b39c5..a3684f75383e5 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataTableReader.NextResult/CS/Project.csproj
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataTableReader.NextResult/CS/Project.csproj
@@ -3,5 +3,9 @@
Library
net6.0
-
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataTableReader.NextResult/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataTableReader.NextResult/CS/source.cs
index 9000326c01405..3d03c1165a669 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataTableReader.NextResult/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataTableReader.NextResult/CS/source.cs
@@ -1,15 +1,12 @@
using System;
using System.Data;
-class DataTableReaderConstructor
+static class DataTableReaderConstructor
{
[STAThread]
- static void Main()
- {
- TestConstructor();
- }
+ static void Main() => TestConstructor();
//
- private static void TestConstructor()
+ static void TestConstructor()
{
// Create two data adapters, one for each of the two
// DataTables to be filled.
@@ -17,7 +14,7 @@ private static void TestConstructor()
DataTable productDataTable = GetProducts();
// Create the new DataTableReader.
- using (DataTableReader reader = new DataTableReader(
+ using (DataTableReader reader = new(
new DataTable[] { customerDataTable, productDataTable }))
{
// Print the contents of each of the result sets.
@@ -31,15 +28,15 @@ private static void TestConstructor()
Console.ReadLine();
}
- private static DataTable GetCustomers()
+ static DataTable GetCustomers()
{
// Create sample Customers table, in order
// to demonstrate the behavior of the DataTableReader.
- DataTable table = new DataTable();
+ DataTable table = new();
// Create two columns, ID and Name.
DataColumn idColumn = table.Columns.Add("ID", typeof(int));
- table.Columns.Add("Name", typeof(string ));
+ table.Columns.Add("Name", typeof(string));
// Set the ID column as the primary key column.
table.PrimaryKey = new DataColumn[] { idColumn };
@@ -51,15 +48,15 @@ private static DataTable GetCustomers()
return table;
}
- private static DataTable GetProducts()
+ static DataTable GetProducts()
{
// Create sample Products table, in order
// to demonstrate the behavior of the DataTableReader.
- DataTable table = new DataTable();
+ DataTable table = new();
// Create two columns, ID and Name.
DataColumn idColumn = table.Columns.Add("ID", typeof(int));
- table.Columns.Add("Name", typeof(string ));
+ table.Columns.Add("Name", typeof(string));
// Set the ID column as the primary key column.
table.PrimaryKey = new DataColumn[] { idColumn };
@@ -71,12 +68,12 @@ private static DataTable GetProducts()
return table;
}
- private static void PrintColumns(DataTableReader reader)
+ static void PrintColumns(DataTableReader reader)
{
// Loop through all the rows in the DataTableReader
while (reader.Read())
{
- for (int i = 0; i < reader.FieldCount; i++)
+ for (var i = 0; i < reader.FieldCount; i++)
{
Console.Write(reader[i] + " ");
}
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommand/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommand/CS/Project.csproj
new file mode 100644
index 0000000000000..8f99831a66cfa
--- /dev/null
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommand/CS/Project.csproj
@@ -0,0 +1,14 @@
+
+
+
+ Library
+ net6.0
+ enable
+
+
+
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommand/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommand/CS/source.cs
index 54b82f44040b9..e74316d834ad3 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommand/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommand/CS/source.cs
@@ -1,11 +1,9 @@
using System;
-using System.Data;
-using System.Data.SqlClient;
-using System.Data.OleDb;
using System.Configuration;
using System.Data.Common;
+using System.Data.SqlClient;
-class Program
+static class Program
{
static void Main()
{
@@ -30,12 +28,12 @@ static void ExecuteDbCommand(DbConnection connection)
DbCommand command = connection.CreateCommand();
command.CommandText =
"INSERT INTO Categories (CategoryName) VALUES ('Low Carb')";
- int rows = command.ExecuteNonQuery();
+ var rows = command.ExecuteNonQuery();
// Display number of rows inserted.
Console.WriteLine("Inserted {0} rows.", rows);
}
- // Handle data errors.
+ // Handle data errors.
catch (DbException exDb)
{
Console.WriteLine("DbException.GetType: {0}", exDb.GetType());
@@ -43,7 +41,7 @@ static void ExecuteDbCommand(DbConnection connection)
Console.WriteLine("DbException.ErrorCode: {0}", exDb.ErrorCode);
Console.WriteLine("DbException.Message: {0}", exDb.Message);
}
- // Handle all other exceptions.
+ // Handle all other exceptions.
catch (Exception ex)
{
Console.WriteLine("Exception.Message: {0}", ex.Message);
@@ -59,11 +57,11 @@ static void ExecuteDbCommand(DbConnection connection)
// Given a provider, create the factory and connect to the data source.
// The provider invariant name is in the format System.Data.ProviderName.
- static DbConnection CreateFactoryConnection(string providerName)
+ static DbConnection? CreateFactoryConnection(string providerName)
{
// Retrieve the connection string from the configuration file
// by supplying the provider name to a custom function.
- string connectionString = GetConnectionStringByProvider(providerName);
+ var connectionString = GetConnectionStringByProvider(providerName);
// Create the factory if there's a valid connection string.
if (connectionString != null)
@@ -72,18 +70,21 @@ static DbConnection CreateFactoryConnection(string providerName)
DbProviderFactories.GetFactory(providerName);
// Create the connection.
- DbConnection connection = factory.CreateConnection();
- connection.ConnectionString = connectionString;
- try
+ DbConnection? connection = factory.CreateConnection();
+ if (connection != null)
{
- connection.Open();
- }
- catch (SqlException ex)
- {
- Console.WriteLine("sqlx: " + ex.ToString());
+ connection.ConnectionString = connectionString;
+ try
+ {
+ connection.Open();
+ }
+ catch (SqlException ex)
+ {
+ Console.WriteLine("sqlx: " + ex);
+ }
}
- Console.WriteLine(connection.State);
+ Console.WriteLine((connection?.State.ToString()) ?? "invalid Connection!");
// Return the open connection.
return connection;
@@ -95,9 +96,9 @@ static DbConnection CreateFactoryConnection(string providerName)
// If there are multiple connection strings for the same
// provider, the first one found is returned.
// Returns null if the provider is not found.
- static string GetConnectionStringByProvider(string providerName)
+ static string? GetConnectionStringByProvider(string providerName)
{
- for (int i = 0; i < ConfigurationManager.ConnectionStrings.Count; i++)
+ for (var i = 0; i < ConfigurationManager.ConnectionStrings.Count; i++)
{
ConnectionStringSettings settings =
ConfigurationManager.ConnectionStrings[i];
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommandData/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommandData/CS/Project.csproj
new file mode 100644
index 0000000000000..5f32e737b1eb5
--- /dev/null
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommandData/CS/Project.csproj
@@ -0,0 +1,13 @@
+
+
+
+ Library
+ net6.0
+ enable
+
+
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommandData/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommandData/CS/source.cs
index 26e73d914cf05..5b0ac96d06a1a 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommandData/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommandData/CS/source.cs
@@ -1,17 +1,18 @@
using System;
-using System.Data;
-using System.Data.SqlClient;
-using System.Data.OleDb;
using System.Configuration;
+using System.Data;
using System.Data.Common;
-class Program
+static class Program
{
static void Main()
{
- DbConnection c = CreateFactoryConnection("System.Data.OleDb");
- //DbConnection c = CreateFactoryConnection("System.Data.SqlClient");
- DbCommandSelect(c);
+ DbConnection? c = CreateFactoryConnection("System.Data.OleDb");
+ //DbConnection? c = CreateFactoryConnection("System.Data.SqlClient");
+ if (c != null)
+ {
+ DbCommandSelect(c);
+ }
Console.ReadLine();
}
@@ -20,7 +21,7 @@ static void Main()
// from the Categories table by executing a DbDataReader.
static void DbCommandSelect(DbConnection connection)
{
- string queryString =
+ const string queryString =
"SELECT CategoryID, CategoryName FROM Categories";
// Check for valid DbConnection.
@@ -45,7 +46,6 @@ static void DbCommandSelect(DbConnection connection)
Console.WriteLine("{0}. {1}", reader[0], reader[1]);
}
}
-
catch (Exception ex)
{
Console.WriteLine("Exception.Message: {0}", ex.Message);
@@ -60,11 +60,11 @@ static void DbCommandSelect(DbConnection connection)
//
// Given a provider, create the factory and connect to the data source.
// The provider invariant name is in the format System.Data.ProviderName.
- static DbConnection CreateFactoryConnection(string providerName)
+ static DbConnection? CreateFactoryConnection(string providerName)
{
// Retrieve the connection string from the configuration file
// by supplying the provider name to a custom function.
- string connectionString = GetConnectionStringByProvider(providerName);
+ var connectionString = GetConnectionStringByProvider(providerName);
// Create the factory if there's a valid connection string.
if (connectionString != null)
@@ -73,8 +73,11 @@ static DbConnection CreateFactoryConnection(string providerName)
DbProviderFactories.GetFactory(providerName);
// Create the connection.
- DbConnection connection = factory.CreateConnection();
- connection.ConnectionString = connectionString;
+ DbConnection? connection = factory.CreateConnection();
+ if (connection != null)
+ {
+ connection.ConnectionString = connectionString;
+ }
// Return the connection.
return connection;
@@ -86,9 +89,9 @@ static DbConnection CreateFactoryConnection(string providerName)
// If there are multiple connection strings for the same
// provider, the first one found is returned.
// Returns null if the provider is not found.
- static string GetConnectionStringByProvider(string providerName)
+ static string? GetConnectionStringByProvider(string providerName)
{
- for (int i = 0; i < ConfigurationManager.ConnectionStrings.Count; i++)
+ for (var i = 0; i < ConfigurationManager.ConnectionStrings.Count; i++)
{
ConnectionStringSettings settings =
ConfigurationManager.ConnectionStrings[i];
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbDataAdapter/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbDataAdapter/CS/Project.csproj
index b83f0211b39c5..a3684f75383e5 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbDataAdapter/CS/Project.csproj
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbDataAdapter/CS/Project.csproj
@@ -3,5 +3,9 @@
Library
net6.0
-
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbDataAdapter/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbDataAdapter/CS/source.cs
index de450ba802b24..cf32be4e9c980 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbDataAdapter/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbDataAdapter/CS/source.cs
@@ -1,11 +1,8 @@
using System;
using System.Data;
-using System.Data.SqlClient;
-using System.Data.OleDb;
-using System.Configuration;
using System.Data.Common;
-class Program
+static class Program
{
static void Main()
{
@@ -30,7 +27,7 @@ static void CreateDataAdapter(string providerName, string connectionString)
using (connection)
{
// Define the query.
- string queryString =
+ const string queryString =
"SELECT CategoryName FROM Categories";
// Create the DbCommand.
@@ -43,7 +40,7 @@ static void CreateDataAdapter(string providerName, string connectionString)
adapter.SelectCommand = command;
// Fill the DataTable.
- DataTable table = new DataTable();
+ DataTable table = new();
adapter.Fill(table);
// Display each row and column value.
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbDataAdapterModify/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbDataAdapterModify/CS/Project.csproj
index b83f0211b39c5..a3684f75383e5 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbDataAdapterModify/CS/Project.csproj
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbDataAdapterModify/CS/Project.csproj
@@ -3,5 +3,9 @@
Library
net6.0
-
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbDataAdapterModify/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbDataAdapterModify/CS/source.cs
index 0db6f3d12dead..07eb78cb3e9d4 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbDataAdapterModify/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbDataAdapterModify/CS/source.cs
@@ -1,11 +1,8 @@
using System;
using System.Data;
-using System.Data.SqlClient;
-using System.Data.OleDb;
-using System.Configuration;
using System.Data.Common;
-class Program
+static class Program
{
static void Main()
{
@@ -30,7 +27,7 @@ static void CreateDataAdapter(string providerName, string connectionString)
using (connection)
{
// Define the query.
- string queryString =
+ const string queryString =
"SELECT CustomerID, CompanyName FROM Customers";
// Create the select command.
@@ -60,7 +57,7 @@ static void CreateDataAdapter(string providerName, string connectionString)
adapter.DeleteCommand.CommandText);
// Fill the DataTable.
- DataTable table = new DataTable();
+ DataTable table = new();
adapter.Fill(table);
// Insert a new row.
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.GetFactory/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.GetFactory/CS/Project.csproj
index b83f0211b39c5..a3684f75383e5 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.GetFactory/CS/Project.csproj
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.GetFactory/CS/Project.csproj
@@ -3,5 +3,9 @@
Library
net6.0
-
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.GetFactory/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.GetFactory/CS/source.cs
index 776a57a6fb1f3..a4d40a9ccccd7 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.GetFactory/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.GetFactory/CS/source.cs
@@ -1,10 +1,7 @@
using System;
-using System.Data;
-using System.Data.SqlClient;
-using System.Configuration;
using System.Data.Common;
-class Program
+static class Program
{
static void Main()
{
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories/CS/Project.csproj
index b83f0211b39c5..a3684f75383e5 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories/CS/Project.csproj
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories/CS/Project.csproj
@@ -3,5 +3,9 @@
Library
net6.0
-
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories/CS/source.cs
index 44f2d394fce71..539f22de42422 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories/CS/source.cs
@@ -1,11 +1,8 @@
using System;
using System.Data;
-using System.Data.SqlClient;
-using System.Data.OleDb;
-using System.Configuration;
using System.Data.Common;
-class Program
+static class Program
{
static void Main()
{
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks LargeValueType.Param/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks LargeValueType.Param/CS/Project.csproj
new file mode 100644
index 0000000000000..9659b3497e484
--- /dev/null
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks LargeValueType.Param/CS/Project.csproj
@@ -0,0 +1,12 @@
+
+
+
+ Library
+ net6.0
+ enable
+
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks LargeValueType.Param/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks LargeValueType.Param/CS/source.cs
index 1f55ff4a39b9c..9b184a387217d 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks LargeValueType.Param/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks LargeValueType.Param/CS/source.cs
@@ -1,21 +1,22 @@
using System;
using System.Data;
using System.Data.SqlClient;
-class Program
+
+static class Program
{
static void Main()
{
// Supply any valid Document ID value.
// The value 7 is supplied for demonstration purposes.
- string summaryString = GetDocumentSummary(7);
+ var summaryString = GetDocumentSummary(7);
Console.ReadLine();
}
//
- static private string GetDocumentSummary(int documentID)
+ static string? GetDocumentSummary(int documentID)
{
//Assumes GetConnectionString returns a valid connection string.
using (SqlConnection connection =
- new SqlConnection(GetConnectionString()))
+ new(GetConnectionString()))
{
connection.Open();
SqlCommand command = connection.CreateCommand();
@@ -27,21 +28,25 @@ static private string GetDocumentSummary(int documentID)
// Set up the input parameter for the DocumentID.
SqlParameter paramID =
- new SqlParameter("@DocumentID", SqlDbType.Int);
- paramID.Value = documentID;
+ new("@DocumentID", SqlDbType.Int)
+ {
+ Value = documentID
+ };
command.Parameters.Add(paramID);
// Set up the output parameter to retrieve the summary.
SqlParameter paramSummary =
- new SqlParameter("@DocumentSummary",
- SqlDbType.NVarChar, -1);
- paramSummary.Direction = ParameterDirection.Output;
+ new("@DocumentSummary",
+ SqlDbType.NVarChar, -1)
+ {
+ Direction = ParameterDirection.Output
+ };
command.Parameters.Add(paramSummary);
// Execute the stored procedure.
command.ExecuteNonQuery();
- Console.WriteLine((String)(paramSummary.Value));
- return (String)(paramSummary.Value);
+ Console.WriteLine((string)paramSummary.Value);
+ return (string)paramSummary.Value;
}
catch (Exception ex)
{
@@ -51,12 +56,10 @@ static private string GetDocumentSummary(int documentID)
}
}
//
- static private string GetConnectionString()
- {
+ static string GetConnectionString() =>
// To avoid storing the connectionection string in your code,
// you can retrieve it from a configuration file, using the
// System.Configuration.ConfigurationSettings.AppSettings property
- return "Data Source=(local);Initial Catalog=AdventureWorks;" +
+ "Data Source=(local);Initial Catalog=AdventureWorks;" +
"Integrated Security=SSPI";
- }
}
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks LargeValueType.Photo/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks LargeValueType.Photo/CS/Project.csproj
new file mode 100644
index 0000000000000..0a34647858c2b
--- /dev/null
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks LargeValueType.Photo/CS/Project.csproj
@@ -0,0 +1,13 @@
+
+
+
+ Library
+ net6.0
+ enable
+
+
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks LargeValueType.Photo/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks LargeValueType.Photo/CS/source.cs
index a92b12cd2207d..9e06ffcc0f443 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks LargeValueType.Photo/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks LargeValueType.Photo/CS/source.cs
@@ -1,12 +1,14 @@
using System;
-using System.Data.SqlClient;
using System.Data;
+using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Drawing;
using System.Drawing.Imaging;
-using System.IO;
+using System.Runtime.Versioning;
-class Program
+// API is only supported on Windows
+[SupportedOSPlatform("windows")]
+static class Program
{
static void Main()
{
@@ -17,14 +19,14 @@ static void Main()
Console.ReadLine();
}
//
- static private void TestGetSqlBytes(int documentID, string filePath)
+ static void TestGetSqlBytes(int documentID, string filePath)
{
// Assumes GetConnectionString returns a valid connection string.
using (SqlConnection connection =
- new SqlConnection(GetConnectionString()))
+ new(GetConnectionString()))
{
SqlCommand command = connection.CreateCommand();
- SqlDataReader reader = null;
+ SqlDataReader reader = default!;
try
{
// Setup the command
@@ -36,12 +38,14 @@ static private void TestGetSqlBytes(int documentID, string filePath)
// Declare the parameter
SqlParameter paramID =
- new SqlParameter("@ProductPhotoID", SqlDbType.Int);
- paramID.Value = documentID;
+ new("@ProductPhotoID", SqlDbType.Int)
+ {
+ Value = documentID
+ };
command.Parameters.Add(paramID);
connection.Open();
- string photoName = null;
+ string photoName = default!;
reader = command.ExecuteReader(CommandBehavior.CloseConnection);
@@ -60,9 +64,9 @@ static private void TestGetSqlBytes(int documentID, string filePath)
else
{
SqlBytes bytes = reader.GetSqlBytes(1);
- using (Bitmap productImage = new Bitmap(bytes.Stream))
+ using (Bitmap productImage = new(bytes.Stream))
{
- String fileName = filePath + photoName;
+ var fileName = filePath + photoName;
// Save in gif format.
productImage.Save(fileName, ImageFormat.Gif);
@@ -82,19 +86,16 @@ static private void TestGetSqlBytes(int documentID, string filePath)
}
finally
{
- if (reader != null)
- reader.Dispose();
+ reader?.Dispose();
}
}
}
//
- static private string GetConnectionString()
- {
+ static string GetConnectionString() =>
// To avoid storing the connectionection string in your code,
// you can retrieve it from a configuration file, using the
// System.Configuration.ConfigurationSettings.AppSettings property
- return "Data Source=(local);Initial Catalog=AdventureWorks;" +
+ "Data Source=(local);Initial Catalog=AdventureWorks;" +
"Integrated Security=SSPI";
- }
}
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks OleDb.JetAutonumberMerge/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks OleDb.JetAutonumberMerge/CS/Project.csproj
new file mode 100644
index 0000000000000..98d93a4347feb
--- /dev/null
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks OleDb.JetAutonumberMerge/CS/Project.csproj
@@ -0,0 +1,13 @@
+
+
+
+ Library
+ net6.0
+ enable
+
+
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks OleDb.JetAutonumberMerge/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks OleDb.JetAutonumberMerge/CS/source.cs
index 3626e204f222f..ebdef4f4dd30d 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks OleDb.JetAutonumberMerge/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks OleDb.JetAutonumberMerge/CS/source.cs
@@ -1,32 +1,38 @@
using System;
using System.Data;
using System.Data.OleDb;
+using System.Runtime.Versioning;
-class Program
+// API is only supported on Windows
+[SupportedOSPlatform("windows")]
+static class Program
{
static void Main()
{
- string connectionString = GetConnectionString();
- connection = new OleDbConnection(connectionString);
- MergeIdentityColumns(connection);
+ var connectionString = GetConnectionString();
+ s_connection = new OleDbConnection(connectionString);
+ MergeIdentityColumns(s_connection);
Console.ReadLine();
}
//
- private static OleDbConnection connection = null;
+ static OleDbConnection s_connection = default!;
- private static void MergeIdentityColumns(OleDbConnection connection)
+ static void MergeIdentityColumns(OleDbConnection connection)
{
using (connection)
{
// Create a DataAdapter based on a SELECT query.
- OleDbDataAdapter adapter = new OleDbDataAdapter(
+ OleDbDataAdapter adapter = new(
"SELECT CategoryID, CategoryName FROM Categories",
- connection);
-
- // Create the INSERT command for the new category.
- adapter.InsertCommand = new OleDbCommand(
- "INSERT INTO Categories (CategoryName) Values(?)", connection);
- adapter.InsertCommand.CommandType = CommandType.Text;
+ connection)
+ {
+ // Create the INSERT command for the new category.
+ InsertCommand = new OleDbCommand(
+ "INSERT INTO Categories (CategoryName) Values(?)", connection)
+ {
+ CommandType = CommandType.Text
+ }
+ };
// Add the parameter for the CategoryName.
adapter.InsertCommand.Parameters.Add(
@@ -34,27 +40,29 @@ private static void MergeIdentityColumns(OleDbConnection connection)
adapter.InsertCommand.UpdatedRowSource = UpdateRowSource.Both;
// Create a DataTable
- DataTable categories = new DataTable();
+ DataTable categories = new();
// Create the CategoryID column and set its auto
// incrementing properties to decrement from zero.
- DataColumn column = new DataColumn();
- column.DataType = System.Type.GetType("System.Int32");
- column.ColumnName = "CategoryID";
- column.AutoIncrement = true;
- column.AutoIncrementSeed = 0;
- column.AutoIncrementStep = -1;
- categories.Columns.Add(column);
+ DataColumn catId = new()
+ {
+ DataType = Type.GetType("System.Int32"),
+ ColumnName = "CategoryID",
+ AutoIncrement = true,
+ AutoIncrementSeed = 0,
+ AutoIncrementStep = -1
+ };
+ categories.Columns.Add(catId);
// Create the CategoryName column.
- column = new DataColumn();
- column.DataType = System.Type.GetType("System.String");
- column.ColumnName = "CategoryName";
- categories.Columns.Add(column);
+ categories.Columns.Add(new DataColumn
+ {
+ DataType = Type.GetType("System.String"),
+ ColumnName = "CategoryName"
+ });
// Set the primary key on CategoryID.
- DataColumn[] pKey = new DataColumn[1];
- pKey[0] = categories.Columns["CategoryID"];
+ var pKey = new DataColumn[] { catId };
categories.PrimaryKey = pKey;
// Fetch the data and fill the DataTable
@@ -72,11 +80,11 @@ private static void MergeIdentityColumns(OleDbConnection connection)
// Add changed rows to a new DataTable that will be
// used to post the inserts to the database.
- DataTable dataChanges = categories.GetChanges();
+ DataTable dataChanges = categories.GetChanges()!;
// Include an event to fill in the Autonumber value.
adapter.RowUpdated +=
- new OleDbRowUpdatedEventHandler(OnRowUpdated);
+ OnRowUpdated;
// Update the database, inserting the new rows.
adapter.Update(dataChanges);
@@ -107,26 +115,24 @@ private static void MergeIdentityColumns(OleDbConnection connection)
//
//
- private static void OnRowUpdated(
+ static void OnRowUpdated(
object sender, OleDbRowUpdatedEventArgs e)
{
// Conditionally execute this code block on inserts only.
if (e.StatementType == StatementType.Insert)
{
- OleDbCommand cmdNewID = new OleDbCommand("SELECT @@IDENTITY",
- connection);
+ OleDbCommand cmdNewID = new("SELECT @@IDENTITY",
+ s_connection);
// Retrieve the Autonumber and store it in the CategoryID column.
- e.Row["CategoryID"] = (int)cmdNewID.ExecuteScalar();
+ e.Row["CategoryID"] = (int)cmdNewID.ExecuteScalar()!;
e.Status = UpdateStatus.SkipCurrentRow;
}
}
//
- static string GetConnectionString()
- {
+ static string GetConnectionString() =>
// To avoid storing the connection string in your code,
// you can retrieve it from a configuration file.
- return "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
+ "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
+ "c:\\Data\\Northwind.mdb;User Id=admin;Password=;";
- }
}
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.Odbc/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.Odbc/CS/Project.csproj
new file mode 100644
index 0000000000000..a25336f18292f
--- /dev/null
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.Odbc/CS/Project.csproj
@@ -0,0 +1,13 @@
+
+
+
+ Library
+ net6.0
+ enable
+
+
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.Odbc/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.Odbc/CS/source.cs
index 701071ddb16b7..30c5e3bea0f0d 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.Odbc/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.Odbc/CS/source.cs
@@ -1,36 +1,35 @@
//
using System;
-using System.Data;
using System.Data.Odbc;
-class Program
+static class Program
{
static void Main()
{
// The connection string assumes that the Access
// Northwind.mdb is located in the c:\Data folder.
- string connectionString =
+ const string connectionString =
"Driver={Microsoft Access Driver (*.mdb)};"
+ "Dbq=c:\\Data\\Northwind.mdb;Uid=Admin;Pwd=;";
// Provide the query string with a parameter placeholder.
- string queryString =
+ const string queryString =
"SELECT ProductID, UnitPrice, ProductName from products "
+ "WHERE UnitPrice > ? "
+ "ORDER BY UnitPrice DESC;";
// Specify the parameter value.
- int paramValue = 5;
+ const int paramValue = 5;
// Create and open the connection in a using block. This
// ensures that all resources will be closed and disposed
// when the code exits.
using (OdbcConnection connection =
- new OdbcConnection(connectionString))
+ new(connectionString))
{
// Create the Command and Parameter objects.
- OdbcCommand command = new OdbcCommand(queryString, connection);
+ OdbcCommand command = new(queryString, connection);
command.Parameters.AddWithValue("@pricePoint", paramValue);
// Open the connection in a try/catch block.
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.OleDb/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.OleDb/CS/Project.csproj
new file mode 100644
index 0000000000000..a681da0d65a63
--- /dev/null
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.OleDb/CS/Project.csproj
@@ -0,0 +1,13 @@
+
+
+
+ Library
+ net6.0
+ enable
+
+
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.OleDb/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.OleDb/CS/source.cs
index d420d20bde430..a27b1e886a7f2 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.OleDb/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.OleDb/CS/source.cs
@@ -1,36 +1,38 @@
//
using System;
-using System.Data;
using System.Data.OleDb;
+using System.Runtime.Versioning;
-class Program
+// API is only supported on Windows
+[SupportedOSPlatform("windows")]
+static class Program
{
static void Main()
{
// The connection string assumes that the Access
// Northwind.mdb is located in the c:\Data folder.
- string connectionString =
+ const string connectionString =
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
+ "c:\\Data\\Northwind.mdb;User Id=admin;Password=;";
// Provide the query string with a parameter placeholder.
- string queryString =
+ const string queryString =
"SELECT ProductID, UnitPrice, ProductName from products "
+ "WHERE UnitPrice > ? "
+ "ORDER BY UnitPrice DESC;";
// Specify the parameter value.
- int paramValue = 5;
+ const int paramValue = 5;
// Create and open the connection in a using block. This
// ensures that all resources will be closed and disposed
// when the code exits.
using (OleDbConnection connection =
- new OleDbConnection(connectionString))
+ new(connectionString))
{
// Create the Command and Parameter objects.
- OleDbCommand command = new OleDbCommand(queryString, connection);
+ OleDbCommand command = new(queryString, connection);
command.Parameters.AddWithValue("@pricePoint", paramValue);
// Open the connection in a try/catch block.
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.Oracle/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.Oracle/CS/Project.csproj
new file mode 100644
index 0000000000000..ded0f6fc2dc79
--- /dev/null
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.Oracle/CS/Project.csproj
@@ -0,0 +1,13 @@
+
+
+
+ Library
+ net6.0
+ enable
+
+
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.Oracle/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.Oracle/CS/source.cs
index 9332617d85cd7..ed222ad7a5cde 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.Oracle/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.Oracle/CS/source.cs
@@ -1,18 +1,17 @@
//
using System;
-using System.Data;
using System.Data.OracleClient;
-class Program
+static class Program
{
static void Main()
{
- string connectionString =
+ const string connectionString =
"Data Source=ThisOracleServer;Integrated Security=yes;";
- string queryString =
+ const string queryString =
"SELECT CUSTOMER_ID, NAME FROM DEMO.CUSTOMER";
using (OracleConnection connection =
- new OracleConnection(connectionString))
+ new(connectionString))
{
OracleCommand command = connection.CreateCommand();
command.CommandText = queryString;
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.SqlClient/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.SqlClient/CS/Project.csproj
new file mode 100644
index 0000000000000..9659b3497e484
--- /dev/null
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.SqlClient/CS/Project.csproj
@@ -0,0 +1,12 @@
+
+
+
+ Library
+ net6.0
+ enable
+
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.SqlClient/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.SqlClient/CS/source.cs
index 1e25e8e7a50d5..9596f3873f1a8 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.SqlClient/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.SqlClient/CS/source.cs
@@ -1,34 +1,33 @@
//
using System;
-using System.Data;
using System.Data.SqlClient;
-class Program
+static class Program
{
static void Main()
{
- string connectionString =
+ const string connectionString =
"Data Source=(local);Initial Catalog=Northwind;"
+ "Integrated Security=true";
// Provide the query string with a parameter placeholder.
- string queryString =
+ const string queryString =
"SELECT ProductID, UnitPrice, ProductName from dbo.products "
+ "WHERE UnitPrice > @pricePoint "
+ "ORDER BY UnitPrice DESC;";
// Specify the parameter value.
- int paramValue = 5;
+ const int paramValue = 5;
// Create and open the connection in a using block. This
// ensures that all resources will be closed and disposed
// when the code exits.
using (SqlConnection connection =
- new SqlConnection(connectionString))
+ new(connectionString))
{
// Create the Command and Parameter objects.
- SqlCommand command = new SqlCommand(queryString, connection);
+ SqlCommand command = new(queryString, connection);
command.Parameters.AddWithValue("@pricePoint", paramValue);
// Open the connection in a try/catch block.
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SnapshotIsolation.Demo/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SnapshotIsolation.Demo/CS/Project.csproj
new file mode 100644
index 0000000000000..9659b3497e484
--- /dev/null
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SnapshotIsolation.Demo/CS/Project.csproj
@@ -0,0 +1,12 @@
+
+
+
+ Library
+ net6.0
+ enable
+
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SnapshotIsolation.Demo/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SnapshotIsolation.Demo/CS/source.cs
index 465fecc7e706e..96b82e27383d1 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SnapshotIsolation.Demo/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SnapshotIsolation.Demo/CS/source.cs
@@ -2,15 +2,15 @@
using System.Data;
using System.Data.SqlClient;
-class Program
+static class Program
{
static void Main()
{
//
// Assumes GetConnectionString returns a valid connection string
// where pooling is turned off by setting Pooling=False;.
- string connectionString = GetConnectionString();
- using (SqlConnection connection1 = new SqlConnection(connectionString))
+ var connectionString = GetConnectionString();
+ using (SqlConnection connection1 = new(connectionString))
{
// Drop the TestSnapshot table if it exists
connection1.Open();
@@ -51,7 +51,7 @@ static void Main()
command1.ExecuteNonQuery();
// Open a second connection to AdventureWorks
- using (SqlConnection connection2 = new SqlConnection(connectionString))
+ using (SqlConnection connection2 = new(connectionString))
{
connection2.Open();
// Initiate a second transaction to read from TestSnapshot
@@ -67,8 +67,8 @@ static void Main()
while (reader2.Read())
{
Console.WriteLine("Expected 1,1 Actual "
- + reader2.GetValue(0).ToString()
- + "," + reader2.GetValue(1).ToString());
+ + reader2.GetValue(0)
+ + "," + reader2.GetValue(1));
}
transaction2.Commit();
}
@@ -81,7 +81,7 @@ static void Main()
// and will time out after 4 seconds.
// You would see the same behavior with the
// RepeatableRead or Serializable isolation levels.
- using (SqlConnection connection3 = new SqlConnection(connectionString))
+ using (SqlConnection connection3 = new(connectionString))
{
connection3.Open();
SqlCommand command3 = connection3.CreateCommand();
@@ -115,7 +115,7 @@ static void Main()
// of the proposed new value 22 for valueCol. If the first
// transaction rolls back, this value will never actually have
// existed in the database.
- using (SqlConnection connection4 = new SqlConnection(connectionString))
+ using (SqlConnection connection4 = new(connectionString))
{
connection4.Open();
SqlCommand command4 = connection4.CreateCommand();
@@ -128,8 +128,8 @@ static void Main()
while (reader4.Read())
{
Console.WriteLine("Expected 1,22 Actual "
- + reader4.GetValue(0).ToString()
- + "," + reader4.GetValue(1).ToString());
+ + reader4.GetValue(0)
+ + "," + reader4.GetValue(1));
}
transaction4.Commit();
@@ -142,7 +142,7 @@ static void Main()
// CLEANUP
// Delete the TestSnapshot table and set
// ALLOW_SNAPSHOT_ISOLATION OFF
- using (SqlConnection connection5 = new SqlConnection(connectionString))
+ using (SqlConnection connection5 = new(connectionString))
{
connection5.Open();
SqlCommand command5 = connection5.CreateCommand();
@@ -164,12 +164,10 @@ static void Main()
//
}
- static private string GetConnectionString()
- {
+ static string GetConnectionString() =>
// To avoid storing the connection string in your code,
// you can retrieve it from a configuration file, using the
// System.Configuration.ConfigurationSettings.AppSettings property
- return "Data Source=localhost;Initial Catalog=AdventureWorks;"
+ "Data Source=localhost;Initial Catalog=AdventureWorks;"
+ "Integrated Security=SSPI";
- }
}
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SnapshotIsolation.DemoUpdate/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SnapshotIsolation.DemoUpdate/CS/Project.csproj
new file mode 100644
index 0000000000000..9659b3497e484
--- /dev/null
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SnapshotIsolation.DemoUpdate/CS/Project.csproj
@@ -0,0 +1,12 @@
+
+
+
+ Library
+ net6.0
+ enable
+
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SnapshotIsolation.DemoUpdate/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SnapshotIsolation.DemoUpdate/CS/source.cs
index f097da3446646..a26a338aba762 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SnapshotIsolation.DemoUpdate/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SnapshotIsolation.DemoUpdate/CS/source.cs
@@ -1,17 +1,16 @@
using System;
using System.Data;
-using System.Data.Common;
using System.Data.SqlClient;
-class Program
+static class Program
{
static void Main()
{
//
// Assumes GetConnectionString returns a valid connection string
// where pooling is turned off by setting Pooling=False;.
- string connectionString = GetConnectionString();
- using (SqlConnection connection1 = new SqlConnection(connectionString))
+ var connectionString = GetConnectionString();
+ using (SqlConnection connection1 = new(connectionString))
{
connection1.Open();
SqlCommand command1 = connection1.CreateCommand();
@@ -65,7 +64,7 @@ static void Main()
// Begin, but do not complete, a transaction
// using the Snapshot isolation level.
- SqlTransaction transaction1 = null;
+ SqlTransaction transaction1 = default!;
try
{
transaction1 = connection1.BeginTransaction(IsolationLevel.Snapshot);
@@ -77,7 +76,7 @@ static void Main()
// Open a second Connection/Transaction to update data
// using ReadCommitted. This transaction should succeed.
- using (SqlConnection connection2 = new SqlConnection(connectionString))
+ using (SqlConnection connection2 = new(connectionString))
{
connection2.Open();
SqlCommand command2 = connection2.CreateCommand();
@@ -128,7 +127,7 @@ static void Main()
// CLEANUP:
// Turn off Snapshot isolation and delete the table
- using (SqlConnection connection3 = new SqlConnection(connectionString))
+ using (SqlConnection connection3 = new(connectionString))
{
connection3.Open();
SqlCommand command3 = connection3.CreateCommand();
@@ -160,12 +159,10 @@ static void Main()
Console.ReadLine();
}
- static private string GetConnectionString()
- {
+ static string GetConnectionString() =>
// To avoid storing the connection string in your code,
// you can retrieve it from a configuration file, using the
// System.Configuration.ConfigurationSettings.AppSettings property
- return "Data Source=(local);Initial Catalog=AdventureWorks;"
+ "Data Source=(local);Initial Catalog=AdventureWorks;"
+ "Integrated Security=SSPI;Pooling=false";
- }
}
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.ColumnMappingOrdersDetails/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.ColumnMappingOrdersDetails/CS/Project.csproj
new file mode 100644
index 0000000000000..9659b3497e484
--- /dev/null
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.ColumnMappingOrdersDetails/CS/Project.csproj
@@ -0,0 +1,12 @@
+
+
+
+ Library
+ net6.0
+ enable
+
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.ColumnMappingOrdersDetails/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.ColumnMappingOrdersDetails/CS/source.cs
index 4ef3d70b30bd8..cdbf2187dcdf7 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.ColumnMappingOrdersDetails/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.ColumnMappingOrdersDetails/CS/source.cs
@@ -3,33 +3,33 @@
//
using System.Data.SqlClient;
-class Program
+static class Program
{
static void Main()
{
- string connectionString = GetConnectionString();
+ var connectionString = GetConnectionString();
// Open a connection to the AdventureWorks database.
using (SqlConnection connection =
- new SqlConnection(connectionString))
+ new(connectionString))
{
connection.Open();
// Empty the destination tables.
- SqlCommand deleteHeader = new SqlCommand(
+ SqlCommand deleteHeader = new(
"DELETE FROM dbo.BulkCopyDemoOrderHeader;",
connection);
deleteHeader.ExecuteNonQuery();
- SqlCommand deleteDetail = new SqlCommand(
+ SqlCommand deleteDetail = new(
"DELETE FROM dbo.BulkCopyDemoOrderDetail;",
connection);
deleteDetail.ExecuteNonQuery();
// Perform an initial count on the destination
// table with matching columns.
- SqlCommand countRowHeader = new SqlCommand(
+ SqlCommand countRowHeader = new(
"SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderHeader;",
connection);
- long countStartHeader = System.Convert.ToInt32(
+ long countStartHeader = Convert.ToInt32(
countRowHeader.ExecuteScalar());
Console.WriteLine(
"Starting row count for Header table = {0}",
@@ -37,10 +37,10 @@ static void Main()
// Perform an initial count on the destination
// table with different column positions.
- SqlCommand countRowDetail = new SqlCommand(
+ SqlCommand countRowDetail = new(
"SELECT COUNT(*) FROM dbo.BulkCopyDemoOrderDetail;",
connection);
- long countStartDetail = System.Convert.ToInt32(
+ long countStartDetail = Convert.ToInt32(
countRowDetail.ExecuteScalar());
Console.WriteLine(
"Starting row count for Detail table = {0}",
@@ -53,41 +53,45 @@ static void Main()
// To keep the example simple and quick, a parameter is
// used to select only orders for a particular account
// as the source for the bulk insert.
- SqlCommand headerData = new SqlCommand(
+ SqlCommand headerData = new(
"SELECT [SalesOrderID], [OrderDate], " +
"[AccountNumber] FROM [Sales].[SalesOrderHeader] " +
"WHERE [AccountNumber] = @accountNumber;",
connection);
- SqlParameter parameterAccount = new SqlParameter();
- parameterAccount.ParameterName = "@accountNumber";
- parameterAccount.SqlDbType = SqlDbType.NVarChar;
- parameterAccount.Direction = ParameterDirection.Input;
- parameterAccount.Value = "10-4020-000034";
+ SqlParameter parameterAccount = new()
+ {
+ ParameterName = "@accountNumber",
+ SqlDbType = SqlDbType.NVarChar,
+ Direction = ParameterDirection.Input,
+ Value = "10-4020-000034"
+ };
headerData.Parameters.Add(parameterAccount);
SqlDataReader readerHeader = headerData.ExecuteReader();
// Get the Detail data in a separate connection.
- using (SqlConnection connection2 = new SqlConnection(connectionString))
+ using (SqlConnection connection2 = new(connectionString))
{
connection2.Open();
- SqlCommand sourceDetailData = new SqlCommand(
+ SqlCommand sourceDetailData = new(
"SELECT [Sales].[SalesOrderDetail].[SalesOrderID], [SalesOrderDetailID], " +
"[OrderQty], [ProductID], [UnitPrice] FROM [Sales].[SalesOrderDetail] " +
"INNER JOIN [Sales].[SalesOrderHeader] ON [Sales].[SalesOrderDetail]." +
"[SalesOrderID] = [Sales].[SalesOrderHeader].[SalesOrderID] " +
"WHERE [AccountNumber] = @accountNumber;", connection2);
- SqlParameter accountDetail = new SqlParameter();
- accountDetail.ParameterName = "@accountNumber";
- accountDetail.SqlDbType = SqlDbType.NVarChar;
- accountDetail.Direction = ParameterDirection.Input;
- accountDetail.Value = "10-4020-000034";
+ SqlParameter accountDetail = new()
+ {
+ ParameterName = "@accountNumber",
+ SqlDbType = SqlDbType.NVarChar,
+ Direction = ParameterDirection.Input,
+ Value = "10-4020-000034"
+ };
sourceDetailData.Parameters.Add(accountDetail);
SqlDataReader readerDetail = sourceDetailData.ExecuteReader();
// Create the SqlBulkCopy object.
using (SqlBulkCopy bulkCopy =
- new SqlBulkCopy(connectionString))
+ new(connectionString))
{
bulkCopy.DestinationTableName =
"dbo.BulkCopyDemoOrderHeader";
@@ -113,7 +117,7 @@ static void Main()
}
// Set up the order details destination.
- bulkCopy.DestinationTableName ="dbo.BulkCopyDemoOrderDetail";
+ bulkCopy.DestinationTableName = "dbo.BulkCopyDemoOrderDetail";
// Clear the ColumnMappingCollection.
bulkCopy.ColumnMappings.Clear();
@@ -142,11 +146,11 @@ static void Main()
// Perform a final count on the destination
// tables to see how many rows were added.
- long countEndHeader = System.Convert.ToInt32(
+ long countEndHeader = Convert.ToInt32(
countRowHeader.ExecuteScalar());
Console.WriteLine("{0} rows were added to the Header table.",
countEndHeader - countStartHeader);
- long countEndDetail = System.Convert.ToInt32(
+ long countEndDetail = Convert.ToInt32(
countRowDetail.ExecuteScalar());
Console.WriteLine("{0} rows were added to the Detail table.",
countEndDetail - countStartDetail);
@@ -156,9 +160,9 @@ static void Main()
}
}
- private static string GetConnectionString()
- // To avoid storing the connection string in your code,
- // you can retrieve it from a configuration file.
+ static string GetConnectionString()
+ // To avoid storing the connection string in your code,
+ // you can retrieve it from a configuration file.
{
return "Data Source=(local); " +
" Integrated Security=true;" +
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.DefaultTransaction/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.DefaultTransaction/CS/Project.csproj
new file mode 100644
index 0000000000000..9659b3497e484
--- /dev/null
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.DefaultTransaction/CS/Project.csproj
@@ -0,0 +1,12 @@
+
+
+
+ Library
+ net6.0
+ enable
+
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.DefaultTransaction/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.DefaultTransaction/CS/source.cs
index ddb99fae6a9a4..38b4407703bd4 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.DefaultTransaction/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.DefaultTransaction/CS/source.cs
@@ -1,24 +1,25 @@
using System;
-using System.Data;
//
using System.Data.SqlClient;
-class Program
+static class Program
{
static void Main()
{
- string connectionString = GetConnectionString();
+ var connectionString = GetConnectionString();
// Open a sourceConnection to the AdventureWorks database.
using (SqlConnection sourceConnection =
- new SqlConnection(connectionString))
+ new(connectionString))
{
sourceConnection.Open();
// Delete all from the destination table.
- SqlCommand commandDelete = new SqlCommand();
- commandDelete.Connection = sourceConnection;
- commandDelete.CommandText =
- "DELETE FROM dbo.BulkCopyDemoMatchingColumns";
+ SqlCommand commandDelete = new()
+ {
+ Connection = sourceConnection,
+ CommandText =
+ "DELETE FROM dbo.BulkCopyDemoMatchingColumns"
+ };
commandDelete.ExecuteNonQuery();
// Add a single row that will result in duplicate key
@@ -31,32 +32,34 @@ static void Main()
// does exist in your version of the Production.Products
// table. Choose any ProductID in the middle of the table
// (not first or last row) to best illustrate the result.
- SqlCommand commandInsert = new SqlCommand();
- commandInsert.Connection = sourceConnection;
- commandInsert.CommandText =
+ SqlCommand commandInsert = new()
+ {
+ Connection = sourceConnection,
+ CommandText =
"SET IDENTITY_INSERT dbo.BulkCopyDemoMatchingColumns ON;" +
"INSERT INTO " + "dbo.BulkCopyDemoMatchingColumns " +
"([ProductID], [Name] ,[ProductNumber]) " +
"VALUES(446, 'Lock Nut 23','LN-3416');" +
- "SET IDENTITY_INSERT dbo.BulkCopyDemoMatchingColumns OFF";
+ "SET IDENTITY_INSERT dbo.BulkCopyDemoMatchingColumns OFF"
+ };
commandInsert.ExecuteNonQuery();
// Perform an initial count on the destination table.
- SqlCommand commandRowCount = new SqlCommand(
+ SqlCommand commandRowCount = new(
"SELECT COUNT(*) FROM dbo.BulkCopyDemoMatchingColumns;",
sourceConnection);
- long countStart = System.Convert.ToInt32(
+ long countStart = Convert.ToInt32(
commandRowCount.ExecuteScalar());
Console.WriteLine("Starting row count = {0}", countStart);
// Get data from the source table as a SqlDataReader.
- SqlCommand commandSourceData = new SqlCommand(
+ SqlCommand commandSourceData = new(
"SELECT ProductID, Name, ProductNumber " +
"FROM Production.Product;", sourceConnection);
SqlDataReader reader = commandSourceData.ExecuteReader();
// Set up the bulk copy object using the KeepIdentity option.
- using (SqlBulkCopy bulkCopy = new SqlBulkCopy(
+ using (SqlBulkCopy bulkCopy = new(
connectionString, SqlBulkCopyOptions.KeepIdentity))
{
bulkCopy.BatchSize = 10;
@@ -82,7 +85,7 @@ static void Main()
// Perform a final count on the destination
// table to see how many rows were added.
- long countEnd = System.Convert.ToInt32(
+ long countEnd = Convert.ToInt32(
commandRowCount.ExecuteScalar());
Console.WriteLine("Ending row count = {0}", countEnd);
Console.WriteLine("{0} rows were added.", countEnd - countStart);
@@ -91,9 +94,9 @@ static void Main()
}
}
- private static string GetConnectionString()
- // To avoid storing the sourceConnection string in your code,
- // you can retrieve it from a configuration file.
+ static string GetConnectionString()
+ // To avoid storing the sourceConnection string in your code,
+ // you can retrieve it from a configuration file.
{
return "Data Source=(local); " +
" Integrated Security=true;" +
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.InternalTransaction/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.InternalTransaction/CS/Project.csproj
new file mode 100644
index 0000000000000..8697cda1d2f1c
--- /dev/null
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.InternalTransaction/CS/Project.csproj
@@ -0,0 +1,12 @@
+
+
+
+ Library
+ net6.0
+ enable
+
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.InternalTransaction/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.InternalTransaction/CS/source.cs
index 155d590ba6ca3..097101fa44c42 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.InternalTransaction/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.InternalTransaction/CS/source.cs
@@ -1,24 +1,25 @@
using System;
-using System.Data;
//
using System.Data.SqlClient;
-class Program
+static class Program
{
static void Main()
{
- string connectionString = GetConnectionString();
+ var connectionString = GetConnectionString();
// Open a sourceConnection to the AdventureWorks database.
using (SqlConnection sourceConnection =
- new SqlConnection(connectionString))
+ new(connectionString))
{
sourceConnection.Open();
// Delete all from the destination table.
- SqlCommand commandDelete = new SqlCommand();
- commandDelete.Connection = sourceConnection;
- commandDelete.CommandText =
- "DELETE FROM dbo.BulkCopyDemoMatchingColumns";
+ SqlCommand commandDelete = new()
+ {
+ Connection = sourceConnection,
+ CommandText =
+ "DELETE FROM dbo.BulkCopyDemoMatchingColumns"
+ };
commandDelete.ExecuteNonQuery();
// Add a single row that will result in duplicate key
@@ -31,26 +32,28 @@ static void Main()
// does exist in your version of the Production.Products
// table. Choose any ProductID in the middle of the table
// (not first or last row) to best illustrate the result.
- SqlCommand commandInsert = new SqlCommand();
- commandInsert.Connection = sourceConnection;
- commandInsert.CommandText =
+ SqlCommand commandInsert = new()
+ {
+ Connection = sourceConnection,
+ CommandText =
"SET IDENTITY_INSERT dbo.BulkCopyDemoMatchingColumns ON;" +
"INSERT INTO " + "dbo.BulkCopyDemoMatchingColumns " +
"([ProductID], [Name] ,[ProductNumber]) " +
"VALUES(446, 'Lock Nut 23','LN-3416');" +
- "SET IDENTITY_INSERT dbo.BulkCopyDemoMatchingColumns OFF";
+ "SET IDENTITY_INSERT dbo.BulkCopyDemoMatchingColumns OFF"
+ };
commandInsert.ExecuteNonQuery();
// Perform an initial count on the destination table.
- SqlCommand commandRowCount = new SqlCommand(
+ SqlCommand commandRowCount = new(
"SELECT COUNT(*) FROM dbo.BulkCopyDemoMatchingColumns;",
sourceConnection);
- long countStart = System.Convert.ToInt32(
+ long countStart = Convert.ToInt32(
commandRowCount.ExecuteScalar());
Console.WriteLine("Starting row count = {0}", countStart);
// Get data from the source table as a SqlDataReader.
- SqlCommand commandSourceData = new SqlCommand(
+ SqlCommand commandSourceData = new(
"SELECT ProductID, Name, ProductNumber " +
"FROM Production.Product;", sourceConnection);
SqlDataReader reader = commandSourceData.ExecuteReader();
@@ -61,7 +64,7 @@ static void Main()
// Therefore, you must use the SqlBulkCopy construct that
// requires a string for the connection, rather than an
// existing SqlConnection object.
- using (SqlBulkCopy bulkCopy = new SqlBulkCopy(
+ using (SqlBulkCopy bulkCopy = new(
connectionString, SqlBulkCopyOptions.KeepIdentity |
SqlBulkCopyOptions.UseInternalTransaction))
{
@@ -88,7 +91,7 @@ static void Main()
// Perform a final count on the destination
// table to see how many rows were added.
- long countEnd = System.Convert.ToInt32(
+ long countEnd = Convert.ToInt32(
commandRowCount.ExecuteScalar());
Console.WriteLine("Ending row count = {0}", countEnd);
Console.WriteLine("{0} rows were added.", countEnd - countStart);
@@ -97,9 +100,9 @@ static void Main()
}
}
- private static string GetConnectionString()
- // To avoid storing the sourceConnection string in your code,
- // you can retrieve it from a configuration file.
+ static string GetConnectionString()
+ // To avoid storing the sourceConnection string in your code,
+ // you can retrieve it from a configuration file.
{
return "Data Source=(local); " +
" Integrated Security=true;" +
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.SqlTransaction/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.SqlTransaction/CS/Project.csproj
new file mode 100644
index 0000000000000..8697cda1d2f1c
--- /dev/null
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.SqlTransaction/CS/Project.csproj
@@ -0,0 +1,12 @@
+
+
+
+ Library
+ net6.0
+ enable
+
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.SqlTransaction/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.SqlTransaction/CS/source.cs
index da370fe644422..ccd79d44f7795 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.SqlTransaction/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.SqlTransaction/CS/source.cs
@@ -1,24 +1,25 @@
using System;
-using System.Data;
//
using System.Data.SqlClient;
-class Program
+static class Program
{
static void Main()
{
- string connectionString = GetConnectionString();
+ var connectionString = GetConnectionString();
// Open a sourceConnection to the AdventureWorks database.
using (SqlConnection sourceConnection =
- new SqlConnection(connectionString))
+ new(connectionString))
{
sourceConnection.Open();
// Delete all from the destination table.
- SqlCommand commandDelete = new SqlCommand();
- commandDelete.Connection = sourceConnection;
- commandDelete.CommandText =
- "DELETE FROM dbo.BulkCopyDemoMatchingColumns";
+ SqlCommand commandDelete = new()
+ {
+ Connection = sourceConnection,
+ CommandText =
+ "DELETE FROM dbo.BulkCopyDemoMatchingColumns"
+ };
commandDelete.ExecuteNonQuery();
// Add a single row that will result in duplicate key
@@ -31,40 +32,42 @@ static void Main()
// does exist in your version of the Production.Products
// table. Choose any ProductID in the middle of the table
// (not first or last row) to best illustrate the result.
- SqlCommand commandInsert = new SqlCommand();
- commandInsert.Connection = sourceConnection;
- commandInsert.CommandText =
+ SqlCommand commandInsert = new()
+ {
+ Connection = sourceConnection,
+ CommandText =
"SET IDENTITY_INSERT dbo.BulkCopyDemoMatchingColumns ON;" +
"INSERT INTO " + "dbo.BulkCopyDemoMatchingColumns " +
"([ProductID], [Name] ,[ProductNumber]) " +
"VALUES(446, 'Lock Nut 23','LN-3416');" +
- "SET IDENTITY_INSERT dbo.BulkCopyDemoMatchingColumns OFF";
+ "SET IDENTITY_INSERT dbo.BulkCopyDemoMatchingColumns OFF"
+ };
commandInsert.ExecuteNonQuery();
// Perform an initial count on the destination table.
- SqlCommand commandRowCount = new SqlCommand(
+ SqlCommand commandRowCount = new(
"SELECT COUNT(*) FROM dbo.BulkCopyDemoMatchingColumns;",
sourceConnection);
- long countStart = System.Convert.ToInt32(
+ long countStart = Convert.ToInt32(
commandRowCount.ExecuteScalar());
Console.WriteLine("Starting row count = {0}", countStart);
// Get data from the source table as a SqlDataReader.
- SqlCommand commandSourceData = new SqlCommand(
+ SqlCommand commandSourceData = new(
"SELECT ProductID, Name, ProductNumber " +
"FROM Production.Product;", sourceConnection);
SqlDataReader reader = commandSourceData.ExecuteReader();
//Set up the bulk copy object inside the transaction.
using (SqlConnection destinationConnection =
- new SqlConnection(connectionString))
+ new(connectionString))
{
destinationConnection.Open();
using (SqlTransaction transaction =
destinationConnection.BeginTransaction())
{
- using (SqlBulkCopy bulkCopy = new SqlBulkCopy(
+ using (SqlBulkCopy bulkCopy = new(
destinationConnection, SqlBulkCopyOptions.KeepIdentity,
transaction))
{
@@ -94,7 +97,7 @@ static void Main()
// Perform a final count on the destination
// table to see how many rows were added.
- long countEnd = System.Convert.ToInt32(
+ long countEnd = Convert.ToInt32(
commandRowCount.ExecuteScalar());
Console.WriteLine("Ending row count = {0}", countEnd);
Console.WriteLine("{0} rows were added.", countEnd - countStart);
@@ -103,9 +106,9 @@ static void Main()
}
}
- private static string GetConnectionString()
- // To avoid storing the sourceConnection string in your code,
- // you can retrieve it from a configuration file.
+ static string GetConnectionString()
+ // To avoid storing the sourceConnection string in your code,
+ // you can retrieve it from a configuration file.
{
return "Data Source=(local); " +
" Integrated Security=true;" +
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.CAS/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.CAS/CS/source.cs
deleted file mode 100644
index 067b112defcf7..0000000000000
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.CAS/CS/source.cs
+++ /dev/null
@@ -1,82 +0,0 @@
-//
-using System;
-using System.Data;
-using System.Data.SqlClient;
-using System.Security;
-using System.Security.Permissions;
-
-namespace PartialTrustTopic {
- public class PartialTrustHelper : MarshalByRefObject {
- public void TestConnectionOpen(string connectionString) {
- // Try to open a connection.
- using (SqlConnection connection = new SqlConnection(connectionString)) {
- connection.Open();
- }
- }
- }
-
- class Program {
- static void Main(string[] args) {
- TestCAS("Data Source=(local);Integrated Security=true", "Data Source=(local);Integrated Security=true;Initial Catalog=Test");
- }
-
- static void TestCAS(string connectString1, string connectString2) {
- // Create permission set for sandbox AppDomain.
- // This example only allows execution.
- PermissionSet permissions = new PermissionSet(PermissionState.None);
- permissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
-
- // Create sandbox AppDomain with permission set that only allows execution,
- // and has no SqlClientPermissions.
- AppDomainSetup appDomainSetup = new AppDomainSetup();
- appDomainSetup.ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
- AppDomain firstDomain = AppDomain.CreateDomain("NoSqlPermissions", null, appDomainSetup, permissions);
-
- // Create helper object in sandbox AppDomain so that code can be executed in that AppDomain.
- Type helperType = typeof(PartialTrustHelper);
- PartialTrustHelper firstHelper = (PartialTrustHelper)firstDomain.CreateInstanceAndUnwrap(helperType.Assembly.FullName, helperType.FullName);
-
- try {
- // Attempt to open a connection in the sandbox AppDomain.
- // This is expected to fail.
- firstHelper.TestConnectionOpen(connectString1);
- Console.WriteLine("Connection opened, unexpected.");
- }
- catch (System.Security.SecurityException ex) {
- Console.WriteLine("Failed, as expected: {0}",
- ex.FirstPermissionThatFailed);
-
- // Uncomment the following line to see Exception details.
- // Console.WriteLine("BaseException: " + ex.GetBaseException());
- }
-
- // Add permission for a specific connection string.
- SqlClientPermission sqlPermission = new SqlClientPermission(PermissionState.None);
- sqlPermission.Add(connectString1, "", KeyRestrictionBehavior.AllowOnly);
-
- permissions.AddPermission(sqlPermission);
-
- AppDomain secondDomain = AppDomain.CreateDomain("OneSqlPermission", null, appDomainSetup, permissions);
- PartialTrustHelper secondHelper = (PartialTrustHelper)secondDomain.CreateInstanceAndUnwrap(helperType.Assembly.FullName, helperType.FullName);
-
- // Try connection open again, it should succeed now.
- try {
- secondHelper.TestConnectionOpen(connectString1);
- Console.WriteLine("Connection opened, as expected.");
- }
- catch (System.Security.SecurityException ex) {
- Console.WriteLine("Unexpected failure: {0}", ex.Message);
- }
-
- // Try a different connection string. This should fail.
- try {
- secondHelper.TestConnectionOpen(connectString2);
- Console.WriteLine("Connection opened, unexpected.");
- }
- catch (System.Security.SecurityException ex) {
- Console.WriteLine("Failed, as expected: {0}", ex.Message);
- }
- }
- }
-}
-//
\ No newline at end of file
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.DataAdapterUpdate/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.DataAdapterUpdate/CS/source.cs
index 6f014df10db94..fda946765aae5 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.DataAdapterUpdate/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.DataAdapterUpdate/CS/source.cs
@@ -2,27 +2,28 @@
using System.Data;
using System.Data.SqlClient;
-class Program
+static class Program
{
static void Main()
{
- string connectionString = GetConnectionString();
+ var connectionString = GetConnectionString();
AdapterUpdate(connectionString);
Console.ReadLine();
}
//
- private static void AdapterUpdate(string connectionString)
+ static void AdapterUpdate(string connectionString)
{
using (SqlConnection connection =
- new SqlConnection(connectionString))
+ new(connectionString))
{
- SqlDataAdapter dataAdapter = new SqlDataAdapter(
+ SqlDataAdapter dataAdapter = new(
"SELECT CategoryID, CategoryName FROM Categories",
- connection);
-
- dataAdapter.UpdateCommand = new SqlCommand(
+ connection)
+ {
+ UpdateCommand = new SqlCommand(
"UPDATE Categories SET CategoryName = @CategoryName " +
- "WHERE CategoryID = @CategoryID", connection);
+ "WHERE CategoryID = @CategoryID", connection)
+ };
dataAdapter.UpdateCommand.Parameters.Add(
"@CategoryName", SqlDbType.NVarChar, 15, "CategoryName");
@@ -32,7 +33,7 @@ private static void AdapterUpdate(string connectionString)
parameter.SourceColumn = "CategoryID";
parameter.SourceVersion = DataRowVersion.Original;
- DataTable categoryTable = new DataTable();
+ DataTable categoryTable = new();
dataAdapter.Fill(categoryTable);
DataRow categoryRow = categoryTable.Rows[0];
@@ -51,11 +52,9 @@ private static void AdapterUpdate(string connectionString)
}
//
- static private string GetConnectionString()
- {
+ static string GetConnectionString() =>
// To avoid storing the connection string in your code,
// you can retrieve it from a configuration file.
- return "Data Source=(local);Initial Catalog=Northwind;"
+ "Data Source=(local);Initial Catalog=Northwind;"
+ "Integrated Security=true";
- }
}
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.GetSchemaTable/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.GetSchemaTable/CS/Project.csproj
new file mode 100644
index 0000000000000..9659b3497e484
--- /dev/null
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.GetSchemaTable/CS/Project.csproj
@@ -0,0 +1,12 @@
+
+
+
+ Library
+ net6.0
+ enable
+
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.GetSchemaTable/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.GetSchemaTable/CS/source.cs
index a0e3da5ca2b40..fb6efc8260642 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.GetSchemaTable/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.GetSchemaTable/CS/source.cs
@@ -1,49 +1,46 @@
using System;
-using System.Data.SqlClient;
using System.Data;
+using System.Data.SqlClient;
-namespace NextResultCS
+namespace NextResultCS;
+
+static class Program
{
- class Program
+ static void Main()
{
- static void Main()
- {
- string s = GetConnectionString();
- SqlConnection c = new SqlConnection(s);
- GetSchemaInfo(c);
- Console.ReadLine();
- }
- //
- static void GetSchemaInfo(SqlConnection connection)
+ var s = GetConnectionString();
+ SqlConnection c = new(s);
+ GetSchemaInfo(c);
+ Console.ReadLine();
+ }
+ //
+ static void GetSchemaInfo(SqlConnection connection)
+ {
+ using (connection)
{
- using (connection)
- {
- SqlCommand command = new SqlCommand(
- "SELECT CategoryID, CategoryName FROM Categories;",
- connection);
- connection.Open();
+ SqlCommand command = new(
+ "SELECT CategoryID, CategoryName FROM Categories;",
+ connection);
+ connection.Open();
- SqlDataReader reader = command.ExecuteReader();
- DataTable schemaTable = reader.GetSchemaTable();
+ SqlDataReader reader = command.ExecuteReader();
+ DataTable schemaTable = reader.GetSchemaTable();
- foreach (DataRow row in schemaTable.Rows)
+ foreach (DataRow row in schemaTable.Rows)
+ {
+ foreach (DataColumn column in schemaTable.Columns)
{
- foreach (DataColumn column in schemaTable.Columns)
- {
- Console.WriteLine(String.Format("{0} = {1}",
- column.ColumnName, row[column]));
- }
+ Console.WriteLine(string.Format("{0} = {1}",
+ column.ColumnName, row[column]));
}
}
}
- //
-
- static private string GetConnectionString()
- {
- // To avoid storing the connection string in your code,
- // you can retrieve it from a configuration file.
- return "Data Source=(local);Initial Catalog=Northwind;"
- + "Integrated Security=SSPI";
- }
}
+ //
+
+ static string GetConnectionString() =>
+ // To avoid storing the connection string in your code,
+ // you can retrieve it from a configuration file.
+ "Data Source=(local);Initial Catalog=Northwind;"
+ + "Integrated Security=SSPI";
}
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.GetXmlDataReader/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.GetXmlDataReader/CS/Project.csproj
new file mode 100644
index 0000000000000..9659b3497e484
--- /dev/null
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.GetXmlDataReader/CS/Project.csproj
@@ -0,0 +1,12 @@
+
+
+
+ Library
+ net6.0
+ enable
+
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.GetXmlDataReader/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.GetXmlDataReader/CS/source.cs
index dc3094b0d84cd..fed73ae355204 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.GetXmlDataReader/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.GetXmlDataReader/CS/source.cs
@@ -1,14 +1,13 @@
using System;
-using System.Data;
using System.Data.SqlClient;
-using System.Xml;
using System.Data.SqlTypes;
+using System.Xml;
-class Class1
+static class Class1
{
static void Main()
{
- string c = "Data Source=(local);Integrated Security=true;" +
+ const string c = "Data Source=(local);Integrated Security=true;" +
"Initial Catalog=AdventureWorks; ";
GetXmlData(c);
Console.ReadLine();
@@ -21,7 +20,7 @@ static void Main()
static void GetXmlData(string connectionString)
{
- using (SqlConnection connection = new SqlConnection(connectionString))
+ using (SqlConnection connection = new(connectionString))
{
connection.Open();
@@ -30,18 +29,18 @@ static void GetXmlData(string connectionString)
// for the CustomerID criteria. The example selects two rows
// in order to demonstrate reading first from one row to
// another, then from one node to another within the xml column.
- string commandText =
+ const string commandText =
"SELECT Demographics from Sales.Store WHERE " +
"CustomerID = 3 OR CustomerID = 4";
- SqlCommand commandSales = new SqlCommand(commandText, connection);
+ SqlCommand commandSales = new(commandText, connection);
SqlDataReader salesReaderData = commandSales.ExecuteReader();
// Multiple rows are returned by the SELECT, so each row
// is read and an XmlReader (an xml data type) is set to the
// value of its first (and only) column.
- int countRow = 1;
+ var countRow = 1;
while (salesReaderData.Read())
// Must use GetSqlXml here to get a SqlXml type.
// GetValue returns a string instead of SqlXml.
@@ -61,14 +60,14 @@ static void GetXmlData(string connectionString)
{
if (salesReaderXml.NodeType == XmlNodeType.Element)
{
- string elementLocalName =
+ var elementLocalName =
salesReaderXml.LocalName;
salesReaderXml.Read();
Console.WriteLine(elementLocalName + ": " +
salesReaderXml.Value);
}
}
- countRow = countRow + 1;
+ countRow++;
}
}
}
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.HasRows/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.HasRows/CS/Project.csproj
new file mode 100644
index 0000000000000..9659b3497e484
--- /dev/null
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.HasRows/CS/Project.csproj
@@ -0,0 +1,12 @@
+
+
+
+ Library
+ net6.0
+ enable
+
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.HasRows/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.HasRows/CS/source.cs
index 96fe012ecdeab..4bcf548c6ee43 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.HasRows/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.HasRows/CS/source.cs
@@ -1,52 +1,48 @@
using System;
using System.Data.SqlClient;
-using System.Data;
-namespace NextResultCS
+namespace NextResultCS;
+
+static class Program
{
- class Program
+ static void Main()
{
- static void Main()
- {
- string s = GetConnectionString();
- SqlConnection c = new SqlConnection(s);
- HasRows(c);
- Console.ReadLine();
- }
- //
- static void HasRows(SqlConnection connection)
+ var s = GetConnectionString();
+ SqlConnection c = new(s);
+ HasRows(c);
+ Console.ReadLine();
+ }
+ //
+ static void HasRows(SqlConnection connection)
+ {
+ using (connection)
{
- using (connection)
- {
- SqlCommand command = new SqlCommand(
- "SELECT CategoryID, CategoryName FROM Categories;",
- connection);
- connection.Open();
+ SqlCommand command = new(
+ "SELECT CategoryID, CategoryName FROM Categories;",
+ connection);
+ connection.Open();
- SqlDataReader reader = command.ExecuteReader();
+ SqlDataReader reader = command.ExecuteReader();
- if (reader.HasRows)
- {
- while (reader.Read())
- {
- Console.WriteLine("{0}\t{1}", reader.GetInt32(0),
- reader.GetString(1));
- }
- }
- else
+ if (reader.HasRows)
+ {
+ while (reader.Read())
{
- Console.WriteLine("No rows found.");
+ Console.WriteLine("{0}\t{1}", reader.GetInt32(0),
+ reader.GetString(1));
}
- reader.Close();
}
- }
- //
- static private string GetConnectionString()
- {
- // To avoid storing the connection string in your code,
- // you can retrieve it from a configuration file.
- return "Data Source=(local);Initial Catalog=Northwind;"
- + "Integrated Security=SSPI";
+ else
+ {
+ Console.WriteLine("No rows found.");
+ }
+ reader.Close();
}
}
+ //
+ static string GetConnectionString() =>
+ // To avoid storing the connection string in your code,
+ // you can retrieve it from a configuration file.
+ "Data Source=(local);Initial Catalog=Northwind;"
+ + "Integrated Security=SSPI";
}
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.MergeIdentity/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.MergeIdentity/CS/Project.csproj
new file mode 100644
index 0000000000000..9659b3497e484
--- /dev/null
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.MergeIdentity/CS/Project.csproj
@@ -0,0 +1,12 @@
+
+
+
+ Library
+ net6.0
+ enable
+
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.MergeIdentity/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.MergeIdentity/CS/source.cs
index 70bc8ec8cd385..a08c40fce12f9 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.MergeIdentity/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.MergeIdentity/CS/source.cs
@@ -6,28 +6,29 @@ class Program
{
static void Main()
{
- string connectionString = GetConnectionString();
+ var connectionString = GetConnectionString();
MergeIdentityColumns(connectionString);
Console.ReadLine();
}
//
- private static void MergeIdentityColumns(string connectionString)
+ static void MergeIdentityColumns(string connectionString)
{
using (SqlConnection connection =
- new SqlConnection(connectionString))
+ new(connectionString))
{
// Create the DataAdapter
SqlDataAdapter adapter =
- new SqlDataAdapter(
+ new(
"SELECT ShipperID, CompanyName FROM dbo.Shippers",
- connection);
-
- //Add the InsertCommand to retrieve new identity value.
- adapter.InsertCommand = new SqlCommand(
+ connection)
+ {
+ //Add the InsertCommand to retrieve new identity value.
+ InsertCommand = new SqlCommand(
"INSERT INTO dbo.Shippers (CompanyName) " +
"VALUES (@CompanyName); " +
"SELECT ShipperID, CompanyName FROM dbo.Shippers " +
- "WHERE ShipperID = SCOPE_IDENTITY();", connection);
+ "WHERE ShipperID = SCOPE_IDENTITY();", connection)
+ };
// Add the parameter for the inserted value.
adapter.InsertCommand.Parameters.Add(
@@ -40,7 +41,7 @@ private static void MergeIdentityColumns(string connectionString)
adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
// Fill the DataTable.
- DataTable shipper = new DataTable();
+ DataTable shipper = new();
adapter.Fill(shipper);
// Add a new shipper.
@@ -50,11 +51,11 @@ private static void MergeIdentityColumns(string connectionString)
// Add changed rows to a new DataTable. This
// DataTable will be used by the DataAdapter.
- DataTable dataChanges = shipper.GetChanges();
+ DataTable dataChanges = shipper.GetChanges()!;
// Add the event handler.
adapter.RowUpdated +=
- new SqlRowUpdatedEventHandler(OnRowUpdated);
+ OnRowUpdated;
adapter.Update(dataChanges);
connection.Close();
@@ -88,11 +89,9 @@ protected static void OnRowUpdated(
}
//
- static private string GetConnectionString()
- {
+ static string GetConnectionString() =>
// To avoid storing the connection string in your code,
// you can retrieve it from a configuration file.
- return "Data Source=(local);Initial Catalog=Northwind;"
+ "Data Source=(local);Initial Catalog=Northwind;"
+ "Integrated Security=true";
- }
}
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.NextResult/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.NextResult/CS/Project.csproj
new file mode 100644
index 0000000000000..9659b3497e484
--- /dev/null
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.NextResult/CS/Project.csproj
@@ -0,0 +1,12 @@
+
+
+
+ Library
+ net6.0
+ enable
+
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.NextResult/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.NextResult/CS/source.cs
index d4c85f4b5ae9c..50df721767981 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.NextResult/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.NextResult/CS/source.cs
@@ -1,54 +1,48 @@
using System;
-using System.Collections.Generic;
-using System.Text;
using System.Data.SqlClient;
-using System.Data;
-namespace NextResultCS
+namespace NextResultCS;
+
+static class Program
{
- class Program
+ static void Main()
{
- static void Main()
- {
- string s = GetConnectionString();
- SqlConnection c = new SqlConnection(s);
- RetrieveMultipleResults(c);
- Console.ReadLine();
- }
- //
- static void RetrieveMultipleResults(SqlConnection connection)
+ var s = GetConnectionString();
+ SqlConnection c = new(s);
+ RetrieveMultipleResults(c);
+ Console.ReadLine();
+ }
+ //
+ static void RetrieveMultipleResults(SqlConnection connection)
+ {
+ using (connection)
{
- using (connection)
- {
- SqlCommand command = new SqlCommand(
- "SELECT CategoryID, CategoryName FROM dbo.Categories;" +
- "SELECT EmployeeID, LastName FROM dbo.Employees",
- connection);
- connection.Open();
+ SqlCommand command = new(
+ "SELECT CategoryID, CategoryName FROM dbo.Categories;" +
+ "SELECT EmployeeID, LastName FROM dbo.Employees",
+ connection);
+ connection.Open();
- SqlDataReader reader = command.ExecuteReader();
+ SqlDataReader reader = command.ExecuteReader();
- while (reader.HasRows)
- {
- Console.WriteLine("\t{0}\t{1}", reader.GetName(0),
- reader.GetName(1));
+ while (reader.HasRows)
+ {
+ Console.WriteLine("\t{0}\t{1}", reader.GetName(0),
+ reader.GetName(1));
- while (reader.Read())
- {
- Console.WriteLine("\t{0}\t{1}", reader.GetInt32(0),
- reader.GetString(1));
- }
- reader.NextResult();
+ while (reader.Read())
+ {
+ Console.WriteLine("\t{0}\t{1}", reader.GetInt32(0),
+ reader.GetString(1));
}
+ reader.NextResult();
}
}
- //
- static private string GetConnectionString()
- {
- // To avoid storing the connection string in your code,
- // you can retrieve it from a configuration file.
- return "Data Source=(local);Initial Catalog=Northwind;"
- + "Integrated Security=SSPI";
- }
}
+ //
+ static string GetConnectionString() =>
+ // To avoid storing the connection string in your code,
+ // you can retrieve it from a configuration file.
+ "Data Source=(local);Initial Catalog=Northwind;"
+ + "Integrated Security=SSPI";
}
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.RetrieveIdentityStoredProcedure/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.RetrieveIdentityStoredProcedure/CS/Project.csproj
new file mode 100644
index 0000000000000..9659b3497e484
--- /dev/null
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.RetrieveIdentityStoredProcedure/CS/Project.csproj
@@ -0,0 +1,12 @@
+
+
+
+ Library
+ net6.0
+ enable
+
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.RetrieveIdentityStoredProcedure/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.RetrieveIdentityStoredProcedure/CS/source.cs
index 2bd4353ef1c2a..a04473e9f71f6 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.RetrieveIdentityStoredProcedure/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.RetrieveIdentityStoredProcedure/CS/source.cs
@@ -2,30 +2,33 @@
using System.Data;
using System.Data.SqlClient;
-class Program
+static class Program
{
static void Main()
{
- string connectionString = GetConnectionString();
+ var connectionString = GetConnectionString();
RetrieveIdentity(connectionString);
Console.ReadLine();
}
//
- private static void RetrieveIdentity(string connectionString)
+ static void RetrieveIdentity(string connectionString)
{
using (SqlConnection connection =
- new SqlConnection(connectionString))
+ new(connectionString))
{
// Create a SqlDataAdapter based on a SELECT query.
SqlDataAdapter adapter =
- new SqlDataAdapter(
+ new(
"SELECT CategoryID, CategoryName FROM dbo.Categories",
- connection);
-
- //Create the SqlCommand to execute the stored procedure.
- adapter.InsertCommand = new SqlCommand("dbo.InsertCategory",
- connection);
- adapter.InsertCommand.CommandType = CommandType.StoredProcedure;
+ connection)
+ {
+ //Create the SqlCommand to execute the stored procedure.
+ InsertCommand = new SqlCommand("dbo.InsertCategory",
+ connection)
+ {
+ CommandType = CommandType.StoredProcedure
+ }
+ };
// Add the parameter for the CategoryName. Specifying the
// ParameterDirection for an input parameter is not required.
@@ -41,7 +44,7 @@ private static void RetrieveIdentity(string connectionString)
parameter.Direction = ParameterDirection.Output;
// Create a DataTable and fill it.
- DataTable categories = new DataTable();
+ DataTable categories = new();
adapter.Fill(categories);
// Add a new row.
@@ -62,11 +65,9 @@ private static void RetrieveIdentity(string connectionString)
}
//
- static private string GetConnectionString()
- {
+ static string GetConnectionString() =>
// To avoid storing the connection string in your code,
// you can retrieve it from a configuration file.
- return "Data Source=(local);Initial Catalog=Northwind;"
+ "Data Source=(local);Initial Catalog=Northwind;"
+ "Integrated Security=true";
- }
}
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.SprocIdentityReturn/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.SprocIdentityReturn/CS/Project.csproj
new file mode 100644
index 0000000000000..9659b3497e484
--- /dev/null
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.SprocIdentityReturn/CS/Project.csproj
@@ -0,0 +1,12 @@
+
+
+
+ Library
+ net6.0
+ enable
+
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.SprocIdentityReturn/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.SprocIdentityReturn/CS/source.cs
index e6d54cf8d5614..c81484610801d 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.SprocIdentityReturn/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.SprocIdentityReturn/CS/source.cs
@@ -3,25 +3,28 @@
using System.Data;
using System.Data.SqlClient;
-class Program
+static class Program
{
static void Main()
{
- string connectionString = GetConnectionString();
+ var connectionString = GetConnectionString();
ReturnIdentity(connectionString);
// Console.ReadLine();
}
- private static void ReturnIdentity(string connectionString)
+ static void ReturnIdentity(string connectionString)
{
- using (SqlConnection connection = new SqlConnection(connectionString))
+ using (SqlConnection connection = new(connectionString))
{
// Create a SqlDataAdapter based on a SELECT query.
- SqlDataAdapter adapter = new SqlDataAdapter("SELECT CategoryID, CategoryName FROM dbo.Categories", connection);
-
- // Create a SqlCommand to execute the stored procedure.
- adapter.InsertCommand = new SqlCommand("InsertCategory", connection);
- adapter.InsertCommand.CommandType = CommandType.StoredProcedure;
+ SqlDataAdapter adapter = new("SELECT CategoryID, CategoryName FROM dbo.Categories", connection)
+ {
+ // Create a SqlCommand to execute the stored procedure.
+ InsertCommand = new SqlCommand("InsertCategory", connection)
+ {
+ CommandType = CommandType.StoredProcedure
+ }
+ };
// Create a parameter for the ReturnValue.
SqlParameter parameter = adapter.InsertCommand.Parameters.Add("@RowCount", SqlDbType.Int);
@@ -36,7 +39,7 @@ private static void ReturnIdentity(string connectionString)
parameter.Direction = ParameterDirection.Output;
// Create a DataTable and fill it.
- DataTable categories = new DataTable();
+ DataTable categories = new();
adapter.Fill(categories);
// Add a new row.
@@ -48,22 +51,20 @@ private static void ReturnIdentity(string connectionString)
adapter.Update(categories);
// Retrieve the ReturnValue.
- Int32 rowCount = (Int32)adapter.InsertCommand.Parameters["@RowCount"].Value;
+ var rowCount = (int)adapter.InsertCommand.Parameters["@RowCount"].Value;
Console.WriteLine("ReturnValue: {0}", rowCount.ToString());
Console.WriteLine("All Rows:");
foreach (DataRow row in categories.Rows)
{
- Console.WriteLine(" {0}: {1}", row[0], row[1]);
+ Console.WriteLine(" {0}: {1}", row[0], row[1]);
}
}
}
- static private string GetConnectionString()
- {
+ static string GetConnectionString() =>
// To avoid storing the connection string in your code,
// you can retrieve it from a configuration file.
- return "Data Source=(local);Initial Catalog=Northwind;Integrated Security=true";
- }
+ "Data Source=(local);Initial Catalog=Northwind;Integrated Security=true";
}
//
\ No newline at end of file
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.StoredProcedure/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.StoredProcedure/CS/Project.csproj
new file mode 100644
index 0000000000000..9659b3497e484
--- /dev/null
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.StoredProcedure/CS/Project.csproj
@@ -0,0 +1,12 @@
+
+
+
+ Library
+ net6.0
+ enable
+
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.StoredProcedure/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.StoredProcedure/CS/source.cs
index 1559d56e69f40..9f8016fbdf16d 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.StoredProcedure/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.StoredProcedure/CS/source.cs
@@ -1,7 +1,8 @@
using System;
using System.Data;
using System.Data.SqlClient;
-class Program
+
+static class Program
{
static void Main()
{
@@ -14,20 +15,24 @@ static void Main()
static void GetSalesByCategory(string connectionString,
string categoryName)
{
- using (SqlConnection connection = new SqlConnection(connectionString))
+ using (SqlConnection connection = new(connectionString))
{
// Create the command and set its properties.
- SqlCommand command = new SqlCommand();
- command.Connection = connection;
- command.CommandText = "SalesByCategory";
- command.CommandType = CommandType.StoredProcedure;
+ SqlCommand command = new()
+ {
+ Connection = connection,
+ CommandText = "SalesByCategory",
+ 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;
+ SqlParameter parameter = new()
+ {
+ ParameterName = "@CategoryName",
+ SqlDbType = SqlDbType.NVarChar,
+ Direction = ParameterDirection.Input,
+ Value = categoryName
+ };
// Add the parameter to the Parameters collection.
command.Parameters.Add(parameter);
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlCommand.ExecuteScalar/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlCommand.ExecuteScalar/CS/Project.csproj
new file mode 100644
index 0000000000000..9659b3497e484
--- /dev/null
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlCommand.ExecuteScalar/CS/Project.csproj
@@ -0,0 +1,12 @@
+
+
+
+ Library
+ net6.0
+ enable
+
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlCommand.ExecuteScalar/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlCommand.ExecuteScalar/CS/source.cs
index 3dc28f824a31b..d4005d950a4e7 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlCommand.ExecuteScalar/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlCommand.ExecuteScalar/CS/source.cs
@@ -2,44 +2,42 @@
using System.Data;
using System.Data.SqlClient;
-class Class1
+static class Class1
{
static void Main()
{
- int ret = AddProductCategory("newval", GetConnectionString());
+ var ret = AddProductCategory("newval", GetConnectionString());
Console.WriteLine(ret.ToString());
Console.ReadLine();
}
//
- static public int AddProductCategory(string newName, string connString)
+ public static int AddProductCategory(string newName, string connString)
{
- Int32 newProdID = 0;
- string sql =
+ var newProdID = 0;
+ const string sql =
"INSERT INTO Production.ProductCategory (Name) VALUES (@Name); "
+ "SELECT CAST(scope_identity() AS int)";
- using (SqlConnection conn = new SqlConnection(connString))
+ using (SqlConnection conn = new(connString))
{
- SqlCommand cmd = new SqlCommand(sql, conn);
+ SqlCommand cmd = new(sql, conn);
cmd.Parameters.Add("@Name", SqlDbType.VarChar);
cmd.Parameters["@name"].Value = newName;
try
{
conn.Open();
- newProdID = (Int32)cmd.ExecuteScalar();
+ newProdID = (int)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
- return (int)newProdID;
+ return newProdID;
}
//
- static private string GetConnectionString()
- {
+ static string GetConnectionString() =>
// To avoid storing the connection string in your code,
// you can retrieve it from a configuration file.
- return "Data Source=(local);Initial Catalog=AdventureWorks;"
+ "Data Source=(local);Initial Catalog=AdventureWorks;"
+ "Integrated Security=true";
- }
}
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlConnectionStringBuilder.UserNamePwd/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlConnectionStringBuilder.UserNamePwd/CS/Project.csproj
new file mode 100644
index 0000000000000..8f99831a66cfa
--- /dev/null
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlConnectionStringBuilder.UserNamePwd/CS/Project.csproj
@@ -0,0 +1,14 @@
+
+
+
+ Library
+ net6.0
+ enable
+
+
+
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlConnectionStringBuilder.UserNamePwd/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlConnectionStringBuilder.UserNamePwd/CS/source.cs
index 4011db5fcb09b..fb5592fb7e29c 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlConnectionStringBuilder.UserNamePwd/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlConnectionStringBuilder.UserNamePwd/CS/source.cs
@@ -1,9 +1,8 @@
using System;
-using System.Data;
-using System.Data.SqlClient;
using System.Configuration;
+using System.Data.SqlClient;
-class Program
+static class Program
{
static void Main()
{
@@ -12,7 +11,7 @@ static void Main()
}
//
- private static void BuildConnectionString(string dataSource,
+ static void BuildConnectionString(string dataSource,
string userName, string userPassword)
{
// Retrieve the partial connection string named databaseConnection
@@ -20,21 +19,22 @@ private static void BuildConnectionString(string dataSource,
ConnectionStringSettings settings =
ConfigurationManager.ConnectionStrings["partialConnectString"];
- if (null != settings)
+ if (settings != null)
{
// Retrieve the partial connection string.
- string connectString = settings.ConnectionString;
+ var 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;
+ new(connectString)
+ {
+ // Supply the additional values.
+ DataSource = dataSource,
+ UserID = userName,
+ Password = userPassword
+ };
Console.WriteLine("Modified: {0}", builder.ConnectionString);
}
}
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Default.aspx b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Default.aspx
deleted file mode 100644
index 54377e2740f4b..0000000000000
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Default.aspx
+++ /dev/null
@@ -1,19 +0,0 @@
-<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
-
-
-
-
-
- Untitled Page
-
-
-
-
-
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Default.aspx.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Default.aspx.cs
deleted file mode 100644
index 59dcc432dfea4..0000000000000
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Default.aspx.cs
+++ /dev/null
@@ -1,80 +0,0 @@
-using System;
-using System.Data;
-using System.Configuration;
-using System.Web;
-using System.Web.Security;
-using System.Web.UI;
-using System.Web.UI.WebControls;
-using System.Web.UI.WebControls.WebParts;
-using System.Web.UI.HtmlControls;
-using System.Data.SqlClient;
-using System.Web.Caching;
-
-public partial class _Default : System.Web.UI.Page
-{
- //
- protected void Page_Load(object sender, EventArgs e)
- {
- Label1.Text = "Cache Refresh: " +
- DateTime.Now.ToLongTimeString();
-
- // Create a dependency connection to the database.
- SqlDependency.Start(GetConnectionString());
-
- using (SqlConnection connection =
- new SqlConnection(GetConnectionString()))
- {
- using (SqlCommand command =
- new SqlCommand(GetSQL(), connection))
- {
- SqlCacheDependency dependency =
- new SqlCacheDependency(command);
- // Refresh the cache after the number of minutes
- // listed below if a change does not occur.
- // This value could be stored in a configuration file.
- int numberOfMinutes = 3;
- DateTime expires =
- DateTime.Now.AddMinutes(numberOfMinutes);
-
- Response.Cache.SetExpires(expires);
- Response.Cache.SetCacheability(HttpCacheability.Public);
- Response.Cache.SetValidUntilExpires(true);
-
- Response.AddCacheDependency(dependency);
-
- connection.Open();
-
- GridView1.DataSource = command.ExecuteReader();
- GridView1.DataBind();
- }
- }
- }
- //
-
- //
- private string GetConnectionString()
- {
- // To avoid storing the connection string in your code,
- // you can retrieve it from a configuration file.
- return "Data Source=(local);Integrated Security=true;" +
- "Initial Catalog=AdventureWorks;";
- }
- private string GetSQL()
- {
- return "SELECT Production.Product.ProductID, " +
- "Production.Product.Name, " +
- "Production.Location.Name AS Location, " +
- "Production.ProductInventory.Quantity " +
- "FROM Production.Product INNER JOIN " +
- "Production.ProductInventory " +
- "ON Production.Product.ProductID = " +
- "Production.ProductInventory.ProductID " +
- "INNER JOIN Production.Location " +
- "ON Production.ProductInventory.LocationID = " +
- "Production.Location.LocationID " +
- "WHERE ( Production.ProductInventory.Quantity <= 100 ) " +
- "ORDER BY Production.ProductInventory.Quantity, " +
- "Production.Product.Name;";
- }
- //
-}
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlNotification.Perms/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlNotification.Perms/CS/source.cs
deleted file mode 100644
index 8dc1c29839f9f..0000000000000
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlNotification.Perms/CS/source.cs
+++ /dev/null
@@ -1,33 +0,0 @@
-using System;
-using System.Data;
-using System.Security.Permissions;
-using System.Data.SqlClient;
-
-class Program
-{
- static void Main()
- {
- }
-
- //
- // Code requires directives to
- // System.Security.Permissions and
- // System.Data.SqlClient
-
- private bool CanRequestNotifications()
- {
- SqlClientPermission permission =
- new SqlClientPermission(
- PermissionState.Unrestricted);
- try
- {
- permission.Demand();
- return true;
- }
- catch (System.Exception)
- {
- return false;
- }
- }
- //
-}
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTransaction.Local/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTransaction.Local/CS/Project.csproj
new file mode 100644
index 0000000000000..9659b3497e484
--- /dev/null
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTransaction.Local/CS/Project.csproj
@@ -0,0 +1,12 @@
+
+
+
+ Library
+ net6.0
+ enable
+
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTransaction.Local/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTransaction.Local/CS/source.cs
index d59c5265227ff..17f274d8d3e39 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTransaction.Local/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTransaction.Local/CS/source.cs
@@ -1,66 +1,64 @@
using System;
-using System.Data;
using System.Data.SqlClient;
-namespace SqlPrepareCS
+namespace SqlPrepareCS;
+
+static class Program
{
- class Program
+ static void Main()
{
- static void Main()
- {
- string connectionString =
- "Persist Security Info=False;Integrated Security=true;database=Northwind;server=(local)";
- LocalTrans(connectionString);
- Console.ReadLine();
- }
- private static void LocalTrans(string connectionString)
+ const string connectionString =
+ "Persist Security Info=False;Integrated Security=true;database=Northwind;server=(local)";
+ LocalTrans(connectionString);
+ Console.ReadLine();
+ }
+ static void LocalTrans(string connectionString)
+ {
+ //
+ using (SqlConnection connection = new(connectionString))
{
- //
- using (SqlConnection connection = new SqlConnection(connectionString))
- {
- connection.Open();
+ connection.Open();
- // Start a local transaction.
- SqlTransaction sqlTran = connection.BeginTransaction();
+ // Start a local transaction.
+ SqlTransaction sqlTran = connection.BeginTransaction();
- // Enlist a command in the current transaction.
- SqlCommand command = connection.CreateCommand();
- command.Transaction = sqlTran;
+ // Enlist a command in the current transaction.
+ SqlCommand command = connection.CreateCommand();
+ command.Transaction = sqlTran;
+
+ try
+ {
+ // Execute two separate commands.
+ command.CommandText =
+ "INSERT INTO Production.ScrapReason(Name) VALUES('Wrong size')";
+ command.ExecuteNonQuery();
+ command.CommandText =
+ "INSERT INTO Production.ScrapReason(Name) VALUES('Wrong color')";
+ command.ExecuteNonQuery();
+
+ // Commit the transaction.
+ sqlTran.Commit();
+ Console.WriteLine("Both records were written to database.");
+ }
+ catch (Exception ex)
+ {
+ // Handle the exception if the transaction fails to commit.
+ Console.WriteLine(ex.Message);
try
{
- // Execute two separate commands.
- command.CommandText =
- "INSERT INTO Production.ScrapReason(Name) VALUES('Wrong size')";
- command.ExecuteNonQuery();
- command.CommandText =
- "INSERT INTO Production.ScrapReason(Name) VALUES('Wrong color')";
- command.ExecuteNonQuery();
-
- // Commit the transaction.
- sqlTran.Commit();
- Console.WriteLine("Both records were written to database.");
+ // Attempt to roll back the transaction.
+ sqlTran.Rollback();
}
- catch (Exception ex)
+ catch (Exception exRollback)
{
- // Handle the exception if the transaction fails to commit.
- Console.WriteLine(ex.Message);
-
- try
- {
- // Attempt to roll back the transaction.
- sqlTran.Rollback();
- }
- catch (Exception exRollback)
- {
- // Throws an InvalidOperationException if the connection
- // is closed or the transaction has already been rolled
- // back on the server.
- Console.WriteLine(exRollback.Message);
- }
+ // Throws an InvalidOperationException if the connection
+ // is closed or the transaction has already been rolled
+ // back on the server.
+ Console.WriteLine(exRollback.Message);
}
}
- //
}
+ //
}
}
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTypes.CompareNulls/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTypes.CompareNulls/CS/Project.csproj
index b83f0211b39c5..a3684f75383e5 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTypes.CompareNulls/CS/Project.csproj
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTypes.CompareNulls/CS/Project.csproj
@@ -3,5 +3,9 @@
Library
net6.0
-
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTypes.CompareNulls/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTypes.CompareNulls/CS/source.cs
index c05f4c0a97f6e..dc078d54c2490 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTypes.CompareNulls/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTypes.CompareNulls/CS/source.cs
@@ -1,60 +1,58 @@
using System;
-using System.Data;
using System.Data.SqlTypes;
-namespace SqlNullsCS
+namespace SqlNullsCS;
+
+static class Program
{
- class Program
+ static void Main()
+ {
+ CompareNulls();
+ Console.ReadLine();
+ }
+ //
+ static void CompareNulls()
+ {
+ // Create two new null strings.
+ SqlString a = new();
+ SqlString b = new();
+
+ // Compare nulls using static/shared SqlString.Equals.
+ Console.WriteLine("SqlString.Equals shared/static method:");
+ Console.WriteLine(" Two nulls={0}", SqlStringEquals(a, b));
+
+ // Compare nulls using instance method String.Equals.
+ Console.WriteLine();
+ Console.WriteLine("String.Equals instance method:");
+ Console.WriteLine(" Two nulls={0}", StringEquals(a, b));
+
+ // Make them empty strings.
+ a = "";
+ b = "";
+
+ // When comparing two empty strings (""), both the shared/static and
+ // the instance Equals methods evaluate to true.
+ Console.WriteLine();
+ Console.WriteLine("SqlString.Equals shared/static method:");
+ Console.WriteLine(" Two empty strings={0}", SqlStringEquals(a, b));
+
+ Console.WriteLine();
+ Console.WriteLine("String.Equals instance method:");
+ Console.WriteLine(" Two empty strings={0}", StringEquals(a, b));
+ }
+
+ static string SqlStringEquals(SqlString string1, SqlString string2)
+ {
+ // SqlString.Equals uses database semantics for evaluating nulls.
+ var returnValue = SqlString.Equals(string1, string2).ToString();
+ return returnValue;
+ }
+
+ static string StringEquals(SqlString string1, SqlString string2)
{
- static void Main()
- {
- CompareNulls();
- Console.ReadLine();
- }
- //
- private static void CompareNulls()
- {
- // Create two new null strings.
- SqlString a = new SqlString();
- SqlString b = new SqlString();
-
- // Compare nulls using static/shared SqlString.Equals.
- Console.WriteLine("SqlString.Equals shared/static method:");
- Console.WriteLine(" Two nulls={0}", SqlStringEquals(a, b));
-
- // Compare nulls using instance method String.Equals.
- Console.WriteLine();
- Console.WriteLine("String.Equals instance method:");
- Console.WriteLine(" Two nulls={0}", StringEquals(a, b));
-
- // Make them empty strings.
- a = "";
- b = "";
-
- // When comparing two empty strings (""), both the shared/static and
- // the instance Equals methods evaluate to true.
- Console.WriteLine();
- Console.WriteLine("SqlString.Equals shared/static method:");
- Console.WriteLine(" Two empty strings={0}", SqlStringEquals(a, b));
-
- Console.WriteLine();
- Console.WriteLine("String.Equals instance method:");
- Console.WriteLine(" Two empty strings={0}", StringEquals(a, b));
- }
-
- private static string SqlStringEquals(SqlString string1, SqlString string2)
- {
- // SqlString.Equals uses database semantics for evaluating nulls.
- string returnValue = SqlString.Equals(string1, string2).ToString();
- return returnValue;
- }
-
- private static string StringEquals(SqlString string1, SqlString string2)
- {
- // String.Equals uses CLR type semantics for evaluating nulls.
- string returnValue = string1.Equals(string2).ToString();
- return returnValue;
- }
+ // String.Equals uses CLR type semantics for evaluating nulls.
+ var returnValue = string1.Equals(string2).ToString();
+ return returnValue;
}
- //
}
+//
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTypes.GetTypeAW/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTypes.GetTypeAW/CS/Project.csproj
new file mode 100644
index 0000000000000..9659b3497e484
--- /dev/null
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTypes.GetTypeAW/CS/Project.csproj
@@ -0,0 +1,12 @@
+
+
+
+ Library
+ net6.0
+ enable
+
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTypes.GetTypeAW/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTypes.GetTypeAW/CS/source.cs
index abeaebcd17d7f..559a817556707 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTypes.GetTypeAW/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTypes.GetTypeAW/CS/source.cs
@@ -3,45 +3,43 @@
using System.Data.SqlClient;
using System.Data.SqlTypes;
-class Program
+static class Program
{
static void Main()
{
- string connectionString = GetConnectionString();
+ var connectionString = GetConnectionString();
GetSqlTypesAW(connectionString);
Console.ReadLine();
}
//
- static private void GetSqlTypesAW(string connectionString)
+ static void GetSqlTypesAW(string connectionString)
{
// Create a DataTable and specify a SqlType
// for each column.
- DataTable table = new DataTable();
- DataColumn icolumnolumn =
- table.Columns.Add("SalesOrderID", typeof(SqlInt32));
- DataColumn priceColumn =
- table.Columns.Add("UnitPrice", typeof(SqlMoney));
- DataColumn totalColumn =
- table.Columns.Add("LineTotal", typeof(SqlDecimal));
- DataColumn columnModifiedDate =
- table.Columns.Add("ModifiedDate", typeof(SqlDateTime));
+ DataTable table = new();
+ table.Columns.Add("SalesOrderID", typeof(SqlInt32));
+ table.Columns.Add("UnitPrice", typeof(SqlMoney));
+ table.Columns.Add("LineTotal", typeof(SqlDecimal));
+ table.Columns.Add("ModifiedDate", typeof(SqlDateTime));
// Open a connection to SQL Server and fill the DataTable
// with data from the Sales.SalesOrderDetail table
// in the AdventureWorks sample database.
- using (SqlConnection connection = new SqlConnection(connectionString))
+ using (SqlConnection connection = new(connectionString))
{
- string queryString =
+ const string queryString =
"SELECT TOP 5 SalesOrderID, UnitPrice, LineTotal, ModifiedDate "
+ "FROM Sales.SalesOrderDetail WHERE LineTotal < @LineTotal";
// Create the SqlCommand.
- SqlCommand command = new SqlCommand(queryString, connection);
+ SqlCommand command = new(queryString, connection);
// Create the SqlParameter and assign a value.
SqlParameter parameter =
- new SqlParameter("@LineTotal", SqlDbType.Decimal);
- parameter.Value = 1.5;
+ new("@LineTotal", SqlDbType.Decimal)
+ {
+ Value = 1.5
+ };
command.Parameters.Add(parameter);
// Open the connection and load the data.
@@ -75,12 +73,10 @@ static private void GetSqlTypesAW(string connectionString)
}
//
- static private string GetConnectionString()
- {
+ static string GetConnectionString() =>
// To avoid storing the connection string in your code,
// you can retrieve it from a configuration file, using the
// System.Configuration.ConfigurationSettings.AppSettings property
- return "Data Source=(local);Initial Catalog=AdventureWorks;"
+ "Data Source=(local);Initial Catalog=AdventureWorks;"
+ "Integrated Security=SSPI;";
- }
}
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTypes.Guid/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTypes.Guid/CS/Project.csproj
index b83f0211b39c5..a3684f75383e5 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTypes.Guid/CS/Project.csproj
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTypes.Guid/CS/Project.csproj
@@ -3,5 +3,9 @@
Library
net6.0
-
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTypes.Guid/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTypes.Guid/CS/source.cs
index 6467d345af880..ef886e81f8c00 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTypes.Guid/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTypes.Guid/CS/source.cs
@@ -1,9 +1,8 @@
using System;
-using System.Data;
using System.Collections;
using System.Data.SqlTypes;
-class Program
+static class Program
{
static void Main()
{
@@ -11,13 +10,15 @@ static void Main()
Console.ReadLine();
}
//
- private static void WorkWithGuids()
+ static void WorkWithGuids()
{
// Create an ArrayList and fill it with Guid values.
- ArrayList guidList = new ArrayList();
- guidList.Add(new Guid("3AAAAAAA-BBBB-CCCC-DDDD-2EEEEEEEEEEE"));
- guidList.Add(new Guid("2AAAAAAA-BBBB-CCCC-DDDD-1EEEEEEEEEEE"));
- guidList.Add(new Guid("1AAAAAAA-BBBB-CCCC-DDDD-3EEEEEEEEEEE"));
+ ArrayList guidList = new()
+ {
+ new Guid("3AAAAAAA-BBBB-CCCC-DDDD-2EEEEEEEEEEE"),
+ new Guid("2AAAAAAA-BBBB-CCCC-DDDD-1EEEEEEEEEEE"),
+ new Guid("1AAAAAAA-BBBB-CCCC-DDDD-3EEEEEEEEEEE")
+ };
// Display the unsorted Guid values.
Console.WriteLine("Unsorted Guids:");
@@ -39,10 +40,12 @@ private static void WorkWithGuids()
Console.WriteLine("");
// Create an ArrayList of SqlGuids.
- ArrayList sqlGuidList = new ArrayList();
- sqlGuidList.Add(new SqlGuid("3AAAAAAA-BBBB-CCCC-DDDD-2EEEEEEEEEEE"));
- sqlGuidList.Add(new SqlGuid("2AAAAAAA-BBBB-CCCC-DDDD-1EEEEEEEEEEE"));
- sqlGuidList.Add(new SqlGuid("1AAAAAAA-BBBB-CCCC-DDDD-3EEEEEEEEEEE"));
+ ArrayList sqlGuidList = new()
+ {
+ new SqlGuid("3AAAAAAA-BBBB-CCCC-DDDD-2EEEEEEEEEEE"),
+ new SqlGuid("2AAAAAAA-BBBB-CCCC-DDDD-1EEEEEEEEEEE"),
+ new SqlGuid("1AAAAAAA-BBBB-CCCC-DDDD-3EEEEEEEEEEE")
+ };
// Sort the SqlGuids. The unsorted SqlGuids are in the same order
// as the unsorted Guid values.
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTypes.IsNull/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTypes.IsNull/CS/Project.csproj
index b83f0211b39c5..a3684f75383e5 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTypes.IsNull/CS/Project.csproj
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTypes.IsNull/CS/Project.csproj
@@ -3,5 +3,9 @@
Library
net6.0
-
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTypes.IsNull/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTypes.IsNull/CS/source.cs
index 4f326c6bb5228..4a6738a76473f 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTypes.IsNull/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTypes.IsNull/CS/source.cs
@@ -1,9 +1,8 @@
using System;
using System.Data;
-using System.Data.SqlClient;
using System.Data.SqlTypes;
-class Program
+static class Program
{
static void Main()
{
@@ -11,9 +10,9 @@ static void Main()
Console.ReadLine();
}
//
- static private void WorkWithSqlNulls()
+ static void WorkWithSqlNulls()
{
- DataTable table = new DataTable();
+ DataTable table = new();
// Specify the SqlType for each column.
DataColumn idColumn =