GVKun编程网logo

遍历 Linq fluent API 方法 (C#)(fluent journal循环批处理)

15

如果您想了解遍历LinqfluentAPI方法(C#)的相关知识,那么本文是一篇不可错过的文章,我们将对fluentjournal循环批处理进行全面详尽的解释,并且为您提供关于'InfluxDBCli

如果您想了解遍历 Linq fluent API 方法 (C#)的相关知识,那么本文是一篇不可错过的文章,我们将对fluent journal循环批处理进行全面详尽的解释,并且为您提供关于'InfluxDBClient' 对象在 Python 和 Docker 中没有属性 'api_client'、.Net Web Api中利用FluentValidate进行参数验证的方法、23.3 Fluent builder API 快速构建API、ASP.NET Core WebApi中使用FluentValidation验证数据模型的方法的有价值的信息。

本文目录一览:

遍历 Linq fluent API 方法 (C#)(fluent journal循环批处理)

遍历 Linq fluent API 方法 (C#)(fluent journal循环批处理)

如何解决遍历 Linq fluent API 方法 (C#)?

我正在寻找一种方法来遍历先前构建的 Linq 方法集合,然后操作它们,例如更改表达式树。

这是一个例子:

enter image description here

我只想做的是一个 forEach(或类似的东西)来获得一个循环:

我在第一个位置得到 linq .Where(e => e.Summary == "sum")

我在第二个位置得到 linq .Where(l => l.Description == "asd")

我在最后一次迭代中得到了 linq .Take(2)

这可能吗?最有可能通过反思,但我可以做到或找到。

其他示例

使用上面的示例,我想查看 Ienumerable/Iqueryable 并获取第一个 where,获得 等价 结果:

var c = list
        .Where(e => e.Summary == "sum");

让我强调一下,我希望通过运行时使用 Ienumerable/Iqueryable 作为输入。

谢谢,

解决方法

我认为最简单的方法是创建新函数(例如 _Where()_Take()),这些函数只调用 WhereTake 函数,而且保存您调用它们以及使用哪些参数这一事实。稍后您可以再次阅读它们。

这样做的缺点是您需要以某种方式存储哪些调用属于哪个调用。 IE。如果您有两个语句 list.Where().Where()list.Where().Take(),您需要保存哪些调用属于第一行,哪些属于第二行。

你也可以尝试让这些特殊的函数返回一个包含结果和调用信息的元组。然后你应该为每个 linq 方法创建两个函数:一个只接受一个可枚举的,一个接受一个可枚举的元组和之前的调用信息。通过这种方式,您可以将新的通话信息添加到旧的通话信息中。如果使用扩展函数,当然要扩展可枚举和元组。

编辑

让我补充一个我的想法的例子......注意,很难完美地序列化Where函数中给出的函数。有可能,例如检查 Convert Func delegate to a string

Overloads.cs:

public static class Overloads
{
    public static (IEnumerable<T>,List<string>) Where_<T>(this IEnumerable<T> inp,Func<T,bool> predicate)
    {
        return (inp.Where(predicate),new List<string> { ".Where(...)" });
    }

    public static (IEnumerable<T>,List<string>) Where_<T>(this (IEnumerable<T>,List<string>) inp,bool> predicate)
    {
        inp.Item2.Add(".Where(...)");
        return (inp.Item1.Where(predicate),inp.Item2);
    }

    public static (IEnumerable<T>,List<string>) Take_<T>(this IEnumerable<T> inp,int count)
    {
        return (inp.Take(count),new List<string> { $".Take({count})" });
    }

    public static (IEnumerable<T>,List<string>) Take_<T>(this (IEnumerable<T>,int count)
    {
        inp.Item2.Add($".Take({count})");
        return (inp.Item1.Take(count),inp.Item2);
    }
}

示例运行:

public static void Main(string[] args)
{
    var a = new List<int> { 0,1,2,3,4,5,6,7,8,9 };

    var (result,calls) = a
        .Where_(x => x % 2 == 0)
        .Where_(x => x % 3 == 0)
        .Take_(1);

    Console.WriteLine(string.Join(",",result));
    Console.WriteLine(string.Join(",calls));
}

输出:

0
.Where(...),.Where(...),.Take(1)

'InfluxDBClient' 对象在 Python 和 Docker 中没有属性 'api_client'

'InfluxDBClient' 对象在 Python 和 Docker 中没有属性 'api_client'

如何解决''InfluxDBClient'' 对象在 Python 和 Docker 中没有属性 ''api_client''?

我正在尝试使用 python 脚本将 JSON 文件插入到 influxDB 数据库中。
我所有的脚本都是通过 Docker 容器化的。
每次我尝试打开连接以插入 json 日志时都告诉我 ''InfluxDBClient'' object has no attribute ''api_client''

我尝试了很多不同的配置,这是实际的配置:

from influxdb_client import InfluxDBClient,Point,WriteOptions
from dotenv import load_dotenv
import json
import os

class DB():

    # Method to open connection
    @classmethod
    def open_con(cls):
        load_dotenv()
        cls.token = os.getenv(''INFLUXDB_V2_TOKEN'')
        cls.org = os.getenv(''INFLUXDB_V2_ORG'')
        cls.bucket = os.getenv(''INFLUXDB_V2_BUCKET'')
        cls.url = "http://influxdb:8086"
        cls.client = InfluxDBClient(url=cls.url,token=cls.token,org=cls.org)
        print(''Connected'')
        cls.write_api = cls.client.write_api(write_options=WriteOptions(batch_size=500,flush_interval=10_000,jitter_interval=2_000,retry_interval=5_000,max_retries=5,max_retry_delay=30_000,exponential_base=2))

    # Method to close connection
    @classmethod
    def close_con(cls):
        cls.client.close()

    # Method to insert JSON
    @classmethod
    def insert_json(cls,file):
        cls.open_con()
        with open(file) as f:
            file_data = json.load(f)
        cls.write_api.write(bucket=cls.bucket,org=cls.org,record=file_data)
        cls.close_con()
        print(f''Json inséré'')

这是我的 Docker compose 文件:

version: "3.8"

services:
  buffer:
    image: buffer:1.0
    build:
      context: ./insert
      dockerfile: Dockerfile
    container_name: buffer
    restart: unless-stopped
    volumes:
      - ./json_files:/app/json_files
    depends_on: 
      - influxdb
  influxdb:
    image: influxdb
    container_name: influxdb
    restart: always
    ports:
      - "8086:8086"
    volumes:
      - influxdbv2:/.influxdbv2
  influxdb_cli:
    links:
      - influxdb
    image: influxdb:1.7
    container_name: influxdb_cli
    entrypoint: influx setup --bucket ${INFLUXDB_V2_BUCKET} -t ${INFLUXDB_V2_TOKEN} -o ${INFLUXDB_V2_ORG} --username=${INFLUXDB_USERNAME} --password=${INFLUXDB_PASSWORD} --host=http://influxdb:8086 -f
    restart: on-failure:10
    depends_on: 
      - influxdb
volumes:
  influxdbv2:

最后这是我要插入的 json 格式:

[
  {
    "measurement": "BTC @ 14/03/2021 16:52:33","tags": {
        "crypto_name": "Bitcoin","crypto_symbol": "BTC"
    },"time": "14/03/2021 16:52:33","fields": {
        "name": "Bitcoin","symbol": "BTC","currency": "$","value": 59623.19,"market_cap": 1110000000000,"volume": 17680000000}
  },...
]

这是Docker logs buffer给出的消息(缓冲区是尝试将json插入到influxdb的脚本):

Traceback (most recent call last):
    File "./app/buffer.py",line 5,in <module>
        from influxdb_connection import DB
    File "/app/influxdb_connection.py",line 36,in <module>
        DB.open_con()
    File "/app/influxdb_connection.py",line 17,in open_con
        cls.client = InfluxDBClient(url=cls.url,org=cls.org)
    File "/usr/local/lib/python3.8/site-packages/influxdb_client/client/influxdb_client.py",line 62,in __init__
    auth_header_value = "Token " + auth_token
TypeError: can only concatenate str (not "nonetype") to str
Exception ignored in: <function InfluxDBClient.__del__ at 0x7f064f97b040>
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/site-packages/influxdb_client/client/influxdb_client.py",line 171,in __del__
    if self.api_client:
AttributeError: ''InfluxDBClient'' object has no attribute ''api_client''

编辑:

我将此行添加到我的 docker compose 中。

...
env_file:
    - .env
...

.env 是我的环境文件的名称。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

.Net Web Api中利用FluentValidate进行参数验证的方法

.Net Web Api中利用FluentValidate进行参数验证的方法

前言

本文主要介绍了关于.Net Web Api用FluentValidate参数验证的相关内容,下面话不多说了,来一起看看详细的介绍吧。

方法如下

安装FluentValidate

在ASP.NET Web Api中请安装 FluentValidation.WebApi版本

创建一个需要验证的Model

 public class Product 
 {
  public string name { get; set; }
  public string des { get; set; }
  public string place { get; set; }
 }

配置FluentValidation,需要继承AbstractValidator类,并添加对应的验证规则

 public class ProductValidator : AbstractValidator<Product>
 {
  public ProductValidator()
  {
   RuleFor(product => product.name).NotNull().NotEmpty();//name 字段不能为null,也不能为空字符串
  }
 }

在Config中配置 FluentValidation

在 WebApiConfig配置文件中添加

public static class WebApiConfig
{
 public static void Register(HttpConfiguration config)
 {
  // Web API routes
  ...
  FluentValidationModelValidatorProvider.Configure(config);
 }
}

验证参数

需要在进入Controller之前进行验证,如果有错误就返回,不再进入Controller,需要使用 ActionFilterAttribute

public class ValidateModelStateFilter : ActionFilterAttribute
{
 public override void OnActionExecuting(HttpActionContext actionContext)
 {
  if (!actionContext.ModelState.IsValid)
  {
   actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
  }
 }
}

如果要让这个过滤器对所有的Controller都起作用,请在WebApiConfig中注册

public static class WebApiConfig
{
 public static void Register(HttpConfiguration config)
 {
  // Web API configuration and services
  config.Filters.Add(new ValidateModelStateFilter());

  // Web API routes
  ...

FluentValidationModelValidatorProvider.Configure(config);
 }
}

如果指对某一个Controller起作用,可以在Controller注册

[ValidateModelStateFilter]
public class ProductController : ApiController
{
 //具体的逻辑
}

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。

您可能感兴趣的文章:
  • 详解ASP.NET Core WebApi 返回统一格式参数
  • asp.net core webapi项目配置全局路由的方法示例
  • ASP.NET WebAPI连接数据库的方法
  • .Net WebApi消息拦截器之MessageHandler的示例
  • .Net Core2.1 WebAPI新增Swagger插件详解
  • ASP.net WebAPI跨域调用问题的解决方法
  • asp.net core webapi 服务端配置跨域的实例
  • ASP.NET Core 2.0 WebApi全局配置及日志实例
  • asp.net core 2.0 webapi集成signalr(实例讲解)
  • 详解.net core webapi 前后端开发分离后的配置和部署

23.3 Fluent builder API 快速构建API

23.3 Fluent builder API 快速构建API

如果 你需要构造 有等级的ApplicationContext(容器上下文)  (有 父/子 关系的 多个上下文)[multiple contexts with a

parent/child relationship],或者你 只是喜欢使用 快速构建 API ,你可以使用 SpringApplicationBuilder

在 SpringApplicationBuilder 中,允许你连条调用多个方法,包括父类 和 子类的方法

来创建你的 等级。

For example

public static void main(String[] args) {

		new SpringApplicationBuilder().bannerMode(Banner.Mode.OFF)
		.sources(Parent.class).child(ApplicationCH.class).run(args);

}

Note

在你创建ApplicationContext层级 时,有一些限制。

Web 组件必须包含在“子上下文” child context 中,一些环境变量,也要同时

用于 父子上下文中,查看 SpringApplicationBuilder Javadoc 查看详情。

 

ASP.NET Core WebApi中使用FluentValidation验证数据模型的方法

ASP.NET Core WebApi中使用FluentValidation验证数据模型的方法

介绍

验证用户输入是一个Web应用中的基本功能。对于生产系统,开发人员通常需要花费大量时间,编写大量的代码来完成这一功能。如果我们使用FluentValidation构建ASP.NET Core Web API,输入验证的任务将比以前容易的多。

FluentValidation是一个非常流行的构建强类型验证规则的.NET库。

配置项目

第一步:下载FluentValidation

我们可以使用Nuget下载最新的 FluentValidation

PM> Install-Package FluentValidation.AspNetCore

第二步:添加FluentValidation服务

我们需要在 Startup.cs 文件中添加FluentValidation服务

public void ConfigureServices(IServiceCollection services) 
{ 
  // mvc + validating
  services.AddMvc()
  .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
  .AddFluentValidation();
}

添加校验器

FluentValidation 提供了多种内置的校验器。在下面的例子中,我们可以看到其中的2种

  • NotNull 校验器
  • NotEmpty 校验器

第一步: 添加一个需要验证的数据模型

下面我们添加一个 User 类。

public class User
{
  public string Gender { get; set; }
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public string SIN { get; set; }
}

第二步: 添加校验器类

使用 FluentValidation 创建校验器类,校验器类都需要继承自一个抽象类 AbstractValidator

public class UserValidator : AbstractValidator<User>
{
  public UserValidator()
  {
   // 在这里添加规则
  }
}

第三步: 添加验证规则

在这个例子中,我们需要验证FirstName, LastName, SIN不能为null, 不能为空。我们也需要验证工卡SIN(Social Insurance Number)编号是合法的

public static class Utilities
{
  public static bool IsValidSIN(int sin)
  {
   if (sin < 0 || sin > 999999998) return false;

   int checksum = 0;
   for (int i = 4; i != 0; i--)
   {
     checksum += sin % 10;
     sin /= 10;

     int addend = 2 * (sin % 10); 
     
     if (addend >= 10) addend -= 9;
     
     checksum += addend;
     sin /= 10;
   }
     
   return (checksum + sin) % 10 == 0;
  }
}

下面我们在 UserValidator 类的构造函数中,添加验证规则

public class UserValidator : AbstractValidator<User>
{
  public UserValidator()
  {
   RuleFor(x => x.FirstName)
   .NotEmpty()
   .WithMessage("FirstName is mandatory.");

   RuleFor(x => x.LastName)
   .NotEmpty()
   .WithMessage("LastName is mandatory.");

   RuleFor(x => x.SIN)
   .NotEmpty()
   .WithMessage("SIN is mandatory.")
   .Must((o, list, context) =>
   {
     if (null != o.SIN)
     {
      context.MessageFormatter.AppendArgument("SIN", o.SIN);
      return Utilities.IsValidSIN(int.Parse(o.SIN));
     }
     return true;
   })
   .WithMessage("SIN ({SIN}) is not valid.");
  } 
}

第四步: 注入验证服务

public void ConfigureServices(IServiceCollection services) 
{ 
  // 添加验证器
  services.AddSingleton<IValidator<User>, UserValidator>();
  // mvc + validating
  services
    .AddMvc()
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
    .AddFluentValidation();
}

第五步:在 Startup.cs 中管理你的验证错误

ASP.NET Core 2.1及以上版本中,你可以覆盖ModelState管理的默认行为(ApiBehaviorOptions)

public void ConfigureServices(IServiceCollection services) 
{ 
  // Validators
  services.AddSingleton<IValidator<User>, UserValidator>();
  // mvc + validating
  services
    .AddMvc()
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
    .AddFluentValidation();

  // override modelstate
  services.Configure<ApiBehaviorOptions>(options =>
  {
    options.InvalidModelStateResponseFactory = (context) =>
    {
     var errors = context.ModelState
       .Values
       .SelectMany(x => x.Errors
             .Select(p => p.ErrorMessage))
       .ToList();
      
     var result = new
     {
       Code = "00009",
       Message = "Validation errors",
       Errors = errors
     };
      
     return new BadRequestObjectResult(result);
    };
  });
}

当数据模型验证失败时,程序会执行这段代码。

在这个例子,我设置了如何向客户端显示错误。这里返回结果中,我只是包含了一个错误代码,错误消息以及错误对象列表。

下面让我们看一下最终效果。

使用验证器

这里验证器使用起来非常容易。

你只需要创建一个action, 并将需要验证的数据模型放到action的参数中。

由于验证服务已在配置中添加,因此当请求这个action时, FluentValidation 将自动验证你的数据模型!

第一步:创建一个使用待验证数据模型的action

[Route("api/[controller]")]
[ApiController]
public class DemoValidationController : ControllerBase
{
  [HttpPost]
  public IActionResult Post(User user)
  {
   return NoContent();
  }
}

第二步:使用POSTMAN测试你的action

总结

在本篇博客中,我讲解了如何使用 FluentValidation 进行数据模型验证。

本篇源代码 https://github.com/lamondlu/FluentValidationExample

原文链接:Common features in ASP.NET Core 2.1 WebApi: Validation

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

您可能感兴趣的文章:
  • 基于ASP.NET Core数据保护生成验证token示例
  • asp.net数据验证控件
  • 基于.NET的FluentValidation数据验证实现

关于遍历 Linq fluent API 方法 (C#)fluent journal循环批处理的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于'InfluxDBClient' 对象在 Python 和 Docker 中没有属性 'api_client'、.Net Web Api中利用FluentValidate进行参数验证的方法、23.3 Fluent builder API 快速构建API、ASP.NET Core WebApi中使用FluentValidation验证数据模型的方法等相关知识的信息别忘了在本站进行查找喔。

本文标签: