diff --git a/snippets/csharp/System.ComponentModel/AmbientValueAttribute/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/AmbientValueAttribute/Overview/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/AmbientValueAttribute/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/AmbientValueAttribute/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/AmbientValueAttribute/Overview/attributesdemocontrol.cs b/snippets/csharp/System.ComponentModel/AmbientValueAttribute/Overview/attributesdemocontrol.cs
index d599bc0d717..0d2ed8854bc 100644
--- a/snippets/csharp/System.ComponentModel/AmbientValueAttribute/Overview/attributesdemocontrol.cs
+++ b/snippets/csharp/System.ComponentModel/AmbientValueAttribute/Overview/attributesdemocontrol.cs
@@ -1,632 +1,511 @@
//
//
using System;
-using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Drawing;
-using System.Data;
using System.Reflection;
-using System.Text;
using System.Windows.Forms;
+using System.Globalization;
//
// This sample demonstrates the use of various attributes for
-// authoring a control.
-namespace AttributesDemoControlLibrary
+// authoring a control.
+namespace AttributesDemoControlLibrary;
+
+// This is the event handler delegate for the ThresholdExceeded event.
+public delegate void ThresholdExceededEventHandler(ThresholdExceededEventArgs e);
+
+//
+//
+// This control demonstrates a simple logging capability.
+[ComplexBindingProperties("DataSource", "DataMember")]
+[DefaultBindingProperty("TitleText")]
+[DefaultEvent("ThresholdExceeded")]
+[DefaultProperty("Threshold")]
+[HelpKeyword(typeof(UserControl))]
+[ToolboxItem("System.Windows.Forms.Design.AutoSizeToolboxItem,System.Design")]
+public class AttributesDemoControl : UserControl
{
- // This is the event handler delegate for the ThresholdExceeded event.
- public delegate void ThresholdExceededEventHandler(ThresholdExceededEventArgs e);
-
- //
- //
- // This control demonstrates a simple logging capability.
- [ComplexBindingProperties("DataSource", "DataMember")]
- [DefaultBindingProperty("TitleText")]
- [DefaultEvent("ThresholdExceeded")]
- [DefaultProperty("Threshold")]
- [HelpKeywordAttribute(typeof(UserControl))]
- [ToolboxItem("System.Windows.Forms.Design.AutoSizeToolboxItem,System.Design")]
- public class AttributesDemoControl : UserControl
- {
- //
-
- // This backs the Threshold property.
- private object thresholdValue;
-
- // The default fore color value for DataGridView cells that
- // contain values that exceed the threshold.
- private static Color defaultAlertForeColorValue = Color.White;
+ //
- // The default back color value for DataGridView cells that
- // contain values that exceed the threshold.
- private static Color defaultAlertBackColorValue = Color.Red;
+ // The default fore color value for DataGridView cells that
+ // contain values that exceed the threshold.
+ static readonly Color s_defaultAlertForeColorValue = Color.White;
- // The ambient color value.
- private static Color ambientColorValue = Color.Empty;
+ // The default back color value for DataGridView cells that
+ // contain values that exceed the threshold.
+ static readonly Color s_defaultAlertBackColorValue = Color.Red;
- // The fore color value for DataGridView cells that
- // contain values that exceed the threshold.
- private Color alertForeColorValue = defaultAlertForeColorValue;
+ // The ambient color value.
+ static readonly Color s_ambientColorValue = Color.Empty;
- // The back color value for DataGridView cells that
- // contain values that exceed the threshold.
- private Color alertBackColorValue = defaultAlertBackColorValue;
+ // The fore color value for DataGridView cells that
+ // contain values that exceed the threshold.
+ Color _alertForeColorValue = s_defaultAlertForeColorValue;
- // Child controls that comprise this UserControl.
- private TableLayoutPanel tableLayoutPanel1;
- private DataGridView dataGridView1;
- private Label label1;
+ // The back color value for DataGridView cells that
+ // contain values that exceed the threshold.
+ Color _alertBackColorValue = s_defaultAlertBackColorValue;
- // Required for designer support.
- private System.ComponentModel.IContainer components = null;
+ // Child controls that comprise this UserControl.
+ TableLayoutPanel _tableLayoutPanel1;
+ DataGridView _dataGridView1;
+ Label _label1;
- // Default constructor.
- public AttributesDemoControl()
- {
- InitializeComponent();
- }
+ // Required for designer support.
+ readonly IContainer _components;
- //
- [Category("Appearance")]
- [Description("The title of the log data.")]
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
- [Localizable(true)]
- [HelpKeywordAttribute("AttributesDemoControlLibrary.AttributesDemoControl.TitleText")]
- public string TitleText
- {
- get
- {
- return this.label1.Text;
- }
+ // Default constructor.
+ public AttributesDemoControl() => InitializeComponent();
- set
- {
- this.label1.Text = value;
- }
- }
- //
-
- //
- // The inherited Text property is hidden at design time and
- // raises an exception at run time. This enforces a requirement
- // that client code uses the TitleText property instead.
- [Browsable(false)]
- [EditorBrowsable(EditorBrowsableState.Never)]
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- public override string Text
- {
- get
- {
- throw new NotSupportedException();
- }
- set
- {
- throw new NotSupportedException();
- }
- }
- //
-
- //
- [AmbientValue(typeof(Color), "Empty")]
- [Category("Appearance")]
- [DefaultValue(typeof(Color), "White")]
- [Description("The color used for painting alert text.")]
- public Color AlertForeColor
- {
- get
- {
- if (this.alertForeColorValue == Color.Empty &&
- this.Parent != null)
- {
- return Parent.ForeColor;
- }
-
- return this.alertForeColorValue;
- }
-
- set
- {
- this.alertForeColorValue = value;
- }
- }
+ //
+ [Category("Appearance")]
+ [Description("The title of the log data.")]
+ [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
+ [Localizable(true)]
+ [HelpKeyword("AttributesDemoControlLibrary.AttributesDemoControl.TitleText")]
+ public string TitleText
+ {
+ get => _label1.Text;
+ set => _label1.Text = value;
+ }
+ //
+
+ //
+ // The inherited Text property is hidden at design time and
+ // raises an exception at run time. This enforces a requirement
+ // that client code uses the TitleText property instead.
+ [Browsable(false)]
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
+ public override string Text
+ {
+ get => throw new NotSupportedException();
+ set => throw new NotSupportedException();
+ }
+ //
+
+ //
+ [AmbientValue(typeof(Color), "Empty")]
+ [Category("Appearance")]
+ [DefaultValue(typeof(Color), "White")]
+ [Description("The color used for painting alert text.")]
+ public Color AlertForeColor
+ {
+ get =>
+ _alertForeColorValue == Color.Empty &&
+ Parent != null
+ ? Parent.ForeColor
+ : _alertForeColorValue;
- // This method is used by designers to enable resetting the
- // property to its default value.
- public void ResetAlertForeColor()
- {
- this.AlertForeColor = AttributesDemoControl.defaultAlertForeColorValue;
- }
+ set => _alertForeColorValue = value;
+ }
- // This method indicates to designers whether the property
- // value is different from the ambient value, in which case
- // the designer should persist the value.
- private bool ShouldSerializeAlertForeColor()
- {
- return (this.alertForeColorValue != AttributesDemoControl.ambientColorValue);
- }
- //
-
- //
- [AmbientValue(typeof(Color), "Empty")]
- [Category("Appearance")]
- [DefaultValue(typeof(Color), "Red")]
- [Description("The background color for painting alert text.")]
- public Color AlertBackColor
- {
- get
- {
- if (this.alertBackColorValue == Color.Empty &&
- this.Parent != null)
- {
- return Parent.BackColor;
- }
+ // This method is used by designers to enable resetting the
+ // property to its default value.
+ public void ResetAlertForeColor() =>
+ AlertForeColor = s_defaultAlertForeColorValue;
+
+ // This method indicates to designers whether the property
+ // value is different from the ambient value, in which case
+ // the designer should persist the value.
+ bool ShouldSerializeAlertForeColor() =>
+ _alertForeColorValue != s_ambientColorValue;
+ //
+
+ //
+ [AmbientValue(typeof(Color), "Empty")]
+ [Category("Appearance")]
+ [DefaultValue(typeof(Color), "Red")]
+ [Description("The background color for painting alert text.")]
+ public Color AlertBackColor
+ {
+ get =>
+ _alertBackColorValue == Color.Empty &&
+ Parent != null
+ ? Parent.BackColor
+ : _alertBackColorValue;
- return this.alertBackColorValue;
- }
+ set => _alertBackColorValue = value;
+ }
- set
- {
- this.alertBackColorValue = value;
- }
- }
+ // This method is used by designers to enable resetting the
+ // property to its default value.
+ public void ResetAlertBackColor() =>
+ AlertBackColor = s_defaultAlertBackColorValue;
+
+ // This method indicates to designers whether the property
+ // value is different from the ambient value, in which case
+ // the designer should persist the value.
+ bool ShouldSerializeAlertBackColor() =>
+ _alertBackColorValue != s_ambientColorValue;
+ //
+
+ //
+ [Category("Data")]
+ [Description("Indicates the source of data for the control.")]
+ [RefreshProperties(RefreshProperties.Repaint)]
+ [AttributeProvider(typeof(IListSource))]
+ public object DataSource
+ {
+ get => _dataGridView1.DataSource;
+ set => _dataGridView1.DataSource = value;
+ }
+ //
- // This method is used by designers to enable resetting the
- // property to its default value.
- public void ResetAlertBackColor()
+ //
+ [Category("Data")]
+ [Description("Indicates a sub-list of the data source to show in the control.")]
+ public string DataMember
+ {
+ get => _dataGridView1.DataMember;
+ set => _dataGridView1.DataMember = value;
+ }
+ //
+
+ //
+ // This property would normally have its BrowsableAttribute
+ // set to false, but this code demonstrates using
+ // ReadOnlyAttribute, so BrowsableAttribute is true to show
+ // it in any attached PropertyGrid control.
+ [Browsable(true)]
+ [Category("Behavior")]
+ [Description("The timestamp of the latest entry.")]
+ [ReadOnly(true)]
+ public DateTime CurrentLogTime
+ {
+ get
{
- this.AlertBackColor = AttributesDemoControl.defaultAlertBackColorValue;
- }
+ int lastRowIndex =
+ _dataGridView1.Rows.GetLastRow(
+ DataGridViewElementStates.Visible);
- // This method indicates to designers whether the property
- // value is different from the ambient value, in which case
- // the designer should persist the value.
- private bool ShouldSerializeAlertBackColor()
- {
- return (this.alertBackColorValue != AttributesDemoControl.ambientColorValue);
- }
- //
-
- //
- [Category("Data")]
- [Description("Indicates the source of data for the control.")]
- [RefreshProperties(RefreshProperties.Repaint)]
- [AttributeProvider(typeof(IListSource))]
- public object DataSource
- {
- get
+ if (lastRowIndex > -1)
{
- return this.dataGridView1.DataSource;
+ DataGridViewRow lastRow = _dataGridView1.Rows[lastRowIndex];
+ DataGridViewCell lastCell = lastRow.Cells["EntryTime"];
+ return (DateTime)lastCell.Value;
}
-
- set
+ else
{
- this.dataGridView1.DataSource = value;
+ return DateTime.MinValue;
}
}
- //
- //
- [Category("Data")]
- [Description("Indicates a sub-list of the data source to show in the control.")]
- public string DataMember
- {
- get
- {
- return this.dataGridView1.DataMember;
- }
-
- set
- {
- this.dataGridView1.DataMember = value;
- }
- }
- //
-
- //
- // This property would normally have its BrowsableAttribute
- // set to false, but this code demonstrates using
- // ReadOnlyAttribute, so BrowsableAttribute is true to show
- // it in any attached PropertyGrid control.
- [Browsable(true)]
- [Category("Behavior")]
- [Description("The timestamp of the latest entry.")]
- [ReadOnly(true)]
- public DateTime CurrentLogTime
+ set { }
+ }
+ //
+
+ //
+ [Category("Behavior")]
+ [Description("The value above which the ThresholdExceeded event will be raised.")]
+ public object Threshold { get; set; }
+ //
+
+ //
+ // This property exists only to demonstrate the
+ // PasswordPropertyText attribute. When this control
+ // is attached to a PropertyGrid control, the returned
+ // string will be displayed with obscuring characters
+ // such as asterisks. This property has no other effect.
+ [Category("Security")]
+ [Description("Demonstrates PasswordPropertyTextAttribute.")]
+ [PasswordPropertyText(true)]
+ public string Password => "This is a demo password.";
+ //
+
+ //
+ // This property exists only to demonstrate the
+ // DisplayName attribute. When this control
+ // is attached to a PropertyGrid control, the
+ // property will appear as "RenamedProperty"
+ // instead of "MisnamedProperty".
+ [Description("Demonstrates DisplayNameAttribute.")]
+ [DisplayName("RenamedProperty")]
+ public bool MisnamedProperty => true;
+ //
+
+ // This is the declaration for the ThresholdExceeded event.
+ public event ThresholdExceededEventHandler ThresholdExceeded;
+
+ #region Implementation
+
+ //
+ // This is the event handler for the DataGridView control's
+ // CellFormatting event. Handling this event allows the
+ // AttributesDemoControl to examine the incoming log entries
+ // from the data source as they arrive.
+ //
+ // If the cell for which this event is raised holds the
+ // log entry's timestamp, the cell value is formatted with
+ // the full date/time pattern.
+ //
+ // Otherwise, the cell's value is assumed to hold the log
+ // entry value. If the value exceeds the threshold value,
+ // the cell is painted with the colors specified by the
+ // AlertForeColor and AlertBackColor properties, after which
+ // the ThresholdExceeded is raised. For this comparison to
+ // succeed, the log entry's type must implement the IComparable
+ // interface.
+ void dataGridView1_CellFormatting(
+ object sender,
+ DataGridViewCellFormattingEventArgs e)
+ {
+ try
{
- get
+ if (e.Value != null)
{
- int lastRowIndex =
- this.dataGridView1.Rows.GetLastRow(
- DataGridViewElementStates.Visible);
-
- if (lastRowIndex > -1)
+ if (e.Value is DateTime)
{
- DataGridViewRow lastRow = this.dataGridView1.Rows[lastRowIndex];
- DataGridViewCell lastCell = lastRow.Cells["EntryTime"];
- return ((DateTime)lastCell.Value);
+ // Display the log entry time with the
+ // full date/time pattern (long time).
+ e.CellStyle.Format = "F";
}
else
{
- return DateTime.MinValue;
- }
- }
-
- set
- {
- }
- }
- //
-
- //
- [Category("Behavior")]
- [Description("The value above which the ThresholdExceeded event will be raised.")]
- public object Threshold
- {
- get
- {
- return this.thresholdValue;
- }
-
- set
- {
- this.thresholdValue = value;
- }
- }
- //
-
- //
- // This property exists only to demonstrate the
- // PasswordPropertyText attribute. When this control
- // is attached to a PropertyGrid control, the returned
- // string will be displayed with obscuring characters
- // such as asterisks. This property has no other effect.
- [Category("Security")]
- [Description("Demonstrates PasswordPropertyTextAttribute.")]
- [PasswordPropertyText(true)]
- public string Password
- {
- get
- {
- return "This is a demo password.";
- }
- }
- //
-
- //
- // This property exists only to demonstrate the
- // DisplayName attribute. When this control
- // is attached to a PropertyGrid control, the
- // property will appear as "RenamedProperty"
- // instead of "MisnamedProperty".
- [Description("Demonstrates DisplayNameAttribute.")]
- [DisplayName("RenamedProperty")]
- public bool MisnamedProperty
- {
- get
- {
- return true;
- }
- }
- //
-
- // This is the declaration for the ThresholdExceeded event.
- public event ThresholdExceededEventHandler ThresholdExceeded;
-
- #region Implementation
+ // Scroll to the most recent entry.
+ DataGridViewRow row = _dataGridView1.Rows[e.RowIndex];
+ DataGridViewCell cell = row.Cells[e.ColumnIndex];
+ _dataGridView1.FirstDisplayedCell = cell;
- //
- // This is the event handler for the DataGridView control's
- // CellFormatting event. Handling this event allows the
- // AttributesDemoControl to examine the incoming log entries
- // from the data source as they arrive.
- //
- // If the cell for which this event is raised holds the
- // log entry's timestamp, the cell value is formatted with
- // the full date/time pattern.
- //
- // Otherwise, the cell's value is assumed to hold the log
- // entry value. If the value exceeds the threshold value,
- // the cell is painted with the colors specified by the
- // AlertForeColor and AlertBackColor properties, after which
- // the ThresholdExceeded is raised. For this comparison to
- // succeed, the log entry's type must implement the IComparable
- // interface.
- private void dataGridView1_CellFormatting(
- object sender,
- DataGridViewCellFormattingEventArgs e)
- {
- try
- {
- if (e.Value != null)
- {
- if (e.Value is DateTime)
+ if (Threshold != null)
{
- // Display the log entry time with the
- // full date/time pattern (long time).
- e.CellStyle.Format = "F";
- }
- else
- {
- // Scroll to the most recent entry.
- DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];
- DataGridViewCell cell = row.Cells[e.ColumnIndex];
- this.dataGridView1.FirstDisplayedCell = cell;
-
- if (this.thresholdValue != null)
+ // Get the type of the log entry.
+ object val = e.Value;
+ Type paramType = val.GetType();
+
+ // Compare the log entry value to the threshold value.
+ // Use reflection to call the CompareTo method on the
+ // template parameter's type.
+ int compareVal = (int)paramType.InvokeMember(
+ "CompareTo",
+ BindingFlags.Default | BindingFlags.InvokeMethod,
+ null,
+ e.Value,
+ [Threshold],
+ CultureInfo.InvariantCulture);
+
+ // If the log entry value exceeds the threshold value,
+ // set the cell's fore color and back color properties
+ // and raise the ThresholdExceeded event.
+ if (compareVal > 0)
{
- // Get the type of the log entry.
- object val = e.Value;
- Type paramType = val.GetType();
-
- // Compare the log entry value to the threshold value.
- // Use reflection to call the CompareTo method on the
- // template parameter's type.
- int compareVal = (int)paramType.InvokeMember(
- "CompareTo",
- BindingFlags.Default | BindingFlags.InvokeMethod,
- null,
- e.Value,
- new object[] { this.thresholdValue },
- System.Globalization.CultureInfo.InvariantCulture);
-
- // If the log entry value exceeds the threshold value,
- // set the cell's fore color and back color properties
- // and raise the ThresholdExceeded event.
- if (compareVal > 0)
- {
- e.CellStyle.BackColor = this.alertBackColorValue;
- e.CellStyle.ForeColor = this.alertForeColorValue;
-
- ThresholdExceededEventArgs teea =
- new ThresholdExceededEventArgs(
- this.thresholdValue,
- e.Value);
- this.ThresholdExceeded(teea);
- }
+ e.CellStyle.BackColor = _alertBackColorValue;
+ e.CellStyle.ForeColor = _alertForeColorValue;
+
+ ThresholdExceededEventArgs teea =
+ new(
+ Threshold,
+ e.Value);
+ ThresholdExceeded(teea);
}
}
}
}
- catch (Exception ex)
- {
- Trace.WriteLine(ex.Message);
- }
}
- //
-
- protected override void Dispose(bool disposing)
+ catch (Exception ex)
{
- if (disposing && (components != null))
- {
- components.Dispose();
- }
- base.Dispose(disposing);
+ Trace.WriteLine(ex.Message);
}
+ }
+ //
- private void InitializeComponent()
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing && (_components != null))
{
- System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
- this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
- this.dataGridView1 = new System.Windows.Forms.DataGridView();
- this.label1 = new System.Windows.Forms.Label();
- this.tableLayoutPanel1.SuspendLayout();
- ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
- this.SuspendLayout();
- //
- // tableLayoutPanel1
- //
- this.tableLayoutPanel1.AutoSize = true;
- this.tableLayoutPanel1.ColumnCount = 1;
- this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 100F));
- this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 100F));
- this.tableLayoutPanel1.Controls.Add(this.dataGridView1, 0, 1);
- this.tableLayoutPanel1.Controls.Add(this.label1, 0, 0);
- this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
- this.tableLayoutPanel1.Location = new System.Drawing.Point(10, 10);
- this.tableLayoutPanel1.Name = "tableLayoutPanel1";
- this.tableLayoutPanel1.Padding = new System.Windows.Forms.Padding(10);
- this.tableLayoutPanel1.RowCount = 2;
- this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F));
- this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 80F));
- this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F));
- this.tableLayoutPanel1.Size = new System.Drawing.Size(425, 424);
- this.tableLayoutPanel1.TabIndex = 0;
- //
- // dataGridView1
- //
- this.dataGridView1.AllowUserToAddRows = false;
- this.dataGridView1.AllowUserToDeleteRows = false;
- this.dataGridView1.AllowUserToOrderColumns = true;
- this.dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
- this.dataGridView1.AutoSizeRowsMode = System.Windows.Forms.DataGridViewAutoSizeRowsMode.AllCells;
- dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
- dataGridViewCellStyle1.BackColor = System.Drawing.SystemColors.Control;
- dataGridViewCellStyle1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
- dataGridViewCellStyle1.ForeColor = System.Drawing.SystemColors.WindowText;
- dataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.Highlight;
- dataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
- dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.False;
- this.dataGridView1.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle1;
- this.dataGridView1.ColumnHeadersHeight = 4;
- this.dataGridView1.Dock = System.Windows.Forms.DockStyle.Fill;
- this.dataGridView1.Location = new System.Drawing.Point(13, 57);
- this.dataGridView1.Name = "dataGridView1";
- this.dataGridView1.ReadOnly = true;
- this.dataGridView1.RowHeadersVisible = false;
- this.dataGridView1.Size = new System.Drawing.Size(399, 354);
- this.dataGridView1.TabIndex = 1;
- this.dataGridView1.CellFormatting += new System.Windows.Forms.DataGridViewCellFormattingEventHandler(this.dataGridView1_CellFormatting);
- //
- // label1
- //
- this.label1.AutoSize = true;
- this.label1.BackColor = System.Drawing.SystemColors.Control;
- this.label1.Dock = System.Windows.Forms.DockStyle.Fill;
- this.label1.Location = new System.Drawing.Point(13, 13);
- this.label1.Name = "label1";
- this.label1.Size = new System.Drawing.Size(399, 38);
- this.label1.TabIndex = 2;
- this.label1.Text = "label1";
- this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
- //
- // AttributesDemoControl
- //
- this.Controls.Add(this.tableLayoutPanel1);
- this.Name = "AttributesDemoControl";
- this.Padding = new System.Windows.Forms.Padding(10);
- this.Size = new System.Drawing.Size(445, 444);
- this.tableLayoutPanel1.ResumeLayout(false);
- this.tableLayoutPanel1.PerformLayout();
- ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
- this.ResumeLayout(false);
- this.PerformLayout();
+ _components.Dispose();
}
-
- #endregion
+ base.Dispose(disposing);
}
- //
- //
- // This is the EventArgs class for the ThresholdExceeded event.
- public class ThresholdExceededEventArgs : EventArgs
+ void InitializeComponent()
{
- private object thresholdValue = null;
- private object exceedingValue = null;
-
- public ThresholdExceededEventArgs(
- object thresholdValue,
- object exceedingValue)
- {
- this.thresholdValue = thresholdValue;
- this.exceedingValue = exceedingValue;
- }
+ DataGridViewCellStyle dataGridViewCellStyle1 = new DataGridViewCellStyle();
+ _tableLayoutPanel1 = new TableLayoutPanel();
+ _dataGridView1 = new DataGridView();
+ _label1 = new Label();
+ _tableLayoutPanel1.SuspendLayout();
+ ((ISupportInitialize)_dataGridView1).BeginInit();
+ SuspendLayout();
+ //
+ // tableLayoutPanel1
+ //
+ _tableLayoutPanel1.AutoSize = true;
+ _tableLayoutPanel1.ColumnCount = 1;
+ _tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 100F));
+ _tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 100F));
+ _tableLayoutPanel1.Controls.Add(_dataGridView1, 0, 1);
+ _tableLayoutPanel1.Controls.Add(_label1, 0, 0);
+ _tableLayoutPanel1.Dock = DockStyle.Fill;
+ _tableLayoutPanel1.Location = new Point(10, 10);
+ _tableLayoutPanel1.Name = "tableLayoutPanel1";
+ _tableLayoutPanel1.Padding = new Padding(10);
+ _tableLayoutPanel1.RowCount = 2;
+ _tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Percent, 10F));
+ _tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Percent, 80F));
+ _tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Percent, 10F));
+ _tableLayoutPanel1.Size = new Size(425, 424);
+ _tableLayoutPanel1.TabIndex = 0;
+ //
+ // dataGridView1
+ //
+ _dataGridView1.AllowUserToAddRows = false;
+ _dataGridView1.AllowUserToDeleteRows = false;
+ _dataGridView1.AllowUserToOrderColumns = true;
+ _dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
+ _dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
+ dataGridViewCellStyle1.Alignment = DataGridViewContentAlignment.MiddleLeft;
+ dataGridViewCellStyle1.BackColor = SystemColors.Control;
+ dataGridViewCellStyle1.Font = new Font("Microsoft Sans Serif", 8.25F, FontStyle.Regular, GraphicsUnit.Point, 0);
+ dataGridViewCellStyle1.ForeColor = SystemColors.WindowText;
+ dataGridViewCellStyle1.SelectionBackColor = SystemColors.Highlight;
+ dataGridViewCellStyle1.SelectionForeColor = SystemColors.HighlightText;
+ dataGridViewCellStyle1.WrapMode = DataGridViewTriState.False;
+ _dataGridView1.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle1;
+ _dataGridView1.ColumnHeadersHeight = 4;
+ _dataGridView1.Dock = DockStyle.Fill;
+ _dataGridView1.Location = new Point(13, 57);
+ _dataGridView1.Name = "dataGridView1";
+ _dataGridView1.ReadOnly = true;
+ _dataGridView1.RowHeadersVisible = false;
+ _dataGridView1.Size = new Size(399, 354);
+ _dataGridView1.TabIndex = 1;
+ _dataGridView1.CellFormatting += dataGridView1_CellFormatting;
+ //
+ // label1
+ //
+ _label1.AutoSize = true;
+ _label1.BackColor = SystemColors.Control;
+ _label1.Dock = DockStyle.Fill;
+ _label1.Location = new Point(13, 13);
+ _label1.Name = "label1";
+ _label1.Size = new Size(399, 38);
+ _label1.TabIndex = 2;
+ _label1.Text = "label1";
+ _label1.TextAlign = ContentAlignment.MiddleCenter;
+ //
+ // AttributesDemoControl
+ //
+ Controls.Add(_tableLayoutPanel1);
+ Name = "AttributesDemoControl";
+ Padding = new Padding(10);
+ Size = new Size(445, 444);
+ _tableLayoutPanel1.ResumeLayout(false);
+ _tableLayoutPanel1.PerformLayout();
+ ((ISupportInitialize)_dataGridView1).EndInit();
+ ResumeLayout(false);
+ PerformLayout();
+ }
- public object ThresholdValue
- {
- get
- {
- return this.thresholdValue;
- }
- }
+ #endregion
+}
+//
- public object ExceedingValue
- {
- get
- {
- return this.exceedingValue;
- }
- }
+//
+// This is the EventArgs class for the ThresholdExceeded event.
+public class ThresholdExceededEventArgs : EventArgs
+{
+ public ThresholdExceededEventArgs(
+ object thresholdValue,
+ object exceedingValue)
+ {
+ ThresholdValue = thresholdValue;
+ ExceedingValue = exceedingValue;
}
- //
-
- //
- // This class encapsulates a log entry. It is a parameterized
- // type (also known as a template class). The parameter type T
- // defines the type of data being logged. For threshold detection
- // to work, this type must implement the IComparable interface.
- [TypeConverter("LogEntryTypeConverter")]
- public class LogEntry where T : IComparable
+
+ public object ThresholdValue { get; }
+
+ public object ExceedingValue { get; }
+}
+//
+
+//
+// This class encapsulates a log entry. It is a parameterized
+// type (also known as a template class). The parameter type T
+// defines the type of data being logged. For threshold detection
+// to work, this type must implement the IComparable interface.
+[TypeConverter("LogEntryTypeConverter")]
+public class LogEntry where T : IComparable
+{
+ public LogEntry(
+ T value,
+ DateTime time)
{
- private T entryValue;
- private DateTime entryTimeValue;
+ Entry = value;
+ EntryTime = time;
+ }
- public LogEntry(
- T value,
- DateTime time)
- {
- this.entryValue = value;
- this.entryTimeValue = time;
- }
+ public T Entry { get; }
- public T Entry
- {
- get
- {
- return this.entryValue;
- }
- }
+ public DateTime EntryTime { get; }
- public DateTime EntryTime
+ //
+ // This is the TypeConverter for the LogEntry class.
+ public class LogEntryTypeConverter : TypeConverter
+ {
+ //
+ public override bool CanConvertFrom(
+ ITypeDescriptorContext context,
+ Type sourceType) =>
+ sourceType == typeof(string) ||
+ base.CanConvertFrom(context, sourceType);
+ //
+
+ //
+ public override object ConvertFrom(
+ ITypeDescriptorContext context,
+ CultureInfo culture,
+ object value)
{
- get
+ if (value is string valstr)
{
- return this.entryTimeValue;
+ string[] v = valstr.Split(['|']);
+
+ Type paramType = typeof(T);
+ T entryValue = (T)paramType.InvokeMember(
+ "Parse",
+ BindingFlags.Static | BindingFlags.Public | BindingFlags.InvokeMethod,
+ null,
+ null,
+ [v[0]],
+ culture);
+
+ return new LogEntry(
+ entryValue,
+ DateTime.Parse(v[2]));
}
- }
- //
- // This is the TypeConverter for the LogEntry class.
- public class LogEntryTypeConverter : TypeConverter
+ return base.ConvertFrom(context, culture, value);
+ }
+ //
+
+ //
+ public override object ConvertTo(
+ ITypeDescriptorContext context,
+ CultureInfo culture,
+ object value,
+ Type destinationType)
{
- //
- public override bool CanConvertFrom(
- ITypeDescriptorContext context,
- Type sourceType)
+ if (destinationType == typeof(string))
{
- if (sourceType == typeof(string))
- {
- return true;
- }
+ LogEntry le = value as LogEntry;
- return base.CanConvertFrom(context, sourceType);
- }
- //
+ string stringRepresentation =
+ string.Format("{0} | {1}",
+ le.Entry,
+ le.EntryTime);
- //
- public override object ConvertFrom(
- ITypeDescriptorContext context,
- System.Globalization.CultureInfo culture,
- object value)
- {
- if (value is string)
- {
- string[] v = ((string)value).Split(new char[] { '|' });
-
- Type paramType = typeof(T);
- T entryValue = (T)paramType.InvokeMember(
- "Parse",
- BindingFlags.Static | BindingFlags.Public | BindingFlags.InvokeMethod,
- null,
- null,
- new string[] { v[0] },
- culture);
-
- return new LogEntry(
- entryValue,
- DateTime.Parse(v[2]));
- }
-
- return base.ConvertFrom(context, culture, value);
+ return stringRepresentation;
}
- //
-
- //
- public override object ConvertTo(
- ITypeDescriptorContext context,
- System.Globalization.CultureInfo culture,
- object value,
- Type destinationType)
- {
- if (destinationType == typeof(string))
- {
- LogEntry le = value as LogEntry;
- string stringRepresentation =
- String.Format("{0} | {1}",
- le.Entry,
- le.EntryTime);
-
- return stringRepresentation;
- }
-
- return base.ConvertTo(context, culture, value, destinationType);
- }
- //
+ return base.ConvertTo(context, culture, value, destinationType);
}
- //
+ //
}
- //
+ //
}
+//
//
diff --git a/snippets/csharp/System.ComponentModel/AmbientValueAttribute/Overview/form1.cs b/snippets/csharp/System.ComponentModel/AmbientValueAttribute/Overview/form1.cs
index 2773d944161..54e33d85ad3 100644
--- a/snippets/csharp/System.ComponentModel/AmbientValueAttribute/Overview/form1.cs
+++ b/snippets/csharp/System.ComponentModel/AmbientValueAttribute/Overview/form1.cs
@@ -1,9 +1,7 @@
//
//
using System;
-using System.Collections.Generic;
using System.ComponentModel;
-using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
@@ -12,273 +10,268 @@
// This sample demonstrates using the AttributesDemoControl to log
// data from a data source.
-namespace AttributesDemoControlTest
+namespace AttributesDemoControlTest;
+
+public class Form1 : Form
{
- public class Form1 : Form
- {
- private BindingSource bindingSource1;
- private System.Diagnostics.PerformanceCounter performanceCounter1;
- private Button startButton;
- private Button stopButton;
- private System.Timers.Timer timer1;
- private ToolStripStatusLabel statusStripPanel1;
- private NumericUpDown numericUpDown1;
- private GroupBox groupBox1;
- private GroupBox groupBox2;
- private TableLayoutPanel tableLayoutPanel1;
- private AttributesDemoControl attributesDemoControl1;
- private System.ComponentModel.IContainer components = null;
+ BindingSource bindingSource1;
+ PerformanceCounter performanceCounter1;
+ Button startButton;
+ Button stopButton;
+ System.Timers.Timer timer1;
+ ToolStripStatusLabel statusStripPanel1;
+ NumericUpDown numericUpDown1;
+ GroupBox groupBox1;
+ GroupBox groupBox2;
+ TableLayoutPanel tableLayoutPanel1;
+ AttributesDemoControl attributesDemoControl1;
+ Container _components;
- // This form uses an AttributesDemoControl to display a stream
- // of LogEntry objects. The data stream is generated by polling
- // a performance counter and communicating the counter values
- // to the control with data binding.
- public Form1()
- {
- InitializeComponent();
+ // This form uses an AttributesDemoControl to display a stream
+ // of LogEntry objects. The data stream is generated by polling
+ // a performance counter and communicating the counter values
+ // to the control with data binding.
+ public Form1()
+ {
+ InitializeComponent();
- // Set the initial value of the threshold up/down control
- // to the control's threshold value.
- this.numericUpDown1.Value =
- (decimal)(float)this.attributesDemoControl1.Threshold;
+ // Set the initial value of the threshold up/down control
+ // to the control's threshold value.
+ numericUpDown1.Value =
+ (decimal)(float)attributesDemoControl1.Threshold;
- // Assign the performance counter's name to the control's
- // title text.
- this.attributesDemoControl1.TitleText =
- this.performanceCounter1.CounterName;
- }
+ // Assign the performance counter's name to the control's
+ // title text.
+ attributesDemoControl1.TitleText =
+ performanceCounter1.CounterName;
+ }
- // This method handles the ThresholdExceeded event. It posts
- // the value that exceeded the threshold to the status strip.
- private void attributesDemoControl1_ThresholdExceeded(
- ThresholdExceededEventArgs e)
- {
- string msg = String.Format(
- "{0}: Value {1} exceeded threshold {2}",
- this.attributesDemoControl1.CurrentLogTime,
- e.ExceedingValue,
- e.ThresholdValue);
+ // This method handles the ThresholdExceeded event. It posts
+ // the value that exceeded the threshold to the status strip.
+ void attributesDemoControl1_ThresholdExceeded(
+ ThresholdExceededEventArgs e)
+ {
+ string msg = string.Format(
+ "{0}: Value {1} exceeded threshold {2}",
+ attributesDemoControl1.CurrentLogTime,
+ e.ExceedingValue,
+ e.ThresholdValue);
- this.ReportStatus( msg );
- }
+ ReportStatus(msg);
+ }
- //
- // This method handles the timer's Elapsed event. It queries
- // the performance counter for the next value, packs the
- // value in a LogEntry object, and adds the new LogEntry to
- // the list managed by the BindingSource.
- private void timer1_Elapsed(
- object sender,
- System.Timers.ElapsedEventArgs e)
- {
- // Get the latest value from the performance counter.
- float val = this.performanceCounter1.NextValue();
+ //
+ // This method handles the timer's Elapsed event. It queries
+ // the performance counter for the next value, packs the
+ // value in a LogEntry object, and adds the new LogEntry to
+ // the list managed by the BindingSource.
+ void timer1_Elapsed(
+ object sender,
+ System.Timers.ElapsedEventArgs e)
+ {
+ // Get the latest value from the performance counter.
+ float val = performanceCounter1.NextValue();
- // The performance counter returns values of type float,
- // but any type that implements the IComparable interface
- // will work.
- LogEntry entry = new LogEntry(val, DateTime.Now);
+ // The performance counter returns values of type float,
+ // but any type that implements the IComparable interface
+ // will work.
+ LogEntry entry = new(val, DateTime.Now);
- // Add the new LogEntry to the BindingSource list.
- this.bindingSource1.Add(entry);
- }
- //
+ // Add the new LogEntry to the BindingSource list.
+ _ = bindingSource1.Add(entry);
+ }
+ //
- private void numericUpDown1_ValueChanged(object sender, EventArgs e)
- {
- this.attributesDemoControl1.Threshold =
- (float)this.numericUpDown1.Value;
+ void numericUpDown1_ValueChanged(object sender, EventArgs e)
+ {
+ attributesDemoControl1.Threshold =
+ (float)numericUpDown1.Value;
- string msg = String.Format(
- "Threshold changed to {0}",
- this.attributesDemoControl1.Threshold);
+ string msg = string.Format(
+ "Threshold changed to {0}",
+ attributesDemoControl1.Threshold);
- this.ReportStatus(msg);
- }
+ ReportStatus(msg);
+ }
- private void startButton_Click(object sender, EventArgs e)
- {
- this.ReportStatus(DateTime.Now + ": Starting");
+ void startButton_Click(object sender, EventArgs e)
+ {
+ ReportStatus(DateTime.Now + ": Starting");
- this.timer1.Start();
- }
+ timer1.Start();
+ }
- private void stopButton_Click(object sender, EventArgs e)
- {
- this.ReportStatus(DateTime.Now + ": Stopping");
+ void stopButton_Click(object sender, EventArgs e)
+ {
+ ReportStatus(DateTime.Now + ": Stopping");
- this.timer1.Stop();
- }
+ timer1.Stop();
+ }
- private void ReportStatus(string msg)
+ void ReportStatus(string msg)
+ {
+ if (msg != null)
{
- if (msg != null)
- {
- this.statusStripPanel1.Text = msg;
- }
+ statusStripPanel1.Text = msg;
}
+ }
- [STAThread]
- static void Main()
- {
- Application.EnableVisualStyles();
- Application.Run(new Form1());
- }
+ [STAThread]
+ static void Main()
+ {
+ Application.EnableVisualStyles();
+ Application.Run(new Form1());
+ }
- protected override void Dispose(bool disposing)
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing && (_components != null))
{
- if (disposing && (components != null))
- {
- components.Dispose();
- }
- base.Dispose(disposing);
+ _components.Dispose();
}
-
- private void InitializeComponent()
- {
- this.components = new System.ComponentModel.Container();
- this.bindingSource1 = new System.Windows.Forms.BindingSource(this.components);
- this.performanceCounter1 = new System.Diagnostics.PerformanceCounter();
- this.startButton = new System.Windows.Forms.Button();
- this.stopButton = new System.Windows.Forms.Button();
- this.timer1 = new System.Timers.Timer();
- this.statusStripPanel1 = new System.Windows.Forms.ToolStripStatusLabel();
- this.numericUpDown1 = new System.Windows.Forms.NumericUpDown();
- this.groupBox1 = new System.Windows.Forms.GroupBox();
- this.groupBox2 = new System.Windows.Forms.GroupBox();
- this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
- this.attributesDemoControl1 = new AttributesDemoControlLibrary.AttributesDemoControl();
- ((System.ComponentModel.ISupportInitialize)(this.bindingSource1)).BeginInit();
- ((System.ComponentModel.ISupportInitialize)(this.performanceCounter1)).BeginInit();
- ((System.ComponentModel.ISupportInitialize)(this.timer1)).BeginInit();
+ base.Dispose(disposing);
+ }
+
+ void InitializeComponent()
+ {
+ _components = new Container();
+ bindingSource1 = new BindingSource(_components);
+ performanceCounter1 = new PerformanceCounter();
+ startButton = new Button();
+ stopButton = new Button();
+ timer1 = new System.Timers.Timer();
+ statusStripPanel1 = new ToolStripStatusLabel();
+ numericUpDown1 = new NumericUpDown();
+ groupBox1 = new GroupBox();
+ groupBox2 = new GroupBox();
+ tableLayoutPanel1 = new TableLayoutPanel();
+ attributesDemoControl1 = new AttributesDemoControl();
+ ((ISupportInitialize)bindingSource1).BeginInit();
+ performanceCounter1.BeginInit();
+ timer1.BeginInit();
- ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).BeginInit();
- this.groupBox1.SuspendLayout();
- this.groupBox2.SuspendLayout();
- this.tableLayoutPanel1.SuspendLayout();
- this.SuspendLayout();
- //
- // performanceCounter1
- //
- this.performanceCounter1.CategoryName = ".NET CLR Memory";
- this.performanceCounter1.CounterName = "Gen 0 heap size";
- this.performanceCounter1.InstanceName = "_Global_";
- //
- // startButton
- //
- this.startButton.Location = new System.Drawing.Point(31, 25);
- this.startButton.Name = "startButton";
- this.startButton.TabIndex = 1;
- this.startButton.Text = "Start";
- this.startButton.Click += new System.EventHandler(this.startButton_Click);
- //
- // stopButton
- //
- this.stopButton.Location = new System.Drawing.Point(112, 25);
- this.stopButton.Name = "stopButton";
- this.stopButton.TabIndex = 2;
- this.stopButton.Text = "Stop";
- this.stopButton.Click += new System.EventHandler(this.stopButton_Click);
- //
- // timer1
- //
- this.timer1.Interval = 1000;
- this.timer1.SynchronizingObject = this;
- this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Elapsed);
- //
- // statusStripPanel1
- //
- this.statusStripPanel1.BorderStyle = System.Windows.Forms.Border3DStyle.SunkenOuter;
- this.statusStripPanel1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
- this.statusStripPanel1.Name = "statusStripPanel1";
- this.statusStripPanel1.Text = "Ready";
- //
- // numericUpDown1
- //
- this.numericUpDown1.Location = new System.Drawing.Point(37, 29);
- this.numericUpDown1.Maximum = new decimal(new int[] {
- 1410065408,
- 2,
- 0,
- 0});
- this.numericUpDown1.Name = "numericUpDown1";
- this.numericUpDown1.TabIndex = 7;
- this.numericUpDown1.ValueChanged += new System.EventHandler(this.numericUpDown1_ValueChanged);
- //
- // groupBox1
- //
- this.groupBox1.Anchor = System.Windows.Forms.AnchorStyles.None;
- this.groupBox1.Controls.Add(this.numericUpDown1);
- this.groupBox1.Location = new System.Drawing.Point(280, 326);
- this.groupBox1.Name = "groupBox1";
- this.groupBox1.Size = new System.Drawing.Size(200, 70);
- this.groupBox1.TabIndex = 13;
- this.groupBox1.TabStop = false;
- this.groupBox1.Text = "Threshold Value";
- //
- // groupBox2
- //
- this.groupBox2.Anchor = System.Windows.Forms.AnchorStyles.None;
- this.groupBox2.Controls.Add(this.startButton);
- this.groupBox2.Controls.Add(this.stopButton);
- this.groupBox2.Location = new System.Drawing.Point(26, 327);
- this.groupBox2.Name = "groupBox2";
- this.groupBox2.Size = new System.Drawing.Size(214, 68);
- this.groupBox2.TabIndex = 14;
- this.groupBox2.TabStop = false;
- this.groupBox2.Text = "Logging";
- //
- // tableLayoutPanel1
- //
- this.tableLayoutPanel1.ColumnCount = 2;
- this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
- this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
- this.tableLayoutPanel1.Controls.Add(this.groupBox2, 0, 1);
- this.tableLayoutPanel1.Controls.Add(this.groupBox1, 1, 1);
- this.tableLayoutPanel1.Controls.Add(this.attributesDemoControl1, 0, 0);
- this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
- this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 0);
- this.tableLayoutPanel1.Name = "tableLayoutPanel1";
- this.tableLayoutPanel1.Padding = new System.Windows.Forms.Padding(10);
- this.tableLayoutPanel1.RowCount = 2;
- this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 80F));
- this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 20F));
- this.tableLayoutPanel1.Size = new System.Drawing.Size(514, 411);
- this.tableLayoutPanel1.TabIndex = 15;
- //
- // attributesDemoControl1
- //
- this.tableLayoutPanel1.SetColumnSpan(this.attributesDemoControl1, 2);
- this.attributesDemoControl1.DataMember = "";
- this.attributesDemoControl1.DataSource = this.bindingSource1;
- this.attributesDemoControl1.Dock = System.Windows.Forms.DockStyle.Fill;
- this.attributesDemoControl1.Location = new System.Drawing.Point(13, 13);
- this.attributesDemoControl1.Name = "attributesDemoControl1";
- this.attributesDemoControl1.Padding = new System.Windows.Forms.Padding(10);
- this.attributesDemoControl1.Size = new System.Drawing.Size(488, 306);
- this.attributesDemoControl1.TabIndex = 0;
- this.attributesDemoControl1.Threshold = 200000F;
- this.attributesDemoControl1.TitleText = "TITLE";
- this.attributesDemoControl1.ThresholdExceeded += new AttributesDemoControlLibrary.ThresholdExceededEventHandler(this.attributesDemoControl1_ThresholdExceeded);
- //
- // Form1
- //
- this.BackColor = System.Drawing.SystemColors.Control;
- this.ClientSize = new System.Drawing.Size(514, 430);
- this.Controls.Add(this.tableLayoutPanel1);
- this.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
- this.Name = "Form1";
- this.Text = "Form1";
- ((System.ComponentModel.ISupportInitialize)(this.bindingSource1)).EndInit();
- ((System.ComponentModel.ISupportInitialize)(this.performanceCounter1)).EndInit();
- ((System.ComponentModel.ISupportInitialize)(this.timer1)).EndInit();
- ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).EndInit();
- this.groupBox1.ResumeLayout(false);
- this.groupBox2.ResumeLayout(false);
- this.tableLayoutPanel1.ResumeLayout(false);
- this.ResumeLayout(false);
- this.PerformLayout();
- }
- }
+ numericUpDown1.BeginInit();
+ groupBox1.SuspendLayout();
+ groupBox2.SuspendLayout();
+ tableLayoutPanel1.SuspendLayout();
+ SuspendLayout();
+ //
+ // performanceCounter1
+ //
+ performanceCounter1.CategoryName = ".NET CLR Memory";
+ performanceCounter1.CounterName = "Gen 0 heap size";
+ performanceCounter1.InstanceName = "_Global_";
+ //
+ // startButton
+ //
+ startButton.Location = new Point(31, 25);
+ startButton.Name = "startButton";
+ startButton.TabIndex = 1;
+ startButton.Text = "Start";
+ startButton.Click += startButton_Click;
+ //
+ // stopButton
+ //
+ stopButton.Location = new Point(112, 25);
+ stopButton.Name = "stopButton";
+ stopButton.TabIndex = 2;
+ stopButton.Text = "Stop";
+ stopButton.Click += stopButton_Click;
+ //
+ // timer1
+ //
+ timer1.Interval = 1000;
+ timer1.SynchronizingObject = this;
+ timer1.Elapsed += timer1_Elapsed;
+ //
+ // statusStripPanel1
+ //
+ statusStripPanel1.BorderStyle = Border3DStyle.SunkenOuter;
+ statusStripPanel1.DisplayStyle = ToolStripItemDisplayStyle.Text;
+ statusStripPanel1.Name = "statusStripPanel1";
+ statusStripPanel1.Text = "Ready";
+ //
+ // numericUpDown1
+ //
+ numericUpDown1.Location = new Point(37, 29);
+ numericUpDown1.Maximum = new decimal(new int[] { 1410065408, 2, 0, 0 });
+ numericUpDown1.Name = "numericUpDown1";
+ numericUpDown1.TabIndex = 7;
+ numericUpDown1.ValueChanged += numericUpDown1_ValueChanged;
+ //
+ // groupBox1
+ //
+ groupBox1.Anchor = AnchorStyles.None;
+ groupBox1.Controls.Add(numericUpDown1);
+ groupBox1.Location = new Point(280, 326);
+ groupBox1.Name = "groupBox1";
+ groupBox1.Size = new Size(200, 70);
+ groupBox1.TabIndex = 13;
+ groupBox1.TabStop = false;
+ groupBox1.Text = "Threshold Value";
+ //
+ // groupBox2
+ //
+ groupBox2.Anchor = AnchorStyles.None;
+ groupBox2.Controls.Add(startButton);
+ groupBox2.Controls.Add(stopButton);
+ groupBox2.Location = new Point(26, 327);
+ groupBox2.Name = "groupBox2";
+ groupBox2.Size = new Size(214, 68);
+ groupBox2.TabIndex = 14;
+ groupBox2.TabStop = false;
+ groupBox2.Text = "Logging";
+ //
+ // tableLayoutPanel1
+ //
+ tableLayoutPanel1.ColumnCount = 2;
+ tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
+ tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
+ tableLayoutPanel1.Controls.Add(groupBox2, 0, 1);
+ tableLayoutPanel1.Controls.Add(groupBox1, 1, 1);
+ tableLayoutPanel1.Controls.Add(attributesDemoControl1, 0, 0);
+ tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
+ tableLayoutPanel1.Location = new System.Drawing.Point(0, 0);
+ tableLayoutPanel1.Name = "tableLayoutPanel1";
+ tableLayoutPanel1.Padding = new System.Windows.Forms.Padding(10);
+ tableLayoutPanel1.RowCount = 2;
+ tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 80F));
+ tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 20F));
+ tableLayoutPanel1.Size = new System.Drawing.Size(514, 411);
+ tableLayoutPanel1.TabIndex = 15;
+ //
+ // attributesDemoControl1
+ //
+ tableLayoutPanel1.SetColumnSpan(attributesDemoControl1, 2);
+ attributesDemoControl1.DataMember = "";
+ attributesDemoControl1.DataSource = bindingSource1;
+ attributesDemoControl1.Dock = DockStyle.Fill;
+ attributesDemoControl1.Location = new Point(13, 13);
+ attributesDemoControl1.Name = "attributesDemoControl1";
+ attributesDemoControl1.Padding = new Padding(10);
+ attributesDemoControl1.Size = new Size(488, 306);
+ attributesDemoControl1.TabIndex = 0;
+ attributesDemoControl1.Threshold = 200000F;
+ attributesDemoControl1.TitleText = "TITLE";
+ attributesDemoControl1.ThresholdExceeded += new ThresholdExceededEventHandler(attributesDemoControl1_ThresholdExceeded);
+ //
+ // Form1
+ //
+ BackColor = SystemColors.Control;
+ ClientSize = new Size(514, 430);
+ Controls.Add(tableLayoutPanel1);
+ Font = new Font("Microsoft Sans Serif", 8.25F, FontStyle.Regular, GraphicsUnit.Point, 0);
+ Name = "Form1";
+ Text = "Form1";
+ ((ISupportInitialize)bindingSource1).EndInit();
+ performanceCounter1.EndInit();
+ timer1.EndInit();
+ numericUpDown1.EndInit();
+ groupBox1.ResumeLayout(false);
+ groupBox2.ResumeLayout(false);
+ tableLayoutPanel1.ResumeLayout(false);
+ ResumeLayout(false);
+ PerformLayout();
+ }
}
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System.ComponentModel/AsyncCompletedEventArgs/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/AsyncCompletedEventArgs/Overview/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/AsyncCompletedEventArgs/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/AsyncCompletedEventArgs/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/AsyncCompletedEventArgs/Overview/primenumbercalculatormain.cs b/snippets/csharp/System.ComponentModel/AsyncCompletedEventArgs/Overview/primenumbercalculatormain.cs
index 11fb63cda94..8e7c9b03508 100644
--- a/snippets/csharp/System.ComponentModel/AsyncCompletedEventArgs/Overview/primenumbercalculatormain.cs
+++ b/snippets/csharp/System.ComponentModel/AsyncCompletedEventArgs/Overview/primenumbercalculatormain.cs
@@ -4,916 +4,891 @@
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
-using System.Data;
using System.Drawing;
using System.Globalization;
using System.Threading;
using System.Windows.Forms;
//
-namespace AsyncOperationManagerExample
+namespace AsyncOperationManagerExample;
+
+// This form tests the PrimeNumberCalculator component.
+public class PrimeNumberCalculatorMain : Form
{
- // This form tests the PrimeNumberCalculator component.
- public class PrimeNumberCalculatorMain : System.Windows.Forms.Form
- {
- /////////////////////////////////////////////////////////////
- // Private fields
- //
- #region Private fields
-
- private PrimeNumberCalculator primeNumberCalculator1;
- private System.Windows.Forms.GroupBox taskGroupBox;
- private System.Windows.Forms.ListView listView1;
- private System.Windows.Forms.ColumnHeader taskIdColHeader;
- private System.Windows.Forms.ColumnHeader progressColHeader;
- private System.Windows.Forms.ColumnHeader currentColHeader;
- private System.Windows.Forms.Panel buttonPanel;
- private System.Windows.Forms.Panel panel2;
- private System.Windows.Forms.Button startAsyncButton;
- private System.Windows.Forms.Button cancelButton;
- private System.Windows.Forms.ColumnHeader testNumberColHeader;
- private System.Windows.Forms.ColumnHeader resultColHeader;
- private System.Windows.Forms.ColumnHeader firstDivisorColHeader;
- private System.ComponentModel.IContainer components;
- private int progressCounter;
- private int progressInterval = 100;
-
- #endregion // Private fields
-
- /////////////////////////////////////////////////////////////
- // Construction and destruction
+ /////////////////////////////////////////////////////////////
+ // Private fields
+ //
+ #region Private fields
+
+ PrimeNumberCalculator primeNumberCalculator1;
+ GroupBox taskGroupBox;
+ ListView listView1;
+ ColumnHeader taskIdColHeader;
+ ColumnHeader progressColHeader;
+ ColumnHeader currentColHeader;
+ Panel buttonPanel;
+ Panel panel2;
+ Button startAsyncButton;
+ Button cancelButton;
+ ColumnHeader testNumberColHeader;
+ ColumnHeader resultColHeader;
+ ColumnHeader firstDivisorColHeader;
+ IContainer _components;
+ int progressCounter;
+ readonly int progressInterval = 100;
+
+ #endregion // Private fields
+
+ /////////////////////////////////////////////////////////////
+ // Construction and destruction
+ //
+ #region Private fields
+ public PrimeNumberCalculatorMain()
+ {
//
- #region Private fields
- public PrimeNumberCalculatorMain ()
- {
- //
- // Required for Windows Form Designer support
- //
- InitializeComponent();
-
- // Hook up event handlers.
- this.primeNumberCalculator1.CalculatePrimeCompleted +=
- new CalculatePrimeCompletedEventHandler(
- primeNumberCalculator1_CalculatePrimeCompleted);
-
- this.primeNumberCalculator1.ProgressChanged +=
- new ProgressChangedEventHandler(
- primeNumberCalculator1_ProgressChanged);
-
- this.listView1.SelectedIndexChanged +=
- new EventHandler(listView1_SelectedIndexChanged);
- }
-
- protected override void Dispose( bool disposing )
- {
- if( disposing )
- {
- if (components != null)
- {
- components.Dispose();
- }
- }
- base.Dispose( disposing );
- }
-
- #endregion // Construction and destruction
-
- /////////////////////////////////////////////////////////////
+ // Required for Windows Form Designer support
//
- #region Implementation
-
- // This event handler selects a number randomly to test
- // for primality. It then starts the asynchronous
- // calculation by calling the PrimeNumberCalculator
- // component's CalculatePrimeAsync method.
- private void startAsyncButton_Click (
- System.Object sender, System.EventArgs e)
- {
- // Randomly choose test numbers
- // up to 200,000 for primality.
- Random rand = new Random();
- int testNumber = rand.Next(200000);
-
- // Task IDs are Guids.
- Guid taskId = Guid.NewGuid();
- this.AddListViewItem(taskId, testNumber);
-
- // Start the asynchronous task.
- this.primeNumberCalculator1.CalculatePrimeAsync(
- testNumber,
- taskId);
- }
+ InitializeComponent();
+
+ // Hook up event handlers.
+ primeNumberCalculator1.CalculatePrimeCompleted +=
- private void listView1_SelectedIndexChanged(
- object sender,
- EventArgs e)
+ primeNumberCalculator1_CalculatePrimeCompleted;
+
+ primeNumberCalculator1.ProgressChanged +=
+ new ProgressChangedEventHandler(
+ primeNumberCalculator1_ProgressChanged);
+
+ listView1.SelectedIndexChanged +=
+ listView1_SelectedIndexChanged;
+ }
+
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing)
{
- this.cancelButton.Enabled = CanCancel();
+ _components?.Dispose();
}
+ base.Dispose(disposing);
+ }
+
+ #endregion // Construction and destruction
+
+ /////////////////////////////////////////////////////////////
+ //
+ #region Implementation
+
+ // This event handler selects a number randomly to test
+ // for primality. It then starts the asynchronous
+ // calculation by calling the PrimeNumberCalculator
+ // component's CalculatePrimeAsync method.
+ void startAsyncButton_Click(
+ object sender, EventArgs e)
+ {
+ // Randomly choose test numbers
+ // up to 200,000 for primality.
+ Random rand = new();
+ int testNumber = rand.Next(200000);
+
+ // Task IDs are Guids.
+ Guid taskId = Guid.NewGuid();
+ _ = AddListViewItem(taskId, testNumber);
+
+ // Start the asynchronous task.
+ primeNumberCalculator1.CalculatePrimeAsync(
+ testNumber,
+ taskId);
+ }
- // This event handler cancels all pending tasks that are
- // selected in the ListView control.
- private void cancelButton_Click(
- System.Object sender,
- System.EventArgs e)
- {
- Guid taskId = Guid.Empty;
+ void listView1_SelectedIndexChanged(
+ object sender,
+ EventArgs e) =>
+ cancelButton.Enabled = CanCancel();
- // Cancel all selected tasks.
- foreach(ListViewItem lvi in this.listView1.SelectedItems)
+ // This event handler cancels all pending tasks that are
+ // selected in the ListView control.
+ void cancelButton_Click(
+ object sender,
+ EventArgs e)
+ {
+
+ // Cancel all selected tasks.
+ foreach (ListViewItem lvi in listView1.SelectedItems)
+ {
+ // Tasks that have been completed or canceled have
+ // their corresponding ListViewItem.Tag property
+ // set to null.
+ if (lvi.Tag != null)
{
- // Tasks that have been completed or canceled have
- // their corresponding ListViewItem.Tag property
- // set to null.
- if (lvi.Tag != null)
- {
- taskId = (Guid)lvi.Tag;
- this.primeNumberCalculator1.CancelAsync(taskId);
- lvi.Selected = false;
- }
+ Guid taskId = (Guid)lvi.Tag;
+ primeNumberCalculator1.CancelAsync(taskId);
+ lvi.Selected = false;
}
-
- cancelButton.Enabled = false;
}
- //
- // This event handler updates the ListView control when the
- // PrimeNumberCalculator raises the ProgressChanged event.
- //
- // On fast computers, the PrimeNumberCalculator can raise many
- // successive ProgressChanged events, so the user interface
- // may be flooded with messages. To prevent the user interface
- // from hanging, progress is only reported at intervals.
- private void primeNumberCalculator1_ProgressChanged(
- ProgressChangedEventArgs e)
+ cancelButton.Enabled = false;
+ }
+
+ //
+ // This event handler updates the ListView control when the
+ // PrimeNumberCalculator raises the ProgressChanged event.
+ //
+ // On fast computers, the PrimeNumberCalculator can raise many
+ // successive ProgressChanged events, so the user interface
+ // may be flooded with messages. To prevent the user interface
+ // from hanging, progress is only reported at intervals.
+ void primeNumberCalculator1_ProgressChanged(
+ ProgressChangedEventArgs e)
+ {
+ if (progressCounter++ % progressInterval == 0)
{
- if (this.progressCounter++ % this.progressInterval == 0)
- {
- Guid taskId = (Guid)e.UserState;
+ Guid taskId = (Guid)e.UserState;
- if (e is CalculatePrimeProgressChangedEventArgs)
- {
- CalculatePrimeProgressChangedEventArgs cppcea =
- e as CalculatePrimeProgressChangedEventArgs;
+ if (e is CalculatePrimeProgressChangedEventArgs)
+ {
+ CalculatePrimeProgressChangedEventArgs cppcea =
+ e as CalculatePrimeProgressChangedEventArgs;
- this.UpdateListViewItem(
- taskId,
- cppcea.ProgressPercentage,
- cppcea.LatestPrimeNumber);
- }
- else
- {
- this.UpdateListViewItem(
- taskId,
- e.ProgressPercentage);
- }
+ _ = UpdateListViewItem(
+ taskId,
+ cppcea.ProgressPercentage,
+ cppcea.LatestPrimeNumber);
}
- else if (this.progressCounter > this.progressInterval)
+ else
{
- this.progressCounter = 0;
+ _ = UpdateListViewItem(
+ taskId,
+ e.ProgressPercentage);
}
}
- //
-
- //
- // This event handler updates the ListView control when the
- // PrimeNumberCalculator raises the CalculatePrimeCompleted
- // event. The ListView item is updated with the appropriate
- // outcome of the calculation: Canceled, Error, or result.
- private void primeNumberCalculator1_CalculatePrimeCompleted(
- object sender,
- CalculatePrimeCompletedEventArgs e)
+ else if (progressCounter > progressInterval)
{
- Guid taskId = (Guid)e.UserState;
+ progressCounter = 0;
+ }
+ }
+ //
+
+ //
+ // This event handler updates the ListView control when the
+ // PrimeNumberCalculator raises the CalculatePrimeCompleted
+ // event. The ListView item is updated with the appropriate
+ // outcome of the calculation: Canceled, Error, or result.
+ void primeNumberCalculator1_CalculatePrimeCompleted(
+ object sender,
+ CalculatePrimeCompletedEventArgs e)
+ {
+ Guid taskId = (Guid)e.UserState;
- if (e.Cancelled)
- {
- string result = "Canceled";
+ if (e.Cancelled)
+ {
+ string result = "Canceled";
- ListViewItem lvi = UpdateListViewItem(taskId, result);
+ ListViewItem lvi = UpdateListViewItem(taskId, result);
- if (lvi != null)
- {
- lvi.BackColor = Color.Pink;
- lvi.Tag = null;
- }
- }
- else if (e.Error != null)
+ if (lvi != null)
{
- string result = "Error";
+ lvi.BackColor = Color.Pink;
+ lvi.Tag = null;
+ }
+ }
+ else if (e.Error != null)
+ {
+ string result = "Error";
- ListViewItem lvi = UpdateListViewItem(taskId, result);
+ ListViewItem lvi = UpdateListViewItem(taskId, result);
- if (lvi != null)
- {
- lvi.BackColor = Color.Red;
- lvi.ForeColor = Color.White;
- lvi.Tag = null;
- }
+ if (lvi != null)
+ {
+ lvi.BackColor = Color.Red;
+ lvi.ForeColor = Color.White;
+ lvi.Tag = null;
}
- else
- {
- bool result = e.IsPrime;
+ }
+ else
+ {
+ bool result = e.IsPrime;
- ListViewItem lvi = UpdateListViewItem(
- taskId,
- result,
- e.FirstDivisor);
+ ListViewItem lvi = UpdateListViewItem(
+ taskId,
+ result,
+ e.FirstDivisor);
- if (lvi != null)
- {
- lvi.BackColor = Color.LightGray;
- lvi.Tag = null;
- }
+ if (lvi != null)
+ {
+ lvi.BackColor = Color.LightGray;
+ lvi.Tag = null;
}
}
- //
+ }
+ //
- #endregion // Implementation
+ #endregion // Implementation
- /////////////////////////////////////////////////////////////
- //
- #region Private Methods
+ /////////////////////////////////////////////////////////////
+ //
+ #region Private Methods
- private ListViewItem AddListViewItem(
- Guid guid,
- int testNumber )
+ ListViewItem AddListViewItem(
+ Guid guid,
+ int testNumber)
+ {
+ ListViewItem lvi = new()
{
- ListViewItem lvi = new ListViewItem();
- lvi.Text = testNumber.ToString(
- CultureInfo.CurrentCulture.NumberFormat);
-
- lvi.SubItems.Add("Not Started");
- lvi.SubItems.Add("1");
- lvi.SubItems.Add(guid.ToString());
- lvi.SubItems.Add("---");
- lvi.SubItems.Add("---");
- lvi.Tag = guid;
+ Text = testNumber.ToString(
+ CultureInfo.CurrentCulture.NumberFormat)
+ };
- this.listView1.Items.Add( lvi );
+ _ = lvi.SubItems.Add("Not Started");
+ _ = lvi.SubItems.Add("1");
+ _ = lvi.SubItems.Add(guid.ToString());
+ _ = lvi.SubItems.Add("---");
+ _ = lvi.SubItems.Add("---");
+ lvi.Tag = guid;
- return lvi;
- }
+ _ = listView1.Items.Add(lvi);
- private ListViewItem UpdateListViewItem(
- Guid guid,
- int percentComplete,
- int current )
- {
- ListViewItem lviRet = null;
-
- foreach (ListViewItem lvi in this.listView1.Items)
- {
- if (lvi.Tag != null)
- {
- if ((Guid)lvi.Tag == guid)
- {
- lvi.SubItems[1].Text =
- percentComplete.ToString(
- CultureInfo.CurrentCulture.NumberFormat);
- lvi.SubItems[2].Text =
- current.ToString(
- CultureInfo.CurrentCulture.NumberFormat);
- lviRet = lvi;
- break;
- }
- }
- }
+ return lvi;
+ }
- return lviRet;
- }
+ ListViewItem UpdateListViewItem(
+ Guid guid,
+ int percentComplete,
+ int current)
+ {
+ ListViewItem lviRet = null;
- private ListViewItem UpdateListViewItem(
- Guid guid,
- int percentComplete,
- int current,
- bool result,
- int firstDivisor )
+ foreach (ListViewItem lvi in listView1.Items)
{
- ListViewItem lviRet = null;
-
- foreach (ListViewItem lvi in this.listView1.Items)
+ if (lvi.Tag != null)
{
if ((Guid)lvi.Tag == guid)
{
- lvi.SubItems[1].Text =
+ lvi.SubItems[1].Text =
percentComplete.ToString(
CultureInfo.CurrentCulture.NumberFormat);
- lvi.SubItems[2].Text =
+ lvi.SubItems[2].Text =
current.ToString(
CultureInfo.CurrentCulture.NumberFormat);
- lvi.SubItems[4].Text =
- result ? "Prime" : "Composite";
- lvi.SubItems[5].Text =
- firstDivisor.ToString(
- CultureInfo.CurrentCulture.NumberFormat);
-
lviRet = lvi;
-
break;
}
}
-
- return lviRet;
}
- private ListViewItem UpdateListViewItem(
- Guid guid,
- int percentComplete )
- {
- ListViewItem lviRet = null;
+ return lviRet;
+ }
- foreach (ListViewItem lvi in this.listView1.Items)
+ ListViewItem UpdateListViewItem(
+ Guid guid,
+ int percentComplete,
+ int current,
+ bool result,
+ int firstDivisor)
+ {
+ ListViewItem lviRet = null;
+
+ foreach (ListViewItem lvi in listView1.Items)
+ {
+ if ((Guid)lvi.Tag == guid)
{
- if (lvi.Tag != null)
- {
- if ((Guid)lvi.Tag == guid)
- {
- lvi.SubItems[1].Text =
- percentComplete.ToString(
- CultureInfo.CurrentCulture.NumberFormat);
- lviRet = lvi;
- break;
- }
- }
+ lvi.SubItems[1].Text =
+ percentComplete.ToString(
+ CultureInfo.CurrentCulture.NumberFormat);
+ lvi.SubItems[2].Text =
+ current.ToString(
+ CultureInfo.CurrentCulture.NumberFormat);
+ lvi.SubItems[4].Text =
+ result ? "Prime" : "Composite";
+ lvi.SubItems[5].Text =
+ firstDivisor.ToString(
+ CultureInfo.CurrentCulture.NumberFormat);
+
+ lviRet = lvi;
+
+ break;
}
-
- return lviRet;
}
- private ListViewItem UpdateListViewItem(
- Guid guid,
- bool result,
- int firstDivisor )
- {
- ListViewItem lviRet = null;
+ return lviRet;
+ }
- foreach (ListViewItem lvi in this.listView1.Items)
+ ListViewItem UpdateListViewItem(
+ Guid guid,
+ int percentComplete)
+ {
+ ListViewItem lviRet = null;
+
+ foreach (ListViewItem lvi in listView1.Items)
+ {
+ if (lvi.Tag != null)
{
- if (lvi.Tag != null)
+ if ((Guid)lvi.Tag == guid)
{
- if ((Guid)lvi.Tag == guid)
- {
- lvi.SubItems[4].Text =
- result ? "Prime" : "Composite";
- lvi.SubItems[5].Text =
- firstDivisor.ToString(
- CultureInfo.CurrentCulture.NumberFormat);
- lviRet = lvi;
- break;
- }
+ lvi.SubItems[1].Text =
+ percentComplete.ToString(
+ CultureInfo.CurrentCulture.NumberFormat);
+ lviRet = lvi;
+ break;
}
}
-
- return lviRet;
}
- private ListViewItem UpdateListViewItem(
- Guid guid,
- string result)
- {
- ListViewItem lviRet = null;
+ return lviRet;
+ }
- foreach (ListViewItem lvi in this.listView1.Items)
+ ListViewItem UpdateListViewItem(
+ Guid guid,
+ bool result,
+ int firstDivisor)
+ {
+ ListViewItem lviRet = null;
+
+ foreach (ListViewItem lvi in listView1.Items)
+ {
+ if (lvi.Tag != null)
{
- if (lvi.Tag != null)
+ if ((Guid)lvi.Tag == guid)
{
- if ((Guid)lvi.Tag == guid)
- {
- lvi.SubItems[4].Text = result;
- lviRet = lvi;
- break;
- }
+ lvi.SubItems[4].Text =
+ result ? "Prime" : "Composite";
+ lvi.SubItems[5].Text =
+ firstDivisor.ToString(
+ CultureInfo.CurrentCulture.NumberFormat);
+ lviRet = lvi;
+ break;
}
}
-
- return lviRet;
}
- private bool CanCancel()
- {
- bool oneIsActive = false;
+ return lviRet;
+ }
+
+ ListViewItem UpdateListViewItem(
+ Guid guid,
+ string result)
+ {
+ ListViewItem lviRet = null;
- foreach(ListViewItem lvi in this.listView1.SelectedItems)
+ foreach (ListViewItem lvi in listView1.Items)
+ {
+ if (lvi.Tag != null)
{
- if (lvi.Tag != null)
+ if ((Guid)lvi.Tag == guid)
{
- oneIsActive = true;
+ lvi.SubItems[4].Text = result;
+ lviRet = lvi;
break;
}
}
-
- return( oneIsActive == true );
}
- #endregion
-
- #region Windows Form Designer generated code
-
- private void InitializeComponent()
- {
- this.components = new System.ComponentModel.Container();
- this.taskGroupBox = new System.Windows.Forms.GroupBox();
- this.buttonPanel = new System.Windows.Forms.Panel();
- this.cancelButton = new System.Windows.Forms.Button();
- this.startAsyncButton = new System.Windows.Forms.Button();
- this.listView1 = new System.Windows.Forms.ListView();
- this.testNumberColHeader = new System.Windows.Forms.ColumnHeader();
- this.progressColHeader = new System.Windows.Forms.ColumnHeader();
- this.currentColHeader = new System.Windows.Forms.ColumnHeader();
- this.taskIdColHeader = new System.Windows.Forms.ColumnHeader();
- this.resultColHeader = new System.Windows.Forms.ColumnHeader();
- this.firstDivisorColHeader = new System.Windows.Forms.ColumnHeader();
- this.panel2 = new System.Windows.Forms.Panel();
- this.primeNumberCalculator1 = new AsyncOperationManagerExample.PrimeNumberCalculator(this.components);
- this.taskGroupBox.SuspendLayout();
- this.buttonPanel.SuspendLayout();
- this.SuspendLayout();
- //
- // taskGroupBox
- //
- this.taskGroupBox.Controls.Add(this.buttonPanel);
- this.taskGroupBox.Controls.Add(this.listView1);
- this.taskGroupBox.Dock = System.Windows.Forms.DockStyle.Fill;
- this.taskGroupBox.Location = new System.Drawing.Point(0, 0);
- this.taskGroupBox.Name = "taskGroupBox";
- this.taskGroupBox.Size = new System.Drawing.Size(608, 254);
- this.taskGroupBox.TabIndex = 1;
- this.taskGroupBox.TabStop = false;
- this.taskGroupBox.Text = "Tasks";
- //
- // buttonPanel
- //
- this.buttonPanel.Controls.Add(this.cancelButton);
- this.buttonPanel.Controls.Add(this.startAsyncButton);
- this.buttonPanel.Dock = System.Windows.Forms.DockStyle.Bottom;
- this.buttonPanel.Location = new System.Drawing.Point(3, 176);
- this.buttonPanel.Name = "buttonPanel";
- this.buttonPanel.Size = new System.Drawing.Size(602, 75);
- this.buttonPanel.TabIndex = 1;
- //
- // cancelButton
- //
- this.cancelButton.Enabled = false;
- this.cancelButton.Location = new System.Drawing.Point(128, 24);
- this.cancelButton.Name = "cancelButton";
- this.cancelButton.Size = new System.Drawing.Size(88, 23);
- this.cancelButton.TabIndex = 1;
- this.cancelButton.Text = "Cancel";
- this.cancelButton.Click += new System.EventHandler(this.cancelButton_Click);
- //
- // startAsyncButton
- //
- this.startAsyncButton.Location = new System.Drawing.Point(24, 24);
- this.startAsyncButton.Name = "startAsyncButton";
- this.startAsyncButton.Size = new System.Drawing.Size(88, 23);
- this.startAsyncButton.TabIndex = 0;
- this.startAsyncButton.Text = "Start New Task";
- this.startAsyncButton.Click += new System.EventHandler(this.startAsyncButton_Click);
- //
- // listView1
- //
- this.listView1.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
- this.testNumberColHeader,
- this.progressColHeader,
- this.currentColHeader,
- this.taskIdColHeader,
- this.resultColHeader,
- this.firstDivisorColHeader});
- this.listView1.Dock = System.Windows.Forms.DockStyle.Fill;
- this.listView1.FullRowSelect = true;
- this.listView1.GridLines = true;
- this.listView1.Location = new System.Drawing.Point(3, 16);
- this.listView1.Name = "listView1";
- this.listView1.Size = new System.Drawing.Size(602, 160);
- this.listView1.TabIndex = 0;
- this.listView1.View = System.Windows.Forms.View.Details;
- //
- // testNumberColHeader
- //
- this.testNumberColHeader.Text = "Test Number";
- this.testNumberColHeader.Width = 80;
- //
- // progressColHeader
- //
- this.progressColHeader.Text = "Progress";
- //
- // currentColHeader
- //
- this.currentColHeader.Text = "Current";
- //
- // taskIdColHeader
- //
- this.taskIdColHeader.Text = "Task ID";
- this.taskIdColHeader.Width = 200;
- //
- // resultColHeader
- //
- this.resultColHeader.Text = "Result";
- this.resultColHeader.Width = 80;
- //
- // firstDivisorColHeader
- //
- this.firstDivisorColHeader.Text = "First Divisor";
- this.firstDivisorColHeader.Width = 80;
- //
- // panel2
- //
- this.panel2.Location = new System.Drawing.Point(200, 128);
- this.panel2.Name = "panel2";
- this.panel2.TabIndex = 2;
- //
- // PrimeNumberCalculatorMain
- //
- this.ClientSize = new System.Drawing.Size(608, 254);
- this.Controls.Add(this.taskGroupBox);
- this.Name = "PrimeNumberCalculatorMain";
- this.Text = "Prime Number Calculator";
- this.taskGroupBox.ResumeLayout(false);
- this.buttonPanel.ResumeLayout(false);
- this.ResumeLayout(false);
- }
- #endregion
+ return lviRet;
+ }
+
+ bool CanCancel()
+ {
+ bool oneIsActive = false;
- [STAThread]
- static void Main()
- {
- Application.Run(new PrimeNumberCalculatorMain());
+ foreach (ListViewItem lvi in listView1.SelectedItems)
+ {
+ if (lvi.Tag != null)
+ {
+ oneIsActive = true;
+ break;
+ }
}
+
+ return oneIsActive == true;
}
- //
+ #endregion
+
+ #region Windows Form Designer generated code
- /////////////////////////////////////////////////////////////
- #region PrimeNumberCalculator Implementation
+ void InitializeComponent()
+ {
+ _components = new Container();
+ taskGroupBox = new GroupBox();
+ buttonPanel = new Panel();
+ cancelButton = new Button();
+ startAsyncButton = new Button();
+ listView1 = new ListView();
+ testNumberColHeader = new ColumnHeader();
+ progressColHeader = new ColumnHeader();
+ currentColHeader = new ColumnHeader();
+ taskIdColHeader = new ColumnHeader();
+ resultColHeader = new ColumnHeader();
+ firstDivisorColHeader = new ColumnHeader();
+ panel2 = new Panel();
+ primeNumberCalculator1 = new PrimeNumberCalculator(_components);
+ taskGroupBox.SuspendLayout();
+ buttonPanel.SuspendLayout();
+ SuspendLayout();
+ //
+ // taskGroupBox
+ //
+ taskGroupBox.Controls.Add(buttonPanel);
+ taskGroupBox.Controls.Add(listView1);
+ taskGroupBox.Dock = DockStyle.Fill;
+ taskGroupBox.Location = new Point(0, 0);
+ taskGroupBox.Name = "taskGroupBox";
+ taskGroupBox.Size = new Size(608, 254);
+ taskGroupBox.TabIndex = 1;
+ taskGroupBox.TabStop = false;
+ taskGroupBox.Text = "Tasks";
+ //
+ // buttonPanel
+ //
+ buttonPanel.Controls.Add(cancelButton);
+ buttonPanel.Controls.Add(startAsyncButton);
+ buttonPanel.Dock = DockStyle.Bottom;
+ buttonPanel.Location = new Point(3, 176);
+ buttonPanel.Name = "buttonPanel";
+ buttonPanel.Size = new Size(602, 75);
+ buttonPanel.TabIndex = 1;
+ //
+ // cancelButton
+ //
+ cancelButton.Enabled = false;
+ cancelButton.Location = new Point(128, 24);
+ cancelButton.Name = "cancelButton";
+ cancelButton.Size = new Size(88, 23);
+ cancelButton.TabIndex = 1;
+ cancelButton.Text = "Cancel";
+ cancelButton.Click += cancelButton_Click;
+ //
+ // startAsyncButton
+ //
+ startAsyncButton.Location = new Point(24, 24);
+ startAsyncButton.Name = "startAsyncButton";
+ startAsyncButton.Size = new Size(88, 23);
+ startAsyncButton.TabIndex = 0;
+ startAsyncButton.Text = "Start New Task";
+ startAsyncButton.Click += startAsyncButton_Click;
+ //
+ // listView1
+ //
+ listView1.Columns.AddRange(new ColumnHeader[] {
+ testNumberColHeader,
+ progressColHeader,
+ currentColHeader,
+ taskIdColHeader,
+ resultColHeader,
+ firstDivisorColHeader});
+ listView1.Dock = DockStyle.Fill;
+ listView1.FullRowSelect = true;
+ listView1.GridLines = true;
+ listView1.Location = new Point(3, 16);
+ listView1.Name = "listView1";
+ listView1.Size = new Size(602, 160);
+ listView1.TabIndex = 0;
+ listView1.View = View.Details;
+ //
+ // testNumberColHeader
+ //
+ testNumberColHeader.Text = "Test Number";
+ testNumberColHeader.Width = 80;
+ //
+ // progressColHeader
+ //
+ progressColHeader.Text = "Progress";
+ //
+ // currentColHeader
+ //
+ currentColHeader.Text = "Current";
+ //
+ // taskIdColHeader
+ //
+ taskIdColHeader.Text = "Task ID";
+ taskIdColHeader.Width = 200;
+ //
+ // resultColHeader
+ //
+ resultColHeader.Text = "Result";
+ resultColHeader.Width = 80;
+ //
+ // firstDivisorColHeader
+ //
+ firstDivisorColHeader.Text = "First Divisor";
+ firstDivisorColHeader.Width = 80;
+ //
+ // panel2
+ //
+ panel2.Location = new Point(200, 128);
+ panel2.Name = "panel2";
+ panel2.TabIndex = 2;
+ //
+ // PrimeNumberCalculatorMain
+ //
+ ClientSize = new Size(608, 254);
+ Controls.Add(taskGroupBox);
+ Name = "PrimeNumberCalculatorMain";
+ Text = "Prime Number Calculator";
+ taskGroupBox.ResumeLayout(false);
+ buttonPanel.ResumeLayout(false);
+ ResumeLayout(false);
+ }
+ #endregion
- //
- public delegate void ProgressChangedEventHandler(
- ProgressChangedEventArgs e);
+ [STAThread]
+ static void Main() =>
+ Application.Run(new PrimeNumberCalculatorMain());
+}
- public delegate void CalculatePrimeCompletedEventHandler(
- object sender,
- CalculatePrimeCompletedEventArgs e);
- //
+//
- // This class implements the Event-based Asynchronous Pattern.
- // It asynchronously computes whether a number is prime or
- // composite (not prime).
- public class PrimeNumberCalculator : Component
- {
- //
- private delegate void WorkerEventHandler(
- int numberToCheck,
- AsyncOperation asyncOp);
- //
+/////////////////////////////////////////////////////////////
+#region PrimeNumberCalculator Implementation
- //
- private SendOrPostCallback onProgressReportDelegate;
- private SendOrPostCallback onCompletedDelegate;
- //
+//
+public delegate void ProgressChangedEventHandler(
+ ProgressChangedEventArgs e);
- //
- private HybridDictionary userStateToLifetime =
- new HybridDictionary();
- //
+public delegate void CalculatePrimeCompletedEventHandler(
+ object sender,
+ CalculatePrimeCompletedEventArgs e);
+//
- private System.ComponentModel.Container components = null;
+// This class implements the Event-based Asynchronous Pattern.
+// It asynchronously computes whether a number is prime or
+// composite (not prime).
+public class PrimeNumberCalculator : Component
+{
+ //
+ delegate void WorkerEventHandler(
+ int numberToCheck,
+ AsyncOperation asyncOp);
+ //
- /////////////////////////////////////////////////////////////
- #region Public events
+ //
+ SendOrPostCallback onProgressReportDelegate;
+ SendOrPostCallback onCompletedDelegate;
+ //
- //
- public event ProgressChangedEventHandler ProgressChanged;
- public event CalculatePrimeCompletedEventHandler CalculatePrimeCompleted;
- //
+ //
+ readonly HybridDictionary userStateToLifetime =
+ [];
+ //
- #endregion
+ Container components;
- /////////////////////////////////////////////////////////////
- #region Construction and destruction
+ /////////////////////////////////////////////////////////////
+ #region Public events
- public PrimeNumberCalculator(IContainer container)
- {
- container.Add(this);
- InitializeComponent();
+ //
+ public event ProgressChangedEventHandler ProgressChanged;
+ public event CalculatePrimeCompletedEventHandler CalculatePrimeCompleted;
+ //
- InitializeDelegates();
- }
+ #endregion
- //
- public PrimeNumberCalculator()
- {
- InitializeComponent();
+ /////////////////////////////////////////////////////////////
+ #region Construction and destruction
- InitializeDelegates();
- }
- //
+ public PrimeNumberCalculator(IContainer container)
+ {
+ container.Add(this);
+ InitializeComponent();
- //
- protected virtual void InitializeDelegates()
- {
- onProgressReportDelegate =
- new SendOrPostCallback(ReportProgress);
- onCompletedDelegate =
- new SendOrPostCallback(CalculateCompleted);
- }
- //
+ InitializeDelegates();
+ }
+
+ //
+ public PrimeNumberCalculator()
+ {
+ InitializeComponent();
+
+ InitializeDelegates();
+ }
+ //
- protected override void Dispose(bool disposing)
+ //
+ protected virtual void InitializeDelegates()
+ {
+ onProgressReportDelegate =
+ new SendOrPostCallback(ReportProgress);
+ onCompletedDelegate =
+ new SendOrPostCallback(CalculateCompleted);
+ }
+ //
+
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing)
{
- if (disposing)
- {
- if (components != null)
- {
- components.Dispose();
- }
- }
- base.Dispose(disposing);
+ components?.Dispose();
}
+ base.Dispose(disposing);
+ }
- #endregion // Construction and destruction
+ #endregion // Construction and destruction
- /////////////////////////////////////////////////////////////
- ///
- #region Implementation
+ /////////////////////////////////////////////////////////////
+ #region Implementation
+
+ //
+ // This method starts an asynchronous calculation.
+ // First, it checks the supplied task ID for uniqueness.
+ // If taskId is unique, it creates a new WorkerEventHandler
+ // and calls its BeginInvoke method to start the calculation.
+ public virtual void CalculatePrimeAsync(
+ int numberToTest,
+ object taskId)
+ {
+ // Create an AsyncOperation for taskId.
+ AsyncOperation asyncOp =
+ AsyncOperationManager.CreateOperation(taskId);
- //
- // This method starts an asynchronous calculation.
- // First, it checks the supplied task ID for uniqueness.
- // If taskId is unique, it creates a new WorkerEventHandler
- // and calls its BeginInvoke method to start the calculation.
- public virtual void CalculatePrimeAsync(
- int numberToTest,
- object taskId)
+ // Multiple threads will access the task dictionary,
+ // so it must be locked to serialize access.
+ lock (userStateToLifetime.SyncRoot)
{
- // Create an AsyncOperation for taskId.
- AsyncOperation asyncOp =
- AsyncOperationManager.CreateOperation(taskId);
-
- // Multiple threads will access the task dictionary,
- // so it must be locked to serialize access.
- lock (userStateToLifetime.SyncRoot)
+ if (userStateToLifetime.Contains(taskId))
{
- if (userStateToLifetime.Contains(taskId))
- {
- throw new ArgumentException(
- "Task ID parameter must be unique",
- "taskId");
- }
-
- userStateToLifetime[taskId] = asyncOp;
+ throw new ArgumentException(
+ "Task ID parameter must be unique",
+ nameof(taskId));
}
- // Start the asynchronous operation.
- WorkerEventHandler workerDelegate = new WorkerEventHandler(CalculateWorker);
- workerDelegate.BeginInvoke(
- numberToTest,
- asyncOp,
- null,
- null);
+ userStateToLifetime[taskId] = asyncOp;
}
- //
- //
- // Utility method for determining if a
- // task has been canceled.
- private bool TaskCanceled(object taskId)
- {
- return( userStateToLifetime[taskId] == null );
- }
- //
-
- //
- // This method cancels a pending asynchronous operation.
- public void CancelAsync(object taskId)
+ // Start the asynchronous operation.
+ WorkerEventHandler workerDelegate = new(CalculateWorker);
+ _ = workerDelegate.BeginInvoke(
+ numberToTest,
+ asyncOp,
+ null,
+ null);
+ }
+ //
+
+ //
+ // Utility method for determining if a
+ // task has been canceled.
+ bool TaskCanceled(object taskId) =>
+ userStateToLifetime[taskId] == null;
+ //
+
+ //
+ // This method cancels a pending asynchronous operation.
+ public void CancelAsync(object taskId)
+ {
+ if (userStateToLifetime[taskId] is AsyncOperation)
{
- AsyncOperation asyncOp = userStateToLifetime[taskId] as AsyncOperation;
- if (asyncOp != null)
- {
- lock (userStateToLifetime.SyncRoot)
- {
- userStateToLifetime.Remove(taskId);
- }
+ lock (userStateToLifetime.SyncRoot)
+ {
+ userStateToLifetime.Remove(taskId);
}
}
- //
-
- //
- // This method performs the actual prime number computation.
- // It is executed on the worker thread.
- private void CalculateWorker(
- int numberToTest,
- AsyncOperation asyncOp)
+ }
+ //
+
+ //
+ // This method performs the actual prime number computation.
+ // It is executed on the worker thread.
+ void CalculateWorker(
+ int numberToTest,
+ AsyncOperation asyncOp)
+ {
+ bool isPrime = false;
+ int firstDivisor = 1;
+ Exception e = null;
+
+ // Check that the task is still active.
+ // The operation may have been canceled before
+ // the thread was scheduled.
+ if (!TaskCanceled(asyncOp.UserSuppliedState))
{
- bool isPrime = false;
- int firstDivisor = 1;
- Exception e = null;
-
- // Check that the task is still active.
- // The operation may have been canceled before
- // the thread was scheduled.
- if (!TaskCanceled(asyncOp.UserSuppliedState))
+ try
{
- try
- {
- // Find all the prime numbers up to
- // the square root of numberToTest.
- ArrayList primes = BuildPrimeNumberList(
- numberToTest,
- asyncOp);
-
- // Now we have a list of primes less than
- // numberToTest.
- isPrime = IsPrime(
- primes,
- numberToTest,
- out firstDivisor);
- }
- catch (Exception ex)
- {
- e = ex;
- }
+ // Find all the prime numbers up to
+ // the square root of numberToTest.
+ ArrayList primes = BuildPrimeNumberList(
+ numberToTest,
+ asyncOp);
+
+ // Now we have a list of primes less than
+ // numberToTest.
+ isPrime = IsPrime(
+ primes,
+ numberToTest,
+ out firstDivisor);
+ }
+ catch (Exception ex)
+ {
+ e = ex;
}
+ }
- //CalculatePrimeState calcState = new CalculatePrimeState(
- // numberToTest,
- // firstDivisor,
- // isPrime,
- // e,
- // TaskCanceled(asyncOp.UserSuppliedState),
- // asyncOp);
+ //CalculatePrimeState calcState = new CalculatePrimeState(
+ // numberToTest,
+ // firstDivisor,
+ // isPrime,
+ // e,
+ // TaskCanceled(asyncOp.UserSuppliedState),
+ // asyncOp);
- //this.CompletionMethod(calcState);
+ //this.CompletionMethod(calcState);
- this.CompletionMethod(
- numberToTest,
- firstDivisor,
- isPrime,
- e,
- TaskCanceled(asyncOp.UserSuppliedState),
- asyncOp);
+ CompletionMethod(
+ numberToTest,
+ firstDivisor,
+ isPrime,
+ e,
+ TaskCanceled(asyncOp.UserSuppliedState),
+ asyncOp);
- //completionMethodDelegate(calcState);
- }
- //
-
- //
- // This method computes the list of prime numbers used by the
- // IsPrime method.
- private ArrayList BuildPrimeNumberList(
- int numberToTest,
- AsyncOperation asyncOp)
+ //completionMethodDelegate(calcState);
+ }
+ //
+
+ //
+ // This method computes the list of prime numbers used by the
+ // IsPrime method.
+ ArrayList BuildPrimeNumberList(
+ int numberToTest,
+ AsyncOperation asyncOp)
+ {
+ ArrayList primes = [];
+ int n = 5;
+
+ // Add the first prime numbers.
+ _ = primes.Add(2);
+ _ = primes.Add(3);
+
+ // Do the work.
+ while (n < numberToTest &&
+ !TaskCanceled(asyncOp.UserSuppliedState))
{
- ProgressChangedEventArgs e = null;
- ArrayList primes = new ArrayList();
- int firstDivisor;
- int n = 5;
-
- // Add the first prime numbers.
- primes.Add(2);
- primes.Add(3);
-
- // Do the work.
- while (n < numberToTest &&
- !TaskCanceled( asyncOp.UserSuppliedState ) )
+ if (IsPrime(primes, n, out int firstDivisor))
{
- if (IsPrime(primes, n, out firstDivisor))
- {
- // Report to the client that a prime was found.
- e = new CalculatePrimeProgressChangedEventArgs(
- n,
- (int)((float)n / (float)numberToTest * 100),
- asyncOp.UserSuppliedState);
+ // Report to the client that a prime was found.
+ ProgressChangedEventArgs e = new CalculatePrimeProgressChangedEventArgs(
+ n,
+ (int)(n / (float)numberToTest * 100),
+ asyncOp.UserSuppliedState);
- asyncOp.Post(this.onProgressReportDelegate, e);
+ asyncOp.Post(onProgressReportDelegate, e);
- primes.Add(n);
-
- // Yield the rest of this time slice.
- Thread.Sleep(0);
- }
+ _ = primes.Add(n);
- // Skip even numbers.
- n += 2;
+ // Yield the rest of this time slice.
+ Thread.Sleep(0);
}
- return primes;
+ // Skip even numbers.
+ n += 2;
}
- //
-
- //
- // This method tests n for primality against the list of
- // prime numbers contained in the primes parameter.
- private bool IsPrime(
- ArrayList primes,
- int n,
- out int firstDivisor)
+
+ return primes;
+ }
+ //
+
+ //
+ // This method tests n for primality against the list of
+ // prime numbers contained in the primes parameter.
+ bool IsPrime(
+ ArrayList primes,
+ int n,
+ out int firstDivisor)
+ {
+ bool foundDivisor = false;
+ bool exceedsSquareRoot = false;
+
+ int i = 0;
+ firstDivisor = 1;
+
+ // Stop the search if:
+ // there are no more primes in the list,
+ // there is a divisor of n in the list, or
+ // there is a prime that is larger than
+ // the square root of n.
+ while (
+ (i < primes.Count) &&
+ !foundDivisor &&
+ !exceedsSquareRoot)
{
- bool foundDivisor = false;
- bool exceedsSquareRoot = false;
-
- int i = 0;
- int divisor = 0;
- firstDivisor = 1;
-
- // Stop the search if:
- // there are no more primes in the list,
- // there is a divisor of n in the list, or
- // there is a prime that is larger than
- // the square root of n.
- while (
- (i < primes.Count) &&
- !foundDivisor &&
- !exceedsSquareRoot)
- {
- // The divisor variable will be the smallest
- // prime number not yet tried.
- divisor = (int)primes[i++];
+ // The divisor variable will be the smallest
+ // prime number not yet tried.
+ int divisor = (int)primes[i++];
- // Determine whether the divisor is greater
- // than the square root of n.
- if (divisor * divisor > n)
- {
- exceedsSquareRoot = true;
- }
- // Determine whether the divisor is a factor of n.
- else if (n % divisor == 0)
- {
- firstDivisor = divisor;
- foundDivisor = true;
- }
+ // Determine whether the divisor is greater
+ // than the square root of n.
+ if (divisor * divisor > n)
+ {
+ exceedsSquareRoot = true;
+ }
+ // Determine whether the divisor is a factor of n.
+ else if (n % divisor == 0)
+ {
+ firstDivisor = divisor;
+ foundDivisor = true;
}
-
- return !foundDivisor;
}
- //
- //
- // This method is invoked via the AsyncOperation object,
- // so it is guaranteed to be executed on the correct thread.
- private void CalculateCompleted(object operationState)
- {
- CalculatePrimeCompletedEventArgs e =
- operationState as CalculatePrimeCompletedEventArgs;
+ return !foundDivisor;
+ }
+ //
- OnCalculatePrimeCompleted(e);
- }
+ //
+ // This method is invoked via the AsyncOperation object,
+ // so it is guaranteed to be executed on the correct thread.
+ void CalculateCompleted(object operationState)
+ {
+ CalculatePrimeCompletedEventArgs e =
+ operationState as CalculatePrimeCompletedEventArgs;
- // This method is invoked via the AsyncOperation object,
- // so it is guaranteed to be executed on the correct thread.
- private void ReportProgress(object state)
- {
- ProgressChangedEventArgs e =
- state as ProgressChangedEventArgs;
+ OnCalculatePrimeCompleted(e);
+ }
- OnProgressChanged(e);
- }
+ // This method is invoked via the AsyncOperation object,
+ // so it is guaranteed to be executed on the correct thread.
+ void ReportProgress(object state)
+ {
+ ProgressChangedEventArgs e =
+ state as ProgressChangedEventArgs;
- protected void OnCalculatePrimeCompleted(
- CalculatePrimeCompletedEventArgs e)
- {
- if (CalculatePrimeCompleted != null)
- {
- CalculatePrimeCompleted(this, e);
- }
- }
+ OnProgressChanged(e);
+ }
+
+ protected void OnCalculatePrimeCompleted(
+ CalculatePrimeCompletedEventArgs e) =>
+ CalculatePrimeCompleted?.Invoke(this, e);
+
+ protected void OnProgressChanged(ProgressChangedEventArgs e) =>
+ ProgressChanged?.Invoke(e);
+ //
+
+ //
+ // This is the method that the underlying, free-threaded
+ // asynchronous behavior will invoke. This will happen on
+ // an arbitrary thread.
+ void CompletionMethod(
+ int numberToTest,
+ int firstDivisor,
+ bool isPrime,
+ Exception exception,
+ bool canceled,
+ AsyncOperation asyncOp)
- protected void OnProgressChanged(ProgressChangedEventArgs e)
+ {
+ // If the task was not previously canceled,
+ // remove the task from the lifetime collection.
+ if (!canceled)
{
- if (ProgressChanged != null)
+ lock (userStateToLifetime.SyncRoot)
{
- ProgressChanged(e);
+ userStateToLifetime.Remove(asyncOp.UserSuppliedState);
}
}
- //
-
- //
- // This is the method that the underlying, free-threaded
- // asynchronous behavior will invoke. This will happen on
- // an arbitrary thread.
- private void CompletionMethod(
- int numberToTest,
- int firstDivisor,
- bool isPrime,
- Exception exception,
- bool canceled,
- AsyncOperation asyncOp )
- {
- // If the task was not previously canceled,
- // remove the task from the lifetime collection.
- if (!canceled)
- {
- lock (userStateToLifetime.SyncRoot)
- {
- userStateToLifetime.Remove(asyncOp.UserSuppliedState);
- }
- }
+ // Package the results of the operation in a
+ // CalculatePrimeCompletedEventArgs.
+ CalculatePrimeCompletedEventArgs e =
+ new(
+
- // Package the results of the operation in a
- // CalculatePrimeCompletedEventArgs.
- CalculatePrimeCompletedEventArgs e =
- new CalculatePrimeCompletedEventArgs(
numberToTest,
firstDivisor,
isPrime,
@@ -921,122 +896,107 @@ private void CompletionMethod(
canceled,
asyncOp.UserSuppliedState);
- // End the task. The asyncOp object is responsible
- // for marshaling the call.
- asyncOp.PostOperationCompleted(onCompletedDelegate, e);
+ // End the task. The asyncOp object is responsible
+ // for marshaling the call.
+ asyncOp.PostOperationCompleted(onCompletedDelegate, e);
- // Note that after the call to OperationCompleted,
- // asyncOp is no longer usable, and any attempt to use it
- // will cause an exception to be thrown.
- }
- //
+ // Note that after the call to OperationCompleted,
+ // asyncOp is no longer usable, and any attempt to use it
+ // will cause an exception to be thrown.
+ }
+ //
- #endregion
+ #endregion
- /////////////////////////////////////////////////////////////
- #region Component Designer generated code
+ /////////////////////////////////////////////////////////////
+ #region Component Designer generated code
- private void InitializeComponent()
- {
- components = new System.ComponentModel.Container();
- }
+ void InitializeComponent() => components = new Container();
- #endregion
-
- }
+ #endregion
- //
- public class CalculatePrimeProgressChangedEventArgs :
- ProgressChangedEventArgs
- {
- private int latestPrimeNumberValue = 1;
+}
- public CalculatePrimeProgressChangedEventArgs(
- int latestPrime,
- int progressPercentage,
- object userToken) : base( progressPercentage, userToken )
- {
- this.latestPrimeNumberValue = latestPrime;
- }
+//
+public class CalculatePrimeProgressChangedEventArgs :
+ ProgressChangedEventArgs
+{
+ public CalculatePrimeProgressChangedEventArgs(
+ int latestPrime,
+ int progressPercentage,
+ object userToken) : base(progressPercentage, userToken) => LatestPrimeNumber = latestPrime;
- public int LatestPrimeNumber
- {
- get
- {
- return latestPrimeNumberValue;
- }
- }
- }
- //
+ public int LatestPrimeNumber { get; } = 1;
+}
+//
- //
- public class CalculatePrimeCompletedEventArgs :
- AsyncCompletedEventArgs
+//
+public class CalculatePrimeCompletedEventArgs :
+ AsyncCompletedEventArgs
+{
+ readonly int numberToTestValue;
+ readonly int firstDivisorValue = 1;
+ readonly bool isPrimeValue;
+
+ public CalculatePrimeCompletedEventArgs(
+ int numberToTest,
+ int firstDivisor,
+ bool isPrime,
+ Exception e,
+ bool canceled,
+ object state) : base(e, canceled, state)
{
- private int numberToTestValue = 0;
- private int firstDivisorValue = 1;
- private bool isPrimeValue;
-
- public CalculatePrimeCompletedEventArgs(
- int numberToTest,
- int firstDivisor,
- bool isPrime,
- Exception e,
- bool canceled,
- object state) : base(e, canceled, state)
- {
- this.numberToTestValue = numberToTest;
- this.firstDivisorValue = firstDivisor;
- this.isPrimeValue = isPrime;
- }
+ numberToTestValue = numberToTest;
+ firstDivisorValue = firstDivisor;
+ isPrimeValue = isPrime;
+ }
- public int NumberToTest
+ public int NumberToTest
+ {
+ get
{
- get
- {
- // Raise an exception if the operation failed or
- // was canceled.
- RaiseExceptionIfNecessary();
+ // Raise an exception if the operation failed or
+ // was canceled.
+ RaiseExceptionIfNecessary();
- // If the operation was successful, return the
- // property value.
- return numberToTestValue;
- }
+ // If the operation was successful, return the
+ // property value.
+ return numberToTestValue;
}
+ }
- public int FirstDivisor
+ public int FirstDivisor
+ {
+ get
{
- get
- {
- // Raise an exception if the operation failed or
- // was canceled.
- RaiseExceptionIfNecessary();
+ // Raise an exception if the operation failed or
+ // was canceled.
+ RaiseExceptionIfNecessary();
- // If the operation was successful, return the
- // property value.
- return firstDivisorValue;
- }
+ // If the operation was successful, return the
+ // property value.
+ return firstDivisorValue;
}
+ }
- public bool IsPrime
+ public bool IsPrime
+ {
+ get
{
- get
- {
- // Raise an exception if the operation failed or
- // was canceled.
- RaiseExceptionIfNecessary();
+ // Raise an exception if the operation failed or
+ // was canceled.
+ RaiseExceptionIfNecessary();
- // If the operation was successful, return the
- // property value.
- return isPrimeValue;
- }
+ // If the operation was successful, return the
+ // property value.
+ return isPrimeValue;
}
}
+}
- //
+//
- #endregion
+#endregion
- //
-}
-//
\ No newline at end of file
+//
+//
diff --git a/snippets/csharp/System.ComponentModel/AttributeCollection/.ctor/Project.csproj b/snippets/csharp/System.ComponentModel/AttributeCollection/.ctor/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/AttributeCollection/.ctor/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/AttributeCollection/.ctor/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/AttributeCollection/.ctor/source.cs b/snippets/csharp/System.ComponentModel/AttributeCollection/.ctor/source.cs
index 59d4e7f90a6..e0e852b6b2e 100644
--- a/snippets/csharp/System.ComponentModel/AttributeCollection/.ctor/source.cs
+++ b/snippets/csharp/System.ComponentModel/AttributeCollection/.ctor/source.cs
@@ -1,17 +1,13 @@
-using System;
+using System.ComponentModel;
using System.Windows.Forms;
-using System.ComponentModel;
-public class Form1: Form
+public class Form1 : Form
{
- protected Button button1;
- protected TextBox textBox1;
+ protected Button button1;
+ protected TextBox textBox1;
-protected void Method()
-{
-//
-AttributeCollection collection1;
-collection1 = TypeDescriptor.GetAttributes(button1);
-}
-//
+ protected void Method() =>
+ //
+ _ = TypeDescriptor.GetAttributes(button1);
+ //
}
diff --git a/snippets/csharp/System.ComponentModel/AttributeCollection/Count/Project.csproj b/snippets/csharp/System.ComponentModel/AttributeCollection/Count/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/AttributeCollection/Count/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/AttributeCollection/Count/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/AttributeCollection/Count/source.cs b/snippets/csharp/System.ComponentModel/AttributeCollection/Count/source.cs
index 91265b02dc8..f38a5b75f00 100644
--- a/snippets/csharp/System.ComponentModel/AttributeCollection/Count/source.cs
+++ b/snippets/csharp/System.ComponentModel/AttributeCollection/Count/source.cs
@@ -1,20 +1,20 @@
-using System;
+using System.ComponentModel;
using System.Windows.Forms;
-using System.ComponentModel;
-public class Form1: Form
+public class Form1 : Form
{
- protected Button button1;
- protected TextBox textBox1;
-//
-private void GetCount() {
- // Creates a new collection and assigns it the attributes for button1.
- AttributeCollection attributes;
- attributes = TypeDescriptor.GetAttributes(button1);
+ protected Button button1;
+ protected TextBox textBox1;
+ //
+ void GetCount()
+ {
+ // Creates a new collection and assigns it the attributes for button1.
+ AttributeCollection attributes;
+ attributes = TypeDescriptor.GetAttributes(button1);
- // Prints the number of items in the collection.
- textBox1.Text = attributes.Count.ToString();
- }
+ // Prints the number of items in the collection.
+ textBox1.Text = attributes.Count.ToString();
+ }
-//
+ //
}
diff --git a/snippets/csharp/System.ComponentModel/AttributeCollection/GetEnumerator/Project.csproj b/snippets/csharp/System.ComponentModel/AttributeCollection/GetEnumerator/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/AttributeCollection/GetEnumerator/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/AttributeCollection/GetEnumerator/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/AttributeCollection/GetEnumerator/source.cs b/snippets/csharp/System.ComponentModel/AttributeCollection/GetEnumerator/source.cs
index 11ebb10cd88..4692ba96141 100644
--- a/snippets/csharp/System.ComponentModel/AttributeCollection/GetEnumerator/source.cs
+++ b/snippets/csharp/System.ComponentModel/AttributeCollection/GetEnumerator/source.cs
@@ -1,28 +1,28 @@
-using System;
+using System.ComponentModel;
using System.Windows.Forms;
-using System.ComponentModel;
-public class Form1: Form
+public class Form1 : Form
{
- protected Button button1;
- protected TextBox textBox1;
-//
-private void MyEnumerator() {
- // Creates a new collection and assigns it the attributes for button1.
- AttributeCollection attributes;
- attributes = TypeDescriptor.GetAttributes(button1);
+ protected Button button1;
+ protected TextBox textBox1;
+ //
+ void MyEnumerator()
+ {
+ // Creates a new collection and assigns it the attributes for button1.
+ AttributeCollection attributes;
+ attributes = TypeDescriptor.GetAttributes(button1);
- // Creates an enumerator for the collection.
- System.Collections.IEnumerator ie = attributes.GetEnumerator();
+ // Creates an enumerator for the collection.
+ System.Collections.IEnumerator ie = attributes.GetEnumerator();
- // Prints the type of each attribute in the collection.
- Object myAttribute;
- while(ie.MoveNext()) {
- myAttribute = ie.Current;
- textBox1.Text += myAttribute.ToString();
- textBox1.Text += '\n';
+ // Prints the type of each attribute in the collection.
+ object myAttribute;
+ while (ie.MoveNext())
+ {
+ myAttribute = ie.Current;
+ textBox1.Text += myAttribute.ToString();
+ textBox1.Text += '\n';
+ }
}
- }
-
-//
+ //
}
diff --git a/snippets/csharp/System.ComponentModel/AttributeCollection/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/AttributeCollection/Overview/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/AttributeCollection/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/AttributeCollection/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/AttributeCollection/Overview/source.cs b/snippets/csharp/System.ComponentModel/AttributeCollection/Overview/source.cs
index ad1ef048114..92769f4887f 100644
--- a/snippets/csharp/System.ComponentModel/AttributeCollection/Overview/source.cs
+++ b/snippets/csharp/System.ComponentModel/AttributeCollection/Overview/source.cs
@@ -1,39 +1,37 @@
-using System;
+using System.ComponentModel;
using System.Windows.Forms;
-using System.ComponentModel;
-public class Form1:Form
+public class Form1 : Form
{
- protected Button button1;
- protected TextBox textBox1;
+ protected Button button1;
+ protected TextBox textBox1;
-//
-private void ContainsAttribute() {
- // Creates a new collection and assigns it the attributes for button1.
- AttributeCollection attributes;
- attributes = TypeDescriptor.GetAttributes(button1);
+ //
+ void ContainsAttribute()
+ {
+ // Creates a new collection and assigns it the attributes for button1.
+ AttributeCollection attributes;
+ attributes = TypeDescriptor.GetAttributes(button1);
- // Sets an Attribute to the specific attribute.
- BrowsableAttribute myAttribute = BrowsableAttribute.Yes;
+ // Sets an Attribute to the specific attribute.
+ BrowsableAttribute myAttribute = BrowsableAttribute.Yes;
- if (attributes.Contains(myAttribute))
- textBox1.Text = "button1 has a browsable attribute.";
- else
- textBox1.Text = "button1 does not have a browsable attribute.";
- }
-//
-//
-private void GetAttributeValue() {
- // Creates a new collection and assigns it the attributes for button1.
- AttributeCollection attributes;
- attributes = TypeDescriptor.GetAttributes(button1);
+ textBox1.Text = attributes.Contains(myAttribute) ? "button1 has a browsable attribute." : "button1 does not have a browsable attribute.";
+ }
+ //
+ //
+ void GetAttributeValue()
+ {
+ // Creates a new collection and assigns it the attributes for button1.
+ AttributeCollection attributes;
+ attributes = TypeDescriptor.GetAttributes(button1);
- // Gets the designer attribute from the collection.
- DesignerAttribute myDesigner;
- myDesigner = (DesignerAttribute)attributes[typeof(DesignerAttribute)];
+ // Gets the designer attribute from the collection.
+ DesignerAttribute myDesigner;
+ myDesigner = (DesignerAttribute)attributes[typeof(DesignerAttribute)];
- // Prints the value of the attribute in a text box.
- textBox1.Text = myDesigner.DesignerTypeName;
- }
-//
+ // Prints the value of the attribute in a text box.
+ textBox1.Text = myDesigner.DesignerTypeName;
+ }
+ //
}
diff --git a/snippets/csharp/System.ComponentModel/BackgroundWorker/IsBusy/Form1.cs b/snippets/csharp/System.ComponentModel/BackgroundWorker/IsBusy/Form1.cs
index c6a44a074e5..5fb90e228c0 100644
--- a/snippets/csharp/System.ComponentModel/BackgroundWorker/IsBusy/Form1.cs
+++ b/snippets/csharp/System.ComponentModel/BackgroundWorker/IsBusy/Form1.cs
@@ -1,18 +1,16 @@
//
using System;
-using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
-using System.Threading;
using System.Windows.Forms;
using System.Xml;
public class Form1 : Form
{
- private BackgroundWorker backgroundWorker1;
- private Button downloadButton;
- private ProgressBar progressBar1;
- private XmlDocument document = null;
+ readonly BackgroundWorker backgroundWorker1;
+ Button downloadButton;
+ ProgressBar progressBar1;
+ XmlDocument document;
public Form1()
{
@@ -20,33 +18,33 @@ public Form1()
// Instantiate BackgroundWorker and attach handlers to its
// DoWork and RunWorkerCompleted events.
- backgroundWorker1 = new System.ComponentModel.BackgroundWorker();
- backgroundWorker1.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker1_DoWork);
- backgroundWorker1.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker1_RunWorkerCompleted);
+ backgroundWorker1 = new BackgroundWorker();
+ backgroundWorker1.DoWork += backgroundWorker1_DoWork;
+ backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;
}
//
- private void downloadButton_Click(object sender, EventArgs e)
+ void downloadButton_Click(object sender, EventArgs e)
{
// Start the download operation in the background.
- this.backgroundWorker1.RunWorkerAsync();
+ backgroundWorker1.RunWorkerAsync();
// Disable the button for the duration of the download.
- this.downloadButton.Enabled = false;
+ downloadButton.Enabled = false;
- // Once you have started the background thread you
- // can exit the handler and the application will
+ // Once you have started the background thread you
+ // can exit the handler and the application will
// wait until the RunWorkerCompleted event is raised.
// Or if you want to do something else in the main thread,
- // such as update a progress bar, you can do so in a loop
+ // such as update a progress bar, you can do so in a loop
// while checking IsBusy to see if the background task is
// still running.
- while (this.backgroundWorker1.IsBusy)
+ while (backgroundWorker1.IsBusy)
{
progressBar1.Increment(1);
- // Keep UI messages moving, so the form remains
+ // Keep UI messages moving, so the form remains
// responsive during the asynchronous operation.
Application.DoEvents();
}
@@ -54,7 +52,7 @@ private void downloadButton_Click(object sender, EventArgs e)
//
//
- private void backgroundWorker1_DoWork(
+ void backgroundWorker1_DoWork(
object sender,
DoWorkEventArgs e)
{
@@ -65,12 +63,12 @@ private void backgroundWorker1_DoWork(
//Thread.Sleep(5000);
// Replace this file name with a valid file name.
- document.Load(@"http://www.tailspintoys.com/sample.xml");
+ document.Load("http://www.tailspintoys.com/sample.xml");
}
//
//
- private void backgroundWorker1_RunWorkerCompleted(
+ void backgroundWorker1_RunWorkerCompleted(
object sender,
RunWorkerCompletedEventArgs e)
{
@@ -78,9 +76,7 @@ private void backgroundWorker1_RunWorkerCompleted(
progressBar1.Value = 100;
if (e.Error == null)
- {
MessageBox.Show(document.InnerXml, "Download Complete");
- }
else
{
MessageBox.Show(
@@ -91,7 +87,7 @@ private void backgroundWorker1_RunWorkerCompleted(
}
// Enable the download button and reset the progress bar.
- this.downloadButton.Enabled = true;
+ downloadButton.Enabled = true;
progressBar1.Value = 0;
}
//
@@ -101,7 +97,7 @@ private void backgroundWorker1_RunWorkerCompleted(
///
/// Required designer variable.
///
- private System.ComponentModel.IContainer components = null;
+ readonly IContainer _components;
///
/// Clean up any resources being used.
@@ -109,9 +105,9 @@ private void backgroundWorker1_RunWorkerCompleted(
/// true if managed resources should be disposed; otherwise, false.
protected override void Dispose(bool disposing)
{
- if (disposing && (components != null))
+ if (disposing && (_components != null))
{
- components.Dispose();
+ _components.Dispose();
}
base.Dispose(disposing);
}
@@ -119,39 +115,39 @@ protected override void Dispose(bool disposing)
///
/// Required method for Designer support
///
- private void InitializeComponent()
+ void InitializeComponent()
{
- this.downloadButton = new System.Windows.Forms.Button();
- this.progressBar1 = new System.Windows.Forms.ProgressBar();
- this.SuspendLayout();
- //
+ downloadButton = new Button();
+ progressBar1 = new ProgressBar();
+ SuspendLayout();
+ //
// downloadButton
- //
- this.downloadButton.Location = new System.Drawing.Point(12, 12);
- this.downloadButton.Name = "downloadButton";
- this.downloadButton.Size = new System.Drawing.Size(100, 23);
- this.downloadButton.TabIndex = 0;
- this.downloadButton.Text = "Download file";
- this.downloadButton.UseVisualStyleBackColor = true;
- this.downloadButton.Click += new System.EventHandler(this.downloadButton_Click);
- //
+ //
+ downloadButton.Location = new Point(12, 12);
+ downloadButton.Name = "downloadButton";
+ downloadButton.Size = new Size(100, 23);
+ downloadButton.TabIndex = 0;
+ downloadButton.Text = "Download file";
+ downloadButton.UseVisualStyleBackColor = true;
+ downloadButton.Click += downloadButton_Click;
+ //
// progressBar1
- //
- this.progressBar1.Location = new System.Drawing.Point(12, 50);
- this.progressBar1.Name = "progressBar1";
- this.progressBar1.Size = new System.Drawing.Size(100, 26);
- this.progressBar1.TabIndex = 1;
- //
+ //
+ progressBar1.Location = new Point(12, 50);
+ progressBar1.Name = "progressBar1";
+ progressBar1.Size = new Size(100, 26);
+ progressBar1.TabIndex = 1;
+ //
// Form1
- //
- this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
- this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.ClientSize = new System.Drawing.Size(133, 104);
- this.Controls.Add(this.progressBar1);
- this.Controls.Add(this.downloadButton);
- this.Name = "Form1";
- this.Text = "Form1";
- this.ResumeLayout(false);
+ //
+ AutoScaleDimensions = new SizeF(6F, 13F);
+ AutoScaleMode = AutoScaleMode.Font;
+ ClientSize = new Size(133, 104);
+ Controls.Add(progressBar1);
+ Controls.Add(downloadButton);
+ Name = "Form1";
+ Text = "Form1";
+ ResumeLayout(false);
}
#endregion
diff --git a/snippets/csharp/System.ComponentModel/BackgroundWorker/IsBusy/Project.csproj b/snippets/csharp/System.ComponentModel/BackgroundWorker/IsBusy/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/BackgroundWorker/IsBusy/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/BackgroundWorker/IsBusy/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/BackgroundWorker/Overview/backgroundworkersimple.csproj b/snippets/csharp/System.ComponentModel/BackgroundWorker/Overview/backgroundworkersimple.csproj
index e800ef582fe..c731b80e440 100644
--- a/snippets/csharp/System.ComponentModel/BackgroundWorker/Overview/backgroundworkersimple.csproj
+++ b/snippets/csharp/System.ComponentModel/BackgroundWorker/Overview/backgroundworkersimple.csproj
@@ -2,7 +2,7 @@
Exe
- net6.0-windows
+ net8.0-windows
true
BackgroundWorkerSimple.Program
diff --git a/snippets/csharp/System.ComponentModel/BackgroundWorker/Overview/fibonacciform.cs b/snippets/csharp/System.ComponentModel/BackgroundWorker/Overview/fibonacciform.cs
index aa02e5cf261..c370252e559 100644
--- a/snippets/csharp/System.ComponentModel/BackgroundWorker/Overview/fibonacciform.cs
+++ b/snippets/csharp/System.ComponentModel/BackgroundWorker/Overview/fibonacciform.cs
@@ -1,318 +1,304 @@
//
//
using System;
-using System.Collections;
using System.ComponentModel;
using System.Drawing;
-using System.Threading;
using System.Windows.Forms;
//
-namespace BackgroundWorkerExample
-{
- public class FibonacciForm : System.Windows.Forms.Form
- {
- //
- private int numberToCompute = 0;
- private int highestPercentageReached = 0;
- //
-
- private System.Windows.Forms.NumericUpDown numericUpDown1;
- private System.Windows.Forms.Button startAsyncButton;
- private System.Windows.Forms.Button cancelAsyncButton;
- private System.Windows.Forms.ProgressBar progressBar1;
- private System.Windows.Forms.Label resultLabel;
- private System.ComponentModel.BackgroundWorker backgroundWorker1;
-
- public FibonacciForm()
- {
- InitializeComponent();
-
- InitializeBackgroundWorker();
- }
+namespace BackgroundWorkerExample;
- // Set up the BackgroundWorker object by
- // attaching event handlers.
- private void InitializeBackgroundWorker()
- {
- backgroundWorker1.DoWork +=
- new DoWorkEventHandler(backgroundWorker1_DoWork);
- backgroundWorker1.RunWorkerCompleted +=
- new RunWorkerCompletedEventHandler(
- backgroundWorker1_RunWorkerCompleted);
- backgroundWorker1.ProgressChanged +=
- new ProgressChangedEventHandler(
- backgroundWorker1_ProgressChanged);
- }
-
- //
- private void startAsyncButton_Click(System.Object sender,
- System.EventArgs e)
- {
- // Reset the text in the result label.
- resultLabel.Text = String.Empty;
+public class FibonacciForm : Form
+{
+ //
+ int numberToCompute;
+ int highestPercentageReached;
+ //
- // Disable the UpDown control until
- // the asynchronous operation is done.
- this.numericUpDown1.Enabled = false;
+ NumericUpDown numericUpDown1;
+ Button startAsyncButton;
+ Button cancelAsyncButton;
+ ProgressBar progressBar1;
+ Label resultLabel;
+ BackgroundWorker backgroundWorker1;
- // Disable the Start button until
- // the asynchronous operation is done.
- this.startAsyncButton.Enabled = false;
+ public FibonacciForm()
+ {
+ InitializeComponent();
- // Enable the Cancel button while
- // the asynchronous operation runs.
- this.cancelAsyncButton.Enabled = true;
+ InitializeBackgroundWorker();
+ }
- // Get the value from the UpDown control.
- numberToCompute = (int)numericUpDown1.Value;
+ // Set up the BackgroundWorker object by
+ // attaching event handlers.
+ void InitializeBackgroundWorker()
+ {
+ backgroundWorker1.DoWork +=
+ backgroundWorker1_DoWork;
+ backgroundWorker1.RunWorkerCompleted +=
- // Reset the variable for percentage tracking.
- highestPercentageReached = 0;
+ backgroundWorker1_RunWorkerCompleted;
+ backgroundWorker1.ProgressChanged +=
- //
- // Start the asynchronous operation.
- backgroundWorker1.RunWorkerAsync(numberToCompute);
- //
- }
- //
+ backgroundWorker1_ProgressChanged;
+ }
- //
- private void cancelAsyncButton_Click(System.Object sender,
- System.EventArgs e)
- {
- // Cancel the asynchronous operation.
- this.backgroundWorker1.CancelAsync();
+ //
+ void startAsyncButton_Click(object sender,
+ EventArgs e)
+ {
+ // Reset the text in the result label.
+ resultLabel.Text = string.Empty;
- // Disable the Cancel button.
- cancelAsyncButton.Enabled = false;
+ // Disable the UpDown control until
+ // the asynchronous operation is done.
+ numericUpDown1.Enabled = false;
+
+ // Disable the Start button until
+ // the asynchronous operation is done.
+ startAsyncButton.Enabled = false;
+
+ // Enable the Cancel button while
+ // the asynchronous operation runs.
+ cancelAsyncButton.Enabled = true;
+
+ // Get the value from the UpDown control.
+ numberToCompute = (int)numericUpDown1.Value;
+
+ // Reset the variable for percentage tracking.
+ highestPercentageReached = 0;
+
+ //
+ // Start the asynchronous operation.
+ backgroundWorker1.RunWorkerAsync(numberToCompute);
+ //
+ }
+ //
+
+ //
+ void cancelAsyncButton_Click(object sender,
+ EventArgs e)
+ {
+ // Cancel the asynchronous operation.
+ backgroundWorker1.CancelAsync();
+
+ // Disable the Cancel button.
+ cancelAsyncButton.Enabled = false;
+ }
+ //
+
+ //
+ // This event handler is where the actual,
+ // potentially time-consuming work is done.
+ void backgroundWorker1_DoWork(object sender,
+ DoWorkEventArgs e)
+ {
+ // Get the BackgroundWorker that raised this event.
+ BackgroundWorker worker = sender as BackgroundWorker;
+
+ // Assign the result of the computation
+ // to the Result property of the DoWorkEventArgs
+ // object. This is will be available to the
+ // RunWorkerCompleted eventhandler.
+ e.Result = ComputeFibonacci((int)e.Argument, worker, e);
+ }
+ //
+
+ //
+ // This event handler deals with the results of the
+ // background operation.
+ void backgroundWorker1_RunWorkerCompleted(
+ object sender, RunWorkerCompletedEventArgs e)
+ {
+ // First, handle the case where an exception was thrown.
+ if (e.Error != null)
+ {
+ _ = MessageBox.Show(e.Error.Message);
}
- //
-
- //
- // This event handler is where the actual,
- // potentially time-consuming work is done.
- private void backgroundWorker1_DoWork(object sender,
- DoWorkEventArgs e)
- {
- // Get the BackgroundWorker that raised this event.
- BackgroundWorker worker = sender as BackgroundWorker;
-
- // Assign the result of the computation
- // to the Result property of the DoWorkEventArgs
- // object. This is will be available to the
- // RunWorkerCompleted eventhandler.
- e.Result = ComputeFibonacci((int)e.Argument, worker, e);
+ else if (e.Cancelled)
+ {
+ // Next, handle the case where the user canceled
+ // the operation.
+ // Note that due to a race condition in
+ // the DoWork event handler, the Cancelled
+ // flag may not have been set, even though
+ // CancelAsync was called.
+ resultLabel.Text = "Canceled";
}
- //
-
- //
- // This event handler deals with the results of the
- // background operation.
- private void backgroundWorker1_RunWorkerCompleted(
- object sender, RunWorkerCompletedEventArgs e)
+ else
{
- // First, handle the case where an exception was thrown.
- if (e.Error != null)
- {
- MessageBox.Show(e.Error.Message);
- }
- else if (e.Cancelled)
- {
- // Next, handle the case where the user canceled
- // the operation.
- // Note that due to a race condition in
- // the DoWork event handler, the Cancelled
- // flag may not have been set, even though
- // CancelAsync was called.
- resultLabel.Text = "Canceled";
- }
- else
- {
- // Finally, handle the case where the operation
- // succeeded.
- resultLabel.Text = e.Result.ToString();
- }
+ // Finally, handle the case where the operation
+ // succeeded.
+ resultLabel.Text = e.Result.ToString();
+ }
- // Enable the UpDown control.
- this.numericUpDown1.Enabled = true;
+ // Enable the UpDown control.
+ numericUpDown1.Enabled = true;
- // Enable the Start button.
- startAsyncButton.Enabled = true;
+ // Enable the Start button.
+ startAsyncButton.Enabled = true;
- // Disable the Cancel button.
- cancelAsyncButton.Enabled = false;
- }
- //
+ // Disable the Cancel button.
+ cancelAsyncButton.Enabled = false;
+ }
+ //
+
+ //
+ // This event handler updates the progress bar.
+ void backgroundWorker1_ProgressChanged(object sender,
+ ProgressChangedEventArgs e) => progressBar1.Value = e.ProgressPercentage;
+ //
- //
- // This event handler updates the progress bar.
- private void backgroundWorker1_ProgressChanged(object sender,
- ProgressChangedEventArgs e)
+ //
+ // This is the method that does the actual work. For this
+ // example, it computes a Fibonacci number and
+ // reports progress as it does its work.
+ long ComputeFibonacci(int n, BackgroundWorker worker, DoWorkEventArgs e)
+ {
+ // The parameter n must be >= 0 and <= 91.
+ // Fib(n), with n > 91, overflows a long.
+ if (n is < 0 or > 91)
{
- this.progressBar1.Value = e.ProgressPercentage;
+ throw new ArgumentException(
+ "value must be >= 0 and <= 91", nameof(n));
}
- //
- //
- // This is the method that does the actual work. For this
- // example, it computes a Fibonacci number and
- // reports progress as it does its work.
- long ComputeFibonacci(int n, BackgroundWorker worker, DoWorkEventArgs e)
+ long result = 0;
+
+ //
+ // Abort the operation if the user has canceled.
+ // Note that a call to CancelAsync may have set
+ // CancellationPending to true just after the
+ // last invocation of this method exits, so this
+ // code will not have the opportunity to set the
+ // DoWorkEventArgs.Cancel flag to true. This means
+ // that RunWorkerCompletedEventArgs.Cancelled will
+ // not be set to true in your RunWorkerCompleted
+ // event handler. This is a race condition.
+
+ //
+ if (worker.CancellationPending)
+ {
+ e.Cancel = true;
+ }
+ //
+ else
{
- // The parameter n must be >= 0 and <= 91.
- // Fib(n), with n > 91, overflows a long.
- if ((n < 0) || (n > 91))
+ result = n < 2
+ ? 1
+ : ComputeFibonacci(n - 1, worker, e) +
+ ComputeFibonacci(n - 2, worker, e);
+
+ //
+ // Report progress as a percentage of the total task.
+ int percentComplete =
+ (int)(n / (float)numberToCompute * 100);
+ if (percentComplete > highestPercentageReached)
{
- throw new ArgumentException(
- "value must be >= 0 and <= 91", "n");
+ highestPercentageReached = percentComplete;
+ worker.ReportProgress(percentComplete);
}
+ //
+ }
+ //
- long result = 0;
-
- //
- // Abort the operation if the user has canceled.
- // Note that a call to CancelAsync may have set
- // CancellationPending to true just after the
- // last invocation of this method exits, so this
- // code will not have the opportunity to set the
- // DoWorkEventArgs.Cancel flag to true. This means
- // that RunWorkerCompletedEventArgs.Cancelled will
- // not be set to true in your RunWorkerCompleted
- // event handler. This is a race condition.
-
- //
- if (worker.CancellationPending)
- {
- e.Cancel = true;
- }
- //
- else
- {
- if (n < 2)
- {
- result = 1;
- }
- else
- {
- result = ComputeFibonacci(n - 1, worker, e) +
- ComputeFibonacci(n - 2, worker, e);
- }
-
- //
- // Report progress as a percentage of the total task.
- int percentComplete =
- (int)((float)n / (float)numberToCompute * 100);
- if (percentComplete > highestPercentageReached)
- {
- highestPercentageReached = percentComplete;
- worker.ReportProgress(percentComplete);
- }
- //
- }
- //
+ return result;
+ }
+ //
- return result;
- }
- //
+ #region Windows Form Designer generated code
- #region Windows Form Designer generated code
-
- private void InitializeComponent()
- {
- this.numericUpDown1 = new System.Windows.Forms.NumericUpDown();
- this.startAsyncButton = new System.Windows.Forms.Button();
- this.cancelAsyncButton = new System.Windows.Forms.Button();
- this.resultLabel = new System.Windows.Forms.Label();
- this.progressBar1 = new System.Windows.Forms.ProgressBar();
- this.backgroundWorker1 = new System.ComponentModel.BackgroundWorker();
- ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).BeginInit();
- this.SuspendLayout();
- //
- // numericUpDown1
- //
- this.numericUpDown1.Location = new System.Drawing.Point(16, 16);
- this.numericUpDown1.Maximum = new System.Decimal(new int[] {
+ void InitializeComponent()
+ {
+ numericUpDown1 = new NumericUpDown();
+ startAsyncButton = new Button();
+ cancelAsyncButton = new Button();
+ resultLabel = new Label();
+ progressBar1 = new ProgressBar();
+ backgroundWorker1 = new BackgroundWorker();
+ ((ISupportInitialize)numericUpDown1).BeginInit();
+ SuspendLayout();
+ //
+ // numericUpDown1
+ //
+ numericUpDown1.Location = new Point(16, 16);
+ numericUpDown1.Maximum = new decimal(new int[] {
91,
0,
0,
0});
- this.numericUpDown1.Minimum = new System.Decimal(new int[] {
+ numericUpDown1.Minimum = new decimal(new int[] {
1,
0,
0,
0});
- this.numericUpDown1.Name = "numericUpDown1";
- this.numericUpDown1.Size = new System.Drawing.Size(80, 20);
- this.numericUpDown1.TabIndex = 0;
- this.numericUpDown1.Value = new System.Decimal(new int[] {
+ numericUpDown1.Name = "numericUpDown1";
+ numericUpDown1.Size = new Size(80, 20);
+ numericUpDown1.TabIndex = 0;
+ numericUpDown1.Value = new decimal(new int[] {
1,
0,
0,
0});
- //
- // startAsyncButton
- //
- this.startAsyncButton.Location = new System.Drawing.Point(16, 72);
- this.startAsyncButton.Name = "startAsyncButton";
- this.startAsyncButton.Size = new System.Drawing.Size(120, 23);
- this.startAsyncButton.TabIndex = 1;
- this.startAsyncButton.Text = "Start Async";
- this.startAsyncButton.Click += new System.EventHandler(this.startAsyncButton_Click);
- //
- // cancelAsyncButton
- //
- this.cancelAsyncButton.Enabled = false;
- this.cancelAsyncButton.Location = new System.Drawing.Point(153, 72);
- this.cancelAsyncButton.Name = "cancelAsyncButton";
- this.cancelAsyncButton.Size = new System.Drawing.Size(119, 23);
- this.cancelAsyncButton.TabIndex = 2;
- this.cancelAsyncButton.Text = "Cancel Async";
- this.cancelAsyncButton.Click += new System.EventHandler(this.cancelAsyncButton_Click);
- //
- // resultLabel
- //
- this.resultLabel.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
- this.resultLabel.Location = new System.Drawing.Point(112, 16);
- this.resultLabel.Name = "resultLabel";
- this.resultLabel.Size = new System.Drawing.Size(160, 23);
- this.resultLabel.TabIndex = 3;
- this.resultLabel.Text = "(no result)";
- this.resultLabel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
- //
- // progressBar1
- //
- this.progressBar1.Location = new System.Drawing.Point(18, 48);
- this.progressBar1.Name = "progressBar1";
- this.progressBar1.Size = new System.Drawing.Size(256, 8);
- this.progressBar1.Step = 2;
- this.progressBar1.TabIndex = 4;
- //
- // backgroundWorker1
- //
- this.backgroundWorker1.WorkerReportsProgress = true;
- this.backgroundWorker1.WorkerSupportsCancellation = true;
- //
- // FibonacciForm
- //
- this.ClientSize = new System.Drawing.Size(292, 118);
- this.Controls.Add(this.progressBar1);
- this.Controls.Add(this.resultLabel);
- this.Controls.Add(this.cancelAsyncButton);
- this.Controls.Add(this.startAsyncButton);
- this.Controls.Add(this.numericUpDown1);
- this.Name = "FibonacciForm";
- this.Text = "Fibonacci Calculator";
- ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).EndInit();
- this.ResumeLayout(false);
- }
- #endregion
-
- [STAThread]
- static void Main()
- {
- Application.Run(new FibonacciForm());
- }
+ //
+ // startAsyncButton
+ //
+ startAsyncButton.Location = new Point(16, 72);
+ startAsyncButton.Name = "startAsyncButton";
+ startAsyncButton.Size = new Size(120, 23);
+ startAsyncButton.TabIndex = 1;
+ startAsyncButton.Text = "Start Async";
+ startAsyncButton.Click += startAsyncButton_Click;
+ //
+ // cancelAsyncButton
+ //
+ cancelAsyncButton.Enabled = false;
+ cancelAsyncButton.Location = new Point(153, 72);
+ cancelAsyncButton.Name = "cancelAsyncButton";
+ cancelAsyncButton.Size = new Size(119, 23);
+ cancelAsyncButton.TabIndex = 2;
+ cancelAsyncButton.Text = "Cancel Async";
+ cancelAsyncButton.Click += cancelAsyncButton_Click;
+ //
+ // resultLabel
+ //
+ resultLabel.BorderStyle = BorderStyle.Fixed3D;
+ resultLabel.Location = new Point(112, 16);
+ resultLabel.Name = "resultLabel";
+ resultLabel.Size = new Size(160, 23);
+ resultLabel.TabIndex = 3;
+ resultLabel.Text = "(no result)";
+ resultLabel.TextAlign = ContentAlignment.MiddleCenter;
+ //
+ // progressBar1
+ //
+ progressBar1.Location = new Point(18, 48);
+ progressBar1.Name = "progressBar1";
+ progressBar1.Size = new Size(256, 8);
+ progressBar1.Step = 2;
+ progressBar1.TabIndex = 4;
+ //
+ // backgroundWorker1
+ //
+ backgroundWorker1.WorkerReportsProgress = true;
+ backgroundWorker1.WorkerSupportsCancellation = true;
+ //
+ // FibonacciForm
+ //
+ ClientSize = new Size(1794, 927);
+ Controls.Add(progressBar1);
+ Controls.Add(resultLabel);
+ Controls.Add(cancelAsyncButton);
+ Controls.Add(startAsyncButton);
+ Controls.Add(numericUpDown1);
+ Name = "FibonacciForm";
+ Text = "Fibonacci Calculator";
+ ((ISupportInitialize)numericUpDown1).EndInit();
+ ResumeLayout(false);
}
+ #endregion
+
+ [STAThread]
+ static void Main() => Application.Run(new FibonacciForm());
}
//
diff --git a/snippets/csharp/System.ComponentModel/BackgroundWorker/Overview/form1.cs b/snippets/csharp/System.ComponentModel/BackgroundWorker/Overview/form1.cs
index 45a6dedd591..fed9beedf96 100644
--- a/snippets/csharp/System.ComponentModel/BackgroundWorker/Overview/form1.cs
+++ b/snippets/csharp/System.ComponentModel/BackgroundWorker/Overview/form1.cs
@@ -3,78 +3,64 @@
using System.ComponentModel;
using System.Windows.Forms;
-namespace BackgroundWorkerSimple
+namespace BackgroundWorkerSimple;
+
+public partial class Form1 : Form
{
- public partial class Form1 : Form
+ public Form1()
{
- public Form1()
- {
- InitializeComponent();
- backgroundWorker1.WorkerReportsProgress = true;
- backgroundWorker1.WorkerSupportsCancellation = true;
- }
-
- private void startAsyncButton_Click(object sender, EventArgs e)
- {
- if (!backgroundWorker1.IsBusy)
- {
- // Start the asynchronous operation.
- backgroundWorker1.RunWorkerAsync();
- }
- }
+ InitializeComponent();
+ backgroundWorker1.WorkerReportsProgress = true;
+ backgroundWorker1.WorkerSupportsCancellation = true;
+ }
- private void cancelAsyncButton_Click(object sender, EventArgs e)
+ void startAsyncButton_Click(object sender, EventArgs e)
+ {
+ if (!backgroundWorker1.IsBusy)
{
- if (backgroundWorker1.WorkerSupportsCancellation)
- {
- // Cancel the asynchronous operation.
- backgroundWorker1.CancelAsync();
- }
+ // Start the asynchronous operation.
+ backgroundWorker1.RunWorkerAsync();
}
+ }
- // This event handler is where the time-consuming work is done.
- private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
+ void cancelAsyncButton_Click(object sender, EventArgs e)
+ {
+ if (backgroundWorker1.WorkerSupportsCancellation)
{
- BackgroundWorker worker = sender as BackgroundWorker;
-
- for (int i = 1; i <= 10; i++)
- {
- if (worker.CancellationPending)
- {
- e.Cancel = true;
- break;
- }
- else
- {
- // Perform a time consuming operation and report progress.
- System.Threading.Thread.Sleep(500);
- worker.ReportProgress(i * 10);
- }
- }
+ // Cancel the asynchronous operation.
+ backgroundWorker1.CancelAsync();
}
+ }
- // This event handler updates the progress.
- private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
- {
- resultLabel.Text = (e.ProgressPercentage.ToString() + "%");
- }
+ // This event handler is where the time-consuming work is done.
+ void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
+ {
+ BackgroundWorker worker = sender as BackgroundWorker;
- // This event handler deals with the results of the background operation.
- private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
+ for (int i = 1; i <= 10; i++)
{
- if (e.Cancelled)
- {
- resultLabel.Text = "Canceled!";
- }
- else if (e.Error != null)
+ if (worker.CancellationPending)
{
- resultLabel.Text = "Error: " + e.Error.Message;
+ e.Cancel = true;
+ break;
}
else
{
- resultLabel.Text = "Done!";
+ // Perform a time consuming operation and report progress.
+ System.Threading.Thread.Sleep(500);
+ worker.ReportProgress(i * 10);
}
}
}
+
+ // This event handler updates the progress.
+ void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) =>
+ resultLabel.Text = e.ProgressPercentage.ToString() + "%";
+
+ // This event handler deals with the results of the background operation.
+ void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) =>
+ resultLabel.Text = e.Cancelled ?
+ "Canceled!"
+ : e.Error != null ? "Error: " + e.Error.Message : "Done!";
}
//
diff --git a/snippets/csharp/System.ComponentModel/BackgroundWorker/Overview/program.cs b/snippets/csharp/System.ComponentModel/BackgroundWorker/Overview/program.cs
index 91fc8e37252..f7de10a8556 100644
--- a/snippets/csharp/System.ComponentModel/BackgroundWorker/Overview/program.cs
+++ b/snippets/csharp/System.ComponentModel/BackgroundWorker/Overview/program.cs
@@ -1,19 +1,18 @@
using System;
using System.Windows.Forms;
-namespace BackgroundWorkerSimple
+namespace BackgroundWorkerSimple;
+
+static class Program
{
- static class Program
+ ///
+ /// The main entry point for the application.
+ ///
+ [STAThread]
+ static void Main()
{
- ///
- /// The main entry point for the application.
- ///
- [STAThread]
- static void Main()
- {
- Application.EnableVisualStyles();
- Application.SetCompatibleTextRenderingDefault(false);
- Application.Run(new Form1());
- }
+ Application.EnableVisualStyles();
+ Application.SetCompatibleTextRenderingDefault(false);
+ Application.Run(new Form1());
}
}
diff --git a/snippets/csharp/System.ComponentModel/BackgroundWorker/ReportProgress/Project.csproj b/snippets/csharp/System.ComponentModel/BackgroundWorker/ReportProgress/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/BackgroundWorker/ReportProgress/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/BackgroundWorker/ReportProgress/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/BackgroundWorker/ReportProgress/form1.cs b/snippets/csharp/System.ComponentModel/BackgroundWorker/ReportProgress/form1.cs
index 1cdafec890a..8de1f7b4e6a 100644
--- a/snippets/csharp/System.ComponentModel/BackgroundWorker/ReportProgress/form1.cs
+++ b/snippets/csharp/System.ComponentModel/BackgroundWorker/ReportProgress/form1.cs
@@ -1,144 +1,159 @@
//
using System;
-using System.Collections.Generic;
-using System.Windows.Forms;
using System.ComponentModel;
+using System.Windows.Forms;
class FibonacciNumber : Form
{
- [STAThread]
- static void Main()
- {
- Application.EnableVisualStyles();
- Application.Run(new FibonacciNumber());
- }
+ [STAThread]
+ static void Main()
+ {
+ Application.EnableVisualStyles();
+ Application.Run(new FibonacciNumber());
+ }
+
+ readonly StatusStrip progressStatusStrip;
+ readonly ToolStripProgressBar toolStripProgressBar;
+ readonly NumericUpDown requestedCountControl;
+ readonly Button goButton;
+ readonly TextBox outputTextBox;
+ readonly BackgroundWorker backgroundWorker;
+ readonly ToolStripStatusLabel toolStripStatusLabel;
+ int requestedCount;
+
+ public FibonacciNumber()
+ {
+ Text = "Fibonacci";
- private StatusStrip progressStatusStrip;
- private ToolStripProgressBar toolStripProgressBar;
- private NumericUpDown requestedCountControl;
- private Button goButton;
- private TextBox outputTextBox;
- private BackgroundWorker backgroundWorker;
- private ToolStripStatusLabel toolStripStatusLabel;
- private int requestedCount;
+ // Prepare the StatusStrip.
+ progressStatusStrip = new StatusStrip();
+ toolStripProgressBar = new ToolStripProgressBar
+ {
+ Enabled = false
+ };
+ toolStripStatusLabel = new ToolStripStatusLabel();
+ _ = progressStatusStrip.Items.Add(toolStripProgressBar);
+ _ = progressStatusStrip.Items.Add(toolStripStatusLabel);
- public FibonacciNumber()
- {
- Text = "Fibonacci";
-
- // Prepare the StatusStrip.
- progressStatusStrip = new StatusStrip();
- toolStripProgressBar = new ToolStripProgressBar();
- toolStripProgressBar.Enabled = false;
- toolStripStatusLabel = new ToolStripStatusLabel();
- progressStatusStrip.Items.Add(toolStripProgressBar);
- progressStatusStrip.Items.Add(toolStripStatusLabel);
+ FlowLayoutPanel flp = new()
+ {
+ Dock = DockStyle.Top
+ };
- FlowLayoutPanel flp = new FlowLayoutPanel();
- flp.Dock = DockStyle.Top;
+ Label beforeLabel = new()
+ {
+ Text = "Calculate the first ",
+ AutoSize = true
+ };
+ flp.Controls.Add(beforeLabel);
+ //
+ requestedCountControl = new NumericUpDown
+ {
+ Maximum = 1000,
+ Minimum = 1,
+ Value = 100
+ };
+ flp.Controls.Add(requestedCountControl);
+ //
+ Label afterLabel = new()
+ {
+ Text = "Numbers in the Fibonacci sequence.",
+ AutoSize = true
+ };
+ flp.Controls.Add(afterLabel);
- Label beforeLabel = new Label();
- beforeLabel.Text = "Calculate the first ";
- beforeLabel.AutoSize = true;
- flp.Controls.Add(beforeLabel);
- //
- requestedCountControl = new NumericUpDown();
- requestedCountControl.Maximum = 1000;
- requestedCountControl.Minimum = 1;
- requestedCountControl.Value = 100;
- flp.Controls.Add(requestedCountControl);
- //
- Label afterLabel = new Label();
- afterLabel.Text = "Numbers in the Fibonacci sequence.";
- afterLabel.AutoSize = true;
- flp.Controls.Add(afterLabel);
-
- goButton = new Button();
- goButton.Text = "&Go";
- goButton.Click += new System.EventHandler(button1_Click);
- flp.Controls.Add(goButton);
+ goButton = new Button
+ {
+ Text = "&Go"
+ };
+ goButton.Click += button1_Click;
+ flp.Controls.Add(goButton);
- outputTextBox = new TextBox();
- outputTextBox.Multiline = true;
- outputTextBox.ReadOnly = true;
- outputTextBox.ScrollBars = ScrollBars.Vertical;
- outputTextBox.Dock = DockStyle.Fill;
+ outputTextBox = new TextBox
+ {
+ Multiline = true,
+ ReadOnly = true,
+ ScrollBars = ScrollBars.Vertical,
+ Dock = DockStyle.Fill
+ };
- Controls.Add(outputTextBox);
- Controls.Add(progressStatusStrip);
- Controls.Add(flp);
+ Controls.Add(outputTextBox);
+ Controls.Add(progressStatusStrip);
+ Controls.Add(flp);
- backgroundWorker = new BackgroundWorker();
- backgroundWorker.WorkerReportsProgress = true;
- backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
- backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
- backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
- }
+ backgroundWorker = new BackgroundWorker
+ {
+ WorkerReportsProgress = true
+ };
+ backgroundWorker.DoWork += backgroundWorker1_DoWork;
+ backgroundWorker.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;
+ backgroundWorker.ProgressChanged += backgroundWorker1_ProgressChanged;
+ }
//
- private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
- {
- // This method will run on a thread other than the UI thread.
- // Be sure not to manipulate any Windows Forms controls created
- // on the UI thread from this method.
- backgroundWorker.ReportProgress(0, "Working...");
- Decimal lastlast = 0;
- Decimal last = 1;
- Decimal current;
- if (requestedCount >= 1)
- { AppendNumber(0); }
- if (requestedCount >= 2)
- { AppendNumber(1); }
- for (int i = 2; i < requestedCount; ++i)
- {
- // Calculate the number.
- checked { current = lastlast + last; }
- // Introduce some delay to simulate a more complicated calculation.
- System.Threading.Thread.Sleep(100);
- AppendNumber(current);
- backgroundWorker.ReportProgress((100 * i) / requestedCount, "Working...");
- // Get ready for the next iteration.
- lastlast = last;
- last = current;
- }
+ void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
+ {
+ // This method will run on a thread other than the UI thread.
+ // Be sure not to manipulate any Windows Forms controls created
+ // on the UI thread from this method.
+ backgroundWorker.ReportProgress(0, "Working...");
+ decimal lastlast = 0;
+ decimal last = 1;
+ decimal current;
+ if (requestedCount >= 1)
+ { AppendNumber(0); }
+ if (requestedCount >= 2)
+ { AppendNumber(1); }
+ for (int i = 2; i < requestedCount; ++i)
+ {
+ // Calculate the number.
+ checked { current = lastlast + last; }
+ // Introduce some delay to simulate a more complicated calculation.
+ System.Threading.Thread.Sleep(100);
+ AppendNumber(current);
+ backgroundWorker.ReportProgress(100 * i / requestedCount, "Working...");
+ // Get ready for the next iteration.
+ lastlast = last;
+ last = current;
+ }
- backgroundWorker.ReportProgress(100, "Complete!");
- }
+ backgroundWorker.ReportProgress(100, "Complete!");
+ }
//
- private delegate void AppendNumberDelegate(Decimal number);
- //
- private void AppendNumber(Decimal number)
- {
- if (outputTextBox.InvokeRequired)
- { outputTextBox.Invoke(new AppendNumberDelegate(AppendNumber), number); }
- else
- { outputTextBox.AppendText(number.ToString("N0") + Environment.NewLine); }
- }
- //
- private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
- {
- toolStripProgressBar.Value = e.ProgressPercentage;
- toolStripStatusLabel.Text = e.UserState as String;
- }
+ delegate void AppendNumberDelegate(decimal number);
+ //
+ void AppendNumber(decimal number)
+ {
+ if (outputTextBox.InvokeRequired)
+ { _ = outputTextBox.Invoke(new AppendNumberDelegate(AppendNumber), number); }
+ else
+ { outputTextBox.AppendText(number.ToString("N0") + Environment.NewLine); }
+ }
+ //
+ void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
+ {
+ toolStripProgressBar.Value = e.ProgressPercentage;
+ toolStripStatusLabel.Text = e.UserState as string;
+ }
- private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
- {
- if (e.Error is OverflowException)
- { outputTextBox.AppendText(Environment.NewLine + "**OVERFLOW ERROR, number is too large to be represented by the decimal data type**"); }
- toolStripProgressBar.Enabled = false;
- requestedCountControl.Enabled = true;
- goButton.Enabled = true;
- }
+ void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
+ {
+ if (e.Error is OverflowException)
+ { outputTextBox.AppendText(Environment.NewLine + "**OVERFLOW ERROR, number is too large to be represented by the decimal data type**"); }
+ toolStripProgressBar.Enabled = false;
+ requestedCountControl.Enabled = true;
+ goButton.Enabled = true;
+ }
- private void button1_Click(object sender, EventArgs e)
- {
- goButton.Enabled = false;
- toolStripProgressBar.Enabled = true;
- requestedCount = (int)requestedCountControl.Value;
- requestedCountControl.Enabled = false;
- outputTextBox.Clear();
- backgroundWorker.RunWorkerAsync();
- }
+ void button1_Click(object sender, EventArgs e)
+ {
+ goButton.Enabled = false;
+ toolStripProgressBar.Enabled = true;
+ requestedCount = (int)requestedCountControl.Value;
+ requestedCountControl.Enabled = false;
+ outputTextBox.Clear();
+ backgroundWorker.RunWorkerAsync();
+ }
}
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System.ComponentModel/BindableAttribute/Bindable/Project.csproj b/snippets/csharp/System.ComponentModel/BindableAttribute/Bindable/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/BindableAttribute/Bindable/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/BindableAttribute/Bindable/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/BindableAttribute/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/BindableAttribute/Overview/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/BindableAttribute/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/BindableAttribute/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/BindableAttribute/Overview/source.cs b/snippets/csharp/System.ComponentModel/BindableAttribute/Overview/source.cs
index 85ea6f4ce8e..104aa94ad5e 100644
--- a/snippets/csharp/System.ComponentModel/BindableAttribute/Overview/source.cs
+++ b/snippets/csharp/System.ComponentModel/BindableAttribute/Overview/source.cs
@@ -1,67 +1,77 @@
-using System;
-using System.ComponentModel;
+using System.ComponentModel;
using System.Windows.Forms;
-public class Form1:Form
+public class Form1 : Form
{
- protected TextBox textBox1;
+ protected TextBox textBox1;
-//
-[Bindable(true)]
- public int MyProperty {
- get {
- // Insert code here.
- return 0;
- }
- set {
- // Insert code here.
+ //
+ [Bindable(true)]
+ public int MyProperty
+ {
+ get =>
+ // Insert code here.
+ 0;
+ set
+ {
+ // Insert code here.
+ }
}
- }
-//
- public int MyProperty2 {
- get {
- //
- // Gets the attributes for the property.
- AttributeCollection attributes =
- TypeDescriptor.GetProperties(this)["MyProperty"].Attributes;
+ //
+ public int MyProperty2
+ {
+ get
+ {
+ //
+ // Gets the attributes for the property.
+ AttributeCollection attributes =
+ TypeDescriptor.GetProperties(this)["MyProperty"].Attributes;
- // Checks to see if the value of the BindableAttribute is Yes.
- if(attributes[typeof(BindableAttribute)].Equals(BindableAttribute.Yes)) {
- // Insert code here.
- }
+ // Checks to see if the value of the BindableAttribute is Yes.
+ if (attributes[typeof(BindableAttribute)].Equals(BindableAttribute.Yes))
+ {
+ // Insert code here.
+ }
- // This is another way to see whether the property is bindable.
- BindableAttribute myAttribute =
- (BindableAttribute)attributes[typeof(BindableAttribute)];
- if(myAttribute.Bindable) {
- // Insert code here.
- }
+ // This is another way to see whether the property is bindable.
+ BindableAttribute myAttribute =
+ (BindableAttribute)attributes[typeof(BindableAttribute)];
+ if (myAttribute.Bindable)
+ {
+ // Insert code here.
+ }
- // Yet another way to see whether the property is bindable.
- if (attributes.Contains(BindableAttribute.Yes)) {
- // Insert code here.
- }
+ // Yet another way to see whether the property is bindable.
+ if (attributes.Contains(BindableAttribute.Yes))
+ {
+ // Insert code here.
+ }
- //
- return 0;
- }
- set {
- // Insert code here.
- }
- }
- public int MyProperty3 {
- get {
- //
- AttributeCollection attributes =
- TypeDescriptor.GetAttributes(MyProperty);
- if(attributes[typeof(BindableAttribute)].Equals(BindableAttribute.Yes)) {
+ //
+ return 0;
+ }
+ set
+ {
// Insert code here.
- }
- //
- return 0;
+ }
}
- set {
- // Insert code here.
+ public int MyProperty3
+ {
+ get
+ {
+ //
+ AttributeCollection attributes =
+ TypeDescriptor.GetAttributes(MyProperty);
+ if (attributes[typeof(BindableAttribute)].Equals(BindableAttribute.Yes))
+ {
+ // Insert code here.
+ }
+ //
+ return 0;
+ }
+ set
+ {
+ // Insert code here.
+ }
}
- }
}
diff --git a/snippets/csharp/System.ComponentModel/BindingListT/FindCore/Form1.cs b/snippets/csharp/System.ComponentModel/BindingListT/FindCore/Form1.cs
index 81b4b1d6062..9a15603b3ca 100644
--- a/snippets/csharp/System.ComponentModel/BindingListT/FindCore/Form1.cs
+++ b/snippets/csharp/System.ComponentModel/BindingListT/FindCore/Form1.cs
@@ -1,105 +1,103 @@
//
//
using System;
-using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
-using System.Text;
using System.Windows.Forms;
//
//
-namespace BindingSourceExamples
+namespace BindingSourceExamples;
+
+public class Form1 : Form
{
- public class Form1 : Form
+ [STAThread]
+ static void Main()
{
- [STAThread]
- static void Main()
- {
- Application.EnableVisualStyles();
- Application.Run(new Form1());
- }
+ Application.EnableVisualStyles();
+ Application.Run(new Form1());
+ }
- public Form1()
- {
- this.Load += new EventHandler(Form1_Load);
- }
+ public Form1() => Load += Form1_Load;
- private TextBox textBox1;
- private Button button1;
- private ListBox listBox1;
-
- private BindingSource binding1;
- void Form1_Load(object sender, EventArgs e)
- {
- listBox1 = new ListBox();
- textBox1 = new TextBox();
- binding1 = new BindingSource();
- button1 = new Button();
- listBox1.Location = new Point(140, 25);
- listBox1.Size = new Size(123, 160);
- textBox1.Location = new Point(23, 70);
- textBox1.Size = new Size(100, 20);
- textBox1.Text = "Wingdings";
- button1.Location = new Point(23, 25);
- button1.Size = new Size(75, 23);
- button1.Text = "Search";
- button1.Click += new EventHandler(this.button1_Click);
- this.ClientSize = new Size(292, 266);
- this.Controls.Add(this.button1);
- this.Controls.Add(this.textBox1);
- this.Controls.Add(this.listBox1);
+ TextBox textBox1;
+ Button button1;
+ ListBox listBox1;
- MyFontList fonts = new MyFontList();
- for (int i = 0; i < FontFamily.Families.Length; i++)
+ BindingSource binding1;
+ void Form1_Load(object sender, EventArgs e)
+ {
+ listBox1 = new ListBox();
+ textBox1 = new TextBox();
+ binding1 = [];
+ button1 = new Button();
+ listBox1.Location = new Point(140, 25);
+ listBox1.Size = new Size(123, 160);
+ textBox1.Location = new Point(23, 70);
+ textBox1.Size = new Size(100, 20);
+ textBox1.Text = "Wingdings";
+ button1.Location = new Point(23, 25);
+ button1.Size = new Size(75, 23);
+ button1.Text = "Search";
+ button1.Click += button1_Click;
+ ClientSize = new Size(292, 266);
+ Controls.Add(button1);
+ Controls.Add(textBox1);
+ Controls.Add(listBox1);
+
+ MyFontList fonts = [];
+ for (int i = 0; i < FontFamily.Families.Length; i++)
+ {
+ if (FontFamily.Families[i].IsStyleAvailable(FontStyle.Regular))
{
- if (FontFamily.Families[i].IsStyleAvailable(FontStyle.Regular))
- fonts.Add(new Font(FontFamily.Families[i], 11.0F, FontStyle.Regular));
+ fonts.Add(new Font(FontFamily.Families[i], 11.0F, FontStyle.Regular));
}
- binding1.DataSource = fonts;
- listBox1.DataSource = binding1;
- listBox1.DisplayMember = "Name";
}
+ binding1.DataSource = fonts;
+ listBox1.DataSource = binding1;
+ listBox1.DisplayMember = "Name";
+ }
- //
- private void button1_Click(object sender, EventArgs e)
+ //
+ void button1_Click(object sender, EventArgs e)
+ {
+ if (!binding1.SupportsSearching)
{
- if (!binding1.SupportsSearching)
+ _ = MessageBox.Show("Cannot search the list.");
+ }
+ else
+ {
+ int foundIndex = binding1.Find("Name", textBox1.Text);
+ if (foundIndex > -1)
{
- MessageBox.Show("Cannot search the list.");
+ listBox1.SelectedIndex = foundIndex;
}
else
{
- int foundIndex = binding1.Find("Name", textBox1.Text);
- if (foundIndex > -1)
- listBox1.SelectedIndex = foundIndex;
- else
- MessageBox.Show("Font was not found.");
+ _ = MessageBox.Show("Font was not found.");
}
}
- //
}
-
+ //
+}
+
//
- //
- public class MyFontList : BindingList
+//
+public class MyFontList : BindingList
+{
+ protected override bool SupportsSearchingCore => true;
+ protected override int FindCore(PropertyDescriptor prop, object key)
{
-
- protected override bool SupportsSearchingCore
- {
- get { return true; }
- }
- protected override int FindCore(PropertyDescriptor prop, object key)
+ // Ignore the prop value and search by family name.
+ for (int i = 0; i < Count; ++i)
{
- // Ignore the prop value and search by family name.
- for (int i = 0; i < Count; ++i)
+ if (Items[i].FontFamily.Name.Equals((string)key, StringComparison.CurrentCultureIgnoreCase))
{
- if (Items[i].FontFamily.Name.ToLower() == ((string)key).ToLower())
- return i;
+ return i;
}
- return -1;
}
+ return -1;
}
}
//
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System.ComponentModel/BindingListT/FindCore/Project.csproj b/snippets/csharp/System.ComponentModel/BindingListT/FindCore/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/BindingListT/FindCore/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/BindingListT/FindCore/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/BindingListT/Overview/Form1.cs b/snippets/csharp/System.ComponentModel/BindingListT/Overview/Form1.cs
index 9aa4a08e418..0758386e438 100644
--- a/snippets/csharp/System.ComponentModel/BindingListT/Overview/Form1.cs
+++ b/snippets/csharp/System.ComponentModel/BindingListT/Overview/Form1.cs
@@ -1,150 +1,132 @@
//
using System;
-using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
-using System.Text;
using System.Windows.Forms;
-namespace BindingListOfTExamples
+namespace BindingListOfTExamples;
+
+public partial class Form1 : Form
{
- public partial class Form1 : Form
+ readonly TextBox textBox2;
+ readonly ListBox listBox1;
+ readonly Button button1;
+ readonly TextBox textBox1;
+ readonly Random randomNumber = new();
+
+ public Form1()
{
- private TextBox textBox2;
- private ListBox listBox1;
- private Button button1;
- private TextBox textBox1;
- Random randomNumber = new Random();
-
- public Form1()
- {
- this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.textBox1 = new System.Windows.Forms.TextBox();
- this.textBox2 = new System.Windows.Forms.TextBox();
- this.listBox1 = new System.Windows.Forms.ListBox();
- this.button1 = new System.Windows.Forms.Button();
- this.textBox1.Location = new System.Drawing.Point(169, 26);
- this.textBox1.Size = new System.Drawing.Size(100, 20);
- this.textBox1.Text = "Bracket";
- this.textBox2.Location = new System.Drawing.Point(169, 57);
- this.textBox2.ReadOnly = true;
- this.textBox2.Size = new System.Drawing.Size(100, 20);
- this.textBox2.Text = "4343";
- this.listBox1.FormattingEnabled = true;
- this.listBox1.Location = new System.Drawing.Point(12, 12);
- this.listBox1.Size = new System.Drawing.Size(120, 95);
- this.button1.Location = new System.Drawing.Point(180, 83);
- this.button1.Size = new System.Drawing.Size(75, 23);
- this.button1.Text = "Add New Item";
- this.button1.Click += new System.EventHandler(this.button1_Click);
- this.ClientSize = new System.Drawing.Size(292, 266);
- this.Controls.Add(this.button1);
- this.Controls.Add(this.listBox1);
- this.Controls.Add(this.textBox2);
- this.Controls.Add(this.textBox1);
- this.Text = "Parts Form";
- this.Load += new EventHandler(Form1_Load);
- }
-
- void Form1_Load(object sender, EventArgs e)
- {
- InitializeListOfParts();
- listBox1.DataSource = listOfParts;
- listBox1.DisplayMember = "PartName";
- listOfParts.AddingNew += new AddingNewEventHandler(listOfParts_AddingNew);
- listOfParts.ListChanged += new ListChangedEventHandler(listOfParts_ListChanged);
- }
+ AutoScaleMode = AutoScaleMode.Font;
+ textBox1 = new TextBox();
+ textBox2 = new TextBox();
+ listBox1 = new ListBox();
+ button1 = new Button();
+ textBox1.Location = new Point(169, 26);
+ textBox1.Size = new Size(100, 20);
+ textBox1.Text = "Bracket";
+ textBox2.Location = new Point(169, 57);
+ textBox2.ReadOnly = true;
+ textBox2.Size = new Size(100, 20);
+ textBox2.Text = "4343";
+ listBox1.FormattingEnabled = true;
+ listBox1.Location = new Point(12, 12);
+ listBox1.Size = new Size(120, 95);
+ button1.Location = new Point(180, 83);
+ button1.Size = new Size(75, 23);
+ button1.Text = "Add New Item";
+ button1.Click += button1_Click;
+ ClientSize = new Size(292, 266);
+ Controls.Add(button1);
+ Controls.Add(listBox1);
+ Controls.Add(textBox2);
+ Controls.Add(textBox1);
+ Text = "Parts Form";
+ Load += Form1_Load;
+ }
+
+ void Form1_Load(object sender, EventArgs e)
+ {
+ InitializeListOfParts();
+ listBox1.DataSource = listOfParts;
+ listBox1.DisplayMember = "PartName";
+ listOfParts.AddingNew += listOfParts_AddingNew;
+ listOfParts.ListChanged += listOfParts_ListChanged;
+ }
- //
- // Declare a new BindingListOfT with the Part business object.
- BindingList listOfParts;
- private void InitializeListOfParts()
+ //
+ // Declare a new BindingListOfT with the Part business object.
+ BindingList listOfParts;
+ void InitializeListOfParts()
+ {
+ // Create the new BindingList of Part type.
+ listOfParts = new BindingList
{
- // Create the new BindingList of Part type.
- listOfParts = new BindingList();
-
// Allow new parts to be added, but not removed once committed.
- listOfParts.AllowNew = true;
- listOfParts.AllowRemove = false;
+ AllowNew = true,
+ AllowRemove = false,
// Raise ListChanged events when new parts are added.
- listOfParts.RaiseListChangedEvents = true;
+ RaiseListChangedEvents = true,
// Do not allow parts to be edited.
- listOfParts.AllowEdit = false;
-
- // Add a couple of parts to the list.
- listOfParts.Add(new Part("Widget", 1234));
- listOfParts.Add(new Part("Gadget", 5647));
- }
- //
+ AllowEdit = false
+ };
- //
- // Create a new part from the text in the two text boxes.
- void listOfParts_AddingNew(object sender, AddingNewEventArgs e)
- {
- e.NewObject = new Part(textBox1.Text, int.Parse(textBox2.Text));
- }
- //
+ // Add a couple of parts to the list.
+ listOfParts.Add(new Part("Widget", 1234));
+ listOfParts.Add(new Part("Gadget", 5647));
+ }
+ //
- //
- // Add the new part unless the part number contains
- // spaces. In that case cancel the add.
- private void button1_Click(object sender, EventArgs e)
- {
- Part newPart = listOfParts.AddNew();
-
- if (newPart.PartName.Contains(" "))
- {
- MessageBox.Show("Part names cannot contain spaces.");
- listOfParts.CancelNew(listOfParts.IndexOf(newPart));
- }
- else
- {
- textBox2.Text = randomNumber.Next(9999).ToString();
- textBox1.Text = "Enter part name";
- }
- }
- //
+ //
+ // Create a new part from the text in the two text boxes.
+ void listOfParts_AddingNew(object sender, AddingNewEventArgs e) => e.NewObject = new Part(textBox1.Text, int.Parse(textBox2.Text));
+ //
- //
- void listOfParts_ListChanged(object sender, ListChangedEventArgs e)
- {
- MessageBox.Show(e.ListChangedType.ToString());
- }
- //
+ //
+ // Add the new part unless the part number contains
+ // spaces. In that case cancel the add.
+ void button1_Click(object sender, EventArgs e)
+ {
+ Part newPart = listOfParts.AddNew();
- [STAThread]
- static void Main()
+ if (newPart.PartName.Contains(' '))
{
- Application.EnableVisualStyles();
- Application.Run(new Form1());
+ _ = MessageBox.Show("Part names cannot contain spaces.");
+ listOfParts.CancelNew(listOfParts.IndexOf(newPart));
}
- }
-
- // A simple business object for example purposes.
- public class Part
- {
- private string name;
- private int number;
- public Part() { }
- public Part(string nameForPart, int numberForPart)
+ else
{
- PartName = nameForPart;
- PartNumber = numberForPart;
+ textBox2.Text = randomNumber.Next(9999).ToString();
+ textBox1.Text = "Enter part name";
}
+ }
+ //
- public string PartName
- {
- get { return name; }
- set { name = value; }
- }
+ //
+ void listOfParts_ListChanged(object sender, ListChangedEventArgs e) => MessageBox.Show(e.ListChangedType.ToString());
+ //
- public int PartNumber
- {
- get { return number; }
- set { number = value; }
- }
+ [STAThread]
+ static void Main()
+ {
+ Application.EnableVisualStyles();
+ Application.Run(new Form1());
+ }
+}
+
+// A simple business object for example purposes.
+public class Part
+{
+ public Part() { }
+ public Part(string nameForPart, int numberForPart)
+ {
+ PartName = nameForPart;
+ PartNumber = numberForPart;
}
+
+ public string PartName { get; set; }
+
+ public int PartNumber { get; set; }
}
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System.ComponentModel/BindingListT/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/BindingListT/Overview/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/BindingListT/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/BindingListT/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/BooleanConverter/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/BooleanConverter/Overview/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/BooleanConverter/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/BooleanConverter/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/BooleanConverter/Overview/converters.cs b/snippets/csharp/System.ComponentModel/BooleanConverter/Overview/converters.cs
index 0171de52165..4fa5afd7b56 100644
--- a/snippets/csharp/System.ComponentModel/BooleanConverter/Overview/converters.cs
+++ b/snippets/csharp/System.ComponentModel/BooleanConverter/Overview/converters.cs
@@ -1,254 +1,253 @@
using System;
using System.ComponentModel;
-namespace TypeCon
+namespace TypeCon;
+
+public static class TypeCon_Doc
{
- public class TypeCon_Doc {
-
- enum Servers {Windows=1, Exchange=2, BizTalk=3};
-
- static void Main(string[] args) {
-
- // ArrayConverter
- //
- // implemented in another file
- //
-
- //============================================================
- // BaseNumberConverter
- //
- // implemented in another file
- //
-
- //============================================================
- // BooleanConverter
- // This sample converts a Boolean variable to and from a string variable.
- //
- bool bVal=true;
- string strA="false";
- Console.WriteLine(TypeDescriptor.GetConverter(bVal).ConvertTo(bVal, typeof(string)));
- Console.WriteLine(TypeDescriptor.GetConverter(bVal).ConvertFrom(strA));
- //
-
- //============================================================
- // ByteConverter - work
- // This sample converts an 8-bit unsigned integer to and from a string.
- //
- byte myUint = 5;
- string myUStr = "2";
- Console.WriteLine(TypeDescriptor.GetConverter(myUint).ConvertTo(myUint, typeof(string)));
- Console.WriteLine(TypeDescriptor.GetConverter(myUint).ConvertFrom(myUStr));
- //
-
- //============================================================
- // CharConverter
- // This sample converts a Char variable to and from a String.
- //
- Char chrA='a';
- string strB="b";
- Console.WriteLine(TypeDescriptor.GetConverter(chrA).ConvertTo(chrA, typeof(string)));
- Console.WriteLine(TypeDescriptor.GetConverter(chrA).ConvertFrom(strB));
- //
-
- //============================================================
- // CollectionConverter
- //
- // implemented in another file
- //
-
- //============================================================
- // ComponentConverter
- //
- // implemented in another file
- //
-
- //============================================================
- // CultureInfoConverter
- // This sample converts a CultureInfo object to and from a string.
- //
- // The sample first constructs a CultureInfo variable using the Greek culture - 'el'.
- System.Globalization.CultureInfo myCulture= new System.Globalization.CultureInfo("el");
- string myCString="Russian";
- Console.WriteLine(TypeDescriptor.GetConverter(myCulture).ConvertTo(myCulture, typeof(string)));
- // The following line will output 'ru' based on the string being converted.
- Console.WriteLine(TypeDescriptor.GetConverter(myCulture).ConvertFrom(myCString));
- //
-
- //============================================================
- // DateTimeConverter
- // This sample converts a DateTime variable to and from a String.
- //
- DateTime dt=new DateTime(1990,5,6);
- Console.WriteLine(TypeDescriptor.GetConverter(dt).ConvertTo(dt, typeof(string)));
- string myStr="1991-10-10";
- Console.WriteLine(TypeDescriptor.GetConverter(dt).ConvertFrom(myStr));
- //
-
- //============================================================
- // DecimalConverter
- //
- decimal myDec = 40;
- string myDStr = "20";
- Console.WriteLine(TypeDescriptor.GetConverter(myDec).ConvertTo(myDec, typeof(string)));
- Console.WriteLine(TypeDescriptor.GetConverter(myDec).ConvertFrom(myDStr));
- //
-
- //============================================================
- // DoubleConverter
- //
- double myDoub = 100.55;
- string myDoStr = "4000.425";
- Console.WriteLine(TypeDescriptor.GetConverter(myDoub).ConvertTo(myDoub, typeof(string)));
- Console.WriteLine(TypeDescriptor.GetConverter(myDoub).ConvertFrom(myDoStr));
- //
-
- //============================================================
- // EnumConverter - work
- // This converter can only convert an enumeration object to and from a string.
- // This is declared before main() enum Servers {Windows=1, Exchange=2, BizTalk=3};
- //
- Enum myServer= Servers.Exchange;
- string myServerString = "BizTalk";
- Console.WriteLine(TypeDescriptor.GetConverter(myServer).ConvertTo(myServer, typeof(string)));
- Console.WriteLine(TypeDescriptor.GetConverter(myServer).ConvertFrom(myServerString));
-
- //
-
- //============================================================
- // GUIDConverter
- // This converter can only convert a globally unique identifier object to and from a string.
- //
- Guid myGuid = new Guid("B80D56EC-5899-459d-83B4-1AE0BB8418E4");
- string myGuidString = "1AA7F83F-C7F5-11D0-A376-00C04FC9DA04";
- Console.WriteLine(TypeDescriptor.GetConverter(myGuid).ConvertTo(myGuid, typeof(string)));
- Console.WriteLine(TypeDescriptor.GetConverter(myGuid).ConvertFrom(myGuidString));
- //
-
- //============================================================
- // Int16Converter
- // The Int16 value type represents signed integers with values ranging from negative 32768 through positive 32767.
- // This converter can only convert a 16-bit signed integer object to and from a string.
- //
- short myInt16 = -10000;
- string myInt16String = "+20000";
- Console.WriteLine(TypeDescriptor.GetConverter(myInt16).ConvertTo(myInt16, typeof(string)));
- Console.WriteLine(TypeDescriptor.GetConverter(myInt16).ConvertFrom(myInt16String));
- //
-
- //============================================================
- // Int32Converter
- // The Int32 value type represents signed integers with values ranging from negative 2,147,483,648 through positive 2,147,483,647.
- // This converter can only convert a 32-bit signed integer object to and from a string.
- //
- int myInt32 = -967299;
- string myInt32String = "+1345556";
- Console.WriteLine(TypeDescriptor.GetConverter(myInt32).ConvertTo(myInt32, typeof(string)));
- Console.WriteLine(TypeDescriptor.GetConverter(myInt32).ConvertFrom(myInt32String));
- //
-
- //============================================================
- // Int64Converter - work
- // The Int64 value type represents integers with values ranging from negative 9,223,372,036,854,775,808 through positive 9,223,372,036,854,775,807.
- // This converter can only convert a 64-bit signed integer object to and from a string.
- //
- long myInt64 = -123456789123;
- string myInt64String = "+184467440737095551";
- Console.WriteLine(TypeDescriptor.GetConverter(myInt64).ConvertTo(myInt64, typeof(string)));
- Console.WriteLine(TypeDescriptor.GetConverter(myInt64).ConvertFrom(myInt64String));
- //
-
- //============================================================
- // ReferenceConverter
- //
- // implemented in another file
- //
-
- //============================================================
- // SByteConverter
- // The SByte value type represents integers with values ranging from negative 128 to positive 127.
- // This converter can convert only an 8-bit unsigned integer object to and from a string.
- //
- sbyte mySByte=+121;
- string mySByteStr="-100";
- Console.WriteLine(TypeDescriptor.GetConverter(mySByte).ConvertTo(mySByte, typeof(string)));
- Console.WriteLine(TypeDescriptor.GetConverter(mySByte).ConvertFrom(mySByteStr));
- //
-
- //============================================================
- // SingleConverter
- // Single - ranging in value from -3.402823E+38 to -1.401298E-45 for negative values and from 1.401298E-45 to 3.402823E+38 for positive values
- // This converter can only convert a single-precision, floating point number object to and from a string.
- //
- Single s=3.402823E+10F;
- string mySStr="3.402823E+10";
- Console.WriteLine(TypeDescriptor.GetConverter(s).ConvertTo(s, typeof(string)));
- Console.WriteLine(TypeDescriptor.GetConverter(s).ConvertFrom(mySStr));
- //
-
- //============================================================
- // StringConverter
- //cpconconvertingstringstonetframeworkdatatypes
- //
- //implemented in anothner file
- //
-
- //============================================================
- // TimeSpanConverter
- // This converter can only convert a TimeSpan object to and from a string.
- //
- TimeSpan ts=new TimeSpan(133333330);
- string myTSStr = "5000000";
- Console.WriteLine(TypeDescriptor.GetConverter(ts).ConvertTo(ts, typeof(string)));
- Console.WriteLine(TypeDescriptor.GetConverter(ts).ConvertFrom(myTSStr));
- //
-
- //============================================================
- // TypeListConverter
- //
- // implemented in another file
- //
-
- //============================================================
- // UInt16Converter
- // The UInt16 value type represents unsigned integers with values ranging from 0 to 65535
- // This converter can only convert a 16-bit unsigned integer object to and from a string.
- //
- ushort myUInt16 = 10000;
- string myUInt16String = "20000";
- Console.WriteLine(TypeDescriptor.GetConverter(myUInt16).ConvertTo(myUInt16, typeof(string)));
- Console.WriteLine(TypeDescriptor.GetConverter(myUInt16).ConvertFrom(myUInt16String));
- //
-
- //============================================================
- // UInt32Converter
- // The UInt32 value type represents unsigned integers with values ranging from 0 to 4,294,967,295.
- // This converter can only convert a 32-bit unsigned integer object to and from a string.
- //
- uint myUInt32 = 967299;
- string myUInt32String = "1345556";
- Console.WriteLine(TypeDescriptor.GetConverter(myUInt32).ConvertTo(myUInt32, typeof(string)));
- Console.WriteLine(TypeDescriptor.GetConverter(myUInt32).ConvertFrom(myUInt32String));
- //
-
- //============================================================
- // UInt64Converter
- // The UInt64 value type represents unsigned integers with values ranging from 0 to 184,467,440,737,095,551,615.
- // This converter can only convert a 64-bit unsigned integer object to and from a string.
- //
- ulong myUInt64 = 123456789123;
- string myUInt64String = "184467440737095551";
- Console.WriteLine(TypeDescriptor.GetConverter(myUInt64).ConvertTo(myUInt64, typeof(string)));
- Console.WriteLine(TypeDescriptor.GetConverter(myUInt64).ConvertFrom(myUInt64String));
- //
-
- //============================================================
-// ExpandableObjectConverter
-//
-string strM="1,2,3,4";
-System.Drawing.Printing.Margins m= new System.Drawing.Printing.Margins(1,2,3,4);
-Console.WriteLine(TypeDescriptor.GetConverter(strM).CanConvertTo(typeof(System.Drawing.Printing.Margins)));
-Console.WriteLine(TypeDescriptor.GetConverter(m).ConvertToString(m));
-//
- }
+ enum Servers { Windows = 1, Exchange = 2, BizTalk = 3 };
+
+ static void Main()
+ {
+ // ArrayConverter
+ //
+ // implemented in another file
+ //
+
+ //============================================================
+ // BaseNumberConverter
+ //
+ // implemented in another file
+ //
+
+ //============================================================
+ // BooleanConverter
+ // This sample converts a Boolean variable to and from a string variable.
+ //
+ bool bVal = true;
+ string strA = "false";
+ Console.WriteLine(TypeDescriptor.GetConverter(bVal).ConvertTo(bVal, typeof(string)));
+ Console.WriteLine(TypeDescriptor.GetConverter(bVal).ConvertFrom(strA));
+ //
+
+ //============================================================
+ // ByteConverter - work
+ // This sample converts an 8-bit unsigned integer to and from a string.
+ //
+ byte myUint = 5;
+ string myUStr = "2";
+ Console.WriteLine(TypeDescriptor.GetConverter(myUint).ConvertTo(myUint, typeof(string)));
+ Console.WriteLine(TypeDescriptor.GetConverter(myUint).ConvertFrom(myUStr));
+ //
+
+ //============================================================
+ // CharConverter
+ // This sample converts a Char variable to and from a String.
+ //
+ char chrA = 'a';
+ string strB = "b";
+ Console.WriteLine(TypeDescriptor.GetConverter(chrA).ConvertTo(chrA, typeof(string)));
+ Console.WriteLine(TypeDescriptor.GetConverter(chrA).ConvertFrom(strB));
+ //
+
+ //============================================================
+ // CollectionConverter
+ //
+ // implemented in another file
+ //
+
+ //============================================================
+ // ComponentConverter
+ //
+ // implemented in another file
+ //
+
+ //============================================================
+ // CultureInfoConverter
+ // This sample converts a CultureInfo object to and from a string.
+ //
+ // The sample first constructs a CultureInfo variable using the Greek culture - 'el'.
+ System.Globalization.CultureInfo myCulture = new("el");
+ string myCString = "Russian";
+ Console.WriteLine(TypeDescriptor.GetConverter(myCulture).ConvertTo(myCulture, typeof(string)));
+ // The following line will output 'ru' based on the string being converted.
+ Console.WriteLine(TypeDescriptor.GetConverter(myCulture).ConvertFrom(myCString));
+ //
+
+ //============================================================
+ // DateTimeConverter
+ // This sample converts a DateTime variable to and from a String.
+ //
+ DateTime dt = new(1990, 5, 6);
+ Console.WriteLine(TypeDescriptor.GetConverter(dt).ConvertTo(dt, typeof(string)));
+ string myStr = "1991-10-10";
+ Console.WriteLine(TypeDescriptor.GetConverter(dt).ConvertFrom(myStr));
+ //
+
+ //============================================================
+ // DecimalConverter
+ //
+ decimal myDec = 40;
+ string myDStr = "20";
+ Console.WriteLine(TypeDescriptor.GetConverter(myDec).ConvertTo(myDec, typeof(string)));
+ Console.WriteLine(TypeDescriptor.GetConverter(myDec).ConvertFrom(myDStr));
+ //
+
+ //============================================================
+ // DoubleConverter
+ //
+ double myDoub = 100.55;
+ string myDoStr = "4000.425";
+ Console.WriteLine(TypeDescriptor.GetConverter(myDoub).ConvertTo(myDoub, typeof(string)));
+ Console.WriteLine(TypeDescriptor.GetConverter(myDoub).ConvertFrom(myDoStr));
+ //
+
+ //============================================================
+ // EnumConverter - work
+ // This converter can only convert an enumeration object to and from a string.
+ // This is declared before main() enum Servers {Windows=1, Exchange=2, BizTalk=3};
+ //
+ Enum myServer = Servers.Exchange;
+ string myServerString = "BizTalk";
+ Console.WriteLine(TypeDescriptor.GetConverter(myServer).ConvertTo(myServer, typeof(string)));
+ Console.WriteLine(TypeDescriptor.GetConverter(myServer).ConvertFrom(myServerString));
+
+ //
+
+ //============================================================
+ // GUIDConverter
+ // This converter can only convert a globally unique identifier object to and from a string.
+ //
+ Guid myGuid = new("B80D56EC-5899-459d-83B4-1AE0BB8418E4");
+ string myGuidString = "1AA7F83F-C7F5-11D0-A376-00C04FC9DA04";
+ Console.WriteLine(TypeDescriptor.GetConverter(myGuid).ConvertTo(myGuid, typeof(string)));
+ Console.WriteLine(TypeDescriptor.GetConverter(myGuid).ConvertFrom(myGuidString));
+ //
+
+ //============================================================
+ // Int16Converter
+ // The Int16 value type represents signed integers with values ranging from negative 32768 through positive 32767.
+ // This converter can only convert a 16-bit signed integer object to and from a string.
+ //
+ short myInt16 = -10000;
+ string myInt16String = "+20000";
+ Console.WriteLine(TypeDescriptor.GetConverter(myInt16).ConvertTo(myInt16, typeof(string)));
+ Console.WriteLine(TypeDescriptor.GetConverter(myInt16).ConvertFrom(myInt16String));
+ //
+
+ //============================================================
+ // Int32Converter
+ // The Int32 value type represents signed integers with values ranging from negative 2,147,483,648 through positive 2,147,483,647.
+ // This converter can only convert a 32-bit signed integer object to and from a string.
+ //
+ int myInt32 = -967299;
+ string myInt32String = "+1345556";
+ Console.WriteLine(TypeDescriptor.GetConverter(myInt32).ConvertTo(myInt32, typeof(string)));
+ Console.WriteLine(TypeDescriptor.GetConverter(myInt32).ConvertFrom(myInt32String));
+ //
+
+ //============================================================
+ // Int64Converter - work
+ // The Int64 value type represents integers with values ranging from negative 9,223,372,036,854,775,808 through positive 9,223,372,036,854,775,807.
+ // This converter can only convert a 64-bit signed integer object to and from a string.
+ //
+ long myInt64 = -123456789123;
+ string myInt64String = "+184467440737095551";
+ Console.WriteLine(TypeDescriptor.GetConverter(myInt64).ConvertTo(myInt64, typeof(string)));
+ Console.WriteLine(TypeDescriptor.GetConverter(myInt64).ConvertFrom(myInt64String));
+ //
+
+ //============================================================
+ // ReferenceConverter
+ //
+ // implemented in another file
+ //
+
+ //============================================================
+ // SByteConverter
+ // The SByte value type represents integers with values ranging from negative 128 to positive 127.
+ // This converter can convert only an 8-bit unsigned integer object to and from a string.
+ //
+ sbyte mySByte = +121;
+ string mySByteStr = "-100";
+ Console.WriteLine(TypeDescriptor.GetConverter(mySByte).ConvertTo(mySByte, typeof(string)));
+ Console.WriteLine(TypeDescriptor.GetConverter(mySByte).ConvertFrom(mySByteStr));
+ //
+
+ //============================================================
+ // SingleConverter
+ // Single - ranging in value from -3.402823E+38 to -1.401298E-45 for negative values and from 1.401298E-45 to 3.402823E+38 for positive values
+ // This converter can only convert a single-precision, floating point number object to and from a string.
+ //
+ float s = 3.402823E+10F;
+ string mySStr = "3.402823E+10";
+ Console.WriteLine(TypeDescriptor.GetConverter(s).ConvertTo(s, typeof(string)));
+ Console.WriteLine(TypeDescriptor.GetConverter(s).ConvertFrom(mySStr));
+ //
+
+ //============================================================
+ // StringConverter
+ //cpconconvertingstringstonetframeworkdatatypes
+ //
+ //implemented in anothner file
+ //
+
+ //============================================================
+ // TimeSpanConverter
+ // This converter can only convert a TimeSpan object to and from a string.
+ //
+ TimeSpan ts = new(133333330);
+ string myTSStr = "5000000";
+ Console.WriteLine(TypeDescriptor.GetConverter(ts).ConvertTo(ts, typeof(string)));
+ Console.WriteLine(TypeDescriptor.GetConverter(ts).ConvertFrom(myTSStr));
+ //
+
+ //============================================================
+ // TypeListConverter
+ //
+ // implemented in another file
+ //
+
+ //============================================================
+ // UInt16Converter
+ // The UInt16 value type represents unsigned integers with values ranging from 0 to 65535
+ // This converter can only convert a 16-bit unsigned integer object to and from a string.
+ //
+ ushort myUInt16 = 10000;
+ string myUInt16String = "20000";
+ Console.WriteLine(TypeDescriptor.GetConverter(myUInt16).ConvertTo(myUInt16, typeof(string)));
+ Console.WriteLine(TypeDescriptor.GetConverter(myUInt16).ConvertFrom(myUInt16String));
+ //
+
+ //============================================================
+ // UInt32Converter
+ // The UInt32 value type represents unsigned integers with values ranging from 0 to 4,294,967,295.
+ // This converter can only convert a 32-bit unsigned integer object to and from a string.
+ //
+ uint myUInt32 = 967299;
+ string myUInt32String = "1345556";
+ Console.WriteLine(TypeDescriptor.GetConverter(myUInt32).ConvertTo(myUInt32, typeof(string)));
+ Console.WriteLine(TypeDescriptor.GetConverter(myUInt32).ConvertFrom(myUInt32String));
+ //
+
+ //============================================================
+ // UInt64Converter
+ // The UInt64 value type represents unsigned integers with values ranging from 0 to 184,467,440,737,095,551,615.
+ // This converter can only convert a 64-bit unsigned integer object to and from a string.
+ //
+ ulong myUInt64 = 123456789123;
+ string myUInt64String = "184467440737095551";
+ Console.WriteLine(TypeDescriptor.GetConverter(myUInt64).ConvertTo(myUInt64, typeof(string)));
+ Console.WriteLine(TypeDescriptor.GetConverter(myUInt64).ConvertFrom(myUInt64String));
+ //
+
+ //============================================================
+ // ExpandableObjectConverter
+ //
+ string strM = "1,2,3,4";
+ System.Drawing.Printing.Margins m = new(1, 2, 3, 4);
+ Console.WriteLine(TypeDescriptor.GetConverter(strM).CanConvertTo(typeof(System.Drawing.Printing.Margins)));
+ Console.WriteLine(TypeDescriptor.GetConverter(m).ConvertToString(m));
+ //
}
}
diff --git a/snippets/csharp/System.ComponentModel/BrowsableAttribute/.ctor/Project.csproj b/snippets/csharp/System.ComponentModel/BrowsableAttribute/.ctor/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/BrowsableAttribute/.ctor/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/BrowsableAttribute/.ctor/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/BrowsableAttribute/.ctor/source.cs b/snippets/csharp/System.ComponentModel/BrowsableAttribute/.ctor/source.cs
index bf4590c57c3..5d93aa79236 100644
--- a/snippets/csharp/System.ComponentModel/BrowsableAttribute/.ctor/source.cs
+++ b/snippets/csharp/System.ComponentModel/BrowsableAttribute/.ctor/source.cs
@@ -1,6 +1,4 @@
-using System;
-using System.Data;
-using System.ComponentModel;
+using System.ComponentModel;
using System.Windows.Forms;
public class Form1 : Form
@@ -10,11 +8,9 @@ public class Form1 : Form
[Browsable(true)]
public int MyProperty
{
- get
- {
+ get =>
// Insert code here.
- return 0;
- }
+ 0;
set
{
// Insert code here.
diff --git a/snippets/csharp/System.ComponentModel/BrowsableAttribute/Browsable/Project.csproj b/snippets/csharp/System.ComponentModel/BrowsableAttribute/Browsable/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/BrowsableAttribute/Browsable/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/BrowsableAttribute/Browsable/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/BrowsableAttribute/Browsable/source.cs b/snippets/csharp/System.ComponentModel/BrowsableAttribute/Browsable/source.cs
index 30fb9c2a156..8a9b5586651 100644
--- a/snippets/csharp/System.ComponentModel/BrowsableAttribute/Browsable/source.cs
+++ b/snippets/csharp/System.ComponentModel/BrowsableAttribute/Browsable/source.cs
@@ -1,23 +1,22 @@
-using System;
-using System.Data;
-using System.ComponentModel;
+using System.ComponentModel;
using System.Windows.Forms;
-public class Form1: Form
+public class Form1 : Form
{
- protected void Method()
- {
-//
-// Gets the attributes for the property.
- AttributeCollection attributes =
- TypeDescriptor.GetProperties(this)["MyProperty"].Attributes;
-
- // Checks to see if the property is browsable.
- BrowsableAttribute myAttribute = (BrowsableAttribute)attributes[typeof(BrowsableAttribute)];
- if(myAttribute.Browsable) {
- // Insert code here.
- }
-
-//
- }
+ protected void Method()
+ {
+ //
+ // Gets the attributes for the property.
+ AttributeCollection attributes =
+ TypeDescriptor.GetProperties(this)["MyProperty"].Attributes;
+
+ // Checks to see if the property is browsable.
+ BrowsableAttribute myAttribute = (BrowsableAttribute)attributes[typeof(BrowsableAttribute)];
+ if (myAttribute.Browsable)
+ {
+ // Insert code here.
+ }
+
+ //
+ }
}
diff --git a/snippets/csharp/System.ComponentModel/BrowsableAttribute/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/BrowsableAttribute/Overview/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/BrowsableAttribute/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/BrowsableAttribute/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/BrowsableAttribute/Overview/source.cs b/snippets/csharp/System.ComponentModel/BrowsableAttribute/Overview/source.cs
index 27d0600d8d3..b979a2d261a 100644
--- a/snippets/csharp/System.ComponentModel/BrowsableAttribute/Overview/source.cs
+++ b/snippets/csharp/System.ComponentModel/BrowsableAttribute/Overview/source.cs
@@ -1,6 +1,4 @@
-using System;
-using System.Data;
-using System.ComponentModel;
+using System.ComponentModel;
using System.Windows.Forms;
public class Form1 : Form
@@ -9,11 +7,9 @@ public class Form1 : Form
[Browsable(true)]
public int MyProperty
{
- get
- {
+ get =>
// Insert code here.
- return 0;
- }
+ 0;
set
{
// Insert code here.
diff --git a/snippets/csharp/System.ComponentModel/CancelEventArgs/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/CancelEventArgs/Overview/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/CancelEventArgs/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/CancelEventArgs/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/CancelEventArgs/Overview/source.cs b/snippets/csharp/System.ComponentModel/CancelEventArgs/Overview/source.cs
index fed978ad045..ae5301054d3 100644
--- a/snippets/csharp/System.ComponentModel/CancelEventArgs/Overview/source.cs
+++ b/snippets/csharp/System.ComponentModel/CancelEventArgs/Overview/source.cs
@@ -1,30 +1,32 @@
-using System;
-using System.Data;
-using System.ComponentModel;
+using System.ComponentModel;
using System.Windows.Forms;
-public class Form1: Form
+public class Form1 : Form
{
- protected bool isDataSaved;
-//
-// Call this method from the constructor of your form
- private void OtherInitialize() {
- this.Closing += new CancelEventHandler(this.Form1_Closing);
- // Exchange commented line and note the difference.
- this.isDataSaved = true;
- //this.isDataSaved = false;
+ protected bool isDataSaved;
+ //
+ // Call this method from the constructor of your form
+ void OtherInitialize()
+ {
+ Closing += Form1_Closing;
+ // Exchange commented line and note the difference.
+ isDataSaved = true;
+ //this.isDataSaved = false;
}
- private void Form1_Closing(Object sender, CancelEventArgs e) {
- if (!isDataSaved) {
- e.Cancel = true;
- MessageBox.Show("You must save first.");
- }
- else {
- e.Cancel = false;
- MessageBox.Show("Goodbye.");
- }
+ void Form1_Closing(object sender, CancelEventArgs e)
+ {
+ if (!isDataSaved)
+ {
+ e.Cancel = true;
+ _ = MessageBox.Show("You must save first.");
+ }
+ else
+ {
+ e.Cancel = false;
+ _ = MessageBox.Show("Goodbye.");
+ }
}
-
-//
+
+ //
}
diff --git a/snippets/csharp/System.ComponentModel/CategoryAttribute/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/CategoryAttribute/Overview/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/CategoryAttribute/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/CategoryAttribute/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/CategoryAttribute/Overview/source.cs b/snippets/csharp/System.ComponentModel/CategoryAttribute/Overview/source.cs
index bed853cb9a5..5bed0f9858b 100644
--- a/snippets/csharp/System.ComponentModel/CategoryAttribute/Overview/source.cs
+++ b/snippets/csharp/System.ComponentModel/CategoryAttribute/Overview/source.cs
@@ -1,36 +1,37 @@
using System;
-using System.Data;
using System.ComponentModel;
-using System.Windows.Forms;
using System.Drawing;
+using System.Windows.Forms;
-public class Form1: Form
+public class Form1 : Form
{
- protected TextBox textBox1;
- protected Image image1;
- //
-[Description("The image associated with the control"),Category("Appearance")]
- public Image MyImage {
- get {
- // Insert code here.
- return image1;
+ protected TextBox textBox1;
+ protected Image image1;
+ //
+ [Description("The image associated with the control"), Category("Appearance")]
+ public Image MyImage
+ {
+ get =>
+ // Insert code here.
+ image1;
+ set
+ {
+ // Insert code here.
+ }
}
- set {
- // Insert code here.
+ //
+ public void MyMethod()
+ {
+ //
+ // Gets the attributes for the property.
+ AttributeCollection attributes =
+ TypeDescriptor.GetProperties(this)["MyImage"].Attributes;
+
+ // Prints the description by retrieving the CategoryAttribute.
+ // from the AttributeCollection.
+ CategoryAttribute myAttribute =
+ (CategoryAttribute)attributes[typeof(CategoryAttribute)];
+ Console.WriteLine(myAttribute.Category);
+ //
}
- }
-//
-public void MyMethod(){
- //
- // Gets the attributes for the property.
- AttributeCollection attributes =
- TypeDescriptor.GetProperties(this)["MyImage"].Attributes;
-
- // Prints the description by retrieving the CategoryAttribute.
- // from the AttributeCollection.
- CategoryAttribute myAttribute =
- (CategoryAttribute)attributes[typeof(CategoryAttribute)];
- Console.WriteLine(myAttribute.Category);
- //
-}
}
diff --git a/snippets/csharp/System.ComponentModel/ComponentCollection/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/ComponentCollection/Overview/Project.csproj
index c02dc5044e7..5a1b02db677 100644
--- a/snippets/csharp/System.ComponentModel/ComponentCollection/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/ComponentCollection/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0
+ net8.0
\ No newline at end of file
diff --git a/snippets/csharp/System.ComponentModel/ComponentCollection/Overview/librarycontainer.cs b/snippets/csharp/System.ComponentModel/ComponentCollection/Overview/librarycontainer.cs
index d38328038bd..661faa32153 100644
--- a/snippets/csharp/System.ComponentModel/ComponentCollection/Overview/librarycontainer.cs
+++ b/snippets/csharp/System.ComponentModel/ComponentCollection/Overview/librarycontainer.cs
@@ -1,260 +1,196 @@
using System;
-using System.ComponentModel;
using System.Collections;
+using System.ComponentModel;
+
+namespace InterfaceSample;
+
+//
+///
+/// The following example demonstrates the implementation of
+/// ISite, IComponent, and IContainer for use in a simple library container.
+///
+/// This example uses the System, System.ComponentModel, and System.Collections
+/// namespaces.
+///
+//This code segment implements the ISite and IComponent interfaces.
+//The implementation of the IContainer interface can be seen in the documentation
+//of IContainer.
+
+//Implement the ISite interface.
+
+// The ISBNSite class represents the ISBN name of the book component
+class ISBNSite : ISite
+{
+ readonly IComponent m_curComponent;
+ readonly IContainer m_curContainer;
+ readonly bool m_bDesignMode;
+ string m_ISBNCmpName;
+
+ public ISBNSite(IContainer actvCntr, IComponent prntCmpnt)
+ {
+ m_curComponent = prntCmpnt;
+ m_curContainer = actvCntr;
+ m_bDesignMode = false;
+ m_ISBNCmpName = null;
+ }
+
+ //Support the ISite interface.
+ public virtual IComponent Component => m_curComponent;
+
+ public virtual IContainer Container => m_curContainer;
+
+ public virtual bool DesignMode => m_bDesignMode;
+
+ public virtual string Name
+ {
+ get => m_ISBNCmpName;
+
+ set => m_ISBNCmpName = value;
+ }
+
+ //Support the IServiceProvider interface.
+ public virtual object GetService(Type serviceType) =>
+ //This example does not use any service object.
+ null;
+}
+
+// The BookComponent class represents the book component of the library container.
+
+// This class implements the IComponent interface.
+
+class BookComponent : IComponent
+{
+ public event EventHandler Disposed;
+ ISite m_curISBNSite;
+
+ public BookComponent(string Title, string Author)
+ {
+ m_curISBNSite = null;
+ Disposed = null;
+ this.Title = Title;
+ this.Author = Author;
+ }
+
+ public string Title { get; }
+
+ public string Author { get; }
+
+ public virtual void Dispose() =>
+ //There is nothing to clean.
+ Disposed?.Invoke(this, EventArgs.Empty);
+
+ public virtual ISite Site
+ {
+ get => m_curISBNSite;
+ set => m_curISBNSite = value;
+ }
+
+ public override bool Equals(object cmp)
+ {
+ BookComponent cmpObj = (BookComponent)cmp;
+ return Title.Equals(cmpObj.Title) && Author.Equals(cmpObj.Author);
+ }
+
+ public override int GetHashCode() => base.GetHashCode();
+}
+//
+//
+//This code segment implements the IContainer interface. The code segment
+//containing the implementation of ISite and IComponent can be found in the documentation
+//for those interfaces.
+
+//Implement the LibraryContainer using the IContainer interface.
-namespace InterfaceSample
+class LibraryContainer : IContainer
{
- //
- ///
- /// The following example demonstrates the implementation of
- /// ISite, IComponent, and IContainer for use in a simple library container.
- ///
- /// This example uses the System, System.ComponentModel, and System.Collections
- /// namespaces.
- ///
-
- //This code segment implements the ISite and IComponent interfaces.
- //The implementation of the IContainer interface can be seen in the documentation
- //of IContainer.
-
- //Implement the ISite interface.
-
- // The ISBNSite class represents the ISBN name of the book component
- class ISBNSite : ISite
- {
- private IComponent m_curComponent;
- private IContainer m_curContainer;
- private bool m_bDesignMode;
- private string m_ISBNCmpName;
-
- public ISBNSite(IContainer actvCntr, IComponent prntCmpnt)
- {
- m_curComponent = prntCmpnt;
- m_curContainer = actvCntr;
- m_bDesignMode = false;
- m_ISBNCmpName = null;
- }
-
- //Support the ISite interface.
- public virtual IComponent Component
- {
- get
- {
- return m_curComponent;
- }
- }
-
- public virtual IContainer Container
- {
- get
- {
- return m_curContainer;
- }
- }
-
- public virtual bool DesignMode
- {
- get
- {
- return m_bDesignMode;
- }
- }
-
- public virtual string Name
- {
- get
- {
- return m_ISBNCmpName;
- }
-
- set
- {
- m_ISBNCmpName = value;
- }
- }
-
- //Support the IServiceProvider interface.
- public virtual object GetService(Type serviceType)
- {
- //This example does not use any service object.
- return null;
- }
- }
-
- // The BookComponent class represents the book component of the library container.
-
- // This class implements the IComponent interface.
-
- class BookComponent : IComponent
- {
- public event EventHandler Disposed;
- private ISite m_curISBNSite;
- private string m_bookTitle;
- private string m_bookAuthor;
-
- public BookComponent(string Title, string Author)
- {
- m_curISBNSite = null;
- Disposed = null;
- m_bookTitle = Title;
- m_bookAuthor = Author;
- }
-
- public string Title
- {
- get
- {
- return m_bookTitle;
- }
- }
-
- public string Author
- {
- get
- {
- return m_bookAuthor;
- }
- }
-
- public virtual void Dispose()
- {
- //There is nothing to clean.
- if(Disposed != null)
- Disposed(this,EventArgs.Empty);
- }
-
- public virtual ISite Site
- {
- get
- {
- return m_curISBNSite;
- }
- set
- {
- m_curISBNSite = value;
- }
- }
-
- public override bool Equals(object cmp)
- {
- BookComponent cmpObj = (BookComponent)cmp;
- if(this.Title.Equals(cmpObj.Title) && this.Author.Equals(cmpObj.Author))
- return true;
-
- return false;
- }
-
- public override int GetHashCode()
- {
- return base.GetHashCode();
- }
- }
- //
- //
- //This code segment implements the IContainer interface. The code segment
- //containing the implementation of ISite and IComponent can be found in the documentation
- //for those interfaces.
-
- //Implement the LibraryContainer using the IContainer interface.
-
- class LibraryContainer : IContainer
- {
- private ArrayList m_bookList;
-
- public LibraryContainer()
- {
- m_bookList = new ArrayList();
- }
-
- public virtual void Add(IComponent book)
- {
- //The book will be added without creation of the ISite object.
- m_bookList.Add(book);
- }
-
- public virtual void Add(IComponent book, string ISNDNNum)
- {
- for(int i =0; i < m_bookList.Count; ++i)
- {
- IComponent curObj = (IComponent)m_bookList[i];
- if(curObj.Site != null)
- {
- if(curObj.Site.Name.Equals(ISNDNNum))
- throw new ArgumentException("The ISBN number already exists in the container");
- }
- }
-
- ISBNSite data = new ISBNSite(this, book);
- data.Name = ISNDNNum;
- book.Site = data;
- m_bookList.Add(book);
- }
-
- public virtual void Remove(IComponent book)
- {
- for(int i =0; i < m_bookList.Count; ++i)
- {
- if(book.Equals(m_bookList[i]))
- {
- m_bookList.RemoveAt(i);
- break;
- }
- }
- }
-
- public ComponentCollection Components
- {
- get
- {
- IComponent[] datalist = new BookComponent[m_bookList.Count];
- m_bookList.CopyTo(datalist);
- return new ComponentCollection(datalist);
- }
- }
-
- public virtual void Dispose()
- {
- for(int i =0; i < m_bookList.Count; ++i)
- {
- IComponent curObj = (IComponent)m_bookList[i];
- curObj.Dispose();
- }
-
- m_bookList.Clear();
- }
-
- static void Main(string[] args)
- {
- LibraryContainer cntrExmpl = new LibraryContainer();
-
- try
- {
- BookComponent book1 = new BookComponent("Wizard's First Rule", "Terry Gooodkind");
- cntrExmpl.Add(book1, "0812548051");
- BookComponent book2 = new BookComponent("Stone of Tears", "Terry Gooodkind");
- cntrExmpl.Add(book2, "0812548094");
- BookComponent book3 = new BookComponent("Blood of the Fold", "Terry Gooodkind");
- cntrExmpl.Add(book3, "0812551478");
- BookComponent book4 = new BookComponent("The Soul of the Fire", "Terry Gooodkind");
- //This will generate exception because the ISBN already exists in the container.
- cntrExmpl.Add(book4, "0812551478");
- }
- catch (ArgumentException e)
- {
- Console.WriteLine("Unable to add books: " + e.Message);
- }
-
- ComponentCollection datalist =cntrExmpl.Components;
- IEnumerator denum = datalist.GetEnumerator();
-
- while(denum.MoveNext())
- {
- BookComponent cmp = (BookComponent)denum.Current;
- Console.WriteLine("Book Title: " + cmp.Title);
- Console.WriteLine("Book Author: " + cmp.Author);
- Console.WriteLine("Book ISBN: " + cmp.Site.Name);
- }
- }
- }
- //
+ readonly ArrayList m_bookList = [];
+
+ public virtual void Add(IComponent book) =>
+ //The book will be added without creation of the ISite object.
+ m_bookList.Add(book);
+
+ public virtual void Add(IComponent book, string ISNDNNum)
+ {
+ for (int i = 0; i < m_bookList.Count; ++i)
+ {
+ IComponent curObj = (IComponent)m_bookList[i];
+ if (curObj.Site != null)
+ {
+ if (curObj.Site.Name.Equals(ISNDNNum))
+ {
+ throw new ArgumentException("The ISBN number already exists in the container");
+ }
+ }
+ }
+
+ book.Site = new ISBNSite(this, book) { Name = ISNDNNum };
+ m_bookList.Add(book);
+ }
+
+ public virtual void Remove(IComponent book)
+ {
+ for (int i = 0; i < m_bookList.Count; ++i)
+ {
+ if (book.Equals(m_bookList[i]))
+ {
+ m_bookList.RemoveAt(i);
+ break;
+ }
+ }
+ }
+
+ public ComponentCollection Components
+ {
+ get
+ {
+ IComponent[] datalist = new BookComponent[m_bookList.Count];
+ m_bookList.CopyTo(datalist);
+ return new ComponentCollection(datalist);
+ }
+ }
+
+ public virtual void Dispose()
+ {
+ for (int i = 0; i < m_bookList.Count; ++i)
+ {
+ IComponent curObj = (IComponent)m_bookList[i];
+ curObj.Dispose();
+ }
+
+ m_bookList.Clear();
+ }
+
+ static void Main()
+ {
+ LibraryContainer cntrExmpl = new();
+
+ try
+ {
+ BookComponent book1 = new("Wizard's First Rule", "Terry Gooodkind");
+ cntrExmpl.Add(book1, "0812548051");
+ BookComponent book2 = new("Stone of Tears", "Terry Gooodkind");
+ cntrExmpl.Add(book2, "0812548094");
+ BookComponent book3 = new("Blood of the Fold", "Terry Gooodkind");
+ cntrExmpl.Add(book3, "0812551478");
+ BookComponent book4 = new("The Soul of the Fire", "Terry Gooodkind");
+ //This will generate exception because the ISBN already exists in the container.
+ cntrExmpl.Add(book4, "0812551478");
+ }
+ catch (ArgumentException e)
+ {
+ Console.WriteLine("Unable to add books: " + e.Message);
+ }
+
+ ComponentCollection datalist = cntrExmpl.Components;
+ IEnumerator denum = datalist.GetEnumerator();
+
+ while (denum.MoveNext())
+ {
+ BookComponent cmp = (BookComponent)denum.Current;
+ Console.WriteLine("Book Title: " + cmp.Title);
+ Console.WriteLine("Book Author: " + cmp.Author);
+ Console.WriteLine("Book ISBN: " + cmp.Site.Name);
+ }
+ }
}
+//
diff --git a/snippets/csharp/System.ComponentModel/ComponentEditor/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/ComponentEditor/Overview/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/ComponentEditor/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/ComponentEditor/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/ComponentEditor/Overview/componenteditorexamplecomponent.cs b/snippets/csharp/System.ComponentModel/ComponentEditor/Overview/componenteditorexamplecomponent.cs
index e3b9373a8d2..d80a1e535c7 100644
--- a/snippets/csharp/System.ComponentModel/ComponentEditor/Overview/componenteditorexamplecomponent.cs
+++ b/snippets/csharp/System.ComponentModel/ComponentEditor/Overview/componenteditorexamplecomponent.cs
@@ -4,135 +4,126 @@
using System.ComponentModel.Design;
using System.Drawing;
using System.Windows.Forms;
+using System.Windows.Forms.Design;
-// This example demonstrates how to implement a component editor that hosts
-// component pages and associate it with a component. This example also
-// demonstrates how to implement a component page that provides a panel-based
+// This example demonstrates how to implement a component editor that hosts
+// component pages and associate it with a component. This example also
+// demonstrates how to implement a component page that provides a panel-based
// control system and Help keyword support.
-namespace ComponentEditorExample
+
+// The ExampleComponentEditor displays two ExampleComponentEditorPage pages.
+public class ExampleComponentEditor : WindowsFormsComponentEditor
{
- // The ExampleComponentEditor displays two ExampleComponentEditorPage pages.
- public class ExampleComponentEditor : System.Windows.Forms.Design.WindowsFormsComponentEditor
- {
- //
- // This method override returns an type array containing the type of
- // each component editor page to display.
- protected override Type[] GetComponentEditorPages()
- {
- return new Type[] { typeof(ExampleComponentEditorPage),
- typeof(ExampleComponentEditorPage) };
- }
- //
+ //
+ // This method override returns an type array containing the type of
+ // each component editor page to display.
+ protected override Type[] GetComponentEditorPages() => [typeof(ExampleComponentEditorPage), typeof(ExampleComponentEditorPage)];
+ //
- //
- // This method override returns the index of the page to display when the
- // component editor is first displayed.
- protected override int GetInitialComponentEditorPageIndex()
- {
- return 1;
- }
- //
- }
+ //
+ // This method override returns the index of the page to display when the
+ // component editor is first displayed.
+ protected override int GetInitialComponentEditorPageIndex() => 1;
+ //
+}
+
+//
+// This example component editor page type provides an example
+// ComponentEditorPage implementation.
+class ExampleComponentEditorPage : ComponentEditorPage
+{
+ readonly Label _l1;
+ readonly Button b1;
+ readonly PropertyGrid pg1;
- //
- // This example component editor page type provides an example
- // ComponentEditorPage implementation.
- internal class ExampleComponentEditorPage : System.Windows.Forms.Design.ComponentEditorPage
+ public ExampleComponentEditorPage()
{
- Label l1;
- Button b1;
- PropertyGrid pg1;
+ // Initialize the page, which inherits from Panel, and its controls.
+ Size = new Size(400, 250);
+ Icon = new Icon("myicon.ico");
+ Text = "Example Page";
- public ExampleComponentEditorPage()
+ b1 = new Button
{
- // Initialize the page, which inherits from Panel, and its controls.
- this.Size = new Size(400, 250);
- this.Icon = new Icon("myicon.ico");
- this.Text = "Example Page";
-
- b1 = new Button();
- b1.Size = new Size(200, 20);
- b1.Location = new Point(200, 0);
- b1.Text = "Set a random background color";
- b1.Click += new EventHandler(this.randomBackColor);
- this.Controls.Add(b1);
-
- l1 = new Label();
- l1.Size = new Size(190, 20);
- l1.Location = new Point(4, 2);
- l1.Text = "Example Component Editor Page";
- this.Controls.Add(l1);
-
- pg1 = new PropertyGrid();
- pg1.Size = new Size(400, 280);
- pg1.Location = new Point(0, 30);
- this.Controls.Add(pg1);
- }
+ Size = new Size(200, 20),
+ Location = new Point(200, 0),
+ Text = "Set a random background color"
+ };
+ b1.Click += randomBackColor;
+ Controls.Add(b1);
- // This method indicates that the Help button should be enabled for this
- // component editor page.
- public override bool SupportsHelp()
+ _l1 = new Label
{
- return true;
- }
+ Size = new Size(190, 20),
+ Location = new Point(4, 2),
+ Text = "Example Component Editor Page"
+ };
+ Controls.Add(_l1);
- //
- // This method is called when the Help button for this component editor page is pressed.
- // This implementation uses the IHelpService to show the Help topic for a sample keyword.
- public override void ShowHelp()
+ pg1 = new PropertyGrid
{
- // The GetSelectedComponent method of a ComponentEditorPage retrieves the
- // IComponent associated with the WindowsFormsComponentEditor.
- IComponent selectedComponent = this.GetSelectedComponent();
-
- // Retrieve the Site of the component, and return if null.
- ISite componentSite = selectedComponent.Site;
- if (componentSite == null)
- return;
-
- // Acquire the IHelpService to display a help topic using a indexed keyword lookup.
- IHelpService helpService = (IHelpService)componentSite.GetService(typeof(IHelpService));
- if (helpService != null)
- helpService.ShowHelpFromKeyword("System.Windows.Forms.ComboBox");
- }
- //
+ Size = new Size(400, 280),
+ Location = new Point(0, 30)
+ };
+ Controls.Add(pg1);
+ }
- // The LoadComponent method is raised when the ComponentEditorPage is displayed.
- protected override void LoadComponent()
- {
- this.pg1.SelectedObject = this.Component;
- }
+ // This method indicates that the Help button should be enabled for this
+ // component editor page.
+ public override bool SupportsHelp() => true;
- // The SaveComponent method is raised when the WindowsFormsComponentEditor is closing
- // or the current ComponentEditorPage is closing.
- protected override void SaveComponent()
- {
- }
+ //
+ // This method is called when the Help button for this component editor page is pressed.
+ // This implementation uses the IHelpService to show the Help topic for a sample keyword.
+ public override void ShowHelp()
+ {
+ // The GetSelectedComponent method of a ComponentEditorPage retrieves the
+ // IComponent associated with the WindowsFormsComponentEditor.
+ IComponent selectedComponent = GetSelectedComponent();
- // If the associated component is a Control, this method sets the BackColor to a random color.
- // This method is invoked by the button on this ComponentEditorPage.
- private void randomBackColor(object sender, EventArgs e)
+ // Retrieve the Site of the component, and return if null.
+ ISite componentSite = selectedComponent.Site;
+ if (componentSite == null)
{
- if (typeof(System.Windows.Forms.Control).IsAssignableFrom(this.Component.GetType()))
- {
- // Sets the background color of the Control associated with the
- // WindowsFormsComponentEditor to a random color.
- Random rnd = new Random();
- ((System.Windows.Forms.Control)this.Component).BackColor =
- Color.FromArgb(rnd.Next(255), rnd.Next(255), rnd.Next(255));
- pg1.Refresh();
- }
+ return;
}
+
+ // Acquire the IHelpService to display a help topic using a indexed keyword lookup.
+ IHelpService helpService = (IHelpService)componentSite.GetService(typeof(IHelpService));
+ helpService?.ShowHelpFromKeyword("System.Windows.Forms.ComboBox");
}
- //
+ //
+
+ // The LoadComponent method is raised when the ComponentEditorPage is displayed.
+ protected override void LoadComponent() => pg1.SelectedObject = Component;
- //
- // This example control is associated with the ExampleComponentEditor
- // through the following EditorAttribute.
- [EditorAttribute(typeof(ExampleComponentEditor), typeof(ComponentEditor))]
- public class ExampleUserControl : System.Windows.Forms.UserControl
+ // The SaveComponent method is raised when the WindowsFormsComponentEditor is closing
+ // or the current ComponentEditorPage is closing.
+ protected override void SaveComponent()
{
}
- //
+
+ // If the associated component is a Control, this method sets the BackColor to a random color.
+ // This method is invoked by the button on this ComponentEditorPage.
+ void randomBackColor(object sender, EventArgs e)
+ {
+ if (typeof(Control).IsAssignableFrom(Component.GetType()))
+ {
+ // Sets the background color of the Control associated with the
+ // WindowsFormsComponentEditor to a random color.
+ Random rnd = new();
+ ((Control)Component).BackColor =
+ Color.FromArgb(rnd.Next(255), rnd.Next(255), rnd.Next(255));
+ pg1.Refresh();
+ }
+ }
}
+//
+
+//
+// This example control is associated with the ExampleComponentEditor
+// through the following EditorAttribute.
+[Editor(typeof(ExampleComponentEditor), typeof(ComponentEditor))]
+public class ExampleUserControl : UserControl;
+//
//
diff --git a/snippets/csharp/System.ComponentModel/ComponentResourceManager/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/ComponentResourceManager/Overview/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/ComponentResourceManager/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/ComponentResourceManager/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/ComponentResourceManager/Overview/form1.cs b/snippets/csharp/System.ComponentModel/ComponentResourceManager/Overview/form1.cs
index 39199d98545..f3ae0e2e891 100644
--- a/snippets/csharp/System.ComponentModel/ComponentResourceManager/Overview/form1.cs
+++ b/snippets/csharp/System.ComponentModel/ComponentResourceManager/Overview/form1.cs
@@ -1,151 +1,146 @@
//
using System;
-using System.Collections.Generic;
using System.ComponentModel;
-using System.Data;
using System.Drawing;
-using System.Text;
using System.Windows.Forms;
-namespace WindowsApplication10
+namespace WindowsApplication10;
+
+public class Form1 : Form
{
- public class Form1 : Form
+ ToolStripButton toolStripButton1;
+ ToolStripButton toolStripButton2;
+ ToolStripButton toolStripButton3;
+ ContextMenuStrip contextMenuStrip1;
+ IContainer components;
+ ToolStripMenuItem toolStripMenuItem1;
+ ToolStripMenuItem toolStripMenuItem2;
+ ContextMenuStrip contextMenuStrip2;
+ ToolStripMenuItem rearrangeButtonsToolStripMenuItem;
+ ToolStripMenuItem selectIconsToolStripMenuItem;
+ ToolStrip toolStrip1;
+
+ public Form1() => InitializeComponent();
+ [STAThread]
+ static void Main()
{
- private ToolStripButton toolStripButton1;
- private ToolStripButton toolStripButton2;
- private ToolStripButton toolStripButton3;
- private ContextMenuStrip contextMenuStrip1;
- private IContainer components;
- private ToolStripMenuItem toolStripMenuItem1;
- private ToolStripMenuItem toolStripMenuItem2;
- private ContextMenuStrip contextMenuStrip2;
- private ToolStripMenuItem rearrangeButtonsToolStripMenuItem;
- private ToolStripMenuItem selectIconsToolStripMenuItem;
- private ToolStrip toolStrip1;
-
- public Form1()
- {
- InitializeComponent();
- }
- [STAThread]
- static void Main()
- {
- Application.EnableVisualStyles();
- Application.Run(new Form1());
- }
+ Application.EnableVisualStyles();
+ Application.Run(new Form1());
+ }
- private void InitializeComponent()
- {
- this.components = new System.ComponentModel.Container();
- System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
- this.toolStrip1 = new System.Windows.Forms.ToolStrip();
- this.toolStripButton1 = new System.Windows.Forms.ToolStripButton();
- this.toolStripButton2 = new System.Windows.Forms.ToolStripButton();
- this.toolStripButton3 = new System.Windows.Forms.ToolStripButton();
- this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
- this.contextMenuStrip2 = new System.Windows.Forms.ContextMenuStrip(this.components);
- this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
- this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripMenuItem();
- this.rearrangeButtonsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.selectIconsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
- this.toolStrip1.SuspendLayout();
- this.contextMenuStrip1.SuspendLayout();
- this.contextMenuStrip2.SuspendLayout();
- this.SuspendLayout();
- //
- //
- // Associate contextMenuStrip2 with toolStrip1.
- // toolStrip1 property settings follow.
- //
- this.toolStrip1.ContextMenuStrip = this.contextMenuStrip2;
- this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
- this.toolStripButton1,
- this.toolStripButton2,
- this.toolStripButton3});
- this.toolStrip1.Location = new System.Drawing.Point(0, 0);
- this.toolStrip1.Name = "toolStrip1";
- this.toolStrip1.Size = new System.Drawing.Size(292, 25);
- this.toolStrip1.TabIndex = 0;
- this.toolStrip1.Text = "toolStrip1";
- //
- //
- // toolStripButton1
- //
- this.toolStripButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
- this.toolStripButton1.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton1.Image")));
- this.toolStripButton1.ImageTransparentColor = System.Drawing.Color.Magenta;
- this.toolStripButton1.Name = "toolStripButton1";
- this.toolStripButton1.Text = "toolStripButton1";
- //
- // toolStripButton2
- //
- this.toolStripButton2.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
- this.toolStripButton2.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton2.Image")));
- this.toolStripButton2.ImageTransparentColor = System.Drawing.Color.Magenta;
- this.toolStripButton2.Name = "toolStripButton2";
- this.toolStripButton2.Text = "toolStripButton2";
- //
- // toolStripButton3
- //
- this.toolStripButton3.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
- this.toolStripButton3.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton3.Image")));
- this.toolStripButton3.ImageTransparentColor = System.Drawing.Color.Magenta;
- this.toolStripButton3.Name = "toolStripButton3";
- this.toolStripButton3.Text = "toolStripButton3";
- //
- // contextMenuStrip1
- //
- this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
- this.toolStripMenuItem1,
- this.toolStripMenuItem2});
- this.contextMenuStrip1.Name = "contextMenuStrip1";
- this.contextMenuStrip1.RightToLeft = System.Windows.Forms.RightToLeft.No;
- this.contextMenuStrip1.Size = new System.Drawing.Size(131, 48);
- //
- // contextMenuStrip2
- //
- this.contextMenuStrip2.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
- this.rearrangeButtonsToolStripMenuItem,
- this.selectIconsToolStripMenuItem});
- this.contextMenuStrip2.Name = "contextMenuStrip2";
- this.contextMenuStrip2.RightToLeft = System.Windows.Forms.RightToLeft.No;
- this.contextMenuStrip2.Size = new System.Drawing.Size(162, 48);
- //
- // toolStripMenuItem1
- //
- this.toolStripMenuItem1.Name = "toolStripMenuItem1";
- this.toolStripMenuItem1.Text = "&Resize";
- //
- // toolStripMenuItem2
- //
- this.toolStripMenuItem2.Name = "toolStripMenuItem2";
- this.toolStripMenuItem2.Text = "&Keep on Top";
- //
- // rearrangeButtonsToolStripMenuItem
- //
- this.rearrangeButtonsToolStripMenuItem.Name = "rearrangeButtonsToolStripMenuItem";
- this.rearrangeButtonsToolStripMenuItem.Text = "R&earrange Buttons";
- //
- // selectIconsToolStripMenuItem
- //
- this.selectIconsToolStripMenuItem.Name = "selectIconsToolStripMenuItem";
- this.selectIconsToolStripMenuItem.Text = "&Select Icons";
- //
- //
- // Associate contextMenuStrip1 with Form1.
- // Form1 property settings follow.
- //
- this.ClientSize = new System.Drawing.Size(292, 266);
- this.ContextMenuStrip = this.contextMenuStrip1;
- this.Controls.Add(this.toolStrip1);
- this.Name = "Form1";
- this.toolStrip1.ResumeLayout(false);
- this.contextMenuStrip1.ResumeLayout(false);
- this.contextMenuStrip2.ResumeLayout(false);
- this.ResumeLayout(false);
- this.PerformLayout();
- //
- }
+ void InitializeComponent()
+ {
+ components = new Container();
+ ComponentResourceManager resources = new(typeof(Form1));
+ toolStrip1 = new ToolStrip();
+ toolStripButton1 = new ToolStripButton();
+ toolStripButton2 = new ToolStripButton();
+ toolStripButton3 = new ToolStripButton();
+ contextMenuStrip1 = new ContextMenuStrip(components);
+ contextMenuStrip2 = new ContextMenuStrip(components);
+ toolStripMenuItem1 = new ToolStripMenuItem();
+ toolStripMenuItem2 = new ToolStripMenuItem();
+ rearrangeButtonsToolStripMenuItem = new ToolStripMenuItem();
+ selectIconsToolStripMenuItem = new ToolStripMenuItem();
+ toolStrip1.SuspendLayout();
+ contextMenuStrip1.SuspendLayout();
+ contextMenuStrip2.SuspendLayout();
+ SuspendLayout();
+ //
+ //
+ // Associate contextMenuStrip2 with toolStrip1.
+ // toolStrip1 property settings follow.
+ //
+ toolStrip1.ContextMenuStrip = contextMenuStrip2;
+ toolStrip1.Items.AddRange(
+ [
+ toolStripButton1,
+ toolStripButton2,
+ toolStripButton3
+ ]);
+ toolStrip1.Location = new Point(0, 0);
+ toolStrip1.Name = "toolStrip1";
+ toolStrip1.Size = new Size(292, 25);
+ toolStrip1.TabIndex = 0;
+ toolStrip1.Text = "toolStrip1";
+ //
+ //
+ // toolStripButton1
+ //
+ toolStripButton1.DisplayStyle = ToolStripItemDisplayStyle.Image;
+ toolStripButton1.Image = (Image)resources.GetObject("toolStripButton1.Image");
+ toolStripButton1.ImageTransparentColor = Color.Magenta;
+ toolStripButton1.Name = "toolStripButton1";
+ toolStripButton1.Text = "toolStripButton1";
+ //
+ // toolStripButton2
+ //
+ toolStripButton2.DisplayStyle = ToolStripItemDisplayStyle.Image;
+ toolStripButton2.Image = (Image)resources.GetObject("toolStripButton2.Image");
+ toolStripButton2.ImageTransparentColor = Color.Magenta;
+ toolStripButton2.Name = "toolStripButton2";
+ toolStripButton2.Text = "toolStripButton2";
+ //
+ // toolStripButton3
+ //
+ toolStripButton3.DisplayStyle = ToolStripItemDisplayStyle.Image;
+ toolStripButton3.Image = (Image)resources.GetObject("toolStripButton3.Image");
+ toolStripButton3.ImageTransparentColor = Color.Magenta;
+ toolStripButton3.Name = "toolStripButton3";
+ toolStripButton3.Text = "toolStripButton3";
+ //
+ // contextMenuStrip1
+ //
+ contextMenuStrip1.Items.AddRange([
+ toolStripMenuItem1,
+ toolStripMenuItem2]);
+ contextMenuStrip1.Name = "contextMenuStrip1";
+ contextMenuStrip1.RightToLeft = RightToLeft.No;
+ contextMenuStrip1.Size = new Size(131, 48);
+ //
+ // contextMenuStrip2
+ //
+ contextMenuStrip2.Items.AddRange([
+ rearrangeButtonsToolStripMenuItem,
+ selectIconsToolStripMenuItem]);
+ contextMenuStrip2.Name = "contextMenuStrip2";
+ contextMenuStrip2.RightToLeft = RightToLeft.No;
+ contextMenuStrip2.Size = new Size(162, 48);
+ //
+ // toolStripMenuItem1
+ //
+ toolStripMenuItem1.Name = "toolStripMenuItem1";
+ toolStripMenuItem1.Text = "&Resize";
+ //
+ // toolStripMenuItem2
+ //
+ toolStripMenuItem2.Name = "toolStripMenuItem2";
+ toolStripMenuItem2.Text = "&Keep on Top";
+ //
+ // rearrangeButtonsToolStripMenuItem
+ //
+ rearrangeButtonsToolStripMenuItem.Name = "rearrangeButtonsToolStripMenuItem";
+ rearrangeButtonsToolStripMenuItem.Text = "R&earrange Buttons";
+ //
+ // selectIconsToolStripMenuItem
+ //
+ selectIconsToolStripMenuItem.Name = "selectIconsToolStripMenuItem";
+ selectIconsToolStripMenuItem.Text = "&Select Icons";
+ //
+ //
+ // Associate contextMenuStrip1 with Form1.
+ // Form1 property settings follow.
+ //
+ ClientSize = new Size(292, 266);
+ ContextMenuStrip = contextMenuStrip1;
+ Controls.Add(toolStrip1);
+ Name = "Form1";
+ toolStrip1.ResumeLayout(false);
+ contextMenuStrip1.ResumeLayout(false);
+ contextMenuStrip2.ResumeLayout(false);
+ ResumeLayout(false);
+ PerformLayout();
+ //
}
}
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System.ComponentModel/DefaultEventAttribute/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/DefaultEventAttribute/Overview/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/DefaultEventAttribute/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/DefaultEventAttribute/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/DefaultEventAttribute/Overview/source.cs b/snippets/csharp/System.ComponentModel/DefaultEventAttribute/Overview/source.cs
index 97e92b9cf86..9bb3840fb73 100644
--- a/snippets/csharp/System.ComponentModel/DefaultEventAttribute/Overview/source.cs
+++ b/snippets/csharp/System.ComponentModel/DefaultEventAttribute/Overview/source.cs
@@ -1,40 +1,38 @@
using System;
-using System.Data;
using System.ComponentModel;
using System.Windows.Forms;
-public class MyClass {
+public static class MyClass
+{
//
[DefaultEvent("CollectionChanged")]
- public class MyCollection : BaseCollection {
-
- private CollectionChangeEventHandler onCollectionChanged;
-
- public event CollectionChangeEventHandler CollectionChanged {
- add {
- onCollectionChanged += value;
- }
- remove {
- onCollectionChanged -= value;
- }
+ public class MyCollection : BaseCollection
+ {
+ CollectionChangeEventHandler onCollectionChanged;
+
+ public event CollectionChangeEventHandler CollectionChanged
+ {
+ add => onCollectionChanged += value;
+ remove => onCollectionChanged -= value;
}
// Insert additional code.
}
//
//
- public static int Main() {
+ public static int Main()
+ {
// Creates a new collection.
- MyCollection myNewCollection = new MyCollection();
-
+ MyCollection myNewCollection = new();
+
// Gets the attributes for the collection.
AttributeCollection attributes = TypeDescriptor.GetAttributes(myNewCollection);
-
- /* Prints the name of the default event by retrieving the
+
+ /* Prints the name of the default event by retrieving the
* DefaultEventAttribute from the AttributeCollection. */
- DefaultEventAttribute myAttribute =
+ DefaultEventAttribute myAttribute =
(DefaultEventAttribute)attributes[typeof(DefaultEventAttribute)];
Console.WriteLine("The default event is: " + myAttribute.Name);
return 0;
- }
+ }
//
}
diff --git a/snippets/csharp/System.ComponentModel/DefaultPropertyAttribute/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/DefaultPropertyAttribute/Overview/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/DefaultPropertyAttribute/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/DefaultPropertyAttribute/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/DefaultPropertyAttribute/Overview/source.cs b/snippets/csharp/System.ComponentModel/DefaultPropertyAttribute/Overview/source.cs
index 66577d36668..1dbe6e63ee9 100644
--- a/snippets/csharp/System.ComponentModel/DefaultPropertyAttribute/Overview/source.cs
+++ b/snippets/csharp/System.ComponentModel/DefaultPropertyAttribute/Overview/source.cs
@@ -1,42 +1,43 @@
using System;
-using System.Data;
using System.ComponentModel;
using System.Windows.Forms;
-public class Form1: Form
+public class Form1 : Form
{
//
- public static int Main() {
+ public static int Main()
+ {
// Creates a new control.
- MyControl myNewControl = new MyControl();
-
+ MyControl myNewControl = new();
+
// Gets the attributes for the collection.
AttributeCollection attributes = TypeDescriptor.GetAttributes(myNewControl);
-
+
/* Prints the name of the default property by retrieving the
* DefaultPropertyAttribute from the AttributeCollection. */
- DefaultPropertyAttribute myAttribute =
+ DefaultPropertyAttribute myAttribute =
(DefaultPropertyAttribute)attributes[typeof(DefaultPropertyAttribute)];
Console.WriteLine("The default property is: " + myAttribute.Name);
-
+
return 0;
- }
+ }
//
//
[DefaultProperty("MyProperty")]
- public class MyControl : Control {
-
- public int MyProperty {
- get {
- // Insert code here.
- return 0;
- }
- set {
- // Insert code here.
- }
+ public class MyControl : Control
+ {
+ public int MyProperty
+ {
+ get =>
+ // Insert code here.
+ 0;
+ set
+ {
+ // Insert code here.
+ }
}
-
+
// Insert any additional code.
- }
+ }
//
}
diff --git a/snippets/csharp/System.ComponentModel/DefaultValueAttribute/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/DefaultValueAttribute/Overview/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/DefaultValueAttribute/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/DefaultValueAttribute/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/DefaultValueAttribute/Overview/source.cs b/snippets/csharp/System.ComponentModel/DefaultValueAttribute/Overview/source.cs
index 1828e23702d..26c5f61d595 100644
--- a/snippets/csharp/System.ComponentModel/DefaultValueAttribute/Overview/source.cs
+++ b/snippets/csharp/System.ComponentModel/DefaultValueAttribute/Overview/source.cs
@@ -1,39 +1,26 @@
using System;
-using System.Data;
using System.ComponentModel;
using System.Windows.Forms;
public class Form1 : Form
{
-//
-
- private bool _myVal = false;
-
+ //
[DefaultValue(false)]
- public bool MyProperty
- {
- get
- {
- return _myVal;
- }
- set
- {
- _myVal = value;
- }
- }
-//
+ public bool MyProperty { get; set; }
+ //
+
protected void Method()
{
-//
+ //
// Gets the attributes for the property.
AttributeCollection attributes =
TypeDescriptor.GetProperties(this)["MyProperty"].Attributes;
- /* Prints the default value by retrieving the DefaultValueAttribute
+ /* Prints the default value by retrieving the DefaultValueAttribute
* from the AttributeCollection. */
DefaultValueAttribute myAttribute =
- (DefaultValueAttribute) attributes[typeof(DefaultValueAttribute)];
+ (DefaultValueAttribute)attributes[typeof(DefaultValueAttribute)];
Console.WriteLine("The default value is: " + myAttribute.Value.ToString());
-//
+ //
}
}
diff --git a/snippets/csharp/System.ComponentModel/DescriptionAttribute/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/DescriptionAttribute/Overview/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/DescriptionAttribute/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/DescriptionAttribute/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/DescriptionAttribute/Overview/source.cs b/snippets/csharp/System.ComponentModel/DescriptionAttribute/Overview/source.cs
index 5511b57c8b4..c527addf583 100644
--- a/snippets/csharp/System.ComponentModel/DescriptionAttribute/Overview/source.cs
+++ b/snippets/csharp/System.ComponentModel/DescriptionAttribute/Overview/source.cs
@@ -1,36 +1,36 @@
using System;
-using System.Data;
using System.ComponentModel;
-using System.Windows.Forms;
using System.Drawing;
+using System.Windows.Forms;
-public class Form1: Form
- {
+public class Form1 : Form
+{
protected Image image1;
//
- [Description("The image associated with the control"),Category("Appearance")]
- public Image MyImage {
- get {
- // Insert code here.
- return image1;
+ [Description("The image associated with the control"), Category("Appearance")]
+ public Image MyImage
+ {
+ get =>
+ // Insert code here.
+ image1;
+ set
+ {
+ // Insert code here.
}
- set {
- // Insert code here.
- }
- }
+ }
//
- protected void Method()
- {
- //
- // Gets the attributes for the property.
- AttributeCollection attributes =
- TypeDescriptor.GetProperties(this)["MyImage"].Attributes;
-
- /* Prints the description by retrieving the DescriptionAttribute
- * from the AttributeCollection. */
- DescriptionAttribute myAttribute =
- (DescriptionAttribute)attributes[typeof(DescriptionAttribute)];
- Console.WriteLine(myAttribute.Description);
- //
- }
+ protected void Method()
+ {
+ //
+ // Gets the attributes for the property.
+ AttributeCollection attributes =
+ TypeDescriptor.GetProperties(this)["MyImage"].Attributes;
+
+ /* Prints the description by retrieving the DescriptionAttribute
+ * from the AttributeCollection. */
+ DescriptionAttribute myAttribute =
+ (DescriptionAttribute)attributes[typeof(DescriptionAttribute)];
+ Console.WriteLine(myAttribute.Description);
+ //
+ }
}
diff --git a/snippets/csharp/System.ComponentModel/DesignOnlyAttribute/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/DesignOnlyAttribute/Overview/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/DesignOnlyAttribute/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/DesignOnlyAttribute/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/DesignOnlyAttribute/Overview/source.cs b/snippets/csharp/System.ComponentModel/DesignOnlyAttribute/Overview/source.cs
index 0ee5357c23f..ac1bd85f2e1 100644
--- a/snippets/csharp/System.ComponentModel/DesignOnlyAttribute/Overview/source.cs
+++ b/snippets/csharp/System.ComponentModel/DesignOnlyAttribute/Overview/source.cs
@@ -1,7 +1,5 @@
using System;
-using System.Data;
using System.ComponentModel;
-using System.Windows.Forms;
using System.Globalization;
public class Class1
@@ -9,34 +7,35 @@ public class Class1
protected CultureInfo myCultureInfo;
//
[DesignOnly(true)]
- public CultureInfo GetLanguage {
- get {
- // Insert code here.
- return myCultureInfo;
- }
- set {
- // Insert code here.
+ public CultureInfo GetLanguage
+ {
+ get =>
+ // Insert code here.
+ myCultureInfo;
+ set
+ {
+ // Insert code here.
}
- }
+ }
//
- private int Property1
- {
+ int Property1
+ {
get
- {
+ {
//
// Gets the attributes for the property.
- AttributeCollection attributes =
- TypeDescriptor.GetProperties(this)["GetLanguage"].Attributes;
+ AttributeCollection attributes =
+ TypeDescriptor.GetProperties(this)["GetLanguage"].Attributes;
- /* Prints whether the property is marked as DesignOnly
- * by retrieving the DesignOnlyAttribute from the AttributeCollection. */
- DesignOnlyAttribute myAttribute =
- (DesignOnlyAttribute)attributes[typeof(DesignOnlyAttribute)];
- Console.WriteLine("This property is design only :" +
- myAttribute.IsDesignOnly.ToString());
- //
- return 1;
- }
+ /* Prints whether the property is marked as DesignOnly
+ * by retrieving the DesignOnlyAttribute from the AttributeCollection. */
+ DesignOnlyAttribute myAttribute =
+ (DesignOnlyAttribute)attributes[typeof(DesignOnlyAttribute)];
+ Console.WriteLine("This property is design only :" +
+ myAttribute.IsDesignOnly.ToString());
+ //
+ return 1;
}
+ }
}
diff --git a/snippets/csharp/System.ComponentModel/DesignerAttribute/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/DesignerAttribute/Overview/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/DesignerAttribute/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/DesignerAttribute/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/DesignerAttribute/Overview/source.cs b/snippets/csharp/System.ComponentModel/DesignerAttribute/Overview/source.cs
index 355f5ff800f..cf1c916616a 100644
--- a/snippets/csharp/System.ComponentModel/DesignerAttribute/Overview/source.cs
+++ b/snippets/csharp/System.ComponentModel/DesignerAttribute/Overview/source.cs
@@ -1,33 +1,34 @@
using System;
-using System.Data;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Windows.Forms;
-public class Class1
+public static class Class1
{
//
- [Designer("System.Windows.Forms.Design.DocumentDesigner, System.Windows.Forms.Design.DLL",
+ [Designer("System.Windows.Forms.Design.DocumentDesigner, System.Windows.Forms.Design.DLL",
typeof(IRootDesigner)),
DesignerCategory("Form")]
- public class MyForm : ContainerControl {
+ public class MyForm : ContainerControl
+ {
// Insert code here.
}
//
//
- public static int Main() {
+ public static int Main()
+ {
// Creates a new form.
- MyForm myNewForm = new MyForm();
-
+ MyForm myNewForm = new();
+
// Gets the attributes for the collection.
AttributeCollection attributes = TypeDescriptor.GetAttributes(myNewForm);
-
+
/* Prints the name of the designer by retrieving the DesignerAttribute
* from the AttributeCollection. */
- DesignerAttribute myAttribute =
+ DesignerAttribute myAttribute =
(DesignerAttribute)attributes[typeof(DesignerAttribute)];
Console.WriteLine("The designer for this class is: " + myAttribute.DesignerTypeName);
-
+
return 0;
}
//
diff --git a/snippets/csharp/System.ComponentModel/DesignerCategoryAttribute/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/DesignerCategoryAttribute/Overview/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/DesignerCategoryAttribute/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/DesignerCategoryAttribute/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/DesignerCategoryAttribute/Overview/source.cs b/snippets/csharp/System.ComponentModel/DesignerCategoryAttribute/Overview/source.cs
index bb48e7c654f..7b55918c39e 100644
--- a/snippets/csharp/System.ComponentModel/DesignerCategoryAttribute/Overview/source.cs
+++ b/snippets/csharp/System.ComponentModel/DesignerCategoryAttribute/Overview/source.cs
@@ -1,34 +1,35 @@
using System;
-using System.Data;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Windows.Forms;
-public class Class1
+public static class Class1
{
//
- [Designer("System.Windows.Forms.Design.DocumentDesigner, System.Windows.Forms.Design",
+ [Designer("System.Windows.Forms.Design.DocumentDesigner, System.Windows.Forms.Design",
typeof(IRootDesigner)),
DesignerCategory("Form")]
-
- public class MyForm : ContainerControl {
+
+ public class MyForm : ContainerControl
+ {
// Insert code here.
- }
+ }
//
//
- public static int Main() {
+ public static int Main()
+ {
// Creates a new form.
- MyForm myNewForm = new MyForm();
-
+ MyForm myNewForm = new();
+
// Gets the attributes for the collection.
AttributeCollection attributes = TypeDescriptor.GetAttributes(myNewForm);
-
+
/* Prints the name of the designer by retrieving the
* DesignerCategoryAttribute from the AttributeCollection. */
- DesignerCategoryAttribute myAttribute =
+ DesignerCategoryAttribute myAttribute =
(DesignerCategoryAttribute)attributes[typeof(DesignerCategoryAttribute)];
Console.WriteLine("The category of the designer for this class is: " + myAttribute.Category);
-
+
return 0;
}
//
diff --git a/snippets/csharp/System.ComponentModel/DesignerSerializationVisibilityAttribute/.ctor/Project.csproj b/snippets/csharp/System.ComponentModel/DesignerSerializationVisibilityAttribute/.ctor/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/DesignerSerializationVisibilityAttribute/.ctor/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/DesignerSerializationVisibilityAttribute/.ctor/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/DesignerSerializationVisibilityAttribute/.ctor/source.cs b/snippets/csharp/System.ComponentModel/DesignerSerializationVisibilityAttribute/.ctor/source.cs
index 05f8a0b61cb..a4fa7add4e4 100644
--- a/snippets/csharp/System.ComponentModel/DesignerSerializationVisibilityAttribute/.ctor/source.cs
+++ b/snippets/csharp/System.ComponentModel/DesignerSerializationVisibilityAttribute/.ctor/source.cs
@@ -1,20 +1,19 @@
-using System;
-using System.Data;
-using System.ComponentModel;
+using System.ComponentModel;
using System.Windows.Forms;
-public class Form1: Form
+public class Form1 : Form
{
//
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
- public int MyProperty {
- get {
- // Insert code here.
- return(0);
+ public int MyProperty
+ {
+ get =>
+ // Insert code here.
+ 0;
+ set
+ {
+ // Insert code here.
}
- set {
- // Insert code here.
- }
- }
+ }
//
}
diff --git a/snippets/csharp/System.ComponentModel/DesignerSerializationVisibilityAttribute/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/DesignerSerializationVisibilityAttribute/Overview/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/DesignerSerializationVisibilityAttribute/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/DesignerSerializationVisibilityAttribute/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/DesignerSerializationVisibilityAttribute/Overview/source.cs b/snippets/csharp/System.ComponentModel/DesignerSerializationVisibilityAttribute/Overview/source.cs
index 1685ab6c080..045bb66e3d0 100644
--- a/snippets/csharp/System.ComponentModel/DesignerSerializationVisibilityAttribute/Overview/source.cs
+++ b/snippets/csharp/System.ComponentModel/DesignerSerializationVisibilityAttribute/Overview/source.cs
@@ -1,88 +1,56 @@
//
-using System;
-using System.Collections;
using System.ComponentModel;
-using System.ComponentModel.Design;
using System.Drawing;
using System.Windows.Forms;
-namespace DesignerSerializationVisibilityTest
-{
- // The code for this user control declares a public property of type DimensionData with a DesignerSerializationVisibility
- // attribute set to DesignerSerializationVisibility.Content, indicating that the properties of the object should be serialized.
+namespace DesignerSerializationVisibilityTest;
- // The public, not hidden properties of the object that are set at design time will be persisted in the initialization code
- // for the class object. Content persistence will not work for structs without a custom TypeConverter.
+// The code for this user control declares a public property of type DimensionData with a DesignerSerializationVisibility
+// attribute set to DesignerSerializationVisibility.Content, indicating that the properties of the object should be serialized.
- public class ContentSerializationExampleControl : System.Windows.Forms.UserControl
- {
- private System.ComponentModel.Container components = null;
-
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
- public DimensionData Dimensions
- {
- get
- {
- return new DimensionData(this);
- }
- }
+// The public, not hidden properties of the object that are set at design time will be persisted in the initialization code
+// for the class object. Content persistence will not work for structs without a custom TypeConverter.
+
+public class ContentSerializationExampleControl : UserControl
+{
+ Container components;
+
+ [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
+ public DimensionData Dimensions => new(this);
- public ContentSerializationExampleControl()
- {
- InitializeComponent();
- }
-
- protected override void Dispose( bool disposing )
- {
- if( disposing )
- {
- if( components != null )
- components.Dispose();
- }
- base.Dispose( disposing );
- }
+ public ContentSerializationExampleControl() => InitializeComponent();
- private void InitializeComponent()
- {
- components = new System.ComponentModel.Container();
- }
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ components?.Dispose();
+ }
+ base.Dispose(disposing);
}
- [TypeConverterAttribute(typeof(System.ComponentModel.ExpandableObjectConverter))]
- // This attribute indicates that the public properties of this object should be listed in the property grid.
- public class DimensionData
- {
- private Control owner;
+ void InitializeComponent() => components = new Container();
+}
+
+[TypeConverter(typeof(ExpandableObjectConverter))]
+// This attribute indicates that the public properties of this object should be listed in the property grid.
+public class DimensionData
+{
+ readonly Control owner;
- // This class reads and writes the Location and Size properties from the Control which it is initialized to.
- internal DimensionData(Control owner)
- {
- this.owner = owner;
- }
+ // This class reads and writes the Location and Size properties from the Control which it is initialized to.
+ internal DimensionData(Control owner) => this.owner = owner;
- public Point Location
- {
- get
- {
- return owner.Location;
- }
- set
- {
- owner.Location = value;
- }
- }
+ public Point Location
+ {
+ get => owner.Location;
+ set => owner.Location = value;
+ }
- public Size FormSize
- {
- get
- {
- return owner.Size;
- }
- set
- {
- owner.Size = value;
- }
- }
+ public Size FormSize
+ {
+ get => owner.Size;
+ set => owner.Size = value;
}
}
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System.ComponentModel/DesignerSerializationVisibilityAttribute/Visibility/Project.csproj b/snippets/csharp/System.ComponentModel/DesignerSerializationVisibilityAttribute/Visibility/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/DesignerSerializationVisibilityAttribute/Visibility/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/DesignerSerializationVisibilityAttribute/Visibility/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/DesignerSerializationVisibilityAttribute/Visibility/source.cs b/snippets/csharp/System.ComponentModel/DesignerSerializationVisibilityAttribute/Visibility/source.cs
index e812092db94..9789911193e 100644
--- a/snippets/csharp/System.ComponentModel/DesignerSerializationVisibilityAttribute/Visibility/source.cs
+++ b/snippets/csharp/System.ComponentModel/DesignerSerializationVisibilityAttribute/Visibility/source.cs
@@ -1,31 +1,31 @@
-using System;
-using System.Data;
-using System.ComponentModel;
+using System.ComponentModel;
using System.Windows.Forms;
-public class Form1: Form
+public class Form1 : Form
{
- protected TextBox textBox1;
+ protected TextBox textBox1;
- protected void Method()
- {
-//
-// Gets the attributes for the property.
- AttributeCollection attributes =
- TypeDescriptor.GetProperties(this)["MyProperty"].Attributes;
-
- // Checks to see if the value of the DesignerSerializationVisibilityAttribute is set to Content.
- if(attributes[typeof(DesignerSerializationVisibilityAttribute)].Equals(DesignerSerializationVisibilityAttribute.Content)) {
- // Insert code here.
- }
-
- // This is another way to see whether the property is marked as serializing content.
- DesignerSerializationVisibilityAttribute myAttribute =
- (DesignerSerializationVisibilityAttribute)attributes[typeof(DesignerSerializationVisibilityAttribute)];
- if(myAttribute.Visibility == DesignerSerializationVisibility.Content) {
- // Insert code here.
- }
+ protected void Method()
+ {
+ //
+ // Gets the attributes for the property.
+ AttributeCollection attributes =
+ TypeDescriptor.GetProperties(this)["MyProperty"].Attributes;
-//
-}
+ // Checks to see if the value of the DesignerSerializationVisibilityAttribute is set to Content.
+ if (attributes[typeof(DesignerSerializationVisibilityAttribute)].Equals(DesignerSerializationVisibilityAttribute.Content))
+ {
+ // Insert code here.
+ }
+
+ // This is another way to see whether the property is marked as serializing content.
+ DesignerSerializationVisibilityAttribute myAttribute =
+ (DesignerSerializationVisibilityAttribute)attributes[typeof(DesignerSerializationVisibilityAttribute)];
+ if (myAttribute.Visibility == DesignerSerializationVisibility.Content)
+ {
+ // Insert code here.
+ }
+
+ //
+ }
}
diff --git a/snippets/csharp/System.ComponentModel/DoWorkEventArgs/Overview/Form1.cs b/snippets/csharp/System.ComponentModel/DoWorkEventArgs/Overview/Form1.cs
index 0e15e213aaf..6933cb6b72e 100644
--- a/snippets/csharp/System.ComponentModel/DoWorkEventArgs/Overview/Form1.cs
+++ b/snippets/csharp/System.ComponentModel/DoWorkEventArgs/Overview/Form1.cs
@@ -7,226 +7,215 @@
using System.Windows.Forms;
//
-namespace BackgroundWorkerExample
+namespace BackgroundWorkerExample;
+
+public class Form1 : Form
{
- public class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
+ public Form1() => InitializeComponent();
- //
- private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
- {
- // Do not access the form's BackgroundWorker reference directly.
- // Instead, use the reference provided by the sender parameter.
- BackgroundWorker bw = sender as BackgroundWorker;
+ //
+ void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
+ {
+ // Do not access the form's BackgroundWorker reference directly.
+ // Instead, use the reference provided by the sender parameter.
+ BackgroundWorker bw = sender as BackgroundWorker;
- // Extract the argument.
- int arg = (int)e.Argument;
+ // Extract the argument.
+ int arg = (int)e.Argument;
- // Start the time-consuming operation.
- e.Result = TimeConsumingOperation(bw, arg);
+ // Start the time-consuming operation.
+ e.Result = TimeConsumingOperation(bw, arg);
- // If the operation was canceled by the user,
- // set the DoWorkEventArgs.Cancel property to true.
- if (bw.CancellationPending)
- {
- e.Cancel = true;
- }
+ // If the operation was canceled by the user,
+ // set the DoWorkEventArgs.Cancel property to true.
+ if (bw.CancellationPending)
+ {
+ e.Cancel = true;
}
- //
-
- //
- // This event handler demonstrates how to interpret
- // the outcome of the asynchronous operation implemented
- // in the DoWork event handler.
- private void backgroundWorker1_RunWorkerCompleted(
- object sender,
- RunWorkerCompletedEventArgs e)
- {
- if (e.Cancelled)
- {
- // The user canceled the operation.
- MessageBox.Show("Operation was canceled");
- }
- else if (e.Error != null)
- {
- // There was an error during the operation.
- string msg = String.Format("An error occurred: {0}", e.Error.Message);
- MessageBox.Show(msg);
- }
- else
- {
- // The operation completed normally.
- string msg = String.Format("Result = {0}", e.Result);
- MessageBox.Show(msg);
- }
+ }
+ //
+
+ //
+ // This event handler demonstrates how to interpret
+ // the outcome of the asynchronous operation implemented
+ // in the DoWork event handler.
+ void backgroundWorker1_RunWorkerCompleted(
+ object sender,
+ RunWorkerCompletedEventArgs e)
+ {
+ if (e.Cancelled)
+ {
+ // The user canceled the operation.
+ _ = MessageBox.Show("Operation was canceled");
+ }
+ else if (e.Error != null)
+ {
+ // There was an error during the operation.
+ string msg = $"An error occurred: {e.Error.Message}";
+ _ = MessageBox.Show(msg);
}
- //
-
- //
- // This method models an operation that may take a long time
- // to run. It can be cancelled, it can raise an exception,
- // or it can exit normally and return a result. These outcomes
- // are chosen randomly.
- private int TimeConsumingOperation(
- BackgroundWorker bw,
- int sleepPeriod )
+ else
{
- int result = 0;
+ // The operation completed normally.
+ string msg = string.Format("Result = {0}", e.Result);
+ _ = MessageBox.Show(msg);
+ }
+ }
+ //
+
+ //
+ // This method models an operation that may take a long time
+ // to run. It can be cancelled, it can raise an exception,
+ // or it can exit normally and return a result. These outcomes
+ // are chosen randomly.
+ int TimeConsumingOperation(
+ BackgroundWorker bw,
+ int sleepPeriod)
+ {
+ int result = 0;
- Random rand = new Random();
+ Random rand = new();
- while (!bw.CancellationPending)
- {
- bool exit = false;
+ while (!bw.CancellationPending)
+ {
+ bool exit = false;
- switch (rand.Next(3))
- {
- // Raise an exception.
- case 0:
+ switch (rand.Next(3))
+ {
+ // Raise an exception.
+ case 0:
{
throw new Exception("An error condition occurred.");
- break;
}
- // Sleep for the number of milliseconds
- // specified by the sleepPeriod parameter.
- case 1:
+ // Sleep for the number of milliseconds
+ // specified by the sleepPeriod parameter.
+ case 1:
{
Thread.Sleep(sleepPeriod);
break;
}
- // Exit and return normally.
- case 2:
+ // Exit and return normally.
+ case 2:
{
result = 23;
exit = true;
break;
}
- default:
+ default:
{
break;
}
- }
-
- if( exit )
- {
- break;
- }
}
- return result;
- }
- //
-
- //
- private void startBtn_Click(object sender, EventArgs e)
- {
- this.backgroundWorker1.RunWorkerAsync(2000);
- }
- //
-
- //
- private void cancelBtn_Click(object sender, EventArgs e)
- {
- this.backgroundWorker1.CancelAsync();
- }
- //
-
- ///
- /// Required designer variable.
- ///
- private System.ComponentModel.IContainer components = null;
-
- ///
- /// Clean up any resources being used.
- ///
- /// true if managed resources should be disposed; otherwise, false.
- protected override void Dispose(bool disposing)
- {
- if (disposing && (components != null))
+ if (exit)
{
- components.Dispose();
+ break;
}
- base.Dispose(disposing);
}
- #region Windows Form Designer generated code
-
- ///
- /// Required method for Designer support - do not modify
- /// the contents of this method with the code editor.
- ///
- private void InitializeComponent()
+ return result;
+ }
+ //
+
+ //
+ void startBtn_Click(object sender, EventArgs e) => backgroundWorker1.RunWorkerAsync(2000);
+ //
+
+ //
+ void cancelBtn_Click(object sender, EventArgs e) => backgroundWorker1.CancelAsync();
+ //
+
+ ///
+ /// Required designer variable.
+ ///
+ readonly IContainer _components;
+
+ ///
+ /// Clean up any resources being used.
+ ///
+ /// true if managed resources should be disposed; otherwise, false.
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing && (_components != null))
{
- this.backgroundWorker1 = new System.ComponentModel.BackgroundWorker();
- this.startBtn = new System.Windows.Forms.Button();
- this.cancelBtn = new System.Windows.Forms.Button();
- this.SuspendLayout();
- //
- // backgroundWorker1
- //
- this.backgroundWorker1.WorkerSupportsCancellation = true;
- this.backgroundWorker1.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker1_DoWork);
- this.backgroundWorker1.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker1_RunWorkerCompleted);
- //
- // startBtn
- //
- this.startBtn.Location = new System.Drawing.Point(12, 12);
- this.startBtn.Name = "startBtn";
- this.startBtn.Size = new System.Drawing.Size(75, 23);
- this.startBtn.TabIndex = 0;
- this.startBtn.Text = "Start";
- this.startBtn.Click += new System.EventHandler(this.startBtn_Click);
- //
- // cancelBtn
- //
- this.cancelBtn.Location = new System.Drawing.Point(94, 11);
- this.cancelBtn.Name = "cancelBtn";
- this.cancelBtn.Size = new System.Drawing.Size(75, 23);
- this.cancelBtn.TabIndex = 1;
- this.cancelBtn.Text = "Cancel";
- this.cancelBtn.Click += new System.EventHandler(this.cancelBtn_Click);
- //
- // Form1
- //
- this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
- this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.ClientSize = new System.Drawing.Size(183, 49);
- this.Controls.Add(this.cancelBtn);
- this.Controls.Add(this.startBtn);
- this.Name = "Form1";
- this.Text = "Form1";
- this.ResumeLayout(false);
+ _components.Dispose();
}
+ base.Dispose(disposing);
+ }
- #endregion
+ #region Windows Form Designer generated code
- private System.ComponentModel.BackgroundWorker backgroundWorker1;
- private System.Windows.Forms.Button startBtn;
- private System.Windows.Forms.Button cancelBtn;
+ ///
+ /// Required method for Designer support - do not modify
+ /// the contents of this method with the code editor.
+ ///
+ void InitializeComponent()
+ {
+ backgroundWorker1 = new BackgroundWorker();
+ startBtn = new Button();
+ cancelBtn = new Button();
+ SuspendLayout();
+ //
+ // backgroundWorker1
+ //
+ backgroundWorker1.WorkerSupportsCancellation = true;
+ backgroundWorker1.DoWork += backgroundWorker1_DoWork;
+ backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;
+ //
+ // startBtn
+ //
+ startBtn.Location = new Point(12, 12);
+ startBtn.Name = "startBtn";
+ startBtn.Size = new Size(75, 23);
+ startBtn.TabIndex = 0;
+ startBtn.Text = "Start";
+ startBtn.Click += startBtn_Click;
+ //
+ // cancelBtn
+ //
+ cancelBtn.Location = new Point(94, 11);
+ cancelBtn.Name = "cancelBtn";
+ cancelBtn.Size = new Size(75, 23);
+ cancelBtn.TabIndex = 1;
+ cancelBtn.Text = "Cancel";
+ cancelBtn.Click += cancelBtn_Click;
+ //
+ // Form1
+ //
+ AutoScaleDimensions = new SizeF(6F, 13F);
+ AutoScaleMode = AutoScaleMode.Font;
+ ClientSize = new Size(183, 49);
+ Controls.Add(cancelBtn);
+ Controls.Add(startBtn);
+ Name = "Form1";
+ Text = "Form1";
+ ResumeLayout(false);
}
- public class Program
+ #endregion
+
+ BackgroundWorker backgroundWorker1;
+ Button startBtn;
+ Button cancelBtn;
+}
+
+public class Program
+{
+ Program()
{
- private Program()
- {
- }
+ }
- ///
- /// The main entry point for the application.
- ///
- [STAThread]
- static void Main()
- {
- Application.EnableVisualStyles();
- Application.Run(new Form1());
- }
+ ///
+ /// The main entry point for the application.
+ ///
+ [STAThread]
+ static void Main()
+ {
+ Application.EnableVisualStyles();
+ Application.Run(new Form1());
}
}
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System.ComponentModel/DoWorkEventArgs/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/DoWorkEventArgs/Overview/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/DoWorkEventArgs/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/DoWorkEventArgs/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/EditorAttribute/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/EditorAttribute/Overview/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/EditorAttribute/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/EditorAttribute/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/EditorAttribute/Overview/source.cs b/snippets/csharp/System.ComponentModel/EditorAttribute/Overview/source.cs
index 0d80c4ebd1f..04e70888d1a 100644
--- a/snippets/csharp/System.ComponentModel/EditorAttribute/Overview/source.cs
+++ b/snippets/csharp/System.ComponentModel/EditorAttribute/Overview/source.cs
@@ -1,35 +1,35 @@
using System;
-using System.Drawing;
-using System.Drawing.Design;
using System.ComponentModel;
-using System.Windows.Forms;
+using System.Drawing.Design;
-public class Class1{
+public static class Class1
+{
//
- [Editor("System.Windows.Forms.ImageEditorIndex, System.Design",
- typeof(UITypeEditor))]
+ [Editor("System.Windows.Forms.ImageEditorIndex, System.Design",
+ typeof(UITypeEditor))]
- public class MyImage
- {
- // Insert code here.
+ public class MyImage
+ {
+ // Insert code here.
}
//
//
- public static int Main() {
+ public static int Main()
+ {
// Creates a new component.
- MyImage myNewImage = new MyImage();
-
+ MyImage myNewImage = new();
+
// Gets the attributes for the component.
AttributeCollection attributes = TypeDescriptor.GetAttributes(myNewImage);
-
+
/* Prints the name of the editor by retrieving the EditorAttribute
* from the AttributeCollection. */
-
+
EditorAttribute myAttribute = (EditorAttribute)attributes[typeof(EditorAttribute)];
Console.WriteLine("The editor for this class is: " + myAttribute.EditorTypeName);
-
+
return 0;
- }
+ }
//
}
diff --git a/snippets/csharp/System.ComponentModel/EditorBrowsableAttribute/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/EditorBrowsableAttribute/Overview/Project.csproj
index c02dc5044e7..5a1b02db677 100644
--- a/snippets/csharp/System.ComponentModel/EditorBrowsableAttribute/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/EditorBrowsableAttribute/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0
+ net8.0
\ No newline at end of file
diff --git a/snippets/csharp/System.ComponentModel/EditorBrowsableAttribute/Overview/ctleditorbrowsable.cs b/snippets/csharp/System.ComponentModel/EditorBrowsableAttribute/Overview/ctleditorbrowsable.cs
index d33e486603b..96e2d913c1a 100644
--- a/snippets/csharp/System.ComponentModel/EditorBrowsableAttribute/Overview/ctleditorbrowsable.cs
+++ b/snippets/csharp/System.ComponentModel/EditorBrowsableAttribute/Overview/ctleditorbrowsable.cs
@@ -1,22 +1,21 @@
//
using System.ComponentModel;
-namespace EditorBrowsableDemo
+namespace EditorBrowsableDemo;
+
+public class Class1
{
- public class Class1
- {
- public Class1() { }
+ public Class1() { }
- [EditorBrowsable(EditorBrowsableState.Never)]
- public int Age
- {
- get; set;
- }
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public int Age
+ {
+ get; set;
+ }
- public int Height
- {
- get; set;
- }
+ public int Height
+ {
+ get; set;
}
}
//
diff --git a/snippets/csharp/System.ComponentModel/EventDescriptor/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/EventDescriptor/Overview/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/EventDescriptor/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/EventDescriptor/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/EventDescriptor/Overview/eventdescriptor.cs b/snippets/csharp/System.ComponentModel/EventDescriptor/Overview/eventdescriptor.cs
index 974eeba91ee..e3fb7f9f946 100644
--- a/snippets/csharp/System.ComponentModel/EventDescriptor/Overview/eventdescriptor.cs
+++ b/snippets/csharp/System.ComponentModel/EventDescriptor/Overview/eventdescriptor.cs
@@ -1,110 +1,98 @@
using System;
-using System.Drawing;
-using System.Collections;
using System.ComponentModel;
+using System.Drawing;
using System.Windows.Forms;
-using System.Data;
-namespace EventDescriptor
-{
- ///
- /// Summary description for Form1.
- ///
- public class Form1 : System.Windows.Forms.Form
- {
- private System.Windows.Forms.Button button1;
- private System.Windows.Forms.TextBox textBox1;
- ///
- /// Required designer variable.
- ///
- private System.ComponentModel.Container components = null;
+namespace EventDescriptor;
- public Form1()
- {
- //
- // Required for Windows Form Designer support
- //
- InitializeComponent();
+///
+/// Summary description for Form1.
+///
+public class Form1 : Form
+{
+ Button button1;
+ TextBox textBox1;
+ ///
+ /// Required designer variable.
+ ///
+ readonly Container _components;
- //
- // TODO: Add any constructor code after InitializeComponent call
- //
- }
+ public Form1() =>
+ //
+ // Required for Windows Form Designer support
+ //
+ InitializeComponent();
- ///
- /// Clean up any resources being used.
- ///
- protected override void Dispose( bool disposing )
- {
- if( disposing )
- {
- if (components != null)
- {
- components.Dispose();
- }
- }
- base.Dispose( disposing );
- }
+ ///
+ /// Clean up any resources being used.
+ ///
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ _components?.Dispose();
+ }
+ base.Dispose(disposing);
+ }
- #region Windows Form Designer generated code
- ///
- /// Required method for Designer support - do not modify
- /// the contents of this method with the code editor.
- ///
- private void InitializeComponent()
- {
- this.button1 = new System.Windows.Forms.Button();
- this.textBox1 = new System.Windows.Forms.TextBox();
- this.SuspendLayout();
- //
- // button1
- //
- this.button1.Name = "button1";
- this.button1.TabIndex = 0;
- this.button1.Text = "button1";
- //
- // textBox1
- //
- this.textBox1.Location = new System.Drawing.Point(8, 96);
- this.textBox1.Multiline = true;
- this.textBox1.Name = "textBox1";
- this.textBox1.Size = new System.Drawing.Size(608, 160);
- this.textBox1.TabIndex = 1;
- this.textBox1.Text = "textBox1";
- //
- // Form1
- //
- this.ClientSize = new System.Drawing.Size(632, 273);
- this.Controls.AddRange(new System.Windows.Forms.Control[] {
- this.textBox1,
- this.button1});
- this.Name = "Form1";
- this.Text = "Form1";
- this.Load += new System.EventHandler(this.Form1_Load);
- this.ResumeLayout(false);
- }
- #endregion
+ #region Windows Form Designer generated code
+ ///
+ /// Required method for Designer support - do not modify
+ /// the contents of this method with the code editor.
+ ///
+ void InitializeComponent()
+ {
+ button1 = new Button();
+ textBox1 = new TextBox();
+ SuspendLayout();
+ //
+ // button1
+ //
+ button1.Name = "button1";
+ button1.TabIndex = 0;
+ button1.Text = "button1";
+ //
+ // textBox1
+ //
+ textBox1.Location = new Point(8, 96);
+ textBox1.Multiline = true;
+ textBox1.Name = "textBox1";
+ textBox1.Size = new Size(608, 160);
+ textBox1.TabIndex = 1;
+ textBox1.Text = "textBox1";
+ //
+ // Form1
+ //
+ ClientSize = new Size(632, 273);
+ Controls.AddRange(
+ [
+ textBox1,
+ button1
+ ]);
+ Name = "Form1";
+ Text = "Form1";
+ Load += Form1_Load;
+ ResumeLayout(false);
+ }
+ #endregion
- ///
- /// The main entry point for the application.
- ///
- [STAThread]
- static void Main()
- {
- Application.Run(new Form1());
- }
+ ///
+ /// The main entry point for the application.
+ ///
+ [STAThread]
+ static void Main() => Application.Run(new Form1());
- private void Form1_Load(object sender, System.EventArgs e)
- {
-//
-EventDescriptorCollection events = TypeDescriptor.GetEvents(button1);
-// Displays each event's information in the collection in a text box.
-foreach (System.ComponentModel.EventDescriptor myEvent in events) {
- textBox1.Text += myEvent.Category + '\n';
- textBox1.Text += myEvent.Description + '\n';
- textBox1.Text += myEvent.DisplayName + '\n';
-}
-//
- }
- }
+ void Form1_Load(object sender, EventArgs e)
+ {
+ //
+ EventDescriptorCollection events = TypeDescriptor.GetEvents(button1);
+ // Displays each event's information in the collection in a text box.
+ foreach (System.ComponentModel.EventDescriptor myEvent in events)
+ {
+ textBox1.Text += myEvent.Category + '\n';
+ textBox1.Text += myEvent.Description + '\n';
+ textBox1.Text += myEvent.DisplayName + '\n';
+ }
+ //
+ }
}
diff --git a/snippets/csharp/System.ComponentModel/EventDescriptorCollection/.ctor/Project.csproj b/snippets/csharp/System.ComponentModel/EventDescriptorCollection/.ctor/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/EventDescriptorCollection/.ctor/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/EventDescriptorCollection/.ctor/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/EventDescriptorCollection/.ctor/source.cs b/snippets/csharp/System.ComponentModel/EventDescriptorCollection/.ctor/source.cs
index f5ce49e51d5..aac2d2d8607 100644
--- a/snippets/csharp/System.ComponentModel/EventDescriptorCollection/.ctor/source.cs
+++ b/snippets/csharp/System.ComponentModel/EventDescriptorCollection/.ctor/source.cs
@@ -1,18 +1,15 @@
-using System;
-using System.Data;
-using System.ComponentModel;
+using System.ComponentModel;
using System.Windows.Forms;
-public class Form1: Form
+public class Form1 : Form
{
- protected TextBox textBox1;
- protected Button button1;
+ protected TextBox textBox1;
+ protected Button button1;
- protected void Method()
-{
-//
-EventDescriptorCollection events = TypeDescriptor.GetEvents(button1);
-
-//
-}
+ protected void Method()
+ {
+ //
+ _ = TypeDescriptor.GetEvents(button1);
+ //
+ }
}
diff --git a/snippets/csharp/System.ComponentModel/EventDescriptorCollection/Count/Project.csproj b/snippets/csharp/System.ComponentModel/EventDescriptorCollection/Count/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/EventDescriptorCollection/Count/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/EventDescriptorCollection/Count/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/EventDescriptorCollection/Count/source.cs b/snippets/csharp/System.ComponentModel/EventDescriptorCollection/Count/source.cs
index e1b495cf1f5..e114376aad1 100644
--- a/snippets/csharp/System.ComponentModel/EventDescriptorCollection/Count/source.cs
+++ b/snippets/csharp/System.ComponentModel/EventDescriptorCollection/Count/source.cs
@@ -1,20 +1,19 @@
-using System;
-using System.Data;
-using System.ComponentModel;
+using System.ComponentModel;
using System.Windows.Forms;
-public class Form1: Form
+public class Form1 : Form
{
- protected TextBox textBox1;
- protected Button button1;
-//
-private void GetCount() {
- // Creates a new collection and assigns it the events for button1.
- EventDescriptorCollection events = TypeDescriptor.GetEvents(button1);
-
- // Prints the number of events on button1 in a text box.
- textBox1.Text = events.Count.ToString();
- }
+ protected TextBox textBox1;
+ protected Button button1;
+ //
+ void GetCount()
+ {
+ // Creates a new collection and assigns it the events for button1.
+ EventDescriptorCollection events = TypeDescriptor.GetEvents(button1);
-//
+ // Prints the number of events on button1 in a text box.
+ textBox1.Text = events.Count.ToString();
+ }
+
+ //
}
diff --git a/snippets/csharp/System.ComponentModel/EventDescriptorCollection/Find/Project.csproj b/snippets/csharp/System.ComponentModel/EventDescriptorCollection/Find/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/EventDescriptorCollection/Find/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/EventDescriptorCollection/Find/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/EventDescriptorCollection/Find/source.cs b/snippets/csharp/System.ComponentModel/EventDescriptorCollection/Find/source.cs
index 22223ac71bc..54f747366f5 100644
--- a/snippets/csharp/System.ComponentModel/EventDescriptorCollection/Find/source.cs
+++ b/snippets/csharp/System.ComponentModel/EventDescriptorCollection/Find/source.cs
@@ -1,23 +1,22 @@
-using System;
-using System.Data;
-using System.ComponentModel;
+using System.ComponentModel;
using System.Windows.Forms;
-public class Form1: Form
+public class Form1 : Form
{
- protected TextBox textBox1;
- protected Button button1;
-//
-private void FindEvent() {
- // Creates a new collection and assigns it the events for button1.
- EventDescriptorCollection events = TypeDescriptor.GetEvents(button1);
-
- // Sets an EventDescriptor to the specific event.
- EventDescriptor myEvent = events.Find("Resize", false);
-
- // Prints the event name and event description.
- textBox1.Text = myEvent.Name + ": " + myEvent.Description;
- }
+ protected TextBox textBox1;
+ protected Button button1;
+ //
+ void FindEvent()
+ {
+ // Creates a new collection and assigns it the events for button1.
+ EventDescriptorCollection events = TypeDescriptor.GetEvents(button1);
-//
+ // Sets an EventDescriptor to the specific event.
+ EventDescriptor myEvent = events.Find("Resize", false);
+
+ // Prints the event name and event description.
+ textBox1.Text = myEvent.Name + ": " + myEvent.Description;
+ }
+
+ //
}
diff --git a/snippets/csharp/System.ComponentModel/EventDescriptorCollection/GetEnumerator/Project.csproj b/snippets/csharp/System.ComponentModel/EventDescriptorCollection/GetEnumerator/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/EventDescriptorCollection/GetEnumerator/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/EventDescriptorCollection/GetEnumerator/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/EventDescriptorCollection/GetEnumerator/source.cs b/snippets/csharp/System.ComponentModel/EventDescriptorCollection/GetEnumerator/source.cs
index 3c34871ebf5..b8a2c8c0c10 100644
--- a/snippets/csharp/System.ComponentModel/EventDescriptorCollection/GetEnumerator/source.cs
+++ b/snippets/csharp/System.ComponentModel/EventDescriptorCollection/GetEnumerator/source.cs
@@ -1,27 +1,28 @@
-using System;
-using System.Collections;
+using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
-public class Form1: Form
+public class Form1 : Form
{
- protected TextBox textBox1;
- protected Button button1;
-//
-private void MyEnumerator() {
- // Creates a new collection, and assigns to it the events for button1.
- EventDescriptorCollection events = TypeDescriptor.GetEvents(button1);
-
- // Creates an enumerator.
- IEnumerator ie = events.GetEnumerator();
-
- // Prints the name of each event in the collection.
- Object myEvent;
- while(ie.MoveNext()) {
- myEvent = ie.Current;
- textBox1.Text += myEvent.ToString() + '\n';
+ protected TextBox textBox1;
+ protected Button button1;
+ //
+ void MyEnumerator()
+ {
+ // Creates a new collection, and assigns to it the events for button1.
+ EventDescriptorCollection events = TypeDescriptor.GetEvents(button1);
+
+ // Creates an enumerator.
+ IEnumerator ie = events.GetEnumerator();
+
+ // Prints the name of each event in the collection.
+ object myEvent;
+ while (ie.MoveNext())
+ {
+ myEvent = ie.Current;
+ textBox1.Text += myEvent.ToString() + '\n';
+ }
}
- }
-//
+ //
}
diff --git a/snippets/csharp/System.ComponentModel/EventDescriptorCollection/InternalSort/Project.csproj b/snippets/csharp/System.ComponentModel/EventDescriptorCollection/InternalSort/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/EventDescriptorCollection/InternalSort/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/EventDescriptorCollection/InternalSort/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/EventDescriptorCollection/InternalSort/source.cs b/snippets/csharp/System.ComponentModel/EventDescriptorCollection/InternalSort/source.cs
index ad04190681d..4826476ba89 100644
--- a/snippets/csharp/System.ComponentModel/EventDescriptorCollection/InternalSort/source.cs
+++ b/snippets/csharp/System.ComponentModel/EventDescriptorCollection/InternalSort/source.cs
@@ -1,16 +1,15 @@
-using System;
-using System.Data;
-using System.ComponentModel;
-using System.Windows.Forms;
+using System.ComponentModel;
-public abstract class Coll1: EventDescriptorCollection {
-
- public Coll1() : base(null) {
+public abstract class Coll1 : EventDescriptorCollection
+{
+ public Coll1() : base(null)
+ {
}
- protected void Method() {
+ protected void Method()
+ {
//
- this.InternalSort(new string[]{"D", "B"});
+ InternalSort(["D", "B"]);
//
}
}
diff --git a/snippets/csharp/System.ComponentModel/EventDescriptorCollection/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/EventDescriptorCollection/Overview/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/EventDescriptorCollection/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/EventDescriptorCollection/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/EventDescriptorCollection/Overview/source.cs b/snippets/csharp/System.ComponentModel/EventDescriptorCollection/Overview/source.cs
index ed3a42f4c54..94d70848aca 100644
--- a/snippets/csharp/System.ComponentModel/EventDescriptorCollection/Overview/source.cs
+++ b/snippets/csharp/System.ComponentModel/EventDescriptorCollection/Overview/source.cs
@@ -1,21 +1,22 @@
-using System;
-using System.Data;
-using System.ComponentModel;
+using System.ComponentModel;
using System.Windows.Forms;
-public class Form1: Form
+public class Form1 : Form
{
- protected TextBox textBox1;
- protected Button button1;
-//
-private void MyEventCollection() {
- // Creates a new collection and assigns it the events for button1.
- EventDescriptorCollection events = TypeDescriptor.GetEvents(button1);
-
- // Displays each event in the collection in a text box.
- foreach (EventDescriptor myEvent in events)
- textBox1.Text += myEvent.Name + '\n';
- }
+ protected TextBox textBox1;
+ protected Button button1;
+ //
+ void MyEventCollection()
+ {
+ // Creates a new collection and assigns it the events for button1.
+ EventDescriptorCollection events = TypeDescriptor.GetEvents(button1);
-//
+ // Displays each event in the collection in a text box.
+ foreach (EventDescriptor myEvent in events)
+ {
+ textBox1.Text += myEvent.Name + '\n';
+ }
+ }
+
+ //
}
diff --git a/snippets/csharp/System.ComponentModel/EventDescriptorCollection/Sort/Project.csproj b/snippets/csharp/System.ComponentModel/EventDescriptorCollection/Sort/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/EventDescriptorCollection/Sort/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/EventDescriptorCollection/Sort/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/EventDescriptorCollection/Sort/source.cs b/snippets/csharp/System.ComponentModel/EventDescriptorCollection/Sort/source.cs
index 57893514506..2d3267254e9 100644
--- a/snippets/csharp/System.ComponentModel/EventDescriptorCollection/Sort/source.cs
+++ b/snippets/csharp/System.ComponentModel/EventDescriptorCollection/Sort/source.cs
@@ -1,17 +1,16 @@
-using System;
-using System.Data;
-using System.ComponentModel;
-using System.Windows.Forms;
+using System.ComponentModel;
-public abstract class Coll1: EventDescriptorCollection
+public abstract class Coll1 : EventDescriptorCollection
{
- protected Object myNewColl;
+ protected object myNewColl;
- public Coll1() : base(null) {
+ public Coll1() : base(null)
+ {
}
- protected void Method() {
+ protected void Method()
+ {
//
- myNewColl = this.Sort(new string[]{"D", "B"});
+ myNewColl = Sort(["D", "B"]);
//
}
}
diff --git a/snippets/csharp/System.ComponentModel/ExpandableObjectConverter/Overview/DemoControl.cs b/snippets/csharp/System.ComponentModel/ExpandableObjectConverter/Overview/DemoControl.cs
index cecd025e7e9..8e5e9feb721 100644
--- a/snippets/csharp/System.ComponentModel/ExpandableObjectConverter/Overview/DemoControl.cs
+++ b/snippets/csharp/System.ComponentModel/ExpandableObjectConverter/Overview/DemoControl.cs
@@ -5,136 +5,108 @@
using System.Globalization;
using System.Windows.Forms;
-namespace ExpandableObjectDemo
+namespace ExpandableObjectDemo;
+
+public partial class DemoControl : UserControl
{
- public partial class DemoControl : UserControl
- {
- BorderAppearance borderAppearanceValue = new BorderAppearance();
- private System.ComponentModel.IContainer components = null;
+ Container components;
- public DemoControl()
- {
- InitializeComponent();
- }
+ public DemoControl() => InitializeComponent();
- protected override void Dispose(bool disposing)
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing && (components != null))
{
- if (disposing && (components != null))
- {
- components.Dispose();
- }
- base.Dispose(disposing);
+ components.Dispose();
}
+ base.Dispose(disposing);
+ }
- //
- [Browsable(true)]
- [EditorBrowsable(EditorBrowsableState.Always)]
- [Category("Demo")]
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
- public BorderAppearance Border
- {
- get
- {
- return this.borderAppearanceValue;
- }
-
- set
- {
- this.borderAppearanceValue = value;
- }
- }
- //
+ //
+ [Browsable(true)]
+ [EditorBrowsable(EditorBrowsableState.Always)]
+ [Category("Demo")]
+ [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
+ public BorderAppearance Border { get; set; } = new();
+ //
- private void InitializeComponent()
- {
- components = new System.ComponentModel.Container();
- this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- }
+ void InitializeComponent()
+ {
+ components = new Container();
+ AutoScaleMode = AutoScaleMode.Font;
}
+}
- //
- [TypeConverter(typeof(BorderAppearanceConverter))]
- public class BorderAppearance
- {
- private int borderSizeValue = 1;
- private Color borderColorValue = Color.Empty;
+//
+[TypeConverter(typeof(BorderAppearanceConverter))]
+public class BorderAppearance
+{
+ int borderSizeValue = 1;
+ Color borderColorValue = Color.Empty;
- [Browsable(true),
- NotifyParentProperty(true),
- EditorBrowsable(EditorBrowsableState.Always),
- DefaultValue(1)]
- public int BorderSize
+ [Browsable(true),
+ NotifyParentProperty(true),
+ EditorBrowsable(EditorBrowsableState.Always),
+ DefaultValue(1)]
+ public int BorderSize
+ {
+ get => borderSizeValue;
+ set
{
- get
+ if (value < 0)
{
- return borderSizeValue;
+ throw new ArgumentOutOfRangeException(
+ "BorderSize",
+ value,
+ "must be >= 0");
}
- set
- {
- if (value < 0)
- {
- throw new ArgumentOutOfRangeException(
- "BorderSize",
- value,
- "must be >= 0");
- }
- if (borderSizeValue != value)
- {
- borderSizeValue = value;
- }
- }
- }
-
- [Browsable(true)]
- [NotifyParentProperty(true)]
- [EditorBrowsable(EditorBrowsableState.Always)]
- [DefaultValue(typeof(Color), "")]
- public Color BorderColor
- {
- get
+ if (borderSizeValue != value)
{
- return borderColorValue;
- }
- set
- {
- if (value.Equals(Color.Transparent))
- {
- throw new NotSupportedException("Transparent colors are not supported.");
- }
-
- if (borderColorValue != value)
- {
- borderColorValue = value;
- }
+ borderSizeValue = value;
}
}
}
- //
- //
- public class BorderAppearanceConverter : ExpandableObjectConverter
+ [Browsable(true)]
+ [NotifyParentProperty(true)]
+ [EditorBrowsable(EditorBrowsableState.Always)]
+ [DefaultValue(typeof(Color), "")]
+ public Color BorderColor
{
- // This override prevents the PropertyGrid from
- // displaying the full type name in the value cell.
- public override object ConvertTo(
- ITypeDescriptorContext context,
- CultureInfo culture,
- object value,
- Type destinationType)
+ get => borderColorValue;
+ set
{
- if (destinationType == typeof(string))
+ if (value.Equals(Color.Transparent))
{
- return "";
+ throw new NotSupportedException("Transparent colors are not supported.");
}
- return base.ConvertTo(
- context,
- culture,
- value,
- destinationType);
+ if (borderColorValue != value)
+ {
+ borderColorValue = value;
+ }
}
}
- //
}
-//
\ No newline at end of file
+//
+
+//
+public class BorderAppearanceConverter : ExpandableObjectConverter
+{
+ // This override prevents the PropertyGrid from
+ // displaying the full type name in the value cell.
+ public override object ConvertTo(
+ ITypeDescriptorContext context,
+ CultureInfo culture,
+ object value,
+ Type destinationType) => destinationType == typeof(string)
+ ? ""
+ : base.ConvertTo(
+ context,
+ culture,
+ value,
+ destinationType);
+}
+//
+//
diff --git a/snippets/csharp/System.ComponentModel/ExpandableObjectConverter/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/ExpandableObjectConverter/Overview/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/ExpandableObjectConverter/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/ExpandableObjectConverter/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/IBindingList/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/IBindingList/Overview/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/IBindingList/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/IBindingList/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/IBindingList/Overview/binding_editable.cs b/snippets/csharp/System.ComponentModel/IBindingList/Overview/binding_editable.cs
index 66c46681be9..4272b71dc49 100644
--- a/snippets/csharp/System.ComponentModel/IBindingList/Overview/binding_editable.cs
+++ b/snippets/csharp/System.ComponentModel/IBindingList/Overview/binding_editable.cs
@@ -1,422 +1,305 @@
using System;
-using System.Drawing;
using System.Collections;
using System.ComponentModel;
-using System.Windows.Forms;
-using System.Data;
+using System.Drawing;
using System.IO;
+using System.Windows.Forms;
+
+namespace IBindingList_Doc;
+
+///
+/// Summary description for Form1.
+///
+public class Form1 : Form
+{
+ ///
+ /// Required designer variable.
+ ///
+ readonly Container _components;
+
+ public Form1()
+ {
+ InitializeComponent();
+ }
+
+ ///
+ /// Clean up any resources being used.
+ ///
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ _components?.Dispose();
+ }
+ base.Dispose(disposing);
+ }
+
+ #region Windows Form Designer generated code
+ ///
+ /// Required method for Designer support - do not modify
+ /// the contents of this method with the code editor.
+ ///
+ void InitializeComponent()
+ {
+ //
+ // Form1
+ //
+ ClientSize = new Size(292, 273);
+ Name = "Form1";
+ Text = "Form1";
+ Load += Form1_Load;
+ }
+ #endregion
+
+ ///
+ /// The main entry point for the application.
+ ///
+ [STAThread]
+ static void Main() => Application.Run(new Form1());
+
+ void Form1_Load(object sender, EventArgs e)
+ {
+ }
+}
-namespace IBindingList_Doc
+// sample for IEditableObject
+//
+public class Customer : IEditableObject
{
- ///
- /// Summary description for Form1.
- ///
- public class Form1 : System.Windows.Forms.Form
- {
- ///
- /// Required designer variable.
- ///
- private System.ComponentModel.Container components = null;
-
- public Form1()
- {
- //
- // Required for Windows Form Designer support
- //
- InitializeComponent();
-
- //
- // TODO: Add any constructor code after InitializeComponent call
- //
- }
-
- ///
- /// Clean up any resources being used.
- ///
- protected override void Dispose( bool disposing )
- {
- if( disposing )
- {
- if (components != null)
- {
- components.Dispose();
- }
- }
- base.Dispose( disposing );
- }
-
- #region Windows Form Designer generated code
- ///
- /// Required method for Designer support - do not modify
- /// the contents of this method with the code editor.
- ///
- private void InitializeComponent()
- {
- //
- // Form1
- //
- this.ClientSize = new System.Drawing.Size(292, 273);
- this.Name = "Form1";
- this.Text = "Form1";
- this.Load += new System.EventHandler(this.Form1_Load);
- }
- #endregion
-
- ///
- /// The main entry point for the application.
- ///
- [STAThread]
- static void Main()
- {
- Application.Run(new Form1());
- }
-
- private void Form1_Load(object sender, System.EventArgs e)
- {
- }
- }
-
- // sample for IEditableObject
- //
- public class Customer : IEditableObject
- {
-
- struct CustomerData
- {
- internal string id ;
- internal string firstName ;
- internal string lastName ;
- }
-
- private CustomersList parent;
- private CustomerData custData;
- private CustomerData backupData;
- private bool inTxn = false;
-
- // Implements IEditableObject
- void IEditableObject.BeginEdit()
- {
- Console.WriteLine("Start BeginEdit");
- if (!inTxn)
- {
- this.backupData = custData;
- inTxn = true;
- Console.WriteLine("BeginEdit - " + this.backupData.lastName);
- }
- Console.WriteLine("End BeginEdit");
- }
-
- void IEditableObject.CancelEdit()
- {
- Console.WriteLine("Start CancelEdit");
- if (inTxn)
- {
- this.custData = backupData;
- inTxn = false;
- Console.WriteLine("CancelEdit - " + this.custData.lastName);
- }
- Console.WriteLine("End CancelEdit");
- }
-
- void IEditableObject.EndEdit()
- {
- Console.WriteLine("Start EndEdit" + this.custData.id + this.custData.lastName);
- if (inTxn)
- {
- backupData = new CustomerData();
- inTxn = false;
- Console.WriteLine("Done EndEdit - " + this.custData.id + this.custData.lastName);
- }
- Console.WriteLine("End EndEdit");
- }
-
- public Customer(string ID) : base()
- {
- this.custData = new CustomerData();
- this.custData.id = ID;
- this.custData.firstName = "";
- this.custData.lastName = "";
- }
-
- public string ID
- {
- get
- {
- return this.custData.id;
- }
- }
-
- public string FirstName
- {
- get
- {
- return this.custData.firstName;
- }
- set
- {
- this.custData.firstName = value;
- this.OnCustomerChanged();
- }
- }
-
- public string LastName
- {
- get
- {
- return this.custData.lastName;
- }
- set
- {
- this.custData.lastName = value;
- this.OnCustomerChanged();
- }
- }
-
- internal CustomersList Parent
- {
- get
- {
- return parent;
- }
- set
- {
- parent = value ;
- }
- }
-
- private void OnCustomerChanged()
- {
- if (!inTxn && Parent != null)
- {
- Parent.CustomerChanged(this);
- }
- }
-
- public override string ToString()
- {
- StringWriter sb = new StringWriter();
- sb.Write(this.FirstName);
- sb.Write(" ");
- sb.Write(this.LastName);
- return sb.ToString();
- }
- }
- //
- // end of Customer class - sample for IEditableObject
-
- // sample for IBindingList
- //
- public class CustomersList : CollectionBase, IBindingList
- {
-
- private ListChangedEventArgs resetEvent = new ListChangedEventArgs(ListChangedType.Reset, -1);
- private ListChangedEventHandler onListChanged;
-
- public void LoadCustomers()
- {
- IList l = (IList)this;
- l.Add(ReadCustomer1());
- l.Add(ReadCustomer2());
- OnListChanged(resetEvent);
- }
-
- public Customer this[int index]
- {
- get
- {
- return (Customer)(List[index]);
- }
- set
- {
- List[index] = value;
- }
- }
-
- public int Add (Customer value)
- {
- return List.Add(value);
- }
-
- public Customer AddNew()
- {
- return (Customer)((IBindingList)this).AddNew();
- }
-
- public void Remove (Customer value)
- {
- List.Remove(value);
- }
-
- protected virtual void OnListChanged(ListChangedEventArgs ev)
- {
- if (onListChanged != null)
- {
- onListChanged(this, ev);
- }
- }
-
- protected override void OnClear()
- {
- foreach (Customer c in List)
- {
- c.Parent = null;
- }
- }
-
- protected override void OnClearComplete()
- {
- OnListChanged(resetEvent);
- }
-
- protected override void OnInsertComplete(int index, object value)
- {
- Customer c = (Customer)value;
- c.Parent = this;
- OnListChanged(new ListChangedEventArgs(ListChangedType.ItemAdded, index));
- }
-
- protected override void OnRemoveComplete(int index, object value)
- {
- Customer c = (Customer)value;
- c.Parent = this;
- OnListChanged(new ListChangedEventArgs(ListChangedType.ItemDeleted, index));
- }
-
- protected override void OnSetComplete(int index, object oldValue, object newValue)
- {
- if (oldValue != newValue)
- {
-
- Customer oldcust = (Customer)oldValue;
- Customer newcust = (Customer)newValue;
-
- oldcust.Parent = null;
- newcust.Parent = this;
-
- OnListChanged(new ListChangedEventArgs(ListChangedType.ItemAdded, index));
- }
- }
-
- // Called by Customer when it changes.
- internal void CustomerChanged(Customer cust)
- {
-
- int index = List.IndexOf(cust);
-
- OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, index));
- }
-
- // Implements IBindingList.
- bool IBindingList.AllowEdit
- {
- get { return true ; }
- }
-
- bool IBindingList.AllowNew
- {
- get { return true ; }
- }
-
- bool IBindingList.AllowRemove
- {
- get { return true ; }
- }
-
- bool IBindingList.SupportsChangeNotification
- {
- get { return true ; }
- }
-
- bool IBindingList.SupportsSearching
- {
- get { return false ; }
- }
-
- bool IBindingList.SupportsSorting
- {
- get { return false ; }
- }
-
- // Events.
- public event ListChangedEventHandler ListChanged
- {
- add
- {
- onListChanged += value;
- }
- remove
- {
- onListChanged -= value;
- }
- }
-
- // Methods.
- object IBindingList.AddNew()
- {
- Customer c = new Customer(this.Count.ToString());
- List.Add(c);
- return c;
- }
-
- // Unsupported properties.
- bool IBindingList.IsSorted
- {
- get { throw new NotSupportedException(); }
- }
-
- ListSortDirection IBindingList.SortDirection
- {
- get { throw new NotSupportedException(); }
- }
-
- PropertyDescriptor IBindingList.SortProperty
- {
- get { throw new NotSupportedException(); }
- }
-
- // Unsupported Methods.
- void IBindingList.AddIndex(PropertyDescriptor property)
- {
- throw new NotSupportedException();
- }
-
- void IBindingList.ApplySort(PropertyDescriptor property, ListSortDirection direction)
- {
- throw new NotSupportedException();
- }
-
- int IBindingList.Find(PropertyDescriptor property, object key)
- {
- throw new NotSupportedException();
- }
-
- void IBindingList.RemoveIndex(PropertyDescriptor property)
- {
- throw new NotSupportedException();
- }
-
- void IBindingList.RemoveSort()
- {
- throw new NotSupportedException();
- }
-
- // Worker functions to populate the list with data.
- private static Customer ReadCustomer1()
- {
- Customer cust = new Customer("536-45-1245");
- cust.FirstName = "Jo";
- cust.LastName = "Brown";
- return cust;
- }
-
- private static Customer ReadCustomer2()
- {
- Customer cust = new Customer("246-12-5645");
- cust.FirstName = "Robert";
- cust.LastName = "Brown";
- return cust;
- }
- }
-
- //
+ struct CustomerData
+ {
+ internal string id;
+ internal string firstName;
+ internal string lastName;
+ }
+
+ CustomerData custData;
+ CustomerData backupData;
+ bool inTxn;
+
+ // Implements IEditableObject
+ void IEditableObject.BeginEdit()
+ {
+ Console.WriteLine("Start BeginEdit");
+ if (!inTxn)
+ {
+ backupData = custData;
+ inTxn = true;
+ Console.WriteLine("BeginEdit - " + backupData.lastName);
+ }
+ Console.WriteLine("End BeginEdit");
+ }
+
+ void IEditableObject.CancelEdit()
+ {
+ Console.WriteLine("Start CancelEdit");
+ if (inTxn)
+ {
+ custData = backupData;
+ inTxn = false;
+ Console.WriteLine("CancelEdit - " + custData.lastName);
+ }
+ Console.WriteLine("End CancelEdit");
+ }
+
+ void IEditableObject.EndEdit()
+ {
+ Console.WriteLine("Start EndEdit" + custData.id + custData.lastName);
+ if (inTxn)
+ {
+ backupData = new CustomerData();
+ inTxn = false;
+ Console.WriteLine("Done EndEdit - " + custData.id + custData.lastName);
+ }
+ Console.WriteLine("End EndEdit");
+ }
+
+ public Customer(string ID) : base() => custData = new CustomerData
+ {
+ id = ID,
+ firstName = "",
+ lastName = ""
+ };
+
+ public string ID => custData.id;
+
+ public string FirstName
+ {
+ get => custData.firstName;
+ set
+ {
+ custData.firstName = value;
+ OnCustomerChanged();
+ }
+ }
+
+ public string LastName
+ {
+ get => custData.lastName;
+ set
+ {
+ custData.lastName = value;
+ OnCustomerChanged();
+ }
+ }
+
+ internal CustomersList Parent { get; set; }
+
+ void OnCustomerChanged()
+ {
+ if (!inTxn && Parent != null)
+ {
+ Parent.CustomerChanged(this);
+ }
+ }
+
+ public override string ToString()
+ {
+ StringWriter sb = new();
+ sb.Write(FirstName);
+ sb.Write(" ");
+ sb.Write(LastName);
+ return sb.ToString();
+ }
}
+//
+// end of Customer class - sample for IEditableObject
+
+// sample for IBindingList
+//
+public class CustomersList : CollectionBase, IBindingList
+{
+ readonly ListChangedEventArgs resetEvent = new(ListChangedType.Reset, -1);
+ ListChangedEventHandler onListChanged;
+
+ public void LoadCustomers()
+ {
+ IList l = this;
+ _ = l.Add(ReadCustomer1());
+ _ = l.Add(ReadCustomer2());
+ OnListChanged(resetEvent);
+ }
+
+ public Customer this[int index]
+ {
+ get => (Customer)List[index]; set => List[index] = value;
+ }
+
+ public int Add(Customer value) => List.Add(value);
+
+ public Customer AddNew() => (Customer)((IBindingList)this).AddNew();
+
+ public void Remove(Customer value) => List.Remove(value);
+
+ protected virtual void OnListChanged(ListChangedEventArgs ev) => onListChanged?.Invoke(this, ev);
+
+ protected override void OnClear()
+ {
+ foreach (Customer c in List)
+ {
+ c.Parent = null;
+ }
+ }
+
+ protected override void OnClearComplete() => OnListChanged(resetEvent);
+
+ protected override void OnInsertComplete(int index, object value)
+ {
+ Customer c = (Customer)value;
+ c.Parent = this;
+ OnListChanged(new ListChangedEventArgs(ListChangedType.ItemAdded, index));
+ }
+
+ protected override void OnRemoveComplete(int index, object value)
+ {
+ Customer c = (Customer)value;
+ c.Parent = this;
+ OnListChanged(new ListChangedEventArgs(ListChangedType.ItemDeleted, index));
+ }
+
+ protected override void OnSetComplete(int index, object oldValue, object newValue)
+ {
+ if (oldValue != newValue)
+ {
+ Customer oldcust = (Customer)oldValue;
+ Customer newcust = (Customer)newValue;
+
+ oldcust.Parent = null;
+ newcust.Parent = this;
+
+ OnListChanged(new ListChangedEventArgs(ListChangedType.ItemAdded, index));
+ }
+ }
+
+ // Called by Customer when it changes.
+ internal void CustomerChanged(Customer cust)
+ {
+ int index = List.IndexOf(cust);
+
+ OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, index));
+ }
+
+ // Implements IBindingList.
+ bool IBindingList.AllowEdit => true;
+
+ bool IBindingList.AllowNew => true;
+
+ bool IBindingList.AllowRemove => true;
+
+ bool IBindingList.SupportsChangeNotification => true;
+
+ bool IBindingList.SupportsSearching => false;
+
+ bool IBindingList.SupportsSorting => false;
+
+ // Events.
+ public event ListChangedEventHandler ListChanged
+ {
+ add => onListChanged += value; remove => onListChanged -= value;
+ }
+
+ // Methods.
+ object IBindingList.AddNew()
+ {
+ Customer c = new(Count.ToString());
+ _ = List.Add(c);
+ return c;
+ }
+
+ // Unsupported properties.
+ bool IBindingList.IsSorted => throw new NotSupportedException();
+
+ ListSortDirection IBindingList.SortDirection => throw new NotSupportedException();
+
+ PropertyDescriptor IBindingList.SortProperty => throw new NotSupportedException();
+
+ // Unsupported Methods.
+ void IBindingList.AddIndex(PropertyDescriptor property) => throw new NotSupportedException();
+
+ void IBindingList.ApplySort(PropertyDescriptor property, ListSortDirection direction) => throw new NotSupportedException();
+
+ int IBindingList.Find(PropertyDescriptor property, object key) => throw new NotSupportedException();
+
+ void IBindingList.RemoveIndex(PropertyDescriptor property) => throw new NotSupportedException();
+
+ void IBindingList.RemoveSort() => throw new NotSupportedException();
+
+ // Worker functions to populate the list with data.
+ static Customer ReadCustomer1() => new("536-45-1245")
+ {
+ FirstName = "Jo",
+ LastName = "Brown"
+ };
+
+ static Customer ReadCustomer2()
+ {
+ Customer cust = new("246-12-5645")
+ {
+ FirstName = "Robert",
+ LastName = "Brown"
+ };
+ return cust;
+ }
+}
+
+//
diff --git a/snippets/csharp/System.ComponentModel/IEditableCollectionView/Overview/App.xaml.cs b/snippets/csharp/System.ComponentModel/IEditableCollectionView/Overview/App.xaml.cs
index 71b07f6daca..b0b471738bd 100644
--- a/snippets/csharp/System.ComponentModel/IEditableCollectionView/Overview/App.xaml.cs
+++ b/snippets/csharp/System.ComponentModel/IEditableCollectionView/Overview/App.xaml.cs
@@ -1,16 +1,8 @@
-using System;
-using System.Collections.Generic;
-using System.Configuration;
-using System.Data;
-using System.Linq;
-using System.Windows;
+using System.Windows;
-namespace EditingCollectionsSnippets
-{
- ///
- /// Interaction logic for App.xaml
- ///
- public partial class App : Application
- {
- }
-}
+namespace EditingCollectionsSnippets;
+
+///
+/// Interaction logic for App.xaml
+///
+public partial class App : Application;
diff --git a/snippets/csharp/System.ComponentModel/IEditableCollectionView/Overview/ChangeItem.xaml.cs b/snippets/csharp/System.ComponentModel/IEditableCollectionView/Overview/ChangeItem.xaml.cs
index 61936e2ead0..d0a81f90999 100644
--- a/snippets/csharp/System.ComponentModel/IEditableCollectionView/Overview/ChangeItem.xaml.cs
+++ b/snippets/csharp/System.ComponentModel/IEditableCollectionView/Overview/ChangeItem.xaml.cs
@@ -1,32 +1,17 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Windows;
-using System.Windows.Controls;
-using System.Windows.Data;
-using System.Windows.Documents;
-using System.Windows.Input;
-using System.Windows.Media;
-using System.Windows.Media.Imaging;
-using System.Windows.Shapes;
+using System.Windows;
-namespace EditingCollectionsSnippets
+namespace EditingCollectionsSnippets;
+
+///
+/// Interaction logic for ChangeItem.xaml
+///
+public partial class ChangeItemWindow : Window
{
- ///
- /// Interaction logic for ChangeItem.xaml
- ///
- public partial class ChangeItemWindow : Window
- {
- public ChangeItemWindow()
- {
- InitializeComponent();
- }
+ public ChangeItemWindow() => InitializeComponent();
- private void Submit_Click(object sender, RoutedEventArgs e)
- {
- DialogResult = true;
- Close();
- }
+ void Submit_Click(object sender, RoutedEventArgs e)
+ {
+ DialogResult = true;
+ Close();
}
}
diff --git a/snippets/csharp/System.ComponentModel/IEditableCollectionView/Overview/EditingCollectionsSnippets.csproj b/snippets/csharp/System.ComponentModel/IEditableCollectionView/Overview/EditingCollectionsSnippets.csproj
index 7f1404bd378..16194617d0a 100644
--- a/snippets/csharp/System.ComponentModel/IEditableCollectionView/Overview/EditingCollectionsSnippets.csproj
+++ b/snippets/csharp/System.ComponentModel/IEditableCollectionView/Overview/EditingCollectionsSnippets.csproj
@@ -2,7 +2,7 @@
WinExe
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/IEditableCollectionView/Overview/Window1.xaml.cs b/snippets/csharp/System.ComponentModel/IEditableCollectionView/Overview/Window1.xaml.cs
index 4c59ae1dcf4..df923fae2ff 100644
--- a/snippets/csharp/System.ComponentModel/IEditableCollectionView/Overview/Window1.xaml.cs
+++ b/snippets/csharp/System.ComponentModel/IEditableCollectionView/Overview/Window1.xaml.cs
@@ -1,250 +1,221 @@
using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Windows;
-using System.Windows.Controls;
-using System.Windows.Data;
-using System.Windows.Documents;
-using System.Windows.Input;
-using System.Windows.Media;
-using System.Windows.Media.Imaging;
-using System.Windows.Navigation;
-using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.ComponentModel;
+using System.Windows;
+
+namespace EditingCollectionsSnippets;
-namespace EditingCollectionsSnippets
+///
+/// Interaction logic for Window1.xaml
+///
+public partial class Window1 : Window
{
- ///
- /// Interaction logic for Window1.xaml
- ///
- public partial class Window1 : Window
+ public Window1() => InitializeComponent();
+
+ void edit_Click(object sender, RoutedEventArgs e)
{
- public Window1()
+ if (itemsControl.SelectedItem == null)
{
- InitializeComponent();
+ _ = MessageBox.Show("No item is selected");
+ return;
}
- private void edit_Click(object sender, RoutedEventArgs e)
- {
- if (itemsControl.SelectedItem == null)
- {
- MessageBox.Show("No item is selected");
- return;
- }
-
- //
- IEditableCollectionView editableCollectionView =
- itemsControl.Items as IEditableCollectionView;
+ //
+ IEditableCollectionView editableCollectionView =
+ itemsControl.Items;
- // Create a window that prompts the user to edit an item.
- ChangeItemWindow win = new ChangeItemWindow();
- editableCollectionView.EditItem(itemsControl.SelectedItem);
- win.DataContext = itemsControl.SelectedItem;
+ // Create a window that prompts the user to edit an item.
+ ChangeItemWindow win = new();
+ editableCollectionView.EditItem(itemsControl.SelectedItem);
+ win.DataContext = itemsControl.SelectedItem;
- // If the user submits the new item, commit the changes.
- // If the user cancels the edits, discard the changes.
- if ((bool)win.ShowDialog())
- {
- editableCollectionView.CommitEdit();
- }
- else
- {
- //
- // If the objects in the collection can discard pending
- // changes, calling IEditableCollectionView.CancelEdit
- // will revert the changes. Otherwise, you must provide
- // your own logic to revert the changes in the object.
-
- if (!editableCollectionView.CanCancelEdit)
- {
- // Provide logic to revert changes.
- }
-
- editableCollectionView.CancelEdit();
- //
- }
- //
+ // If the user submits the new item, commit the changes.
+ // If the user cancels the edits, discard the changes.
+ if ((bool)win.ShowDialog())
+ {
+ editableCollectionView.CommitEdit();
}
-
- private void add_Click(object sender, RoutedEventArgs e)
+ else
{
- //
- IEditableCollectionView editableCollectionView =
- itemsControl.Items as IEditableCollectionView;
-
- if (!editableCollectionView.CanAddNew)
- {
- MessageBox.Show("You cannot add items to the list.");
- return;
- }
-
- // Create a window that prompts the user to enter a new
- // item to sell.
- ChangeItemWindow win = new ChangeItemWindow();
+ //
+ // If the objects in the collection can discard pending
+ // changes, calling IEditableCollectionView.CancelEdit
+ // will revert the changes. Otherwise, you must provide
+ // your own logic to revert the changes in the object.
- //Create a new item to be added to the collection.
- win.DataContext = editableCollectionView.AddNew();
-
- // If the user submits the new item, commit the new
- // object to the collection. If the user cancels
- // adding the new item, discard the new item.
- if ((bool)win.ShowDialog())
+ if (!editableCollectionView.CanCancelEdit)
{
- editableCollectionView.CommitNew();
- }
- else
- {
- editableCollectionView.CancelNew();
+ // Provide logic to revert changes.
}
- //
+ editableCollectionView.CancelEdit();
+ //
}
+ //
+ }
- private void remove_Click(object sender, RoutedEventArgs e)
- {
- PurchaseItem item = itemsControl.SelectedItem as PurchaseItem;
+ void add_Click(object sender, RoutedEventArgs e)
+ {
+ //
+ IEditableCollectionView editableCollectionView =
+ itemsControl.Items;
- if (item == null)
- {
- MessageBox.Show("No Item is selected");
- return;
- }
+ if (!editableCollectionView.CanAddNew)
+ {
+ _ = MessageBox.Show("You cannot add items to the list.");
+ return;
+ }
- //
- IEditableCollectionView editableCollectionView =
- itemsControl.Items as IEditableCollectionView;
-
- if (!editableCollectionView.CanRemove)
- {
- MessageBox.Show("You cannot remove items from the list.");
- return;
- }
+ // Create a window that prompts the user to enter a new
+ // item to sell.
+ ChangeItemWindow win = new()
+ {
+ //Create a new item to be added to the collection.
+ DataContext = editableCollectionView.AddNew()
+ };
- if (MessageBox.Show("Are you sure you want to remove " + item.Description,
- "Remove Item", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
- {
- editableCollectionView.Remove(itemsControl.SelectedItem);
- }
- //
+ // If the user submits the new item, commit the new
+ // object to the collection. If the user cancels
+ // adding the new item, discard the new item.
+ if ((bool)win.ShowDialog())
+ {
+ editableCollectionView.CommitNew();
}
+ else
+ {
+ editableCollectionView.CancelNew();
+ }
+
+ //
}
- public class PurchaseItem : IEditableObject, INotifyPropertyChanged
+ void remove_Click(object sender, RoutedEventArgs e)
{
- struct ItemData
+ if (itemsControl.SelectedItem is not PurchaseItem item)
{
- internal string Description;
- internal double Price;
- internal DateTime OfferExpires;
+ _ = MessageBox.Show("No Item is selected");
+ return;
}
- ItemData copyData;
- ItemData currentData;
- public PurchaseItem()
- : this("New item", 0, DateTime.Now)
- {
- }
+ //
+ IEditableCollectionView editableCollectionView =
+ itemsControl.Items;
- public PurchaseItem(string desc, double price, DateTime endDate)
+ if (!editableCollectionView.CanRemove)
{
- Description = desc;
- Price = price;
- OfferExpires = endDate;
+ _ = MessageBox.Show("You cannot remove items from the list.");
+ return;
}
- public override string ToString()
+ if (MessageBox.Show("Are you sure you want to remove " + item.Description,
+ "Remove Item", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
{
- return String.Format("{0}, {1:c}, {2:D}", Description, Price, OfferExpires);
+ editableCollectionView.Remove(itemsControl.SelectedItem);
}
+ //
+ }
+}
+
+public class PurchaseItem : IEditableObject, INotifyPropertyChanged
+{
+ struct ItemData
+ {
+ internal string Description;
+ internal double Price;
+ internal DateTime OfferExpires;
+ }
+ ItemData copyData;
+ ItemData currentData;
+
+ public PurchaseItem()
+ : this("New item", 0, DateTime.Now)
+ {
+ }
- public string Description
+ public PurchaseItem(string desc, double price, DateTime endDate)
+ {
+ Description = desc;
+ Price = price;
+ OfferExpires = endDate;
+ }
+
+ public override string ToString() => string.Format("{0}, {1:c}, {2:D}", Description, Price, OfferExpires);
+
+ public string Description
+ {
+ get => currentData.Description;
+ set
{
- get { return currentData.Description; }
- set
+ if (currentData.Description != value)
{
- if (currentData.Description != value)
- {
- currentData.Description = value;
- NotifyPropertyChanged("Description");
- }
+ currentData.Description = value;
+ NotifyPropertyChanged("Description");
}
}
+ }
- public double Price
+ public double Price
+ {
+ get => currentData.Price;
+ set
{
- get { return currentData.Price; }
- set
+ if (currentData.Price != value)
{
- if (currentData.Price != value)
- {
- currentData.Price = value;
- NotifyPropertyChanged("Price");
- }
+ currentData.Price = value;
+ NotifyPropertyChanged("Price");
}
}
+ }
- public DateTime OfferExpires
+ public DateTime OfferExpires
+ {
+ get => currentData.OfferExpires;
+ set
{
- get { return currentData.OfferExpires; }
- set
+ if (value != currentData.OfferExpires)
{
- if (value != currentData.OfferExpires)
- {
- currentData.OfferExpires = value;
- NotifyPropertyChanged("OfferExpires");
- }
+ currentData.OfferExpires = value;
+ NotifyPropertyChanged("OfferExpires");
}
}
+ }
- #region INotifyPropertyChanged Members
+ #region INotifyPropertyChanged Members
- public event PropertyChangedEventHandler PropertyChanged;
+ public event PropertyChangedEventHandler PropertyChanged;
- private void NotifyPropertyChanged(String info)
- {
- if (PropertyChanged != null)
- {
- PropertyChanged(this, new PropertyChangedEventArgs(info));
- }
- }
+ void NotifyPropertyChanged(string info) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(info));
- #endregion
+ #endregion
- #region IEditableObject Members
+ #region IEditableObject Members
- public void BeginEdit()
- {
- copyData = currentData;
- }
+ public void BeginEdit() => copyData = currentData;
- public void CancelEdit()
- {
- currentData = copyData;
- NotifyPropertyChanged("");
- }
+ public void CancelEdit()
+ {
+ currentData = copyData;
+ NotifyPropertyChanged("");
+ }
- public void EndEdit()
- {
- copyData = new ItemData();
- }
+ public void EndEdit() => copyData = new ItemData();
- #endregion
+ #endregion
- }
+}
- public class ItemsForSale : ObservableCollection
- {
- public ItemsForSale()
- {
- Add((new PurchaseItem("Snowboard and bindings", 120, new DateTime(2009, 1, 1))));
- Add((new PurchaseItem("Inside C#, second edition", 10, new DateTime(2009, 2, 2))));
- Add((new PurchaseItem("Laptop - only 1 year old", 499.99, new DateTime(2009, 2, 28))));
- Add((new PurchaseItem("Set of 6 chairs", 120, new DateTime(2009, 2, 28))));
- Add((new PurchaseItem("My DVD Collection", 15, new DateTime(2009, 1, 1))));
- Add((new PurchaseItem("TV Drama Series", 39.985, new DateTime(2009, 1, 1))));
- Add((new PurchaseItem("Squash racket", 60, new DateTime(2009, 2, 28))));
- }
- }
+public class ItemsForSale : ObservableCollection
+{
+ public ItemsForSale() : base(
+[
+ new("Snowboard and bindings", 120, new DateTime(2009, 1, 1)),
+ new ("Snowboard and bindings", 120, new DateTime(2009, 1, 1)),
+ new ("Inside C#, second edition", 10, new DateTime(2009, 2, 2)),
+ new ("Laptop - only 1 year old", 499.99, new DateTime(2009, 2, 28)),
+ new ("Set of 6 chairs", 120, new DateTime(2009, 2, 28)),
+ new ("My DVD Collection", 15, new DateTime(2009, 1, 1)),
+ new ("TV Drama Series", 39.985, new DateTime(2009, 1, 1)),
+ new ("Squash racket", 60, new DateTime(2009, 2, 28))
+ ])
+ { }
}
diff --git a/snippets/csharp/System.ComponentModel/IEditableCollectionViewAddNewItem/Overview/additem.xaml.cs b/snippets/csharp/System.ComponentModel/IEditableCollectionViewAddNewItem/Overview/additem.xaml.cs
index 3fb76905d37..621807dff78 100644
--- a/snippets/csharp/System.ComponentModel/IEditableCollectionViewAddNewItem/Overview/additem.xaml.cs
+++ b/snippets/csharp/System.ComponentModel/IEditableCollectionViewAddNewItem/Overview/additem.xaml.cs
@@ -2,28 +2,24 @@
using System.Windows;
using System.Windows.Controls;
-namespace IEditableCollectionViewAddItemExample
+namespace IEditableCollectionViewAddItemExample;
+
+public partial class AddItemWindow : Window
{
- public partial class AddItemWindow : Window
- {
- public AddItemWindow()
- {
- InitializeComponent();
- }
+ public AddItemWindow() => InitializeComponent();
- private void Submit_Click(object sender, RoutedEventArgs e)
- {
- DialogResult = true;
- Close();
- }
+ void Submit_Click(object sender, RoutedEventArgs e)
+ {
+ DialogResult = true;
+ Close();
+ }
- // Select all text when the TextBox gets focus.
- private void TextBoxFocus(object sender, RoutedEventArgs e)
- {
- TextBox tbx = sender as TextBox;
+ // Select all text when the TextBox gets focus.
+ void TextBoxFocus(object sender, RoutedEventArgs e)
+ {
+ TextBox tbx = sender as TextBox;
- tbx.SelectAll();
- }
+ tbx.SelectAll();
}
}
//
diff --git a/snippets/csharp/System.ComponentModel/IEditableCollectionViewAddNewItem/Overview/app.xaml.cs b/snippets/csharp/System.ComponentModel/IEditableCollectionViewAddNewItem/Overview/app.xaml.cs
index ebc002951cb..a8ca5626305 100644
--- a/snippets/csharp/System.ComponentModel/IEditableCollectionViewAddNewItem/Overview/app.xaml.cs
+++ b/snippets/csharp/System.ComponentModel/IEditableCollectionViewAddNewItem/Overview/app.xaml.cs
@@ -1,16 +1,8 @@
-using System;
-using System.Collections.Generic;
-using System.Configuration;
-using System.Data;
-using System.Linq;
-using System.Windows;
+using System.Windows;
-namespace IEditableCollectionViewAddItemExample
-{
- ///
- /// Interaction logic for App.xaml
- ///
- public partial class App : Application
- {
- }
-}
+namespace IEditableCollectionViewAddItemExample;
+
+///
+/// Interaction logic for App.xaml
+///
+public partial class App : Application;
diff --git a/snippets/csharp/System.ComponentModel/IEditableCollectionViewAddNewItem/Overview/data.cs b/snippets/csharp/System.ComponentModel/IEditableCollectionViewAddNewItem/Overview/data.cs
index 0c62215d5ae..ba28148be44 100644
--- a/snippets/csharp/System.ComponentModel/IEditableCollectionViewAddNewItem/Overview/data.cs
+++ b/snippets/csharp/System.ComponentModel/IEditableCollectionViewAddNewItem/Overview/data.cs
@@ -3,354 +3,329 @@
using System.Collections.ObjectModel;
using System.ComponentModel;
-namespace IEditableCollectionViewAddItemExample
+namespace IEditableCollectionViewAddItemExample;
+
+// LibraryItem implements INotifyPropertyChanged so that the
+// application is notified when a property changes. It
+// implements IEditableObject so that pending changes can be discarded.
+public class LibraryItem : INotifyPropertyChanged, IEditableObject
{
- // LibraryItem implements INotifyPropertyChanged so that the
- // application is notified when a property changes. It
- // implements IEditableObject so that pending changes can be discarded.
- public class LibraryItem : INotifyPropertyChanged, IEditableObject
+ struct ItemData
{
- struct ItemData
- {
- internal string Title;
- internal string CallNumber;
- internal DateTime DueDate;
- }
+ internal string Title;
+ internal string CallNumber;
+ internal DateTime DueDate;
+ }
- ItemData copyData;
- ItemData currentData;
+ ItemData copyData;
+ ItemData currentData;
- public LibraryItem(string title, string callNum, DateTime dueDate)
- {
- Title = title;
- CallNumber = callNum;
- DueDate = dueDate;
- }
+ public LibraryItem(string title, string callNum, DateTime dueDate)
+ {
+ Title = title;
+ CallNumber = callNum;
+ DueDate = dueDate;
+ }
- public override string ToString()
- {
- return String.Format("{0}, {1:c}, {2:D}", Title, CallNumber, DueDate);
- }
+ public override string ToString() => string.Format("{0}, {1:c}, {2:D}", Title, CallNumber, DueDate);
- public string Title
+ public string Title
+ {
+ get => currentData.Title;
+ set
{
- get { return currentData.Title; }
- set
+ if (currentData.Title != value)
{
- if (currentData.Title != value)
- {
- currentData.Title = value;
- NotifyPropertyChanged("Title");
- }
+ currentData.Title = value;
+ NotifyPropertyChanged("Title");
}
}
+ }
- public string CallNumber
+ public string CallNumber
+ {
+ get => currentData.CallNumber;
+ set
{
- get { return currentData.CallNumber; }
- set
+ if (currentData.CallNumber != value)
{
- if (currentData.CallNumber != value)
- {
- currentData.CallNumber = value;
- NotifyPropertyChanged("CallNumber");
- }
+ currentData.CallNumber = value;
+ NotifyPropertyChanged("CallNumber");
}
}
+ }
- public DateTime DueDate
+ public DateTime DueDate
+ {
+ get => currentData.DueDate;
+ set
{
- get { return currentData.DueDate; }
- set
+ if (value != currentData.DueDate)
{
- if (value != currentData.DueDate)
- {
- currentData.DueDate = value;
- NotifyPropertyChanged("DueDate");
- }
+ currentData.DueDate = value;
+ NotifyPropertyChanged("DueDate");
}
}
+ }
- #region INotifyPropertyChanged Members
+ #region INotifyPropertyChanged Members
- public event PropertyChangedEventHandler PropertyChanged;
+ public event PropertyChangedEventHandler PropertyChanged;
- protected void NotifyPropertyChanged(String info)
- {
- if (PropertyChanged != null)
- {
- PropertyChanged(this, new PropertyChangedEventArgs(info));
- }
- }
+ protected void NotifyPropertyChanged(string info) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(info));
- #endregion
+ #endregion
- #region IEditableObject Members
+ #region IEditableObject Members
- public virtual void BeginEdit()
- {
- copyData = currentData;
- }
+ public virtual void BeginEdit() => copyData = currentData;
- public virtual void CancelEdit()
- {
- currentData = copyData;
- NotifyPropertyChanged("");
- }
+ public virtual void CancelEdit()
+ {
+ currentData = copyData;
+ NotifyPropertyChanged("");
+ }
- public virtual void EndEdit()
- {
- copyData = new ItemData();
- }
+ public virtual void EndEdit() => copyData = new ItemData();
- #endregion
+ #endregion
- }
+}
- public class MusicCD : LibraryItem
+public class MusicCD : LibraryItem
+{
+ struct MusicData
{
- private struct MusicData
- {
- internal int SongNumber;
- internal string Artist;
- }
+ internal int SongNumber;
+ internal string Artist;
+ }
- MusicData copyData;
- MusicData currentData;
+ MusicData copyData;
+ MusicData currentData;
- public MusicCD(string title, string artist, int songNum, string callNum, DateTime dueDate)
- : base(title, callNum, dueDate)
- {
- currentData.SongNumber = songNum;
- currentData.Artist = artist;
- }
+ public MusicCD(string title, string artist, int songNum, string callNum, DateTime dueDate)
+ : base(title, callNum, dueDate)
+ {
+ currentData.SongNumber = songNum;
+ currentData.Artist = artist;
+ }
- public string Artist
+ public string Artist
+ {
+ get => currentData.Artist;
+ set
{
- get { return currentData.Artist; }
- set
+ if (value != currentData.Artist)
{
- if (value != currentData.Artist)
- {
- currentData.Artist = value;
- NotifyPropertyChanged("Artist");
- }
+ currentData.Artist = value;
+ NotifyPropertyChanged("Artist");
}
}
+ }
- public int NumberOfTracks
+ public int NumberOfTracks
+ {
+ get => currentData.SongNumber;
+ set
{
- get { return currentData.SongNumber; }
- set
+ if (value != currentData.SongNumber)
{
- if (value != currentData.SongNumber)
- {
- currentData.SongNumber = value;
- NotifyPropertyChanged("NumberOfTracks");
- }
+ currentData.SongNumber = value;
+ NotifyPropertyChanged("NumberOfTracks");
}
}
+ }
- public override void BeginEdit()
- {
- base.BeginEdit();
- copyData = currentData;
- }
-
- public override void CancelEdit()
- {
- base.CancelEdit();
- currentData = copyData;
- }
+ public override void BeginEdit()
+ {
+ base.BeginEdit();
+ copyData = currentData;
+ }
- public override void EndEdit()
- {
- base.EndEdit();
- copyData = new MusicData();
- }
+ public override void CancelEdit()
+ {
+ base.CancelEdit();
+ currentData = copyData;
+ }
- public override string ToString()
- {
- return string.Format(
- "Album: {0}\nArtist: {1}\nTracks: {2}\nDue Date: {3:d}\nCall Number: {4}",
- this.Title, this.Artist, this.NumberOfTracks, this.DueDate, this.CallNumber);
- }
+ public override void EndEdit()
+ {
+ base.EndEdit();
+ copyData = new MusicData();
}
- public class Book : LibraryItem
+ public override string ToString() => string.Format(
+ "Album: {0}\nArtist: {1}\nTracks: {2}\nDue Date: {3:d}\nCall Number: {4}",
+ Title, Artist, NumberOfTracks, DueDate, CallNumber);
+}
+
+public class Book : LibraryItem
+{
+ struct BookData
{
- private struct BookData
- {
- internal string Author;
- internal string Genre;
- }
+ internal string Author;
+ internal string Genre;
+ }
- BookData currentData;
- BookData copyData;
+ BookData currentData;
+ BookData copyData;
- public Book(string title, string author, string genre, string callnum, DateTime dueDate)
- : base (title, callnum, dueDate)
- {
- this.Author = author;
- this.Genre = genre;
- }
+ public Book(string title, string author, string genre, string callnum, DateTime dueDate)
+ : base(title, callnum, dueDate)
+ {
+ Author = author;
+ Genre = genre;
+ }
- public string Author
+ public string Author
+ {
+ get => currentData.Author;
+ set
{
- get { return currentData.Author; }
- set
+ if (value != currentData.Author)
{
- if (value != currentData.Author)
- {
- currentData.Author = value;
- NotifyPropertyChanged("Author");
- }
+ currentData.Author = value;
+ NotifyPropertyChanged("Author");
}
}
+ }
- public string Genre
+ public string Genre
+ {
+ get => currentData.Genre;
+ set
{
- get { return currentData.Genre; }
- set
+ if (value != currentData.Genre)
{
- if (value != currentData.Genre)
- {
- currentData.Genre = value;
- NotifyPropertyChanged("Genre");
- }
+ currentData.Genre = value;
+ NotifyPropertyChanged("Genre");
}
}
+ }
- public override void BeginEdit()
- {
- base.BeginEdit();
- copyData = currentData;
- }
-
- public override void CancelEdit()
- {
- base.CancelEdit();
- currentData = copyData;
- }
+ public override void BeginEdit()
+ {
+ base.BeginEdit();
+ copyData = currentData;
+ }
- public override void EndEdit()
- {
- base.EndEdit();
- copyData = new BookData();
- }
+ public override void CancelEdit()
+ {
+ base.CancelEdit();
+ currentData = copyData;
+ }
- public override string ToString()
- {
- return String.Format(
- "Title: {0}\nAuthor: {1}\nGenre: {2}\nDue Date: {3:d}\nCall Number: {4}",
- this.Title, this.Author, this.Genre, this.DueDate, this.CallNumber);
- }
+ public override void EndEdit()
+ {
+ base.EndEdit();
+ copyData = new BookData();
}
- public class MovieDVD : LibraryItem
+ public override string ToString() => string.Format(
+ "Title: {0}\nAuthor: {1}\nGenre: {2}\nDue Date: {3:d}\nCall Number: {4}",
+ Title, Author, Genre, DueDate, CallNumber);
+}
+
+public class MovieDVD : LibraryItem
+{
+ struct MovieData
{
- private struct MovieData
- {
- internal TimeSpan Length;
- internal string Director;
- internal string Genre;
- }
+ internal TimeSpan Length;
+ internal string Director;
+ internal string Genre;
+ }
- private MovieData currentData;
- private MovieData copyData;
+ MovieData currentData;
+ MovieData copyData;
- public MovieDVD(string title, string director, string genre, TimeSpan length, string callnum, DateTime dueDate)
- : base(title, callnum, dueDate)
- {
- this.Director = director;
- this.Length = length;
- this.Genre = genre;
- }
+ public MovieDVD(string title, string director, string genre, TimeSpan length, string callnum, DateTime dueDate)
+ : base(title, callnum, dueDate)
+ {
+ Director = director;
+ Length = length;
+ Genre = genre;
+ }
- public TimeSpan Length
+ public TimeSpan Length
+ {
+ get => currentData.Length;
+ set
{
- get { return currentData.Length; }
- set
+ if (value != currentData.Length)
{
- if (value != currentData.Length)
- {
- currentData.Length = value;
- NotifyPropertyChanged("Length");
- }
+ currentData.Length = value;
+ NotifyPropertyChanged("Length");
}
}
+ }
- public string Director
+ public string Director
+ {
+ get => currentData.Director;
+ set
{
- get { return currentData.Director; }
- set
+ if (value != currentData.Director)
{
- if (value != currentData.Director)
- {
- currentData.Director = value;
- NotifyPropertyChanged("Director");
- }
+ currentData.Director = value;
+ NotifyPropertyChanged("Director");
}
}
+ }
- public string Genre
+ public string Genre
+ {
+ get => currentData.Genre;
+ set
{
- get { return currentData.Genre; }
- set
+ if (value != currentData.Genre)
{
- if (value != currentData.Genre)
- {
- currentData.Genre = value;
- NotifyPropertyChanged("Genre");
- }
+ currentData.Genre = value;
+ NotifyPropertyChanged("Genre");
}
}
+ }
- public override void BeginEdit()
- {
- base.BeginEdit();
- copyData = currentData;
- }
-
- public override void CancelEdit()
- {
- base.CancelEdit();
- currentData = copyData;
- }
+ public override void BeginEdit()
+ {
+ base.BeginEdit();
+ copyData = currentData;
+ }
- public override void EndEdit()
- {
- base.EndEdit();
- copyData = new MovieData();
- }
+ public override void CancelEdit()
+ {
+ base.CancelEdit();
+ currentData = copyData;
+ }
- public override string ToString()
- {
- return String.Format("Title: {0}\nDirector: {1}\nGenre: {2}\nLength: {3}\nDue Date: {4:d}\nCall Number: {5}",
- this.Title, this.Director, this.Genre, this.Length, this.DueDate, this.CallNumber);
- }
+ public override void EndEdit()
+ {
+ base.EndEdit();
+ copyData = new MovieData();
}
- public class LibraryCatalog : ObservableCollection
+ public override string ToString() => string.Format("Title: {0}\nDirector: {1}\nGenre: {2}\nLength: {3}\nDue Date: {4:d}\nCall Number: {5}",
+ Title, Director, Genre, Length, DueDate, CallNumber);
+}
+
+public class LibraryCatalog : ObservableCollection
+{
+ public LibraryCatalog()
{
- public LibraryCatalog()
- {
- Add(new MusicCD("A Programmers Plight", "Jon Orton",
- 12, "CD.OrtPro", new DateTime(2010, 3, 24)));
-
- Add(new Book("Cooking with Thyme", "Eliot J. Graff",
- "Home Economics", "HE.GraThy", new DateTime(2010, 2, 26)));
-
- Add(new MovieDVD("Terror of the Testers", "Molly Dempsey",
- "Horror", new TimeSpan(1, 27, 19), "DVD.DemTer",
- new DateTime(2010, 2, 1)));
-
- Add(new MusicCD("The Best of Jim Hance", "Jim Hance",
- 15, "CD.HanBes", new DateTime(2010, 1, 31)));
-
- Add(new Book("Victor and the VB Vehicle", "Tommy Hortono",
- "YA Fiction", "YA.HorVic", new DateTime(2010, 3, 1)));
- }
+ Add(new MusicCD("A Programmers Plight", "Jon Orton",
+ 12, "CD.OrtPro", new DateTime(2010, 3, 24)));
+
+ Add(new Book("Cooking with Thyme", "Eliot J. Graff",
+ "Home Economics", "HE.GraThy", new DateTime(2010, 2, 26)));
+
+ Add(new MovieDVD("Terror of the Testers", "Molly Dempsey",
+ "Horror", new TimeSpan(1, 27, 19), "DVD.DemTer",
+ new DateTime(2010, 2, 1)));
+
+ Add(new MusicCD("The Best of Jim Hance", "Jim Hance",
+ 15, "CD.HanBes", new DateTime(2010, 1, 31)));
+
+ Add(new Book("Victor and the VB Vehicle", "Tommy Hortono",
+ "YA Fiction", "YA.HorVic", new DateTime(2010, 3, 1)));
}
}
//
diff --git a/snippets/csharp/System.ComponentModel/IEditableCollectionViewAddNewItem/Overview/ieditablecollectionviewadditemexample.csproj b/snippets/csharp/System.ComponentModel/IEditableCollectionViewAddNewItem/Overview/ieditablecollectionviewadditemexample.csproj
index 7f1404bd378..16194617d0a 100644
--- a/snippets/csharp/System.ComponentModel/IEditableCollectionViewAddNewItem/Overview/ieditablecollectionviewadditemexample.csproj
+++ b/snippets/csharp/System.ComponentModel/IEditableCollectionViewAddNewItem/Overview/ieditablecollectionviewadditemexample.csproj
@@ -2,7 +2,7 @@
WinExe
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/IEditableCollectionViewAddNewItem/Overview/window1.xaml.cs b/snippets/csharp/System.ComponentModel/IEditableCollectionViewAddNewItem/Overview/window1.xaml.cs
index ffd4d20c760..24d83885d07 100644
--- a/snippets/csharp/System.ComponentModel/IEditableCollectionViewAddNewItem/Overview/window1.xaml.cs
+++ b/snippets/csharp/System.ComponentModel/IEditableCollectionViewAddNewItem/Overview/window1.xaml.cs
@@ -3,74 +3,58 @@
using System.ComponentModel;
using System.Windows;
-namespace IEditableCollectionViewAddItemExample
+namespace IEditableCollectionViewAddItemExample;
+
+public partial class Window1 : Window
{
- public partial class Window1 : Window
+ public Window1() => InitializeComponent();
+
+ void Button_Click(object sender, RoutedEventArgs e)
{
- public Window1()
+ IEditableCollectionViewAddNewItem viewToAddDisparateItems =
+ catalogList.Items;
+
+ if (!viewToAddDisparateItems.CanAddNewItem)
{
- InitializeComponent();
+ _ = MessageBox.Show("You cannot add items to the list.");
+ return;
}
- private void Button_Click(object sender, RoutedEventArgs e)
+ // Create a window that prompts the user to enter a new
+ // item to sell.
+ AddItemWindow win = new();
+
+ // Create an item, depending on which RadioButton is selected.
+ // Radio buttons correspond to book, cd, dvd, or other.
+ LibraryItem newItem = (bool)book.IsChecked
+ ? new Book("Enter the book title", "Enter an Author", "Enter a Genre",
+ "Enter a call number", DateTime.Now + new TimeSpan(21, 0, 0, 0))
+ : (bool)cd.IsChecked
+ ? new MusicCD("Enter the Album", "Enter the artist", 0, "CD.******",
+ DateTime.Now + new TimeSpan(14, 0, 0, 0))
+ : (bool)dvd.IsChecked
+ ? new MovieDVD("Enter the movie title", "Enter the director",
+ "Enter the genre", new TimeSpan(), "DVD.******",
+ DateTime.Now + new TimeSpan(7, 0, 0, 0))
+ : new LibraryItem("Enter the title", "Enter the call number",
+ DateTime.Now + new TimeSpan(14, 0, 0, 0));
+
+ // Add the new item to the collection by calling
+ // IEditableCollectionViewAddNewItem.AddNewItem.
+ // Set the DataContext of the AddItemWindow to the
+ // returned item.
+ win.DataContext = viewToAddDisparateItems.AddNewItem(newItem);
+
+ // If the user submits the new item, commit the new
+ // object to the collection. If the user cancels
+ // adding the new item, discard the new item.
+ if ((bool)win.ShowDialog())
{
- IEditableCollectionViewAddNewItem viewToAddDisparateItems =
- catalogList.Items as IEditableCollectionViewAddNewItem;
-
- if (!viewToAddDisparateItems.CanAddNewItem)
- {
- MessageBox.Show("You cannot add items to the list.");
- return;
- }
-
- // Create a window that prompts the user to enter a new
- // item to sell.
- AddItemWindow win = new AddItemWindow();
-
- // Create an item, depending on which RadioButton is selected.
- // Radio buttons correspond to book, cd, dvd, or other.
- LibraryItem newItem;
-
- if ((bool)book.IsChecked)
- {
- newItem = new Book("Enter the book title", "Enter an Author", "Enter a Genre",
- "Enter a call number", DateTime.Now + new TimeSpan(21, 0, 0, 0));
- }
- else if ((bool)cd.IsChecked)
- {
- newItem = new MusicCD("Enter the Album", "Enter the artist", 0, "CD.******",
- DateTime.Now + new TimeSpan(14, 0, 0, 0));
- }
-
- else if ((bool)dvd.IsChecked)
- {
- newItem = new MovieDVD("Enter the movie title", "Enter the director",
- "Enter the genre", new TimeSpan(), "DVD.******",
- DateTime.Now + new TimeSpan(7, 0, 0, 0));
- }
- else
- {
- newItem = new LibraryItem("Enter the title", "Enter the call number",
- DateTime.Now + new TimeSpan(14, 0, 0, 0));
- }
-
- // Add the new item to the collection by calling
- // IEditableCollectionViewAddNewItem.AddNewItem.
- // Set the DataContext of the AddItemWindow to the
- // returned item.
- win.DataContext = viewToAddDisparateItems.AddNewItem(newItem);
-
- // If the user submits the new item, commit the new
- // object to the collection. If the user cancels
- // adding the new item, discard the new item.
- if ((bool)win.ShowDialog())
- {
- viewToAddDisparateItems.CommitNew();
- }
- else
- {
- viewToAddDisparateItems.CancelNew();
- }
+ viewToAddDisparateItems.CommitNew();
+ }
+ else
+ {
+ viewToAddDisparateItems.CancelNew();
}
}
}
diff --git a/snippets/csharp/System.ComponentModel/IExtenderProvider/Overview/HelpLabel.cs b/snippets/csharp/System.ComponentModel/IExtenderProvider/Overview/HelpLabel.cs
index 7ded95775c4..5a82bbeddf0 100644
--- a/snippets/csharp/System.ComponentModel/IExtenderProvider/Overview/HelpLabel.cs
+++ b/snippets/csharp/System.ComponentModel/IExtenderProvider/Overview/HelpLabel.cs
@@ -1,459 +1,429 @@
//
-namespace Microsoft.Samples.WinForms.Cs.HelpLabel
+
+using System;
+using System.Collections;
+using System.ComponentModel;
+using System.ComponentModel.Design;
+using System.Drawing;
+using System.Windows.Forms;
+using System.Windows.Forms.Design;
+
+namespace Microsoft.Samples.WinForms.Cs.HelpLabel;
+//
+//
+//
+// Help Label offers an extender property called
+// "HelpText". It monitors the active control
+// and displays the help text for the active control.
+//
+//
+//
+[
+ProvideProperty("HelpText", typeof(Control)),
+Designer(typeof(HelpLabelDesigner))
+]
+public class HelpLabel : Control, IExtenderProvider
{
- using System;
- using System.Collections;
- using System.ComponentModel;
- using System.ComponentModel.Design;
- using System.Drawing;
- using System.Windows.Forms;
- using System.Windows.Forms.Design;
+ ///
+ /// Required designer variable.
+ ///
+ Container components;
+ readonly Hashtable helpTexts;
+ Control activeControl;
//
//
//
- // Help Label offers an extender property called
- // "HelpText". It monitors the active control
- // and displays the help text for the active control.
+ // Creates a new help label object.
//
//
//
- [
- ProvideProperty("HelpText",typeof(Control)),
- Designer(typeof(HelpLabel.HelpLabelDesigner))
- ]
- public class HelpLabel : Control, System.ComponentModel.IExtenderProvider
+ public HelpLabel()
{
- ///
- /// Required designer variable.
- ///
- private System.ComponentModel.Container components;
- private Hashtable helpTexts;
- private System.Windows.Forms.Control activeControl;
-
//
- //
- //
- // Creates a new help label object.
- //
- //
+ // Required for Windows Form Designer support
//
- public HelpLabel()
- {
- //
- // Required for Windows Form Designer support
- //
- InitializeComponent();
+ InitializeComponent();
- helpTexts = new Hashtable();
- }
+ helpTexts = [];
+ }
- ///
- /// Clean up any resources being used.
- ///
- protected override void Dispose(bool disposing)
- {
- if (disposing)
- {
- components.Dispose();
- }
- base.Dispose(disposing);
- }
+ ///
+ /// Clean up any resources being used.
+ ///
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ components.Dispose();
+ }
+ base.Dispose(disposing);
+ }
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
- private void InitializeComponent()
+ void InitializeComponent()
{
- this.BackColor = System.Drawing.SystemColors.Info;
- this.components = new System.ComponentModel.Container ();
- this.ForeColor = System.Drawing.SystemColors.InfoText;
- this.TabStop = false;
+ BackColor = SystemColors.Info;
+ components = new Container();
+ ForeColor = SystemColors.InfoText;
+ TabStop = false;
}
- //
- //
- //
- // Overrides the text property of Control. This label ignores
- // the text property, so we add additional attributes here so the
- // property does not show up in the properties window and is not
- // persisted.
- //
- //
- //
- [
- Browsable(false),
- EditorBrowsable(EditorBrowsableState.Never),
- DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
- ]
- public override string Text
+ //
+ //
+ //
+ // Overrides the text property of Control. This label ignores
+ // the text property, so we add additional attributes here so the
+ // property does not show up in the properties window and is not
+ // persisted.
+ //
+ //
+ //
+ [
+ Browsable(false),
+ EditorBrowsable(EditorBrowsableState.Never),
+ DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
+ ]
+ public override string Text
+ {
+ get => base.Text; set => base.Text = value;
+ }
+
+ //
+ //
+ //
+ // This implements the IExtenderProvider.CanExtend method. The
+ // help label provides an extender property, and the design time
+ // framework will call this method once for each component to determine
+ // if we are interested in providing our extended properties for the
+ // component. We return true here if the object is a control and is
+ // not a HelpLabel (since it would be silly to add this property to
+ // ourselves).
+ //
+ //
+ //
+ bool IExtenderProvider.CanExtend(object target) => target is Control and
+ not HelpLabel;
+
+ //
+ //
+ //
+ // This is the extended property for the HelpText property. Extended
+ // properties are actual methods because they take an additional parameter
+ // that is the object or control to provide the property for.
+ //
+ //
+ //
+ [
+ DefaultValue(""),
+ ]
+ public string GetHelpText(Control control)
+ {
+ string text = (string)helpTexts[control];
+ text ??= string.Empty;
+ return text;
+ }
+
+ //
+ //
+ //
+ // This is an event handler that responds to the OnControlEnter
+ // event. We attach this to each control we are providing help
+ // text for.
+ //
+ //
+ //
+ void OnControlEnter(object sender, EventArgs e)
+ {
+ activeControl = (Control)sender;
+ Invalidate();
+ }
+
+ //
+ //
+ //
+ // This is an event handler that responds to the OnControlLeave
+ // event. We attach this to each control we are providing help
+ // text for.
+ //
+ //
+ //
+ void OnControlLeave(object sender, EventArgs e)
+ {
+ if (sender == activeControl)
{
- get
- {
- return base.Text;
- }
- set
- {
- base.Text = value;
- }
+ activeControl = null;
+ Invalidate();
}
+ }
- //
- //
- //
- // This implements the IExtenderProvider.CanExtend method. The
- // help label provides an extender property, and the design time
- // framework will call this method once for each component to determine
- // if we are interested in providing our extended properties for the
- // component. We return true here if the object is a control and is
- // not a HelpLabel (since it would be silly to add this property to
- // ourselves).
- //
- //
- //
- bool IExtenderProvider.CanExtend(object target)
+ //
+ //
+ //
+ // This is the extended property for the HelpText property.
+ //
+ //
+ //
+ public void SetHelpText(Control control, string value)
+ {
+ value ??= string.Empty;
+
+ if (value.Length == 0)
{
- if (target is Control &&
- !(target is HelpLabel))
- {
- return true;
- }
- return false;
- }
+ helpTexts.Remove(control);
- //
- //
- //
- // This is the extended property for the HelpText property. Extended
- // properties are actual methods because they take an additional parameter
- // that is the object or control to provide the property for.
- //
- //
- //
- [
- DefaultValue(""),
- ]
- public string GetHelpText(Control control)
+ control.Enter -= OnControlEnter;
+ control.Leave -= OnControlLeave;
+ }
+ else
{
- string text = (string)helpTexts[control];
- text ??= string.Empty;
- return text;
+ helpTexts[control] = value;
+
+ control.Enter += OnControlEnter;
+ control.Leave += OnControlLeave;
}
- //
- //
- //
- // This is an event handler that responds to the OnControlEnter
- // event. We attach this to each control we are providing help
- // text for.
- //
- //
- //
- private void OnControlEnter(object sender, EventArgs e)
+ if (control == activeControl)
{
- activeControl = (Control)sender;
Invalidate();
}
+ }
+ //
+ //
+ //
+ // Overrides Control.OnPaint. Here we draw our
+ // label.
+ //
+ //
+ //
+ protected override void OnPaint(PaintEventArgs pe)
+ {
+ // Let the base draw. This will cover our back
+ // color and set any image that the user may have
+ // provided.
//
- //
- //
- // This is an event handler that responds to the OnControlLeave
- // event. We attach this to each control we are providing help
- // text for.
- //
- //
+ base.OnPaint(pe);
+
+ // Draw a rectangle around our control.
+ //
+ Rectangle rect = ClientRectangle;
+
+ Pen borderPen = new(ForeColor);
+ pe.Graphics.DrawRectangle(borderPen, rect);
+ borderPen.Dispose();
+
+ // Finally, draw the text over the top of the
+ // rectangle.
//
- private void OnControlLeave(object sender, EventArgs e)
+ if (activeControl != null)
{
- if (sender == activeControl)
+ string text = (string)helpTexts[activeControl];
+ if (!string.IsNullOrEmpty(text))
{
- activeControl = null;
- Invalidate();
+ rect.Inflate(-2, -2);
+ Brush brush = new SolidBrush(ForeColor);
+ pe.Graphics.DrawString(text, Font, brush, rect);
+ brush.Dispose();
}
}
+ }
- //
- //
- //
- // This is the extended property for the HelpText property.
- //
- //
- //
- public void SetHelpText(Control control, string value)
- {
- value ??= string.Empty;
+ //
+ //
+ // Returns true if the backColor should be persisted in code gen. We
+ // override this because we change the default back color.
+ //
+ //
+ // true if the backColor should be persisted.
+ //
+ //
+ //
+ public bool ShouldSerializeBackColor() => !BackColor.Equals(SystemColors.Info);
- if (value.Length == 0)
- {
- helpTexts.Remove(control);
+ //
+ //
+ // Returns true if the foreColor should be persisted in code gen. We
+ // override this because we change the default foreground color.
+ //
+ //
+ // true if the foreColor should be persisted.
+ //
+ //
+ //
+ public bool ShouldSerializeForeColor() => !ForeColor.Equals(SystemColors.InfoText);
- control.Enter -= new EventHandler(OnControlEnter);
- control.Leave -= new EventHandler(OnControlLeave);
- }
- else
- {
- helpTexts[control] = value;
+ //
+ //
+ //
+ //
+ // This is a designer for the HelpLabel. This designer provides
+ // design time feedback for the label. The help label responds
+ // to changes in the active control, but these events do not
+ // occur at design time. In order to provide some usable feedback
+ // that the control is working the right way, this designer listens
+ // to selection change events and uses those events to trigger active
+ // control changes.
+ //
+ //
+ //
+ public class HelpLabelDesigner : ControlDesigner
+ {
+ bool trackSelection = true;
- control.Enter += new EventHandler(OnControlEnter);
- control.Leave += new EventHandler(OnControlLeave);
+ ///
+ /// This property is added to the control's set of properties in the method
+ /// PreFilterProperties below. Note that on designers, properties that are
+ /// explicitly declared by TypeDescriptor.CreateProperty can be declared as
+ /// private on the designer. This helps to keep the designer's public
+ /// object model clean.
+ ///
+ [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
+ bool TrackSelection
+ {
+ get => trackSelection;
+ set
+ {
+ trackSelection = value;
+ if (trackSelection)
+ {
+ ISelectionService ss = (ISelectionService)GetService(typeof(ISelectionService));
+ if (ss != null)
+ {
+ UpdateHelpLabelSelection(ss);
+ }
+ }
+ else
+ {
+ HelpLabel helpLabel = (HelpLabel)Control;
+ if (helpLabel.activeControl != null)
+ {
+ helpLabel.activeControl = null;
+ helpLabel.Invalidate();
+ }
+ }
}
+ }
- if (control == activeControl)
+ public override DesignerVerbCollection Verbs
+ {
+ get
{
- Invalidate();
+ DesignerVerb[] verbs = [
+ new("Sample Verb", new EventHandler(OnSampleVerb))
+ ];
+ return [.. verbs];
}
}
//
//
//
- // Overrides Control.OnPaint. Here we draw our
- // label.
+ // Overrides Dispose. Here we remove our handler for the selection changed
+ // event. With designers, it is critical that they clean up any events they
+ // have attached. Otherwise, during the course of an editing session many
+ // designers may get created and never destroyed.
//
//
//
- protected override void OnPaint(PaintEventArgs pe)
+ protected override void Dispose(bool disposing)
{
-
- // Let the base draw. This will cover our back
- // color and set any image that the user may have
- // provided.
- //
- base.OnPaint(pe);
-
- // Draw a rectangle around our control.
- //
- Rectangle rect = ClientRectangle;
-
- Pen borderPen = new Pen(ForeColor);
- pe.Graphics.DrawRectangle(borderPen, rect);
- borderPen.Dispose();
-
- // Finally, draw the text over the top of the
- // rectangle.
- //
- if (activeControl != null)
+ if (disposing)
{
- string text = (string)helpTexts[activeControl];
- if (text != null && text.Length > 0)
+ ISelectionService ss = (ISelectionService)GetService(typeof(ISelectionService));
+ if (ss != null)
{
- rect.Inflate(-2, -2);
- Brush brush = new SolidBrush(ForeColor);
- pe.Graphics.DrawString(text, Font, brush, rect);
- brush.Dispose();
+ ss.SelectionChanged -= OnSelectionChanged;
}
}
- }
- //
- //
- // Returns true if the backColor should be persisted in code gen. We
- // override this because we change the default back color.
- //
- //
- // true if the backColor should be persisted.
- //
- //
- //
- public bool ShouldSerializeBackColor()
- {
- return(!BackColor.Equals(SystemColors.Info));
+ base.Dispose(disposing);
}
+ //
//
//
- // Returns true if the foreColor should be persisted in code gen. We
- // override this because we change the default foreground color.
+ // Overrides initialize. Here we add an event handler to the selection service.
+ // Notice that we are very careful not to assume that the selection service is
+ // available. It is entirely optional that a service is available and you should
+ // always degrade gracefully if a service could not be found.
//
- //
- // true if the foreColor should be persisted.
- //
//
//
- public bool ShouldSerializeForeColor()
+ public override void Initialize(IComponent component)
{
- return(!ForeColor.Equals(SystemColors.InfoText));
+ base.Initialize(component);
+
+ ISelectionService ss = (ISelectionService)GetService(typeof(ISelectionService));
+ if (ss != null)
+ {
+ ss.SelectionChanged += OnSelectionChanged;
+ }
}
-//
+ void OnSampleVerb(object sender, EventArgs e) => MessageBox.Show("You have just invoked a sample verb. Normally, this would do something interesting.");
+
//
//
//
- // This is a designer for the HelpLabel. This designer provides
- // design time feedback for the label. The help label responds
- // to changes in the active control, but these events do not
- // occur at design time. In order to provide some usable feedback
- // that the control is working the right way, this designer listens
- // to selection change events and uses those events to trigger active
- // control changes.
+ // Our handler for the selection change event. Here we update the active control within
+ // the help label.
//
//
//
- public class HelpLabelDesigner : System.Windows.Forms.Design.ControlDesigner
+ void OnSelectionChanged(object sender, EventArgs e)
{
-
- private bool trackSelection = true;
-
- ///
- /// This property is added to the control's set of properties in the method
- /// PreFilterProperties below. Note that on designers, properties that are
- /// explicitly declared by TypeDescriptor.CreateProperty can be declared as
- /// private on the designer. This helps to keep the designer's public
- /// object model clean.
- ///
- [DesignerSerializationVisibility( DesignerSerializationVisibility.Hidden )]
- private bool TrackSelection
+ if (trackSelection)
{
- get
- {
- return trackSelection;
- }
- set
- {
- trackSelection = value;
- if (trackSelection)
- {
- ISelectionService ss = (ISelectionService)GetService(typeof(ISelectionService));
- if (ss != null)
- {
- UpdateHelpLabelSelection(ss);
- }
- }
- else
- {
- HelpLabel helpLabel = (HelpLabel)Control;
- if (helpLabel.activeControl != null)
- {
- helpLabel.activeControl = null;
- helpLabel.Invalidate();
- }
- }
- }
- }
-
- public override DesignerVerbCollection Verbs
- {
- get
- {
- DesignerVerb[] verbs = new DesignerVerb[] {
- new DesignerVerb("Sample Verb", new EventHandler(OnSampleVerb))
- };
- return new DesignerVerbCollection(verbs);
- }
- }
-
- //
- //
- //
- // Overrides Dispose. Here we remove our handler for the selection changed
- // event. With designers, it is critical that they clean up any events they
- // have attached. Otherwise, during the course of an editing session many
- // designers may get created and never destroyed.
- //
- //
- //
- protected override void Dispose(bool disposing)
- {
- if (disposing)
- {
- ISelectionService ss = (ISelectionService)GetService(typeof(ISelectionService));
- if (ss != null)
- {
- ss.SelectionChanged -= new EventHandler(OnSelectionChanged);
- }
- }
-
- base.Dispose(disposing);
- }
-
- //
- //
- //
- // Overrides initialize. Here we add an event handler to the selection service.
- // Notice that we are very careful not to assume that the selection service is
- // available. It is entirely optional that a service is available and you should
- // always degrade gracefully if a service could not be found.
- //
- //
- //
- public override void Initialize(IComponent component)
- {
- base.Initialize(component);
-
- ISelectionService ss = (ISelectionService)GetService(typeof(ISelectionService));
- if (ss != null)
- {
- ss.SelectionChanged += new EventHandler(OnSelectionChanged);
- }
- }
-
- private void OnSampleVerb(object sender, EventArgs e)
- {
- MessageBox.Show("You have just invoked a sample verb. Normally, this would do something interesting.");
+ ISelectionService ss = (ISelectionService)sender;
+ UpdateHelpLabelSelection(ss);
}
+ }
- //
- //
- //
- // Our handler for the selection change event. Here we update the active control within
- // the help label.
- //
- //
- //
- private void OnSelectionChanged(object sender, EventArgs e)
- {
- if (trackSelection)
- {
- ISelectionService ss = (ISelectionService)sender;
- UpdateHelpLabelSelection(ss);
- }
- }
+ protected override void PreFilterProperties(IDictionary properties)
+ {
+ // Always call base first in PreFilter* methods, and last in PostFilter*
+ // methods.
+ base.PreFilterProperties(properties);
+
+ // We add a design-time property called "TrackSelection" that is used to track
+ // the active selection. If the user sets this to true (the default), then
+ // we will listen to selection change events and update the control's active
+ // control to point to the current primary selection.
+ properties["TrackSelection"] = TypeDescriptor.CreateProperty(
+ GetType(), // the type this property is defined on
+ "TrackSelection", // the name of the property
+ typeof(bool), // the type of the property
+ [CategoryAttribute.Design]); // attributes
+ }
- protected override void PreFilterProperties(IDictionary properties)
+ ///
+ /// This is a helper method that, given a selection service, will update the active control
+ /// of our help label with the currently active selection.
+ ///
+ ///
+ void UpdateHelpLabelSelection(ISelectionService ss)
+ {
+ HelpLabel helpLabel = (HelpLabel)Control;
+ if (ss.PrimarySelection is Control c)
{
- // Always call base first in PreFilter* methods, and last in PostFilter*
- // methods.
- base.PreFilterProperties(properties);
-
- // We add a design-time property called "TrackSelection" that is used to track
- // the active selection. If the user sets this to true (the default), then
- // we will listen to selection change events and update the control's active
- // control to point to the current primary selection.
- properties["TrackSelection"] = TypeDescriptor.CreateProperty(
- this.GetType(), // the type this property is defined on
- "TrackSelection", // the name of the property
- typeof(bool), // the type of the property
- new Attribute[] {CategoryAttribute.Design}); // attributes
+ helpLabel.activeControl = c;
+ helpLabel.Invalidate();
}
-
- ///
- /// This is a helper method that, given a selection service, will update the active control
- /// of our help label with the currently active selection.
- ///
- ///
- private void UpdateHelpLabelSelection(ISelectionService ss)
+ else
{
- Control c = ss.PrimarySelection as Control;
- HelpLabel helpLabel = (HelpLabel)Control;
- if (c != null)
+ if (helpLabel.activeControl != null)
{
- helpLabel.activeControl = c;
+ helpLabel.activeControl = null;
helpLabel.Invalidate();
}
- else
- {
- if (helpLabel.activeControl != null)
- {
- helpLabel.activeControl = null;
- helpLabel.Invalidate();
- }
- }
}
}
- //
}
+ //
}
//
diff --git a/snippets/csharp/System.ComponentModel/IExtenderProvider/Overview/HostApp.cs b/snippets/csharp/System.ComponentModel/IExtenderProvider/Overview/HostApp.cs
index f2e4ba2b962..c3bbe62ac61 100644
--- a/snippets/csharp/System.ComponentModel/IExtenderProvider/Overview/HostApp.cs
+++ b/snippets/csharp/System.ComponentModel/IExtenderProvider/Overview/HostApp.cs
@@ -1,97 +1,91 @@
//
-namespace Microsoft.Samples.WinForms.Cs.HostApp
-{
- using System;
- using System.ComponentModel;
- using System.Drawing;
- using System.Windows.Forms;
- using Microsoft.Samples.WinForms.Cs.HelpLabel;
- public class HostApp : System.Windows.Forms.Form
- {
- ///
- /// Required designer variable.
- ///
- private System.ComponentModel.Container components;
- private System.Windows.Forms.Label label1;
- private System.Windows.Forms.TextBox textBox1;
- private System.Windows.Forms.Button button1;
- private Microsoft.Samples.WinForms.Cs.HelpLabel.HelpLabel helpLabel1;
+using System;
+using System.ComponentModel;
+using System.Drawing;
+using System.Windows.Forms;
+using SAMP = Microsoft.Samples.WinForms.Cs.HelpLabel;
+
+namespace Microsoft.Samples.WinForms.Cs.HostApp;
+public class HostApp : Form
+{
+ ///
+ /// Required designer variable.
+ ///
+ Container components;
+ Label label1;
+ TextBox textBox1;
+ Button button1;
+ SAMP.HelpLabel helpLabel1;
- public HostApp()
- {
- //
- // Required for Windows Form Designer support
- //
- InitializeComponent();
- }
+ public HostApp() =>
+ //
+ // Required for Windows Form Designer support
+ //
+ InitializeComponent();
- ///
- /// Clean up any resources being used.
- ///
- protected override void Dispose(bool disposing)
- {
- if (disposing)
- {
- components.Dispose();
- }
- base.Dispose(disposing);
- }
+ ///
+ /// Clean up any resources being used.
+ ///
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ components.Dispose();
+ }
+ base.Dispose(disposing);
+ }
- ///
- /// Required method for Designer support - do not modify
- /// the contents of this method with the code editor.
- ///
- private void InitializeComponent()
- {
- this.components = new System.ComponentModel.Container();
- this.label1 = new System.Windows.Forms.Label();
- this.button1 = new System.Windows.Forms.Button();
- this.textBox1 = new System.Windows.Forms.TextBox();
- this.helpLabel1 = new Microsoft.Samples.WinForms.Cs.HelpLabel.HelpLabel();
+ ///
+ /// Required method for Designer support - do not modify
+ /// the contents of this method with the code editor.
+ ///
+ void InitializeComponent()
+ {
+ components = new Container();
+ label1 = new Label();
+ button1 = new Button();
+ textBox1 = new TextBox();
+ helpLabel1 = new SAMP.HelpLabel();
- label1.Location = new System.Drawing.Point(16, 16);
- label1.Text = "Name:";
- label1.Size = new System.Drawing.Size(56, 24);
- label1.TabIndex = 3;
+ label1.Location = new Point(16, 16);
+ label1.Text = "Name:";
+ label1.Size = new Size(56, 24);
+ label1.TabIndex = 3;
- helpLabel1.Dock = System.Windows.Forms.DockStyle.Bottom;
- helpLabel1.Size = new System.Drawing.Size(448, 40);
- helpLabel1.TabIndex = 0;
- helpLabel1.Location = new System.Drawing.Point(0, 117);
+ helpLabel1.Dock = DockStyle.Bottom;
+ helpLabel1.Size = new Size(448, 40);
+ helpLabel1.TabIndex = 0;
+ helpLabel1.Location = new Point(0, 117);
- button1.Anchor = AnchorStyles.Right | AnchorStyles.Bottom;
- button1.Size = new System.Drawing.Size(104, 40);
- button1.TabIndex = 1;
- helpLabel1.SetHelpText(button1, "This is the Save Button. Press the Save Button to save your work.");
- button1.Text = "&Save";
- button1.Location = new System.Drawing.Point(336, 56);
+ button1.Anchor = AnchorStyles.Right | AnchorStyles.Bottom;
+ button1.Size = new Size(104, 40);
+ button1.TabIndex = 1;
+ helpLabel1.SetHelpText(button1, "This is the Save Button. Press the Save Button to save your work.");
+ button1.Text = "&Save";
+ button1.Location = new Point(336, 56);
- this.Text = "Control Example";
- this.ClientSize = new System.Drawing.Size(448, 157);
+ Text = "Control Example";
+ ClientSize = new Size(448, 157);
- textBox1.Anchor = AnchorStyles.Left| AnchorStyles.Right | AnchorStyles.Top;
- textBox1.Location = new System.Drawing.Point(80, 16);
- textBox1.Text = "";
- helpLabel1.SetHelpText(textBox1, "This is the name field. Please enter your name here.");
- textBox1.TabIndex = 2;
- textBox1.Size = new System.Drawing.Size(360, 20);
+ textBox1.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
+ textBox1.Location = new Point(80, 16);
+ textBox1.Text = "";
+ helpLabel1.SetHelpText(textBox1, "This is the name field. Please enter your name here.");
+ textBox1.TabIndex = 2;
+ textBox1.Size = new Size(360, 20);
- this.Controls.Add(label1);
- this.Controls.Add(textBox1);
- this.Controls.Add(button1);
- this.Controls.Add(helpLabel1);
- }
+ Controls.Add(label1);
+ Controls.Add(textBox1);
+ Controls.Add(button1);
+ Controls.Add(helpLabel1);
+ }
- ///
- /// The main entry point for the application.
- ///
- [STAThread]
- public static void Main(string[] args)
- {
- Application.Run(new HostApp());
- }
- }
+ ///
+ /// The main entry point for the application.
+ ///
+ [STAThread]
+ public static void Main() => Application.Run(new HostApp());
}
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System.ComponentModel/IExtenderProvider/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/IExtenderProvider/Overview/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/IExtenderProvider/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/IExtenderProvider/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/IListSource/Overview/BusinessObjectBase.cs b/snippets/csharp/System.ComponentModel/IListSource/Overview/BusinessObjectBase.cs
index 1d59e60d33d..178528dbd12 100644
--- a/snippets/csharp/System.ComponentModel/IListSource/Overview/BusinessObjectBase.cs
+++ b/snippets/csharp/System.ComponentModel/IListSource/Overview/BusinessObjectBase.cs
@@ -1,32 +1,18 @@
//
-using System;
-using System.Collections.Generic;
-using System.Text;
using System.ComponentModel;
-using System.Diagnostics;
-namespace IListSourceCS
+namespace IListSourceCS;
+
+public class BusinessObjectBase : INotifyPropertyChanged
{
- public class BusinessObjectBase : INotifyPropertyChanged
- {
- #region INotifyPropertyChanged Members
+ #region INotifyPropertyChanged Members
- public event PropertyChangedEventHandler PropertyChanged;
+ public event PropertyChangedEventHandler PropertyChanged;
- protected virtual void OnPropertyChanged(string propertyName)
- {
- OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
- }
+ protected virtual void OnPropertyChanged(string propertyName) => OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
- private void OnPropertyChanged(PropertyChangedEventArgs e)
- {
- if (null != PropertyChanged)
- {
- PropertyChanged(this, e);
- }
- }
+ void OnPropertyChanged(PropertyChangedEventArgs e) => PropertyChanged?.Invoke(this, e);
- #endregion
- }
+ #endregion
}
//
diff --git a/snippets/csharp/System.ComponentModel/IListSource/Overview/Employee.cs b/snippets/csharp/System.ComponentModel/IListSource/Overview/Employee.cs
index b087fc185ba..f8a434b1d29 100644
--- a/snippets/csharp/System.ComponentModel/IListSource/Overview/Employee.cs
+++ b/snippets/csharp/System.ComponentModel/IListSource/Overview/Employee.cs
@@ -1,65 +1,57 @@
//
using System;
-using System.Collections.Generic;
-using System.Text;
-using System.ComponentModel;
-namespace IListSourceCS
+namespace IListSourceCS;
+
+public class Employee : BusinessObjectBase
{
- public class Employee : BusinessObjectBase
- {
- private string _id;
- private string _name;
- private Decimal parkingId;
+ string _name;
+ decimal parkingId;
- public Employee() : this(string.Empty, 0) {}
- public Employee(string name) : this(name, 0) {}
+ public Employee() : this(string.Empty, 0) { }
+ public Employee(string name) : this(name, 0) { }
- public Employee(string name, Decimal parkingId) : base()
- {
- this._id = System.Guid.NewGuid().ToString();
+ public Employee(string name, decimal parkingId) : base()
+ {
+ ID = Guid.NewGuid().ToString();
- // Set values
- this.Name = name;
- this.ParkingID = parkingId;
- }
+ // Set values
+ Name = name;
+ ParkingID = parkingId;
+ }
- public string ID
- {
- get { return _id; }
- }
+ public string ID { get; }
- const string NAME = "Name";
- public string Name
+ const string NAME = "Name";
+ public string Name
+ {
+ get => _name;
+ set
{
- get { return _name; }
- set
+ if (_name != value)
{
- if (_name != value)
- {
- _name = value;
+ _name = value;
- // Raise the PropertyChanged event.
- OnPropertyChanged(NAME);
- }
+ // Raise the PropertyChanged event.
+ OnPropertyChanged(NAME);
}
}
+ }
- const string PARKING_ID = "Salary";
- public Decimal ParkingID
+ const string PARKING_ID = "Salary";
+ public decimal ParkingID
+ {
+ get => parkingId;
+ set
{
- get { return parkingId; }
- set
+ if (parkingId != value)
{
- if (parkingId != value)
- {
- parkingId = value;
+ parkingId = value;
- // Raise the PropertyChanged event.
- OnPropertyChanged(PARKING_ID);
- }
+ // Raise the PropertyChanged event.
+ OnPropertyChanged(PARKING_ID);
}
}
}
}
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System.ComponentModel/IListSource/Overview/EmployeeListSource.cs b/snippets/csharp/System.ComponentModel/IListSource/Overview/EmployeeListSource.cs
index c69875cb3be..7133ecb8eea 100644
--- a/snippets/csharp/System.ComponentModel/IListSource/Overview/EmployeeListSource.cs
+++ b/snippets/csharp/System.ComponentModel/IListSource/Overview/EmployeeListSource.cs
@@ -1,51 +1,41 @@
//
-using System;
-using System.Collections.Generic;
-using System.Text;
using System.ComponentModel;
-namespace IListSourceCS
+namespace IListSourceCS;
+
+public class EmployeeListSource : Component, IListSource
{
- public class EmployeeListSource : Component, IListSource
+ public EmployeeListSource() { }
+
+ public EmployeeListSource(IContainer container) => container.Add(this);
+
+ //
+ #region IListSource Members
+
+ //
+ bool IListSource.ContainsListCollection => false;
+ //
+
+ //
+ System.Collections.IList IListSource.GetList()
{
- public EmployeeListSource() {}
-
- public EmployeeListSource(IContainer container)
- {
- container.Add(this);
- }
-
- //
- #region IListSource Members
-
- //
- bool IListSource.ContainsListCollection
- {
- get { return false; }
- }
- //
-
- //
- System.Collections.IList IListSource.GetList()
- {
- BindingList ble = new BindingList();
-
- if (!this.DesignMode)
- {
- ble.Add(new Employee("Aaberg, Jesper", 26000000));
- ble.Add(new Employee("Cajhen, Janko", 19600000));
- ble.Add(new Employee("Furse, Kari", 19000000));
- ble.Add(new Employee("Langhorn, Carl", 16000000));
- ble.Add(new Employee("Todorov, Teodor", 15700000));
- ble.Add(new Employee("Verebélyi, Ágnes", 15700000));
- }
-
- return ble;
- }
- //
-
- #endregion
- //
+ BindingList ble = DesignMode
+ ? []
+ : [
+ new("Aaberg, Jesper", 26000000),
+ new ("Aaberg, Jesper", 26000000),
+ new ("Cajhen, Janko", 19600000),
+ new ("Furse, Kari", 19000000),
+ new ("Langhorn, Carl", 16000000),
+ new ("Todorov, Teodor", 15700000),
+ new ("Verebélyi, Ágnes", 15700000)
+ ];
+
+ return ble;
}
+ //
+
+ #endregion
+ //
}
//
diff --git a/snippets/csharp/System.ComponentModel/IListSource/Overview/Form1.cs b/snippets/csharp/System.ComponentModel/IListSource/Overview/Form1.cs
index 8f198a4ac1b..d20ebf7b825 100644
--- a/snippets/csharp/System.ComponentModel/IListSource/Overview/Form1.cs
+++ b/snippets/csharp/System.ComponentModel/IListSource/Overview/Form1.cs
@@ -1,152 +1,145 @@
//
using System;
-using System.Collections.Generic;
using System.ComponentModel;
-using System.Data;
using System.Drawing;
-using System.Text;
using System.Windows.Forms;
-namespace IListSourceCS
+namespace IListSourceCS;
+
+public class Form1 : Form
{
- public class Form1 : Form
- {
- private System.ComponentModel.IContainer components = null;
- private FlowLayoutPanel flowLayoutPanel1;
- private Label label2;
- private DataGridView dataGridView1;
- private DataGridViewTextBoxColumn nameDataGridViewTextBoxColumn;
- private DataGridViewTextBoxColumn salaryDataGridViewTextBoxColumn;
- private DataGridViewTextBoxColumn iDDataGridViewTextBoxColumn;
- private EmployeeListSource employeeListSource1;
+ Container components;
+ FlowLayoutPanel flowLayoutPanel1;
+ Label label2;
+ DataGridView dataGridView1;
+ DataGridViewTextBoxColumn nameDataGridViewTextBoxColumn;
+ DataGridViewTextBoxColumn salaryDataGridViewTextBoxColumn;
+ DataGridViewTextBoxColumn iDDataGridViewTextBoxColumn;
+ EmployeeListSource employeeListSource1;
- public Form1()
- {
- InitializeComponent();
- }
+ public Form1() => InitializeComponent();
- protected override void Dispose(bool disposing)
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing && (components != null))
{
- if (disposing && (components != null))
- {
- components.Dispose();
- }
- base.Dispose(disposing);
+ components.Dispose();
}
+ base.Dispose(disposing);
+ }
- #region Windows Form Designer generated code
-
- private void InitializeComponent()
- {
- this.components = new System.ComponentModel.Container();
- System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
- System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle();
- this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel();
- this.label2 = new System.Windows.Forms.Label();
- this.dataGridView1 = new System.Windows.Forms.DataGridView();
- this.nameDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
- this.salaryDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
- this.iDDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
- this.employeeListSource1 = new EmployeeListSource(this.components);
- this.flowLayoutPanel1.SuspendLayout();
- ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
- this.SuspendLayout();
- //
- // flowLayoutPanel1
- //
- this.flowLayoutPanel1.AutoSize = true;
- this.flowLayoutPanel1.Controls.Add(this.label2);
- this.flowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Top;
- this.flowLayoutPanel1.Location = new System.Drawing.Point(0, 0);
- this.flowLayoutPanel1.Name = "flowLayoutPanel1";
- this.flowLayoutPanel1.Size = new System.Drawing.Size(416, 51);
- this.flowLayoutPanel1.TabIndex = 11;
- //
- // label2
- //
- this.label2.AutoSize = true;
- this.label2.Location = new System.Drawing.Point(3, 6);
- this.label2.Margin = new System.Windows.Forms.Padding(3, 6, 3, 6);
- this.label2.Name = "label2";
- this.label2.Size = new System.Drawing.Size(408, 39);
- this.label2.TabIndex = 0;
- this.label2.Text = "This sample demonstrates how to implement the IListSource interface. In this sam" +
- "ple, a DataGridView is bound at design time to a Component (employeeListSource1)" +
- " that implements IListSource.";
- //
- // dataGridView1
- //
- this.dataGridView1.AllowUserToAddRows = false;
- this.dataGridView1.AllowUserToDeleteRows = false;
- dataGridViewCellStyle1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
- this.dataGridView1.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle1;
- this.dataGridView1.AutoGenerateColumns = false;
- this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
- this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
- this.nameDataGridViewTextBoxColumn,
- this.salaryDataGridViewTextBoxColumn,
- this.iDDataGridViewTextBoxColumn});
- this.dataGridView1.DataSource = this.employeeListSource1;
- this.dataGridView1.Dock = System.Windows.Forms.DockStyle.Fill;
- this.dataGridView1.Location = new System.Drawing.Point(0, 51);
- this.dataGridView1.Name = "dataGridView1";
- this.dataGridView1.RowHeadersVisible = false;
- this.dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
- this.dataGridView1.Size = new System.Drawing.Size(416, 215);
- this.dataGridView1.TabIndex = 12;
- //
- // nameDataGridViewTextBoxColumn
- //
- this.nameDataGridViewTextBoxColumn.DataPropertyName = "Name";
- this.nameDataGridViewTextBoxColumn.FillWeight = 131.7987F;
- this.nameDataGridViewTextBoxColumn.HeaderText = "Name";
- this.nameDataGridViewTextBoxColumn.Name = "nameDataGridViewTextBoxColumn";
- //
- // salaryDataGridViewTextBoxColumn
- //
- this.salaryDataGridViewTextBoxColumn.DataPropertyName = "ParkingID";
- this.salaryDataGridViewTextBoxColumn.DefaultCellStyle = dataGridViewCellStyle2;
- this.salaryDataGridViewTextBoxColumn.FillWeight = 121.8274F;
- this.salaryDataGridViewTextBoxColumn.HeaderText = "Parking ID";
- this.salaryDataGridViewTextBoxColumn.Name = "salaryDataGridViewTextBoxColumn";
- //
- // iDDataGridViewTextBoxColumn
- //
- this.iDDataGridViewTextBoxColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
- this.iDDataGridViewTextBoxColumn.DataPropertyName = "ID";
- this.iDDataGridViewTextBoxColumn.FillWeight = 46.37391F;
- this.iDDataGridViewTextBoxColumn.HeaderText = "ID";
- this.iDDataGridViewTextBoxColumn.Name = "iDDataGridViewTextBoxColumn";
- this.iDDataGridViewTextBoxColumn.ReadOnly = true;
- //
- // Form1
- //
- this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
- this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.ClientSize = new System.Drawing.Size(416, 266);
- this.Controls.Add(this.dataGridView1);
- this.Controls.Add(this.flowLayoutPanel1);
- this.Name = "Form1";
- this.Text = "IListSource Sample";
- this.flowLayoutPanel1.ResumeLayout(false);
- this.flowLayoutPanel1.PerformLayout();
- ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
- this.ResumeLayout(false);
- this.PerformLayout();
- }
+ #region Windows Form Designer generated code
- #endregion
+ void InitializeComponent()
+ {
+ components = new Container();
+ DataGridViewCellStyle dataGridViewCellStyle1 = new();
+ DataGridViewCellStyle dataGridViewCellStyle2 = new();
+ flowLayoutPanel1 = new FlowLayoutPanel();
+ label2 = new Label();
+ dataGridView1 = new DataGridView();
+ nameDataGridViewTextBoxColumn = new DataGridViewTextBoxColumn();
+ salaryDataGridViewTextBoxColumn = new DataGridViewTextBoxColumn();
+ iDDataGridViewTextBoxColumn = new DataGridViewTextBoxColumn();
+ employeeListSource1 = new EmployeeListSource(components);
+ flowLayoutPanel1.SuspendLayout();
+ ((ISupportInitialize)dataGridView1).BeginInit();
+ SuspendLayout();
+ //
+ // flowLayoutPanel1
+ //
+ flowLayoutPanel1.AutoSize = true;
+ flowLayoutPanel1.Controls.Add(label2);
+ flowLayoutPanel1.Dock = DockStyle.Top;
+ flowLayoutPanel1.Location = new Point(0, 0);
+ flowLayoutPanel1.Name = "flowLayoutPanel1";
+ flowLayoutPanel1.Size = new Size(416, 51);
+ flowLayoutPanel1.TabIndex = 11;
+ //
+ // label2
+ //
+ label2.AutoSize = true;
+ label2.Location = new Point(3, 6);
+ label2.Margin = new Padding(3, 6, 3, 6);
+ label2.Name = "label2";
+ label2.Size = new Size(408, 39);
+ label2.TabIndex = 0;
+ label2.Text = "This sample demonstrates how to implement the IListSource interface. In this sam" +
+ "ple, a DataGridView is bound at design time to a Component (employeeListSource1)" +
+ " that implements IListSource.";
+ //
+ // dataGridView1
+ //
+ dataGridView1.AllowUserToAddRows = false;
+ dataGridView1.AllowUserToDeleteRows = false;
+ dataGridViewCellStyle1.BackColor = Color.FromArgb(255, 255, 192);
+ dataGridView1.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle1;
+ dataGridView1.AutoGenerateColumns = false;
+ dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
+ dataGridView1.Columns.AddRange([
+ nameDataGridViewTextBoxColumn,
+ salaryDataGridViewTextBoxColumn,
+ iDDataGridViewTextBoxColumn]);
+ dataGridView1.DataSource = employeeListSource1;
+ dataGridView1.Dock = DockStyle.Fill;
+ dataGridView1.Location = new Point(0, 51);
+ dataGridView1.Name = "dataGridView1";
+ dataGridView1.RowHeadersVisible = false;
+ dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
+ dataGridView1.Size = new Size(416, 215);
+ dataGridView1.TabIndex = 12;
+ //
+ // nameDataGridViewTextBoxColumn
+ //
+ nameDataGridViewTextBoxColumn.DataPropertyName = "Name";
+ nameDataGridViewTextBoxColumn.FillWeight = 131.7987F;
+ nameDataGridViewTextBoxColumn.HeaderText = "Name";
+ nameDataGridViewTextBoxColumn.Name = "nameDataGridViewTextBoxColumn";
+ //
+ // salaryDataGridViewTextBoxColumn
+ //
+ salaryDataGridViewTextBoxColumn.DataPropertyName = "ParkingID";
+ salaryDataGridViewTextBoxColumn.DefaultCellStyle = dataGridViewCellStyle2;
+ salaryDataGridViewTextBoxColumn.FillWeight = 121.8274F;
+ salaryDataGridViewTextBoxColumn.HeaderText = "Parking ID";
+ salaryDataGridViewTextBoxColumn.Name = "salaryDataGridViewTextBoxColumn";
+ //
+ // iDDataGridViewTextBoxColumn
+ //
+ iDDataGridViewTextBoxColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
+ iDDataGridViewTextBoxColumn.DataPropertyName = "ID";
+ iDDataGridViewTextBoxColumn.FillWeight = 46.37391F;
+ iDDataGridViewTextBoxColumn.HeaderText = "ID";
+ iDDataGridViewTextBoxColumn.Name = "iDDataGridViewTextBoxColumn";
+ iDDataGridViewTextBoxColumn.ReadOnly = true;
+ //
+ // Form1
+ //
+ AutoScaleDimensions = new SizeF(6F, 13F);
+ AutoScaleMode = AutoScaleMode.Font;
+ ClientSize = new Size(416, 266);
+ Controls.Add(dataGridView1);
+ Controls.Add(flowLayoutPanel1);
+ Name = "Form1";
+ Text = "IListSource Sample";
+ flowLayoutPanel1.ResumeLayout(false);
+ flowLayoutPanel1.PerformLayout();
+ ((ISupportInitialize)dataGridView1).EndInit();
+ ResumeLayout(false);
+ PerformLayout();
}
- static class Program
- {
- [STAThread]
- static void Main()
- {
- Application.EnableVisualStyles();
- Application.SetCompatibleTextRenderingDefault(false);
- Application.Run(new Form1());
- }
+ #endregion
+}
+
+static class Program
+{
+ [STAThread]
+ static void Main()
+ {
+ Application.EnableVisualStyles();
+ Application.SetCompatibleTextRenderingDefault(false);
+ Application.Run(new Form1());
}
}
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System.ComponentModel/IListSource/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/IListSource/Overview/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/IListSource/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/IListSource/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/ISupportInitialize/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/ISupportInitialize/Overview/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/ISupportInitialize/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/ISupportInitialize/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/ISupportInitialize/Overview/form1.cs b/snippets/csharp/System.ComponentModel/ISupportInitialize/Overview/form1.cs
index becabd46418..012c478e4f4 100644
--- a/snippets/csharp/System.ComponentModel/ISupportInitialize/Overview/form1.cs
+++ b/snippets/csharp/System.ComponentModel/ISupportInitialize/Overview/form1.cs
@@ -1,171 +1,162 @@
//
using System;
using System.Drawing;
-using System.Collections;
-using System.ComponentModel;
using System.Windows.Forms;
-using System.Data;
-namespace TrackBar
-{
- ///
- /// Summary description for Form1.
- ///
- public class Form1 : System.Windows.Forms.Form
- {
- private System.Windows.Forms.Panel panel1;
- private System.Windows.Forms.TrackBar trackBar1;
- private System.Windows.Forms.TrackBar trackBar2;
- private System.Windows.Forms.TrackBar trackBar3;
- private System.Windows.Forms.Label label1;
- private System.Windows.Forms.Label label3;
- private System.Windows.Forms.Label label2;
- ///
- /// Required designer variable.
- ///
- public Form1()
- {
- //
- // Required for Windows Form Designer support
- //
- InitializeComponent();
+namespace TrackBar;
- //
- // TODO: Add any constructor code after InitializeComponent call
- //
- //
- trackBar2.Orientation = Orientation.Vertical;
- trackBar3.Orientation = Orientation.Vertical;
- trackBar1.Maximum = trackBar2.Maximum = trackBar3.Maximum = 255;
- trackBar1.Width = 400;
- trackBar2.Height = trackBar3.Height = trackBar1.Width;
- trackBar1.LargeChange = trackBar2.LargeChange = trackBar3.LargeChange = 16;
- //
- }
+///
+/// Summary description for Form1.
+///
+public class Form1 : Form
+{
+ Panel panel1;
+ System.Windows.Forms.TrackBar trackBar1;
+ System.Windows.Forms.TrackBar trackBar2;
+ System.Windows.Forms.TrackBar trackBar3;
+ Label label1;
+ Label label3;
+ Label label2;
+ ///
+ /// Required designer variable.
+ ///
+ public Form1()
+ {
+ //
+ // Required for Windows Form Designer support
+ //
+ InitializeComponent();
- ///
- /// Clean up any resources being used.
- ///
+ //
+ // TODO: Add any constructor code after InitializeComponent call
+ //
+ //
+ trackBar2.Orientation = Orientation.Vertical;
+ trackBar3.Orientation = Orientation.Vertical;
+ trackBar1.Maximum = trackBar2.Maximum = trackBar3.Maximum = 255;
+ trackBar1.Width = 400;
+ trackBar2.Height = trackBar3.Height = trackBar1.Width;
+ trackBar1.LargeChange = trackBar2.LargeChange = trackBar3.LargeChange = 16;
+ //
+ }
- #region Windows Form Designer generated code
- ///
- /// Required method for Designer support - do not modify
- /// the contents of this method with the code editor.
- ///
- private void InitializeComponent()
- {
- this.trackBar1 = new System.Windows.Forms.TrackBar();
- this.trackBar2 = new System.Windows.Forms.TrackBar();
- this.trackBar3 = new System.Windows.Forms.TrackBar();
- this.panel1 = new System.Windows.Forms.Panel();
- this.label1 = new System.Windows.Forms.Label();
- this.label2 = new System.Windows.Forms.Label();
- this.label3 = new System.Windows.Forms.Label();
- //
- ((System.ComponentModel.ISupportInitialize)(this.trackBar1)).BeginInit();
- ((System.ComponentModel.ISupportInitialize)(this.trackBar2)).BeginInit();
- ((System.ComponentModel.ISupportInitialize)(this.trackBar3)).BeginInit();
- this.SuspendLayout();
- //
- // trackBar1
- //
- this.trackBar1.Location = new System.Drawing.Point(160, 400);
- this.trackBar1.Name = "trackBar1";
- this.trackBar1.TabIndex = 1;
- this.trackBar1.Scroll += new System.EventHandler(this.trackBar_Scroll);
- //
- // trackBar2
- //
- this.trackBar2.Location = new System.Drawing.Point(608, 40);
- this.trackBar2.Name = "trackBar2";
- this.trackBar2.TabIndex = 2;
- this.trackBar2.Scroll += new System.EventHandler(this.trackBar_Scroll);
- //
- // trackBar3
- //
- this.trackBar3.Location = new System.Drawing.Point(56, 40);
- this.trackBar3.Name = "trackBar3";
- this.trackBar3.TabIndex = 3;
- this.trackBar3.Scroll += new System.EventHandler(this.trackBar_Scroll);
- ((System.ComponentModel.ISupportInitialize)(this.trackBar1)).EndInit();
- ((System.ComponentModel.ISupportInitialize)(this.trackBar2)).EndInit();
- ((System.ComponentModel.ISupportInitialize)(this.trackBar3)).EndInit();
- //
- //
- // panel1
- //
- this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
- this.panel1.Location = new System.Drawing.Point(128, 32);
- this.panel1.Name = "panel1";
- this.panel1.Size = new System.Drawing.Size(464, 352);
- this.panel1.TabIndex = 0;
- //
- // label1
- //
- this.label1.Location = new System.Drawing.Point(288, 448);
- this.label1.Name = "label1";
- this.label1.TabIndex = 4;
- //
- // label2
- //
- this.label2.Location = new System.Drawing.Point(600, 16);
- this.label2.Name = "label2";
- this.label2.Size = new System.Drawing.Size(120, 16);
- this.label2.TabIndex = 5;
- //
- // label3
- //
- this.label3.Location = new System.Drawing.Point(8, 16);
- this.label3.Name = "label3";
- this.label3.Size = new System.Drawing.Size(120, 16);
- this.label3.TabIndex = 6;
- //
- // Form1
- //
- this.ClientSize = new System.Drawing.Size(728, 477);
- this.Controls.AddRange(new System.Windows.Forms.Control[] {this.label3,
- this.label2,
- this.label1,
- this.trackBar3,
- this.trackBar2,
- this.trackBar1,
- this.panel1});
- this.Name = "Form1";
- this.Text = "Color builder";
- this.Load += new System.EventHandler(this.Form1_Load);
- this.ResumeLayout(false);
- }
- #endregion
+ ///
+ /// Clean up any resources being used.
+ ///
+ #region Windows Form Designer generated code
+ ///
+ /// Required method for Designer support - do not modify
+ /// the contents of this method with the code editor.
+ ///
+ void InitializeComponent()
+ {
+ trackBar1 = new System.Windows.Forms.TrackBar();
+ trackBar2 = new System.Windows.Forms.TrackBar();
+ trackBar3 = new System.Windows.Forms.TrackBar();
+ panel1 = new Panel();
+ label1 = new Label();
+ label2 = new Label();
+ label3 = new Label();
+ //
+ trackBar1.BeginInit();
+ trackBar2.BeginInit();
+ trackBar3.BeginInit();
+ SuspendLayout();
+ //
+ // trackBar1
+ //
+ trackBar1.Location = new Point(160, 400);
+ trackBar1.Name = "trackBar1";
+ trackBar1.TabIndex = 1;
+ trackBar1.Scroll += trackBar_Scroll;
+ //
+ // trackBar2
+ //
+ trackBar2.Location = new Point(608, 40);
+ trackBar2.Name = "trackBar2";
+ trackBar2.TabIndex = 2;
+ trackBar2.Scroll += trackBar_Scroll;
+ //
+ // trackBar3
+ //
+ trackBar3.Location = new Point(56, 40);
+ trackBar3.Name = "trackBar3";
+ trackBar3.TabIndex = 3;
+ trackBar3.Scroll += trackBar_Scroll;
+ trackBar1.EndInit();
+ trackBar2.EndInit();
+ trackBar3.EndInit();
+ //
+ //
+ // panel1
+ //
+ panel1.BorderStyle = BorderStyle.Fixed3D;
+ panel1.Location = new Point(128, 32);
+ panel1.Name = "panel1";
+ panel1.Size = new Size(464, 352);
+ panel1.TabIndex = 0;
+ //
+ // label1
+ //
+ label1.Location = new Point(288, 448);
+ label1.Name = "label1";
+ label1.TabIndex = 4;
+ //
+ // label2
+ //
+ label2.Location = new Point(600, 16);
+ label2.Name = "label2";
+ label2.Size = new Size(120, 16);
+ label2.TabIndex = 5;
+ //
+ // label3
+ //
+ label3.Location = new Point(8, 16);
+ label3.Name = "label3";
+ label3.Size = new Size(120, 16);
+ label3.TabIndex = 6;
+ //
+ // Form1
+ //
+ ClientSize = new Size(728, 477);
+ Controls.AddRange(
+ [
+ label3,
+ label2,
+ label1,
+ trackBar3,
+ trackBar2,
+ trackBar1,
+ panel1
+ ]);
+ Name = "Form1";
+ Text = "Color builder";
+ Load += Form1_Load;
+ ResumeLayout(false);
+ }
+ #endregion
- ///
- /// The main entry point for the application.
- ///
- [STAThread]
- static void Main()
- {
- Application.Run(new Form1());
- }
+ ///
+ /// The main entry point for the application.
+ ///
+ [STAThread]
+ static void Main() => Application.Run(new Form1());
- private void Form1_Load(object sender, System.EventArgs e)
- {
- showColorValueLabels();
- }
- //
- private void showColorValueLabels()
- {
- label1.Text = "Red value is : " + trackBar1.Value.ToString();
- label2.Text = "Green Value is : " + trackBar2.Value.ToString();
- label3.Text = "Blue Value is : " + trackBar3.Value.ToString();
- }
- private void trackBar_Scroll(object sender, System.EventArgs e)
- {
- System.Windows.Forms.TrackBar myTB;
- myTB = (System.Windows.Forms.TrackBar) sender ;
- panel1.BackColor = Color.FromArgb(trackBar1.Value,trackBar2.Value,trackBar3.Value);
- myTB.Text = "Value is " + myTB.Value.ToString();
- showColorValueLabels();
- }
- //
- }
+ void Form1_Load(object sender, EventArgs e) => showColorValueLabels();
+ //
+ void showColorValueLabels()
+ {
+ label1.Text = "Red value is : " + trackBar1.Value.ToString();
+ label2.Text = "Green Value is : " + trackBar2.Value.ToString();
+ label3.Text = "Blue Value is : " + trackBar3.Value.ToString();
+ }
+ void trackBar_Scroll(object sender, EventArgs e)
+ {
+ System.Windows.Forms.TrackBar myTB = (System.Windows.Forms.TrackBar)sender;
+ panel1.BackColor = Color.FromArgb(trackBar1.Value, trackBar2.Value, trackBar3.Value);
+ myTB.Text = "Value is " + myTB.Value.ToString();
+ showColorValueLabels();
+ }
+ //
}
//
diff --git a/snippets/csharp/System.ComponentModel/ITypeDescriptorContext/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/ITypeDescriptorContext/Overview/Project.csproj
index c02dc5044e7..5a1b02db677 100644
--- a/snippets/csharp/System.ComponentModel/ITypeDescriptorContext/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/ITypeDescriptorContext/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0
+ net8.0
\ No newline at end of file
diff --git a/snippets/csharp/System.ComponentModel/ITypeDescriptorContext/Overview/instancedescriptor.cs b/snippets/csharp/System.ComponentModel/ITypeDescriptorContext/Overview/instancedescriptor.cs
index 0b3fd6539de..d997f1a0b9d 100644
--- a/snippets/csharp/System.ComponentModel/ITypeDescriptorContext/Overview/instancedescriptor.cs
+++ b/snippets/csharp/System.ComponentModel/ITypeDescriptorContext/Overview/instancedescriptor.cs
@@ -1,124 +1,97 @@
//
-namespace Microsoft.Samples.InstanceDescriptorSample
-{
- using System;
- using System.ComponentModel;
- using System.ComponentModel.Design.Serialization;
- using System.Drawing;
- using System.Globalization;
- using System.Reflection;
- // This sample shows how to support code generation for a custom type
- // of object using a type converter and InstanceDescriptor objects.
+using System;
+using System.ComponentModel;
+using System.ComponentModel.Design.Serialization;
+using System.Drawing;
+using System.Globalization;
+using System.Reflection;
+
+namespace Microsoft.Samples.InstanceDescriptorSample;
+// This sample shows how to support code generation for a custom type
+// of object using a type converter and InstanceDescriptor objects.
- // To use this code, copy it to a file and add the file to a project.
- // Then add a component to the project and declare a Triangle field and
- // a public property with accessors for the Triangle field on the component.
+// To use this code, copy it to a file and add the file to a project.
+// Then add a component to the project and declare a Triangle field and
+// a public property with accessors for the Triangle field on the component.
- // The Triangle property will be persisted using code generation.
+// The Triangle property will be persisted using code generation.
- [TypeConverter(typeof(Triangle.TriangleConverter))]
- public class Triangle
+[TypeConverter(typeof(TriangleConverter))]
+public class Triangle
+{
+ // Triangle members.
+ Point P1;
+ Point P2;
+ Point P3;
+
+ public Point Point1
+ {
+ get => P1; set => P1 = value;
+ }
+ public Point Point2
+ {
+ get => P2; set => P2 = value;
+ }
+ public Point Point3
{
- // Triangle members.
- Point P1;
- Point P2;
- Point P3;
+ get => P3; set => P3 = value;
+ }
- public Point Point1 {
- get {
- return P1;
- }
- set {
- P1 = value;
- }
- }
- public Point Point2 {
- get
- {
- return P2;
- }
- set
- {
- P2 = value;
- }
- }
- public Point Point3 {
- get
- {
- return P3;
- }
- set
+ public Triangle(Point point1, Point point2, Point point3)
+ {
+ P1 = point1;
+ P2 = point2;
+ P3 = point3;
+ }
+
+ // A TypeConverter for the Triangle object. Note that you can make it internal,
+ // private, or any scope you want and the designers will still be able to use
+ // it through the TypeDescriptor object. This type converter provides the
+ // capability to convert to an InstanceDescriptor. This object can be used by
+ // the .NET Framework to generate source code that creates an instance of a
+ // Triangle object.
+ internal class TriangleConverter : TypeConverter
+ {
+ // This method overrides CanConvertTo from TypeConverter. This is called when someone
+ // wants to convert an instance of Triangle to another type. Here,
+ // only conversion to an InstanceDescriptor is supported.
+ public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
+ {
+ if (destinationType == typeof(InstanceDescriptor))
{
- P3 = value;
+ return true;
}
- }
- public Triangle(Point point1,Point point2,Point point3) {
- P1 = point1;
- P2 = point2;
- P3 = point3;
+ // Always call the base to see if it can perform the conversion.
+ return base.CanConvertTo(context, destinationType);
}
- // A TypeConverter for the Triangle object. Note that you can make it internal,
- // private, or any scope you want and the designers will still be able to use
- // it through the TypeDescriptor object. This type converter provides the
- // capability to convert to an InstanceDescriptor. This object can be used by
- // the .NET Framework to generate source code that creates an instance of a
- // Triangle object.
- internal class TriangleConverter : TypeConverter
+ // This code performs the actual conversion from a Triangle to an InstanceDescriptor.
+ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
- // This method overrides CanConvertTo from TypeConverter. This is called when someone
- // wants to convert an instance of Triangle to another type. Here,
- // only conversion to an InstanceDescriptor is supported.
- public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
+ if (destinationType == typeof(InstanceDescriptor))
{
- if (destinationType == typeof(InstanceDescriptor))
- {
- return true;
- }
-
- // Always call the base to see if it can perform the conversion.
- return base.CanConvertTo(context, destinationType);
+ ConstructorInfo ci = typeof(Triangle).GetConstructor([typeof(Point),
+ typeof(Point),typeof(Point)]);
+ Triangle t = (Triangle)value;
+ return new InstanceDescriptor(ci, new object[] { t.Point1, t.Point2, t.Point3 });
}
- // This code performs the actual conversion from a Triangle to an InstanceDescriptor.
- public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
- {
- if (destinationType == typeof(InstanceDescriptor))
- {
- ConstructorInfo ci = typeof(Triangle).GetConstructor(new Type[]{typeof(Point),
- typeof(Point),typeof(Point)});
- Triangle t = (Triangle) value;
- return new InstanceDescriptor(ci,new object[]{t.Point1,t.Point2,t.Point3});
- }
-
- // Always call base, even if you can't convert.
- return base.ConvertTo(context, culture, value, destinationType);
- }
+ // Always call base, even if you can't convert.
+ return base.ConvertTo(context, culture, value, destinationType);
}
}
+}
- public class TestComponent : System.ComponentModel.Component
- {
- Triangle myTriangle;
-
- public TestComponent() {
- myTriangle = new Triangle(
- new Point(5,5),
- new Point(10,10),
- new Point(1,8)
- );
- }
+public class TestComponent : Component
+{
+ public TestComponent() => MyTriangle = new Triangle(
+ new Point(5, 5),
+ new Point(10, 10),
+ new Point(1, 8)
+ );
- public Triangle MyTriangle {
- get {
- return myTriangle;
- }
- set {
- myTriangle = value;
- }
- }
- }
+ public Triangle MyTriangle { get; set; }
}
//
diff --git a/snippets/csharp/System.ComponentModel/ITypedList/Overview/Customer.cs b/snippets/csharp/System.ComponentModel/ITypedList/Overview/Customer.cs
index 5c15e8ef1f7..ad400cc1f64 100644
--- a/snippets/csharp/System.ComponentModel/ITypedList/Overview/Customer.cs
+++ b/snippets/csharp/System.ComponentModel/ITypedList/Overview/Customer.cs
@@ -1,148 +1,138 @@
//
-using System;
-using System.Collections.Generic;
-using System.Text;
using System.ComponentModel;
-namespace ITypedListCS
+namespace ITypedListCS;
+
+class Customer : INotifyPropertyChanged
{
- class Customer : INotifyPropertyChanged
+ public Customer() { }
+
+ public Customer(int id, string name, string company, string address, string city, string state, string zip)
{
- public Customer() {}
+ _id = id;
+ _name = name;
+ _company = company;
+ _address = address;
+ _city = city;
+ _state = state;
+ _zip = zip;
+ }
+
+ #region Public Properties
- public Customer(int id, string name, string company, string address, string city, string state, string zip)
+ int _id;
+
+ public int ID
+ {
+ get => _id;
+ set
{
- this._id = id;
- this._name = name;
- this._company = company;
- this._address = address;
- this._city = city;
- this._state = state;
- this._zip = zip;
+ if (_id != value)
+ {
+ _id = value;
+ OnPropertyChanged(new PropertyChangedEventArgs(nameof(ID)));
+ }
}
+ }
- #region Public Properties
-
- private int _id;
-
- public int ID
- {
- get { return _id; }
- set
- {
- if (_id != value)
- {
- _id = value;
- OnPropertyChanged(new PropertyChangedEventArgs("ID"));
- }
- }
- }
-
- private string _name;
-
- public string Name
- {
- get { return _name; }
- set
- {
- if (_name != value)
- {
- _name = value;
- OnPropertyChanged(new PropertyChangedEventArgs("Name"));
- }
- }
- }
-
- private string _company;
-
- public string Company
- {
- get { return _company; }
- set
- {
- if (_company != value)
- {
- _company = value;
- OnPropertyChanged(new PropertyChangedEventArgs("Company"));
- }
- }
- }
-
- private string _address;
-
- public string Address
- {
- get { return _address; }
- set
- {
- if (_address != value)
- {
- _address = value;
- OnPropertyChanged(new PropertyChangedEventArgs("Address"));
- }
- }
- }
-
- private string _city;
-
- public string City
- {
- get { return _city; }
- set
- {
- if (_city != value)
- {
- _city = value;
- OnPropertyChanged(new PropertyChangedEventArgs("City"));
- }
- }
- }
-
- private string _state;
-
- public string State
- {
- get { return _state; }
- set
- {
- if (_state != value)
- {
- _state = value;
- OnPropertyChanged(new PropertyChangedEventArgs("State"));
- }
- }
- }
-
- private string _zip;
-
- public string ZipCode
- {
- get { return _zip; }
- set
- {
- if (_zip != value)
- {
- _zip = value;
- OnPropertyChanged(new PropertyChangedEventArgs("ZipCode"));
- }
- }
+ string _name;
+
+ public string Name
+ {
+ get => _name;
+ set
+ {
+ if (_name != value)
+ {
+ _name = value;
+ OnPropertyChanged(new PropertyChangedEventArgs(nameof(Name)));
+ }
+ }
+ }
+
+ string _company;
+
+ public string Company
+ {
+ get => _company;
+ set
+ {
+ if (_company != value)
+ {
+ _company = value;
+ OnPropertyChanged(new PropertyChangedEventArgs(nameof(Company)));
+ }
+ }
+ }
+
+ string _address;
+
+ public string Address
+ {
+ get => _address;
+ set
+ {
+ if (_address != value)
+ {
+ _address = value;
+ OnPropertyChanged(new PropertyChangedEventArgs(nameof(Address)));
+ }
+ }
+ }
+
+ string _city;
+
+ public string City
+ {
+ get => _city;
+ set
+ {
+ if (_city != value)
+ {
+ _city = value;
+ OnPropertyChanged(new PropertyChangedEventArgs(nameof(City)));
+ }
+ }
+ }
+
+ string _state;
+
+ public string State
+ {
+ get => _state;
+ set
+ {
+ if (_state != value)
+ {
+ _state = value;
+ OnPropertyChanged(new PropertyChangedEventArgs(nameof(State)));
+ }
+ }
+ }
+
+ string _zip;
+
+ public string ZipCode
+ {
+ get => _zip;
+ set
+ {
+ if (_zip != value)
+ {
+ _zip = value;
+ OnPropertyChanged(new PropertyChangedEventArgs(nameof(ZipCode)));
+ }
}
+ }
- #endregion
+ #endregion
- #region INotifyPropertyChanged Members
+ #region INotifyPropertyChanged Members
- public event PropertyChangedEventHandler PropertyChanged;
+ public event PropertyChangedEventHandler PropertyChanged;
- protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
- {
- if (null != PropertyChanged)
- {
- PropertyChanged(this, e);
- }
- }
+ protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) => PropertyChanged?.Invoke(this, e);
- #endregion
- }
+ #endregion
}
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System.ComponentModel/ITypedList/Overview/Form1.cs b/snippets/csharp/System.ComponentModel/ITypedList/Overview/Form1.cs
index 8515f42c551..b2f94e3fa38 100644
--- a/snippets/csharp/System.ComponentModel/ITypedList/Overview/Form1.cs
+++ b/snippets/csharp/System.ComponentModel/ITypedList/Overview/Form1.cs
@@ -1,166 +1,160 @@
//
using System;
-using System.Collections.Generic;
using System.ComponentModel;
-using System.Data;
using System.Drawing;
-using System.Text;
using System.Windows.Forms;
-namespace ITypedListCS
+namespace ITypedListCS;
+
+public partial class Form1 : Form
{
- public partial class Form1 : Form
- {
- private SortableBindingList sortableBindingListOfCustomers;
- private BindingList bindingListOfCustomers;
+ SortableBindingList sortableBindingListOfCustomers;
+ BindingList bindingListOfCustomers;
- private System.ComponentModel.IContainer components = null;
- private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1;
- private System.Windows.Forms.Label label2;
- private DataGridView dataGridView1;
- private Button button1;
- private Button button2;
+ readonly IContainer _components;
+ FlowLayoutPanel flowLayoutPanel1;
+ Label label2;
+ DataGridView dataGridView1;
+ Button button1;
+ Button button2;
- public Form1()
- {
- InitializeComponent();
- }
+ public Form1() => InitializeComponent();
- private void Form1_Load(object sender, EventArgs e)
- {
- this.sortableBindingListOfCustomers = new SortableBindingList();
- this.bindingListOfCustomers = new BindingList();
+ void Form1_Load(object sender, EventArgs e)
+ {
+ sortableBindingListOfCustomers = [];
+ bindingListOfCustomers = [];
- this.dataGridView1.DataSource = this.bindingListOfCustomers;
- }
+ dataGridView1.DataSource = bindingListOfCustomers;
+ }
- private void button1_Click(object sender, EventArgs e)
- {
- this.dataGridView1.DataSource = null;
- this.dataGridView1.DataSource = this.sortableBindingListOfCustomers;
- }
+ void button1_Click(object sender, EventArgs e)
+ {
+ dataGridView1.DataSource = null;
+ dataGridView1.DataSource = sortableBindingListOfCustomers;
+ }
- private void button2_Click(object sender, EventArgs e)
- {
- this.dataGridView1.DataSource = null;
- this.dataGridView1.DataSource = this.bindingListOfCustomers;
- }
+ void button2_Click(object sender, EventArgs e)
+ {
+ dataGridView1.DataSource = null;
+ dataGridView1.DataSource = bindingListOfCustomers;
+ }
- protected override void Dispose(bool disposing)
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing && (_components != null))
{
- if (disposing && (components != null))
- {
- components.Dispose();
- }
- base.Dispose(disposing);
+ _components.Dispose();
}
+ base.Dispose(disposing);
+ }
- #region Windows Form Designer generated code
-
- private void InitializeComponent()
- {
- System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
- this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel();
- this.label2 = new System.Windows.Forms.Label();
- this.dataGridView1 = new System.Windows.Forms.DataGridView();
- this.button1 = new System.Windows.Forms.Button();
- this.button2 = new System.Windows.Forms.Button();
- this.flowLayoutPanel1.SuspendLayout();
- ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
- this.SuspendLayout();
- //
- // flowLayoutPanel1
- //
- this.flowLayoutPanel1.AutoSize = true;
- this.flowLayoutPanel1.Controls.Add(this.label2);
- this.flowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Top;
- this.flowLayoutPanel1.Location = new System.Drawing.Point(0, 0);
- this.flowLayoutPanel1.Name = "flowLayoutPanel1";
- this.flowLayoutPanel1.Size = new System.Drawing.Size(566, 51);
- this.flowLayoutPanel1.TabIndex = 13;
- //
- // label2
- //
- this.label2.AutoSize = true;
- this.label2.Location = new System.Drawing.Point(3, 6);
- this.label2.Margin = new System.Windows.Forms.Padding(3, 6, 3, 6);
- this.label2.Name = "label2";
- this.label2.Size = new System.Drawing.Size(558, 39);
- this.label2.TabIndex = 0;
- this.label2.Text = "This sample demonstrates how to implement the ITypedList interface. Clicking on the 'Sort Columns' button will bind the DataGridView to a sub-classed BindingList that implements ITypedList to provide a sorted list of columns. Clicking on the 'Reset' button will bind the DataGridView to a normal BindingList.";
- //
- // dataGridView1
- //
- this.dataGridView1.AllowUserToAddRows = false;
- this.dataGridView1.AllowUserToDeleteRows = false;
- this.dataGridView1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
- | System.Windows.Forms.AnchorStyles.Left)
- | System.Windows.Forms.AnchorStyles.Right)));
- this.dataGridView1.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
- this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
- this.dataGridView1.Location = new System.Drawing.Point(6, 57);
- this.dataGridView1.Name = "dataGridView1";
- this.dataGridView1.ReadOnly = true;
- this.dataGridView1.RowHeadersVisible = false;
- this.dataGridView1.Size = new System.Drawing.Size(465, 51);
- this.dataGridView1.TabIndex = 14;
- //
- // button1
- //
- this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
- this.button1.Location = new System.Drawing.Point(477, 57);
- this.button1.Name = "button1";
- this.button1.Size = new System.Drawing.Size(82, 23);
- this.button1.TabIndex = 15;
- this.button1.Text = "Sort Columns";
- this.button1.UseVisualStyleBackColor = true;
- this.button1.Click += new System.EventHandler(this.button1_Click);
- //
- // button2
- //
- this.button2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
- this.button2.Location = new System.Drawing.Point(477, 86);
- this.button2.Name = "button2";
- this.button2.Size = new System.Drawing.Size(82, 23);
- this.button2.TabIndex = 16;
- this.button2.Text = "Reset";
- this.button2.UseVisualStyleBackColor = true;
- this.button2.Click += new System.EventHandler(this.button2_Click);
- //
- // Form1
- //
- this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
- this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.ClientSize = new System.Drawing.Size(566, 120);
- this.Controls.Add(this.button2);
- this.Controls.Add(this.button1);
- this.Controls.Add(this.dataGridView1);
- this.Controls.Add(this.flowLayoutPanel1);
- this.Name = "Form1";
- this.Text = "ITypedList Sample";
- this.Load += new System.EventHandler(this.Form1_Load);
- this.flowLayoutPanel1.ResumeLayout(false);
- this.flowLayoutPanel1.PerformLayout();
- ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
- this.ResumeLayout(false);
- this.PerformLayout();
- }
+ #region Windows Form Designer generated code
- #endregion
+ void InitializeComponent()
+ {
+ ComponentResourceManager resources = new(typeof(Form1));
+ flowLayoutPanel1 = new FlowLayoutPanel();
+ label2 = new Label();
+ dataGridView1 = new DataGridView();
+ button1 = new Button();
+ button2 = new Button();
+ flowLayoutPanel1.SuspendLayout();
+ ((ISupportInitialize)dataGridView1).BeginInit();
+ SuspendLayout();
+ //
+ // flowLayoutPanel1
+ //
+ flowLayoutPanel1.AutoSize = true;
+ flowLayoutPanel1.Controls.Add(label2);
+ flowLayoutPanel1.Dock = DockStyle.Top;
+ flowLayoutPanel1.Location = new Point(0, 0);
+ flowLayoutPanel1.Name = "flowLayoutPanel1";
+ flowLayoutPanel1.Size = new Size(566, 51);
+ flowLayoutPanel1.TabIndex = 13;
+ //
+ // label2
+ //
+ label2.AutoSize = true;
+ label2.Location = new Point(3, 6);
+ label2.Margin = new Padding(3, 6, 3, 6);
+ label2.Name = "label2";
+ label2.Size = new Size(558, 39);
+ label2.TabIndex = 0;
+ label2.Text = "This sample demonstrates how to implement the ITypedList interface. Clicking on the 'Sort Columns' button will bind the DataGridView to a sub-classed BindingList that implements ITypedList to provide a sorted list of columns. Clicking on the 'Reset' button will bind the DataGridView to a normal BindingList.";
+ //
+ // dataGridView1
+ //
+ dataGridView1.AllowUserToAddRows = false;
+ dataGridView1.AllowUserToDeleteRows = false;
+ dataGridView1.Anchor = AnchorStyles.Top
+ | AnchorStyles.Bottom
+ | AnchorStyles.Left
+ | AnchorStyles.Right;
+ dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
+ dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
+ dataGridView1.Location = new Point(6, 57);
+ dataGridView1.Name = "dataGridView1";
+ dataGridView1.ReadOnly = true;
+ dataGridView1.RowHeadersVisible = false;
+ dataGridView1.Size = new Size(465, 51);
+ dataGridView1.TabIndex = 14;
+ //
+ // button1
+ //
+ button1.Anchor = AnchorStyles.Top | AnchorStyles.Right;
+ button1.Location = new Point(477, 57);
+ button1.Name = "button1";
+ button1.Size = new Size(82, 23);
+ button1.TabIndex = 15;
+ button1.Text = "Sort Columns";
+ button1.UseVisualStyleBackColor = true;
+ button1.Click += button1_Click;
+ //
+ // button2
+ //
+ button2.Anchor = AnchorStyles.Top | AnchorStyles.Right;
+ button2.Location = new Point(477, 86);
+ button2.Name = "button2";
+ button2.Size = new Size(82, 23);
+ button2.TabIndex = 16;
+ button2.Text = "Reset";
+ button2.UseVisualStyleBackColor = true;
+ button2.Click += button2_Click;
+ //
+ // Form1
+ //
+ AutoScaleDimensions = new SizeF(6F, 13F);
+ AutoScaleMode = AutoScaleMode.Font;
+ ClientSize = new Size(566, 120);
+ Controls.Add(button2);
+ Controls.Add(button1);
+ Controls.Add(dataGridView1);
+ Controls.Add(flowLayoutPanel1);
+ Name = "Form1";
+ Text = "ITypedList Sample";
+ Load += Form1_Load;
+ flowLayoutPanel1.ResumeLayout(false);
+ flowLayoutPanel1.PerformLayout();
+ ((ISupportInitialize)dataGridView1).EndInit();
+ ResumeLayout(false);
+ PerformLayout();
}
- static class Program
+ #endregion
+}
+
+static class Program
+{
+ ///
+ /// The main entry point for the application.
+ ///
+ [STAThread]
+ static void Main()
{
- ///
- /// The main entry point for the application.
- ///
- [STAThread]
- static void Main()
- {
- Application.EnableVisualStyles();
- Application.SetCompatibleTextRenderingDefault(false);
- Application.Run(new Form1());
- }
+ Application.EnableVisualStyles();
+ Application.SetCompatibleTextRenderingDefault(false);
+ Application.Run(new Form1());
}
}
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System.ComponentModel/ITypedList/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/ITypedList/Overview/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/ITypedList/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/ITypedList/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/ITypedList/Overview/SortableBindingList.cs b/snippets/csharp/System.ComponentModel/ITypedList/Overview/SortableBindingList.cs
index 486dcc8e03f..a04bd62ebc0 100644
--- a/snippets/csharp/System.ComponentModel/ITypedList/Overview/SortableBindingList.cs
+++ b/snippets/csharp/System.ComponentModel/ITypedList/Overview/SortableBindingList.cs
@@ -1,66 +1,58 @@
//
using System;
-using System.Collections.Generic;
-using System.Text;
using System.ComponentModel;
using System.Windows.Forms;
-using System.Collections;
-using System.Reflection;
-namespace ITypedListCS
+namespace ITypedListCS;
+
+[Serializable()]
+public class SortableBindingList : BindingList, ITypedList
{
- [Serializable()]
- public class SortableBindingList : BindingList, ITypedList
- {
- [NonSerialized()]
- private PropertyDescriptorCollection properties;
+ [NonSerialized()]
+ readonly PropertyDescriptorCollection properties;
- public SortableBindingList() : base()
- {
- // Get the 'shape' of the list.
- // Only get the public properties marked with Browsable = true.
- PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties(
- typeof(T),
- new Attribute[] { new BrowsableAttribute(true) });
+ public SortableBindingList() : base()
+ {
+ // Get the 'shape' of the list.
+ // Only get the public properties marked with Browsable = true.
+ PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties(
+ typeof(T),
+ [new BrowsableAttribute(true)]);
+
+ // Sort the properties.
+ properties = pdc.Sort();
+ }
- // Sort the properties.
- properties = pdc.Sort();
- }
+ //
+ #region ITypedList Implementation
- //
- #region ITypedList Implementation
+ //
+ public PropertyDescriptorCollection GetItemProperties(PropertyDescriptor[] listAccessors)
+ {
+ PropertyDescriptorCollection pdc;
- //
- public PropertyDescriptorCollection GetItemProperties(PropertyDescriptor[] listAccessors)
+ if (listAccessors != null && listAccessors.Length > 0)
{
- PropertyDescriptorCollection pdc;
-
- if (listAccessors!=null && listAccessors.Length>0)
- {
- // Return child list shape.
- pdc = ListBindingHelper.GetListItemProperties(listAccessors[0].PropertyType);
- }
- else
- {
- // Return properties in sort order.
- pdc = properties;
- }
-
- return pdc;
+ // Return child list shape.
+ pdc = ListBindingHelper.GetListItemProperties(listAccessors[0].PropertyType);
}
- //
-
- //
- // This method is only used in the design-time framework
- // and by the obsolete DataGrid control.
- public string GetListName(PropertyDescriptor[] listAccessors)
- {
- return typeof(T).Name;
+ else
+ {
+ // Return properties in sort order.
+ pdc = properties;
}
- //
- #endregion
- //
+ return pdc;
}
+ //
+
+ //
+ // This method is only used in the design-time framework
+ // and by the obsolete DataGrid control.
+ public string GetListName(PropertyDescriptor[] listAccessors) => typeof(T).Name;
+ //
+
+ #endregion
+ //
}
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System.ComponentModel/InvalidEnumArgumentException/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/InvalidEnumArgumentException/Overview/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/InvalidEnumArgumentException/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/InvalidEnumArgumentException/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/InvalidEnumArgumentException/Overview/enumexception.cs b/snippets/csharp/System.ComponentModel/InvalidEnumArgumentException/Overview/enumexception.cs
index 8e224b53e8b..83eada4ef6e 100644
--- a/snippets/csharp/System.ComponentModel/InvalidEnumArgumentException/Overview/enumexception.cs
+++ b/snippets/csharp/System.ComponentModel/InvalidEnumArgumentException/Overview/enumexception.cs
@@ -1,92 +1,76 @@
using System;
-using System.Drawing;
-using System.Collections;
using System.ComponentModel;
+using System.Drawing;
using System.Windows.Forms;
-using System.Data;
-namespace enumException
-{
- ///
- /// Summary description for Form1.
- ///
- public class Form1 : System.Windows.Forms.Form
- {
- ///
- /// Required designer variable.
- ///
- private System.ComponentModel.Container components = null;
+namespace enumException;
- public Form1()
- {
- //
- // Required for Windows Form Designer support
- //
- InitializeComponent();
+///
+/// Summary description for Form1.
+///
+public class Form1 : Form
+{
+ ///
+ /// Required designer variable.
+ ///
+ readonly Container _components;
- //
- // TODO: Add any constructor code after InitializeComponent call
- //
- }
+ public Form1()
+ {
+ InitializeComponent();
+ }
- ///
- /// Clean up any resources being used.
- ///
- protected override void Dispose( bool disposing )
- {
- if( disposing )
- {
- if (components != null)
- {
- components.Dispose();
- }
- }
- base.Dispose( disposing );
- }
+ ///
+ /// Clean up any resources being used.
+ ///
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ _components?.Dispose();
+ }
+ base.Dispose(disposing);
+ }
- #region Windows Form Designer generated code
- ///
- /// Required method for Designer support - do not modify
- /// the contents of this method with the code editor.
- ///
- private void InitializeComponent()
- {
- //
- // Form1
- //
- this.ClientSize = new System.Drawing.Size(292, 273);
- this.Name = "Form1";
- this.Text = "Form1";
- this.Load += new System.EventHandler(this.Form1_Load);
- }
- #endregion
+ #region Windows Form Designer generated code
+ ///
+ /// Required method for Designer support - do not modify
+ /// the contents of this method with the code editor.
+ ///
+ void InitializeComponent()
+ {
+ //
+ // Form1
+ //
+ ClientSize = new Size(292, 273);
+ Name = "Form1";
+ Text = "Form1";
+ Load += Form1_Load;
+ }
+ #endregion
- ///
- /// The main entry point for the application.
- ///
- [STAThread]
- static void Main()
- {
- Application.Run(new Form1());
- }
+ ///
+ /// The main entry point for the application.
+ ///
+ [STAThread]
+ static void Main() => Application.Run(new Form1());
- private void Form1_Load(object sender, System.EventArgs e)
- {
- //
- try
- {
- // Attempts to pass an invalid enum value (MessageBoxButtons) to the Show method
- MessageBoxButtons myButton= (MessageBoxButtons) 123;
- MessageBox.Show("This is a message","This is the Caption",myButton);
- }
- catch(InvalidEnumArgumentException invE)
- {
- Console.WriteLine(invE.Message);
- Console.WriteLine(invE.ParamName);
- Console.WriteLine(invE.StackTrace);
- Console.WriteLine(invE.Source);
- }
- //
- }
- }
+ void Form1_Load(object sender, EventArgs e)
+ {
+ //
+ try
+ {
+ // Attempts to pass an invalid enum value (MessageBoxButtons) to the Show method
+ MessageBoxButtons myButton = (MessageBoxButtons)123;
+ MessageBox.Show("This is a message", "This is the Caption", myButton);
+ }
+ catch (InvalidEnumArgumentException invE)
+ {
+ Console.WriteLine(invE.Message);
+ Console.WriteLine(invE.ParamName);
+ Console.WriteLine(invE.StackTrace);
+ Console.WriteLine(invE.Source);
+ }
+ //
+ }
}
diff --git a/snippets/csharp/System.ComponentModel/LicenseException/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/LicenseException/Overview/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/LicenseException/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/LicenseException/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/LicenseException/Overview/licenseex.cs b/snippets/csharp/System.ComponentModel/LicenseException/Overview/licenseex.cs
index 163c714f5c0..fa94f0420c9 100644
--- a/snippets/csharp/System.ComponentModel/LicenseException/Overview/licenseex.cs
+++ b/snippets/csharp/System.ComponentModel/LicenseException/Overview/licenseex.cs
@@ -1,92 +1,77 @@
using System;
-using System.Drawing;
-using System.Collections;
using System.ComponentModel;
+using System.Drawing;
using System.Windows.Forms;
-using System.Data;
-namespace test2
-{
- ///
- /// Summary description for Form1.
- ///
-
- [LicenseProvider(typeof(LicFileLicenseProvider))]
- public class Form1 : System.Windows.Forms.Form
- {
- ///
- /// Required designer variable.
- ///
- private System.ComponentModel.Container components = null;
+namespace test2;
- public Form1()
- {
- //
- // Required for Windows Form Designer support
- //
- InitializeComponent();
-
- //
- // TODO: Add any constructor code after InitializeComponent call
- //
- }
+///
+/// Summary description for Form1.
+///
+[LicenseProvider(typeof(LicFileLicenseProvider))]
+public class Form1 : Form
+{
+ ///
+ /// Required designer variable.
+ ///
+ readonly Container _components;
- ///
- /// Clean up any resources being used.
- ///
- protected override void Dispose(bool disposing)
- {
- if(disposing)
- {
- if (components != null)
- {
- components.Dispose();
- }
- base.Dispose();
- }
- }
+ public Form1()
+ {
+ InitializeComponent();
+ //TODO: Add any constructor code after InitializeComponent call
+ }
- #region Windows Form Designer generated code
- ///
- /// Required method for Designer support - do not modify
- /// the contents of this method with the code editor.
- ///
- private void InitializeComponent()
- {
- //
- // Form1
- //
- this.ClientSize = new System.Drawing.Size(292, 273);
- this.Name = "Form1";
- this.Text = "Form1";
- this.Load += new System.EventHandler(this.Form1_Load);
- }
- #endregion
+ ///
+ /// Clean up any resources being used.
+ ///
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ _components?.Dispose();
+ Dispose();
+ }
+ }
- ///
- /// The main entry point for the application.
- ///
- [STAThread]
- static void Main()
- {
- Application.Run(new Form1());
- }
+ #region Windows Form Designer generated code
+ ///
+ /// Required method for Designer support - do not modify
+ /// the contents of this method with the code editor.
+ ///
+ void InitializeComponent()
+ {
+ //
+ // Form1
+ //
+ ClientSize = new Size(292, 273);
+ Name = "Form1";
+ Text = "Form1";
+ Load += Form1_Load;
+ }
+ #endregion
- private void Form1_Load(object sender, System.EventArgs e)
- {
- //
- try {
- License licTest = null;
- licTest = LicenseManager.Validate(typeof(Form1), this);
- }
+ ///
+ /// The main entry point for the application.
+ ///
+ [STAThread]
+ static void Main() => Application.Run(new Form1());
- catch(LicenseException licE) {
- Console.WriteLine(licE.Message);
- Console.WriteLine(licE.LicensedType);
- Console.WriteLine(licE.StackTrace);
- Console.WriteLine(licE.Source);
- }
- //
- }
- }
-}
\ No newline at end of file
+ void Form1_Load(object sender, EventArgs e)
+ {
+ //
+ try
+ {
+ License licTest = null;
+ licTest = LicenseManager.Validate(typeof(Form1), this);
+ }
+ catch (LicenseException licE)
+ {
+ Console.WriteLine(licE.Message);
+ Console.WriteLine(licE.LicensedType);
+ Console.WriteLine(licE.StackTrace);
+ Console.WriteLine(licE.Source);
+ }
+ //
+ }
+}
diff --git a/snippets/csharp/System.ComponentModel/LicenseManager/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/LicenseManager/Overview/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/LicenseManager/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/LicenseManager/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/LicenseManager/Overview/source.cs b/snippets/csharp/System.ComponentModel/LicenseManager/Overview/source.cs
index 788e53b5e90..56726305322 100644
--- a/snippets/csharp/System.ComponentModel/LicenseManager/Overview/source.cs
+++ b/snippets/csharp/System.ComponentModel/LicenseManager/Overview/source.cs
@@ -1,35 +1,32 @@
//
-using System;
using System.ComponentModel;
using System.Windows.Forms;
// Adds the LicenseProviderAttribute to the control.
[LicenseProvider(typeof(LicFileLicenseProvider))]
-public class MyControl : Control
+public class MyControl : Control
{
-
- // Creates a new, null license.
- private License license = null;
-
- public MyControl ()
- {
-
- // Adds Validate to the control's constructor.
- license = LicenseManager.Validate(typeof(MyControl), this);
-
- // Insert code to perform other instance creation tasks here.
- }
-
- protected override void Dispose(bool disposing)
- {
- if(disposing)
- {
- if (license != null)
- {
- license.Dispose();
- license = null;
- }
- }
- }
+ // Creates a new, null license.
+ License license;
+
+ public MyControl()
+ {
+ // Adds Validate to the control's constructor.
+ license = LicenseManager.Validate(typeof(MyControl), this);
+
+ // Insert code to perform other instance creation tasks here.
+ }
+
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ if (license != null)
+ {
+ license.Dispose();
+ license = null;
+ }
+ }
+ }
}
//
diff --git a/snippets/csharp/System.ComponentModel/LicenseProviderAttribute/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/LicenseProviderAttribute/Overview/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/LicenseProviderAttribute/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/LicenseProviderAttribute/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/LicenseProviderAttribute/Overview/source.cs b/snippets/csharp/System.ComponentModel/LicenseProviderAttribute/Overview/source.cs
index 828bde2f0c6..2b08e0e6fd4 100644
--- a/snippets/csharp/System.ComponentModel/LicenseProviderAttribute/Overview/source.cs
+++ b/snippets/csharp/System.ComponentModel/LicenseProviderAttribute/Overview/source.cs
@@ -1,35 +1,37 @@
using System;
-using System.Data;
using System.ComponentModel;
using System.Windows.Forms;
-public class Class1{
+public static class Class1
+{
//
[LicenseProvider(typeof(LicFileLicenseProvider))]
- public class MyControl : Control {
-
+ public class MyControl : Control
+ {
// Insert code here.
-
- protected override void Dispose(bool disposing) {
- /* All components must dispose of the licenses they grant.
- * Insert code here to dispose of the license. */
+
+ protected override void Dispose(bool disposing)
+ {
+ /* All components must dispose of the licenses they grant.
+ * Insert code here to dispose of the license. */
}
- }
+ }
//
//
- public static int Main() {
+ public static int Main()
+ {
// Creates a new component.
- MyControl myNewControl = new MyControl();
-
+ MyControl myNewControl = new();
+
// Gets the attributes for the component.
AttributeCollection attributes = TypeDescriptor.GetAttributes(myNewControl);
-
+
/* Prints the name of the license provider by retrieving the LicenseProviderAttribute
* from the AttributeCollection. */
LicenseProviderAttribute myAttribute = (LicenseProviderAttribute)attributes[typeof(LicenseProviderAttribute)];
Console.WriteLine("The license provider for this class is: " + myAttribute.LicenseProvider.ToString());
-
+
return 0;
- }
+ }
//
}
diff --git a/snippets/csharp/System.ComponentModel/LocalizableAttribute/.ctor/Project.csproj b/snippets/csharp/System.ComponentModel/LocalizableAttribute/.ctor/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/LocalizableAttribute/.ctor/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/LocalizableAttribute/.ctor/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/LocalizableAttribute/.ctor/source.cs b/snippets/csharp/System.ComponentModel/LocalizableAttribute/.ctor/source.cs
index 5be8234d6ae..74036a83c8a 100644
--- a/snippets/csharp/System.ComponentModel/LocalizableAttribute/.ctor/source.cs
+++ b/snippets/csharp/System.ComponentModel/LocalizableAttribute/.ctor/source.cs
@@ -1,22 +1,21 @@
-using System;
-using System.Data;
-using System.ComponentModel;
+using System.ComponentModel;
using System.Windows.Forms;
-public class Form1 : Form {
+public class Form1 : Form
+{
+ //
-//
-
- [Localizable(true)]
- public int MyProperty {
- get {
- // Insert code here.
- return 0;
- }
- set {
- // Insert code here.
+ [Localizable(true)]
+ public int MyProperty
+ {
+ get =>
+ // Insert code here.
+ 0;
+ set
+ {
+ // Insert code here.
+ }
}
- }
-
-//
+
+ //
}
diff --git a/snippets/csharp/System.ComponentModel/LocalizableAttribute/IsLocalizable/Project.csproj b/snippets/csharp/System.ComponentModel/LocalizableAttribute/IsLocalizable/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/LocalizableAttribute/IsLocalizable/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/LocalizableAttribute/IsLocalizable/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/LocalizableAttribute/IsLocalizable/source.cs b/snippets/csharp/System.ComponentModel/LocalizableAttribute/IsLocalizable/source.cs
index c94a478bca6..786d18db6a6 100644
--- a/snippets/csharp/System.ComponentModel/LocalizableAttribute/IsLocalizable/source.cs
+++ b/snippets/csharp/System.ComponentModel/LocalizableAttribute/IsLocalizable/source.cs
@@ -1,26 +1,25 @@
-using System;
-using System.Data;
-using System.ComponentModel;
+using System.ComponentModel;
using System.Windows.Forms;
-public class Form1: Form
+public class Form1 : Form
{
- protected TextBox textBox1;
-
- public void Method()
- {
-//
-// Gets the attributes for the property.
- AttributeCollection attributes =
- TypeDescriptor.GetProperties(this)["MyProperty"].Attributes;
-
- // Checks to see if the property needs to be localized.
- LocalizableAttribute myAttribute =
- (LocalizableAttribute)attributes[typeof(LocalizableAttribute)];
- if(myAttribute.IsLocalizable) {
- // Insert code here.
- }
-
-//
- }
+ protected TextBox textBox1;
+
+ public void Method()
+ {
+ //
+ // Gets the attributes for the property.
+ AttributeCollection attributes =
+ TypeDescriptor.GetProperties(this)["MyProperty"].Attributes;
+
+ // Checks to see if the property needs to be localized.
+ LocalizableAttribute myAttribute =
+ (LocalizableAttribute)attributes[typeof(LocalizableAttribute)];
+ if (myAttribute.IsLocalizable)
+ {
+ // Insert code here.
+ }
+
+ //
+ }
}
diff --git a/snippets/csharp/System.ComponentModel/LocalizableAttribute/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/LocalizableAttribute/Overview/Project.csproj
index c02dc5044e7..5a1b02db677 100644
--- a/snippets/csharp/System.ComponentModel/LocalizableAttribute/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/LocalizableAttribute/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0
+ net8.0
\ No newline at end of file
diff --git a/snippets/csharp/System.ComponentModel/LocalizableAttribute/Overview/source.cs b/snippets/csharp/System.ComponentModel/LocalizableAttribute/Overview/source.cs
index 0cfced9a2e1..63f20b77936 100644
--- a/snippets/csharp/System.ComponentModel/LocalizableAttribute/Overview/source.cs
+++ b/snippets/csharp/System.ComponentModel/LocalizableAttribute/Overview/source.cs
@@ -1,32 +1,33 @@
-using System;
-using System.ComponentModel;
+using System.ComponentModel;
public class Class1
{
//
[Localizable(true)]
- public int MyProperty {
- get {
- // Insert code here.
- return 0;
- }
- set {
- // Insert code here.
+ public int MyProperty
+ {
+ get =>
+ // Insert code here.
+ 0;
+ set
+ {
+ // Insert code here.
}
- }
+ }
//
public void Method1()
{
//
// Gets the attributes for the property.
- AttributeCollection attributes =
+ AttributeCollection attributes =
TypeDescriptor.GetProperties(this)["MyProperty"].Attributes;
// Checks to see if the property needs to be localized.
- LocalizableAttribute myAttribute =
+ LocalizableAttribute myAttribute =
(LocalizableAttribute)attributes[typeof(LocalizableAttribute)];
- if(myAttribute.IsLocalizable) {
- // Insert code here.
+ if (myAttribute.IsLocalizable)
+ {
+ // Insert code here.
}
//
}
diff --git a/snippets/csharp/System.ComponentModel/LookupBindingPropertiesAttribute/Overview/DemoControl.cs b/snippets/csharp/System.ComponentModel/LookupBindingPropertiesAttribute/Overview/DemoControl.cs
index 8a931ee29cb..60882787637 100644
--- a/snippets/csharp/System.ComponentModel/LookupBindingPropertiesAttribute/Overview/DemoControl.cs
+++ b/snippets/csharp/System.ComponentModel/LookupBindingPropertiesAttribute/Overview/DemoControl.cs
@@ -1,57 +1,47 @@
//
-using System;
using System.ComponentModel;
using System.Windows.Forms;
-namespace LookupBindingPropertiesAttributeDemo
-{
- //
- // The DemoControl class shows properties
- // used with lookup-based binding.
- [LookupBindingProperties(
- "DataSource",
- "DisplayMember",
- "ValueMember",
- "LookupMember")]
- public class DemoControl : Control
- {
- }
- //
+namespace LookupBindingPropertiesAttributeDemo;
- //
- // The DemoComboBox control shows a standard
- // combo box binding definition.
- [LookupBindingProperties(
- "DataSource",
- "DisplayMember",
- "ValueMember",
- "SelectedValue")]
- public class DemoComboBox : Control
- {
- }
- //
+//
+// The DemoControl class shows properties
+// used with lookup-based binding.
+[LookupBindingProperties(
+ "DataSource",
+ "DisplayMember",
+ "ValueMember",
+ "LookupMember")]
+public class DemoControl : Control;
+//
- //
- // The DemoComboBox2 class shows that a control can
- // support both simple binding as well as list binding.
- [LookupBindingProperties(
- "DataSource",
- "DisplayMember",
- "ValueMember",
- "SelectedValue")]
- [DefaultBindingProperty("Text")]
- public class DemoComboBox2 : Control
- {
- }
- //
+//
+// The DemoComboBox control shows a standard
+// combo box binding definition.
+[LookupBindingProperties(
+ "DataSource",
+ "DisplayMember",
+ "ValueMember",
+ "SelectedValue")]
+public class DemoComboBox : Control;
+//
- //
- // NonBindableCombo control shows how to unset the
- // LookupBindingProperties by specifying no arguments.
- [LookupBindingProperties()]
- public class NonBindableCombo : Control
- {
- }
- //
-}
+//
+// The DemoComboBox2 class shows that a control can
+// support both simple binding as well as list binding.
+[LookupBindingProperties(
+ "DataSource",
+ "DisplayMember",
+ "ValueMember",
+ "SelectedValue")]
+[DefaultBindingProperty("Text")]
+public class DemoComboBox2 : Control;
+//
+
+//
+// NonBindableCombo control shows how to unset the
+// LookupBindingProperties by specifying no arguments.
+[LookupBindingProperties()]
+public class NonBindableCombo : Control;
+//
//
\ No newline at end of file
diff --git a/snippets/csharp/System.ComponentModel/LookupBindingPropertiesAttribute/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/LookupBindingPropertiesAttribute/Overview/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/LookupBindingPropertiesAttribute/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/LookupBindingPropertiesAttribute/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/MergablePropertyAttribute/.ctor/Project.csproj b/snippets/csharp/System.ComponentModel/MergablePropertyAttribute/.ctor/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/MergablePropertyAttribute/.ctor/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/MergablePropertyAttribute/.ctor/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/MergablePropertyAttribute/.ctor/source.cs b/snippets/csharp/System.ComponentModel/MergablePropertyAttribute/.ctor/source.cs
index 0647b42910d..3a118f35e00 100644
--- a/snippets/csharp/System.ComponentModel/MergablePropertyAttribute/.ctor/source.cs
+++ b/snippets/csharp/System.ComponentModel/MergablePropertyAttribute/.ctor/source.cs
@@ -1,22 +1,21 @@
-using System;
-using System.Data;
-using System.ComponentModel;
+using System.ComponentModel;
using System.Windows.Forms;
-public class Form1: Form
+public class Form1 : Form
{
-//
+ //
- [MergableProperty(true)]
- public int MyProperty {
- get {
- // Insert code here.
- return 0;
+ [MergableProperty(true)]
+ public int MyProperty
+ {
+ get =>
+ // Insert code here.
+ 0;
+ set
+ {
+ // Insert code here.
+ }
}
- set {
- // Insert code here.
- }
- }
-
-//
+
+ //
}
diff --git a/snippets/csharp/System.ComponentModel/MergablePropertyAttribute/AllowMerge/Project.csproj b/snippets/csharp/System.ComponentModel/MergablePropertyAttribute/AllowMerge/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/MergablePropertyAttribute/AllowMerge/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/MergablePropertyAttribute/AllowMerge/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/MergablePropertyAttribute/AllowMerge/source.cs b/snippets/csharp/System.ComponentModel/MergablePropertyAttribute/AllowMerge/source.cs
index 7ad15055f7c..d7fde4ff73f 100644
--- a/snippets/csharp/System.ComponentModel/MergablePropertyAttribute/AllowMerge/source.cs
+++ b/snippets/csharp/System.ComponentModel/MergablePropertyAttribute/AllowMerge/source.cs
@@ -1,23 +1,22 @@
-using System;
-using System.Data;
-using System.ComponentModel;
+using System.ComponentModel;
using System.Windows.Forms;
-public class Form1: Form
+public class Form1 : Form
{
- protected void Method()
- {
-//
- // Gets the attributes for the property.
- AttributeCollection attributes =
- TypeDescriptor.GetProperties(this)["MyPropertyProperty"].Attributes;
-
- // Checks to see if the property is bindable.
- MergablePropertyAttribute myAttribute = (MergablePropertyAttribute)attributes[typeof(MergablePropertyAttribute)];
- if(myAttribute.AllowMerge) {
- // Insert code here.
- }
-
-//
- }
+ protected void Method()
+ {
+ //
+ // Gets the attributes for the property.
+ AttributeCollection attributes =
+ TypeDescriptor.GetProperties(this)["MyPropertyProperty"].Attributes;
+
+ // Checks to see if the property is bindable.
+ MergablePropertyAttribute myAttribute = (MergablePropertyAttribute)attributes[typeof(MergablePropertyAttribute)];
+ if (myAttribute.AllowMerge)
+ {
+ // Insert code here.
+ }
+
+ //
+ }
}
diff --git a/snippets/csharp/System.ComponentModel/MergablePropertyAttribute/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/MergablePropertyAttribute/Overview/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/MergablePropertyAttribute/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/MergablePropertyAttribute/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/MergablePropertyAttribute/Overview/source.cs b/snippets/csharp/System.ComponentModel/MergablePropertyAttribute/Overview/source.cs
index 202c5a9367f..f16d5e4a326 100644
--- a/snippets/csharp/System.ComponentModel/MergablePropertyAttribute/Overview/source.cs
+++ b/snippets/csharp/System.ComponentModel/MergablePropertyAttribute/Overview/source.cs
@@ -1,55 +1,61 @@
-using System;
-using System.Data;
-using System.ComponentModel;
+using System.ComponentModel;
using System.Windows.Forms;
-public class Form1: Form
+public class Form1 : Form
{
//
[MergableProperty(true)]
- public int MyProperty {
- get {
- // Insert code here.
- return 0;
- }
- set {
- // Insert code here.
- }
- }
- //
- public int MyProperty2 {
- get{
- //
- // Gets the attributes for the property.
- AttributeCollection attributes =
- TypeDescriptor.GetProperties(this)["MyProperty"].Attributes;
-
- // Checks to see if the value of the MergablePropertyAttribute is Yes.
- if(attributes[typeof(MergablePropertyAttribute)].Equals(MergablePropertyAttribute.Yes)) {
+ public int MyProperty
+ {
+ get =>
// Insert code here.
- }
-
- // This is another way to see if the property is bindable.
- MergablePropertyAttribute myAttribute =
- (MergablePropertyAttribute)attributes[typeof(MergablePropertyAttribute)];
- if(myAttribute.AllowMerge) {
+ 0;
+ set
+ {
// Insert code here.
- }
- //
- return 0;
+ }
+ }
+ //
+ public int MyProperty2
+ {
+ get
+ {
+ //
+ // Gets the attributes for the property.
+ AttributeCollection attributes =
+ TypeDescriptor.GetProperties(this)["MyProperty"].Attributes;
+
+ // Checks to see if the value of the MergablePropertyAttribute is Yes.
+ if (attributes[typeof(MergablePropertyAttribute)].Equals(MergablePropertyAttribute.Yes))
+ {
+ // Insert code here.
+ }
+
+ // This is another way to see if the property is bindable.
+ MergablePropertyAttribute myAttribute =
+ (MergablePropertyAttribute)attributes[typeof(MergablePropertyAttribute)];
+ if (myAttribute.AllowMerge)
+ {
+ // Insert code here.
+ }
+ //
+ return 0;
}
}
- public int MyProperty3 {
- get{
+ public int MyProperty3
+ {
+ get
+ {
//
- AttributeCollection attributes =
+ AttributeCollection attributes =
TypeDescriptor.GetAttributes(MyProperty);
- if(attributes[typeof(MergablePropertyAttribute)].Equals(MergablePropertyAttribute.Yes)) {
+ if (attributes[typeof(MergablePropertyAttribute)].Equals(MergablePropertyAttribute.Yes))
+ {
// Insert code here.
- }
+ }
//
return 0;
- }
+ }
}
}
diff --git a/snippets/csharp/System.ComponentModel/PropertyDescriptor/Overview/DemoControl.cs b/snippets/csharp/System.ComponentModel/PropertyDescriptor/Overview/DemoControl.cs
index 7cd6e0ff518..fd36f632d92 100644
--- a/snippets/csharp/System.ComponentModel/PropertyDescriptor/Overview/DemoControl.cs
+++ b/snippets/csharp/System.ComponentModel/PropertyDescriptor/Overview/DemoControl.cs
@@ -2,14 +2,13 @@
using System.ComponentModel;
using System.Windows.Forms;
-namespace ReadOnlyPropertyDescriptorTest
+namespace ReadOnlyPropertyDescriptorTest;
+
+[Designer(typeof(DemoControlDesigner))]
+public class DemoControl : Control
{
- [Designer(typeof(DemoControlDesigner))]
- public class DemoControl : Control
+ public DemoControl()
{
- public DemoControl()
- {
- }
}
}
//
diff --git a/snippets/csharp/System.ComponentModel/PropertyDescriptor/Overview/DemoControlDesigner.cs b/snippets/csharp/System.ComponentModel/PropertyDescriptor/Overview/DemoControlDesigner.cs
index 7949b6d98e0..26d4289674f 100644
--- a/snippets/csharp/System.ComponentModel/PropertyDescriptor/Overview/DemoControlDesigner.cs
+++ b/snippets/csharp/System.ComponentModel/PropertyDescriptor/Overview/DemoControlDesigner.cs
@@ -3,26 +3,25 @@
using System.ComponentModel;
using System.Windows.Forms.Design;
-namespace ReadOnlyPropertyDescriptorTest
+namespace ReadOnlyPropertyDescriptorTest;
+
+class DemoControlDesigner : ControlDesigner
{
- class DemoControlDesigner : ControlDesigner
+ // The PostFilterProperties method replaces the control's
+ // Size property with a read-only Size property by using
+ // the SerializeReadOnlyPropertyDescriptor class.
+ protected override void PostFilterProperties(IDictionary properties)
{
- // The PostFilterProperties method replaces the control's
- // Size property with a read-only Size property by using
- // the SerializeReadOnlyPropertyDescriptor class.
- protected override void PostFilterProperties(IDictionary properties)
+ if (properties.Contains("Size"))
{
- if (properties.Contains("Size"))
- {
- PropertyDescriptor original = properties["Size"] as PropertyDescriptor;
- SerializeReadOnlyPropertyDescriptor readOnlyDescriptor =
- new SerializeReadOnlyPropertyDescriptor(original);
-
- properties["Size"] = readOnlyDescriptor;
- }
+ PropertyDescriptor original = properties["Size"] as PropertyDescriptor;
+ SerializeReadOnlyPropertyDescriptor readOnlyDescriptor =
+ new(original);
- base.PostFilterProperties(properties);
+ properties["Size"] = readOnlyDescriptor;
}
+
+ base.PostFilterProperties(properties);
}
}
//
diff --git a/snippets/csharp/System.ComponentModel/PropertyDescriptor/Overview/SerializeReadOnlyPropertyDescriptor.cs b/snippets/csharp/System.ComponentModel/PropertyDescriptor/Overview/SerializeReadOnlyPropertyDescriptor.cs
index 9bc7860d659..21d5bfc514b 100644
--- a/snippets/csharp/System.ComponentModel/PropertyDescriptor/Overview/SerializeReadOnlyPropertyDescriptor.cs
+++ b/snippets/csharp/System.ComponentModel/PropertyDescriptor/Overview/SerializeReadOnlyPropertyDescriptor.cs
@@ -2,186 +2,123 @@
using System;
using System.Collections;
using System.ComponentModel;
-using System.Text;
-namespace ReadOnlyPropertyDescriptorTest
+namespace ReadOnlyPropertyDescriptorTest;
+
+// The SerializeReadOnlyPropertyDescriptor shows how to implement a
+// custom property descriptor. It provides a read-only wrapper
+// around the specified PropertyDescriptor.
+sealed class SerializeReadOnlyPropertyDescriptor : PropertyDescriptor
{
- // The SerializeReadOnlyPropertyDescriptor shows how to implement a
- // custom property descriptor. It provides a read-only wrapper
- // around the specified PropertyDescriptor.
- internal sealed class SerializeReadOnlyPropertyDescriptor : PropertyDescriptor
- {
- private PropertyDescriptor _pd = null;
+ readonly PropertyDescriptor _pd;
- public SerializeReadOnlyPropertyDescriptor(PropertyDescriptor pd)
- : base(pd)
- {
- this._pd = pd;
- }
+ public SerializeReadOnlyPropertyDescriptor(PropertyDescriptor pd)
+ : base(pd) => _pd = pd;
- public override AttributeCollection Attributes
- {
- get
- {
- return( AppendAttributeCollection(
- this._pd.Attributes,
- ReadOnlyAttribute.Yes) );
- }
- }
+ public override AttributeCollection Attributes => AppendAttributeCollection(
+ _pd.Attributes,
+ ReadOnlyAttribute.Yes);
- protected override void FillAttributes(IList attributeList)
- {
- attributeList.Add(ReadOnlyAttribute.Yes);
- }
+ protected override void FillAttributes(IList attributeList) => attributeList.Add(ReadOnlyAttribute.Yes);
- public override Type ComponentType
- {
- get
- {
- return this._pd.ComponentType;
- }
- }
+ public override Type ComponentType => _pd.ComponentType;
- // The type converter for this property.
- // A translator can overwrite with its own converter.
- public override TypeConverter Converter
- {
- get
- {
- return this._pd.Converter;
- }
- }
+ // The type converter for this property.
+ // A translator can overwrite with its own converter.
+ public override TypeConverter Converter => _pd.Converter;
- // Returns the property editor
- // A translator can overwrite with its own editor.
- public override object GetEditor(Type editorBaseType)
- {
- return this._pd.GetEditor(editorBaseType);
- }
+ // Returns the property editor
+ // A translator can overwrite with its own editor.
+ public override object GetEditor(Type editorBaseType) => _pd.GetEditor(editorBaseType);
- // Specifies the property is read only.
- public override bool IsReadOnly
- {
- get
- {
- return true;
- }
- }
+ // Specifies the property is read only.
+ public override bool IsReadOnly => true;
- public override Type PropertyType
- {
- get
- {
- return this._pd.PropertyType;
- }
- }
+ public override Type PropertyType => _pd.PropertyType;
- public override bool CanResetValue(object component)
- {
- return this._pd.CanResetValue(component);
- }
+ public override bool CanResetValue(object component) => _pd.CanResetValue(component);
- public override object GetValue(object component)
- {
- return this._pd.GetValue(component);
- }
+ public override object GetValue(object component) => _pd.GetValue(component);
- public override void ResetValue(object component)
- {
- this._pd.ResetValue(component);
- }
+ public override void ResetValue(object component) => _pd.ResetValue(component);
- public override void SetValue(object component, object val)
- {
- this._pd.SetValue(component, val);
- }
+ public override void SetValue(object component, object val) => _pd.SetValue(component, val);
- // Determines whether a value should be serialized.
- public override bool ShouldSerializeValue(object component)
+ // Determines whether a value should be serialized.
+ public override bool ShouldSerializeValue(object component)
+ {
+ bool result = _pd.ShouldSerializeValue(component);
+
+ if (!result)
{
- bool result = this._pd.ShouldSerializeValue(component);
+ DefaultValueAttribute dva = (DefaultValueAttribute)_pd.Attributes[typeof(DefaultValueAttribute)];
+ result = dva == null || !Equals(_pd.GetValue(component), dva.Value);
+ }
- if (!result)
- {
- DefaultValueAttribute dva = (DefaultValueAttribute)_pd.Attributes[typeof(DefaultValueAttribute)];
- if (dva != null)
- {
- result = !Object.Equals(this._pd.GetValue(component), dva.Value);
- }
- else
- {
- result = true;
- }
- }
+ return result;
+ }
- return result;
- }
+ // The following Utility methods create a new AttributeCollection
+ // by appending the specified attributes to an existing collection.
+ public static AttributeCollection AppendAttributeCollection(
+ AttributeCollection existing,
+ params Attribute[] newAttrs) => new(AppendAttributes(existing, newAttrs));
- // The following Utility methods create a new AttributeCollection
- // by appending the specified attributes to an existing collection.
- static public AttributeCollection AppendAttributeCollection(
- AttributeCollection existing,
- params Attribute[] newAttrs)
+ public static Attribute[] AppendAttributes(
+ AttributeCollection existing,
+ params Attribute[] newAttrs)
+ {
+ if (existing == null)
{
- return new AttributeCollection(AppendAttributes(existing, newAttrs));
+ throw new ArgumentNullException(nameof(existing));
}
- static public Attribute[] AppendAttributes(
- AttributeCollection existing,
- params Attribute[] newAttrs)
- {
- if (existing == null)
- {
- throw new ArgumentNullException(nameof(existing));
- }
+ newAttrs ??= [];
- newAttrs ??= new Attribute[0];
+ Attribute[] attributes;
- Attribute[] attributes;
+ Attribute[] newArray = new Attribute[existing.Count + newAttrs.Length];
+ int actualCount = existing.Count;
+ existing.CopyTo(newArray, 0);
- Attribute[] newArray = new Attribute[existing.Count + newAttrs.Length];
- int actualCount = existing.Count;
- existing.CopyTo(newArray, 0);
-
- for (int idx = 0; idx < newAttrs.Length; idx++)
+ for (int idx = 0; idx < newAttrs.Length; idx++)
+ {
+ if (newAttrs[idx] == null)
{
- if (newAttrs[idx] == null)
- {
- throw new ArgumentNullException("newAttrs");
- }
-
- // Check if this attribute is already in the existing
- // array. If it is, replace it.
- bool match = false;
- for (int existingIdx = 0; existingIdx < existing.Count; existingIdx++)
- {
- if (newArray[existingIdx].TypeId.Equals(newAttrs[idx].TypeId))
- {
- match = true;
- newArray[existingIdx] = newAttrs[idx];
- break;
- }
- }
+ throw new ArgumentNullException(nameof(newAttrs));
+ }
- if (!match)
+ // Check if this attribute is already in the existing
+ // array. If it is, replace it.
+ bool match = false;
+ for (int existingIdx = 0; existingIdx < existing.Count; existingIdx++)
+ {
+ if (newArray[existingIdx].TypeId.Equals(newAttrs[idx].TypeId))
{
- newArray[actualCount++] = newAttrs[idx];
+ match = true;
+ newArray[existingIdx] = newAttrs[idx];
+ break;
}
}
- // If some attributes were collapsed, create a new array.
- if (actualCount < newArray.Length)
- {
- attributes = new Attribute[actualCount];
- Array.Copy(newArray, 0, attributes, 0, actualCount);
- }
- else
+ if (!match)
{
- attributes = newArray;
+ newArray[actualCount++] = newAttrs[idx];
}
+ }
- return attributes;
+ // If some attributes were collapsed, create a new array.
+ if (actualCount < newArray.Length)
+ {
+ attributes = new Attribute[actualCount];
+ Array.Copy(newArray, 0, attributes, 0, actualCount);
+ }
+ else
+ {
+ attributes = newArray;
}
+
+ return attributes;
}
}
-//
\ No newline at end of file
+//
diff --git a/snippets/csharp/System.ComponentModel/PropertyDescriptor/Overview/System.ComponentModel.PropertyDescriptor.csproj b/snippets/csharp/System.ComponentModel/PropertyDescriptor/Overview/System.ComponentModel.PropertyDescriptor.csproj
index 0082a0e05e0..b0bc0cd203b 100644
--- a/snippets/csharp/System.ComponentModel/PropertyDescriptor/Overview/System.ComponentModel.PropertyDescriptor.csproj
+++ b/snippets/csharp/System.ComponentModel/PropertyDescriptor/Overview/System.ComponentModel.PropertyDescriptor.csproj
@@ -2,7 +2,7 @@
Exe
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/PropertyDescriptor/Overview/propertydescriptor.cs b/snippets/csharp/System.ComponentModel/PropertyDescriptor/Overview/propertydescriptor.cs
index 8ef1845c0e7..eae531de297 100644
--- a/snippets/csharp/System.ComponentModel/PropertyDescriptor/Overview/propertydescriptor.cs
+++ b/snippets/csharp/System.ComponentModel/PropertyDescriptor/Overview/propertydescriptor.cs
@@ -1,112 +1,102 @@
using System;
using System.ComponentModel;
+using System.Drawing;
using System.Windows.Forms;
-namespace MyPropertyDescriptor
+namespace MyPropertyDescriptor;
+
+///
+/// Summary description for Form1.
+///
+public class Form1 : Form
{
+ TextBox textBox1;
+ Button button1;
///
- /// Summary description for Form1.
+ /// Required designer variable.
///
- public class Form1 : Form
- {
- private TextBox textBox1;
- private Button button1;
- ///
- /// Required designer variable.
- ///
- private System.ComponentModel.Container components = null;
-
- public Form1()
- {
- //
- // Required for Windows Form Designer support
- //
- InitializeComponent();
+ readonly Container _components;
- //
- // TODO: Add any constructor code after InitializeComponent call
- //
- }
+ public Form1() =>
+ //
+ // Required for Windows Form Designer support
+ //
+ InitializeComponent();
- ///
- /// Clean up any resources being used.
- ///
- protected override void Dispose(bool disposing)
+ ///
+ /// Clean up any resources being used.
+ ///
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing)
{
- if (disposing)
- {
- if (components != null)
- {
- components.Dispose();
- }
- }
- base.Dispose(disposing);
+ _components?.Dispose();
}
+ base.Dispose(disposing);
+ }
- #region Windows Form Designer generated code
- ///
- /// Required method for Designer support - do not modify
- /// the contents of this method with the code editor.
- ///
- private void InitializeComponent()
- {
- this.textBox1 = new TextBox();
- this.button1 = new Button();
- this.SuspendLayout();
- //
- // textBox1
- //
- this.textBox1.Location = new System.Drawing.Point(120, 16);
- this.textBox1.Multiline = true;
- this.textBox1.Name = "textBox1";
- this.textBox1.ScrollBars = ScrollBars.Vertical;
- this.textBox1.Size = new System.Drawing.Size(288, 272);
- this.textBox1.TabIndex = 0;
- this.textBox1.Text = "textBox1";
- //
- // button1
- //
- this.button1.Location = new System.Drawing.Point(40, 112);
- this.button1.Name = "button1";
- this.button1.TabIndex = 1;
- this.button1.Text = "button1";
- //
- // Form1
- //
- this.ClientSize = new System.Drawing.Size(448, 333);
- this.Controls.AddRange(new Control[] {
- this.button1,
- this.textBox1});
- this.Name = "Form1";
- this.Text = "Form1";
- this.Load += new System.EventHandler(this.Form1_Load);
- this.ResumeLayout(false);
- }
- #endregion
+ #region Windows Form Designer generated code
+ ///
+ /// Required method for Designer support - do not modify
+ /// the contents of this method with the code editor.
+ ///
+ void InitializeComponent()
+ {
+ textBox1 = new TextBox();
+ button1 = new Button();
+ SuspendLayout();
+ //
+ // textBox1
+ //
+ textBox1.Location = new Point(120, 16);
+ textBox1.Multiline = true;
+ textBox1.Name = "textBox1";
+ textBox1.ScrollBars = ScrollBars.Vertical;
+ textBox1.Size = new Size(288, 272);
+ textBox1.TabIndex = 0;
+ textBox1.Text = "textBox1";
+ //
+ // button1
+ //
+ button1.Location = new Point(40, 112);
+ button1.Name = "button1";
+ button1.TabIndex = 1;
+ button1.Text = "button1";
+ //
+ // Form1
+ //
+ ClientSize = new Size(448, 333);
+ Controls.AddRange(
+ [
+ button1,
+ textBox1
+ ]);
+ Name = "Form1";
+ Text = "Form1";
+ Load += Form1_Load;
+ ResumeLayout(false);
+ }
+ #endregion
- ///
- /// The main entry point for the application.
- ///
- [STAThread]
- static void Main()
- {
- Application.Run(new Form1());
- }
+ ///
+ /// The main entry point for the application.
+ ///
+ [STAThread]
+ static void Main() => Application.Run(new Form1());
- private void Form1_Load(object sender, System.EventArgs e)
- {
- //
- // Creates a new collection and assign it the properties for button1.
- PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(button1);
+ void Form1_Load(object sender, EventArgs e)
+ {
+ //
+ // Creates a new collection and assign it the properties for button1.
+ PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(button1);
- // Sets an PropertyDescriptor to the specific property.
- System.ComponentModel.PropertyDescriptor myProperty = properties.Find("Text", false);
+ // Sets an PropertyDescriptor to the specific property.
+ PropertyDescriptor myProperty = properties.Find("Text", false);
- // Prints the property and the property description.
- textBox1.Text = myProperty.DisplayName + '\n';
- textBox1.Text += myProperty.Description + '\n';
- textBox1.Text += myProperty.Category + '\n';
- //
- }
+ // Prints the property and the property description.
+ textBox1.Text = myProperty.DisplayName + '\n';
+ textBox1.Text += myProperty.Description + '\n';
+ textBox1.Text += myProperty.Category + '\n';
+ //
}
}
diff --git a/snippets/csharp/System.ComponentModel/PropertyDescriptorCollection/Count/Project.csproj b/snippets/csharp/System.ComponentModel/PropertyDescriptorCollection/Count/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/PropertyDescriptorCollection/Count/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/PropertyDescriptorCollection/Count/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/PropertyDescriptorCollection/Count/source.cs b/snippets/csharp/System.ComponentModel/PropertyDescriptorCollection/Count/source.cs
index d2e0f6fdc0c..80e17b81e26 100644
--- a/snippets/csharp/System.ComponentModel/PropertyDescriptorCollection/Count/source.cs
+++ b/snippets/csharp/System.ComponentModel/PropertyDescriptorCollection/Count/source.cs
@@ -1,20 +1,19 @@
-using System;
-using System.Data;
-using System.ComponentModel;
+using System.ComponentModel;
using System.Windows.Forms;
-public class Form1: Form
+public class Form1 : Form
{
- protected Button button1;
- protected TextBox textBox1;
-//
-private void GetCount() {
- // Creates a new collection and assign it the properties for button1.
- PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(button1);
-
- // Prints the number of properties on button1 in a textbox.
- textBox1.Text = properties.Count.ToString();
- }
+ protected Button button1;
+ protected TextBox textBox1;
+ //
+ void GetCount()
+ {
+ // Creates a new collection and assign it the properties for button1.
+ PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(button1);
-//
+ // Prints the number of properties on button1 in a textbox.
+ textBox1.Text = properties.Count.ToString();
+ }
+
+ //
}
diff --git a/snippets/csharp/System.ComponentModel/PropertyDescriptorCollection/Find/Project.csproj b/snippets/csharp/System.ComponentModel/PropertyDescriptorCollection/Find/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/PropertyDescriptorCollection/Find/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/PropertyDescriptorCollection/Find/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/PropertyDescriptorCollection/Find/source.cs b/snippets/csharp/System.ComponentModel/PropertyDescriptorCollection/Find/source.cs
index 2b48da329dc..8ecb30ab88a 100644
--- a/snippets/csharp/System.ComponentModel/PropertyDescriptorCollection/Find/source.cs
+++ b/snippets/csharp/System.ComponentModel/PropertyDescriptorCollection/Find/source.cs
@@ -1,23 +1,22 @@
-using System;
-using System.Data;
-using System.ComponentModel;
+using System.ComponentModel;
using System.Windows.Forms;
-public class Form1: Form
+public class Form1 : Form
{
- protected Button button1;
- protected TextBox textBox1;
-//
- private void FindProperty() {
- // Creates a new collection and assign it the properties for button1.
- PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(button1);
-
- // Sets a PropertyDescriptor to the specific property.
- PropertyDescriptor myProperty = properties.Find("Opacity", false);
-
- // Prints the property and the property description.
- textBox1.Text = myProperty.DisplayName + '\n' + myProperty.Description;
- }
+ protected Button button1;
+ protected TextBox textBox1;
+ //
+ void FindProperty()
+ {
+ // Creates a new collection and assign it the properties for button1.
+ PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(button1);
-//
+ // Sets a PropertyDescriptor to the specific property.
+ PropertyDescriptor myProperty = properties.Find("Opacity", false);
+
+ // Prints the property and the property description.
+ textBox1.Text = myProperty.DisplayName + '\n' + myProperty.Description;
+ }
+
+ //
}
diff --git a/snippets/csharp/System.ComponentModel/PropertyDescriptorCollection/GetEnumerator/Project.csproj b/snippets/csharp/System.ComponentModel/PropertyDescriptorCollection/GetEnumerator/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/PropertyDescriptorCollection/GetEnumerator/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/PropertyDescriptorCollection/GetEnumerator/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/PropertyDescriptorCollection/GetEnumerator/source.cs b/snippets/csharp/System.ComponentModel/PropertyDescriptorCollection/GetEnumerator/source.cs
index 1cd439ec29f..401863878ce 100644
--- a/snippets/csharp/System.ComponentModel/PropertyDescriptorCollection/GetEnumerator/source.cs
+++ b/snippets/csharp/System.ComponentModel/PropertyDescriptorCollection/GetEnumerator/source.cs
@@ -1,28 +1,28 @@
-using System;
-using System.Data;
-using System.Collections;
+using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
-public class Form1: Form
+public class Form1 : Form
{
- protected Button button1;
- protected TextBox textBox1;
-//
- private void MyEnumerator() {
- // Creates a new collection and assigns it the properties for button1.
- PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(button1);
-
- // Creates an enumerator.
- IEnumerator ie = properties.GetEnumerator();
-
- // Prints the name of each property in the collection.
- Object myProperty;
- while(ie.MoveNext()) {
- myProperty = ie.Current;
- textBox1.Text += myProperty.ToString() + '\n';
+ protected Button button1;
+ protected TextBox textBox1;
+ //
+ void MyEnumerator()
+ {
+ // Creates a new collection and assigns it the properties for button1.
+ PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(button1);
+
+ // Creates an enumerator.
+ IEnumerator ie = properties.GetEnumerator();
+
+ // Prints the name of each property in the collection.
+ object myProperty;
+ while (ie.MoveNext())
+ {
+ myProperty = ie.Current;
+ textBox1.Text += myProperty.ToString() + '\n';
+ }
}
- }
-//
+ //
}
diff --git a/snippets/csharp/System.ComponentModel/PropertyDescriptorCollection/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/PropertyDescriptorCollection/Overview/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/PropertyDescriptorCollection/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/PropertyDescriptorCollection/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/PropertyDescriptorCollection/Overview/source.cs b/snippets/csharp/System.ComponentModel/PropertyDescriptorCollection/Overview/source.cs
index d132dbc372f..062335719a8 100644
--- a/snippets/csharp/System.ComponentModel/PropertyDescriptorCollection/Overview/source.cs
+++ b/snippets/csharp/System.ComponentModel/PropertyDescriptorCollection/Overview/source.cs
@@ -1,26 +1,28 @@
-using System;
-using System.Data;
-using System.ComponentModel;
+using System.ComponentModel;
using System.Windows.Forms;
-public class Form1: Form
+public class Form1 : Form
{
protected Button button1;
protected TextBox textBox1;
- private void Method1()
+ void Method1()
{
//
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(button1);
//
}
+
//
- private void MyPropertyCollection() {
+ void MyPropertyCollection()
+ {
// Creates a new collection and assign it the properties for button1.
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(button1);
-
+
// Displays each property in the collection in a text box.
foreach (PropertyDescriptor myProperty in properties)
- textBox1.Text += myProperty.Name + '\n';
- }
+ {
+ textBox1.Text += myProperty.Name + '\n';
+ }
+ }
//
}
diff --git a/snippets/csharp/System.ComponentModel/PropertyTabAttribute/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/PropertyTabAttribute/Overview/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/PropertyTabAttribute/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/PropertyTabAttribute/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/PropertyTabAttribute/Overview/class1.cs b/snippets/csharp/System.ComponentModel/PropertyTabAttribute/Overview/class1.cs
index fccb7858ffa..0f3332c1393 100644
--- a/snippets/csharp/System.ComponentModel/PropertyTabAttribute/Overview/class1.cs
+++ b/snippets/csharp/System.ComponentModel/PropertyTabAttribute/Overview/class1.cs
@@ -3,71 +3,49 @@
using System.Drawing;
using System.Windows.Forms.Design;
-namespace TypeCategoryTabExample
+namespace TypeCategoryTabExample;
+
+// This component adds a TypeCategoryTab to the property browser
+// that is available for any components in the current design mode document.
+[PropertyTab(typeof(TypeCategoryTab), PropertyTabScope.Document)]
+public class TypeCategoryTabComponent : Component
{
- // This component adds a TypeCategoryTab to the property browser
- // that is available for any components in the current design mode document.
- [PropertyTabAttribute(typeof(TypeCategoryTab), PropertyTabScope.Document)]
- public class TypeCategoryTabComponent : System.ComponentModel.Component
- {
- public TypeCategoryTabComponent()
- {
- }
+ public TypeCategoryTabComponent()
+ {
}
+}
- // A TypeCategoryTab property tab lists properties by the
- // category of the type of each property.
- public class TypeCategoryTab : PropertyTab
+// A TypeCategoryTab property tab lists properties by the
+// category of the type of each property.
+public class TypeCategoryTab : PropertyTab
+{
+ public TypeCategoryTab()
{
- public TypeCategoryTab()
- {
- }
+ }
- //
- // Returns the properties of the specified component extended with
- // a CategoryAttribute reflecting the name of the type of the property.
- public override System.ComponentModel.PropertyDescriptorCollection GetProperties(object component, System.Attribute[] attributes)
+ //
+ // Returns the properties of the specified component extended with
+ // a CategoryAttribute reflecting the name of the type of the property.
+ public override PropertyDescriptorCollection GetProperties(object component, System.Attribute[] attributes)
+ {
+ PropertyDescriptorCollection props = attributes == null ? TypeDescriptor.GetProperties(component) : TypeDescriptor.GetProperties(component, attributes);
+ PropertyDescriptor[] propArray = new PropertyDescriptor[props.Count];
+ for (int i = 0; i < props.Count; i++)
{
- PropertyDescriptorCollection props;
- if( attributes == null )
- props = TypeDescriptor.GetProperties(component);
- else
- props = TypeDescriptor.GetProperties(component, attributes);
-
- PropertyDescriptor[] propArray = new PropertyDescriptor[props.Count];
- for(int i=0; i
+ public override PropertyDescriptorCollection GetProperties(object component) => GetProperties(component, null);
+ //
- // Provides the name for the property tab.
- public override string TabName
- {
- get
- {
- return "Properties by Type";
- }
- }
+ // Provides the name for the property tab.
+ public override string TabName => "Properties by Type";
- // Provides an image for the property tab.
- public override System.Drawing.Bitmap Bitmap
- {
- get
- {
- Bitmap bmp = new Bitmap(@"myproperty.bmp", true);
- return bmp;
- }
- }
- }
+ // Provides an image for the property tab.
+ public override Bitmap Bitmap => new("myproperty.bmp", true);
}
//
diff --git a/snippets/csharp/System.ComponentModel/ProvidePropertyAttribute/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/ProvidePropertyAttribute/Overview/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/ProvidePropertyAttribute/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/ProvidePropertyAttribute/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/ProvidePropertyAttribute/Overview/source.cs b/snippets/csharp/System.ComponentModel/ProvidePropertyAttribute/Overview/source.cs
index b21634f5261..fd55cff9d6b 100644
--- a/snippets/csharp/System.ComponentModel/ProvidePropertyAttribute/Overview/source.cs
+++ b/snippets/csharp/System.ComponentModel/ProvidePropertyAttribute/Overview/source.cs
@@ -1,29 +1,27 @@
-using System;
+using System.ComponentModel;
using System.Globalization;
-using System.ComponentModel;
using System.Windows.Forms;
//
[ProvideProperty("MyProperty", typeof(Control))]
-public class MyClass : IExtenderProvider {
- protected CultureInfo ciMine = null;
+public class MyClass : IExtenderProvider
+{
+ protected CultureInfo ciMine;
// Provides the Get portion of MyProperty.
- public CultureInfo GetMyProperty(Control myControl) {
+ public CultureInfo GetMyProperty(Control myControl) =>
// Insert code here.
- return ciMine;
- }
-
+ ciMine;
+
// Provides the Set portion of MyProperty.
- public void SetMyProperty(Control myControl, string value) {
+ public void SetMyProperty(Control myControl, string value)
+ {
// Insert code here.
}
-
+
/* When you inherit from IExtenderProvider, you must implement the
* CanExtend method. */
- public bool CanExtend(Object target) {
- return(target is Control);
- }
-
+ public bool CanExtend(object target) => target is Control;
+
// Insert additional code here.
- }
+}
//
diff --git a/snippets/csharp/System.ComponentModel/ReadOnlyAttribute/.ctor/Project.csproj b/snippets/csharp/System.ComponentModel/ReadOnlyAttribute/.ctor/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/ReadOnlyAttribute/.ctor/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/ReadOnlyAttribute/.ctor/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/ReadOnlyAttribute/.ctor/source.cs b/snippets/csharp/System.ComponentModel/ReadOnlyAttribute/.ctor/source.cs
index 48a8f35b6f4..d869bc6a699 100644
--- a/snippets/csharp/System.ComponentModel/ReadOnlyAttribute/.ctor/source.cs
+++ b/snippets/csharp/System.ComponentModel/ReadOnlyAttribute/.ctor/source.cs
@@ -1,23 +1,22 @@
-using System;
-using System.Data;
-using System.ComponentModel;
+using System.ComponentModel;
using System.Windows.Forms;
-public class Form1: Form
+public class Form1 : Form
{
- protected TextBox textBox1;
-
-//
- [ReadOnly(true)]
- public int MyProperty {
- get {
- // Insert code here.
- return 0;
- }
- set {
- // Insert code here.
+ protected TextBox textBox1;
+
+ //
+ [ReadOnly(true)]
+ public int MyProperty
+ {
+ get =>
+ // Insert code here.
+ 0;
+ set
+ {
+ // Insert code here.
+ }
}
- }
-
-//
+
+ //
}
diff --git a/snippets/csharp/System.ComponentModel/ReadOnlyAttribute/IsReadOnly/Project.csproj b/snippets/csharp/System.ComponentModel/ReadOnlyAttribute/IsReadOnly/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/ReadOnlyAttribute/IsReadOnly/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/ReadOnlyAttribute/IsReadOnly/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/ReadOnlyAttribute/IsReadOnly/source.cs b/snippets/csharp/System.ComponentModel/ReadOnlyAttribute/IsReadOnly/source.cs
index 2f0cb724496..0172283e71e 100644
--- a/snippets/csharp/System.ComponentModel/ReadOnlyAttribute/IsReadOnly/source.cs
+++ b/snippets/csharp/System.ComponentModel/ReadOnlyAttribute/IsReadOnly/source.cs
@@ -1,27 +1,26 @@
-using System;
-using System.Data;
-using System.ComponentModel;
+using System.ComponentModel;
using System.Windows.Forms;
-public class Form1: Form
+public class Form1 : Form
{
- protected TextBox textBox1;
-
- public void Method()
- {
-//
- // Gets the attributes for the property.
- AttributeCollection attributes =
- TypeDescriptor.GetProperties(this)["MyProperty"].Attributes;
-
- // Checks to see whether the property is read-only.
- ReadOnlyAttribute myAttribute =
- (ReadOnlyAttribute)attributes[typeof(ReadOnlyAttribute)];
-
- if(myAttribute.IsReadOnly) {
- // Insert code here.
- }
-
-//
- }
+ protected TextBox textBox1;
+
+ public void Method()
+ {
+ //
+ // Gets the attributes for the property.
+ AttributeCollection attributes =
+ TypeDescriptor.GetProperties(this)["MyProperty"].Attributes;
+
+ // Checks to see whether the property is read-only.
+ ReadOnlyAttribute myAttribute =
+ (ReadOnlyAttribute)attributes[typeof(ReadOnlyAttribute)];
+
+ if (myAttribute.IsReadOnly)
+ {
+ // Insert code here.
+ }
+
+ //
+ }
}
diff --git a/snippets/csharp/System.ComponentModel/ReadOnlyAttribute/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/ReadOnlyAttribute/Overview/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/ReadOnlyAttribute/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/ReadOnlyAttribute/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/ReadOnlyAttribute/Overview/source.cs b/snippets/csharp/System.ComponentModel/ReadOnlyAttribute/Overview/source.cs
index 580563d4547..4a4e3e63cce 100644
--- a/snippets/csharp/System.ComponentModel/ReadOnlyAttribute/Overview/source.cs
+++ b/snippets/csharp/System.ComponentModel/ReadOnlyAttribute/Overview/source.cs
@@ -1,48 +1,46 @@
-using System;
-using System.Data;
-using System.ComponentModel;
+using System.ComponentModel;
using System.Windows.Forms;
-public class Form1: Form
+public class Form1 : Form
{
protected TextBox textBox1;
//
[ReadOnly(true)]
- public int MyProperty {
- get {
- // Insert code here.
- return 0;
- }
- }
+ public int MyProperty =>
+ // Insert code here.
+ 0;
//
public void Method1()
{
//
// Gets the attributes for the property.
- AttributeCollection attributes =
+ AttributeCollection attributes =
TypeDescriptor.GetProperties(this)["MyProperty"].Attributes;
-
+
// Checks to see whether the value of the ReadOnlyAttribute is Yes.
- if(attributes[typeof(ReadOnlyAttribute)].Equals(ReadOnlyAttribute.Yes)) {
- // Insert code here.
+ if (attributes[typeof(ReadOnlyAttribute)].Equals(ReadOnlyAttribute.Yes))
+ {
+ // Insert code here.
}
-
+
// This is another way to see whether the property is read-only.
- ReadOnlyAttribute myAttribute =
+ ReadOnlyAttribute myAttribute =
(ReadOnlyAttribute)attributes[typeof(ReadOnlyAttribute)];
- if(myAttribute.IsReadOnly) {
- // Insert code here.
+ if (myAttribute.IsReadOnly)
+ {
+ // Insert code here.
}
//
}
-
+
public void Method2()
{
//
- AttributeCollection attributes =
+ AttributeCollection attributes =
TypeDescriptor.GetAttributes(MyProperty);
- if(attributes[typeof(ReadOnlyAttribute)].Equals(ReadOnlyAttribute.Yes)) {
- // Insert code here.
+ if (attributes[typeof(ReadOnlyAttribute)].Equals(ReadOnlyAttribute.Yes))
+ {
+ // Insert code here.
}
//
}
diff --git a/snippets/csharp/System.ComponentModel/RecommendedAsConfigurableAttribute/.ctor/Project.csproj b/snippets/csharp/System.ComponentModel/RecommendedAsConfigurableAttribute/.ctor/Project.csproj
deleted file mode 100644
index a11815b79fb..00000000000
--- a/snippets/csharp/System.ComponentModel/RecommendedAsConfigurableAttribute/.ctor/Project.csproj
+++ /dev/null
@@ -1,9 +0,0 @@
-
-
-
- Library
- net6.0-windows
- true
-
-
-
diff --git a/snippets/csharp/System.ComponentModel/RecommendedAsConfigurableAttribute/.ctor/source.cs b/snippets/csharp/System.ComponentModel/RecommendedAsConfigurableAttribute/.ctor/source.cs
deleted file mode 100644
index 5915d425f15..00000000000
--- a/snippets/csharp/System.ComponentModel/RecommendedAsConfigurableAttribute/.ctor/source.cs
+++ /dev/null
@@ -1,23 +0,0 @@
-using System;
-using System.Data;
-using System.ComponentModel;
-using System.Windows.Forms;
-
-public class Form1: Form
-{
- protected TextBox textBox1;
-
-//
- [RecommendedAsConfigurable(true)]
- public int MyProperty {
- get {
- // Insert code here.
- return 0;
- }
- set {
- // Insert code here.
- }
- }
-
-//
-}
diff --git a/snippets/csharp/System.ComponentModel/RecommendedAsConfigurableAttribute/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/RecommendedAsConfigurableAttribute/Overview/Project.csproj
deleted file mode 100644
index a11815b79fb..00000000000
--- a/snippets/csharp/System.ComponentModel/RecommendedAsConfigurableAttribute/Overview/Project.csproj
+++ /dev/null
@@ -1,9 +0,0 @@
-
-
-
- Library
- net6.0-windows
- true
-
-
-
diff --git a/snippets/csharp/System.ComponentModel/RecommendedAsConfigurableAttribute/Overview/source.cs b/snippets/csharp/System.ComponentModel/RecommendedAsConfigurableAttribute/Overview/source.cs
deleted file mode 100644
index 2abfe3f2fd8..00000000000
--- a/snippets/csharp/System.ComponentModel/RecommendedAsConfigurableAttribute/Overview/source.cs
+++ /dev/null
@@ -1,50 +0,0 @@
-using System;
-using System.Data;
-using System.ComponentModel;
-using System.Windows.Forms;
-
-public class Form1: Form
-{
-
- //
- [RecommendedAsConfigurable(true)]
- public int MyProperty {
- get {
- // Insert code here.
- return 0;
- }
- set {
- // Insert code here.
- }
- }
- //
- public void Method1(){
- //
- // Gets the attributes for the property.
- AttributeCollection attributes =
- TypeDescriptor.GetProperties(this)["MyProperty"].Attributes;
-
- // Checks to see if the value of the RecommendedAsConfigurableAttribute is Yes.
- if(attributes[typeof(RecommendedAsConfigurableAttribute)].Equals(RecommendedAsConfigurableAttribute.Yes)) {
- // Insert code here.
- }
-
- // This is another way to see if the property is recommended as configurable.
- RecommendedAsConfigurableAttribute myAttribute =
- (RecommendedAsConfigurableAttribute)attributes[typeof(RecommendedAsConfigurableAttribute)];
- if(myAttribute.RecommendedAsConfigurable) {
- // Insert code here.
- }
- //
- }
-
- public void Method2(){
- //
- AttributeCollection attributes =
- TypeDescriptor.GetAttributes(MyProperty);
- if(attributes[typeof(RecommendedAsConfigurableAttribute)].Equals(RecommendedAsConfigurableAttribute.Yes)) {
- // Insert code here.
- }
- //
- }
-}
diff --git a/snippets/csharp/System.ComponentModel/RecommendedAsConfigurableAttribute/RecommendedAsConfigurable/Project.csproj b/snippets/csharp/System.ComponentModel/RecommendedAsConfigurableAttribute/RecommendedAsConfigurable/Project.csproj
deleted file mode 100644
index a11815b79fb..00000000000
--- a/snippets/csharp/System.ComponentModel/RecommendedAsConfigurableAttribute/RecommendedAsConfigurable/Project.csproj
+++ /dev/null
@@ -1,9 +0,0 @@
-
-
-
- Library
- net6.0-windows
- true
-
-
-
diff --git a/snippets/csharp/System.ComponentModel/RecommendedAsConfigurableAttribute/RecommendedAsConfigurable/source.cs b/snippets/csharp/System.ComponentModel/RecommendedAsConfigurableAttribute/RecommendedAsConfigurable/source.cs
deleted file mode 100644
index d86490885fc..00000000000
--- a/snippets/csharp/System.ComponentModel/RecommendedAsConfigurableAttribute/RecommendedAsConfigurable/source.cs
+++ /dev/null
@@ -1,26 +0,0 @@
-using System;
-using System.Data;
-using System.ComponentModel;
-using System.Windows.Forms;
-
-public class Form1: Form
-{
- protected TextBox textBox1;
-
- public void Method()
- {
-//
- // Gets the attributes for the property.
- AttributeCollection attributes =
- TypeDescriptor.GetProperties(this)["MyProperty"].Attributes;
-
- // Checks to see if the property is recommended as configurable.
- RecommendedAsConfigurableAttribute myAttribute =
- (RecommendedAsConfigurableAttribute)attributes[typeof(RecommendedAsConfigurableAttribute)];
- if(myAttribute.RecommendedAsConfigurable) {
- // Insert code here.
- }
-
-//
- }
-}
diff --git a/snippets/csharp/System.ComponentModel/RefreshEventHandler/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/RefreshEventHandler/Overview/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/RefreshEventHandler/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/RefreshEventHandler/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/RefreshEventHandler/Overview/refreshevent.cs b/snippets/csharp/System.ComponentModel/RefreshEventHandler/Overview/refreshevent.cs
index 9ede68309ce..5fa464dd675 100644
--- a/snippets/csharp/System.ComponentModel/RefreshEventHandler/Overview/refreshevent.cs
+++ b/snippets/csharp/System.ComponentModel/RefreshEventHandler/Overview/refreshevent.cs
@@ -1,120 +1,101 @@
using System;
-using System.Drawing;
-using System.Collections;
using System.ComponentModel;
+using System.Drawing;
using System.Windows.Forms;
-using System.Data;
-namespace PropertyChanged
+namespace PropertyChanged;
+
+///
+/// Summary description for Form1.
+///
+public class Form1 : Form
{
- ///
- /// Summary description for Form1.
- ///
- public class Form1 : System.Windows.Forms.Form
- {
- private System.Windows.Forms.TextBox textBox1;
- ///
- /// Required designer variable.
- ///
- private System.ComponentModel.Container components = null;
+ TextBox textBox1;
+ ///
+ /// Required designer variable.
+ ///
+ readonly Container _components;
- public Form1()
- {
- //
- // Required for Windows Form Designer support
- //
- InitializeComponent();
+ public Form1()
+ {
+ InitializeComponent();
+ // TODO: Add any constructor code after InitializeComponent call
+ }
- //
- // TODO: Add any constructor code after InitializeComponent call
- //
- }
+ ///
+ /// Clean up any resources being used.
+ ///
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ _components?.Dispose();
+ }
+ base.Dispose(disposing);
+ }
- ///
- /// Clean up any resources being used.
- ///
- protected override void Dispose( bool disposing )
- {
- if( disposing )
- {
- if (components != null)
- {
- components.Dispose();
- }
- }
- base.Dispose( disposing );
- }
+ #region Windows Form Designer generated code
+ ///
+ /// Required method for Designer support - do not modify
+ /// the contents of this method with the code editor.
+ ///
+ void InitializeComponent()
+ {
+ textBox1 = new TextBox();
+ SuspendLayout();
+ //
+ // textBox1
+ //
+ textBox1.Multiline = true;
+ textBox1.Name = "textBox1";
+ textBox1.TabIndex = 0;
+ textBox1.Text = "textBox1";
+ //
+ // Form1
+ //
+ ClientSize = new Size(488, 301);
+ Controls.AddRange([textBox1]);
+ Name = "Form1";
+ Text = "Form1";
+ Load += Form1_Load;
+ ResumeLayout(false);
+ }
+ #endregion
- #region Windows Form Designer generated code
- ///
- /// Required method for Designer support - do not modify
- /// the contents of this method with the code editor.
- ///
- private void InitializeComponent()
- {
- this.textBox1 = new System.Windows.Forms.TextBox();
- this.SuspendLayout();
- //
- // textBox1
- //
- this.textBox1.Multiline = true;
- this.textBox1.Name = "textBox1";
- this.textBox1.TabIndex = 0;
- this.textBox1.Text = "textBox1";
- //
- // Form1
- //
- this.ClientSize = new System.Drawing.Size(488, 301);
- this.Controls.AddRange(new System.Windows.Forms.Control[] {
- this.textBox1});
- this.Name = "Form1";
- this.Text = "Form1";
- this.Load += new System.EventHandler(this.Form1_Load);
- this.ResumeLayout(false);
- }
- #endregion
+ ///
+ /// The main entry point for the application.
+ ///
+ [STAThread]
+ static void Main() => Application.Run(new Form1());
- ///
- /// The main entry point for the application.
- ///
- [STAThread]
- static void Main()
- {
- Application.Run(new Form1());
- }
+ //
+ void Form1_Load(object sender, EventArgs e)
+ {
+ textBox1.Text = "changed";
+ TypeDescriptor.Refreshed += new RefreshEventHandler(OnRefresh);
+ _ = TypeDescriptor.GetProperties(textBox1);
+ TypeDescriptor.Refresh(textBox1);
+ }
-//
-private void Form1_Load(object sender, System.EventArgs e)
-{
- textBox1.Text = "changed";
- System.ComponentModel.TypeDescriptor.Refreshed += new
- System.ComponentModel.RefreshEventHandler(OnRefresh);
- System.ComponentModel.TypeDescriptor.GetProperties(textBox1);
- System.ComponentModel.TypeDescriptor.Refresh(textBox1);
+ protected static void OnRefresh(RefreshEventArgs e) =>
+ Console.WriteLine(e.ComponentChanged.ToString());
+ //
}
-protected static void OnRefresh(System.ComponentModel.RefreshEventArgs e)
+class Control : Component
{
- Console.WriteLine(e.ComponentChanged.ToString());
-}
-//
- }
+ int position;
- class Control : Component
- {
- int position;
-
- public int Position
- {
- get { return position; }
- set
- {
- if (!position.Equals(value))
- {
- position = value;
- //RaisePropertyChangedEvent(position);
- }
- }
- }
- }
+ public int Position
+ {
+ get => position;
+ set
+ {
+ if (!position.Equals(value))
+ {
+ position = value;
+ //RaisePropertyChangedEvent(position);
+ }
+ }
+ }
}
diff --git a/snippets/csharp/System.ComponentModel/ToolboxItemAttribute/Overview/Form1.cs b/snippets/csharp/System.ComponentModel/ToolboxItemAttribute/Overview/Form1.cs
index 3730738dc59..9060e781f89 100644
--- a/snippets/csharp/System.ComponentModel/ToolboxItemAttribute/Overview/Form1.cs
+++ b/snippets/csharp/System.ComponentModel/ToolboxItemAttribute/Overview/Form1.cs
@@ -1,285 +1,256 @@
//
using System;
-using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Design;
-using System.Data;
using System.Runtime.Serialization;
-using System.Text;
using System.Windows.Forms;
-namespace CustomToolboxItem
+namespace CustomToolboxItem;
+
+public class Form1 : Form
{
- public class Form1 : Form
- {
- private System.ComponentModel.IContainer components = null;
- private UserControl1 userControl11;
- private System.Windows.Forms.Label label1;
+ readonly IContainer _components;
+ UserControl1 userControl11;
+ Label label1;
- public Form1()
- {
- InitializeComponent();
- }
+ public Form1() => InitializeComponent();
- private void InitializeComponent()
- {
- this.label1 = new System.Windows.Forms.Label();
- this.userControl11 = new CustomToolboxItem.UserControl1();
- this.SuspendLayout();
- //
- // label1
- //
- this.label1.Location = new System.Drawing.Point(15, 16);
- this.label1.Name = "label1";
- this.label1.Size = new System.Drawing.Size(265, 62);
- this.label1.TabIndex = 0;
- this.label1.Text = "Build the project and drop UserControl1 from the toolbox onto the form.";
- //
- // userControl11
- //
- this.userControl11.LabelText = "This is a custom user control. The text you see here is provided by a custom too" +
- "lbox item when the user control is dropped on the form.";
- this.userControl11.Location = new System.Drawing.Point(74, 81);
- this.userControl11.Name = "userControl11";
- this.userControl11.Padding = new System.Windows.Forms.Padding(6);
- this.userControl11.Size = new System.Drawing.Size(150, 150);
- this.userControl11.TabIndex = 1;
- //
- // Form1
- //
- this.ClientSize = new System.Drawing.Size(292, 266);
- this.Controls.Add(this.userControl11);
- this.Controls.Add(this.label1);
- this.Name = "Form1";
- this.Text = "Form1";
- this.ResumeLayout(false);
- }
+ void InitializeComponent()
+ {
+ label1 = new Label();
+ userControl11 = new UserControl1();
+ SuspendLayout();
+ //
+ // label1
+ //
+ label1.Location = new Point(15, 16);
+ label1.Name = "label1";
+ label1.Size = new Size(265, 62);
+ label1.TabIndex = 0;
+ label1.Text = "Build the project and drop UserControl1 from the toolbox onto the form.";
+ //
+ // userControl11
+ //
+ userControl11.LabelText = "This is a custom user control. The text you see here is provided by a custom too" +
+ "lbox item when the user control is dropped on the form.";
+ userControl11.Location = new Point(74, 81);
+ userControl11.Name = "userControl11";
+ userControl11.Padding = new Padding(6);
+ userControl11.Size = new Size(150, 150);
+ userControl11.TabIndex = 1;
+ //
+ // Form1
+ //
+ ClientSize = new Size(292, 266);
+ Controls.Add(userControl11);
+ Controls.Add(label1);
+ Name = "Form1";
+ Text = "Form1";
+ ResumeLayout(false);
+ }
- protected override void Dispose(bool disposing)
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing && (_components != null))
{
- if (disposing && (components != null))
- {
- components.Dispose();
- }
- base.Dispose(disposing);
+ _components.Dispose();
}
+ base.Dispose(disposing);
+ }
- static void Main()
- {
- Application.EnableVisualStyles();
- Application.Run(new Form1());
- }
+ static void Main()
+ {
+ Application.EnableVisualStyles();
+ Application.Run(new Form1());
}
+}
- // Configure this user control to have a custom toolbox item.
+// Configure this user control to have a custom toolbox item.
//
- [ToolboxItem(typeof(MyToolboxItem))]
- public class UserControl1 : UserControl
+[ToolboxItem(typeof(MyToolboxItem))]
+public class UserControl1 : UserControl
//
- {
- private System.ComponentModel.IContainer components = null;
- private System.Windows.Forms.Label label1;
+{
+ readonly IContainer _components;
+ Label label1;
- public UserControl1()
- {
- InitializeComponent();
- }
+ public UserControl1() => InitializeComponent();
- public string LabelText
- {
- get
- {
- return label1.Text;
- }
- set
- {
- label1.Text = value;
- }
- }
+ public string LabelText
+ {
+ get => label1.Text; set => label1.Text = value;
+ }
- private void InitializeComponent()
- {
- this.label1 = new System.Windows.Forms.Label();
- this.SuspendLayout();
- //
- // label1
- //
- this.label1.Dock = System.Windows.Forms.DockStyle.Fill;
- this.label1.Location = new System.Drawing.Point(6, 6);
- this.label1.Name = "label1";
- this.label1.Size = new System.Drawing.Size(138, 138);
- this.label1.TabIndex = 0;
- this.label1.Text = "This is a custom user control. " +
- "The text you see here is provided by a custom toolbox" +
- " item when the user control is dropped on the form.\r\n";
- this.label1.TextAlign =
- System.Drawing.ContentAlignment.MiddleCenter;
- //
- // UserControl1
- //
- this.Controls.Add(this.label1);
- this.Name = "UserControl1";
- this.Padding = new System.Windows.Forms.Padding(6);
- this.ResumeLayout(false);
- }
+ void InitializeComponent()
+ {
+ label1 = new Label();
+ SuspendLayout();
+ //
+ // label1
+ //
+ label1.Dock = DockStyle.Fill;
+ label1.Location = new Point(6, 6);
+ label1.Name = "label1";
+ label1.Size = new Size(138, 138);
+ label1.TabIndex = 0;
+ label1.Text = "This is a custom user control. " +
+ "The text you see here is provided by a custom toolbox" +
+ " item when the user control is dropped on the form.\r\n";
+ label1.TextAlign =
+ ContentAlignment.MiddleCenter;
+ //
+ // UserControl1
+ //
+ Controls.Add(label1);
+ Name = "UserControl1";
+ Padding = new Padding(6);
+ ResumeLayout(false);
+ }
- protected override void Dispose(bool disposing)
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing && (_components != null))
{
- if (disposing && (components != null))
- {
- components.Dispose();
- }
- base.Dispose(disposing);
+ _components.Dispose();
}
+ base.Dispose(disposing);
}
+}
//
- // Toolbox items must be serializable.
- [Serializable]
- class MyToolboxItem : ToolboxItem
+// Toolbox items must be serializable.
+[Serializable]
+class MyToolboxItem : ToolboxItem
+{
+ // The add components dialog in Visual Studio looks for a public
+ // constructor that takes a type.
+ public MyToolboxItem(Type toolType)
+ : base(toolType)
{
- // The add components dialog in Visual Studio looks for a public
- // constructor that takes a type.
- public MyToolboxItem(Type toolType)
- : base(toolType)
- {
- }
+ }
- // And you must provide this special constructor for serialization.
- // If you add additional data to MyToolboxItem that you
- // want to serialize, you may override Deserialize and
- // Serialize methods to add that data.
-//
- MyToolboxItem(SerializationInfo info, StreamingContext context)
- {
- Deserialize(info, context);
- }
-//
+ // And you must provide this special constructor for serialization.
+ // If you add additional data to MyToolboxItem that you
+ // want to serialize, you may override Deserialize and
+ // Serialize methods to add that data.
+ //
+ MyToolboxItem(SerializationInfo info, StreamingContext context) => Deserialize(info, context);
+ //
- // Let's override the creation code and pop up a dialog.
-//
- protected override IComponent[] CreateComponentsCore(
- System.ComponentModel.Design.IDesignerHost host,
- System.Collections.IDictionary defaultValues)
+ // Let's override the creation code and pop up a dialog.
+ //
+ protected override IComponent[] CreateComponentsCore(
+ System.ComponentModel.Design.IDesignerHost host,
+ System.Collections.IDictionary defaultValues)
+ {
+ // Get the string we want to fill in the custom
+ // user control. If the user cancels out of the dialog,
+ // return null or an empty array to signify that the
+ // tool creation was canceled.
+ using (ToolboxItemDialog d = new())
{
- // Get the string we want to fill in the custom
- // user control. If the user cancels out of the dialog,
- // return null or an empty array to signify that the
- // tool creation was canceled.
- using (ToolboxItemDialog d = new ToolboxItemDialog())
+ if (d.ShowDialog() == DialogResult.OK)
{
- if (d.ShowDialog() == DialogResult.OK)
- {
- string text = d.CreationText;
+ string text = d.CreationText;
- IComponent[] comps =
- base.CreateComponentsCore(host, defaultValues);
- // comps will have a single component: our data type.
- ((UserControl1)comps[0]).LabelText = text;
- return comps;
- }
- else
- {
- return null;
- }
+ IComponent[] comps =
+ base.CreateComponentsCore(host, defaultValues);
+ // comps will have a single component: our data type.
+ ((UserControl1)comps[0]).LabelText = text;
+ return comps;
+ }
+ else
+ {
+ return null;
}
}
-//
}
+ //
+}
//
- public class ToolboxItemDialog : Form
- {
- private System.ComponentModel.IContainer components = null;
- private System.Windows.Forms.Label label1;
- private System.Windows.Forms.TextBox textBox1;
- private System.Windows.Forms.Button button1;
- private System.Windows.Forms.Button button2;
+public class ToolboxItemDialog : Form
+{
+ readonly IContainer _components;
+ Label label1;
+ TextBox textBox1;
+ Button button1;
+ Button button2;
- public ToolboxItemDialog()
- {
- InitializeComponent();
- }
+ public ToolboxItemDialog() => InitializeComponent();
- private void InitializeComponent()
- {
- this.label1 = new System.Windows.Forms.Label();
- this.textBox1 = new System.Windows.Forms.TextBox();
- this.button1 = new System.Windows.Forms.Button();
- this.button2 = new System.Windows.Forms.Button();
- this.SuspendLayout();
- //
- // label1
- //
- this.label1.Location = new System.Drawing.Point(10, 9);
- this.label1.Name = "label1";
- this.label1.Size = new System.Drawing.Size(273, 43);
- this.label1.TabIndex = 0;
- this.label1.Text = "Enter the text you would like" +
- " to have the user control populated with:";
- //
- // textBox1
- //
- this.textBox1.AutoSize = false;
- this.textBox1.Location = new System.Drawing.Point(10, 58);
- this.textBox1.Multiline = true;
- this.textBox1.Name = "textBox1";
- this.textBox1.Size = new System.Drawing.Size(270, 67);
- this.textBox1.TabIndex = 1;
- this.textBox1.Text = "This is a custom user control. " +
- "The text you see here is provided by a custom toolbox" +
- " item when the user control is dropped on the form.";
- //
- // button1
- //
- this.button1.DialogResult = System.Windows.Forms.DialogResult.OK;
- this.button1.Location = new System.Drawing.Point(124, 131);
- this.button1.Name = "button1";
- this.button1.TabIndex = 2;
- this.button1.Text = "OK";
- //
- // button2
- //
- this.button2.DialogResult = System.Windows.Forms.DialogResult.Cancel;
- this.button2.Location = new System.Drawing.Point(205, 131);
- this.button2.Name = "button2";
- this.button2.TabIndex = 3;
- this.button2.Text = "Cancel";
- //
- // ToolboxItemDialog
- //
- this.AcceptButton = this.button1;
- this.CancelButton = this.button2;
- this.ClientSize = new System.Drawing.Size(292, 162);
- this.ControlBox = false;
- this.Controls.Add(this.button2);
- this.Controls.Add(this.button1);
- this.Controls.Add(this.textBox1);
- this.Controls.Add(this.label1);
- this.FormBorderStyle =
- System.Windows.Forms.FormBorderStyle.FixedDialog;
- this.Name = "ToolboxItemDialog";
- this.Text = "ToolboxItemDialog";
- this.ResumeLayout(false);
- }
+ void InitializeComponent()
+ {
+ label1 = new Label();
+ textBox1 = new TextBox();
+ button1 = new Button();
+ button2 = new Button();
+ SuspendLayout();
+ //
+ // label1
+ //
+ label1.Location = new Point(10, 9);
+ label1.Name = "label1";
+ label1.Size = new Size(273, 43);
+ label1.TabIndex = 0;
+ label1.Text = "Enter the text you would like" +
+ " to have the user control populated with:";
+ //
+ // textBox1
+ //
+ textBox1.AutoSize = false;
+ textBox1.Location = new Point(10, 58);
+ textBox1.Multiline = true;
+ textBox1.Name = "textBox1";
+ textBox1.Size = new Size(270, 67);
+ textBox1.TabIndex = 1;
+ textBox1.Text = "This is a custom user control. " +
+ "The text you see here is provided by a custom toolbox" +
+ " item when the user control is dropped on the form.";
+ //
+ // button1
+ //
+ button1.DialogResult = DialogResult.OK;
+ button1.Location = new Point(124, 131);
+ button1.Name = "button1";
+ button1.TabIndex = 2;
+ button1.Text = "OK";
+ //
+ // button2
+ //
+ button2.DialogResult = DialogResult.Cancel;
+ button2.Location = new Point(205, 131);
+ button2.Name = "button2";
+ button2.TabIndex = 3;
+ button2.Text = "Cancel";
+ //
+ // ToolboxItemDialog
+ //
+ AcceptButton = button1;
+ CancelButton = button2;
+ ClientSize = new Size(292, 162);
+ ControlBox = false;
+ Controls.Add(button2);
+ Controls.Add(button1);
+ Controls.Add(textBox1);
+ Controls.Add(label1);
+ FormBorderStyle =
+ FormBorderStyle.FixedDialog;
+ Name = "ToolboxItemDialog";
+ Text = "ToolboxItemDialog";
+ ResumeLayout(false);
+ }
- public string CreationText
- {
- get
- {
- return textBox1.Text;
- }
- }
+ public string CreationText => textBox1.Text;
- protected override void Dispose(bool disposing)
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing && (_components != null))
{
- if (disposing && (components != null))
- {
- components.Dispose();
- }
- base.Dispose(disposing);
+ _components.Dispose();
}
+ base.Dispose(disposing);
}
}
//
diff --git a/snippets/csharp/System.ComponentModel/ToolboxItemAttribute/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/ToolboxItemAttribute/Overview/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/ToolboxItemAttribute/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/ToolboxItemAttribute/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/ToolboxItemFilterAttribute/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/ToolboxItemFilterAttribute/Overview/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/ToolboxItemFilterAttribute/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/ToolboxItemFilterAttribute/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/ToolboxItemFilterAttribute/Overview/samplecontrol.cs b/snippets/csharp/System.ComponentModel/ToolboxItemFilterAttribute/Overview/samplecontrol.cs
index 1fd4961b70d..6ef9212ad73 100644
--- a/snippets/csharp/System.ComponentModel/ToolboxItemFilterAttribute/Overview/samplecontrol.cs
+++ b/snippets/csharp/System.ComponentModel/ToolboxItemFilterAttribute/Overview/samplecontrol.cs
@@ -1,9 +1,7 @@
//
using System;
-using System.Collections;
using System.ComponentModel;
using System.ComponentModel.Design;
-using System.Diagnostics;
using System.Drawing;
using System.Drawing.Design;
using System.Windows.Forms;
@@ -13,123 +11,120 @@
// This example demonstrates how to enable the GetToolSupported method of an IToolboxUser
// designer in order to disable specific toolbox items, and how to respond to the
// invocation of a ToolboxItem in the ToolPicked method of an IToolboxUser implementation.
-namespace IToolboxUserExample
-{
- // This example component class demonstrates the associated IRootDesigner which
- // implements the IToolboxUser interface. When designer view is invoked, Visual
- // Studio .NET attempts to display a design mode view for the class at the top
- // of a code file. This can sometimes fail when the class is one of multiple types
- // in a code file, and has a DesignerAttribute associating it with an IRootDesigner.
- // Placing a derived class at the top of the code file solves this problem. A
- // derived class is not typically needed for this reason, except that placing the
- // RootDesignedComponent class in another file is not a simple solution for a code
- // example that is packaged in one segment of code.
- public class RootViewSampleComponent : RootDesignedComponent
- {
- }
+namespace IToolboxUserExample;
- // The following attribute associates the SampleRootDesigner with this example component.
- [DesignerAttribute(typeof(SampleRootDesigner), typeof(IRootDesigner))]
- public class RootDesignedComponent : System.Windows.Forms.Control
- {
- }
+// This example component class demonstrates the associated IRootDesigner which
+// implements the IToolboxUser interface. When designer view is invoked, Visual
+// Studio .NET attempts to display a design mode view for the class at the top
+// of a code file. This can sometimes fail when the class is one of multiple types
+// in a code file, and has a DesignerAttribute associating it with an IRootDesigner.
+// Placing a derived class at the top of the code file solves this problem. A
+// derived class is not typically needed for this reason, except that placing the
+// RootDesignedComponent class in another file is not a simple solution for a code
+// example that is packaged in one segment of code.
+public class RootViewSampleComponent : RootDesignedComponent;
- // This example IRootDesigner implements the IToolboxUser interface and provides a
- // Windows Forms view technology view for its associated component using an internal
- // Control type.
- // The following ToolboxItemFilterAttribute enables the GetToolSupported method of this
- // IToolboxUser designer to be queried to check for whether to enable or disable all
- // ToolboxItems which create any components whose type name begins with "System.Windows.Forms".
- [ToolboxItemFilterAttribute("System.Windows.Forms", ToolboxItemFilterType.Custom)]
- public class SampleRootDesigner : ParentControlDesigner, IRootDesigner, IToolboxUser
- {
- // This field is a custom Control type named RootDesignerView. This field references
- // a control that is shown in the design mode document window.
- private RootDesignerView view;
+// The following attribute associates the SampleRootDesigner with this example component.
+[Designer(typeof(SampleRootDesigner), typeof(IRootDesigner))]
+public class RootDesignedComponent : Control;
- // This string array contains type names of components that should not be added to
- // the component managed by this designer from the Toolbox. Any ToolboxItems whose
- // type name matches a type name in this array will be marked disabled according to
- // the signal returned by the IToolboxUser.GetToolSupported method of this designer.
- private string[] blockedTypeNames =
- {
- "System.Windows.Forms.ListBox",
- "System.Windows.Forms.GroupBox"
- };
+// This example IRootDesigner implements the IToolboxUser interface and provides a
+// Windows Forms view technology view for its associated component using an internal
+// Control type.
+// The following ToolboxItemFilterAttribute enables the GetToolSupported method of this
+// IToolboxUser designer to be queried to check for whether to enable or disable all
+// ToolboxItems which create any components whose type name begins with "System.Windows.Forms".
+[ToolboxItemFilter("System.Windows.Forms", ToolboxItemFilterType.Custom)]
+public class SampleRootDesigner : ParentControlDesigner, IRootDesigner, IToolboxUser
+{
+ // This field is a custom Control type named RootDesignerView. This field references
+ // a control that is shown in the design mode document window.
+ RootDesignerView view;
- // IRootDesigner.SupportedTechnologies is a required override for an IRootDesigner.
- // This designer provides a display using the Windows Forms view technology.
- ViewTechnology[] IRootDesigner.SupportedTechnologies
+ // This string array contains type names of components that should not be added to
+ // the component managed by this designer from the Toolbox. Any ToolboxItems whose
+ // type name matches a type name in this array will be marked disabled according to
+ // the signal returned by the IToolboxUser.GetToolSupported method of this designer.
+ readonly string[] blockedTypeNames =
+ [
+ "System.Windows.Forms.ListBox",
+ "System.Windows.Forms.GroupBox"
+ ];
+
+ // IRootDesigner.SupportedTechnologies is a required override for an IRootDesigner.
+ // This designer provides a display using the Windows Forms view technology.
+ ViewTechnology[] IRootDesigner.SupportedTechnologies => [ViewTechnology.Default];
+
+ // This method returns an object that provides the view for this root designer.
+ object IRootDesigner.GetView(ViewTechnology technology)
+ {
+ // If the design environment requests a view technology other than Windows
+ // Forms, this method throws an Argument Exception.
+ if (technology != ViewTechnology.Default)
{
- get { return new ViewTechnology[] {ViewTechnology.Default}; }
+ throw new ArgumentException("An unsupported view technology was requested",
+ nameof(technology));
}
- // This method returns an object that provides the view for this root designer.
- object IRootDesigner.GetView(ViewTechnology technology)
+ // Creates the view object if it has not yet been initialized.
+ view ??= new RootDesignerView(this);
+
+ return view;
+ }
+
+ //
+ // This method can signal whether to enable or disable the specified
+ // ToolboxItem when the component associated with this designer is selected.
+ bool IToolboxUser.GetToolSupported(ToolboxItem tool)
+ {
+ // Search the blocked type names array for the type name of the tool
+ // for which support for is being tested. Return false to indicate the
+ // tool should be disabled when the associated component is selected.
+ for (int i = 0; i < blockedTypeNames.Length; i++)
{
- // If the design environment requests a view technology other than Windows
- // Forms, this method throws an Argument Exception.
- if (technology != ViewTechnology.Default)
- throw new ArgumentException("An unsupported view technology was requested",
- "Unsupported view technology.");
-
- // Creates the view object if it has not yet been initialized.
- if (view == null)
- view = new RootDesignerView(this);
-
- return view;
+ if (tool.TypeName == blockedTypeNames[i])
+ {
+ return false;
+ }
}
- //
- // This method can signal whether to enable or disable the specified
- // ToolboxItem when the component associated with this designer is selected.
- bool IToolboxUser.GetToolSupported(ToolboxItem tool)
- {
- // Search the blocked type names array for the type name of the tool
- // for which support for is being tested. Return false to indicate the
- // tool should be disabled when the associated component is selected.
- for( int i=0; i
-
- //
- // This method can perform behavior when the specified tool has been invoked.
- // Invocation of a ToolboxItem typically creates a component or components,
- // and adds any created components to the associated component.
- void IToolboxUser.ToolPicked(ToolboxItem tool)
+ // Return true to indicate support for the tool, if the type name of the
+ // tool is not located in the blockedTypeNames string array.
+ return true;
+ }
+ //
+
+ //
+ // This method can perform behavior when the specified tool has been invoked.
+ // Invocation of a ToolboxItem typically creates a component or components,
+ // and adds any created components to the associated component.
+ void IToolboxUser.ToolPicked(ToolboxItem tool)
+ {
+ }
+ //
+
+ // This control provides a Windows Forms view technology view object that
+ // provides a display for the SampleRootDesigner.
+ [Designer(typeof(ParentControlDesigner), typeof(IDesigner))]
+ internal class RootDesignerView : Control
+ {
+ // This field stores a reference to a designer.
+ readonly IDesigner m_designer;
+
+ public RootDesignerView(IDesigner designer)
{
+ // Perform basic control initialization.
+ m_designer = designer;
+ BackColor = Color.Blue;
+ Font = new Font(Font.FontFamily.Name, 24.0f);
}
- //
- // This control provides a Windows Forms view technology view object that
- // provides a display for the SampleRootDesigner.
- [DesignerAttribute(typeof(ParentControlDesigner), typeof(IDesigner))]
- internal class RootDesignerView : Control
+ // This method is called to draw the view for the SampleRootDesigner.
+ protected override void OnPaint(PaintEventArgs pe)
{
- // This field stores a reference to a designer.
- private IDesigner m_designer;
-
- public RootDesignerView(IDesigner designer)
- {
- // Perform basic control initialization.
- m_designer = designer;
- BackColor = Color.Blue;
- Font = new Font(Font.FontFamily.Name, 24.0f);
- }
-
- // This method is called to draw the view for the SampleRootDesigner.
- protected override void OnPaint(PaintEventArgs pe)
- {
- base.OnPaint(pe);
- // Draw the name of the component in large letters.
- pe.Graphics.DrawString(m_designer.Component.Site.Name, Font, Brushes.Yellow, ClientRectangle);
- }
+ base.OnPaint(pe);
+ // Draw the name of the component in large letters.
+ pe.Graphics.DrawString(m_designer.Component.Site.Name, Font, Brushes.Yellow, ClientRectangle);
}
}
}
diff --git a/snippets/csharp/System.ComponentModel/TypeConverter/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/TypeConverter/Overview/Project.csproj
index c02dc5044e7..5a1b02db677 100644
--- a/snippets/csharp/System.ComponentModel/TypeConverter/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/TypeConverter/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0
+ net8.0
\ No newline at end of file
diff --git a/snippets/csharp/System.ComponentModel/TypeConverter/Overview/source.cs b/snippets/csharp/System.ComponentModel/TypeConverter/Overview/source.cs
index d302970d6fb..940f4da7175 100644
--- a/snippets/csharp/System.ComponentModel/TypeConverter/Overview/source.cs
+++ b/snippets/csharp/System.ComponentModel/TypeConverter/Overview/source.cs
@@ -1,50 +1,53 @@
using System;
-using System.Drawing;
using System.ComponentModel;
+using System.Drawing;
public class Sample
- {
+{
//
[TypeConverter(typeof(MyClassConverter))]
- public class MyClass {
+ public class MyClass
+ {
// Insert code here.
}
//
- public enum MyPropertyEnum {option1, option2, option3};
- public class MyClassConverter{
- }
-
+
+ public enum MyPropertyEnum { option1, option2, option3 };
+ public class MyClassConverter;
+
//
- public MyPropertyEnum MyProperty {
- set {
- // Checks to see if the value passed is valid.
- if (!TypeDescriptor.GetConverter(typeof(MyPropertyEnum)).IsValid(value)) {
- throw new ArgumentException();
- }
- // The value is valid. Insert code to set the property.
+ public MyPropertyEnum MyProperty
+ {
+ set
+ {
+ // Checks to see if the value passed is valid.
+ if (!TypeDescriptor.GetConverter(typeof(MyPropertyEnum)).IsValid(value))
+ {
+ throw new ArgumentException($"{nameof(MyProperty)} is not valid");
+ }
+ // The value is valid. Insert code to set the property.
}
- }
+ }
//
public void Method1()
{
//
Color c = Color.Red;
- Console.WriteLine(TypeDescriptor.GetConverter(typeof(Color)).ConvertToString(c));
+ Console.WriteLine(TypeDescriptor.GetConverter(typeof(Color)).ConvertToString(c));
//
}
- public void Method2()
- {
+ public Color Method2() =>
//
- Color c = (Color)TypeDescriptor.GetConverter(typeof(Color)).ConvertFromString("Red");
+ (Color)TypeDescriptor.GetConverter(typeof(Color)).ConvertFromString("Red");
//
- }
public void Method3()
{
//
- foreach(Color c in TypeDescriptor.GetConverter(typeof(Color)).GetStandardValues()) {
+ foreach (Color c in TypeDescriptor.GetConverter(typeof(Color)).GetStandardValues())
+ {
Console.WriteLine(TypeDescriptor.GetConverter(c).ConvertToString(c));
- }
+ }
//
}
}
diff --git a/snippets/csharp/System.ComponentModel/TypeConverterAttribute/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/TypeConverterAttribute/Overview/Project.csproj
index c02dc5044e7..5a1b02db677 100644
--- a/snippets/csharp/System.ComponentModel/TypeConverterAttribute/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/TypeConverterAttribute/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0
+ net8.0
\ No newline at end of file
diff --git a/snippets/csharp/System.ComponentModel/TypeConverterAttribute/Overview/source.cs b/snippets/csharp/System.ComponentModel/TypeConverterAttribute/Overview/source.cs
index e94a5280e61..37e32a42a8c 100644
--- a/snippets/csharp/System.ComponentModel/TypeConverterAttribute/Overview/source.cs
+++ b/snippets/csharp/System.ComponentModel/TypeConverterAttribute/Overview/source.cs
@@ -1,35 +1,35 @@
using System;
-using System.IO;
using System.ComponentModel;
-public class Class1{
+public static class Class1
+{
//
[TypeConverter(typeof(MyClassConverter))]
- public class MyClass {
+ public class MyClass
+ {
// Insert code here.
- }
+ }
//
- public class MyClassConverter:TypeConverter
- {
- }
+ public class MyClassConverter : TypeConverter;
//
- public static int Main() {
+ public static int Main()
+ {
// Creates a new instance of MyClass.
- MyClass myNewClass = new MyClass();
-
+ MyClass myNewClass = new();
+
// Gets the attributes for the instance.
AttributeCollection attributes = TypeDescriptor.GetAttributes(myNewClass);
-
+
/* Prints the name of the type converter by retrieving the
* TypeConverterAttribute from the AttributeCollection. */
- TypeConverterAttribute myAttribute =
+ TypeConverterAttribute myAttribute =
(TypeConverterAttribute)attributes[typeof(TypeConverterAttribute)];
-
- Console.WriteLine("The type conveter for this class is: " +
+
+ Console.WriteLine("The type conveter for this class is: " +
myAttribute.ConverterTypeName);
-
+
return 0;
- }
+ }
//
}
diff --git a/snippets/csharp/System.ComponentModel/TypeDescriptor/GetProperties/Form1.cs b/snippets/csharp/System.ComponentModel/TypeDescriptor/GetProperties/Form1.cs
index a5d701f2461..e51f9dd7922 100644
--- a/snippets/csharp/System.ComponentModel/TypeDescriptor/GetProperties/Form1.cs
+++ b/snippets/csharp/System.ComponentModel/TypeDescriptor/GetProperties/Form1.cs
@@ -4,34 +4,28 @@
using System.Collections;
using System.ComponentModel;
using System.ComponentModel.Design;
-using System.Diagnostics;
using System.Drawing;
using System.Drawing.Design;
-using System.Data;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.Design;
-using System.Windows.Forms.Design.Behavior;
//
public class Form1 : Form
{
- private DemoControl demoControl1;
+ DemoControl demoControl1;
- private System.ComponentModel.IContainer components = null;
+ readonly IContainer _components;
- public Form1()
- {
- InitializeComponent();
- }
+ public Form1() => InitializeComponent();
protected override void Dispose(bool disposing)
{
- if (disposing && (components != null))
+ if (disposing && (_components != null))
{
- components.Dispose();
+ _components.Dispose();
}
base.Dispose(disposing);
}
@@ -45,30 +39,30 @@ static void Main()
#region Windows Form Designer generated code
- private void InitializeComponent()
+ void InitializeComponent()
{
- this.demoControl1 = new DemoControl();
- this.SuspendLayout();
- //
- // demoControl1
- //
- this.demoControl1.AutoSize = true;
- this.demoControl1.BackColor = System.Drawing.Color.Chartreuse;
- this.demoControl1.Location = new System.Drawing.Point(0, 0);
- this.demoControl1.Name = "demoControl1";
- this.demoControl1.Size = new System.Drawing.Size(232, 14);
- this.demoControl1.TabIndex = 0;
- this.demoControl1.Text = "This text was set by CreateComponentsCore.";
- //
- // Form1
- //
- this.ClientSize = new System.Drawing.Size(492, 482);
- this.Controls.Add(this.demoControl1);
- this.Name = "Form1";
- this.Text = "r";
- this.ResumeLayout(false);
- this.PerformLayout();
- }
+ demoControl1 = new DemoControl();
+ SuspendLayout();
+ //
+ // demoControl1
+ //
+ demoControl1.AutoSize = true;
+ demoControl1.BackColor = Color.Chartreuse;
+ demoControl1.Location = new Point(0, 0);
+ demoControl1.Name = "demoControl1";
+ demoControl1.Size = new Size(232, 14);
+ demoControl1.TabIndex = 0;
+ demoControl1.Text = "This text was set by CreateComponentsCore.";
+ //
+ // Form1
+ //
+ ClientSize = new Size(492, 482);
+ Controls.Add(demoControl1);
+ Name = "Form1";
+ Text = "r";
+ ResumeLayout(false);
+ PerformLayout();
+ }
#endregion
@@ -82,77 +76,71 @@ private void InitializeComponent()
// DemoControlDesigner class.
//
-[DesignerAttribute(typeof(DemoControlDesigner))]
+[Designer(typeof(DemoControlDesigner))]
[ToolboxItem(typeof(DemoToolboxItem))]
public class DemoControl : Label
{
- //
+ //
- private System.ComponentModel.IContainer components = null;
+ readonly IContainer _components;
public DemoControl()
{
InitializeComponent();
- MessageBox.Show("DemoControl", "Constructor");
+ _ = MessageBox.Show("DemoControl", "Constructor");
}
protected override void Dispose(bool disposing)
{
- if (disposing && (components != null))
+ if (disposing && (_components != null))
{
- components.Dispose();
+ _components.Dispose();
}
base.Dispose(disposing);
}
- private void InitializeComponent()
- {
+ void InitializeComponent() =>
//
// DemoControl
//
- this.Name = "DemoControl";
- }
+ Name = "DemoControl";
+
+ //
+ // Toolbox items must be serializable.
+ [Serializable]
+ class DemoToolboxItem : ToolboxItem
+ {
+ // The add components dialog in VS looks for a public
+ // ctor that takes a type.
+ public DemoToolboxItem(Type toolType)
+ : base(toolType)
+ {
+ }
- //
- // Toolbox items must be serializable.
- [Serializable]
- class DemoToolboxItem : ToolboxItem
- {
- // The add components dialog in VS looks for a public
- // ctor that takes a type.
- public DemoToolboxItem(Type toolType)
- : base(toolType)
- {
- }
-
- // And you must provide this special constructor for serialization.
- // If you add additional data to MyToolboxItem that you
- // want to serialize, you may override Deserialize and
- // Serialize methods to add that data.
- DemoToolboxItem(SerializationInfo info, StreamingContext context)
- {
- Deserialize(info, context);
- }
-
- // This implementation sets the new control's Text and
- // AutoSize properties.
- protected override IComponent[] CreateComponentsCore(
- IDesignerHost host,
- IDictionary defaultValues)
- {
-
- IComponent[] comps = base.CreateComponentsCore(host, defaultValues);
-
- // The returned IComponent array contains a single
- // component, which is an instance of DemoControl.
- ((DemoControl)comps[0]).Text = "This text was set by CreateComponentsCore.";
- ((DemoControl)comps[0]).AutoSize = true;
-
- return comps;
- }
- }
- //
+ // And you must provide this special constructor for serialization.
+ // If you add additional data to MyToolboxItem that you
+ // want to serialize, you may override Deserialize and
+ // Serialize methods to add that data.
+ DemoToolboxItem(SerializationInfo info, StreamingContext context) => Deserialize(info, context);
+
+ // This implementation sets the new control's Text and
+ // AutoSize properties.
+ protected override IComponent[] CreateComponentsCore(
+ IDesignerHost host,
+ IDictionary defaultValues)
+ {
+ IComponent[] comps = base.CreateComponentsCore(host, defaultValues);
+
+ // The returned IComponent array contains a single
+ // component, which is an instance of DemoControl.
+ ((DemoControl)comps[0]).Text = "This text was set by CreateComponentsCore.";
+ ((DemoControl)comps[0]).AutoSize = true;
+
+ return comps;
+ }
+ }
+ //
}
//
@@ -161,39 +149,33 @@ protected override IComponent[] CreateComponentsCore(
// being designed.
public class DemoControlDesigner : ControlDesigner
{
- // This member backs the Locked property.
- private bool lockedValue = false;
-
// This is the collection of DesignerActionLists that
// defines the designer actions offered on the control.
- private DesignerActionListCollection actionLists = null;
+ DesignerActionListCollection actionLists;
// This Timer is created when you select the Create Timer
// designer action item.
- private Timer createdTimer = null;
+ Timer createdTimer;
//
// These are the services which DemoControlDesigner will use.
- private DesignerActionService actionService = null;
- private DesignerActionUIService actionUiService = null;
- private IComponentChangeService changeService = null;
- private IDesignerEventService eventService = null;
- private IDesignerHost host = null;
- private IDesignerOptionService optionService = null;
- private IEventBindingService eventBindingService = null;
- private IExtenderListService listService = null;
- private IReferenceService referenceService = null;
- private ISelectionService selectionService = null;
- private ITypeResolutionService typeResService = null;
- private IComponentDiscoveryService componentDiscoveryService = null;
- private IToolboxService toolboxService = null;
- private UndoEngine undoEng = null;
+ DesignerActionService actionService;
+ DesignerActionUIService actionUiService;
+ IComponentChangeService changeService;
+ IDesignerEventService eventService;
+ IDesignerHost host;
+ IDesignerOptionService optionService;
+ IEventBindingService eventBindingService;
+ IExtenderListService listService;
+ IReferenceService referenceService;
+ ISelectionService selectionService;
+ ITypeResolutionService typeResService;
+ IComponentDiscoveryService componentDiscoveryService;
+ IToolboxService toolboxService;
+ UndoEngine undoEng;
//
- public DemoControlDesigner()
- {
- MessageBox.Show("DemoControlDesigner", "Constructor");
- }
+ public DemoControlDesigner() => MessageBox.Show("DemoControlDesigner", "Constructor");
//
// The Dispose method override is implemented so event handlers
@@ -203,34 +185,34 @@ protected override void Dispose(bool disposing)
{
if (disposing)
{
- if (this.changeService != null)
+ if (changeService != null)
{
// Unhook event handlers.
- this.changeService.ComponentChanged -=
- new ComponentChangedEventHandler(
- ChangeService_ComponentChanged);
+ changeService.ComponentChanged -=
+
+ ChangeService_ComponentChanged;
+
+ changeService.ComponentAdded -=
- this.changeService.ComponentAdded -=
- new ComponentEventHandler(
- ChangeService_ComponentAdded);
+ ChangeService_ComponentAdded;
- this.changeService.ComponentRemoved -=
- new ComponentEventHandler(
- changeService_ComponentRemoved);
+ changeService.ComponentRemoved -=
+
+ changeService_ComponentRemoved;
}
- if (this.eventService != null)
+ if (eventService != null)
{
- this.eventService.ActiveDesignerChanged -=
- new ActiveDesignerEventHandler(
- eventService_ActiveDesignerChanged);
+ eventService.ActiveDesignerChanged -=
+
+ eventService_ActiveDesignerChanged;
}
- if (this.selectionService != null)
+ if (selectionService != null)
{
- this.selectionService.SelectionChanged -=
- new EventHandler(
- selectionService_SelectionChanged);
+ selectionService.SelectionChanged -=
+
+ selectionService_SelectionChanged;
}
}
@@ -249,142 +231,129 @@ public override void Initialize(IComponent component)
// Set up the BackColor value that will be serialized.
// This is the shadowed property on the designer.
- this.BackColor = Color.Chartreuse;
+ BackColor = Color.Chartreuse;
// Set up the BackColor value that will be displayed.
- this.Control.BackColor = Color.AliceBlue;
+ Control.BackColor = Color.AliceBlue;
}
//
//
// This method creates the DesignerActionList on demand, causing
// designer actions to appear on the control being designed.
- public override DesignerActionListCollection ActionLists
- {
- get
- {
- if (null == actionLists)
- {
- actionLists = new DesignerActionListCollection();
- actionLists.Add(
- new DemoActionList(this.Component));
- }
-
- return actionLists;
- }
- }
+ public override DesignerActionListCollection ActionLists => actionLists ??= [new DemoActionList(Component),];
//
//
// This utility method connects the designer to various
// services it will use.
- private void InitializeServices()
+ void InitializeServices()
{
// Acquire a reference to DesignerActionService.
- this.actionService =
+ actionService =
GetService(typeof(DesignerActionService))
as DesignerActionService;
- // Acquire a reference to DesignerActionUIService.
- this.actionUiService =
- GetService(typeof(DesignerActionUIService))
- as DesignerActionUIService;
+ // Acquire a reference to DesignerActionUIService.
+ actionUiService =
+ GetService(typeof(DesignerActionUIService))
+ as DesignerActionUIService;
// Acquire a reference to IComponentChangeService.
- this.changeService =
+ changeService =
GetService(typeof(IComponentChangeService))
as IComponentChangeService;
//
// Hook the IComponentChangeService events.
- if (this.changeService != null)
+ if (changeService != null)
{
- this.changeService.ComponentChanged +=
- new ComponentChangedEventHandler(
- ChangeService_ComponentChanged);
+ changeService.ComponentChanged +=
- this.changeService.ComponentAdded +=
- new ComponentEventHandler(
- ChangeService_ComponentAdded);
+ ChangeService_ComponentChanged;
- this.changeService.ComponentRemoved +=
- new ComponentEventHandler(
- changeService_ComponentRemoved);
+ changeService.ComponentAdded +=
+
+ ChangeService_ComponentAdded;
+
+ changeService.ComponentRemoved +=
+
+ changeService_ComponentRemoved;
}
//
// Acquire a reference to ISelectionService.
- this.selectionService =
+ selectionService =
GetService(typeof(ISelectionService))
as ISelectionService;
// Hook the SelectionChanged event.
- if (this.selectionService != null)
+ if (selectionService != null)
{
- this.selectionService.SelectionChanged +=
- new EventHandler(selectionService_SelectionChanged);
+ selectionService.SelectionChanged +=
+ selectionService_SelectionChanged;
}
// Acquire a reference to IDesignerEventService.
- this.eventService =
+ eventService =
GetService(typeof(IDesignerEventService))
as IDesignerEventService;
- if (this.eventService != null)
+ if (eventService != null)
{
- this.eventService.ActiveDesignerChanged +=
- new ActiveDesignerEventHandler(
- eventService_ActiveDesignerChanged);
+ eventService.ActiveDesignerChanged +=
+
+ eventService_ActiveDesignerChanged;
}
// Acquire a reference to IDesignerHost.
- this.host =
+ host =
GetService(typeof(IDesignerHost))
as IDesignerHost;
// Acquire a reference to IDesignerOptionService.
- this.optionService =
+ optionService =
GetService(typeof(IDesignerOptionService))
as IDesignerOptionService;
// Acquire a reference to IEventBindingService.
- this.eventBindingService =
+ eventBindingService =
GetService(typeof(IEventBindingService))
as IEventBindingService;
// Acquire a reference to IExtenderListService.
- this.listService =
+ listService =
GetService(typeof(IExtenderListService))
as IExtenderListService;
// Acquire a reference to IReferenceService.
- this.referenceService =
+ referenceService =
GetService(typeof(IReferenceService))
as IReferenceService;
// Acquire a reference to ITypeResolutionService.
- this.typeResService =
+ typeResService =
GetService(typeof(ITypeResolutionService))
as ITypeResolutionService;
// Acquire a reference to IComponentDiscoveryService.
- this.componentDiscoveryService =
+ componentDiscoveryService =
GetService(typeof(IComponentDiscoveryService))
as IComponentDiscoveryService;
// Acquire a reference to IToolboxService.
- this.toolboxService =
+ toolboxService =
GetService(typeof(IToolboxService))
as IToolboxService;
// Acquire a reference to UndoEngine.
- this.undoEng =
+ undoEng =
GetService(typeof(UndoEngine))
as UndoEngine;
- if (this.undoEng != null)
+ if (undoEng != null)
{
- MessageBox.Show("UndoEngine");
+ _ = MessageBox.Show("UndoEngine");
}
}
//
@@ -395,25 +364,22 @@ private void InitializeServices()
// value of the control's property.
public Color BackColor
{
- get
- {
- return (Color)ShadowProperties["BackColor"];
- }
+ get => (Color)ShadowProperties[nameof(BackColor)];
set
{
- if (this.changeService != null)
+ if (changeService != null)
{
PropertyDescriptor backColorDesc =
- TypeDescriptor.GetProperties(this.Control)["BackColor"];
+ TypeDescriptor.GetProperties(Control)["BackColor"];
- this.changeService.OnComponentChanging(
- this.Control,
+ changeService.OnComponentChanging(
+ Control,
backColorDesc);
- this.ShadowProperties["BackColor"] = value;
+ ShadowProperties[nameof(BackColor)] = value;
- this.changeService.OnComponentChanged(
- this.Control,
+ changeService.OnComponentChanged(
+ Control,
backColorDesc,
null,
null);
@@ -425,17 +391,7 @@ public Color BackColor
//
// This is the property added by the designer in the
// PreFilterProperties method.
- private bool Locked
- {
- get
- {
- return lockedValue;
- }
- set
- {
- lockedValue = value;
- }
- }
+ bool Locked { get; }
//
//
@@ -455,11 +411,10 @@ protected override void PreFilterProperties(IDictionary properties)
properties.Remove("Visible");
// Shadow the BackColor property.
- PropertyDescriptor propertyDesc = TypeDescriptor.CreateProperty(
+ properties["BackColor"] = TypeDescriptor.CreateProperty(
typeof(DemoControlDesigner),
(PropertyDescriptor)properties["BackColor"],
- new Attribute[0]);
- properties["BackColor"] = propertyDesc;
+ []);
// Create the Locked property.
properties["Locked"] = TypeDescriptor.CreateProperty(
@@ -491,9 +446,9 @@ protected override void PostFilterProperties(IDictionary properties)
pd = TypeDescriptor.CreateProperty(
pd.ComponentType,
pd,
- new Attribute[2] {
+ [
new BrowsableAttribute(false),
- new EditorBrowsableAttribute(EditorBrowsableState.Never)});
+ new EditorBrowsableAttribute(EditorBrowsableState.Never)]);
properties[pd.Name] = pd;
@@ -512,7 +467,7 @@ void eventService_ActiveDesignerChanged(
{
if (e.NewDesigner != null)
{
- MessageBox.Show(
+ _ = MessageBox.Show(
e.NewDesigner.ToString(),
"ActiveDesignerChanged");
}
@@ -523,41 +478,35 @@ void ChangeService_ComponentChanged(
object sender,
ComponentChangedEventArgs e)
{
- string msg = String.Format(
+ string msg = string.Format(
"{0}, {1}", e.Component, e.Member);
- MessageBox.Show(msg, "ComponentChanged");
+ _ = MessageBox.Show(msg, "ComponentChanged");
}
void ChangeService_ComponentAdded(
object sender,
- ComponentEventArgs e)
- {
- MessageBox.Show(
+ ComponentEventArgs e) => MessageBox.Show(
e.Component.ToString(),
"ComponentAdded");
- }
void changeService_ComponentRemoved(
object sender,
- ComponentEventArgs e)
- {
- MessageBox.Show(
+ ComponentEventArgs e) => MessageBox.Show(
e.Component.ToString(),
"ComponentRemoved");
- }
//
void selectionService_SelectionChanged(
object sender,
EventArgs e)
{
- if (this.selectionService != null)
+ if (selectionService != null)
{
- if (this.selectionService.PrimarySelection == this.Control)
+ if (selectionService.PrimarySelection == Control)
{
- MessageBox.Show(
- this.Control.ToString(),
+ _ = MessageBox.Show(
+ Control.ToString(),
"SelectionChanged");
}
}
@@ -570,30 +519,30 @@ void selectionService_SelectionChanged(
// This class defines the designer actions that appear on the control
// that is being designed.
internal class DemoActionList :
- System.ComponentModel.Design.DesignerActionList
+ DesignerActionList
{
// Cache a reference to the designer host.
- private IDesignerHost host = null;
+ readonly IDesignerHost host;
// Cache a reference to the control.
- private DemoControl relatedControl = null;
+ readonly DemoControl relatedControl;
// Cache a reference to the designer.
- private DemoControlDesigner relatedDesigner = null;
+ readonly DemoControlDesigner relatedDesigner;
//The constructor associates the control
//with the designer action list.
public DemoActionList(IComponent component)
: base(component)
{
- this.relatedControl = component as DemoControl;
+ relatedControl = component as DemoControl;
- this.host =
- this.Component.Site.GetService(typeof(IDesignerHost))
+ host =
+ Component.Site.GetService(typeof(IDesignerHost))
as IDesignerHost;
- IDesigner dcd = host.GetDesigner(this.Component);
- this.relatedDesigner = dcd as DemoControlDesigner;
+ IDesigner dcd = host.GetDesigner(Component);
+ relatedDesigner = dcd as DemoControlDesigner;
}
// This method creates and populates the
@@ -602,7 +551,7 @@ public DemoActionList(IComponent component)
public override DesignerActionItemCollection GetSortedActionItems()
{
DesignerActionItemCollection items =
- new DesignerActionItemCollection();
+ [];
// If the Timer component has not been created, show the
// "Create Timer" DesignerAction item.
@@ -610,60 +559,60 @@ public override DesignerActionItemCollection GetSortedActionItems()
// If the Timer component exists, show the timer-related
// options.
- if (this.relatedDesigner.createdTimer == null)
+ if (relatedDesigner.createdTimer == null)
{
- items.Add(new DesignerActionMethodItem(
+ _ = items.Add(new DesignerActionMethodItem(
this,
"CreateTimer",
"Create Timer",
true));
}
else
- {
- items.Add(new DesignerActionMethodItem(
+ {
+ _ = items.Add(new DesignerActionMethodItem(
this,
"ShowEventHandlerCode",
"Show Event Handler Code",
true));
- items.Add(new DesignerActionMethodItem(
+ _ = items.Add(new DesignerActionMethodItem(
this,
"RemoveTimer",
"Remove Timer",
true));
}
- items.Add(new DesignerActionMethodItem(
+ _ = items.Add(new DesignerActionMethodItem(
this,
"GetExtenderProviders",
"Get Extender Providers",
true));
- items.Add(new DesignerActionMethodItem(
+ _ = items.Add(new DesignerActionMethodItem(
this,
"GetDemoControlReferences",
"Get DemoControl References",
true));
- items.Add(new DesignerActionMethodItem(
+ _ = items.Add(new DesignerActionMethodItem(
this,
"GetPathOfAssembly",
"Get Path of Executing Assembly",
true));
- items.Add(new DesignerActionMethodItem(
+ _ = items.Add(new DesignerActionMethodItem(
this,
"GetComponentTypes",
"Get ScrollableControl Types",
true));
- items.Add(new DesignerActionMethodItem(
+ _ = items.Add(new DesignerActionMethodItem(
this,
"GetToolboxCategories",
"Get Toolbox Categories",
true));
- items.Add(new DesignerActionMethodItem(
+ _ = items.Add(new DesignerActionMethodItem(
this,
"SetBackColor",
"Set Back Color",
@@ -677,36 +626,34 @@ public override DesignerActionItemCollection GetSortedActionItems()
// IDesignerHost.CreateComponent method. It also
// creates an event handler for the Timer component's
// tick event.
- private void CreateTimer()
+ void CreateTimer()
{
- if (this.host != null)
+ if (host != null)
{
- if (this.relatedDesigner.createdTimer == null)
+ if (relatedDesigner.createdTimer == null)
{
// Create and configure the Timer object.
- this.relatedDesigner.createdTimer =
- this.host.CreateComponent(typeof(Timer)) as Timer;
- Timer t = this.relatedDesigner.createdTimer;
+ relatedDesigner.createdTimer =
+ host.CreateComponent(typeof(Timer)) as Timer;
+ Timer t = relatedDesigner.createdTimer;
t.Interval = 1000;
t.Enabled = true;
EventDescriptorCollection eventColl =
- TypeDescriptor.GetEvents(t, new Attribute[0]);
+ TypeDescriptor.GetEvents(t, []);
if (eventColl != null)
{
- EventDescriptor ed =
- eventColl["Tick"] as EventDescriptor;
- if (ed != null)
+ if (eventColl["Tick"] is EventDescriptor ed)
{
PropertyDescriptor epd =
- this.relatedDesigner.eventBindingService.GetEventProperty(ed);
+ relatedDesigner.eventBindingService.GetEventProperty(ed);
epd.SetValue(t, "timer_Tick");
}
}
- this.relatedDesigner.actionUiService.Refresh(this.relatedControl);
+ relatedDesigner.actionUiService.Refresh(relatedControl);
}
}
}
@@ -716,22 +663,17 @@ private void CreateTimer()
// This method uses the IEventBindingService.ShowCode
// method to start the Code Editor. It places the caret
// in the timer_tick method created by the CreateTimer method.
- private void ShowEventHandlerCode()
+ void ShowEventHandlerCode()
{
- Timer t = this.relatedDesigner.createdTimer;
+ Timer t = relatedDesigner.createdTimer;
if (t != null)
{
EventDescriptorCollection eventColl =
- TypeDescriptor.GetEvents(t, new Attribute[0]);
- if (eventColl != null)
+ TypeDescriptor.GetEvents(t, []);
+ if (eventColl != null && eventColl["Tick"] is EventDescriptor ed)
{
- EventDescriptor ed =
- eventColl["Tick"] as EventDescriptor;
- if (ed != null)
- {
- this.relatedDesigner.eventBindingService.ShowCode(t, ed);
- }
+ _ = relatedDesigner.eventBindingService.ShowCode(t, ed);
}
}
}
@@ -740,19 +682,19 @@ private void ShowEventHandlerCode()
//
// This method uses the IDesignerHost.DestroyComponent method
// to remove the Timer component from the design environment.
- private void RemoveTimer()
+ void RemoveTimer()
{
- if (this.host != null)
+ if (host != null)
{
- if (this.relatedDesigner.createdTimer != null)
+ if (relatedDesigner.createdTimer != null)
{
- this.host.DestroyComponent(
- this.relatedDesigner.createdTimer);
+ host.DestroyComponent(
+ relatedDesigner.createdTimer);
- this.relatedDesigner.createdTimer = null;
+ relatedDesigner.createdTimer = null;
- this.relatedDesigner.actionUiService.Refresh(
- this.relatedControl);
+ relatedDesigner.actionUiService.Refresh(
+ relatedControl);
}
}
}
@@ -762,23 +704,23 @@ private void RemoveTimer()
// This method uses IExtenderListService.GetExtenderProviders
// to enumerate all the extender providers and display them
// in a MessageBox.
- private void GetExtenderProviders()
+ void GetExtenderProviders()
{
- if (this.relatedDesigner.listService != null)
+ if (relatedDesigner.listService != null)
{
- StringBuilder sb = new StringBuilder();
+ StringBuilder sb = new();
IExtenderProvider[] providers =
- this.relatedDesigner.listService.GetExtenderProviders();
+ relatedDesigner.listService.GetExtenderProviders();
for (int i = 0; i < providers.Length; i++)
{
- sb.Append(providers[i].ToString());
- sb.Append("\r\n");
+ _ = sb.Append(providers[i].ToString());
+ _ = sb.Append("\r\n");
}
- MessageBox.Show(
- sb.ToString(),
+ _ = MessageBox.Show(
+ sb.ToString(),
"Extender Providers");
}
}
@@ -787,37 +729,37 @@ private void GetExtenderProviders()
// This method uses the IReferenceService.GetReferences method
// to enumerate all the instances of DemoControl on the
// design surface.
- private void GetDemoControlReferences()
+ void GetDemoControlReferences()
{
- if (this.relatedDesigner.referenceService != null)
+ if (relatedDesigner.referenceService != null)
{
- StringBuilder sb = new StringBuilder();
+ StringBuilder sb = new();
- object[] refs = this.relatedDesigner.referenceService.GetReferences(typeof(DemoControl));
+ object[] refs = relatedDesigner.referenceService.GetReferences(typeof(DemoControl));
for (int i = 0; i < refs.Length; i++)
{
- sb.Append(refs[i].ToString());
- sb.Append("\r\n");
+ _ = sb.Append(refs[i].ToString());
+ _ = sb.Append("\r\n");
}
- MessageBox.Show(
- sb.ToString(),
+ _ = MessageBox.Show(
+ sb.ToString(),
"DemoControl References");
}
}
// This method uses the ITypeResolutionService.GetPathOfAssembly
// method to display the path of the executing assembly.
- private void GetPathOfAssembly()
+ void GetPathOfAssembly()
{
- if (this.relatedDesigner.typeResService != null)
+ if (relatedDesigner.typeResService != null)
{
- System.Reflection.AssemblyName name =
- System.Reflection.Assembly.GetExecutingAssembly().GetName();
+ AssemblyName name =
+ Assembly.GetExecutingAssembly().GetName();
- MessageBox.Show(
- this.relatedDesigner.typeResService.GetPathOfAssembly(name),
+ _ = MessageBox.Show(
+ relatedDesigner.typeResService.GetPathOfAssembly(name),
"Path of executing assembly");
}
}
@@ -825,28 +767,28 @@ private void GetPathOfAssembly()
// This method uses the IComponentDiscoveryService.GetComponentTypes
// method to find all the types that derive from
// ScrollableControl.
- private void GetComponentTypes()
+ void GetComponentTypes()
{
- if (this.relatedDesigner.componentDiscoveryService != null)
+ if (relatedDesigner.componentDiscoveryService != null)
{
- ICollection components = this.relatedDesigner.componentDiscoveryService.GetComponentTypes(host, typeof(ScrollableControl));
+ ICollection components = relatedDesigner.componentDiscoveryService.GetComponentTypes(host, typeof(ScrollableControl));
if (components != null)
{
if (components.Count > 0)
{
- StringBuilder sb = new StringBuilder();
+ StringBuilder sb = new();
IEnumerator e = components.GetEnumerator();
while (e.MoveNext())
{
- sb.Append(e.Current.ToString());
- sb.Append("\r\n");
+ _ = sb.Append(e.Current.ToString());
+ _ = sb.Append("\r\n");
}
- MessageBox.Show(
- sb.ToString(),
+ _ = MessageBox.Show(
+ sb.ToString(),
"Controls derived from ScrollableControl");
}
}
@@ -856,33 +798,33 @@ private void GetComponentTypes()
// This method uses the IToolboxService.CategoryNames
// method to enumerate all the categories that appear
// in the Toolbox.
- private void GetToolboxCategories()
+ void GetToolboxCategories()
{
- if (this.relatedDesigner.toolboxService != null)
+ if (relatedDesigner.toolboxService != null)
{
- StringBuilder sb = new StringBuilder();
+ StringBuilder sb = new();
- CategoryNameCollection names = this.relatedDesigner.toolboxService.CategoryNames;
+ CategoryNameCollection names = relatedDesigner.toolboxService.CategoryNames;
foreach (string name in names)
{
- sb.Append(name.ToString());
- sb.Append("\r\n");
+ _ = sb.Append(name);
+ _ = sb.Append("\r\n");
}
- MessageBox.Show(sb.ToString(), "Toolbox Categories");
+ _ = MessageBox.Show(sb.ToString(), "Toolbox Categories");
}
}
// This method sets the shadowed BackColor property on the
// designer. This is the value that is serialized by the
// design environment.
- private void SetBackColor()
+ void SetBackColor()
{
- ColorDialog d = new ColorDialog();
+ ColorDialog d = new();
if (d.ShowDialog() == DialogResult.OK)
{
- this.relatedDesigner.BackColor = d.Color;
+ relatedDesigner.BackColor = d.Color;
}
}
}
diff --git a/snippets/csharp/System.ComponentModel/TypeDescriptor/GetProperties/Project.csproj b/snippets/csharp/System.ComponentModel/TypeDescriptor/GetProperties/Project.csproj
index a11815b79fb..8b6c102de54 100644
--- a/snippets/csharp/System.ComponentModel/TypeDescriptor/GetProperties/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/TypeDescriptor/GetProperties/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0-windows
+ net8.0-windows
true
diff --git a/snippets/csharp/System.ComponentModel/WarningException/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/WarningException/Overview/Project.csproj
index c02dc5044e7..5a1b02db677 100644
--- a/snippets/csharp/System.ComponentModel/WarningException/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/WarningException/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0
+ net8.0
\ No newline at end of file
diff --git a/snippets/csharp/System.ComponentModel/WarningException/Overview/warningex_doc.cs b/snippets/csharp/System.ComponentModel/WarningException/Overview/warningex_doc.cs
index 5c77dd49eb5..83ce43ca9c0 100644
--- a/snippets/csharp/System.ComponentModel/WarningException/Overview/warningex_doc.cs
+++ b/snippets/csharp/System.ComponentModel/WarningException/Overview/warningex_doc.cs
@@ -1,15 +1,16 @@
using System;
using System.ComponentModel;
-namespace WarningEx
+namespace WarningEx;
+
+public static class WarningEx_Doc
{
- public class WarningEx_Doc {
- static void Main(string[] args) {
- //
- WarningException myEx=new WarningException("This is a warning");
- Console.WriteLine(myEx.Message);
- Console.WriteLine(myEx.ToString());
- //
- }
+ static void Main()
+ {
+ //
+ WarningException myEx = new("This is a warning");
+ Console.WriteLine(myEx.Message);
+ Console.WriteLine(myEx.ToString());
+ //
}
}
diff --git a/snippets/csharp/System.ComponentModel/Win32Exception/Overview/Project.csproj b/snippets/csharp/System.ComponentModel/Win32Exception/Overview/Project.csproj
index c02dc5044e7..5a1b02db677 100644
--- a/snippets/csharp/System.ComponentModel/Win32Exception/Overview/Project.csproj
+++ b/snippets/csharp/System.ComponentModel/Win32Exception/Overview/Project.csproj
@@ -2,7 +2,7 @@
Library
- net6.0
+ net8.0
\ No newline at end of file
diff --git a/snippets/csharp/System.ComponentModel/Win32Exception/Overview/win32exception.cs b/snippets/csharp/System.ComponentModel/Win32Exception/Overview/win32exception.cs
index 4f3659c6b03..2ef04a94b90 100644
--- a/snippets/csharp/System.ComponentModel/Win32Exception/Overview/win32exception.cs
+++ b/snippets/csharp/System.ComponentModel/Win32Exception/Overview/win32exception.cs
@@ -3,16 +3,16 @@
namespace Win32Exception_CS;
-class Class1
+static class Class1
{
- static void Main(string[] args)
+ static void Main()
{
//
try
{
System.Diagnostics.Process myProc = new();
myProc.StartInfo.FileName = @"c:\nonexist.exe"; // Attempt to start a non-existent executable
- myProc.Start();
+ _ = myProc.Start();
}
catch (Win32Exception w)
{
diff --git a/xml/System.ComponentModel/DefaultValueAttribute.xml b/xml/System.ComponentModel/DefaultValueAttribute.xml
index 95fa05430b4..a865b544260 100644
--- a/xml/System.ComponentModel/DefaultValueAttribute.xml
+++ b/xml/System.ComponentModel/DefaultValueAttribute.xml
@@ -65,14 +65,13 @@
with any value. A member's default value is typically its initial value. A visual designer can use the default value to reset the member's value. Code generators can use the default values also to determine whether code should be generated for the member.
-> [!NOTE]
-> A will not cause a member to be automatically initialized with the attribute's value. You must set the initial value in your code.
-
- For more information, see [Attributes](/dotnet/standard/attributes/).
+You can create a with any value. A member's default value is typically its initial value. A visual designer can use the default value to reset the member's value. Code generators can use the default values also to determine whether code should be generated for the member.
+> [!NOTE]
+> A will not cause a member to be automatically initialized with the attribute's value. You must set the initial value in your code.
+For more information, see [Attributes](/dotnet/standard/attributes/).
## Examples
The following example sets the default value of `MyProperty` to `false`.
diff --git a/xml/System.ComponentModel/RecommendedAsConfigurableAttribute.xml b/xml/System.ComponentModel/RecommendedAsConfigurableAttribute.xml
index 0fccbb81118..ae78f5aeeda 100644
--- a/xml/System.ComponentModel/RecommendedAsConfigurableAttribute.xml
+++ b/xml/System.ComponentModel/RecommendedAsConfigurableAttribute.xml
@@ -60,43 +60,11 @@
Specifies that the property can be used as an application setting.
- set to `true` display when you expand the **ConfigurableProperties** line in the **Properties** window. A property that has no recommended setting or that is marked with set to `false` is not shown and is an unlikely candidate for being an application setting. The default is `false`.
-
- You can bind a property that does not have a to a setting in Visual Studio by clicking the ellipsis button (…) under **Settings** in the **Properties** window and selecting the appropriate property from the list.
-
-> [!NOTE]
-> When you mark a property with set to `true`, the value of this attribute is set to the constant member . For a property marked with set to value `false`, the value is . Therefore, when you want to check the value of this attribute in your code, you must specify the attribute as or .
-
- For more information, see [Attributes](/dotnet/standard/attributes/).
-
- .
-
-
-
-## Examples
- The following example marks a property as usable as an application setting.
-
- :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Winforms/Classic RecommendedAsConfigurableAttribute Example/CPP/source.cpp" id="Snippet1":::
- :::code language="csharp" source="~/snippets/csharp/System.ComponentModel/RecommendedAsConfigurableAttribute/Overview/source.cs" id="Snippet1":::
- :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Winforms/Classic RecommendedAsConfigurableAttribute Example/VB/source.vb" id="Snippet1":::
-
- The next example shows how to check the value of the for `MyProperty`. First the code gets a with all the properties for the object. Next it indexes into the to get `MyProperty`. Then it returns the attributes for this property and saves them in the attributes variable.
-
- This example presents two different ways of checking the value of the . In the second code fragment, the example calls the method. In the last code fragment, the example uses the property to check the value.
-
- :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Winforms/Classic RecommendedAsConfigurableAttribute Example/CPP/source.cpp" id="Snippet2":::
- :::code language="csharp" source="~/snippets/csharp/System.ComponentModel/RecommendedAsConfigurableAttribute/Overview/source.cs" id="Snippet2":::
- :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Winforms/Classic RecommendedAsConfigurableAttribute Example/VB/source.vb" id="Snippet2":::
-
- If you marked a class with the , use the following code to check the value.
-
- :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Winforms/Classic RecommendedAsConfigurableAttribute Example/CPP/source.cpp" id="Snippet3":::
- :::code language="csharp" source="~/snippets/csharp/System.ComponentModel/RecommendedAsConfigurableAttribute/Overview/source.cs" id="Snippet3":::
- :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Winforms/Classic RecommendedAsConfigurableAttribute Example/VB/source.vb" id="Snippet3":::
-
+ set to `true` display when you expand the **ConfigurableProperties** line in the **Properties** window. A property that has no recommended setting or that is marked with set to `false` is not shown and is an unlikely candidate for being an application setting. The default is `false`.
+
]]>
@@ -149,18 +117,7 @@
if the property this attribute is bound to can be used as an application setting; otherwise, .
Initializes a new instance of the class.
-
- , sets its value to , and binds it to the property.
-
- :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Winforms/Classic RecommendedAsConfigurableAttribute.RecommendedAsConfigurableAttribute Example/CPP/source.cpp" id="Snippet1":::
- :::code language="csharp" source="~/snippets/csharp/System.ComponentModel/RecommendedAsConfigurableAttribute/.ctor/source.cs" id="Snippet1":::
- :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Winforms/Classic RecommendedAsConfigurableAttribute.RecommendedAsConfigurableAttribute Example/VB/source.vb" id="Snippet1":::
-
- ]]>
-
+ To be added.
@@ -379,13 +336,13 @@
Specifies that a property cannot be used as an application setting. This field is read-only.
- set to `false`, the value of this attribute is set to the constant member . Therefore, when you want to check whether the attribute is set to this value in your code, you must specify the attribute .
-
+ set to `false`, the value of this attribute is set to the constant member . Therefore, when you want to check whether the attribute is set to this value in your code, you must specify the attribute .
+
]]>
@@ -436,26 +393,7 @@
Gets a value indicating whether the property this attribute is bound to can be used as an application setting.
if the property this attribute is bound to can be used as an application setting; otherwise, .
-
- with all the properties for the object.
-
-- Indexing into the to get `MyProperty`.
-
-- Saving the attributes for this property in the attributes variable.
-
- Then the code sets `myAttribute` to the value of the in the and checks whether the property is bindable.
-
- :::code language="cpp" source="~/snippets/cpp/VS_Snippets_Winforms/Classic RecommendedAsConfigurableAttribute.RecommendedAsConfigurable Example/CPP/source.cpp" id="Snippet1":::
- :::code language="csharp" source="~/snippets/csharp/System.ComponentModel/RecommendedAsConfigurableAttribute/RecommendedAsConfigurable/source.cs" id="Snippet1":::
- :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_Winforms/Classic RecommendedAsConfigurableAttribute.RecommendedAsConfigurable Example/VB/source.vb" id="Snippet1":::
-
- ]]>
-
+ To be added.
@@ -500,13 +438,13 @@
Specifies that a property can be used as an application setting. This field is read-only.
- set to `true`, the value of this attribute is set to the constant member .
-
- Therefore, when you want to check whether the attribute is set to this value in your code, you must specify the attribute as .
-
+ set to `true`, the value of this attribute is set to the constant member .
+
+ Therefore, when you want to check whether the attribute is set to this value in your code, you must specify the attribute as .
+
]]>