/// <summary> /// Get a counter entity by id /// </summary> internal static async Task <Counter> GetById(Guid counterId) { using (var conn = new SqlConnection("Server=localhost;Database=EventStore;Trusted_Connection=True;")) { using (var comm = conn.CreateCommand()) { comm.CommandText = "SELECT Version, EventType, Payload FROM EventLog WHERE EntityType = 'Counter' AND EntityId = @EntityID ORDER BY Version"; comm.Parameters.AddWithValue("@EntityID", counterId); await conn.OpenAsync().ConfigureAwait(false); Counter counter = null; using (var reader = await comm.ExecuteReaderAsync().ConfigureAwait(false)) { while (await reader.ReadAsync().ConfigureAwait(false)) { var version = reader.GetInt64(0); var type = reader.GetString(1); var payloadBytes = (byte[])reader["Payload"]; var counterEvent = new CounterEvent { Id = counterId.ToByteString(), Version = (ulong)version, }.SetEventPayload(type, payloadBytes); counter = CounterReducer.Apply(counter, counterEvent); } return(counter); } } } }
/// <summary> /// Store the given event /// </summary> internal static async Task StoreEvent(CounterEvent counterEvent) { using (var conn = new SqlConnection("Server=localhost;Database=EventStore;Trusted_Connection=True;")) { using (var comm = conn.CreateCommand()) { comm.CommandText = "INSERT INTO EventLog (EntityType, EntityId, Version, EventType, Payload) VALUES ('Counter', @EntityId, @Version, @EventType, @Payload)"; comm.Parameters.AddWithValue("@EntityID", counterEvent.Id.ToGuid()); comm.Parameters.AddWithValue("@Version", Convert.ToInt64(counterEvent.Version)); comm.Parameters.AddWithValue("@EventType", counterEvent.EventCase.ToString()); comm.Parameters.AddWithValue("@Payload", counterEvent.GetEventPayload().ToByteArray()); await conn.OpenAsync().ConfigureAwait(false); try { await comm.ExecuteNonQueryAsync().ConfigureAwait(false); EventAdded?.Invoke(new object(), EventArgs.Empty); } catch (SqlException ex) when(ex.Number == 2627) { throw new CounterOutOfDateException(); } } } }
public static CounterEvent SetEventPayload(this CounterEvent counterEvent, string type, byte[] payload) { if (Enum.TryParse(type, out EventOneofCase eventType)) { switch (eventType) { case EventOneofCase.Added: counterEvent.Added = CounterAdded.Parser.ParseFrom(payload); break; case EventOneofCase.Decremented: counterEvent.Decremented = CounterDecremented.Parser.ParseFrom(payload); break; case EventOneofCase.Incremented: counterEvent.Incremented = CounterIncremented.Parser.ParseFrom(payload); break; case EventOneofCase.NameChanged: counterEvent.NameChanged = CounterNameChanged.Parser.ParseFrom(payload); break; case EventOneofCase.Removed: counterEvent.Removed = CounterRemoved.Parser.ParseFrom(payload); break; default: throw new InvalidOperationException("Invalid event type"); } return(counterEvent); } throw new InvalidOperationException($"Could not parse {type} to an event type"); }
/// <summary> /// Initializes a new instance of the FileWriteStreamBase class for a file. /// </summary> /// <param name="file">File reference to write to.</param> /// <param name="fileSize">Size of the file.</param> /// <param name="createNew">Use <c>true</c> if the file is newly created, <c>false</c> otherwise.</param> /// <param name="accessCondition">An <see cref="AccessCondition"/> object that represents the access conditions for the file. If <c>null</c>, no condition is used.</param> /// <param name="options">An <see cref="FileRequestOptions"/> object that specifies additional options for the request.</param> /// <param name="operationContext">An <see cref="OperationContext"/> object for tracking the current operation.</param> protected FileWriteStreamBase(CloudFile file, long fileSize, bool createNew, AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext) : base() { this.internalBuffer = new MultiBufferMemoryStream(file.ServiceClient.BufferManager); this.currentOffset = 0; this.accessCondition = accessCondition; this.options = options; this.operationContext = operationContext; this.noPendingWritesEvent = new CounterEvent(); this.fileMD5 = this.options.StoreFileContentMD5.Value ? new MD5Wrapper() : null; this.rangeMD5 = this.options.UseTransactionalMD5.Value ? new MD5Wrapper() : null; #if !(NETCORE || WINDOWS_RT) this.parallelOperationSemaphoreAsync = new AsyncSemaphoreAsync(options.ParallelOperationThreadCount.Value); #else this.parallelOperationSemaphore = new AsyncSemaphore(options.ParallelOperationThreadCount.Value); #endif this.lastException = null; this.committed = false; this.disposed = false; this.currentFileOffset = 0; this.file = file; this.fileSize = fileSize; this.streamWriteSizeInBytes = file.StreamWriteSizeInBytes; this.newFile = createNew; }
/// <summary> /// Releases the file resources used by the Stream. /// </summary> /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { if (disposing) { if (this.fileMD5 != null) { this.fileMD5.Dispose(); this.fileMD5 = null; } if (this.rangeMD5 != null) { this.rangeMD5.Dispose(); this.rangeMD5 = null; } if (this.internalBuffer != null) { this.internalBuffer.Dispose(); this.internalBuffer = null; } if (this.noPendingWritesEvent != null) { this.noPendingWritesEvent.Dispose(); this.noPendingWritesEvent = null; } } base.Dispose(disposing); }
public void Count(string processName, string subProcessName, string counterCategory, string counterName) { CounterEvent counterEvent = new CounterEvent(); counterEvent.ProcessName = processName; counterEvent.SubProcessName = subProcessName; counterEvent.CounterCategory = counterCategory; counterEvent.CounterName = counterName; m_Queue.Enqueue(counterEvent); m_EventContinue.Set(); }
private void Count(CounterEvent e) { if (e.IsIncremental) { Counters.Increment(e.CounterKey); } else { Counters.SetValue(e.CounterKey, e.Value); } }
public void Add(int toAdd) { count += toAdd; if (count == goal) { // Fire event. var args = new CounterEvent(); args.Message = "Counter has reached 10!"; OnGoalReached(args); } }
/// <summary> /// Initializes a new instance of the BlobWriteStreamBase class. /// </summary> /// <param name="serviceClient">The service client.</param> /// <param name="accessCondition">An <see cref="AccessCondition"/> object that represents the condition that must be met in order for the request to proceed. If <c>null</c>, no condition is used.</param> /// <param name="options">A <see cref="BlobRequestOptions"/> object that specifies additional options for the request.</param> /// <param name="operationContext">An <see cref="OperationContext"/> object that represents the context for the current operation.</param> private BlobWriteStreamBase(CloudBlobClient serviceClient, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) : base() { this.internalBuffer = new MultiBufferMemoryStream(serviceClient.BufferManager); this.accessCondition = accessCondition; this.currentOffset = 0; this.options = options; this.operationContext = operationContext; this.noPendingWritesEvent = new CounterEvent(); this.blobMD5 = this.options.StoreBlobContentMD5.Value ? new MD5Wrapper() : null; this.blockMD5 = this.options.UseTransactionalMD5.Value ? new MD5Wrapper() : null; this.parallelOperationSemaphore = new AsyncSemaphore(options.ParallelOperationThreadCount.Value); this.lastException = null; this.committed = false; this.disposed = false; }
/// <summary> /// Add a counter /// </summary> public async Task <Guid> AddCounter(string name) { var id = Guid.NewGuid(); //var payload = new CounterAdded { Name = "" }; var counterEvent = new CounterEvent { Id = ByteString.CopyFrom(id.ToByteArray()), Version = 0, Added = new CounterAdded { Name = "" } }; await CounterStore.StoreEvent(counterEvent).ConfigureAwait(false); return(id); }
public static IMessage GetEventPayload(this CounterEvent counterEvent) { switch (counterEvent.EventCase) { case EventOneofCase.Added: return(counterEvent.Added); case EventOneofCase.Decremented: return(counterEvent.Decremented); case EventOneofCase.Incremented: return(counterEvent.Incremented); case EventOneofCase.NameChanged: return(counterEvent.NameChanged); case EventOneofCase.Removed: return(counterEvent.Removed); default: throw new InvalidOperationException("Invalid event type"); } }
internal static Counter Apply(Counter counter, CounterEvent counterEvent) { switch (counterEvent.EventCase) { case CounterEvent.EventOneofCase.Added: return(new Counter(new Guid(counterEvent.Id.ToByteArray()), counterEvent.Version, 0, counterEvent.Added.Name)); case CounterEvent.EventOneofCase.Removed: throw new CounterDeletedException(); case CounterEvent.EventOneofCase.Incremented: return(counter.WithCount(counterEvent.Version, counter.Count + 1)); case CounterEvent.EventOneofCase.Decremented: return(counter.WithCount(counterEvent.Version, counter.Count - 1)); case CounterEvent.EventOneofCase.NameChanged: return(counter.WithName(counterEvent.Version, counterEvent.NameChanged.Name)); default: return(counter); } }
public static void Main(string[] args) { Console.WriteLine("----------DotNetCoreSample----------"); // var dataLogger = LogHelper.GetLogger(typeof(DataExtension)); // DataExtension.CommandLogAction = msg => dataLogger.Debug(msg); //AspectTest.ServiceContainerTest(); //ProcessExecutorTest.RawProcessTest(); //ProcessExecutorTest.DotNetInfoTest(); // ProcessExecutorTest.DotNetNugetGlobalPackagesInfoTest(); //LoggerTest.MainTest(); LoggerTest.MicrosoftLoggingTest(); Console.ReadLine(); var services = new ServiceCollection(); services.AddTransient <IFly, MonkeyKing>(); IConfiguration configuration = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build(); var city = configuration.GetAppSetting("City"); var number = configuration.GetAppSetting <int>("Number"); Console.WriteLine($"City:{city}, Number:{number}"); services.AddSingleton(configuration); //services.AddSingleton<IEventStore, EventStoreInMemory>(); //services.AddSingleton<IEventBus, EventBus>(); //services.AddSingleton(DelegateEventHandler.FromAction<CounterEvent>(@event => // LogHelper.GetLogger(typeof(DelegateEventHandler<CounterEvent>)) // .Info($"Event Info: {@event.ToJson()}") // ) //); services.AddSingletonProxy <IFly, MonkeyKing>(); Action <DbContextOptionsBuilder> dbContextOptionsAction = options => { options.UseInMemoryDatabase("Test"); }; services.AddDbContext <TestDbContext>(dbContextOptionsAction); services.AddScopedProxy <TestDbContext>(); services.AddEvents(); services.AddSingletonProxy <IEventBus, EventBus>(); services.AddFluentAspects(options => { options.NoInterceptPropertyGetter <IFly>(f => f.Name); options.InterceptAll() .With <LogInterceptor>() ; options.InterceptMethod <DbContext>(x => x.Name == nameof(DbContext.SaveChanges) || x.Name == nameof(DbContext.SaveChangesAsync)) .With <DbContextSaveInterceptor>() ; options.InterceptMethod <IFly>(f => f.Fly()) .With <LogInterceptor>(); options.InterceptType <IFly>() .With <LogInterceptor>(); options .WithProperty("TraceId", "121212") ; }) // .UseCastleProxy() // .UseAspectCoreProxy() ; DependencyResolver.SetDependencyResolver(services); //var fly = DependencyResolver.ResolveService<IFly>(); //Console.WriteLine(fly.Name); //fly.Fly(); //fly.OpenFly<int>(); //fly.OpenFly<string>(); //fly.FlyAway(); //var animal1 = FluentAspects.AspectOptions.ProxyFactory.CreateInterfaceProxy<IAnimal<int>>(); //animal1.Eat(); //var animal2 = FluentAspects.AspectOptions.ProxyFactory.CreateInterfaceProxy<IAnimal<string>>(); //animal2.Eat(); //var animal = FluentAspects.AspectOptions.ProxyFactory.CreateProxy<Animal<string>>(); //animal.Eat(); //animal.Eat(); //Console.WriteLine(animal.GetEatCount()); //animal.Drink("xxx"); //Console.WriteLine(animal.GetDrinkCount()); //animal = FluentAspects.AspectOptions.ProxyFactory.CreateProxyWithTarget<Animal<string>>(new Animal<string>()); //animal.Eat(); //animal.Eat(); //Console.WriteLine(animal.GetEatCount()); //animal.Drink("xxx"); //Console.WriteLine(animal.GetDrinkCount()); //DependencyResolver.TryInvokeService<TestDbContext>(dbContext => //{ // dbContext.TestEntities.Add(new TestEntity() { Token = "sasa", CreatedTime = DateTime.Now, }); // var hasChanges = dbContext.ChangeTracker.HasChanges(); // Console.WriteLine($"hasChanges:{hasChanges}"); // dbContext.SaveChanges(); //}); //DependencyResolver.TryInvokeService<IEventBus>(eventBus => //{ // eventBus.Publish(new CounterEvent()); //}); DependencyResolver.TryInvoke <IProxyFactory>(proxyFactory => { var counterEvent = new CounterEvent() { Counter = 1 }; var eventBusProxy = proxyFactory.CreateProxy <IEventBus, EventBus>(); eventBusProxy.Publish(counterEvent); var handlerProxy = proxyFactory.CreateProxyWithTarget <IEventHandler <CounterEvent> >(DelegateEventHandler.FromAction <CounterEvent>(e => { Console.WriteLine(e.ToJson()); })); handlerProxy.Handle(counterEvent) .GetAwaiter().GetResult(); }); //DependencyResolver.TryInvokeServiceAsync<TestDbContext>(dbContext => //{ // dbContext.TestEntities.Add(new TestEntity() { Token = "sasa", CreatedTime = DateTime.Now, }); // if (dbContext.ChangeTracker is null) // { // Console.WriteLine($"{nameof(dbContext.ChangeTracker)} is null ..."); // } // else // { // foreach (var entry in dbContext.ChangeTracker.Entries<TestEntity>()) // { // Console.WriteLine(entry.Entity.Token); // } // } // if (dbContext.Database is null) // { // Console.WriteLine($"{nameof(dbContext.Database)} is null ..."); // } // if (dbContext.Database is null) // { // Console.WriteLine($"{nameof(dbContext.Database)} is null ..."); // } // return dbContext.SaveChangesAsync(); //}); //DependencyResolver.ResolveRequiredService<IFly>() // .Fly(); //DependencyInjectionTest.Test(); // EventTest.MainTest(); // SerilogTest.MainTest(); //var builder = new ContainerBuilder(); //builder.RegisterType<MonkeyKing>().As<IFly>(); //DependencyResolver.SetDependencyResolver((IServiceProvider)new AutofacDependencyResolver(builder.Build())); //DependencyInjectionTest.Test(); //int a = 1; //Console.WriteLine(JsonConvert.SerializeObject(a));// output 1 //var pagedListModel = new PagedListModel<int>() //{ // PageNumber = 1, // PageSize = 4, // TotalCount = 10, // Data = new[] { 1, 2, 3, 4 } //}; //Console.WriteLine(pagedListModel.ToJson()); // log test // LoggerTest.MainTest(); // Log4NetTest.MainTest(); //ILoggerFactory loggerFactory = new LoggerFactory(); //loggerFactory.AddConsole(); //loggerFactory.AddDebug(); //loggerFactory.AddDelegateLogger( // (category, logLevel, exception, msg) => // { // Console.WriteLine($"{category}:[{logLevel}] {msg}\n{exception}"); // } //); //var logger = new Logger<Program>(loggerFactory); //logger.LogInformation("Logging information from Microsoft.Extensions.Logging"); //InvokeHelper.TryInvoke(DataExtensionTest.MainTest); //TaskTest.TaskWhenAllTest().GetAwaiter().GetResult(); //Base64UrlEncodeTest.MainTest(); //var a = new { Name = "2123" }; //var name = a.GetProperty("Name").GetValueGetter().Invoke(a); //Console.WriteLine(name); //var structTest = new TestStruct() { Name = "1233" }; //var obj = (object)structTest; //Console.WriteLine(structTest.GetProperty("Name").GetValueGetter<TestStruct>().Invoke(structTest)); //structTest.GetProperty("Name").GetValueSetter().Invoke(obj, "Name1"); //structTest = (TestStruct)obj; //Console.WriteLine(structTest.Name); //Expression<Func<TestEntity, bool>> exp = t => t.Id > 10 && t.Token == "123" && t.Token.Contains("12"); //var str = SqlExpressionParser.ParseExpression(exp); //Console.WriteLine("sql: {0}", str); //exp = t => true; //str = SqlExpressionParser.ParseExpression(exp); //Console.WriteLine("sql: {0}", str); //RepositoryTest.MainTest(); //var securityToken = ApplicationHelper.ApplicationName + "_test_123"; //var code123 = TotpHelper.GenerateCode(securityToken); //Console.WriteLine(code123); //var result = TotpHelper.ValidateCode(securityToken, code123); //Console.WriteLine($"validate result: {result}"); //var ttl = 2; //while (ttl > 1) //{ // ttl = TotpHelper.TTL(securityToken); // Console.WriteLine($"Current ttl: {ttl}, newId: {ObjectIdGenerator.Instance.NewId()}"); // Thread.Sleep(1000); //} //result = TotpHelper.ValidateCode(securityToken, code123); //Console.WriteLine($"validate result1: {result}"); //result = TotpHelper.ValidateCode(securityToken, code123, 60); //Console.WriteLine($"validate result2: {result}"); //var code1234 = TotpHelper.GenerateCode(ApplicationHelper.ApplicationName + "test_1234"); //Console.WriteLine(code1234); // InvokeHelper.TryInvoke(HttpRequesterTest.MainTest); //var pagedListModel = new PagedListModel<int>() //{ // PageNumber = 2, PageSize = 2, TotalCount = 6, Data = new int[] {1, 2}, //}; //var pagedListModel1 = new PagedListModel1<int>() //{ // PageNumber = 2, // PageSize = 2, // TotalCount = 6, // Data = new int[] { 1, 2 }, //}; //Console.WriteLine($"pagedListModel:{JsonConvert.SerializeObject(pagedListModel)}, pagedListModel1:{JsonConvert.SerializeObject(pagedListModel1)}"); //var posts = new[] { new { PostId = 1, PostTitle = "12333", }, new { PostId = 2, PostTitle = "12333", }, }; //var postTags = new[] { new { PostId = 1, Tag = "HHH" } }; //var result = posts.LeftJoin(postTags, p => p.PostId, pt => pt.PostId, (p, pt) => new { p.PostId, p.PostTitle, pt?.Tag }).ToArray(); //Console.WriteLine(result.ToJson()); // CronHelperTest.MainTest(); // DependencyInjectionTest.BuiltInIocTest(); //Expression<Func<TestEntity, bool>> expression = // t => t.Id > 0 && t.CreatedTime < DateTime.Now && t.Token == null; //var visitor = new SqlExpressionVisitor(null); //visitor.Visit(expression); //Console.WriteLine(visitor.GetCondition()); //PipelineTest.TestV2(); //PipelineTest.AsyncPipelineBuilderTestV2().Wait(); Console.ReadLine(); }
private static void CounterGoalReachedAgain(object sender, CounterEvent e) { Console.WriteLine(e.Message); }
protected virtual void OnGoalReached(CounterEvent e) { GoalReached?.Invoke(this, e); }
private static void CounterGoalReached(object sender, CounterEvent e) { Console.WriteLine("Counter reached its goal!"); }
public void Counter(CounterEvent counterEvent) { CounterEvent(counterEvent); }