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); }
static void Main(string[] args) { List <long> data = new List <long>(); DateTime timeBegin = DateTime.Now; //var generator = new IdGenerator(0); var epoch = new DateTime(2020, 7, 22, 0, 0, 0, DateTimeKind.Utc); var structure = new IdStructure(45, 2, 16); var options = new IdGeneratorOptions(structure, new DefaultTimeSource(epoch)); var generator = new IdGenerator(0, options); for (int i = 0; i < 100000000; i++) { var id = generator.CreateId(); data.Add(id); //Console.WriteLine($"生成id:{id}"); } DateTime timeEnd = DateTime.Now; TimeSpan span = timeEnd.Subtract(timeBegin); data.Add(data.Last()); Console.WriteLine($"添加一个测试数据后:{data.Count}"); data = data.Distinct().ToList(); Console.WriteLine($"取出重复数据后:{data.Count}"); Console.WriteLine($"耗时:{span.TotalSeconds}"); Console.WriteLine($"平均每秒产生:{data.Count / span.TotalSeconds}"); Console.ReadLine(); }
public static void Initialize(IdGenSettings settings) { //var epoch = new DateTime(2020, 12, 22, 0, 0, 0, DateTimeKind.Utc); var structure = new IdStructure(settings.TimestampBits, settings.GeneratorIdBits, settings.SequenceBits); var options = new IdGeneratorOptions(structure, new DefaultTimeSource(settings.Epoch)); StaticIdGen.IdGen = new IdGenDistributedId(settings.MachineId, options); }
static LongEntity() { //设置参数,程序初始化时执行一次 var options = new IdGeneratorOptions() { Method = 1, WorkerId = 1 }; YitIdHelper.SetIdGenerator(options); }
public IdManager() { // Fun fact: This is the exact moment that SpookVooper was terminated // which led to the development of Valour becoming more than just a side // project. Viva la Vooperia. var epoch = new DateTime(2021, 1, 11, 4, 37, 0); var structure = new IdStructure(45, 10, 8); var options = new IdGeneratorOptions(structure, new DefaultTimeSource(epoch)); Generator = new IdGenerator(0, options); }
public SnowflakeEngine() { Epoch = new DateTime(2020, 7, 30, 0, 0, 0, DateTimeKind.Utc); //This is written @ 11:58 PM, 30/7/2020 // Create an ID with 31 Bit for TimeStamp, 1 Bits for GeneratorID and 31 Bits for Sequence var IDStructure = new IdStructure(31, 1, 31); var Options = new IdGeneratorOptions(IDStructure, new DefaultTimeSource(Epoch)); Generator = new IdGenerator(1, Options); }
private void Initialise() { lock (_lockObject) { if (_isInitialised) { return; } var epoch = new DateTime(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc); var options = new IdGeneratorOptions(_idStructure, new DefaultTimeSource(epoch), SequenceOverflowStrategy.SpinWait); _idGenerator = new IdGenerator(0, options); _isInitialised = true; } }
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); }
/// <summary> /// Returns an instance of an <see cref="IdGenerator"/> based on the values in the corresponding idGenerator /// element in the idGenSection of the configuration file. The <see cref="DefaultTimeSource"/> is used to /// retrieve timestamp information. /// </summary> /// <param name="name">The name of the <see cref="IdGenerator"/> in the idGenSection.</param> /// <returns> /// An instance of an <see cref="IdGenerator"/> based on the values in the corresponding idGenerator /// element in the idGenSection of the configuration file. /// </returns> /// <remarks> /// When the <see cref="IdGenerator"/> doesn't exist it is created; any consequent calls to this method with /// the same name will return the same instance. /// </remarks> public static IdGenerator GetFromConfig(string name) { var result = _namedgenerators.GetOrAdd(name, (n) => { var idgenerators = (ConfigurationManager.GetSection(IdGeneratorsSection.SectionName) as IdGeneratorsSection).IdGenerators; var idgen = idgenerators.OfType <IdGeneratorElement>().FirstOrDefault(e => e.Name.Equals(n, StringComparison.Ordinal)); if (idgen != null) { var ts = idgen.TickDuration == TimeSpan.Zero ? defaulttimesource : new DefaultTimeSource(idgen.Epoch, idgen.TickDuration); var options = new IdGeneratorOptions(new IdStructure(idgen.TimestampBits, idgen.GeneratorIdBits, idgen.SequenceBits), ts, idgen.SequenceOverflowStrategy); return(new IdGenerator(idgen.Id, options)); } throw new KeyNotFoundException(); }); return(result); }
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 } }
public JsonResult AddBill(string name, string address, string phone, string email, int payment) { try { Bill bill = new Bill(); //Declare snowflake algorithm DateTime epoch = new DateTime(2021, 1, 1, 0, 0, 0, DateTimeKind.Utc); //41 bit for time //12 bit for number of shard //10 bit for sequence IdStructure structure = new IdStructure(41, 12, 10); IdGeneratorOptions option = new IdGeneratorOptions(structure, new DefaultTimeSource(epoch)); IdGenerator generator = new IdGenerator(0, option); //create new id and declare properties to bill long billID = generator.CreateId(); bill.BillID = billID; bill.userName = name; bill.address = address; bill.phoneNumber = phone; bill.email = email; bill.payment = payment; bill.status = 1; bill.orderTime = DateTime.Now; //email content string content = $"You have successfully booked your order, the ready-made product will be delivered within {DateTime.Now.AddDays(3).Date} to {DateTime.Now.AddDays(7).Date}<br/><br/>"; content += $"Order ID: {billID}<br/><br/>"; //head row of table content += "<table><tr style=\"color: white; background-color: #7fad39;\"><td style=\"padding: 5px 10px 5px 10px; font-size: 15px;\">Product</td><td style=\"padding: 5px 10px 5px 10px; font-size: 15px;\">Price</td><td style=\"padding: 5px 10px 5px 10px; font-size: 15px;\">Quantity</td><td style=\"padding: 5px 10px 5px 10px; font-size: 15px;\">Total</td></tr>"; decimal totalValue = 0; //is loged User if (Session["user"] == null) { //didn't log in case, storage cart in cookies Dictionary <string, int> cart; //check is exsisted cart in cookies if (Session["cart"] != null) { //exsisted case, pick up it cart = (Dictionary <string, int>)Session["cart"]; Dictionary <string, int> .KeyCollection keys = cart.Keys; //add bill to database foreach (string key in keys) { bill.productid = Int32.Parse(key); bill.quantity = cart[key]; Product p = db.Products.Find(bill.productid = Int32.Parse(key)); bill.amount = p.price; //add into bill db.Bills.Add(bill); db.SaveChanges(); //add middle row of table decimal total = p.price * cart[key]; content += $"<tr style=\"background - color: #eeeeee;\"><td style=\"padding: 5px 10px 5px 10px; font-size: 15px;\">{p.title}</td><td style=\"padding: 5px 10px 5px 10px; font-size: 15px;\">{p.price.ToString("C")}</td><td style=\"padding: 5px 10px 5px 10px; font-size: 15px;\">{cart[key]}</td><td style=\"padding: 5px 10px 5px 10px; font-size: 15px;\">{total.ToString("C")}</td>"; totalValue += total; } Session.Remove("cart"); } else { //in null case of cart return(Json("Please put item into cart before check out!", JsonRequestBehavior.AllowGet)); } } else { //loged in case Account account = db.Accounts.Find(Int32.Parse(Session["user"].ToString())); bill.userid = account.userID; //load cart infor from database List <Cart> carts = db.Carts.ToList().Select(cart => new Cart { cartid = cart.cartid, userid = cart.userid, productid = cart.productid, quantity = cart.quantity, Account = db.Accounts.Find(cart.userid), Product = db.Products.Find(cart.productid) }).Where(c => c.userid == account.userID).ToList(); //check is exsisted any item in cart in database if (carts.Count > 0) { foreach (Cart cart in carts) { bill.productid = cart.productid; bill.quantity = cart.quantity; bill.amount = cart.Product.price; //add bill db.Bills.Add(bill); //add middle row of table decimal total = cart.Product.price * cart.quantity; content += $"<tr style=\"background - color: #eeeeee;\"><td style=\"padding: 5px 10px 5px 10px; font-size: 15px;\">{cart.Product.title}</td><td style=\"padding: 5px 10px 5px 10px; font-size: 15px;\">{cart.Product.price.ToString("C")}</td><td style=\"padding: 5px 10px 5px 10px; font-size: 15px;\">{cart.quantity}</td><td style=\"padding: 5px 10px 5px 10px; font-size: 15px;\">{total.ToString("C")}</td>"; totalValue += total; //remove item from cart db.Carts.Remove(db.Carts.Find(cart.cartid)); db.SaveChanges(); } } else { //in null case of cart return(Json(new { type = 2, message = "Please put item into cart before check out!" }, JsonRequestBehavior.AllowGet)); } } Session["tempBillID"] = billID; //last row of table content += $"<tr style=\"background-color: #F5F5F5;\"><td style=\"padding: 5px 10px 5px 10px; font-size: 15px;\"></td><td style=\"padding: 5px 10px 5px 10px; font-size: 15px;\"></td><td style=\"padding: 5px 10px 5px 10px; font-size: 15px;\">Total order value</td><td style=\"padding: 5px 10px 5px 10px; font-size: 15px;\">{totalValue.ToString("C")}</td></tr></table>"; try { //send email to user MailAddress senderEmail = new MailAddress("*****@*****.**", "BookStore"); MailAddress receiverEmail = new MailAddress(email, "Receiver"); string password = "******"; string subject = "Order successfull"; string body = content; SmtpClient smtp = new SmtpClient { Host = "smtp.gmail.com", Port = 587, EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(senderEmail.Address, password) }; using (MailMessage mess = new MailMessage(senderEmail, receiverEmail) { Subject = subject, Body = body }) { mess.IsBodyHtml = true; smtp.Send(mess); } return(Json(new { type = 1, message = "Check Out Success!" }, JsonRequestBehavior.AllowGet)); } catch { return(Json(new { type = 2, message = "Send email fail!" }, JsonRequestBehavior.AllowGet)); } } catch { return(Json(new { type = 2, message = "Check Out Fail!" }, JsonRequestBehavior.AllowGet)); } }
public IdGenDistributedId(int generatorId, IdGeneratorOptions options) { _idGen = new IdGenerator(generatorId, options); }
private static void Go(IdGeneratorOptions options) { Count = 0; testList = new List <GenTest>(); // ++++++++++++++++++++++++++++++++ if (single) { if (IdGen == null) { IdGen = new DefaultIdGenerator(options); } if (outputLog) { IdGen.GenIdActionAsync = (arg => { if (arg.ActionType == 1) { Console.WriteLine($">>>> {arg.WorkerId}:开始:{DateTime.Now.ToString("mm:ss:fff")}, 周期次序:{arg.TermIndex}"); } else if (arg.ActionType == 2) { Console.WriteLine($"<<<< {arg.WorkerId}:结束:{DateTime.Now.ToString("mm:ss:fff")},漂移 {arg.OverCostCountInOneTerm} 次,产生 {arg.GenCountInOneTerm} 个, 周期次序:{arg.TermIndex}"); } if (arg.ActionType == 8) { Console.WriteLine($"---- {arg.WorkerId}:AA结束:{DateTime.Now.ToString("mm:ss:fff")},时间回拨"); } }); } for (int i = 1; i < workerCount + 1; i++) { Console.WriteLine("Gen:" + i); var test = new GenTest(IdGen, genIdCount, i); testList.Add(test); // test.GenId(); test.GenStart(); } } else { for (int i = 1; i < workerCount + 1; i++) { IdGeneratorOptions newOptions = new IdGeneratorOptions() { WorkerId = (ushort)i, // workerId 不能设置为0 WorkerIdBitLength = options.WorkerIdBitLength, SeqBitLength = options.SeqBitLength, MinSeqNumber = options.MinSeqNumber, MaxSeqNumber = options.MaxSeqNumber, Method = options.Method, }; Console.WriteLine("Gen:" + i); var idGen2 = new DefaultIdGenerator(newOptions); var test = new GenTest(idGen2, genIdCount, i); if (outputLog) { idGen2.GenIdActionAsync = (arg => { Console.WriteLine($"{DateTime.Now.ToString("mm:ss:fff")} {arg.WorkerId} 漂移了 {arg.OverCostCountInOneTerm}, 顺序:{arg.TermIndex}"); }); } testList.Add(test); // test.GenId(); test.GenStart(); } } while (Count < workerCount) { //Console.WriteLine("Count:" + Count); Thread.Sleep(1000); } //Console.WriteLine("Count:" + Count); if (!checkResult) { return; } var dupCount = 0; foreach (var id in testList[0].idList) { if (id == 0) { Console.WriteLine("############### 错误的ID:" + id + "###########"); } for (int j = 1; j < testList.Count; j++) { if (testList[j].idList.Contains(id)) { dupCount++; Console.WriteLine("xxxxxxxxxx 重复的ID:" + id); } } } if (dupCount > 0) { Console.WriteLine($"重复数量:{dupCount}"); } }
public void ConfigureServices(IServiceCollection services) { Log.Information("Startup::ConfigureServices"); try { services.AddControllers( opt => { //Custom filters can be added here //opt.Filters.Add(typeof(CustomFilterAttribute)); //opt.Filters.Add(new ProducesAttribute("application/json")); } ).SetCompatibilityVersion(CompatibilityVersion.Version_3_0); #region "API versioning" //API versioning service services.AddApiVersioning( o => { //o.Conventions.Controller<UserController>().HasApiVersion(1, 0); o.AssumeDefaultVersionWhenUnspecified = true; o.ReportApiVersions = true; o.DefaultApiVersion = new ApiVersion(1, 0); o.ApiVersionReader = new UrlSegmentApiVersionReader(); } ); // format code as "'v'major[.minor][-status]" services.AddVersionedApiExplorer( options => { options.GroupNameFormat = "'v'VVV"; //versioning by url segment options.SubstituteApiVersionInUrl = true; }); #endregion #region Database // Register Database Entity Maps services.AddSingleton <IEntityTypeMap, UserMap>(); services.AddSingleton <IEntityTypeMap, DroneMap>(); services.AddSingleton <IEntityTypeMap, MissionMap>(); services.AddSingleton <IEntityTypeMap, CompanyAccountMap>(); services.AddSingleton <IEntityTypeMap>(new BaseEntityMap <DroneCommands>()); services.AddSingleton <IEntityTypeMap>(new BaseEntityMap <DroneNetworkSettings>()); services.AddSingleton <IEntityTypeMap>(new BaseEntityMap <DroneOnvifSettings>()); services.AddSingleton <IEntityTypeMap>(new BaseEntityMap <GeoArea>()); services.AddSingleton <IEntityTypeMap>(new BaseEntityMap <GeoPoint>()); services.AddSingleton <IEntityTypeMap>(new BaseEntityMap <PatrolConfig>()); services.AddSingleton <IEntityTypeMap>(new BaseEntityMap <Drone>()); services.AddSingleton <IEntityTypeMap>(new BaseEntityMap <ObjectDetection>()); services.AddSingleton <IEntityTypeMap>(new BaseEntityMap <PlannedRoute>()); services.AddSingleton <IEntityTypeMap>(new BaseEntityMap <StatusReport>()); //DB service if (Configuration["ConnectionStrings:UseInMemoryDatabase"] == "True") { services.AddDbContext <DefaultDbContext>(opt => opt.UseInMemoryDatabase("TestDB-" + Guid.NewGuid().ToString())); } else { services.AddDbContext <DefaultDbContext>(options => options.UseNpgsql( Configuration["ConnectionStrings:Moonlimit.DroneAPIDB"], o => o.UseNetTopologySuite()) , ServiceLifetime.Transient); } #endregion #region "Authentication" if (Configuration["Authentication:UseIdentityServer4"] == "False") { //JWT API authentication service services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = Configuration["Jwt:Issuer"], ValidAudience = Configuration["Jwt:Issuer"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"])) }; } ); } else { //Identity Server 4 API authentication service services.AddAuthorization(); //.AddJsonFormatters(); services.AddAuthentication("Bearer") .AddIdentityServerAuthentication(option => { option.Authority = Configuration["Authentication:IdentityServer4IP"]; option.RequireHttpsMetadata = false; //option.ApiSecret = "secret"; option.ApiName = "Moonlimit.DroneAPI"; //This is the resourceAPI that we defined in the Config.cs in the AuthServ project (apiresouces.json and clients.json). They have to be named equal. }); } #endregion #region "CORS" // include support for CORS // More often than not, we will want to specify that our API accepts requests coming from other origins (other domains). When issuing AJAX requests, browsers make preflights to check if a server accepts requests from the domain hosting the web app. If the response for these preflights don't contain at least the Access-Control-Allow-Origin header specifying that accepts requests from the original domain, browsers won't proceed with the real requests (to improve security). services.AddCors(options => { options.AddPolicy("CorsPolicy-public", builder => builder.AllowAnyOrigin() //WithOrigins and define a specific origin to be allowed (e.g. https://mydomain.com) .AllowAnyMethod() .AllowAnyHeader() //.AllowCredentials() .Build()); }); #endregion #region "MVC and JSON options" //mvc service (set to ignore ReferenceLoopHandling in json serialization like Users[0].Account.Users) //in case you need to serialize entity children use commented out option instead services.AddMvc(option => option.EnableEndpointRouting = false) .AddNewtonsoftJson(options => { options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; }); //NO entity classes' children serialization //.AddNewtonsoftJson(ops => //{ // ops.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize; // ops.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; //}); //WITH entity classes' children serialization #endregion #region "DI code" //ID Generator var epoch = new DateTime(2021, 1, 1, 0, 0, 0, DateTimeKind.Utc); // Create an ID with 31 (68 years if measured in seconds) bits for timestamp, 16 for generator-id and 16 for sequence(65536 per sec.) var structure = new IdStructure(31, 16, 16); // Prepare options var options = new IdGeneratorOptions(structure, new DefaultTimeSource(epoch, TimeSpan.FromSeconds(1.0)), SequenceOverflowStrategy.SpinWait); services.AddSingleton(new IdGenerator(0, options)); //Gen0 is for testing //general unitofwork injections services.AddTransient <IUnitOfWork, UnitOfWork>(); //services injections services.AddTransient(typeof(CompanyAccountService <,>), typeof(CompanyAccountService <,>)); services.AddTransient(typeof(UserService <,>), typeof(UserService <,>)); services.AddTransient(typeof(CompanyAccountServiceAsync <,>), typeof(CompanyAccountServiceAsync <,>)); services.AddTransient(typeof(UserServiceAsync <,>), typeof(UserServiceAsync <,>)); // SetAdditionalDIServices(services); //...add other services // services.AddTransient(typeof(IService <,>), typeof(GenericService <,>)); services.AddTransient(typeof(IServiceAsync <,>), typeof(GenericServiceAsync <,>)); services.AddHttpContextAccessor(); services.AddScoped <IClaimsData, HttpClaimsData>(); services.AddScoped <IClaimValidator <Drone>, BasicClaimValidator <Drone> >(); services.AddScoped <IClaimValidator <DroneNetworkSettings>, BasicClaimValidator <DroneNetworkSettings> >(); services.AddScoped <IClaimValidator <Mission>, BasicClaimValidator <Mission> >(); #endregion //data mapper services configuration services.AddAutoMapper(typeof(MappingProfile)); #region "Swagger API" //Swagger API documentation services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Moonlimit.DroneAPI API", Version = "v1" }); c.SwaggerDoc("v2", new OpenApiInfo { Title = "Moonlimit.DroneAPI API", Version = "v2" }); //In Test project find attached swagger.auth.pdf file with instructions how to run Swagger authentication c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme() { Description = "Authorization header using the Bearer scheme", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey }); c.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Id = "Bearer", //The name of the previously defined security scheme. Type = ReferenceType.SecurityScheme } }, new List <string>() } }); //c.DocumentFilter<api.infrastructure.filters.SwaggerSecurityRequirementsDocumentFilter>(); }); #endregion } catch (Exception ex) { Log.Error(ex.Message); } }
/// <summary> /// 设置参数,建议程序初始化时执行一次 /// </summary> /// <param name="options"></param> public static void SetIdGenerator(IdGeneratorOptions options) { _IdGenInstance = new DefaultIdGenerator(options); }