小编Eri*_*ric的帖子

在C#中取消订阅匿名方法

是否可以从事件中取消订阅匿名方法?

如果我订阅这样的事件:

void MyMethod()
{
    Console.WriteLine("I did it!");
}

MyEvent += MyMethod;
Run Code Online (Sandbox Code Playgroud)

我可以这样取消订阅:

MyEvent -= MyMethod;
Run Code Online (Sandbox Code Playgroud)

但是如果我使用匿名方法订阅:

MyEvent += delegate(){Console.WriteLine("I did it!");};
Run Code Online (Sandbox Code Playgroud)

是否有可能取消订阅这种匿名方法?如果是这样,怎么样?

c# delegates anonymous-methods

214
推荐指数
7
解决办法
7万
查看次数

如何以编程方式更改Active Directory密码

我有一组将要创建的测试帐户,但帐户将设置为在首次登录时要求更改密码.我想用C#编写一个程序来浏览测试帐户并更改密码.

c# directoryservices active-directory

34
推荐指数
3
解决办法
8万
查看次数

为什么我的ServicePointManager.ServerCertificateValidationCallback被忽略?

我正在winforms应用程序中发出Web请求.我正在提供自定义证书验证,如下所示:

    ServicePointManager.ServerCertificateValidationCallback += 
        new RemoteCertificateValidationCallback(certValidator.ValidateRemoteCertificate);
Run Code Online (Sandbox Code Playgroud)

其中certValidator.ValidateRemoteCertificate是

public bool ValidateRemoteCertificate(object sender, X509Certificate certificate,
                                      X509Chain chain, SslPolicyErrors policyErrors)
{
        return false;
}
Run Code Online (Sandbox Code Playgroud)

如您所见,此回调应拒绝所有服务器证书并关闭所有尝试的连接.

我的问题是这个回调完全被忽略了.我提交了一个https请求,它就像一个魅力.在调试器中观察它我可以看到它ValidateRemoteCertificate永远不会被调用.

为什么我的替换回叫从未回拨过?

编辑:LB要求webrequest,所以这里是:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sourceUrl);
request.UseDefaultCredentials = true;
request.UserAgent = "Mozilla/5.0 (Windows; U; MSIE 9.0; WIndows NT 9.0; en-US))";    

request.KeepAlive = false;
request.Headers.Add("Accept-Language", "en-us,en;q=1.0");
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Run Code Online (Sandbox Code Playgroud)

编辑2:它可能不相关,但在.config文件中,我指示它使用配置代理,如下所示:

<system.net>
    <defaultProxy useDefaultCredentials="true"/>
</system.net>
Run Code Online (Sandbox Code Playgroud)

编辑3:下面是一个完整的,最小的例子,表明了行为.我希望这个例子抛出异常,因为所有的证书都应该被拒绝,但是它可以正常工作.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;

namespace SPMCertCallbackDemonstrator
{
    class Program
    {
        static void …
Run Code Online (Sandbox Code Playgroud)

.net c# certificate winforms

10
推荐指数
1
解决办法
1万
查看次数

为什么我的log4net appender没有缓冲?

我已经创建了一个自定义log4net appender.它来自log4net.Appender.SmtpAppender,它来自log4net.Appender.BufferingAppenderSkeleton.

我以编程方式在其构造函数中设置以下参数:

this.Lossy = false;  //don't drop any messages
this.BufferSize = 3; //buffer up to 3 messages
this.Threshold = log4net.Core.Level.Error; //append messages of Error or higher
this.Evaluator = new log4net.Core.LevelEvaluator(Level.Off); //don't flush the buffer for any message, regardless of level
Run Code Online (Sandbox Code Playgroud)

我希望这会缓冲3个级别错误或更高级别的事件,并在填充缓冲区时传递这些事件.但是,我发现事件根本没有缓冲; 相反,每次记录错误时立即调用SendBuffer().

我的配置有错误吗?

谢谢

c# logging log4net

7
推荐指数
1
解决办法
8459
查看次数

鉴于两个证书,我如何验证一个是否与另一个私钥签名?

我有两个X509Certificate2.给他们打电话toCheckcheckWith.

如何检查是否toCheck由私钥签名checkWith

基本上,我希望C#等同于Java

toCheck.verify(checkWith.getPublicKey());
Run Code Online (Sandbox Code Playgroud)

谢谢

c# certificate x509certificate2 x509certificate

6
推荐指数
1
解决办法
724
查看次数

'等待'任务在哪里执行?

考虑以下:

private async void btnSlowPoke_Click(object sender, EventArgs e)
{
    await DoItAsync();
}

private async Task<int> SomeLongJobAsync()
{
    for (int x = 0; x < 999999; x++)
    {
        //ponder my existence for one second
        await Task.Delay(1000);
    }
    return 42;
}

public async Task<int> DoItAsync()
{
    Console.Write("She'll be coming round the mountain");
    Task<int> t = SomeLongJobAsync();  //<--On what thread does this execute?
    Console.WriteLine(" when she comes.");
    return await t;
}
Run Code Online (Sandbox Code Playgroud)
  1. 第一个写入DoItAsync()执行.
  2. SomeLongJobAsync() 开始.
  3. WriteLineDoItAsync()执行.
  4. DoItAsync()在 …

c# multithreading asynchronous task-parallel-library async-await

6
推荐指数
1
解决办法
287
查看次数

为什么我每次都遇到RemoteCertificateNameMismatch?

考虑以下完整程序:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace RemoteCertNameMismatchDiagnosis
{
class Program
{
    private static bool AcceptAllCertificates(object sender, X509Certificate certificate,
                                                                                        X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {
        Console.WriteLine(sslPolicyErrors.ToString());
        return true;
    }

    static void Main(string[] args)
    {
        TcpClient client;
        SslStream sslStream;

        bool acceptAnyCert = false;

        client = new TcpClient("google.com", 443);
        if (acceptAnyCert)
            sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(AcceptAllCertificates), null);
        else
            sslStream = new SslStream(client.GetStream(), false);

        try
        {
            sslStream.AuthenticateAsClient("test client");
        }
        catch (Exception …
Run Code Online (Sandbox Code Playgroud)

c# ssl x509certificate

4
推荐指数
1
解决办法
7384
查看次数

ProtectedData.Protect间歇性失败

我正在写一个密码加密例程.我写了下面的应用来说明我的问题.大约20%的时间,此代码按预期工作.其余时间,解密会引发加密异常 - "数据无效".

我认为问题出在加密部分,因为解密部分每次都是一样的.也就是说,如果加密例程产生解密例程可以解密的值,则它总是可以解密它.但是,如果加密例程产生一个阻塞解密例程的值,它总是会窒息.所以解密程序是一致的; 加密例程不是.

我怀疑我对Unicode编码的使用是不正确的,但我尝试过其他具有相同结果的人.

我究竟做错了什么?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;

namespace DataProtectionTest
{
    public partial class Form1 : Form
    {
        private static readonly byte[] entropy = { 1, 2, 3, 4, 1, 2, 3, 4 };
        private string password;
        public Form1()
        {
            InitializeComponent();
        }

        private void btnEncryptIt_Click(object sender, EventArgs e)
        {
            Byte[] pw = Encoding.Unicode.GetBytes(textBox1.Text);
            Byte[] encryptedPw = ProtectedData.Protect(pw, entropy, DataProtectionScope.LocalMachine);
            password = Encoding.Unicode.GetString(encryptedPw);     
        }

        private void …
Run Code Online (Sandbox Code Playgroud)

.net c# security encoding cryptography

3
推荐指数
1
解决办法
4234
查看次数

这个演员对IDisposable是否正确?

在MSFT的基于任务的异步模式白皮书(第11页)中,Stephen Toub有以下代码说明围绕Timer回调包装任务.

public static Task<DateTimeOffset> Delay(int millisecondsTimeout)
{
    var tcs = new TaskCompletionSource<DateTimeOffset>();
    new Timer(self =>
    {
        ((IDisposable)self).Dispose();  //<--this is the line in question
        tcs.TrySetResult(DateTimeOffset.UtcNow);
    }).Change(millisecondsTimeout, -1);
    return tcs.Task;
}
Run Code Online (Sandbox Code Playgroud)

在第6行,他演员selfIDisposable.如果我正确地读取这个lambda表达式,那么self会"转到"一个没有实现的TimerCallbackIDisposable.我读错了吗?

c# lambda task-parallel-library

1
推荐指数
1
解决办法
165
查看次数