diff --git a/docs/csharp/advanced-topics/interop/snippets/WinSound/snippets5000.json b/docs/csharp/advanced-topics/interop/snippets/WinSound/snippets.5000.json similarity index 100% rename from docs/csharp/advanced-topics/interop/snippets/WinSound/snippets5000.json rename to docs/csharp/advanced-topics/interop/snippets/WinSound/snippets.5000.json 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 index 2ca85bd23b436..129c97cbfa701 100644 --- 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 @@ -1,7 +1,7 @@ - Exe + WinExe net48 DP_LINQ_to_DataSet_Examples DP LINQ to DataSet Examples @@ -12,4 +12,12 @@ + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + 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 index bc0a1bdcfe87f..c6e99371a0c4f 100644 --- 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 @@ -1,14 +1,13 @@ // 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.Linq; using System.Windows.Forms; +// +//using System.Windows.Forms; namespace LINQtoDataSetSamples { @@ -1376,14 +1375,18 @@ static void ToDictionary() { // // Fill the DataSet. - DataSet ds = new DataSet(); - ds.Locale = CultureInfo.InvariantCulture; + DataSet ds = new DataSet + { + Locale = CultureInfo.InvariantCulture + }; FillDataSet(ds); DataTable products = ds.Tables["Product"]; - var scoreRecordsDict = products.AsEnumerable(). - ToDictionary(record => record.Field("Name")); + var scoreRecordsDict = + products.AsEnumerable() + .Where(rec=>rec.Field("Name") !=null) + .ToDictionary(record => record.Field("Name")); Console.WriteLine("Top Tube's ProductID: {0}", scoreRecordsDict["Top Tube"]["ProductID"]); // diff --git a/samples/snippets/visualbasic/VS_Snippets_VBCSharp/VbVbalrEvents/VB/snippets5000.json b/samples/snippets/csharp/VS_Snippets_ADO.NET/DP LINQ to DataSet Examples/CS/snippets5000.json similarity index 100% rename from samples/snippets/visualbasic/VS_Snippets_VBCSharp/VbVbalrEvents/VB/snippets5000.json rename to samples/snippets/csharp/VS_Snippets_ADO.NET/DP LINQ to DataSet Examples/CS/snippets5000.json 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/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataSet.Merge/CS/Project.csproj new file mode 100644 index 0000000000000..9659b3497e484 --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataSet.Merge/CS/Project.csproj @@ -0,0 +1,12 @@ + + + + Library + net6.0 + enable + + + + + + 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 index 9e53535d8b21e..b2c83cc92b5b8 100644 --- 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 @@ -2,32 +2,32 @@ using System.Data; using System.Data.SqlClient; -class Program +static 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); connection.Open(); - DataSet customers = new DataSet(); + DataSet customers = new(); adapter.FillSchema(customers, SchemaType.Source, "Customers"); adapter.Fill(customers, "Customers"); - DataSet orders = new DataSet(); + DataSet orders = new(); orders.ReadXml("Orders.xml", XmlReadMode.ReadSchema); orders.AcceptChanges(); @@ -36,11 +36,9 @@ private static void ConnectToData(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=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/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.CAS/CS/Project.csproj new file mode 100644 index 0000000000000..24117b833cd7c --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.CAS/CS/Project.csproj @@ -0,0 +1,16 @@ + + + + Exe + net4.8 + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.CAS/CS/snippets.5000.json b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.CAS/CS/snippets.5000.json new file mode 100644 index 0000000000000..da9ebf8da2f9d --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.CAS/CS/snippets.5000.json @@ -0,0 +1,3 @@ +{ + "host": "visualstudio" +} 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 index 067b112defcf7..e2dcee9e64469 100644 --- 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 @@ -26,9 +26,9 @@ static void TestCAS(string connectString1, string connectString2) { 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(); + // 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); @@ -79,4 +79,4 @@ static void TestCAS(string connectString1, string connectString2) { } } } -// \ 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/App_Start/BundleConfig.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/App_Start/BundleConfig.cs new file mode 100644 index 0000000000000..5939d90e6fcaa --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/App_Start/BundleConfig.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; +using System.Web.Optimization; +using System.Web.UI; + +namespace WebApplication1 +{ + public class BundleConfig + { + // For more information on Bundling, visit https://go.microsoft.com/fwlink/?LinkID=303951 + public static void RegisterBundles(BundleCollection bundles) + { + bundles.Add(new ScriptBundle("~/bundles/WebFormsJs").Include( + "~/Scripts/WebForms/WebForms.js", + "~/Scripts/WebForms/WebUIValidation.js", + "~/Scripts/WebForms/MenuStandards.js", + "~/Scripts/WebForms/Focus.js", + "~/Scripts/WebForms/GridView.js", + "~/Scripts/WebForms/DetailsView.js", + "~/Scripts/WebForms/TreeView.js", + "~/Scripts/WebForms/WebParts.js")); + + // Order is very important for these files to work, they have explicit dependencies + bundles.Add(new ScriptBundle("~/bundles/MsAjaxJs").Include( + "~/Scripts/WebForms/MsAjax/MicrosoftAjax.js", + "~/Scripts/WebForms/MsAjax/MicrosoftAjaxApplicationServices.js", + "~/Scripts/WebForms/MsAjax/MicrosoftAjaxTimer.js", + "~/Scripts/WebForms/MsAjax/MicrosoftAjaxWebForms.js")); + + // Use the Development version of Modernizr to develop with and learn from. Then, when you’re + // ready for production, use the build tool at https://modernizr.com to pick only the tests you need + bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( + "~/Scripts/modernizr-*")); + } + } +} \ No newline at end of file diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/App_Start/RouteConfig.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/App_Start/RouteConfig.cs new file mode 100644 index 0000000000000..940da02127590 --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/App_Start/RouteConfig.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Web; +using System.Web.Routing; +using Microsoft.AspNet.FriendlyUrls; + +namespace WebApplication1 +{ + public static class RouteConfig + { + public static void RegisterRoutes(RouteCollection routes) + { + var settings = new FriendlyUrlSettings(); + settings.AutoRedirectMode = RedirectMode.Permanent; + routes.EnableFriendlyUrls(settings); + } + } +} 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 index 54377e2740f4b..1768254b03293 100644 --- 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 @@ -1,19 +1,14 @@ -<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> +<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._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 index 59dcc432dfea4..5f87063a6ed40 100644 --- 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 @@ -9,72 +9,76 @@ using System.Web.UI.HtmlControls; using System.Data.SqlClient; using System.Web.Caching; +//using Microsoft.Data.SqlClient; -public partial class _Default : System.Web.UI.Page +namespace WebApplication1 { - // - protected void Page_Load(object sender, EventArgs e) + public partial class _Default : System.Web.UI.Page { - Label1.Text = "Cache Refresh: " + - DateTime.Now.ToLongTimeString(); + // + 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()); + // Create a dependency connection to the database. + SqlDependency.Start(GetConnectionString()); - using (SqlConnection connection = - new SqlConnection(GetConnectionString())) - { - using (SqlCommand command = - new SqlCommand(GetSQL(), connection)) + using (SqlConnection connection = + new SqlConnection(GetConnectionString())) { - 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); + 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.Cache.SetExpires(expires); + Response.Cache.SetCacheability(HttpCacheability.Public); + Response.Cache.SetValidUntilExpires(true); - Response.AddCacheDependency(dependency); + Response.AddCacheDependency(dependency); - connection.Open(); + connection.Open(); - GridView1.DataSource = command.ExecuteReader(); - GridView1.DataBind(); + 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;"; + // + 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 SqlDependency.AspNet/CS/Default.aspx.designer.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Default.aspx.designer.cs new file mode 100644 index 0000000000000..f319f7ad483a0 --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Default.aspx.designer.cs @@ -0,0 +1,35 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace WebApplication1 +{ + + + public partial class _Default + { + + /// + /// Label1 control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.Label Label1; + + /// + /// GridView1 control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.GridView GridView1; + } +} diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Global.asax b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Global.asax new file mode 100644 index 0000000000000..e993a02f6984a --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Global.asax @@ -0,0 +1 @@ +<%@ Application Codebehind="Global.asax.cs" Inherits="WebApplication1.Global" Language="C#" %> diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Global.asax.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Global.asax.cs new file mode 100644 index 0000000000000..33836930e8306 --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Global.asax.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; +using System.Web.Optimization; +using System.Web.Routing; +using System.Web.Security; +using System.Web.SessionState; + +namespace WebApplication1 +{ + public class Global : HttpApplication + { + void Application_Start(object sender, EventArgs e) + { + // Code that runs on application startup + RouteConfig.RegisterRoutes(RouteTable.Routes); + BundleConfig.RegisterBundles(BundleTable.Bundles); + } + } +} \ No newline at end of file diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Properties/AssemblyInfo.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Properties/AssemblyInfo.cs new file mode 100644 index 0000000000000..0bf9e057ea2fe --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Properties/AssemblyInfo.cs @@ -0,0 +1,35 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("WebApplication1")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("WebApplication1")] +[assembly: AssemblyCopyright("Copyright © 2023")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("5f84044b-cfcc-48d5-9b5a-5ffda63f324b")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Revision and Build Numbers +// by using the '*' as shown below: +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Properties/launchSettings.json b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Properties/launchSettings.json new file mode 100644 index 0000000000000..334e62dc4f2f7 --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Properties/launchSettings.json @@ -0,0 +1,12 @@ +{ + "profiles": { + "Project": { + "commandName": "Project", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "applicationUrl": "https://localhost:53723;http://localhost:53724" + } + } +} \ No newline at end of file diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Site.Master b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Site.Master new file mode 100644 index 0000000000000..9c155677cc4f8 --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Site.Master @@ -0,0 +1,69 @@ +<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="WebApplication1.SiteMaster" %> + + + + + + + + <%: Page.Title %> - My ASP.NET Application + + + <%: Scripts.Render("~/bundles/modernizr") %> + + + + + + + + + + + <%--To learn more about bundling scripts in ScriptManager see https://go.microsoft.com/fwlink/?LinkID=301884 --%> + <%--Framework Scripts--%> + + + + + + + + + + + + <%--Site Scripts--%> + + + + + + Application name + + + + + + Home + About + Contact + + + + + + + + + + + + + <%: Scripts.Render("~/Scripts/bootstrap.js") %> + + + diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Site.Master.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Site.Master.cs new file mode 100644 index 0000000000000..92a88b4e80691 --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Site.Master.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; +using System.Web.UI; +using System.Web.UI.WebControls; + +namespace WebApplication1 +{ + public partial class SiteMaster : MasterPage + { + protected void Page_Load(object sender, EventArgs e) + { + + } + } +} \ No newline at end of file diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Site.Master.designer.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Site.Master.designer.cs new file mode 100644 index 0000000000000..2ac01259e7b99 --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Site.Master.designer.cs @@ -0,0 +1,35 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace WebApplication1 +{ + + + public partial class SiteMaster + { + + /// + /// HeadContent control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.ContentPlaceHolder HeadContent; + + /// + /// MainContent control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.ContentPlaceHolder MainContent; + } +} diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Site.Mobile.Master b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Site.Mobile.Master new file mode 100644 index 0000000000000..1d89354f87c75 --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Site.Mobile.Master @@ -0,0 +1,23 @@ +<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.Mobile.master.cs" Inherits="WebApplication1.Site_Mobile" %> +<%@ Register Src="~/ViewSwitcher.ascx" TagPrefix="friendlyUrls" TagName="ViewSwitcher" %> + + + + + + + + + + + + Mobile Master Page + + + + + + + + + diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Site.Mobile.Master.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Site.Mobile.Master.cs new file mode 100644 index 0000000000000..d50e0cc4e9e69 --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Site.Mobile.Master.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; +using System.Web.UI; +using System.Web.UI.WebControls; + +namespace WebApplication1 +{ + public partial class Site_Mobile : System.Web.UI.MasterPage + { + protected void Page_Load(object sender, EventArgs e) + { + + } + } +} \ No newline at end of file diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Site.Mobile.Master.designer.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Site.Mobile.Master.designer.cs new file mode 100644 index 0000000000000..b29be711cd58c --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Site.Mobile.Master.designer.cs @@ -0,0 +1,51 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace WebApplication1 { + + + public partial class Site_Mobile { + + /// + /// HeadContent control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.ContentPlaceHolder HeadContent; + + /// + /// form1 control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.HtmlControls.HtmlForm form1; + + /// + /// FeaturedContent control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.ContentPlaceHolder FeaturedContent; + + /// + /// MainContent control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.ContentPlaceHolder MainContent; + } +} diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/ViewSwitcher.ascx b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/ViewSwitcher.ascx new file mode 100644 index 0000000000000..7b36ab7065fa9 --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/ViewSwitcher.ascx @@ -0,0 +1,4 @@ +<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ViewSwitcher.ascx.cs" Inherits="WebApplication1.ViewSwitcher" %> + + <%: CurrentView %> view | Switch to <%: AlternateView %> + \ No newline at end of file diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/ViewSwitcher.ascx.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/ViewSwitcher.ascx.cs new file mode 100644 index 0000000000000..2d9b705b7e253 --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/ViewSwitcher.ascx.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; +using System.Web.Routing; +using System.Web.UI; +using System.Web.UI.WebControls; +using Microsoft.AspNet.FriendlyUrls.Resolvers; + +namespace WebApplication1 +{ + public partial class ViewSwitcher : System.Web.UI.UserControl + { + protected string CurrentView { get; private set; } + + protected string AlternateView { get; private set; } + + protected string SwitchUrl { get; private set; } + + protected void Page_Load(object sender, EventArgs e) + { + // Determine current view + var isMobile = WebFormsFriendlyUrlResolver.IsMobileView(new HttpContextWrapper(Context)); + CurrentView = isMobile ? "Mobile" : "Desktop"; + + // Determine alternate view + AlternateView = isMobile ? "Desktop" : "Mobile"; + + // Create switch URL from the route, e.g. ~/__FriendlyUrls_SwitchView/Mobile?ReturnUrl=/Page + var switchViewRouteName = "AspNet.FriendlyUrls.SwitchView"; + var switchViewRoute = RouteTable.Routes[switchViewRouteName]; + if (switchViewRoute == null) + { + // Friendly URLs is not enabled or the name of the switch view route is out of sync + this.Visible = false; + return; + } + var url = GetRouteUrl(switchViewRouteName, new { view = AlternateView, __FriendlyUrls_SwitchViews = true }); + url += "?ReturnUrl=" + HttpUtility.UrlEncode(Request.RawUrl); + SwitchUrl = url; + } + } +} \ No newline at end of file diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/ViewSwitcher.ascx.designer.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/ViewSwitcher.ascx.designer.cs new file mode 100644 index 0000000000000..c47ccbe8dd637 --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/ViewSwitcher.ascx.designer.cs @@ -0,0 +1,15 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace WebApplication1 { + + + public partial class ViewSwitcher { + } +} diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Web.Debug.config b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Web.Debug.config new file mode 100644 index 0000000000000..fae9cfefa9716 --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Web.Debug.config @@ -0,0 +1,30 @@ + + + + + + + + + + \ No newline at end of file diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Web.Release.config b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Web.Release.config new file mode 100644 index 0000000000000..da6e960b8d1e5 --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Web.Release.config @@ -0,0 +1,31 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Web.config b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Web.config new file mode 100644 index 0000000000000..c4cd507c1525c --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/Web.config @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/WebApplication1.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/WebApplication1.csproj new file mode 100644 index 0000000000000..e6a2e2e9d2d04 --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/WebApplication1.csproj @@ -0,0 +1,274 @@ + + + + + + Debug + AnyCPU + + + 2.0 + {5F84044B-CFCC-48D5-9B5A-5FFDA63F324B} + {349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} + Library + Properties + WebApplication1 + WebApplication1 + v4.8 + true + + 44325 + + + + + + + + + true + full + false + bin\ + DEBUG;TRACE + prompt + 4 + + + true + pdbonly + true + bin\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + True + packages\Microsoft.Web.Infrastructure.2.0.1\lib\net40\Microsoft.Web.Infrastructure.dll + + + packages\AspNet.ScriptManager.jQuery.3.4.1\lib\net45\AspNet.ScriptManager.jQuery.dll + + + packages\Microsoft.AspNet.ScriptManager.MSAjax.5.0.0\lib\net45\Microsoft.ScriptManager.MSAjax.dll + + + packages\Microsoft.AspNet.ScriptManager.WebForms.5.0.0\lib\net45\Microsoft.ScriptManager.WebForms.dll + + + packages\Microsoft.AspNet.Web.Optimization.1.1.3\lib\net40\System.Web.Optimization.dll + + + packages\Newtonsoft.Json.12.0.2\lib\net45\Newtonsoft.Json.dll + + + True + packages\WebGrease.1.6.0\lib\WebGrease.dll + + + True + packages\Antlr.3.5.0.2\lib\Antlr3.Runtime.dll + + + True + packages\Microsoft.AspNet.Web.Optimization.WebForms.1.1.3\lib\net45\Microsoft.AspNet.Web.Optimization.WebForms.dll + + + packages\Microsoft.AspNet.FriendlyUrls.Core.1.0.2\lib\net45\Microsoft.AspNet.FriendlyUrls.dll + + + + + packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.1\lib\net45\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.dll + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Default.aspx + ASPXCodeBehind + + + Default.aspx + + + Global.asax + + + + Site.Master + ASPXCodeBehind + + + Site.Master + + + Site.Mobile.Master + ASPXCodeBehind + + + Site.Mobile.Master + + + ViewSwitcher.ascx + ASPXCodeBehind + + + ViewSwitcher.ascx + + + + + + + + + + + Web.config + + + Web.config + + + + 10.0 + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) + + + + + + + + + True + True + 49399 + / + https://localhost:44325/ + False + False + + + False + + + + + + + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + + + \ No newline at end of file diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/WebApplication1.sln b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/WebApplication1.sln new file mode 100644 index 0000000000000..30395240c1b9e --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/WebApplication1.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.8.34316.72 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebApplication1", "WebApplication1.csproj", "{5F84044B-CFCC-48D5-9B5A-5FFDA63F324B}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {5F84044B-CFCC-48D5-9B5A-5FFDA63F324B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5F84044B-CFCC-48D5-9B5A-5FFDA63F324B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5F84044B-CFCC-48D5-9B5A-5FFDA63F324B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5F84044B-CFCC-48D5-9B5A-5FFDA63F324B}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {67050FDD-F4EB-40D7-BE43-D17A38A45B3F} + EndGlobalSection +EndGlobal diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/packages.config b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/packages.config new file mode 100644 index 0000000000000..372d43a97e638 --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/packages.config @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/snippets.5000.json b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/snippets.5000.json new file mode 100644 index 0000000000000..da9ebf8da2f9d --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlDependency.AspNet/CS/snippets.5000.json @@ -0,0 +1,3 @@ +{ + "host": "visualstudio" +} diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlNotification.Perms/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlNotification.Perms/CS/Project.csproj new file mode 100644 index 0000000000000..5d7d0ee624db5 --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlNotification.Perms/CS/Project.csproj @@ -0,0 +1,17 @@ + + + + Library + net6.0 + enable + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + 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 index 8dc1c29839f9f..6834c75eef339 100644 --- 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 @@ -1,6 +1,4 @@ -using System; -using System.Data; -using System.Security.Permissions; +using System.Security.Permissions; using System.Data.SqlClient; class Program 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 = diff --git a/samples/snippets/visualbasic/VS_Snippets_VBCSharp/VbVbalrEvents/VB/snippets.5000.json b/samples/snippets/visualbasic/VS_Snippets_VBCSharp/VbVbalrEvents/VB/snippets.5000.json new file mode 100644 index 0000000000000..da9ebf8da2f9d --- /dev/null +++ b/samples/snippets/visualbasic/VS_Snippets_VBCSharp/VbVbalrEvents/VB/snippets.5000.json @@ -0,0 +1,3 @@ +{ + "host": "visualstudio" +}