小编Lir*_*man的帖子

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

我有以下枚举:

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
查看次数

Javascript String.fromCharCode返回错误的值

我有这个Knockout自定义绑定来验证文本框只包含英文字母.但是,似乎Javascript的String.fromCharCode返回错误值.

例如,希伯来字母"ש"以英文字母"A "返回,而右边数字键盘中的数字"1"返回为"a"...

这是我的Knockout绑定:

var arrValidKeys = [8, 16, 17, 20, 35, 36, 37, 39, 46];
    ko.bindingHandlers.validateText = {
        init: function (element, valueAccessor) {
            $(element).on("keydown", function (event) {

                //Regex pattern: allow only (A to Z uppercase, a to z lowercase)
                var englishAlphabet = /[A-Za-z]/g;

                // Retrieving the key from the char code passed in event.which
                var key = String.fromCharCode(event.which);

                // keyCodes list: http://stackoverflow.com/a/3781360/114029
                // check that the key is valid with the above Regex
                valueAccessor()($(this).val()); …
Run Code Online (Sandbox Code Playgroud)

javascript knockout.js

5
推荐指数
0
解决办法
1060
查看次数

C#context.Response.OutputStream.Write希伯来字符

我正在尝试使用以下代码将报告导出到csv:

byte[] csvBytes = AttachmentFileAgent.GetAttachmentFilesCSVBytes(context.Request["appCode"], performingPerson);
context.Response.AddHeader("content-disposition", "attachment; filename=ApplicationReport_" + context.Request["appCode"] + ".csv");
context.Response.ContentType = "text/csv;charset=utf-8";
context.Response.Charset = "utf-8";
context.Response.ContentEncoding = Encoding.UTF8;
context.Response.OutputStream.Write(csvBytes, 0, csvBytes.Length);
Run Code Online (Sandbox Code Playgroud)

但是希伯来文的内容却是胡言乱语('>''''''''''''''''').我试过各种编码(UTF8,Unicode,ASCII),但没有任何作用......

c#

5
推荐指数
0
解决办法
638
查看次数

Android - 如何通过用户名以编程方式切换用户?

我是 Android 新手,我必须在工作中创建一个执行以下任务的应用程序:

  1. 我监听一个应该向我发送用户名的套接字。
  2. 收到用户名后,我需要在平板电脑上切换到该用户帐户。
  3. 如果我收到与当前活动用户相同的用户名,我不需要切换(显然)。

我们的平板电脑已获得 root 权限并运行 CyanogenMod 12.1 和 Android 5.1.1 Lollipop。由于这不是从 Play 商店下载的商业版本,我可以假设我可能需要的所有权限都会被授予。

我搜索了一种干净的代码方法来做到这一点,而无需运行 shell 命令或其他黑客,但找不到任何东西......

android

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

如何摆脱.net核心2.2中的CORS?

我已将我的项目更新为.net core 2.2,看起来CORS正在制造2.1中没有的问题.

我在这个网址上运行我的应用: http://*:5300

我在以下代码中添加了此代码Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    ...

    services.AddCors(options =>
                     options.AddPolicy("MyPolicy", builder =>
                     {
                         builder.AllowAnyOrigin()
                                .AllowAnyMethod()
                                .AllowCredentials()
                                .AllowAnyHeader();
                     }));

    services.AddMvc();

    ...
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    ...

    app.UseCors(builder =>
    {
        builder.AllowAnyOrigin()
               .AllowAnyMethod()
               .AllowCredentials()
               .AllowAnyHeader();
    });

    app.UseAuthentication();
    app.UseMvc();
}
Run Code Online (Sandbox Code Playgroud)

这不起作用,所以我在其上添加[EnableCors]了我的`BaseController"类的属性:

[EnableCors]
[Authorize]
[Produces("application/json")]
[Route("api/[controller]")]
public class BaseController : Controller
{

}
Run Code Online (Sandbox Code Playgroud)

但我仍然收到此CORS错误:

来自' http://192.168.15.63:5302 '的' http://192.168.15.63:5301/api/permissions/UI ' 访问XMLHttpRequest 已被CORS策略阻止: 对预检请求的响应未通过访问控制检查: 当请求的凭据模式为"包含"时,响应中的"Access-Control-Allow-Origin"标头的值不能是通配符"*". XMLHttpRequest发起的请求的凭据模式由withCredentials属性控制.


我还能做些什么来彻底删除CORS?

c# asp.net-core asp.net-core-2.2

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

单个 MongoDB 实例上的 C# MongoDB 驱动程序事务

我正在使用 MongoDB 4.0.8 和 C# 驱动程序 2.8.1,并尝试Transactions在我的项目中实现。我复制粘贴了以下代码示例:

static async Task<bool> UpdateProducts()
{
    //Create client connection to our MongoDB database
    var client = new MongoClient(MongoDBConnectionString);

    //Create a session object that is used when leveraging transactions
    var session = client.StartSession();

    //Create the collection object that represents the "products" collection
    var products = session.Client.GetDatabase("MongoDBStore").GetCollection<Product>("products");

    //Clean up the collection if there is data in there
    products.Database.DropCollection("products");

    //Create some sample data
    var TV = new Product { Description = "Television", SKU = 4001, …
Run Code Online (Sandbox Code Playgroud)

c# mongodb

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

C# - 将xls文件转换为没有office组件的xlsx

我有一台服务器,不能安装任何办公室,所以我使用ClosedXML对excel文件进​​行一些操作.但ClosedXML仅适用于.xlsx文件,我也有xls文件来处理.我花了差不多一整天时间寻找一种方法将.xls文件转换为.xlsx文件,而不使用任何办公室库(因为我的指定服务器上没有安装办公室...)

有人可以告诉我如何将这些.xls文件转换为.xlsx文件?我无法使用Microsoft.Office.Interop,因为它需要在服务器上安装Office.

c# excel

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

C# mongodb - 如何更新嵌套数组元素

我有以下表示项目的 JSON 结构

{
    Id: "a",
    Array1: [{
        Id: "b",
        Array2: [{
            Id: "c",
            Array3: [
                {...}
            ]
        }]
    }]
}
Run Code Online (Sandbox Code Playgroud)

我需要能够Array2用新项目替换数组元素或仅用Array3新数组替换。

这是我替换数组项的代码Array2

await Collection.UpdateOneAsync(
    item => item.Id.Equals("a") &&
    item.Array1.Any(a => a.Id.Equals("b")) &&
    item.Array1[-1].Array2.Any(b => b.Id.Equals("c")),
    Builders<Item>.Update.Set(s => s.Array1[-1].Array2[-1], newArray2Item)
);
Run Code Online (Sandbox Code Playgroud)

执行此代码时,我收到此错误:

"A write operation resulted in an error.
 Too many positional (i.e. '$') elements found in path 'Array1.$.Array2.$'"
Run Code Online (Sandbox Code Playgroud)

这里是我的代码来替换Array3Array2

await Collection.UpdateOneAsync(
        item => item.Id.Equals("a") &&
        item.Array1.Any(a => a.Id.Equals("b")) && …
Run Code Online (Sandbox Code Playgroud)

mongodb mongodb-.net-driver

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

Asp.net Core 2.1-如何提供多个角度应用程序?

我试图从我的.net核心服务中提供2个角度应用程序,如下所示:

public void ConfigureServices(IServiceCollection services)
{
    ...

    services.AddSpaStaticFiles(configuration =>
    {
        configuration.RootPath = "wwwroot/app";
    });

    services.AddSpaStaticFiles(configuration =>
    {
        configuration.RootPath = "wwwroot/admin";
    });

    ...
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    ...

    app.UseSpaStaticFiles(new StaticFileOptions
    {
        OnPrepareResponse = ctx =>
        {
            ctx.Context.Response.Headers.Append("Cache-Control", "public,max-age=0");
        }
    });

    app.UseMvc();

    app.Map("/app", client =>
    {
        client.UseSpa(spa =>
        {
            spa.Options.SourcePath = "wwwroot/app";
        });
    }).Map("/admin", admin =>
    {
        admin.UseSpa(spa =>
        {
            spa.Options.SourcePath = "wwwroot/admin";
        });
    });
}
Run Code Online (Sandbox Code Playgroud)

在文件系统中,我只有dist这些应用程序的输出(因为它们是由另一个团队开发的)。所以看起来像这样:

  • C:[我的项目路径] \ wwwroot \ app
  • C:[我的项目路径] \ …

asp.net-core asp.net-core-webapi asp.net-core-2.1

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

C# MongoDB 驱动程序 - 如何按数组和项目列表进行过滤

我想对字符串数组执行搜索并将其与字符串列表中的任何字符串进行比较。例如:

这是数据结构:

{
    "CategoryIds": [ "A123", "B456", "C789" ]
}
Run Code Online (Sandbox Code Playgroud)

这是搜索词:

List<string> search = new List<string> { "A123", "C789" };
Run Code Online (Sandbox Code Playgroud)

我正在动态构建搜索查询,因此我定义了以下内容:

var builder = Builders<Item>.Filter;
ar filters = Builders<Item>.Filter.Empty;
Run Code Online (Sandbox Code Playgroud)

我已尝试过以下所有方法,但没有一个有效:

使用ElemMatch

filters &= builder.ElemMatch(i => i.CategoryIds, id => search.CategoryIds.Any(i => i.Equals(id)));
Run Code Online (Sandbox Code Playgroud)

使用Intersect

filters &= builder.Where(i => search.CategoryIds.Intersect(i.CategoryIds).Any());
Run Code Online (Sandbox Code Playgroud)

唯一有效的就是这个:

var categoryFilters = new List<FilterDefinition<Item>>();

foreach (string id in search.CategoryIds)
    categoryFilters.Add(builder.AnyEq(i => i.CategoryIds, id));

if (categoryFilters.Any())
    filters &= builder.Or(categoryFilters);
Run Code Online (Sandbox Code Playgroud)

但这似乎有点矫枉过正。有更简单的方法吗?

c# mongodb mongodb-.net-driver

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