示例#1
0
        public void Create()
        {
            // 全局初始化设置WorkerId,默认最大2^16-1。(初始化过程全局只需一次,且必须最先设置)
            var options = new IdGeneratorOptions()
            {
                Method   = 1,
                WorkerId = 1
            };

            YitIdHelper.SetIdGenerator(options);
            var code = YitIdHelper.NextId().ToString();

            var app         = _autofacServiceProvider.GetService <FlowInstanceApp>();
            var instanceReq = new AddFlowInstanceReq
            {
                SchemeId   = "0dac17c2-fec7-4bcd-a391-4ff74de8506a",
                FrmType    = 1,
                DbName     = "FrmLeaveReq",
                FrmData    = "{\"id\":\"\",\"userName\":\"周翔宇\",\"requestType\":\"病假\",\"startDate\":\"2021-03-08T16:00:00.000Z\",\"startTime\":\"2021-03-16T15:11:28.000Z\",\"endDate\":\"2021-03-24T16:00:00.000Z\",\"endTime\":\"2021-03-16T15:11:31.000Z\",\"requestComment\":\"1111\",\"attachment\":\"\",\"files\":[],\"extendInfo\":\"\"}",
                CustomName = DateTime.Now.ToString(),
                Code       = code
            };

            app.CreateInstance(instanceReq);
        }
示例#2
0
文件: Startup.cs 项目: jwc-gh/Wichian
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            //  NGINX 反向代理获取真实IP
            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
            });

            // 添加状态码拦截中间件
            app.UseUnifyResultStatusCodes();

            app.UseHttpsRedirection(); // 强制https
            app.UseStaticFiles();

            // Serilog请求日志中间件---必须在 UseStaticFiles 和 UseRouting 之间
            app.UseSerilogRequestLogging();

            app.UseRouting();

            app.UseCorsAccessor();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseInject(string.Empty);

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapHub <ChatHub>("/hubs/chathub");

                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });

            // 设置雪花Id的workerId,确保每个实例workerId都应不同
            var workerId = ushort.Parse(App.Configuration["SnowId:WorkerId"] ?? "1");

            YitIdHelper.SetIdGenerator(new IdGeneratorOptions {
                WorkerId = workerId
            });

            // 开启自启动定时任务
            App.GetService <ISysTimerService>().StartTimerJob();
        }
示例#3
0
        static LongEntity()
        {
            //设置参数,程序初始化时执行一次
            var options = new IdGeneratorOptions()
            {
                Method   = 1,
                WorkerId = 1
            };

            YitIdHelper.SetIdGenerator(options);
        }
示例#4
0
        private YitterSnowFlake()
        {
            if (_currentWorkerId > MaxWorkerId || _currentWorkerId < 0)
            {
                throw new Exception(string.Format("worker Id can't be greater than {0} or less than 0", MaxWorkerId));
            }

            YitIdHelper.SetIdGenerator(new IdGeneratorOptions((ushort)_currentWorkerId)
            {
                WorkerIdBitLength = YitterWorkerIdBitLength
                ,
                SeqBitLength = YitterSeqBitLength
            });;
        }
示例#5
0
        public void Generate()
        {
            // 全局初始化设置WorkerId,默认最大2^16-1。(初始化过程全局只需一次,且必须最先设置)
            var options = new IdGeneratorOptions()
            {
                Method   = 1,
                WorkerId = 1
            };

            YitIdHelper.SetIdGenerator(options);
            long newId = YitIdHelper.NextId();

            Console.WriteLine("=====================================");
            Console.WriteLine("生成的 Id:" + newId);
        }
示例#6
0
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddConfigurableOptions <WechatOptions>();
        var wechat = App.GetConfig <WechatOptions>("Wechat", true);

        services.AddHttpApi <IWechatApi>(o =>
        {
            o.HttpHost = new Uri(wechat.AuthUrl);
        });

        //TODO id long dto transcation to string
        YitIdHelper.SetIdGenerator(new IdGeneratorOptions(1));

        services.AddCorsAccessor();
        services.AddTaskScheduler();

        services.AddControllers()
        .AddInjectWithUnifyResult();

        services.AddMvcFilter <SessionFilter>();
    }
示例#7
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World! C#");

            var options = new IdGeneratorOptions()
            {
                Method   = method,
                WorkerId = 1,

                WorkerIdBitLength     = 6,
                SeqBitLength          = 6,
                DataCenterIdBitLength = 10,
                TopOverCostCount      = 2000,

                //TimestampType = 1,

                // MinSeqNumber = 1,
                // MaxSeqNumber = 200,

                // BaseTime = DateTime.Now.AddYears(-10),
            };

            IdGen = new DefaultIdGenerator(options);
            GenTest genTest = new GenTest(IdGen, genIdCount, options.WorkerId);

            // 首先测试一下 IdHelper 方法,获取单个Id
            YitIdHelper.SetIdGenerator(options);
            long newId = YitIdHelper.NextId();

            Console.WriteLine("=====================================");
            Console.WriteLine("这是用方法 " + method + " 生成的 Id:" + newId);

            while (true)
            {
                RunSingle();
                //CallDll();
                //Go(options);
                Thread.Sleep(1000); // 每隔1秒执行一次Go
            }
        }
示例#8
0
        public void ConfigureServices(IServiceCollection services)
        {
            //雪花漂移算法
            YitIdHelper.SetIdGenerator(new IdGeneratorOptions(1)
            {
                WorkerIdBitLength = 6
            });

            services.AddScoped <IPermissionHandler, PermissionHandler>();

            // ClaimType不被更改
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

            //用户信息
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            if (_appConfig.IdentityServer.Enable)
            {
                //is4
                services.TryAddSingleton <IUser, UserIdentiyServer>();
            }
            else
            {
                //jwt
                services.TryAddSingleton <IUser, User>();
            }

            //添加数据库
            services.AddDbAsync(_env).Wait();

            //添加IdleBus单例
            var dbConfig          = new ConfigHelper().Get <DbConfig>("dbconfig", _env.EnvironmentName);
            int idleTime          = dbConfig.IdleTime > 0 ? dbConfig.IdleTime : 10;
            IdleBus <IFreeSql> ib = new IdleBus <IFreeSql>(TimeSpan.FromMinutes(idleTime));

            services.AddSingleton(ib);
            //数据库配置
            services.AddSingleton(dbConfig);

            //应用配置
            services.AddSingleton(_appConfig);

            //上传配置
            var uploadConfig = _configHelper.Load("uploadconfig", _env.EnvironmentName, true);

            services.Configure <UploadConfig>(uploadConfig);

            #region AutoMapper 自动映射

            var serviceAssembly = Assembly.Load("Admin.Core.Service");
            services.AddAutoMapper(serviceAssembly);

            #endregion AutoMapper 自动映射

            #region Cors 跨域

            if (_appConfig.CorUrls?.Length > 0)
            {
                services.AddCors(options =>
                {
                    options.AddPolicy(DefaultCorsPolicyName, policy =>
                    {
                        policy
                        .WithOrigins(_appConfig.CorUrls)
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                        .AllowCredentials();
                    });

                    /*
                     * //浏览器会发起2次请求,使用OPTIONS发起预检请求,第二次才是api异步请求
                     * options.AddPolicy("All", policy =>
                     * {
                     *  policy
                     *  .AllowAnyOrigin()
                     *  .SetPreflightMaxAge(new TimeSpan(0, 10, 0))
                     *  .AllowAnyHeader()
                     *  .AllowAnyMethod()
                     *  .AllowCredentials();
                     * });
                     */
                });
            }

            #endregion Cors 跨域

            #region 身份认证授权

            var jwtConfig = _configHelper.Get <JwtConfig>("jwtconfig", _env.EnvironmentName);
            services.TryAddSingleton(jwtConfig);

            if (_appConfig.IdentityServer.Enable)
            {
                //is4
                services.AddAuthentication(options =>
                {
                    options.DefaultScheme          = IdentityServerAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = nameof(ResponseAuthenticationHandler); //401
                    options.DefaultForbidScheme    = nameof(ResponseAuthenticationHandler); //403
                })
                .AddJwtBearer(options =>
                {
                    options.Authority            = _appConfig.IdentityServer.Url;
                    options.RequireHttpsMetadata = false;
                    options.Audience             = "admin.server.api";
                })
                .AddScheme <AuthenticationSchemeOptions, ResponseAuthenticationHandler>(nameof(ResponseAuthenticationHandler), o => { });
            }
            else
            {
                //jwt
                services.AddAuthentication(options =>
                {
                    options.DefaultScheme          = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = nameof(ResponseAuthenticationHandler); //401
                    options.DefaultForbidScheme    = nameof(ResponseAuthenticationHandler); //403
                })
                .AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer           = true,
                        ValidateAudience         = true,
                        ValidateLifetime         = true,
                        ValidateIssuerSigningKey = true,
                        ValidIssuer      = jwtConfig.Issuer,
                        ValidAudience    = jwtConfig.Audience,
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfig.SecurityKey)),
                        ClockSkew        = TimeSpan.Zero
                    };
                })
                .AddScheme <AuthenticationSchemeOptions, ResponseAuthenticationHandler>(nameof(ResponseAuthenticationHandler), o => { });
            }

            #endregion 身份认证授权

            #region Swagger Api文档

            if (_env.IsDevelopment() || _appConfig.Swagger)
            {
                services.AddSwaggerGen(options =>
                {
                    typeof(ApiVersion).GetEnumNames().ToList().ForEach(version =>
                    {
                        options.SwaggerDoc(version, new OpenApiInfo
                        {
                            Version = version,
                            Title   = "Admin.Core"
                        });
                        //c.OrderActionsBy(o => o.RelativePath);
                    });

                    var xmlPath = Path.Combine(basePath, "Admin.Core.xml");
                    options.IncludeXmlComments(xmlPath, true);

                    var xmlCommonPath = Path.Combine(basePath, "Admin.Core.Common.xml");
                    options.IncludeXmlComments(xmlCommonPath, true);

                    var xmlModelPath = Path.Combine(basePath, "Admin.Core.Model.xml");
                    options.IncludeXmlComments(xmlModelPath);

                    var xmlServicesPath = Path.Combine(basePath, "Admin.Core.Service.xml");
                    options.IncludeXmlComments(xmlServicesPath);

                    #region 添加设置Token的按钮

                    if (_appConfig.IdentityServer.Enable)
                    {
                        //添加Jwt验证设置
                        options.AddSecurityRequirement(new OpenApiSecurityRequirement()
                        {
                            {
                                new OpenApiSecurityScheme
                                {
                                    Reference = new OpenApiReference
                                    {
                                        Id   = "oauth2",
                                        Type = ReferenceType.SecurityScheme
                                    }
                                },
                                new List <string>()
                            }
                        });

                        //统一认证
                        options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
                        {
                            Type        = SecuritySchemeType.OAuth2,
                            Description = "oauth2登录授权",
                            Flows       = new OpenApiOAuthFlows
                            {
                                Implicit = new OpenApiOAuthFlow
                                {
                                    AuthorizationUrl = new Uri($"{_appConfig.IdentityServer.Url}/connect/authorize"),
                                    Scopes           = new Dictionary <string, string>
                                    {
                                        { "admin.server.api", "admin后端api" }
                                    }
                                }
                            }
                        });
                    }
                    else
                    {
                        //添加Jwt验证设置
                        options.AddSecurityRequirement(new OpenApiSecurityRequirement()
                        {
                            {
                                new OpenApiSecurityScheme
                                {
                                    Reference = new OpenApiReference
                                    {
                                        Id   = "Bearer",
                                        Type = ReferenceType.SecurityScheme
                                    }
                                },
                                new List <string>()
                            }
                        });

                        options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                        {
                            Description = "Value: Bearer {token}",
                            Name        = "Authorization",
                            In          = ParameterLocation.Header,
                            Type        = SecuritySchemeType.ApiKey
                        });
                    }

                    #endregion 添加设置Token的按钮
                });
            }

            #endregion Swagger Api文档

            #region 操作日志

            if (_appConfig.Log.Operation)
            {
                //services.AddSingleton<ILogHandler, LogHandler>();
                services.AddScoped <ILogHandler, LogHandler>();
            }

            #endregion 操作日志

            #region 控制器

            services.AddControllers(options =>
            {
                options.Filters.Add <AdminExceptionFilter>();
                if (_appConfig.Log.Operation)
                {
                    options.Filters.Add <LogActionFilter>();
                }
                //禁止去除ActionAsync后缀
                options.SuppressAsyncSuffixInActionNames = false;
            })
            //.AddFluentValidation(config =>
            //{
            //    var assembly = Assembly.LoadFrom(Path.Combine(basePath, "Admin.Core.dll"));
            //    config.RegisterValidatorsFromAssembly(assembly);
            //})
            .AddNewtonsoftJson(options =>
            {
                //忽略循环引用
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                //使用驼峰 首字母小写
                options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                //设置时间格式
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
            });

            #endregion 控制器

            #region 缓存

            var cacheConfig = _configHelper.Get <CacheConfig>("cacheconfig", _env.EnvironmentName);
            if (cacheConfig.Type == CacheType.Redis)
            {
                var csredis = new CSRedis.CSRedisClient(cacheConfig.Redis.ConnectionString);
                RedisHelper.Initialization(csredis);
                services.AddSingleton <ICache, RedisCache>();
            }
            else
            {
                services.AddMemoryCache();
                services.AddSingleton <ICache, MemoryCache>();
            }

            #endregion 缓存

            #region IP限流

            if (_appConfig.RateLimit)
            {
                services.AddIpRateLimit(_configuration, cacheConfig);
            }

            #endregion IP限流

            //阻止NLog接收状态消息
            services.Configure <ConsoleLifetimeOptions>(opts => opts.SuppressStatusMessages = true);
        }
示例#9
0
        public void ConfigureServices(IServiceCollection services)
        {
            //界面即时编译,Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation
            //services.AddRazorPages().AddRazorRuntimeCompilation();

            //雪花漂移算法
            YitIdHelper.SetIdGenerator(new IdGeneratorOptions(1)
            {
                WorkerIdBitLength = 6
            });

            services.AddSingleton(_appSettings);
            services.AddSingleton(new IPHelper());
            services.AddDb(_appSettings);

            #region Cors 跨域

            if (_appSettings.CorUrls?.Length > 0)
            {
                services.AddCors(options =>
                {
                    options.AddPolicy("Limit", policy =>
                    {
                        policy
                        .WithOrigins(_appSettings.CorUrls)
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                        .AllowCredentials();
                    });
                });
            }

            #endregion Cors 跨域

            var builder = services.AddIdentityServer(options =>
            {
                options.UserInteraction = new UserInteractionOptions
                {
                    LoginUrl  = "/user/login",
                    LogoutUrl = "/user/logout"
                };
            })
                          .AddInMemoryIdentityResources(Config.IdentityResources)
                          .AddInMemoryApiScopes(Config.ApiScopes)
                          .AddInMemoryApiResources(Config.ApiResources)
                          .AddInMemoryClients(Config.Clients(_appSettings))
                          .AddProfileService <AdminProfileService>()
                          .AddResourceOwnerValidator <AdminResourceOwnerPasswordValidator>();

            if (_env.IsDevelopment())
            {
                builder.AddDeveloperSigningCredential();
            }
            else
            {
                builder.AddSigningCredential(new X509Certificate2(
                                                 Path.Combine(AppContext.BaseDirectory, _appSettings.Certificate.Path),
                                                 _appSettings.Certificate.Password)
                                             );
            }

            services.ConfigureApplicationCookie(options =>
            {
                options.LoginPath = "/user/login";
            });

            services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromSeconds(120);
            });

            services.AddControllersWithViews(options =>
            {
                //禁止去除ActionAsync后缀
                options.SuppressAsyncSuffixInActionNames = false;
            })
            .AddNewtonsoftJson(options =>
            {
                //忽略循环引用
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                //使用驼峰 首字母小写
                options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                //设置时间格式
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
            });

            if (_env.IsDevelopment() || _appSettings.Swagger)
            {
                services.AddSwaggerGen(options =>
                {
                    options.SwaggerDoc("v1", new OpenApiInfo
                    {
                        Version = "v1",
                        Title   = "Admin.IdentityServer"
                    });

                    //添加Jwt验证设置
                    options.AddSecurityRequirement(new OpenApiSecurityRequirement()
                    {
                        {
                            new OpenApiSecurityScheme
                            {
                                Reference = new OpenApiReference
                                {
                                    Id   = "Bearer",
                                    Type = ReferenceType.SecurityScheme
                                }
                            },
                            new List <string>()
                        }
                    });

                    //添加设置Token的按钮
                    options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                    {
                        Description = "Value: Bearer {token}",
                        Name        = "Authorization",
                        In          = ParameterLocation.Header,
                        Type        = SecuritySchemeType.ApiKey
                    });

                    string xmlPath = Path.Combine(basePath, $"{typeof(Startup).Assembly.GetName().Name}.xml");
                    options.IncludeXmlComments(xmlPath);
                });
            }

            if (_appSettings.Health)
            {
                services.AddHealthChecks();
            }
        }