小编Erw*_*yer的帖子

.NET中从1,10和2开始排序字符串并遵守数字排序的最短路径是什么?

我需要按如下方式对文件名进行排序:1.log,2.log,10.log

但是当我使用OrderBy(fn => fn)时,它会将它们排序为:1.log,10.log,2.log

我显然知道这可以通过编写另一个比较器来完成,但有没有更简单的方法从词典顺序转换为自然排序顺序?

编辑:目标是获得与在Windows资源管理器中选择"按名称排序"时相同的顺序.

.net c# sorting string lexicographic

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

实现索引队列的有效方法(在O(1)时间内可以通过索引检索元素)?

根据.NET队列ElementAt性能,使用ElementAt按索引访问项目显然不是一个合理的选择.

是否有适合此要求的替代通用数据结构?

我的队列有固定的容量.

根据Queue类上的MSDN条目," 此类将队列实现为循环数组 ",但它似乎没有公开任何类型的索引属性.

更新:我找到了C5的CircularQueue实现.这似乎符合要求,但如果可能,我宁愿不必导入另一个外部库.

.net c# indexing queue performance

9
推荐指数
2
解决办法
3201
查看次数

我真的被迫ReadToEnd()读取Ionic.Zlib.GZipStream的StreamReader吗?

我使用以下代码解压缩GZipStream(使用DotNetZip库),其中fs是指向gz文件的文件流(使用FileMode.Open,FileAccess.Read,FileShare.ReadWrite):

using (var gz = new GZipStream(fs, CompressionMode.Decompress)) {
    using (var sr = new StreamReader(gz)) {
         header = sr.ReadLine();
    }
}
Run Code Online (Sandbox Code Playgroud)

但是如果直到最后才读取文件(我不喜欢这样做,因为文件可能很大),它会抛出

ZlibException("Bad CRC32 in GZIP trailer. (actual(EC084966)!=expected(8FC3EF16))")

在第一个结束括号(实际上当试图关闭()StreamReader时.

现在如果在关闭流读取器之前调用ReadToEnd()(或者我使用while(!sr.EndOfStream)循环读取所有行),它就可以工作.我观察到500 MB和200 kB压缩文件的相同行为,因此它似乎与文件大小无关.

非常欢迎您的见解!

这是一个简单的专用测试项目的链接.

它适用于System.IO.GZipStream库,所以这很奇怪.

.net c# compression gzip streamreader

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

对于WCF服务,没有证书的TransportWithMessageCredential是否足够安全?

我开发了一个WCF自托管服务,我有两个基本的安全要求,因为它将通过Internet访问:

  • 传输层应防止篡改和嗅探,尤其是检索身份验证凭据.这就是SSL所做的,但从我所看到的设置SSL需要安装证书(除非可能通过这种使用普通证书文件的hack),我不想这样做.

  • 身份验证层应包含用户名/密码验证程序.

我配置我的服务使用:

      <security mode="TransportWithMessageCredential">
        <message clientCredentialType="UserName" />
        <transport clientCredentialType="Basic" />
      </security>
Run Code Online (Sandbox Code Playgroud)

即使传输层是HTTP(而不是HTTPS),这是否会使WCF创建另一个与SSL等效的安全层?如果没有,安全强度方面有什么不同?

另外,有没有办法在不使用SSL证书的情况下保护元数据端点(不是必需但会受到赞赏)?

这是我自托管服务的完整配置代码:

<?xml version="1.0"?>
<configuration>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup>
  <system.serviceModel>
    <services>
      <service name="MyService">
        <host>
          <baseAddresses>
            <add baseAddress = "http://localhost:8000/Services" />
          </baseAddresses>
        </host>
        <endpoint address ="MyService" binding="wsHttpBinding" contract="IMyService">
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </services>
    <bindings>
      <wsHttpBinding>
        <binding name="Binding1" maxReceivedMessageSize="2147483647">
          <security mode="TransportWithMessageCredential">
            <message clientCredentialType="UserName" />
            <transport clientCredentialType="Basic" />
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="True"/>
          <serviceCredentials>
            <userNameAuthentication userNamePasswordValidationMode="Custom" …
Run Code Online (Sandbox Code Playgroud)

.net c# security wcf web-services

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

在React无状态组件中TypeScript相当于rest/spread props

我正在尝试将以下函数从bootstrap-react 文档中添加到我的TypeScript + React项目中:

function FieldGroup({ id, label, help, ...props }) {
    return (
        <FormGroup controlId={id}>
            <ControlLabel>{label}</ControlLabel>
            <FormControl {...props} />
            {help && <HelpBlock>{help}</HelpBlock>}
        </FormGroup>
    );
}
Run Code Online (Sandbox Code Playgroud)

但是,TypeScript版本<2.1不支持用作参数的ECMAScript 6的rest/spread属性.

我目前的实施是:

interface FieldGroupProps extends React.HTMLAttributes {
    id?: string;
    label?: string;
    help?: string;
}

class FieldGroup extends React.Component<FieldGroupProps, {}> {
    public render(): JSX.Element {
        const rest = objectWithout(this.props, ["id", "label", "help"]);
        return (
            <FormGroup controlId={this.props.id}>
                <ControlLabel>{this.props.label}</ControlLabel>
                <FormControl {...rest} />
                {this.props.help && <HelpBlock>{this.props.help}</HelpBlock>}
            </FormGroup>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

这在功能上(不是从性能角度来看)等同于ECMAScript 6版本吗?如果我错过了某些东西或者它可以变得更优雅,那么推荐使用上述rest/spread语法的方法是什么?

javascript typescript reactjs

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

如何在导入MySQL转储文件时覆盖ENGINE = INNODB参数?

我有一个很大的转储(几十GB),我想将它导入一个新表而不考虑ENGINE = INNODB参数.

我试了几个编辑器专用于大型文件编辑转储,但它总是需要花费大量的时间去保存修改,所以它将使更多的意义,只是忽略ENGINE = INNODB参数使用默认引擎覆盖它(例如).

导入然后更改引擎将不是一个选项,因为InnoDB导入转储的速度非常慢,因此需要数天时间.

mysql database import innodb mysqldump

8
推荐指数
2
解决办法
3672
查看次数

StreamWriter.Flush()还会调用FileStream.Flush()吗?

我有一个StreamWriter,底层流是一个FileStream.将下面的代码保证的FileStream同时刷新其缓存到文件系统中的实际文件,或者我需要显式调用Flush()FileStream

using (var fs = new FileStream("blabla", FileMode.Append)) {
    using (var sw = new StreamWriter(fs)) {
        sw.WriteLine("Hello, I want to be flushed.");
        sw.Flush(); //I need this to also flush onto the file, not just to the FileStream
    }
}
Run Code Online (Sandbox Code Playgroud)

根据MSDN," 刷新流不会刷新其底层编码器,除非您明确调用Flush或Close ",但我不知道FileStream是否可以被视为"底层编码器".

此外,如果我没有指定FileOptions.WriteThrough,我保证操作系统最终会将刷新的行写入磁盘,即使程序在两个流关闭之前崩溃(假设例如没有using {}块,只调用Flush())?

在我的场景中,我需要保持流打开(用于记录),所以我不能使用using {}块,但我想确保即使程序崩溃,数据也将始终写入磁盘.如果电源关闭并且操作系统没有刷新到磁盘上,我可以负担得起丢失数据,但是否则我需要操作系统最终刷新,即使我从未正确调用Close()流.

.net c# flush stream filestream

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

使用Noda Time,如何使用LocalDate和LocalTime创建LocalDateTime

我有一个LocalDate和一个LocalTime,并希望简单地从它们创建一个LocalDateTime结构.我想到了以下扩展方法,我认为这是最快的但是由于一个不明原因,当前版本的API中不存在字段localTime.TickOfMillisecond.所以它不起作用.

    public static LocalDateTime At(this LocalDate localDate, LocalTime localTime) {
        return new LocalDateTime(localDate.Year, localDate.Month, localDate.Day, localTime.Hour, localTime.Minute, localTime.Second, localTime.Millisecond, localTime.TickOfMillisecond);
    }
Run Code Online (Sandbox Code Playgroud)

那么,我是不是在平时使用:

    public static LocalDateTime At(this LocalDate localDate, LocalTime localTime) {
        return localDate.AtMidnight().PlusTicks(localTime.TickOfDay);
    }
Run Code Online (Sandbox Code Playgroud)

任何建议表示赞赏.

.net c# datetime nodatime

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

使用EnvDTE.ExecuteCommand以编程方式开始调试特定项目

我有一个包含多个启动项目的解决方案,我试图在每晚自动重新启动其中一个,同时保持新进程连接到同一个调试器.

我能够重新启动进程(使用Process.Start)并将当前调试器附加到它,但到目前为止它还不是很可靠,并且按照设计,单击"停止"按钮只会从进程中分离而不是终止它.

我知道Visual Studio团队已经发布了一个Visual Studio扩展,允许自动将子进程附加到当前调试器,这可能比我的代码更好,但它不可移植,因为它需要本地配置.

实现我需要的最简单的方法似乎是使用IDE本身以编程方式重新启动项目,就像我手动右键单击项目并选择Debug> Start New Instance一样.我可以在我的代码中访问相关的DTE对象(在开发中).

因此,有没有办法使下面的伪代码工作,要求Visual Studio 通过将其作为命令参数传递来开始调试特定项目/ exe?

DTE.ExecuteCommand("ClassViewContextMenus.ClassViewProject.Debug.Startnewinstance", "ProjectToBeRestarted");

DTE.ExecuteCommand("Debug.Start", "ProjectToBeRestarted");

DTE.ExecuteCommand("Debug.Start", "ProjectToBeRestarted.exe");
Run Code Online (Sandbox Code Playgroud)

我想尽可能避免操纵UI(比如存储原始启动项目,设置新项目,以及恢复启动项目).

c# debugging scripting automation visual-studio

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

是什么导致asyncio.new_event_loop()的简单调用挂起?

我使用以下函数强制协程同步运行:

import asyncio
import inspect
import types
from asyncio import BaseEventLoop
from concurrent import futures


def await_sync(coro: types.CoroutineType, timeout_s: int=None):
    """

    :param coro: a coroutine or lambda loop: coroutine(loop)
    :param timeout_s:
    :return:
    """
    loop = asyncio.new_event_loop()  # type: BaseEventLoop
    if not is_awaitable(coro):
        coro = coro(loop)
    if timeout_s is None:
        fut = asyncio.ensure_future(coro, loop=loop)
    else:
        fut = asyncio.ensure_future(asyncio.wait_for(coro, timeout=timeout_s, loop=loop), loop=loop)
    loop.run_until_complete(fut)
    return fut.result()

def is_awaitable(coro_or_future):
    if isinstance(coro_or_future, futures.Future):
        return coro_or_future
    elif asyncio.coroutines.iscoroutine(coro_or_future):
        return True
    elif asyncio.compat.PY35 and inspect.isawaitable(coro_or_future):
        return True …
Run Code Online (Sandbox Code Playgroud)

python event-loop hang coroutine python-asyncio

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