Search code examples
c#.net.net-coredelegatesxceed

Delegate method not invoked in C#


I am trying to call a delegate to validate the incoming SSL Certificates from FTP Server.

When I put a debug point in OnCertificateReceived function, the execution never stops, and the SSL Certificate is never validated.

Can someone please point out if I am doing anything wrong here.

class Program
{

var hostname = '';
var username = '';
var password = '';

public static void main()
{
  new Program().XceedFtpWithSSL();
}

void XceedFtpWithSSL()
{
connection = new FtpConnection(hostname,21,username,password,AuthenticationMethod.TlsAuto,VerificationFlags.None,null,DataChannelProtection.Private,false);

connection.CertificateReceived += new CertificateReceivedEventHandler( this.OnCertificateReceived );
}

// When I put debug point in this method, execution never stops

private void OnCertificateReceived(object sender, CertificateReceivedEventArgs e)
        {
            // The Status argument property tells you if the server certificate was accepted
            // based on the VerificationFlags you provided.
            if (e.Status != VerificationStatus.ValidCertificate)
            {

                Console.WriteLine("Do you want to accept this certificate anyway? [Y/N]");
                int answer = Console.Read();

                if ((answer == 'y') || (answer == 'Y'))
                {
                    e.Action = VerificationAction.Accept;
                }
            }
            else
            {
                Console.WriteLine("Valid certificate received from server.");
                // e.Action's default value is VerificationAction.Accept
            }
        } // End of Delegate

}//End of class

Solution

  • Then you are applying an event to the delegate, for him to execute defato must have some function in FtpConnection that executes this delegate event: Ex

    public delegate void ExDelegate(string value);
    
    class Program
    {
        static void Main(string[] args)
        {
            Connection connection = new Connection();
            connection.ExDelegate += OnConnection_ExDelegate;
            connection.Init();
        }
    
        public static void OnConnection_ExDelegate(string value)
        {
            Console.WriteLine(value);
            Console.ReadLine();
        }
    }
    
    public class Connection
    {
        public event ExDelegate ExDelegate;
    
        public void Init()
        {
            Console.Write("Enter your name: ");
            ExDelegate?.Invoke(Console.ReadLine());
        }
    }