Table of contents

  1. Get affected rows on ExecuteNonQuery in C#
  2. Get ssl certificate in C#
  3. SmtpClient get result from server on send in C#

Get affected rows on ExecuteNonQuery in C#

The ExecuteNonQuery method of the SqlCommand class in C# returns the number of rows affected by the command. You can retrieve this value using the ExecuteNonQuery method's return value.

Here's an example:

using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();

    string commandText = "UPDATE MyTable SET Column1 = @Value WHERE ID = @ID";
    SqlCommand command = new SqlCommand(commandText, connection);
    command.Parameters.AddWithValue("@Value", "New Value");
    command.Parameters.AddWithValue("@ID", 1);

    int rowsAffected = command.ExecuteNonQuery();
    Console.WriteLine($"Rows affected: {rowsAffected}");
}

In this example, we create a new SqlCommand object with a SQL UPDATE statement that sets the value of Column1 to "New Value" for the row with an ID of 1. We then execute the command using the ExecuteNonQuery method and retrieve the number of rows affected by the command using the return value of the method.

We then print the number of rows affected to the console using a Console.WriteLine statement.

Note that the ExecuteNonQuery method returns the number of rows affected by the command, not the number of rows that were actually changed. For example, if you execute an UPDATE statement that sets the value of a column to its existing value, the number of rows affected will still be returned as 1, even though no actual changes were made to the data.


Get ssl certificate in C#

To retrieve an SSL certificate in C#, you can use the X509Store class in the System.Security.Cryptography.X509Certificates namespace. Here's an example:

string serverName = "www.example.com";
int portNumber = 443;
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certificates = store.Certificates.Find(
    X509FindType.FindBySubjectName, serverName, false);

foreach (X509Certificate2 certificate in certificates)
{
    if (certificate.GetCertHashString() != null)
    {
        Console.WriteLine("Certificate found:");
        Console.WriteLine("    Subject: {0}", certificate.Subject);
        Console.WriteLine("    Expiration date: {0}", certificate.GetExpirationDateString());
        Console.WriteLine("    Hash: {0}", certificate.GetCertHashString());
    }
}

store.Close();

In this example, we retrieve the SSL certificate for the server www.example.com on port 443. We create an instance of the X509Store class, which represents the certificate store on the local machine, and open it in read-only mode. We then use the Find() method to find the SSL certificate with the subject name www.example.com. We loop through the collection of certificates returned by the Find() method, and for each certificate that has a non-null hash, we display its subject name, expiration date, and hash value.

Note that you may need to adjust the store name and location depending on your specific scenario. You may also need to adjust the search criteria used in the Find() method to match your SSL certificate. Additionally, you should ensure that your code has the appropriate permissions to access the certificate store on the local machine.


SmtpClient get result from server on send in C#

The SmtpClient class in C# does not provide a direct way to get the result from the server after sending an email. It is designed to be asynchronous and fire-and-forget, which means that it initiates the email sending process and does not wait for the server's response or return any result to the calling code.

However, you can work around this limitation by using the SendCompleted event to receive notifications when the email sending process completes or encounters an error. The SendCompleted event will be raised when the email has been sent or when an exception occurs during the sending process.

Here's an example of how to use the SendCompleted event with SmtpClient:

using System;
using System.Net;
using System.Net.Mail;

public class Program
{
    public static void Main()
    {
        string senderEmail = "[email protected]";
        string senderPassword = "your_sender_password";

        // Replace these values with your actual SMTP server details
        string smtpServer = "your_smtp_server";
        int smtpPort = 587;

        using (SmtpClient smtpClient = new SmtpClient(smtpServer, smtpPort))
        {
            smtpClient.UseDefaultCredentials = false;
            smtpClient.Credentials = new NetworkCredential(senderEmail, senderPassword);
            smtpClient.EnableSsl = true;

            // Subscribe to the SendCompleted event
            smtpClient.SendCompleted += SmtpClient_SendCompleted;

            try
            {
                MailMessage mailMessage = new MailMessage(senderEmail, "[email protected]", "Test Subject", "Test Body");

                // Optionally, you can pass a user-defined object as the second parameter
                // This object will be available in the SendCompleted event arguments
                smtpClient.SendAsync(mailMessage, null);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error sending email: " + ex.Message);
            }
        }
    }

    private static void SmtpClient_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
    {
        // Handle the completion or error here
        if (e.Error != null)
        {
            Console.WriteLine("Email sending failed: " + e.Error.Message);
        }
        else if (e.Cancelled)
        {
            Console.WriteLine("Email sending was canceled.");
        }
        else
        {
            Console.WriteLine("Email sent successfully!");
        }

        // Optionally, you can access the user-defined object passed in SendAsync
        // object userState = e.UserState;
    }
}

In this example, the SmtpClient_SendCompleted method will be called when the email sending process is completed, successfully or with an error. You can handle the result or error in this event handler.

Please keep in mind that the SendCompleted event is asynchronous, and the event handler might be called on a different thread. Make sure to handle any potential thread synchronization issues if you interact with shared resources within the event handler.


More Python Questions

More C# Questions