diff --git a/snippets/csharp/System.Messaging/MessageQueue/.ctor/Project.csproj b/snippets/csharp/System.Messaging/MessageQueue/.ctor/Project.csproj new file mode 100644 index 00000000000..cad0c10dc0d --- /dev/null +++ b/snippets/csharp/System.Messaging/MessageQueue/.ctor/Project.csproj @@ -0,0 +1,16 @@ + + + + Library + net481 + + + + + + + + + + + diff --git a/snippets/csharp/System.Messaging/MessageQueue/.ctor/class1.cs b/snippets/csharp/System.Messaging/MessageQueue/.ctor/class1.cs index 65fc5fdff40..444551d32e8 100644 --- a/snippets/csharp/System.Messaging/MessageQueue/.ctor/class1.cs +++ b/snippets/csharp/System.Messaging/MessageQueue/.ctor/class1.cs @@ -7,13 +7,10 @@ public class QueueExample { public static void Main() { - // Create a new instance of the class. - QueueExample example = new QueueExample(); - // Create a nontransactional queue on the local computer. CreateQueue(".\\exampleQueue", false); - example.UseQueue(); + UseQueue(); return; } @@ -21,7 +18,7 @@ public static void Main() // Create a new queue. public static void CreateQueue(string queuePath, bool transactional) { - if(!MessageQueue.Exists(queuePath)) + if (!MessageQueue.Exists(queuePath)) { MessageQueue.Create(queuePath, transactional); } @@ -31,7 +28,7 @@ public static void CreateQueue(string queuePath, bool transactional) } } - public void UseQueue() + public static void UseQueue() { // // Connect to a queue on the local computer. You must set the queue's diff --git a/snippets/csharp/System.Messaging/MessageQueue/.ctor/class11.cs b/snippets/csharp/System.Messaging/MessageQueue/.ctor/class11.cs index d3ed4a33de8..a2f4a652b28 100644 --- a/snippets/csharp/System.Messaging/MessageQueue/.ctor/class11.cs +++ b/snippets/csharp/System.Messaging/MessageQueue/.ctor/class11.cs @@ -3,17 +3,14 @@ using System; using System.Messaging; -public class QueueExample +public class QueueExample2 { public static void Main() { - // Create a new instance of the class. - QueueExample example = new QueueExample(); - // Create a nontransactional queue on the local computer. CreateQueue(".\\exampleQueue", false); - example.UseQueue(); + UseQueue(); return; } @@ -21,7 +18,7 @@ public static void Main() // Create a new queue. public static void CreateQueue(string queuePath, bool transactional) { - if(!MessageQueue.Exists(queuePath)) + if (!MessageQueue.Exists(queuePath)) { MessageQueue.Create(queuePath, transactional); } @@ -31,7 +28,7 @@ public static void CreateQueue(string queuePath, bool transactional) } } - public void UseQueue() + public static void UseQueue() { // // Connect to a queue on the local computer, grant exclusive read diff --git a/snippets/csharp/System.Messaging/MessageQueue/.ctor/mqctor_denysharedreceive.cs b/snippets/csharp/System.Messaging/MessageQueue/.ctor/mqctor_denysharedreceive.cs index 20997812cdd..132def40e22 100644 --- a/snippets/csharp/System.Messaging/MessageQueue/.ctor/mqctor_denysharedreceive.cs +++ b/snippets/csharp/System.Messaging/MessageQueue/.ctor/mqctor_denysharedreceive.cs @@ -9,7 +9,6 @@ namespace MyProject /// public class MyNewQueue { - //************************************************** // Provides an entry point into the application. // @@ -22,8 +21,8 @@ public static void Main() // Create a new instance of the class. MyNewQueue myNewQueue = new MyNewQueue(); - // Output the count of Lowest priority messages. - myNewQueue.GetExclusiveAccess(); + // Output the count of Lowest priority messages. + GetExclusiveAccess(); return; } @@ -34,7 +33,7 @@ public static void Main() // queue. //************************************************** - public void GetExclusiveAccess() + public static void GetExclusiveAccess() { try { @@ -65,4 +64,4 @@ public void GetExclusiveAccess() } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.Messaging/MessageQueue/BeginPeek/Project.csproj b/snippets/csharp/System.Messaging/MessageQueue/BeginPeek/Project.csproj new file mode 100644 index 00000000000..cad0c10dc0d --- /dev/null +++ b/snippets/csharp/System.Messaging/MessageQueue/BeginPeek/Project.csproj @@ -0,0 +1,16 @@ + + + + Library + net481 + + + + + + + + + + + diff --git a/snippets/csharp/System.Messaging/MessageQueue/BeginPeek/mqbeginpeek_noparms.cs b/snippets/csharp/System.Messaging/MessageQueue/BeginPeek/mqbeginpeek_noparms.cs index 410b055a98f..40ba9910c2a 100644 --- a/snippets/csharp/System.Messaging/MessageQueue/BeginPeek/mqbeginpeek_noparms.cs +++ b/snippets/csharp/System.Messaging/MessageQueue/BeginPeek/mqbeginpeek_noparms.cs @@ -4,60 +4,59 @@ namespace MyProject { - /// - /// Provides a container class for the example. - /// - public class MyNewQueue - { - - //************************************************** - // Provides an entry point into the application. - // - // This example performs asynchronous peek operation - // processing. - //************************************************** - - public static void Main() - { - // Create an instance of MessageQueue. Set its formatter. - MessageQueue myQueue = new MessageQueue(".\\myQueue"); - myQueue.Formatter = new XmlMessageFormatter(new Type[] - {typeof(String)}); - - // Add an event handler for the PeekCompleted event. - myQueue.PeekCompleted += new - PeekCompletedEventHandler(MyPeekCompleted); - - // Begin the asynchronous peek operation. - myQueue.BeginPeek(); - - // Do other work on the current thread. - - return; - } - - //************************************************** - // Provides an event handler for the PeekCompleted - // event. - //************************************************** - - private static void MyPeekCompleted(Object source, - PeekCompletedEventArgs asyncResult) - { - // Connect to the queue. - MessageQueue mq = (MessageQueue)source; - - // End the asynchronous peek operation. - Message m = mq.EndPeek(asyncResult.AsyncResult); - - // Display message information on the screen. - Console.WriteLine("Message: " + (string)m.Body); - - // Restart the asynchronous peek operation. - mq.BeginPeek(); - - return; - } - } + /// + /// Provides a container class for the example. + /// + public class MyNewQueue + { + //************************************************** + // Provides an entry point into the application. + // + // This example performs asynchronous peek operation + // processing. + //************************************************** + + public static void Main() + { + // Create an instance of MessageQueue. Set its formatter. + MessageQueue myQueue = new MessageQueue(".\\myQueue"); + myQueue.Formatter = new XmlMessageFormatter(new Type[] + {typeof(String)}); + + // Add an event handler for the PeekCompleted event. + myQueue.PeekCompleted += new + PeekCompletedEventHandler(MyPeekCompleted); + + // Begin the asynchronous peek operation. + myQueue.BeginPeek(); + + // Do other work on the current thread. + + return; + } + + //************************************************** + // Provides an event handler for the PeekCompleted + // event. + //************************************************** + + private static void MyPeekCompleted(Object source, + PeekCompletedEventArgs asyncResult) + { + // Connect to the queue. + MessageQueue mq = (MessageQueue)source; + + // End the asynchronous peek operation. + Message m = mq.EndPeek(asyncResult.AsyncResult); + + // Display message information on the screen. + Console.WriteLine("Message: " + (string)m.Body); + + // Restart the asynchronous peek operation. + mq.BeginPeek(); + + return; + } + } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.Messaging/MessageQueue/BeginPeek/mqbeginpeek_timeout.cs b/snippets/csharp/System.Messaging/MessageQueue/BeginPeek/mqbeginpeek_timeout.cs index 1c6cbcbc32b..c86b7a44920 100644 --- a/snippets/csharp/System.Messaging/MessageQueue/BeginPeek/mqbeginpeek_timeout.cs +++ b/snippets/csharp/System.Messaging/MessageQueue/BeginPeek/mqbeginpeek_timeout.cs @@ -4,78 +4,77 @@ namespace MyProject { - /// - /// Provides a container class for the example. - /// - public class MyNewQueue - { + /// + /// Provides a container class for the example. + /// + public class MyNewQueue2 + { + //************************************************** + // Provides an entry point into the application. + // + // This example performs asynchronous peek operation + // processing. + //************************************************** - //************************************************** - // Provides an entry point into the application. - // - // This example performs asynchronous peek operation - // processing. - //************************************************** + public static void Main() + { + // Create an instance of MessageQueue. Set its formatter. + MessageQueue myQueue = new MessageQueue(".\\myQueue"); + myQueue.Formatter = new XmlMessageFormatter(new Type[] + {typeof(String)}); - public static void Main() - { - // Create an instance of MessageQueue. Set its formatter. - MessageQueue myQueue = new MessageQueue(".\\myQueue"); - myQueue.Formatter = new XmlMessageFormatter(new Type[] - {typeof(String)}); + // Add an event handler for the PeekCompleted event. + myQueue.PeekCompleted += new + PeekCompletedEventHandler(MyPeekCompleted); - // Add an event handler for the PeekCompleted event. - myQueue.PeekCompleted += new - PeekCompletedEventHandler(MyPeekCompleted); - - // Begin the asynchronous peek operation with a time-out - // of one minute. - myQueue.BeginPeek(new TimeSpan(0,1,0)); - - // Do other work on the current thread. + // Begin the asynchronous peek operation with a time-out + // of one minute. + myQueue.BeginPeek(new TimeSpan(0, 1, 0)); - return; - } + // Do other work on the current thread. - //************************************************** - // Provides an event handler for the PeekCompleted - // event. - //************************************************** - - private static void MyPeekCompleted(Object source, - PeekCompletedEventArgs asyncResult) - { - try - { - // Connect to the queue. - MessageQueue mq = (MessageQueue)source; + return; + } - // End the asynchronous peek operation. - Message m = mq.EndPeek(asyncResult.AsyncResult); + //************************************************** + // Provides an event handler for the PeekCompleted + // event. + //************************************************** - // Display message information on the screen. - Console.WriteLine("Message: " + (string)m.Body); + private static void MyPeekCompleted(Object source, + PeekCompletedEventArgs asyncResult) + { + try + { + // Connect to the queue. + MessageQueue mq = (MessageQueue)source; - // Restart the asynchronous peek operation, with the - // same time-out. - mq.BeginPeek(new TimeSpan(0,1,0)); - } + // End the asynchronous peek operation. + Message m = mq.EndPeek(asyncResult.AsyncResult); - catch(MessageQueueException e) - { - if (e.MessageQueueErrorCode == - MessageQueueErrorCode.IOTimeout) - { - Console.WriteLine(e.ToString()); - } + // Display message information on the screen. + Console.WriteLine("Message: " + (string)m.Body); - // Handle other sources of MessageQueueException. - } - - // Handle other exceptions. - - return; - } - } + // Restart the asynchronous peek operation, with the + // same time-out. + mq.BeginPeek(new TimeSpan(0, 1, 0)); + } + + catch (MessageQueueException e) + { + if (e.MessageQueueErrorCode == + MessageQueueErrorCode.IOTimeout) + { + Console.WriteLine(e.ToString()); + } + + // Handle other sources of MessageQueueException. + } + + // Handle other exceptions. + + return; + } + } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.Messaging/MessageQueue/BeginPeek/mqbeginpeek_timeoutstateobject.cs b/snippets/csharp/System.Messaging/MessageQueue/BeginPeek/mqbeginpeek_timeoutstateobject.cs index 1fc08344aa9..5618bb1d9b3 100644 --- a/snippets/csharp/System.Messaging/MessageQueue/BeginPeek/mqbeginpeek_timeoutstateobject.cs +++ b/snippets/csharp/System.Messaging/MessageQueue/BeginPeek/mqbeginpeek_timeoutstateobject.cs @@ -4,83 +4,83 @@ namespace MyProject { - /// - /// Provides a container class for the example. - /// - public class MyNewQueue - { - // Represents a state object associated with each message. - static int messageNumber = 0; - - //************************************************** - // Provides an entry point into the application. - // - // This example performs asynchronous peek operation - // processing. - //************************************************** - - public static void Main() - { - // Create an instance of MessageQueue. Set its formatter. - MessageQueue myQueue = new MessageQueue(".\\myQueue"); - myQueue.Formatter = new XmlMessageFormatter(new Type[] - {typeof(String)}); - - // Add an event handler for the PeekCompleted event. - myQueue.PeekCompleted += new - PeekCompletedEventHandler(MyPeekCompleted); - - // Begin the asynchronous peek operation with a time-out - // of one minute. - myQueue.BeginPeek(new TimeSpan(0,1,0), messageNumber++); - - // Do other work on the current thread. - - return; - } - - //************************************************** - // Provides an event handler for the PeekCompleted - // event. - //************************************************** - - private static void MyPeekCompleted(Object source, - PeekCompletedEventArgs asyncResult) - { - try - { - // Connect to the queue. - MessageQueue mq = (MessageQueue)source; - - // End the asynchronous peek operation. - Message m = mq.EndPeek(asyncResult.AsyncResult); - - // Display message information on the screen, - // including the message number (state object). - Console.WriteLine("Message: " + - (int)asyncResult.AsyncResult.AsyncState + " " - +(string)m.Body); - - // Restart the asynchronous peek operation, with the - // same time-out. - mq.BeginPeek(new TimeSpan(0,1,0), messageNumber++); - } - - catch(MessageQueueException e) - { - if (e.MessageQueueErrorCode == - MessageQueueErrorCode.IOTimeout) - { - Console.WriteLine(e.ToString()); - } - - // Handle other sources of MessageQueueException. - } - - // Handle other exceptions. - - return; - } - } + /// + /// Provides a container class for the example. + /// + public class MyNewQueue3 + { + // Represents a state object associated with each message. + static int messageNumber = 0; + + //************************************************** + // Provides an entry point into the application. + // + // This example performs asynchronous peek operation + // processing. + //************************************************** + + public static void Main() + { + // Create an instance of MessageQueue. Set its formatter. + MessageQueue myQueue = new MessageQueue(".\\myQueue"); + myQueue.Formatter = new XmlMessageFormatter(new Type[] + {typeof(String)}); + + // Add an event handler for the PeekCompleted event. + myQueue.PeekCompleted += new + PeekCompletedEventHandler(MyPeekCompleted); + + // Begin the asynchronous peek operation with a time-out + // of one minute. + myQueue.BeginPeek(new TimeSpan(0, 1, 0), messageNumber++); + + // Do other work on the current thread. + + return; + } + + //************************************************** + // Provides an event handler for the PeekCompleted + // event. + //************************************************** + + private static void MyPeekCompleted(Object source, + PeekCompletedEventArgs asyncResult) + { + try + { + // Connect to the queue. + MessageQueue mq = (MessageQueue)source; + + // End the asynchronous peek operation. + Message m = mq.EndPeek(asyncResult.AsyncResult); + + // Display message information on the screen, + // including the message number (state object). + Console.WriteLine("Message: " + + (int)asyncResult.AsyncResult.AsyncState + " " + + (string)m.Body); + + // Restart the asynchronous peek operation, with the + // same time-out. + mq.BeginPeek(new TimeSpan(0, 1, 0), messageNumber++); + } + + catch (MessageQueueException e) + { + if (e.MessageQueueErrorCode == + MessageQueueErrorCode.IOTimeout) + { + Console.WriteLine(e.ToString()); + } + + // Handle other sources of MessageQueueException. + } + + // Handle other exceptions. + + return; + } + } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.Net.Sockets/MulticastOption/Overview/Project.csproj b/snippets/csharp/System.Net.Sockets/MulticastOption/Overview/Project.csproj new file mode 100644 index 00000000000..29255f5f4b1 --- /dev/null +++ b/snippets/csharp/System.Net.Sockets/MulticastOption/Overview/Project.csproj @@ -0,0 +1,9 @@ + + + + Library + net6.0 + + + + \ No newline at end of file diff --git a/snippets/csharp/System.Net.Sockets/MulticastOption/Overview/listener.cs b/snippets/csharp/System.Net.Sockets/MulticastOption/Overview/listener.cs index 1dc3c956b35..be7b546f6a6 100644 --- a/snippets/csharp/System.Net.Sockets/MulticastOption/Overview/listener.cs +++ b/snippets/csharp/System.Net.Sockets/MulticastOption/Overview/listener.cs @@ -29,110 +29,105 @@ // namespace Mssc.TransportProtocols.Utilities { + public class TestMulticastOption + { + private static IPAddress s_mcastAddress; + private static int s_mcastPort; + private static Socket s_mcastSocket; + private static MulticastOption s_mcastOption; - public class TestMulticastOption - { + // + private static void MulticastOptionProperties() + { + Console.WriteLine("Current multicast group is: " + s_mcastOption.Group); + Console.WriteLine("Current multicast local address is: " + s_mcastOption.LocalAddress); + } + // - private static IPAddress mcastAddress; - private static int mcastPort; - private static Socket mcastSocket; - private static MulticastOption mcastOption; + private static void StartMulticast() + { + try + { + s_mcastSocket = new Socket(AddressFamily.InterNetwork, + SocketType.Dgram, + ProtocolType.Udp); -// + Console.Write("Enter the local IP address: "); - private static void MulticastOptionProperties() - { - Console.WriteLine("Current multicast group is: " + mcastOption.Group); - Console.WriteLine("Current multicast local address is: " + mcastOption.LocalAddress); - } + IPAddress localIPAddr = IPAddress.Parse(Console.ReadLine()); -// + //IPAddress localIP = IPAddress.Any; + EndPoint localEP = (EndPoint)new IPEndPoint(localIPAddr, s_mcastPort); - private static void StartMulticast() - { - - try - { - mcastSocket = new Socket(AddressFamily.InterNetwork, - SocketType.Dgram, - ProtocolType.Udp); - - Console.Write("Enter the local IP address: "); - - IPAddress localIPAddr = IPAddress.Parse(Console.ReadLine()); - - //IPAddress localIP = IPAddress.Any; - EndPoint localEP = (EndPoint)new IPEndPoint(localIPAddr, mcastPort); - - mcastSocket.Bind(localEP); - -// - - // Define a MulticastOption object specifying the multicast group - // address and the local IPAddress. - // The multicast group address is the same as the address used by the server. - mcastOption = new MulticastOption(mcastAddress, localIPAddr); - - mcastSocket.SetSocketOption(SocketOptionLevel.IP, - SocketOptionName.AddMembership, - mcastOption); -// - } - - catch (Exception e) - { - Console.WriteLine(e.ToString()); - } - } + s_mcastSocket.Bind(localEP); - private static void ReceiveBroadcastMessages() - { - bool done = false; - byte[] bytes = new Byte[100]; - IPEndPoint groupEP = new IPEndPoint(mcastAddress, mcastPort); - EndPoint remoteEP = (EndPoint) new IPEndPoint(IPAddress.Any,0); - - try - { - while (!done) - { - Console.WriteLine("Waiting for multicast packets......."); - Console.WriteLine("Enter ^C to terminate."); + // - mcastSocket.ReceiveFrom(bytes, ref remoteEP); + // Define a MulticastOption object specifying the multicast group + // address and the local IPAddress. + // The multicast group address is the same as the address used by the server. + s_mcastOption = new MulticastOption(s_mcastAddress, localIPAddr); - Console.WriteLine("Received broadcast from {0} :\n {1}\n", - groupEP.ToString(), - Encoding.ASCII.GetString(bytes,0,bytes.Length)); - } + s_mcastSocket.SetSocketOption(SocketOptionLevel.IP, + SocketOptionName.AddMembership, + s_mcastOption); + // + } - mcastSocket.Close(); - } + catch (Exception e) + { + Console.WriteLine(e.ToString()); + } + } - catch (Exception e) - { - Console.WriteLine(e.ToString()); - } - } + private static void ReceiveBroadcastMessages() + { + bool done = false; + byte[] bytes = new byte[100]; + IPEndPoint groupEP = new(s_mcastAddress, s_mcastPort); + EndPoint remoteEP = (EndPoint)new IPEndPoint(IPAddress.Any, 0); + + try + { + while (!done) + { + Console.WriteLine("Waiting for multicast packets......."); + Console.WriteLine("Enter ^C to terminate."); + + s_mcastSocket.ReceiveFrom(bytes, ref remoteEP); + + Console.WriteLine("Received broadcast from {0} :\n {1}\n", + groupEP.ToString(), + Encoding.ASCII.GetString(bytes, 0, bytes.Length)); + } + + s_mcastSocket.Close(); + } + + catch (Exception e) + { + Console.WriteLine(e.ToString()); + } + } - public static void Main(String[] args) - { - // Initialize the multicast address group and multicast port. - // Both address and port are selected from the allowed sets as - // defined in the related RFC documents. These are the same - // as the values used by the sender. - mcastAddress = IPAddress.Parse("224.168.100.2"); - mcastPort = 11000; + public static void Main(string[] args) + { + // Initialize the multicast address group and multicast port. + // Both address and port are selected from the allowed sets as + // defined in the related RFC documents. These are the same + // as the values used by the sender. + s_mcastAddress = IPAddress.Parse("224.168.100.2"); + s_mcastPort = 11000; - // Start a multicast group. - StartMulticast(); + // Start a multicast group. + StartMulticast(); - // Display MulticastOption properties. - MulticastOptionProperties(); + // Display MulticastOption properties. + MulticastOptionProperties(); - // Receive broadcast messages. - ReceiveBroadcastMessages(); + // Receive broadcast messages. + ReceiveBroadcastMessages(); + } } - } } // diff --git a/snippets/csharp/System.Net.Sockets/MulticastOption/Overview/sender.cs b/snippets/csharp/System.Net.Sockets/MulticastOption/Overview/sender.cs index 8197a846fe4..27c9caca76c 100644 --- a/snippets/csharp/System.Net.Sockets/MulticastOption/Overview/sender.cs +++ b/snippets/csharp/System.Net.Sockets/MulticastOption/Overview/sender.cs @@ -4,7 +4,6 @@ // // - using System; using System.Net.Sockets; using System.Net; @@ -19,83 +18,82 @@ // namespace Mssc.TransportProtocols.Utilities { - class TestMulticastOption - { + class TestMulticastOption2 + { + static IPAddress s_mcastAddress; + static int s_mcastPort; + static Socket s_mcastSocket; - static IPAddress mcastAddress; - static int mcastPort; - static Socket mcastSocket; + static void JoinMulticastGroup() + { + try + { + // Create a multicast socket. + s_mcastSocket = new Socket(AddressFamily.InterNetwork, + SocketType.Dgram, + ProtocolType.Udp); - static void JoinMulticastGroup() - { - try - { - // Create a multicast socket. - mcastSocket = new Socket(AddressFamily.InterNetwork, - SocketType.Dgram, - ProtocolType.Udp); - - // Get the local IP address used by the listener and the sender to - // exchange multicast messages. - Console.Write("\nEnter local IPAddress for sending multicast packets: "); - IPAddress localIPAddr = IPAddress.Parse(Console.ReadLine()); + // Get the local IP address used by the listener and the sender to + // exchange multicast messages. + Console.Write("\nEnter local IPAddress for sending multicast packets: "); + IPAddress localIPAddr = IPAddress.Parse(Console.ReadLine()); - // Create an IPEndPoint object. - IPEndPoint IPlocal = new IPEndPoint(localIPAddr, 0); + // Create an IPEndPoint object. + IPEndPoint IPlocal = new IPEndPoint(localIPAddr, 0); - // Bind this endpoint to the multicast socket. - mcastSocket.Bind(IPlocal); + // Bind this endpoint to the multicast socket. + s_mcastSocket.Bind(IPlocal); - // Define a MulticastOption object specifying the multicast group - // address and the local IP address. - // The multicast group address is the same as the address used by the listener. - MulticastOption mcastOption; - mcastOption = new MulticastOption(mcastAddress, localIPAddr); + // Define a MulticastOption object specifying the multicast group + // address and the local IP address. + // The multicast group address is the same as the address used by the listener. + MulticastOption mcastOption; + mcastOption = new MulticastOption(s_mcastAddress, localIPAddr); - mcastSocket.SetSocketOption(SocketOptionLevel.IP, - SocketOptionName.AddMembership, - mcastOption); - } - catch (Exception e) - { - Console.WriteLine("\n" + e.ToString()); - } - } + s_mcastSocket.SetSocketOption(SocketOptionLevel.IP, + SocketOptionName.AddMembership, + mcastOption); + } + catch (Exception e) + { + Console.WriteLine("\n" + e.ToString()); + } + } - static void BroadcastMessage(string message) - { - IPEndPoint endPoint; + static void BroadcastMessage(string message) + { + IPEndPoint endPoint; - try - { - //Send multicast packets to the listener. - endPoint = new IPEndPoint(mcastAddress,mcastPort); - mcastSocket.SendTo(ASCIIEncoding.ASCII.GetBytes(message), endPoint); - Console.WriteLine("Multicast data sent....."); - } - catch (Exception e) - { - Console.WriteLine("\n" + e.ToString()); - } + try + { + //Send multicast packets to the listener. + endPoint = new IPEndPoint(s_mcastAddress, s_mcastPort); + s_mcastSocket.SendTo(ASCIIEncoding.ASCII.GetBytes(message), endPoint); + Console.WriteLine("Multicast data sent....."); + } + catch (Exception e) + { + Console.WriteLine("\n" + e.ToString()); + } - mcastSocket.Close(); - } + s_mcastSocket.Close(); + } - static void Main(string[] args) - { - // Initialize the multicast address group and multicast port. - // Both address and port are selected from the allowed sets as - // defined in the related RFC documents. These are the same - // as the values used by the sender. - mcastAddress = IPAddress.Parse("224.168.100.2"); - mcastPort = 11000; + static void Main(string[] args) + { + // Initialize the multicast address group and multicast port. + // Both address and port are selected from the allowed sets as + // defined in the related RFC documents. These are the same + // as the values used by the sender. + s_mcastAddress = IPAddress.Parse("224.168.100.2"); + s_mcastPort = 11000; - // Join the listener multicast group. - JoinMulticastGroup(); + // Join the listener multicast group. + JoinMulticastGroup(); - // Broadcast the message to the listener. - BroadcastMessage("Hello multicast listener."); + // Broadcast the message to the listener. + BroadcastMessage("Hello multicast listener."); + } } - } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.Reflection.Emit/EnumBuilder/GetCustomAttributes/Project.csproj b/snippets/csharp/System.Reflection.Emit/EnumBuilder/GetCustomAttributes/Project.csproj new file mode 100644 index 00000000000..048f23337c7 --- /dev/null +++ b/snippets/csharp/System.Reflection.Emit/EnumBuilder/GetCustomAttributes/Project.csproj @@ -0,0 +1,9 @@ + + + + Library + net481 + + + + \ No newline at end of file diff --git a/snippets/csharp/System.Reflection.Emit/EnumBuilder/GetCustomAttributes/enumbuilder_setcustomattribute2.cs b/snippets/csharp/System.Reflection.Emit/EnumBuilder/GetCustomAttributes/enumbuilder_setcustomattribute2.cs index 3a79266dacf..d554243b842 100644 --- a/snippets/csharp/System.Reflection.Emit/EnumBuilder/GetCustomAttributes/enumbuilder_setcustomattribute2.cs +++ b/snippets/csharp/System.Reflection.Emit/EnumBuilder/GetCustomAttributes/enumbuilder_setcustomattribute2.cs @@ -4,9 +4,9 @@ /* The following program demonstrates 'GetCustomAttributes(bool)' and 'SetCustomAttribute(ConstructorInfo, byte[])' methods of - 'System.Reflection.Emit.EnumBuilder' class. It defines 'MyAttribute' + 'System.Reflection.Emit.EnumBuilder' class. It defines 'MyAttribute2' class which is derived from 'System.Attribute' class. It builds an - Enum and sets 'MyAttribute' as custom attribute to the Enum. + Enum and sets 'MyAttribute2' as custom attribute to the Enum. It gets the custom attributes of the Enum type and displays its contents on the console. */ @@ -19,17 +19,17 @@ on the console. using System.Reflection.Emit; [AttributeUsage(AttributeTargets.All, AllowMultiple = false)] -public class MyAttribute : Attribute +public class MyAttribute2 : Attribute { public bool myBoolValue; - public MyAttribute(bool myBool) + public MyAttribute2(bool myBool) { this.myBoolValue = myBool; } } -class MyApplication +class MyApplication2 { static EnumBuilder myEnumBuilder; @@ -44,10 +44,10 @@ public static void Main() Console.WriteLine("Custom attribute contains: "); for(int index=0; index < myAttributesArray.Length; index++) { - if(myAttributesArray[index] is MyAttribute) + if(myAttributesArray[index] is MyAttribute2) { Console.WriteLine("myBoolValue: " + - ((MyAttribute)myAttributesArray[index]).myBoolValue); + ((MyAttribute2)myAttributesArray[index]).myBoolValue); } } } @@ -67,7 +67,7 @@ private static void CreateCallee(AppDomain domain) AssemblyBuilder myAssemblyBuilder = domain.DefineDynamicAssembly(myAssemblyName, AssemblyBuilderAccess.Run); - Type myType = typeof(MyAttribute); + Type myType = typeof(MyAttribute2); ConstructorInfo myInfo = myType.GetConstructor(new Type[]{typeof(bool)}); // Create a dynamic module. @@ -85,4 +85,4 @@ AssemblyBuilder myAssemblyBuilder } } // -// \ No newline at end of file +// diff --git a/snippets/csharp/System.Runtime.InteropServices/ComImportAttribute/Overview/Project.csproj b/snippets/csharp/System.Runtime.InteropServices/ComImportAttribute/Overview/Project.csproj new file mode 100644 index 00000000000..29255f5f4b1 --- /dev/null +++ b/snippets/csharp/System.Runtime.InteropServices/ComImportAttribute/Overview/Project.csproj @@ -0,0 +1,9 @@ + + + + Library + net6.0 + + + + \ No newline at end of file diff --git a/snippets/csharp/System.Runtime.InteropServices/ComImportAttribute/Overview/codefile1.cs b/snippets/csharp/System.Runtime.InteropServices/ComImportAttribute/Overview/codefile1.cs deleted file mode 100644 index b96eefffb18..00000000000 --- a/snippets/csharp/System.Runtime.InteropServices/ComImportAttribute/Overview/codefile1.cs +++ /dev/null @@ -1,19 +0,0 @@ -//System.Runtime.InteropServices.IDispatchImplAttribute -//System.Runtime.InteropServices.IDispatchImplType -// -using System; -using System.Runtime.InteropServices; -// by default all classes in this assembly will use COM implementaion -[assembly:IDispatchImpl(IDispatchImplType.CompatibleImpl)] - -namespace MyNamespace -{ - // But this class will use runtime implementaion - [IDispatchImpl(IDispatchImplType.InternalImpl)] - class MyClass - { - // - } -} - -// diff --git a/snippets/csharp/System.Runtime.InteropServices/ComImportAttribute/Overview/codefile2.cs b/snippets/csharp/System.Runtime.InteropServices/ComImportAttribute/Overview/codefile2.cs index f873b69276d..0140be62a19 100644 --- a/snippets/csharp/System.Runtime.InteropServices/ComImportAttribute/Overview/codefile2.cs +++ b/snippets/csharp/System.Runtime.InteropServices/ComImportAttribute/Overview/codefile2.cs @@ -10,54 +10,54 @@ namespace MyModule { - // If you do not have a type library for an interface - // you can redeclare it using ComImportAttribute. - - // This is how the interface would look in an idl file. - - //[ - //object, - //uuid("73EB4AF8-BE9C-4b49-B3A4-24F4FF657B26"), - //dual, helpstring("IMyStorage Interface"), - //pointer_default(unique) - //] - //interface IMyStorage : IDispatch - //{ - // [id(1)] - // HRESULT GetItem([in] BSTR bstrName, [out, retval] IDispatch ** ppItem); - // [id(2)] - // HRESULT GetItems([in] BSTR bstrLocation, [out] SAFEARRAY(VARIANT)* pItems); - // [id(3)] - // HRESULT GetItemDescriptions([in] BSTR bstrLocation, [out] SAFEARRAY(VARIANT) ** ppItems); - // [id(4), propget] - // HRESULT get_IsEmpty([out, retval] BOOL * pfEmpty); - //}; - - // This is the managed declaration. - - [ComImport] - [Guid("73EB4AF8-BE9C-4b49-B3A4-24F4FF657B26")] - public interface IMyStorage - { - [DispId(1)] - [return : MarshalAs( UnmanagedType.Interface )] - Object GetItem( [In, MarshalAs( UnmanagedType.BStr )] String bstrName ); - - [DispId(2)] - void GetItems( [In, MarshalAs( UnmanagedType.BStr )] String bstrLocation, - [Out, MarshalAs( UnmanagedType.SafeArray, - SafeArraySubType = VarEnum.VT_VARIANT )] out Object[] Items ); - - [DispId(3)] - void GetItemDescriptions( [In] String bstrLocation, - [In, Out, MarshalAs( UnmanagedType.SafeArray )] ref Object[] varDescriptions ); - - bool IsEmpty - { - [DispId(4)] - [return : MarshalAs( UnmanagedType.VariantBool )] - get; - } - } + // If you do not have a type library for an interface + // you can redeclare it using ComImportAttribute. + + // This is how the interface would look in an idl file. + + //[ + //object, + //uuid("73EB4AF8-BE9C-4b49-B3A4-24F4FF657B26"), + //dual, helpstring("IMyStorage Interface"), + //pointer_default(unique) + //] + //interface IMyStorage : IDispatch + //{ + // [id(1)] + // HRESULT GetItem([in] BSTR bstrName, [out, retval] IDispatch ** ppItem); + // [id(2)] + // HRESULT GetItems([in] BSTR bstrLocation, [out] SAFEARRAY(VARIANT)* pItems); + // [id(3)] + // HRESULT GetItemDescriptions([in] BSTR bstrLocation, [out] SAFEARRAY(VARIANT) ** ppItems); + // [id(4), propget] + // HRESULT get_IsEmpty([out, retval] BOOL * pfEmpty); + //}; + + // This is the managed declaration. + + [ComImport] + [Guid("73EB4AF8-BE9C-4b49-B3A4-24F4FF657B26")] + public interface IMyStorage + { + [DispId(1)] + [return: MarshalAs(UnmanagedType.Interface)] + object GetItem([In, MarshalAs(UnmanagedType.BStr)] String bstrName); + + [DispId(2)] + void GetItems([In, MarshalAs(UnmanagedType.BStr)] String bstrLocation, + [Out, MarshalAs( UnmanagedType.SafeArray, + SafeArraySubType = VarEnum.VT_VARIANT )] out Object[] Items); + + [DispId(3)] + void GetItemDescriptions([In] String bstrLocation, + [In, Out, MarshalAs(UnmanagedType.SafeArray)] ref Object[] varDescriptions); + + bool IsEmpty + { + [DispId(4)] + [return: MarshalAs(UnmanagedType.VariantBool)] + get; + } + } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.Runtime.InteropServices/ComImportAttribute/Overview/codefile3.cs b/snippets/csharp/System.Runtime.InteropServices/ComImportAttribute/Overview/codefile3.cs index d89100b5451..75e39c8417c 100644 --- a/snippets/csharp/System.Runtime.InteropServices/ComImportAttribute/Overview/codefile3.cs +++ b/snippets/csharp/System.Runtime.InteropServices/ComImportAttribute/Overview/codefile3.cs @@ -7,25 +7,25 @@ namespace A { - class ClassA - { - public static bool IsCOMAssembly( Assembly a ) - { - object[] AsmAttributes = a.GetCustomAttributes( typeof( ImportedFromTypeLibAttribute ), true ); - if( AsmAttributes.Length > 0 ) - { - ImportedFromTypeLibAttribute imptlb = ( ImportedFromTypeLibAttribute )AsmAttributes[0]; - string strImportedFrom = imptlb.Value; - - // Print out the name of the DLL from which the assembly is imported. - Console.WriteLine( "Assembly " + a.FullName + " is imported from " + strImportedFrom ); - - return true; - } - // This is not a COM assembly. - Console.WriteLine( "Assembly " + a.FullName + " is not imported from COM" ); - return false; - } - } + class ClassA + { + public static bool IsCOMAssembly(Assembly a) + { + object[] AsmAttributes = a.GetCustomAttributes(typeof(ImportedFromTypeLibAttribute), true); + if (AsmAttributes.Length > 0) + { + ImportedFromTypeLibAttribute imptlb = (ImportedFromTypeLibAttribute)AsmAttributes[0]; + string strImportedFrom = imptlb.Value; + + // Print out the name of the DLL from which the assembly is imported. + Console.WriteLine("Assembly " + a.FullName + " is imported from " + strImportedFrom); + + return true; + } + // This is not a COM assembly. + Console.WriteLine("Assembly " + a.FullName + " is not imported from COM"); + return false; + } + } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.Runtime.InteropServices/ComImportAttribute/Overview/codefile4.cs b/snippets/csharp/System.Runtime.InteropServices/ComImportAttribute/Overview/codefile4.cs index 0c1dfb9ea7e..661242b0085 100644 --- a/snippets/csharp/System.Runtime.InteropServices/ComImportAttribute/Overview/codefile4.cs +++ b/snippets/csharp/System.Runtime.InteropServices/ComImportAttribute/Overview/codefile4.cs @@ -6,19 +6,19 @@ namespace B { - class ClassB - { - public static bool IsHiddenInterface( Type InterfaceType ) - { - object[] InterfaceAttributes = InterfaceType.GetCustomAttributes( typeof( TypeLibTypeAttribute ), false ); - if( InterfaceAttributes.Length > 0 ) - { - TypeLibTypeAttribute tlt = ( TypeLibTypeAttribute ) InterfaceAttributes[0]; - TypeLibTypeFlags flags = tlt.Value; - return ( flags & TypeLibTypeFlags.FHidden ) != 0; - } - return false; - } - } + class ClassB + { + public static bool IsHiddenInterface(Type InterfaceType) + { + object[] InterfaceAttributes = InterfaceType.GetCustomAttributes(typeof(TypeLibTypeAttribute), false); + if (InterfaceAttributes.Length > 0) + { + TypeLibTypeAttribute tlt = (TypeLibTypeAttribute)InterfaceAttributes[0]; + TypeLibTypeFlags flags = tlt.Value; + return (flags & TypeLibTypeFlags.FHidden) != 0; + } + return false; + } + } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.Runtime.InteropServices/ComImportAttribute/Overview/codefile5.cs b/snippets/csharp/System.Runtime.InteropServices/ComImportAttribute/Overview/codefile5.cs index 30a5b9b8f8a..9ceaf8dbf4c 100644 --- a/snippets/csharp/System.Runtime.InteropServices/ComImportAttribute/Overview/codefile5.cs +++ b/snippets/csharp/System.Runtime.InteropServices/ComImportAttribute/Overview/codefile5.cs @@ -2,26 +2,25 @@ // System.Runtime.InteropServices.TypeLibFuncFlags // -using System; using System.Reflection; using System.Runtime.InteropServices; namespace C { - class ClassC - { - public static bool IsHiddenMethod( MethodInfo mi ) - { - object[] MethodAttributes = mi.GetCustomAttributes( typeof( TypeLibFuncAttribute ), true); - - if( MethodAttributes.Length > 0 ) - { - TypeLibFuncAttribute tlf = ( TypeLibFuncAttribute )MethodAttributes[0]; - TypeLibFuncFlags flags = tlf.Value; - return ( flags & TypeLibFuncFlags.FHidden ) != 0; - } - return false; - } - } + class ClassC + { + public static bool IsHiddenMethod(MethodInfo mi) + { + object[] MethodAttributes = mi.GetCustomAttributes(typeof(TypeLibFuncAttribute), true); + + if (MethodAttributes.Length > 0) + { + TypeLibFuncAttribute tlf = (TypeLibFuncAttribute)MethodAttributes[0]; + TypeLibFuncFlags flags = tlf.Value; + return (flags & TypeLibFuncFlags.FHidden) != 0; + } + return false; + } + } } // diff --git a/snippets/csharp/System.Runtime.InteropServices/Marshal/GetActiveObject/Project.csproj b/snippets/csharp/System.Runtime.InteropServices/Marshal/GetActiveObject/Project.csproj new file mode 100644 index 00000000000..048f23337c7 --- /dev/null +++ b/snippets/csharp/System.Runtime.InteropServices/Marshal/GetActiveObject/Project.csproj @@ -0,0 +1,9 @@ + + + + Library + net481 + + + + \ No newline at end of file diff --git a/snippets/csharp/System.Security.Cryptography/AsymmetricKeyExchangeDeformatter/Overview/ContosoEncryption.cs b/snippets/csharp/System.Security.Cryptography/AsymmetricKeyExchangeDeformatter/Overview/ContosoEncryption.cs deleted file mode 100644 index a172454b594..00000000000 --- a/snippets/csharp/System.Security.Cryptography/AsymmetricKeyExchangeDeformatter/Overview/ContosoEncryption.cs +++ /dev/null @@ -1,43 +0,0 @@ -// This sample demonstrates how to encrypt and decrypt messages using the -// ContosoFormatter and ContosoDeformatter classes. These classes extend -// AsymmetricKeyExchangeFormatter and AsymmetricKeyExchangeDeformatter classes -// respectfully and can be found in their class reference. -// - -using System; -using System.Security.Cryptography; - -namespace Contoso -{ - class ContosoEncryption - { - [STAThread] - static void Main(string[] args) - { - string dataToEncrypt = "Sample Contoso encryption application."; - Console.WriteLine("Data to encrypt : " + dataToEncrypt); - - // Create a public key for encryption/decryption efforts. - RSA rsa = RSA.Create(); - - // Encrypt the data and display the result to the console. - ContosoFormatter formatter = new ContosoFormatter(rsa); - byte[] encryptedData = formatter.CreateKeyExchange( - System.Text.Encoding.ASCII.GetBytes(dataToEncrypt)); - Console.WriteLine("Encrypted data: " + - System.Text.Encoding.ASCII.GetString(encryptedData)); - - // Decrypt the data and display the result to the console. - ContosoDeformatter deformatter = new ContosoDeformatter(rsa); - byte[] decryptedData = - deformatter.DecryptKeyExchange(encryptedData); - Console.WriteLine("Data decrypted : " + - System.Text.Encoding.ASCII.GetString(decryptedData)); - - Console.WriteLine("This sample completed successfully; " + - "press Enter to exit."); - Console.ReadLine(); - } - } -} -// \ No newline at end of file diff --git a/snippets/csharp/System.Security.Cryptography/AsymmetricKeyExchangeDeformatter/Overview/Project.csproj b/snippets/csharp/System.Security.Cryptography/AsymmetricKeyExchangeDeformatter/Overview/Project.csproj new file mode 100644 index 00000000000..29255f5f4b1 --- /dev/null +++ b/snippets/csharp/System.Security.Cryptography/AsymmetricKeyExchangeDeformatter/Overview/Project.csproj @@ -0,0 +1,9 @@ + + + + Library + net6.0 + + + + \ No newline at end of file diff --git a/snippets/csharp/System.Security.Cryptography/AsymmetricKeyExchangeDeformatter/Overview/contosodeformatter.cs b/snippets/csharp/System.Security.Cryptography/AsymmetricKeyExchangeDeformatter/Overview/contosodeformatter.cs index 4967f7f82c2..e6aadfb209f 100644 --- a/snippets/csharp/System.Security.Cryptography/AsymmetricKeyExchangeDeformatter/Overview/contosodeformatter.cs +++ b/snippets/csharp/System.Security.Cryptography/AsymmetricKeyExchangeDeformatter/Overview/contosodeformatter.cs @@ -8,10 +8,10 @@ namespace Contoso { public class ContosoDeformatter : AsymmetricKeyExchangeDeformatter { - private RSA rsaKey; + private RSA _rsaKey; // Default constructor. - public ContosoDeformatter(){} + public ContosoDeformatter() { } // Constructor with the public key to use for encryption. // @@ -23,24 +23,25 @@ public ContosoDeformatter(AsymmetricAlgorithm key) // Set the public key for encyption operations. // - public override void SetKey(AsymmetricAlgorithm key) { + public override void SetKey(AsymmetricAlgorithm key) + { if (key != null) { - rsaKey = (RSA)key; + _rsaKey = (RSA)key; } else { - throw new ArgumentNullException("key"); + throw new ArgumentNullException(nameof(key)); } } // // Disallow access to the parameters of the formatter. // - public override String Parameters + public override string Parameters { get { return null; } - set { ; } + set {; } } // @@ -49,15 +50,14 @@ public override String Parameters // data. This method uses the RSA class only. To // support additional providers or provide custom decryption logic, // add logic to this member. - public override byte[] DecryptKeyExchange(byte[] rgbData) { + public override byte[] DecryptKeyExchange(byte[] rgbData) + { byte[] decryptedBytes = null; - if (rsaKey != null) + if (_rsaKey != null) { - if (rsaKey is RSA) + if (_rsaKey is RSA rsa) { - RSA rsa = (RSA)rsaKey; - decryptedBytes = rsa.Decrypt(rgbData, RSAEncryptionPadding.OaepSHA1); } // Add custom decryption logic here. @@ -81,4 +81,4 @@ public override byte[] DecryptKeyExchange(byte[] rgbData) { // Data decrypted : Sample Contoso encryption application. // // This sample completed successfully; press Enter to exit. -// \ No newline at end of file +// diff --git a/snippets/csharp/System.Security.Cryptography/AsymmetricKeyExchangeDeformatter/Overview/makefile b/snippets/csharp/System.Security.Cryptography/AsymmetricKeyExchangeDeformatter/Overview/makefile deleted file mode 100644 index a4086b602b1..00000000000 --- a/snippets/csharp/System.Security.Cryptography/AsymmetricKeyExchangeDeformatter/Overview/makefile +++ /dev/null @@ -1,8 +0,0 @@ -all: contosoformattercs.dll contosoformatter.exe - -contosoformattercs.dll: contosoformatter.cs - csc /t:library /out:contosoformattercs.dll /r:contosodeformattercs.dll contosoformatter.cs - -contosoformatter.exe: contosoformatter.cs contosoformattercs.dll - csc /t:library /r:contosoformattercs.dll /r:contosodeformattercs.dll /nologo ContosoEncryption.cs - diff --git a/snippets/csharp/System.Windows.Forms/KeyPressEventArgs/Handled/Project.csproj b/snippets/csharp/System.Windows.Forms/KeyPressEventArgs/Handled/Project.csproj new file mode 100644 index 00000000000..61befe5dfa1 --- /dev/null +++ b/snippets/csharp/System.Windows.Forms/KeyPressEventArgs/Handled/Project.csproj @@ -0,0 +1,9 @@ + + + + WinExe + net8.0-windows + true + + + \ No newline at end of file diff --git a/snippets/csharp/System.Xml.Serialization/XmlSerializer/Serialize/Project.csproj b/snippets/csharp/System.Xml.Serialization/XmlSerializer/Serialize/Project.csproj new file mode 100644 index 00000000000..29255f5f4b1 --- /dev/null +++ b/snippets/csharp/System.Xml.Serialization/XmlSerializer/Serialize/Project.csproj @@ -0,0 +1,9 @@ + + + + Library + net6.0 + + + + \ No newline at end of file diff --git a/snippets/csharp/System.Xml.Serialization/XmlSerializer/Serialize/source.cs b/snippets/csharp/System.Xml.Serialization/XmlSerializer/Serialize/source.cs index 9d445c5fc81..74aa1d5820d 100644 --- a/snippets/csharp/System.Xml.Serialization/XmlSerializer/Serialize/source.cs +++ b/snippets/csharp/System.Xml.Serialization/XmlSerializer/Serialize/source.cs @@ -7,47 +7,48 @@ // This is the class that will be serialized. public class OrderedItem { - public string ItemName; - public string Description; - public decimal UnitPrice; - public int Quantity; - public decimal LineTotal; - // A custom method used to calculate price per item. - public void Calculate() - { - LineTotal = UnitPrice * Quantity; - } + public string ItemName; + public string Description; + public decimal UnitPrice; + public int Quantity; + public decimal LineTotal; + // A custom method used to calculate price per item. + public void Calculate() + { + LineTotal = UnitPrice * Quantity; + } } -public class Test{ - public static void Main(string[] args) - { - Test t = new Test(); - // Write a purchase order. - t.SerializeObject("simple.xml"); - } +public class Test +{ + public static void Main(string[] args) + { + Test t = new(); + // Write a purchase order. + t.SerializeObject("simple.xml"); + } - private void SerializeObject(string filename) - { - Console.WriteLine("Writing With TextWriter"); + private void SerializeObject(string filename) + { + Console.WriteLine("Writing With TextWriter"); - XmlSerializer serializer = - new XmlSerializer(typeof(OrderedItem)); - OrderedItem i = new OrderedItem(); - i.ItemName = "Widget"; - i.Description = "Regular Widget"; - i.Quantity = 10; - i.UnitPrice = (decimal) 2.30; - i.Calculate(); + XmlSerializer serializer = new(typeof(OrderedItem)); + OrderedItem i = new() + { + ItemName = "Widget", + Description = "Regular Widget", + Quantity = 10, + UnitPrice = (decimal)2.30 + }; + i.Calculate(); - /* Create a StreamWriter to write with. First create a FileStream - object, and create the StreamWriter specifying an Encoding to use. */ - FileStream fs = new FileStream(filename, FileMode.Create); - TextWriter writer = new StreamWriter(fs, new UTF8Encoding()); - // Serialize using the XmlTextWriter. - serializer.Serialize(writer, i); - writer.Close(); - } + /* Create a StreamWriter to write with. First create a FileStream + object, and create the StreamWriter specifying an Encoding to use. */ + FileStream fs = new(filename, FileMode.Create); + StreamWriter writer = new(fs, new UTF8Encoding()); + // Serialize using the XmlTextWriter. + serializer.Serialize(writer, i); + writer.Close(); + } } - // diff --git a/snippets/csharp/System.Xml.Serialization/XmlSerializer/Serialize/source1.cs b/snippets/csharp/System.Xml.Serialization/XmlSerializer/Serialize/source1.cs index 237e621bf10..41a13e3871b 100644 --- a/snippets/csharp/System.Xml.Serialization/XmlSerializer/Serialize/source1.cs +++ b/snippets/csharp/System.Xml.Serialization/XmlSerializer/Serialize/source1.cs @@ -4,59 +4,60 @@ using System.Xml.Serialization; // This is the class that will be serialized. -public class OrderedItem +public class OrderedItem1 { - [XmlElement(Namespace = "http://www.cpandl.com")] - public string ItemName; - [XmlElement(Namespace = "http://www.cpandl.com")] - public string Description; - [XmlElement(Namespace="http://www.cohowinery.com")] - public decimal UnitPrice; - [XmlElement(Namespace = "http://www.cpandl.com")] - public int Quantity; - [XmlElement(Namespace="http://www.cohowinery.com")] - public decimal LineTotal; - // A custom method used to calculate price per item. - public void Calculate() - { - LineTotal = UnitPrice * Quantity; - } + [XmlElement(Namespace = "http://www.cpandl.com")] + public string ItemName; + [XmlElement(Namespace = "http://www.cpandl.com")] + public string Description; + [XmlElement(Namespace = "http://www.cohowinery.com")] + public decimal UnitPrice; + [XmlElement(Namespace = "http://www.cpandl.com")] + public int Quantity; + [XmlElement(Namespace = "http://www.cohowinery.com")] + public decimal LineTotal; + // A custom method used to calculate price per item. + public void Calculate() + { + LineTotal = UnitPrice * Quantity; + } } -public class Test{ - public static void Main(string[] args) - { - Test t = new Test(); - // Write a purchase order. - t.SerializeObject("simple.xml"); - } +public class Test1 +{ + public static void Main(string[] args) + { + Test1 t = new(); + // Write a purchase order. + t.SerializeObject("simple.xml"); + } - private void SerializeObject(string filename) - { - Console.WriteLine("Writing With TextWriter"); - // Create an XmlSerializer instance using the type. - XmlSerializer serializer = - new XmlSerializer(typeof(OrderedItem)); - OrderedItem i = new OrderedItem(); - i.ItemName = "Widget"; - i.Description = "Regular Widget"; - i.Quantity = 10; - i.UnitPrice = (decimal) 2.30; - i.Calculate(); + private void SerializeObject(string filename) + { + Console.WriteLine("Writing With TextWriter"); + // Create an XmlSerializer instance using the type. + XmlSerializer serializer = new(typeof(OrderedItem1)); + OrderedItem1 i = new() + { + ItemName = "Widget", + Description = "Regular Widget", + Quantity = 10, + UnitPrice = (decimal)2.30 + }; + i.Calculate(); - // Create an XmlSerializerNamespaces object. - XmlSerializerNamespaces ns = - new XmlSerializerNamespaces(); - // Add two namespaces with prefixes. - ns.Add("inventory", "http://www.cpandl.com"); - ns.Add("money", "http://www.cohowinery.com"); - // Create a StreamWriter to write with. - TextWriter writer = new StreamWriter(filename); - /* Serialize using the object using the TextWriter - and namespaces. */ - serializer.Serialize(writer, i, ns); - writer.Close(); - } + // Create an XmlSerializerNamespaces object. + XmlSerializerNamespaces ns = new(); + // Add two namespaces with prefixes. + ns.Add("inventory", "http://www.cpandl.com"); + ns.Add("money", "http://www.cohowinery.com"); + // Create a StreamWriter to write with. + StreamWriter writer = new(filename); + /* Serialize using the object using the TextWriter + and namespaces. */ + serializer.Serialize(writer, i, ns); + writer.Close(); + } } // diff --git a/snippets/csharp/System.Xml.Serialization/XmlSerializer/Serialize/source2.cs b/snippets/csharp/System.Xml.Serialization/XmlSerializer/Serialize/source2.cs index 7e0c844aa24..71818637ae2 100644 --- a/snippets/csharp/System.Xml.Serialization/XmlSerializer/Serialize/source2.cs +++ b/snippets/csharp/System.Xml.Serialization/XmlSerializer/Serialize/source2.cs @@ -4,48 +4,50 @@ using System.Xml.Serialization; // This is the class that will be serialized. -public class OrderedItem +public class OrderedItem2 { - public string ItemName; - public string Description; - public decimal UnitPrice; - public int Quantity; - public decimal LineTotal; + public string ItemName; + public string Description; + public decimal UnitPrice; + public int Quantity; + public decimal LineTotal; - // A custom method used to calculate price per item. - public void Calculate() - { - LineTotal = UnitPrice * Quantity; - } + // A custom method used to calculate price per item. + public void Calculate() + { + LineTotal = UnitPrice * Quantity; + } } -public class Test{ - public static void Main(string[] args) - { - Test t = new Test(); - // Write a purchase order. - t.SerializeObject("simple.xml"); - } +public class Test2 +{ + public static void Main(string[] args) + { + Test2 t = new(); + // Write a purchase order. + t.SerializeObject("simple.xml"); + } - private void SerializeObject(string filename) - { - Console.WriteLine("Writing With Stream"); + private void SerializeObject(string filename) + { + Console.WriteLine("Writing With Stream"); - XmlSerializer serializer = - new XmlSerializer(typeof(OrderedItem)); - OrderedItem i = new OrderedItem(); - i.ItemName = "Widget"; - i.Description = "Regular Widget"; - i.Quantity = 10; - i.UnitPrice = (decimal) 2.30; - i.Calculate(); + XmlSerializer serializer = new(typeof(OrderedItem2)); + OrderedItem2 i = new() + { + ItemName = "Widget", + Description = "Regular Widget", + Quantity = 10, + UnitPrice = (decimal)2.30 + }; + i.Calculate(); - // Create a FileStream to write with. - Stream writer = new FileStream(filename, FileMode.Create); - // Serialize the object, and close the TextWriter - serializer.Serialize(writer, i); - writer.Close(); - } + // Create a FileStream to write with. + FileStream writer = new(filename, FileMode.Create); + // Serialize the object, and close the TextWriter + serializer.Serialize(writer, i); + writer.Close(); + } } // diff --git a/snippets/csharp/System.Xml.Serialization/XmlSerializer/Serialize/source3.cs b/snippets/csharp/System.Xml.Serialization/XmlSerializer/Serialize/source3.cs index 678806fbef4..2b4e90bbe70 100644 --- a/snippets/csharp/System.Xml.Serialization/XmlSerializer/Serialize/source3.cs +++ b/snippets/csharp/System.Xml.Serialization/XmlSerializer/Serialize/source3.cs @@ -5,75 +5,82 @@ using System.Xml.Serialization; // This is the class that will be serialized. -public class OrderedItem { +public class OrderedItem3 +{ [XmlElement(Namespace = "http://www.cpandl.com")] public string ItemName; [XmlElement(Namespace = "http://www.cpandl.com")] public string Description; - [XmlElement(Namespace="http://www.cohowinery.com")] + [XmlElement(Namespace = "http://www.cohowinery.com")] public decimal UnitPrice; [XmlElement(Namespace = "http://www.cpandl.com")] public int Quantity; - [XmlElement(Namespace="http://www.cohowinery.com")] + [XmlElement(Namespace = "http://www.cohowinery.com")] public decimal LineTotal; // A custom method used to calculate price per item. - public void Calculate() { + public void Calculate() + { LineTotal = UnitPrice * Quantity; } } -public class Test { - - public static void Main() { - Test t = new Test(); +public class Test3 +{ + public static void Main() + { + Test3 t = new(); // Write a purchase order. t.SerializeObject("simple.xml"); t.DeserializeObject("simple.xml"); - } + } - private void SerializeObject(string filename) { + private void SerializeObject(string filename) + { Console.WriteLine("Writing With Stream"); XmlSerializer serializer = - new XmlSerializer(typeof(OrderedItem)); - - OrderedItem i = new OrderedItem(); - i.ItemName = "Widget"; - i.Description = "Regular Widget"; - i.Quantity = 10; - i.UnitPrice = (decimal) 2.30; + new(typeof(OrderedItem3)); + + OrderedItem3 i = new() + { + ItemName = "Widget", + Description = "Regular Widget", + Quantity = 10, + UnitPrice = (decimal)2.30 + }; i.Calculate(); // Create an XmlSerializerNamespaces object. - XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); + XmlSerializerNamespaces ns = new(); // Add two prefix-namespace pairs. ns.Add("inventory", "http://www.cpandl.com"); ns.Add("money", "http://www.cohowinery.com"); // Create a FileStream to write with. - Stream writer = new FileStream(filename, FileMode.Create); + FileStream writer = new(filename, FileMode.Create); // Serialize the object, and close the TextWriter serializer.Serialize(writer, i, ns); writer.Close(); } - private void DeserializeObject(string filename) { + private void DeserializeObject(string filename) + { Console.WriteLine("Reading with Stream"); // Create an instance of the XmlSerializer. - XmlSerializer serializer = new XmlSerializer(typeof(OrderedItem)); + XmlSerializer serializer = new(typeof(OrderedItem3)); // Writing the file requires a Stream. - Stream reader= new FileStream(filename,FileMode.Open); + Stream reader = new FileStream(filename, FileMode.Open); // Declare an object variable of the type to be deserialized. - OrderedItem i; + OrderedItem3 i; /* Use the Deserialize method to restore the object's state using data from the XML document. */ - i = (OrderedItem) serializer.Deserialize(reader); + i = (OrderedItem3)serializer.Deserialize(reader); // Write out the properties of the object. Console.Write( diff --git a/snippets/csharp/System.Xml.Serialization/XmlSerializer/Serialize/source4.cs b/snippets/csharp/System.Xml.Serialization/XmlSerializer/Serialize/source4.cs index 7b925879ec8..1960d46bb2d 100644 --- a/snippets/csharp/System.Xml.Serialization/XmlSerializer/Serialize/source4.cs +++ b/snippets/csharp/System.Xml.Serialization/XmlSerializer/Serialize/source4.cs @@ -6,48 +6,49 @@ using System.Xml.Serialization; // This is the class that will be serialized. -public class OrderedItem +public class OrderedItem4 { - public string ItemName; - public string Description; - public decimal UnitPrice; - public int Quantity; - public decimal LineTotal; - // A custom method used to calculate price per item. - public void Calculate() - { - LineTotal = UnitPrice * Quantity; - } + public string ItemName; + public string Description; + public decimal UnitPrice; + public int Quantity; + public decimal LineTotal; + // A custom method used to calculate price per item. + public void Calculate() + { + LineTotal = UnitPrice * Quantity; + } } -public class Test{ - public static void Main() - { - Test t = new Test(); - // Write a purchase order. - t.SerializeObject("simple.xml"); - } +public class Test4 +{ + public static void Main() + { + Test4 t = new(); + // Write a purchase order. + t.SerializeObject("simple.xml"); + } - private void SerializeObject(string filename) - { - Console.WriteLine("Writing With XmlTextWriter"); + private void SerializeObject(string filename) + { + Console.WriteLine("Writing With XmlTextWriter"); - XmlSerializer serializer = - new XmlSerializer(typeof(OrderedItem)); - OrderedItem i = new OrderedItem(); - i.ItemName = "Widget"; - i.Description = "Regular Widget"; - i.Quantity = 10; - i.UnitPrice = (decimal) 2.30; - i.Calculate(); - // Create an XmlTextWriter using a FileStream. - Stream fs = new FileStream(filename, FileMode.Create); - XmlWriter writer = - new XmlTextWriter(fs, Encoding.Unicode); - // Serialize using the XmlTextWriter. - serializer.Serialize(writer, i); - writer.Close(); - } + XmlSerializer serializer = new(typeof(OrderedItem4)); + OrderedItem4 i = new() + { + ItemName = "Widget", + Description = "Regular Widget", + Quantity = 10, + UnitPrice = (decimal)2.30 + }; + i.Calculate(); + // Create an XmlTextWriter using a FileStream. + Stream fs = new FileStream(filename, FileMode.Create); + XmlTextWriter writer = new(fs, Encoding.Unicode); + // Serialize using the XmlTextWriter. + serializer.Serialize(writer, i); + writer.Close(); + } } // diff --git a/snippets/csharp/System.Xml.Serialization/XmlSerializer/Serialize/source5.cs b/snippets/csharp/System.Xml.Serialization/XmlSerializer/Serialize/source5.cs index 53d3a2e854c..d62fcae7a88 100644 --- a/snippets/csharp/System.Xml.Serialization/XmlSerializer/Serialize/source5.cs +++ b/snippets/csharp/System.Xml.Serialization/XmlSerializer/Serialize/source5.cs @@ -6,60 +6,62 @@ using System.Xml.Serialization; // This is the class that will be serialized. -public class OrderedItem +public class OrderedItem5 { - [XmlElement(Namespace = "http://www.cpandl.com")] - public string ItemName; - [XmlElement(Namespace = "http://www.cpandl.com")] - public string Description; - [XmlElement(Namespace="http://www.cohowinery.com")] - public decimal UnitPrice; - [XmlElement(Namespace = "http://www.cpandl.com")] - public int Quantity; - [XmlElement(Namespace="http://www.cohowinery.com")] - public decimal LineTotal; - // A custom method used to calculate price per item. - public void Calculate() - { - LineTotal = UnitPrice * Quantity; - } + [XmlElement(Namespace = "http://www.cpandl.com")] + public string ItemName; + [XmlElement(Namespace = "http://www.cpandl.com")] + public string Description; + [XmlElement(Namespace = "http://www.cohowinery.com")] + public decimal UnitPrice; + [XmlElement(Namespace = "http://www.cpandl.com")] + public int Quantity; + [XmlElement(Namespace = "http://www.cohowinery.com")] + public decimal LineTotal; + // A custom method used to calculate price per item. + public void Calculate() + { + LineTotal = UnitPrice * Quantity; + } } -public class Test{ - public static void Main() - { - Test t = new Test(); - // Write a purchase order. - t.SerializeObject("simple.xml"); - } +public class Test5 +{ + public static void Main() + { + Test5 t = new(); + // Write a purchase order. + t.SerializeObject("simple.xml"); + } - private void SerializeObject(string filename) - { - Console.WriteLine("Writing With XmlTextWriter"); + private void SerializeObject(string filename) + { + Console.WriteLine("Writing With XmlTextWriter"); - XmlSerializer serializer = - new XmlSerializer(typeof(OrderedItem)); - OrderedItem i = new OrderedItem(); - i.ItemName = "Widget"; - i.Description = "Regular Widget"; - i.Quantity = 10; - i.UnitPrice = (decimal) 2.30; - i.Calculate(); + XmlSerializer serializer = new(typeof(OrderedItem5)); + OrderedItem5 i = new() + { + ItemName = "Widget", + Description = "Regular Widget", + Quantity = 10, + UnitPrice = (decimal)2.30 + }; + i.Calculate(); - // Create an XmlSerializerNamespaces object. - XmlSerializerNamespaces ns = - new XmlSerializerNamespaces(); - // Add two namespaces with prefixes. - ns.Add("inventory", "http://www.cpandl.com"); - ns.Add("money", "http://www.cohowinery.com"); - // Create an XmlTextWriter using a FileStream. - Stream fs = new FileStream(filename, FileMode.Create); - XmlWriter writer = - new XmlTextWriter(fs, new UTF8Encoding()); - // Serialize using the XmlTextWriter. - serializer.Serialize(writer, i, ns); - writer.Close(); - } -} + // Create an XmlSerializerNamespaces object. + XmlSerializerNamespaces ns = new(); + + // Add two namespaces with prefixes. + ns.Add("inventory", "http://www.cpandl.com"); + ns.Add("money", "http://www.cohowinery.com"); + // Create an XmlTextWriter using a FileStream. + Stream fs = new FileStream(filename, FileMode.Create); + XmlTextWriter writer = new(fs, new UTF8Encoding()); + + // Serialize using the XmlTextWriter. + serializer.Serialize(writer, i, ns); + writer.Close(); + } +} // diff --git a/snippets/csharp/System/ArrayTypeMismatchException/.ctor/Project.csproj b/snippets/csharp/System/ArrayTypeMismatchException/.ctor/Project.csproj new file mode 100644 index 00000000000..29255f5f4b1 --- /dev/null +++ b/snippets/csharp/System/ArrayTypeMismatchException/.ctor/Project.csproj @@ -0,0 +1,9 @@ + + + + Library + net6.0 + + + + \ No newline at end of file diff --git a/snippets/csharp/System/ArrayTypeMismatchException/.ctor/arraytypemismatch_constructor1.cs b/snippets/csharp/System/ArrayTypeMismatchException/.ctor/arraytypemismatch_constructor1.cs index 78cc2b2fb19..1368d14e1ba 100644 --- a/snippets/csharp/System/ArrayTypeMismatchException/.ctor/arraytypemismatch_constructor1.cs +++ b/snippets/csharp/System/ArrayTypeMismatchException/.ctor/arraytypemismatch_constructor1.cs @@ -10,42 +10,42 @@ // using System; -public class ArrayTypeMisMatchConst +public class ArrayTypeMismatchConst { - public void CopyArray(Array myArray,Array myArray1) - { - string typeArray1 = myArray.GetType().ToString(); - string typeArray2 = myArray1.GetType().ToString(); - // Check whether the two arrays are of same type or not. - if(typeArray1==typeArray2) - { - // Copy the values from one array to another. - myArray.SetValue("Name: "+myArray1.GetValue(0),0); - myArray.SetValue("Name: "+myArray1.GetValue(1),1); - } - else - { - // Throw an exception of type 'ArrayTypeMismatchException'. - throw new ArrayTypeMismatchException(); - } - } - static void Main() - { - try - { - string[] myStringArray = new string[2]; - myStringArray.SetValue("Jones",0); - myStringArray.SetValue("John",1); + public void CopyArray(Array myArray, Array myArray1) + { + string typeArray1 = myArray.GetType().ToString(); + string typeArray2 = myArray1.GetType().ToString(); + // Check whether the two arrays are of same type or not. + if (typeArray1 == typeArray2) + { + // Copy the values from one array to another. + myArray.SetValue("Name: " + myArray1.GetValue(0), 0); + myArray.SetValue("Name: " + myArray1.GetValue(1), 1); + } + else + { + // Throw an exception of type 'ArrayTypeMismatchException'. + throw new ArrayTypeMismatchException(); + } + } + static void Main() + { + try + { + string[] myStringArray = new string[2]; + myStringArray.SetValue("Jones", 0); + myStringArray.SetValue("John", 1); - int[] myIntArray = new int[2]; - ArrayTypeMisMatchConst myArrayType = new ArrayTypeMisMatchConst(); - myArrayType.CopyArray(myStringArray,myIntArray); - } - catch(ArrayTypeMismatchException e) - { - Console.WriteLine("The Exception is :"+e); - } - } + int[] myIntArray = new int[2]; + ArrayTypeMismatchConst myArrayType = new(); + myArrayType.CopyArray(myStringArray, myIntArray); + } + catch (ArrayTypeMismatchException e) + { + Console.WriteLine("The Exception is :" + e); + } + } } // diff --git a/snippets/csharp/System/ArrayTypeMismatchException/.ctor/arraytypemismatch_constructor2.cs b/snippets/csharp/System/ArrayTypeMismatchException/.ctor/arraytypemismatch_constructor2.cs index 60b756bc411..7752045456d 100644 --- a/snippets/csharp/System/ArrayTypeMismatchException/.ctor/arraytypemismatch_constructor2.cs +++ b/snippets/csharp/System/ArrayTypeMismatchException/.ctor/arraytypemismatch_constructor2.cs @@ -12,41 +12,41 @@ caught in the calling method. using System; -public class ArrayTypeMisMatchConst +public class ArrayTypeMismatchConst2 { - public void CopyArray(Array myArray,Array myArray1) - { - string typeArray1 = myArray.GetType().ToString(); - string typeArray2 = myArray1.GetType().ToString(); - // Check whether the two arrays are of same type or not. - if(typeArray1==typeArray2) - { - // Copies the values from one array to another. - myArray.SetValue("Name: "+myArray1.GetValue(0),0); - myArray.SetValue("Name: "+myArray1.GetValue(1),1); - } - else - { - // Throw an exception of type 'ArrayTypeMismatchException' with a message string as parameter. - throw new ArrayTypeMismatchException("The Source and destination arrays are not of same type."); - } - } + public void CopyArray(Array myArray, Array myArray1) + { + string typeArray1 = myArray.GetType().ToString(); + string typeArray2 = myArray1.GetType().ToString(); + // Check whether the two arrays are of same type or not. + if (typeArray1 == typeArray2) + { + // Copies the values from one array to another. + myArray.SetValue("Name: " + myArray1.GetValue(0), 0); + myArray.SetValue("Name: " + myArray1.GetValue(1), 1); + } + else + { + // Throw an exception of type 'ArrayTypeMismatchException' with a message string as parameter. + throw new ArrayTypeMismatchException("The Source and destination arrays are not of same type."); + } + } - static void Main() - { - try - { - string[] myStringArray = new string[2]; - myStringArray.SetValue("Jones",0); - myStringArray.SetValue("John",1); - int[] myIntArray = new int[2]; - ArrayTypeMisMatchConst myArrayType = new ArrayTypeMisMatchConst(); - myArrayType.CopyArray(myStringArray,myIntArray); - } - catch(ArrayTypeMismatchException e) - { - Console.WriteLine("The Exception Message is : " + e.Message); - } - } + static void Main() + { + try + { + string[] myStringArray = new string[2]; + myStringArray.SetValue("Jones", 0); + myStringArray.SetValue("John", 1); + int[] myIntArray = new int[2]; + ArrayTypeMismatchConst2 myArrayType = new(); + myArrayType.CopyArray(myStringArray, myIntArray); + } + catch (ArrayTypeMismatchException e) + { + Console.WriteLine("The Exception Message is : " + e.Message); + } + } } // diff --git a/snippets/csharp/System/ArrayTypeMismatchException/.ctor/arraytypemismatch_constructor3.cs b/snippets/csharp/System/ArrayTypeMismatchException/.ctor/arraytypemismatch_constructor3.cs index 4a9e6d07b79..dce42823e44 100644 --- a/snippets/csharp/System/ArrayTypeMismatchException/.ctor/arraytypemismatch_constructor3.cs +++ b/snippets/csharp/System/ArrayTypeMismatchException/.ctor/arraytypemismatch_constructor3.cs @@ -13,38 +13,38 @@ in the calling method and the error message is displayed to the console. using System; -public class ArrayTypeMisMatchConst +public class ArrayTypeMismatchConst3 { - public void CopyArray(Array myArray,Array myArray1) - { - try - { - // Copies the value of one array into another array. - myArray.SetValue(myArray1.GetValue(0),0); - myArray.SetValue(myArray1.GetValue(1),1); - } - catch(Exception e) - { - // Throw an exception of with a message and innerexception. - throw new ArrayTypeMismatchException("The Source and destination arrays are of not same type.", e); - } - } - static void Main() - { - try - { + public void CopyArray(Array myArray, Array myArray1) + { + try + { + // Copies the value of one array into another array. + myArray.SetValue(myArray1.GetValue(0), 0); + myArray.SetValue(myArray1.GetValue(1), 1); + } + catch (Exception e) + { + // Throw an exception of with a message and innerexception. + throw new ArrayTypeMismatchException("The Source and destination arrays are of not same type.", e); + } + } + static void Main() + { + try + { string[] myStringArray = new string[2]; - myStringArray.SetValue("Jones",0); - myStringArray.SetValue("John",1); + myStringArray.SetValue("Jones", 0); + myStringArray.SetValue("John", 1); int[] myIntArray = new int[2]; - ArrayTypeMisMatchConst myArrayType = new ArrayTypeMisMatchConst(); - myArrayType.CopyArray(myStringArray,myIntArray); - } - catch(ArrayTypeMismatchException e) - { - Console.WriteLine("The Exception Message is : "+e.Message); - Console.WriteLine("The Inner exception is :"+e.InnerException); - } - } + ArrayTypeMismatchConst3 myArrayType = new(); + myArrayType.CopyArray(myStringArray, myIntArray); + } + catch (ArrayTypeMismatchException e) + { + Console.WriteLine("The Exception Message is : " + e.Message); + Console.WriteLine("The Inner exception is :" + e.InnerException); + } + } } // diff --git a/snippets/csharp/System/Type/GetConstructor/Project.csproj b/snippets/csharp/System/Type/GetConstructor/Project.csproj new file mode 100644 index 00000000000..29255f5f4b1 --- /dev/null +++ b/snippets/csharp/System/Type/GetConstructor/Project.csproj @@ -0,0 +1,9 @@ + + + + Library + net6.0 + + + + \ No newline at end of file diff --git a/snippets/csharp/System/Type/GetConstructor/type_getconstructor.cs b/snippets/csharp/System/Type/GetConstructor/type_getconstructor.cs index b89197deef3..d808bcde6aa 100644 --- a/snippets/csharp/System/Type/GetConstructor/type_getconstructor.cs +++ b/snippets/csharp/System/Type/GetConstructor/type_getconstructor.cs @@ -2,12 +2,11 @@ using System; using System.Reflection; -using System.Security; public class MyClass1 { - public MyClass1(){} - public MyClass1(int i){} + public MyClass1() { } + public MyClass1(int i) { } public static void Main() { @@ -30,7 +29,7 @@ public static void Main() "as a parameter is not available."); } } - catch(Exception e) + catch (Exception e) { Console.WriteLine("Exception caught."); Console.WriteLine("Source: " + e.Source); @@ -38,4 +37,4 @@ public static void Main() } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Type/GetConstructor/type_getconstructor2.cs b/snippets/csharp/System/Type/GetConstructor/type_getconstructor2.cs index 0e7d4e1ac04..ff11206a5c5 100644 --- a/snippets/csharp/System/Type/GetConstructor/type_getconstructor2.cs +++ b/snippets/csharp/System/Type/GetConstructor/type_getconstructor2.cs @@ -3,44 +3,44 @@ using System.Reflection; using System.Security; -public class MyClass1 +public class MyClass2 { - public MyClass1(int i){} + public MyClass2(int i) { } public static void Main() { try { - Type myType = typeof(MyClass1); + Type myType = typeof(MyClass2); Type[] types = new Type[1]; types[0] = typeof(int); // Get the constructor that is public and takes an integer parameter. ConstructorInfo constructorInfoObj = myType.GetConstructor( BindingFlags.Instance | BindingFlags.Public, null, types, null); - if (constructorInfoObj != null ) + if (constructorInfoObj != null) { - Console.WriteLine("The constructor of MyClass1 that is public " + + Console.WriteLine("The constructor of MyClass2 that is public " + "and takes an integer as a parameter is:"); Console.WriteLine(constructorInfoObj.ToString()); } else { - Console.WriteLine("The constructor of the MyClass1 that is public " + + Console.WriteLine("The constructor of the MyClass2 that is public " + "and takes an integer as a parameter is not available."); } } - catch(ArgumentNullException e) + catch (ArgumentNullException e) { Console.WriteLine("ArgumentNullException: " + e.Message); } - catch(ArgumentException e) + catch (ArgumentException e) { Console.WriteLine("ArgumentException: " + e.Message); } - catch(SecurityException e) + catch (SecurityException e) { Console.WriteLine("SecurityException: " + e.Message); } - catch(Exception e) + catch (Exception e) { Console.WriteLine("Exception: " + e.Message); } diff --git a/snippets/csharp/System/Type/GetConstructor/type_getconstructor3.cs b/snippets/csharp/System/Type/GetConstructor/type_getconstructor3.cs index 2cfb88308a9..b45977e7545 100644 --- a/snippets/csharp/System/Type/GetConstructor/type_getconstructor3.cs +++ b/snippets/csharp/System/Type/GetConstructor/type_getconstructor3.cs @@ -3,48 +3,48 @@ using System.Reflection; using System.Security; -public class MyClass1 +public class MyClass3 { - public MyClass1(int i){} + public MyClass3(int i) { } public static void Main() { try { - Type myType = typeof(MyClass1); + Type myType = typeof(MyClass3); Type[] types = new Type[1]; types[0] = typeof(int); // Get the public instance constructor that takes an integer parameter. ConstructorInfo constructorInfoObj = myType.GetConstructor( BindingFlags.Instance | BindingFlags.Public, null, CallingConventions.HasThis, types, null); - if(constructorInfoObj != null) + if (constructorInfoObj != null) { - Console.WriteLine("The constructor of MyClass1 that is a public " + + Console.WriteLine("The constructor of MyClass3 that is a public " + "instance method and takes an integer as a parameter is: "); Console.WriteLine(constructorInfoObj.ToString()); } else { - Console.WriteLine("The constructor of MyClass1 that is a public instance " + + Console.WriteLine("The constructor of MyClass3 that is a public instance " + "method and takes an integer as a parameter is not available."); } } - catch(ArgumentNullException e) + catch (ArgumentNullException e) { Console.WriteLine("ArgumentNullException: " + e.Message); } - catch(ArgumentException e) + catch (ArgumentException e) { Console.WriteLine("ArgumentException: " + e.Message); } - catch(SecurityException e) + catch (SecurityException e) { Console.WriteLine("SecurityException: " + e.Message); } - catch(Exception e) + catch (Exception e) { Console.WriteLine("Exception: " + e.Message); } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Type/GetProperty/type_getproperty1.cs b/snippets/csharp/System/Type/GetProperty/type_getproperty1.cs index ded0be8510f..55365091395 100644 --- a/snippets/csharp/System/Type/GetProperty/type_getproperty1.cs +++ b/snippets/csharp/System/Type/GetProperty/type_getproperty1.cs @@ -5,35 +5,26 @@ class MyClass1 { - private int myProperty; // Declare MyProperty. - public int MyProperty - { - get - { - return myProperty; - } - set - { - myProperty=value; - } - } + public int MyProperty { get; set; } } -public class MyTypeClass2 +public class MyTypeClass1 { public static void Main(string[] args) { try { // Get the Type object corresponding to MyClass1. - Type myType=typeof(MyClass1); + Type myType = typeof(MyClass1); + // Get the PropertyInfo object by passing the property name. PropertyInfo myPropInfo = myType.GetProperty("MyProperty"); + // Display the property name. Console.WriteLine("The {0} property exists in MyClass1.", myPropInfo.Name); } - catch(NullReferenceException e) + catch (NullReferenceException e) { Console.WriteLine("The property does not exist in MyClass1." + e.Message); } diff --git a/snippets/csharp/System/Type/GetProperty/type_getproperty2.cs b/snippets/csharp/System/Type/GetProperty/type_getproperty2.cs index 9e1bb07a3d5..6d5fdbebbba 100644 --- a/snippets/csharp/System/Type/GetProperty/type_getproperty2.cs +++ b/snippets/csharp/System/Type/GetProperty/type_getproperty2.cs @@ -5,19 +5,8 @@ class MyClass2 { - private int myProperty; // Declare MyProperty. - public int MyProperty - { - get - { - return myProperty; - } - set - { - myProperty=value; - } - } + public int MyProperty { get; set; } } public class MyTypeClass2 @@ -27,16 +16,21 @@ public static void Main(string[] args) try { // Get Type object of MyClass2. - Type myType=typeof(MyClass2); + Type myType = typeof(MyClass2); + // Get the PropertyInfo by passing the property name and specifying the BindingFlags. - PropertyInfo myPropInfo = myType.GetProperty("MyProperty", BindingFlags.Public | BindingFlags.Instance); + PropertyInfo myPropInfo = myType.GetProperty( + "MyProperty", + BindingFlags.Public | BindingFlags.Instance + ); + // Display Name property to console. Console.WriteLine("{0} is a property of MyClass2.", myPropInfo.Name); } - catch(NullReferenceException e) + catch (NullReferenceException e) { - Console.WriteLine("MyProperty does not exist in MyClass2." +e.Message); + Console.WriteLine("MyProperty does not exist in MyClass2." + e.Message); } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System/Type/GetProperty/type_getproperty21.cs b/snippets/csharp/System/Type/GetProperty/type_getproperty21.cs index 62c5887e96c..5f7ee5d3e84 100644 --- a/snippets/csharp/System/Type/GetProperty/type_getproperty21.cs +++ b/snippets/csharp/System/Type/GetProperty/type_getproperty21.cs @@ -4,17 +4,17 @@ public class MyPropertyClass { - private int [,] myPropertyArray = new int[10,10]; + private readonly int [,] _myPropertyArray = new int[10,10]; // Declare an indexer. public int this [int i,int j] { get { - return myPropertyArray[i,j]; + return _myPropertyArray[i,j]; } set { - myPropertyArray[i,j] = value; + _myPropertyArray[i,j] = value; } } } @@ -27,10 +27,12 @@ public static void Main() { Type myType=typeof(MyPropertyClass); Type[] myTypeArray = new Type[2]; + // Create an instance of the Type array representing the number, order // and type of the parameters for the property. myTypeArray.SetValue(typeof(int),0); myTypeArray.SetValue(typeof(int),1); + // Search for the indexed property whose parameters match the // specified argument types and modifiers. PropertyInfo myPropertyInfo = myType.GetProperty("Item", diff --git a/snippets/csharp/System/Type/GetProperty/type_getproperty3.cs b/snippets/csharp/System/Type/GetProperty/type_getproperty3.cs index e96e5370669..b30e4da0e67 100644 --- a/snippets/csharp/System/Type/GetProperty/type_getproperty3.cs +++ b/snippets/csharp/System/Type/GetProperty/type_getproperty3.cs @@ -5,17 +5,17 @@ class MyClass3 { - private int [,] myArray = {{1,2},{3,4}}; + private readonly int[,] _myArray = { { 1, 2 }, { 3, 4 } }; // Declare an indexer. - public int this [int i,int j] + public int this[int i, int j] { get { - return myArray[i,j]; + return _myArray[i, j]; } set { - myArray[i,j] = value; + _myArray[i, j] = value; } } } @@ -27,21 +27,25 @@ public static void Main(string[] args) try { // Get the Type object. - Type myType=typeof(MyClass3); + Type myType = typeof(MyClass3); Type[] myTypeArr = new Type[2]; + // Create an instance of a Type array. - myTypeArr.SetValue(typeof(int),0); - myTypeArr.SetValue(typeof(int),1); + myTypeArr.SetValue(typeof(int), 0); + myTypeArr.SetValue(typeof(int), 1); + // Get the PropertyInfo object for the indexed property Item, which has two integer parameters. PropertyInfo myPropInfo = myType.GetProperty("Item", myTypeArr); + // Display the property. - Console.WriteLine("The {0} property exists in MyClass3.", myPropInfo.ToString()); + Console.WriteLine("The {0} property exists in MyClass3.", + myPropInfo.ToString()); } - catch(NullReferenceException e) + catch (NullReferenceException e) { Console.WriteLine("An exception occurred."); - Console.WriteLine("Source : {0}" , e.Source); - Console.WriteLine("Message : {0}" , e.Message); + Console.WriteLine("Source : {0}", e.Source); + Console.WriteLine("Message : {0}", e.Message); } } } diff --git a/snippets/csharp/System/Type/GetProperty/type_getproperty_types.cs b/snippets/csharp/System/Type/GetProperty/type_getproperty_types.cs index 43c9ea42150..5bd74bc952a 100644 --- a/snippets/csharp/System/Type/GetProperty/type_getproperty_types.cs +++ b/snippets/csharp/System/Type/GetProperty/type_getproperty_types.cs @@ -5,18 +5,7 @@ class MyPropertyTypeClass { - String myMessage = "Hello World."; - public string MyProperty1 - { - get - { - return myMessage; - } - set - { - myMessage = value; - } - } + public string MyProperty1 { get; set; } = "Hello World."; } class TestClass @@ -24,29 +13,33 @@ class TestClass static void Main() { try - { + { Type myType = typeof(MyPropertyTypeClass); + // Get the PropertyInfo object representing MyProperty1. PropertyInfo myStringProperties1 = myType.GetProperty("MyProperty1", typeof(string)); - Console.WriteLine("The name of the first property of MyPropertyTypeClass is {0}.", myStringProperties1.Name); - Console.WriteLine("The type of the first property of MyPropertyTypeClass is {0}.", myStringProperties1.PropertyType); + + Console.WriteLine("The name of the first property of MyPropertyTypeClass is {0}.", + myStringProperties1.Name); + Console.WriteLine("The type of the first property of MyPropertyTypeClass is {0}.", + myStringProperties1.PropertyType); } - catch(ArgumentNullException e) + catch (ArgumentNullException e) { Console.WriteLine("ArgumentNullException :" + e.Message); } - catch(AmbiguousMatchException e) + catch (AmbiguousMatchException e) { Console.WriteLine("AmbiguousMatchException :" + e.Message); } - catch(NullReferenceException e) + catch (NullReferenceException e) { - Console.WriteLine("Source : {0}" , e.Source); - Console.WriteLine("Message : {0}" , e.Message); + Console.WriteLine("Source : {0}", e.Source); + Console.WriteLine("Message : {0}", e.Message); } - //Output: - //The name of the first property of MyPropertyTypeClass is MyProperty1. - //The type of the first property of MyPropertyTypeClass is System.String. + //Output: + //The name of the first property of MyPropertyTypeClass is MyProperty1. + //The type of the first property of MyPropertyTypeClass is System.String. } } // diff --git a/xml/System.Runtime.InteropServices/IDispatchImplAttribute.xml b/xml/System.Runtime.InteropServices/IDispatchImplAttribute.xml index a0c02ce11a1..dbe78ea02df 100644 --- a/xml/System.Runtime.InteropServices/IDispatchImplAttribute.xml +++ b/xml/System.Runtime.InteropServices/IDispatchImplAttribute.xml @@ -33,22 +33,13 @@ Indicates which implementation the common language runtime uses when exposing dual interfaces and dispinterfaces to COM. - , the `IDispatch` implementation is supplied by passing the type information for the object to COM's `CreateStdDispatch` API. When you set the attribute to , the `IDispatch` implementation is supplied by the common language runtime. Setting the attribute to allows the runtime to choose the appropriate implementation. When using the attribute on an assembly, the attribute applies to all classes defined within the assembly. When using the attribute on an individual class, the attribute applies only to the interfaces exposed by that class and overrides any assembly-level setting. - - - -## Examples - The following example demonstrates how to apply to select the `IDispatch` implementation supplied by the common language runtime. - - :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR/ImprovedInteropSnippets/CPP/codefile1.cpp" id="Snippet1"::: - :::code language="csharp" source="~/snippets/csharp/System.Runtime.InteropServices/ComImportAttribute/Overview/codefile1.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/ImprovedInteropSnippets/VB/codefile1.vb" id="Snippet1"::: - + , the `IDispatch` implementation is supplied by passing the type information for the object to COM's `CreateStdDispatch` API. When you set the attribute to , the `IDispatch` implementation is supplied by the common language runtime. Setting the attribute to allows the runtime to choose the appropriate implementation. When using the attribute on an assembly, the attribute applies to all classes defined within the assembly. When using the attribute on an individual class, the attribute applies only to the interfaces exposed by that class and overrides any assembly-level setting. + ]]> @@ -85,11 +76,11 @@ Indicates which enumeration will be used. Initializes a new instance of the class with specified value. - enumeration member. The Type Library Importer (TlbImp.exe) uses this constructor to avoid generating a typeref to the `IDispatchImplType` value that `value` represents, and then builds the signature with that token. - + enumeration member. The Type Library Importer (TlbImp.exe) uses this constructor to avoid generating a typeref to the `IDispatchImplType` value that `value` represents, and then builds the signature with that token. + ]]> @@ -115,11 +106,11 @@ Indicates which enumeration will be used. Initializes a new instance of the class with specified value. -