小编Lir*_*man的帖子

如何将EventHandler作为方法参数传递

我正在尝试编写一个也会处理click事件的泛型方法,我希望允许用户将自己的方法作为click事件传递.像这样的东西:

public static void BuildPaging(
    Control pagingControl, short currentPage, short totalPages,  ???)
{
    for (int i = 0; i < totalPages; i++)
    {
        LinkButton pageLink = new LinkButton();
        ...
        pageLink.Click += ???;
        pagingControl.Controls.Add(paheLink);
    }
}
Run Code Online (Sandbox Code Playgroud)

我知道这是可能的,但我不记得怎么做了......

c# events delegates event-handling

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

如何在C#中的SSH服务器上运行命令?

我需要使用C#代码执行此操作:

  1. 在后台打开putty.exe(这就像一个cmd窗口)
  2. 使用其IP地址登录远程主机
  3. 输入用户名和密码
  4. 一个接一个地执行几个命令.
  5. 运行另一个命令,获取响应,告诉我在成功执行之前运行的命令

所以我试着这样做:

ProcessStartInfo proc = new ProcessStartInfo() 
{
     FileName = @"C:\putty.exe",
     UseShellExecute = true, //I think I need to use shell execute ?
     RedirectStandardInput = false,
     RedirectStandardOutput = false,
     Arguments = string.Format("-ssh {0}@{1} 22 -pw {2}", userName, hostIP, password)
     ... //How do I send commands to be executed here ?
};
Process.Start(proc);
Run Code Online (Sandbox Code Playgroud)

.net c# ssh ssh.net

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

作为 Windows 服务托管的 .net 核心 - 如何使用配置文件?

我有一个 .Net Core 2 WebAPI,我希望它作为 Windows 服务运行。默认情况下,该服务在http://localhost:5000. 当我在本地运行它时,我使用一个hosting.json文件在那里设置 IP 和端口,但由于某种原因,当我尝试使用配置文件时,该服务将无法启动。

这是我的代码:

public static void Main(string[] args)
{
    var config = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddJsonFile("hosting.json", optional: false, reloadOnChange: true)
        .AddCommandLine(args)
        .Build();

    if (Debugger.IsAttached || args.Contains("--console"))
        BuildWebHost(config, args).Run();
    else
        BuildServiceWebHost(config, args).RunAsService();
}

public static IWebHost BuildWebHost(IConfigurationRoot config, string[] args)
{
    return WebHost.CreateDefaultBuilder(args)
        .UseConfiguration(config)
        .UseStartup<Startup>()
        .Build();
}

public static IWebHost BuildServiceWebHost(IConfigurationRoot config, string[] args)
{
    var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
    var pathToContentRoot = Path.GetDirectoryName(pathToExe);

    var …
Run Code Online (Sandbox Code Playgroud)

asp.net-core-2.0

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

是否有 Microsoft.Office.Interop.Excel 的替代库?

我使用Microsoft.Office.Interop.Excel参考是为了对 excel 文件进行一些操作,例如添加列、锁定单元格、使用密码保护等...

现在我必须在没有安装 office 的服务器上使用此代码,所以我不确定使用此引用的代码是否能够在那里运行。那么有没有办法在没有安装办公室的服务器上对 excel 文件执行所有这些操作?我应该使用另一个图书馆还是有一种方法可以在Microsoft.Office.Interop.Excel没有安装办公室的情况下工作?

c# excel

6
推荐指数
2
解决办法
8093
查看次数

如何向web api 2获取请求发送整数列表?

我正在尝试完成此任务,我需要将一个id(整数)列表发送到web api 2 get请求.

所以我在这里找到了一些样品,它甚至有一个示例项目,但它不起作用......

这是我的web api方法代码:

[HttpGet]
[Route("api/NewHotelData/{ids}")]
public HttpResponseMessage Get([FromUri] List<int> ids)
{
    // ids.Count is 0
    // ids is empty...
}
Run Code Online (Sandbox Code Playgroud)

这是我在fiddler中测试的URL:

http://192.168.9.43/api/NewHotelData/?ids=1,2,3,4
Run Code Online (Sandbox Code Playgroud)

但是列表始终为空,并且没有任何id传递给该方法.

似乎无法理解问题出在方法,URL或两者中......

那怎么可能实现呢?

c# get-request asp.net-web-api2

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

在 ubuntu 上运行控制台应用程序时出现 .net core 2.0 错误

我正在尝试在 ubuntu 16.04-x64 上运行我的第一个 .net core 2.0 控制台应用程序。我按照以下步骤为 ubuntu 发布我的应用程序:

dotnet publish -c release -r ubuntu.16.04-x64
Run Code Online (Sandbox Code Playgroud)

并通过更改我的 .csproj 文件从 Visual Studio 尝试它,如下所示:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.0</TargetFramework>
    <RuntimeIdentifiers>ubuntu.16.04-x64</RuntimeIdentifiers>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="sharpadbclient" Version="2.1.0" />
    <PackageReference Include="System.IO.Ports" Version="4.4.0" />
  </ItemGroup>

</Project>
Run Code Online (Sandbox Code Playgroud)

然后使用发布配置文件发布它。

我按照 Microsoft 的说明在 ubuntu 上安装 .net core。当我尝试运行控制台应用程序的 .dll 文件时,我将发布的输出复制到运行 ubuntu ans 的 PC 我收到此错误:

Unhandled Exception: System.IO.FileLoadException: 
Could not load file or assembly
'System.Console, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
The located assembly's manifest definition does not match the assembly …
Run Code Online (Sandbox Code Playgroud)

c# ubuntu .net-core asp.net-core

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

.net core - 如何正确终止已启动的进程?

我有一个 dotnet core 2.0 控制台应用程序,可以启动另一个 dotnet core WebAPI。问题是,当控制台应用程序关闭时,如何干净地终止 WebAPI 进程?因为到目前为止,我无法启动该进程两次,因为它给出了地址正在使用的错误,我仍然可以在任务管理器中看到该进程。

这是我尝试这样做的方式,但似乎缺少完全杀死所有进程的东西:

class Program
{
    static Process cmd;

    static async Task Main(string[] args)
    {
        AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;

        var startInfo = new ProcessStartInfo("cmd.exe")
        {
            UseShellExecute = false,
            RedirectStandardInput = true,
            CreateNoWindow = true,
        };

        cmd = new Process { StartInfo = startInfo };

        cmd.Start();

        using (cmd)
        {
            cmd.StandardInput.WriteLine($"cd C:/Project/publish");
            cmd.StandardInput.WriteLine($"dotnet WebAPI.dll");
            cmd.WaitForExit();
        }
    }

    static void CurrentDomain_ProcessExit(object sender, EventArgs e)
    {
        Process.GetProcessById(cmd.Id).Kill();
        Environment.Exit(0);
    }
}
Run Code Online (Sandbox Code Playgroud)

c# asp.net-core-2.0

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

消费者“收到”事件未触发

我正在尝试设置对 RabbitMQ 队列的订阅并将其传递给自定义事件处理程序。所以我有一个名为的类RabbitMQClient,其中包含以下方法:

public void Subscribe(string queueName, EventHandler<BasicDeliverEventArgs> receivedHandler)
{
    using (var connection = factory.CreateConnection())
    {
        using (var channel = connection.CreateModel())
        {
            channel.QueueDeclare(
                queue: queueName,
                durable: false,
                exclusive: false,
                autoDelete: false,
                arguments: null
            );

            var consumer = new EventingBasicConsumer(channel);

            consumer.Received += receivedHandler;

            channel.BasicConsume(
                queue: queueName,
                autoAck: false,
                consumer: consumer
            );
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在使用依赖注入,所以我有一个RabbitMQClient(单例)接口。

在我的消费类中,我有这个方法,我想充当 EventHandler

public void Consumer_Received(object sender, BasicDeliverEventArgs e)
{
    var message = e.Body.FromByteArray<ProgressQueueMessage>();
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试像这样订阅队列:

rabbitMQClient.Subscribe(Consts.RabbitMQ.ProgressQueue, Consumer_Received);
Run Code Online (Sandbox Code Playgroud)

我可以看到队列开始获取消息,但该Consumer_Received方法没有触发。

我在这里缺少什么?

c# rabbitmq

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

.Net Core 3 IStringLocalizer.WithCulture(CultureInfo)已过时

我已经将项目从.Net Core 2.2升级到.Net Core 3.0。

在尝试解决所有警告和错误之后,我现在尝试为该警告的解决方案提供资金:

'IStringLocalizer.WithCulture(CultureInfo)' is obsolete: 'This method is obsolete.
 Use `CurrentCulture` and `CurrentUICulture` instead.'
Run Code Online (Sandbox Code Playgroud)

我正在使用它来更改每个登录用户的网站语言。我有此实现可更改每个用户的网站文化:

public class CultureLocalizer : ICultureLocalizer
{
    private readonly IStringLocalizer localizer;
    public CultureLocalizer(IStringLocalizerFactory factory)
    {
        var type = typeof(Resources.PageResources);
        var assemblyName = new AssemblyName(type.GetTypeInfo().Assembly.FullName);
        localizer = factory.Create("PageResources", assemblyName.Name);
    }

    // if we have formatted string we can provide arguments         
    // e.g.: @Localizer.Text("Hello {0}", User.Name)
    public LocalizedString Get(string key, params string[] arguments)
    {
        return arguments == null ? localizer[key] : localizer[key, arguments];
    } …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-core asp.net-core-3.0

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

如何获取枚举值和描述的列表?

我有以下枚举:

public enum AlertSeverity
    {
        [Description("Informative")]
        Informative = 1,

        [Description("Low risk")]
        LowRisk = 2,

        [Description("Medium risk")]
        MediumRisk = 3,

        [Description("High risk")]
        HighRisk = 4,

        Critical = 5
    }
Run Code Online (Sandbox Code Playgroud)

我想获得List<KeyValuePair<string, int>>所有描述/名称和值,所以我尝试了这样的事情:

public static List<KeyValuePair<string, int>> GetEnumValuesAndDescriptions<T>() where T : struct
    {
        var type = typeof(T);
        if (!type.IsEnum)
            throw new InvalidOperationException();
        List<KeyValuePair<string, int>> lst = new List<KeyValuePair<string, int>>();
        foreach (var field in type.GetFields())
        {
            var attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute; // returns null ???
            if (attribute != null)
                lst.Add(new …
Run Code Online (Sandbox Code Playgroud)

enums

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