static void InitializeECommon() { _message = new byte[int.Parse(ConfigurationManager.AppSettings["MessageSize"])]; _mode = ConfigurationManager.AppSettings["Mode"]; _messageCount = int.Parse(ConfigurationManager.AppSettings["MessageCount"]); var logContextText = "mode: " + _mode; ECommonConfiguration .Create() .UseAutofac() .RegisterCommonComponents() .UseLog4Net() .RegisterUnhandledExceptionHandler(); _logger = ObjectContainer.Resolve<ILoggerFactory>().Create(typeof(Program).Name); _performanceService = ObjectContainer.Resolve<IPerformanceService>(); var setting = new PerformanceServiceSetting { AutoLogging = false, StatIntervalSeconds = 1, PerformanceInfoHandler = x => { _logger.InfoFormat("{0}, {1}, totalCount: {2}, throughput: {3}, averageThrughput: {4}, rt: {5:F3}ms, averageRT: {6:F3}ms", _performanceService.Name, logContextText, x.TotalCount, x.Throughput, x.AverageThroughput, x.RT, x.AverageRT); } }; _performanceService.Initialize(_performanceKey, setting); _performanceService.Start(); }
protected AssemblyConfiguration(Dictionary<string, object> defaultValues, ILogger logger) { NameValueCollection nameValues = ConfigurationManager.AppSettings; CreateConfiguration(defaultValues, nameValues); foreach (KeyValuePair<string, string> pair in UsedValues) logger.InfoFormat("Using {0}={1}", pair.Key, pair.Value); }
private T Post <T>(string command, object data) { // create command var httpCommand = new TestRailHttpCommand { Endpoint = command, HttpMethod = HttpMethod.Post.Method, Data = data }; // execute command var entities = HttpExecutor <T>(httpCommand); logger?.InfoFormat(CommandFormat, httpCommand?.Endpoint); // return entity return(entities); }
/// <summary> /// The log elapsed time. /// </summary> /// <param name="logger"> /// The logger. /// </param> /// <param name="prefix"> /// The prefix. /// </param> /// <param name="elapsedTime"> /// The elapsed time. /// </param> /// <param name="numItems"> /// The num items. /// </param> protected void LogElapsedTime(ILogger logger, string prefix, TimeSpan elapsedTime, long numItems) { if (logger.IsInfoEnabled) { logger.InfoFormat( "{0}{1,10:N2} ms = {2,10:N5} ms/item = {3,10:N0} items/s", prefix, elapsedTime.TotalMilliseconds, elapsedTime.TotalMilliseconds / numItems, 1000.0 / elapsedTime.TotalMilliseconds * numItems); } }
public static void WaitForAllHttpRequestsToEnd(ILogger logger) { // http://blogs.msdn.com/b/windowsazure/archive/2013/01/14/the-right-way-to-handle-azure-onstop-events.aspx var pcrc = new PerformanceCounter("ASP.NET", "Requests Current", ""); while (true) { var rc = pcrc.NextValue(); logger.InfoFormat("ASP.NET Requests Current = {0}, {1}.", rc, rc <= 0 ? "permitting role exit" : "blocking role exit"); if (rc <= 0) break; Thread.Sleep(TimeSpan.FromSeconds(1)); } }
public Watcher(string sourcePath, string destinationPath, string filter, ILogger<Watcher> logger) { _logger = logger; SourcePath = sourcePath; DestinationPath = destinationPath; _filter = filter; _watcher = new FileSystemWatcher(sourcePath, filter); _watcher.NotifyFilter = NotifyFilters.LastWrite; _watcher.Changed += Move; _watcher.EnableRaisingEvents = true; _logger.InfoFormat("Watching {0} on {1} to copy to {2}", _sourcePath, _filter, _destinationPath); }
public RequestHandler() { _logger = ObjectContainer.Resolve<ILoggerFactory>().Create(GetType().FullName); _performanceService = ObjectContainer.Resolve<IPerformanceService>(); var setting = new PerformanceServiceSetting { AutoLogging = false, StatIntervalSeconds = 1, PerformanceInfoHandler = x => { _logger.InfoFormat("{0}, totalCount: {1}, throughput: {2}, averageThrughput: {3}, rt: {4:F3}ms, averageRT: {5:F3}ms", _performanceService.Name, x.TotalCount, x.Throughput, x.AverageThroughput, x.RT, x.AverageRT); } }; _performanceService.Initialize(_performanceKey, setting); _performanceService.Start(); }
public void ProcessResult(RawMessage message, ITransport transport, ILogger log) { if (WillRetry(message.RetryCount)) { message.RetryCount++; log.InfoFormat("Message requested to be retried {0} - Retry Count {1}", message.ToString(), message.RetryCount); // Exponential backoff with a 90% - 110% jitter added to avoid synchronized backoffs on failures. var delayTime = TimeSpan.FromMilliseconds((Math.Pow(4, message.RetryCount) * 100) * (1.0 + (new Random().NextDouble() - 0.5) / 5)); message.RetryCount = message.RetryCount; // Convert to a delay result and process var delayResult = new DelayResult(DateTime.UtcNow.Add(delayTime)); delayResult.ProcessResult(message, transport, log); } else { // Out of retries, convert to a fail result var failResult = new FailResult(this.Message); failResult.ProcessResult(message, transport, log); } }
/// <summary> /// Save a file (filepath) in relative path from Git root (identifier) /// </summary> /// <param name="identifier"></param> /// <param name="filepath"></param> public void SaveFile(string identifier, string filepath) { try { if (!File.Exists(filepath)) { _logger.WarnFormat("File {0} not present. Please check the folder where it should be located.", filepath); return; // do nothing } string filepathInWorkDir = identifier; string targetFilePath = Path.Combine(_configurationPath, filepathInWorkDir); string containingDirectory = Path.GetDirectoryName(targetFilePath); if (containingDirectory != null && !Directory.Exists(containingDirectory)) { Directory.CreateDirectory(containingDirectory); } // Check if there is anything that needs to be saved first if (File.Exists(targetFilePath)) { if (FileHelper.AreFilesTheSame(filepath, targetFilePath)) { _logger.InfoFormat("The file {0} that should be persisted has not changed. No action will take place.", targetFilePath); return; } } // Copy the file in the repository File.Copy(filepath, targetFilePath, true); // Commit the change _gitRepo.Index.Add(filepathInWorkDir); string message = string.Format("Saving config file {0} for module {1}", Path.GetFileName(filepath), identifier); _logger.DebugFormat("GIT: committing changes to local branch using default signature ({0})", _signature.Name); _gitRepo.Commit(message, _signature, _signature); PushOptions options = new PushOptions { CredentialsProvider = (url, user, cred) => _credentials }; // Push the change _logger.Debug("GIT: pushing local branch"); _gitRepo.Network.Push(LocalBranch, options); PullOptions pullOptions = new PullOptions { FetchOptions = new FetchOptions { CredentialsProvider = (url, usernameFromUrl, types) => _credentials }, MergeOptions = new MergeOptions { FastForwardStrategy = FastForwardStrategy.Default } }; _logger.Debug("GIT: pulling remote branch"); _gitRepo.Network.Pull(_signature, pullOptions); _logger.InfoFormat("Saved configurations of module {0} to version control system as {1}.", identifier, filepath); } catch (Exception ex) { _logger.ErrorFormat("Failed saving config file {0} for module {1}. Error: {2}", filepath, identifier, ex.Message); } }
public bool SetInput(int input) { if (log.IsDebugEnabled) { log.DebugFormat("SetInput: {0} value {1}", this.FeedbackName, input); } if (input > this.currentInput) { if (this.currentFeedbackLevel == FeedbackLevel.Highest) { return(false); } FeedbackLevel last; var next = this.currentFeedbackLevel; do { last = next; int threshold; this.GetUpperThreshold(last, out threshold); if (input > threshold) { next = this.GetNextHigherThreshold(last, out threshold); } } while (next != last); this.currentInput = input; if (last != this.currentFeedbackLevel) { if (log.IsInfoEnabled) { log.InfoFormat("Transit {0} from {1} to {2} with input {3}", this.FeedbackName, this.currentFeedbackLevel, last, input); } this.currentFeedbackLevel = last; return(true); } } else if (input < this.currentInput && this.currentFeedbackLevel != FeedbackLevel.Lowest) { int threshold; GetLowerThreshold(this.currentFeedbackLevel, out threshold); var next = this.currentFeedbackLevel; while (input < threshold && next != FeedbackLevel.Lowest) { next = this.GetNextLowerThreshold(next, out threshold); } this.currentInput = input; if (next != this.currentFeedbackLevel) { if (log.IsInfoEnabled) { log.InfoFormat("Transit {0} from {1} to {2} with input {3}", this.FeedbackName, this.currentFeedbackLevel, next, input); } this.currentFeedbackLevel = next; return(true); } } return(false); }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); var assemblies = new Assembly[] { Assembly.Load("CooperDemo.Model"), Assembly.Load("CooperDemo.Repositories"), Assembly.Load("CooperDemo") }; Configuration.Config() .SetResolver(new TinyIoCDependencyResolver()) .RegisterDefaultComponents(assemblies); _logger = DependencyResolver.Resolve<ILoggerFactory>().Create(typeof(MainActivity)); _taskFolderService = DependencyResolver.Resolve<ITaskFolderService>(); SetContentView(Resource.Layout.Main); _listView = FindViewById<ListView>(Resource.Id.list); _listView.SetOnCreateContextMenuListener(this); Button button1 = FindViewById<Button>(Resource.Id.GetAllTaskFoldersButton); button1.Click += (sender, e) => { SendGetAllTaskFoldersRequest(); }; SendLoginRequest(); _logger.InfoFormat("Application '{0}' Started.", "Cooper"); }
private Task HandleCommandInternal(ProcessingCommand processingCommand, ICommandHandlerProxy commandHandler, int retryTimes, TaskCompletionSource <bool> taskSource) { var command = processingCommand.Message; var commandContext = processingCommand.CommandExecuteContext; commandContext.Clear(); if (processingCommand.IsDuplicated) { return(RepublishCommandEvents(processingCommand, 0, new TaskCompletionSource <bool>())); } _ioHelper.TryAsyncActionRecursivelyWithoutResult("HandleCommandAsync", async() => { await commandHandler.HandleAsync(commandContext, command).ConfigureAwait(false); }, currentRetryTimes => HandleCommandInternal(processingCommand, commandHandler, currentRetryTimes, taskSource), async() => { _logger.InfoFormat("Handle command success. handlerType:{0}, commandType:{1}, commandId:{2}, aggregateRootId:{3}", commandHandler.GetInnerObject().GetType().Name, command.GetType().Name, command.Id, command.AggregateRootId); if (commandContext.GetApplicationMessage() != null) { await CommitChangesAsync(processingCommand, true, commandContext.GetApplicationMessage(), null, new TaskCompletionSource <bool>()).ConfigureAwait(false); taskSource.SetResult(true); } else { try { await CommitAggregateChanges(processingCommand).ConfigureAwait(false); taskSource.SetResult(true); } catch (AggregateRootReferenceChangedException aggregateRootReferenceChangedException) { _logger.InfoFormat("Aggregate root reference changed when processing command, try to re-handle the command. aggregateRootId: {0}, aggregateRootType: {1}, commandId: {2}, commandType: {3}, handlerType: {4}", aggregateRootReferenceChangedException.AggregateRoot.UniqueId, aggregateRootReferenceChangedException.AggregateRoot.GetType().Name, command.Id, command.GetType().Name, commandHandler.GetInnerObject().GetType().Name ); await HandleCommandInternal(processingCommand, commandHandler, 0, taskSource).ConfigureAwait(false); } catch (Exception ex) { _logger.Error(string.Format("Commit aggregate changes has unknown exception, this should not be happen, and we just complete the command, handlerType:{0}, commandType:{1}, commandId:{2}, aggregateRootId:{3}", commandHandler.GetInnerObject().GetType().Name, command.GetType().Name, command.Id, command.AggregateRootId), ex); await CompleteCommand(processingCommand, CommandStatus.Failed, ex.GetType().Name, "Unknown exception caught when committing changes of command.").ConfigureAwait(false); taskSource.SetResult(true); } } }, () => string.Format("[command:[id:{0},type:{1}],handlerType:{2},aggregateRootId:{3}]", command.Id, command.GetType().Name, commandHandler.GetInnerObject().GetType().Name, command.AggregateRootId), async(ex, errorMessage) => { await HandleExceptionAsync(processingCommand, commandHandler, ex, errorMessage, 0, new TaskCompletionSource <bool>()).ConfigureAwait(false); taskSource.SetResult(true); }, retryTimes); return(taskSource.Task); }
private static bool CheckMonoVersion(ILogger logger) { // check for Mono runtime if (!Core.Application.IsRunningOnMono) { return true; } Version monoVersion = null; try { monoVersion = Core.Application.GetMonoVersionNumer(); } catch (Exception ex) { logger.Warn(Properties.Resources.MonoDetectFailed, ex); } if (monoVersion != null) { if (monoVersion.Major < 2 || (monoVersion.Major == 2 && monoVersion.Minor < 8)) { var ex = new InvalidOperationException(Properties.Resources.MonoTooOld); ShowStartupError(ex); return false; } logger.InfoFormat("Running on Mono v{0}...", monoVersion); } else { logger.Info("Running on Mono..."); } return true; }
public void TestInitialize() { _logger.InfoFormat("----Start to run test: {0}", TestContext.CurrentContext.Test.Name); }
public TcpConnection(Socket socket, IBufferPool bufferPool, Action<ITcpConnection, byte[]> messageArrivedHandler, Action<ITcpConnection, SocketError> connectionClosedHandler) { Ensure.NotNull(socket, "socket"); Ensure.NotNull(messageArrivedHandler, "messageArrivedHandler"); Ensure.NotNull(connectionClosedHandler, "connectionClosedHandler"); _socket = socket; _bufferPool = bufferPool; _localEndPoint = socket.LocalEndPoint; _remotingEndPoint = socket.RemoteEndPoint; _messageArrivedHandler = messageArrivedHandler; _connectionClosedHandler = connectionClosedHandler; _sendSocketArgsStack = new ConcurrentStack<SocketAsyncEventArgs>(); for (var i = 0; i < 5; i++) { var sendSocketArgs = new SocketAsyncEventArgs(); sendSocketArgs.AcceptSocket = socket; sendSocketArgs.Completed += OnSendAsyncCompleted; _sendSocketArgsStack.Push(sendSocketArgs); } _receiveSocketArgs = new SocketAsyncEventArgs(); _receiveSocketArgs.AcceptSocket = socket; _receiveSocketArgs.Completed += OnReceiveAsyncCompleted; _logger = ObjectContainer.Resolve<ILoggerFactory>().Create(GetType().FullName); _framer = new LengthPrefixMessageFramer(); _framer.RegisterMessageArrivedCallback(OnMessageArrived); _scheduleService.StartTask("PrintStreamBufferLength", () => { _logger.InfoFormat("_sendingCount: {0}, _sentCount: {1}", _sendingCount, _sentCount); }, 1000, 1000); TryReceive(); TrySend(); }
public void Handle(ICommandContext context, ChangeNoteTitleCommand command) { context.Get <Note>(command.AggregateRootId).ChangeTitle(command.Title); _logger.InfoFormat("Handled {0}, Note Title:{1}", typeof(ChangeNoteTitleCommand).Name, command.Title); }
public Producer Start() { _remotingClient.Start(); _logger.InfoFormat("Started, producerId:{0}", Id); return(this); }
private void GiveCreditsReward(MmoActor player, ContractCreditsDataReward contractCreditsDataReward) { player.ActionExecutor._AddCredits(contractCreditsDataReward.count); s_Log.InfoFormat("credits reward complete: {0} added".Color(LogColor.orange), contractCreditsDataReward.count); }
/// <summary> /// Initializes the provider by pulling the config info from the web.config and validate/create the DynamoDB table. /// If the table is being created this method will block until the table is active. /// </summary> /// <param name="name"></param> /// <param name="config"></param> public override void Initialize(string name, NameValueCollection config) { _logger.InfoFormat("Initialize : Initializing Session provider {0}", name); if (config == null) { throw new ArgumentNullException("config"); } base.Initialize(name, config); GetConfigSettings(config); RegionEndpoint region = null; if (!string.IsNullOrEmpty(this._regionName)) { region = RegionEndpoint.GetBySystemName(this._regionName); } AWSCredentials credentials = null; if (!string.IsNullOrEmpty(this._accessKey)) { credentials = new BasicAWSCredentials(this._accessKey, this._secretKey); } else if (!string.IsNullOrEmpty(this._profileName)) { if (string.IsNullOrEmpty(this._profilesLocation)) { credentials = new StoredProfileAWSCredentials(this._profileName); } else { credentials = new StoredProfileAWSCredentials(this._profileName, this._profilesLocation); } } AmazonDynamoDBConfig ddbConfig = new AmazonDynamoDBConfig(); if (region != null) { ddbConfig.RegionEndpoint = region; } if (!string.IsNullOrEmpty(this._serviceURL)) { ddbConfig.ServiceURL = this._serviceURL; } if (credentials != null) { this._ddbClient = new AmazonDynamoDBClient(credentials, ddbConfig); } else { this._ddbClient = new AmazonDynamoDBClient(ddbConfig); } ((AmazonDynamoDBClient)this._ddbClient).BeforeRequestEvent += DynamoDBSessionStateStore_BeforeRequestEvent; SetupTable(); }
private void _wavCombine_PlayStateCallback(Domain.wavFileInfo.PlayStateData input) { try { var entity = _commAudioFileNameRepository.FirstOrDefault(x => x.FileName == input.FileName); if (entity == null) { var name = Path.GetFileName(input.FileName); if (!string.IsNullOrEmpty(name) && name.StartsWith("HandTxt")) { if (input.PlayState == 1) { _play.SetPlayWayAuto(); } logger.InfoFormat("手动插播:{0},状态:{1}", input.FileName, input.PlayState); } else { logger.ErrorFormat("数据库中未找到正在播放的文件:{0},状态:{1}(0开始播放,1播放结束)", input.FileName, input.PlayState); } return; } if (input.PlayState == 0) { entity.StartPlayTime = DateTime.Now; entity.PlayStatus = PlayStatus.开始播放; } else if (input.PlayState == 1) { entity.EndPlayTime = DateTime.Now; entity.PlayStatus = PlayStatus.播放完成; } _commAudioFileNameRepository.Update(entity); _logRepository.Insert(new PlayAudioLog() { FileName = input.FileName, Remark = entity.PlayStatus.ToString() + ":" + entity.Remark }); var ports = _commAudioFileNameRepository.GetAllList(x => x.PlayStatus == PlayStatus.开始播放).Select(x => x.PlayPort).ToList(); var port = new TpPortDto(); ports.ForEach(x => { if (!string.IsNullOrEmpty(x) && x.Length == 8) { var cs = x.ToArray(); port.P1 = (cs[0] == '1' || port.P1); port.P2 = (cs[1] == '1' || port.P2); port.P3 = (cs[2] == '1' || port.P3); port.P4 = (cs[3] == '1' || port.P4); port.P5 = (cs[4] == '1' || port.P5); port.P6 = (cs[5] == '1' || port.P6); port.P7 = (cs[6] == '1' || port.P7); port.P8 = (cs[7] == '1' || port.P8); } }); try { hub.RefreshNowPlayAudio(port); }catch (Exception ex) { logger.Error("未登录:" + ex.Message, ex); // logger.ErrorFormat("播放状态数据改变通知前台异常:{0}", ex.Message + ex.Source); } } catch (Exception ex) { var s = ex; logger.ErrorFormat("播放状态数据改变异常{0}:", ex.Message + ex.Source); } }
public void Start(string[] args) { _sw.Start(); var configuration = ConfigurationManager.OpenExeConfiguration("Cdev.Spartan.Sevice.Manager.exe"); var section = configuration.GetSection("gps") as GpsSectionConfig; if (section == null) { throw new NullReferenceException("配置错误!找不到配置节点 gps"); } var config = section.Storages.FirstOrDefault(p => p.Name.ToLower() == args[0].ToLower()); if (config == null) { throw new NullReferenceException("配置错误!找不到任何存储配置"); } var logConfigPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Log4net", config.Name.ToLower() + ".config"); if (!File.Exists(logConfigPath)) { var text = File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Log4net", "log4net.config")); text = text.Replace(@"log\main\", @"log\" + config.Name.ToLower() + @"\"); File.WriteAllText(logConfigPath, text); } _logger = new Log4NetLogger(logConfigPath); _sw.Stop(); _logger.InfoFormat("加载配置信息[{0}毫秒]!", _sw.ElapsedMilliseconds); _sw.Restart(); try { DMContext.SetConnectionString(configuration.ConnectionStrings.ConnectionStrings["DefaultConnectionString"].ConnectionString); CdevContainer.Ins.SetContainer(new UnityObjectContainer()); #region 注入基础服务 CdevContainer.Ins.RegisterInstance(_logger); CdevContainer.Ins.RegisterType<IRepository, Repository>(); CdevContainer.Ins.RegisterType<ICacheService, CacheService>(); CdevContainer.Ins.RegisterType<IConfigService, ConfigService>(); CdevContainer.Ins.RegisterType<IStateService, StateService>(); CdevContainer.Ins.RegisterType<IUserService, UserService>(); CdevContainer.Ins.RegisterType<IMapService, MapService>(); CdevContainer.Ins.RegisterType<IAppSocketClient, DefaultAppTcpSocketClient>("DefaultAppTcpSocketClient", IOCLife.Transient); CdevContainer.Ins.RegisterType<IAppSocketClient, DefaultAppUdpSocketClient>("DefaultAppUdpSocketClient", IOCLife.Transient); _sw.Stop(); _logger.InfoFormat("加载基础服务[{0}毫秒]!", _sw.ElapsedMilliseconds); _sw.Restart(); #endregion 注入基础服务 #region 注入核心服务 CdevContainer.Ins.RegisterType<INodeService, NodeService>(); CdevContainer.Ins.RegisterType<IMileageService, MileageService>(); CdevContainer.Ins.RegisterType<IDeviceGroupService, DeviceGroupService>(); CdevContainer.Ins.RegisterType<IDeviceService, DeviceService>(); CdevContainer.Ins.RegisterType<IPositionService, PositionService>(); _sw.Stop(); _logger.InfoFormat("加载核心服务[{0}毫秒]!", _sw.ElapsedMilliseconds); _sw.Restart(); #endregion 注入核心服务 foreach (var handlerConfig in config.Handlers) { var array = handlerConfig.Type.Split(','); var handler = AssemblyHelper.GetAssemblyByName(array[1].Trim()).CreateInstance(array[0].Trim()) as AbstractForwardHandler; if (handler == null) throw new NullReferenceException("没有找到转发处理器!{0}".GetFormat(handlerConfig.Name)); CdevContainer.Ins.RegisterInstance(handlerConfig.Name, handler, IOCLife.Transient); handler.SetConfig(handlerConfig.Name); handler.Start(); _handlers.Add(handler); } _sw.Stop(); _logger.InfoFormat("加载处理器[{0}毫秒]!", _sw.ElapsedMilliseconds); } catch (Exception ex) { _logger.Error(ex); return; } _logger.Info("开启转发数据服务成功!"); }
internal static void ConsumeDataSimple(ConsumeDataHelperArguments dumpdataOptions) { correlationID = 0; totalCountUTF8 = 0; totalCountOriginal = 0; totalCount = 0; lastNotifytotalCount = 0; KafkaSimpleManagerConfiguration config = new KafkaSimpleManagerConfiguration() { FetchSize = dumpdataOptions.FetchSize, BufferSize = dumpdataOptions.BufferSize, MaxWaitTime = dumpdataOptions.MaxWaitTime, MinWaitBytes = dumpdataOptions.MinWaitBytes, Zookeeper = dumpdataOptions.Zookeeper }; config.Verify(); bool finish = false; try { using (KafkaSimpleManager <int, Message> kafkaSimpleManager = new KafkaSimpleManager <int, Message>(config)) { TopicMetadata topicMetadata = kafkaSimpleManager.RefreshMetadata(0, ClientID, correlationID++, dumpdataOptions.Topic, true); while (true) { try { for (int i = 0; i <= topicMetadata.PartitionsMetadata.Max(r => r.PartitionId); i++) { if (dumpdataOptions.PartitionIndex == -1 || i == dumpdataOptions.PartitionIndex) { #region Get real offset and adjust long earliest = 0; long latest = 0; long offsetBase = 0; OffsetHelper.GetAdjustedOffset <int, Message>(dumpdataOptions.Topic , kafkaSimpleManager, i , KafkaNetLibraryExample.ConvertOffsetType(dumpdataOptions.Offset) , KafkaNetLibraryExample.ConvertOffset(dumpdataOptions.Offset) , dumpdataOptions.LastMessagesCount, out earliest, out latest, out offsetBase); #endregion Console.WriteLine("Topic:{0} Partition:{1} will read from {2} earliest:{3} latest:{4}", dumpdataOptions.Topic, i, offsetBase, earliest, latest); finish = ConsumeDataOfOnePartition(kafkaSimpleManager, i, offsetBase, earliest, latest, dumpdataOptions); if (finish) { break; } } } finish = true; } catch (Exception ex) { Logger.ErrorFormat("ConsumeDataSimple Got exception, will refresh metadata. {0}", ex.FormatException()); kafkaSimpleManager.RefreshMetadata(0, ClientID, correlationID++, dumpdataOptions.Topic, true); } if (finish) { break; } } } Logger.InfoFormat("Topic:{0} Finish Read. totalCount:{1} ", dumpdataOptions.Topic, totalCount); } catch (Exception ex) { Logger.ErrorFormat("ConsumeDataSimple Got exception:{0}\r\ninput parameter: {1}", ex.FormatException(), dumpdataOptions.ToString()); } }
protected virtual async Task ConsumeMessage(IMessageContext commandContext) { try { var command = commandContext.Message as ICommand; var needReply = !string.IsNullOrEmpty(commandContext.ReplyToEndPoint); var sagaInfo = commandContext.SagaInfo; IMessageContext messageReply = null; if (command == null) { _internalConsumer.CommitOffset(commandContext); return; } var needRetry = command.NeedRetry; using (var scope = IoCFactory.Instance.CurrentContainer.CreateChildContainer()) { scope.RegisterInstance(typeof(IMessageContext), commandContext); var messageStore = scope.Resolve <IMessageStore>(); var eventMessageStates = new List <MessageState>(); var commandHandledInfo = messageStore.GetCommandHandledInfo(commandContext.MessageID); if (commandHandledInfo != null) { if (needReply) { messageReply = _messageQueueClient.WrapMessage(commandHandledInfo.Result, commandContext.MessageID, commandContext.ReplyToEndPoint, producer: Producer, messageId: ObjectId.GenerateNewId().ToString()); eventMessageStates.Add(new MessageState(messageReply)); } } else { var eventBus = scope.Resolve <IEventBus>(); var messageHandlerType = _handlerProvider.GetHandlerTypes(command.GetType()).FirstOrDefault(); _logger?.InfoFormat("Handle command, commandID:{0}", commandContext.MessageID); if (messageHandlerType == null) { _logger?.Debug($"command has no handlerTypes, message:{command.ToJson()}"); if (needReply) { messageReply = _messageQueueClient.WrapMessage(new NoHandlerExists(), commandContext.MessageID, commandContext.ReplyToEndPoint, producer: Producer); eventMessageStates.Add(new MessageState(messageReply)); } } else { object messageHandler = null; do { try { if (messageHandler == null) { messageHandler = scope.Resolve(messageHandlerType.Type); } using (var transactionScope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted }, TransactionScopeAsyncFlowOption.Enabled)) { if (messageHandlerType.IsAsync) { await((dynamic)messageHandler).Handle((dynamic)command) .ConfigureAwait(false); } else { var handler = messageHandler; await Task.Run(() => { ((dynamic)handler).Handle((dynamic)command); }).ConfigureAwait(false); } if (needReply) { messageReply = _messageQueueClient.WrapMessage(commandContext.Reply, commandContext.MessageID, commandContext.ReplyToEndPoint, producer: Producer); eventMessageStates.Add(new MessageState(messageReply)); } eventBus.GetEvents() .ForEach(@event => { var topic = @event.GetFormatTopic(); var eventContext = _messageQueueClient.WrapMessage(@event, commandContext.MessageID, topic, @event.Key, sagaInfo: sagaInfo, producer: Producer); eventMessageStates.Add(new MessageState(eventContext)); }); eventBus.GetToPublishAnywayMessages() .ForEach(@event => { var topic = @event.GetFormatTopic(); var eventContext = _messageQueueClient.WrapMessage(@event, commandContext.MessageID, topic, @event.Key, sagaInfo: sagaInfo, producer: Producer); eventMessageStates.Add(new MessageState(eventContext)); }); eventMessageStates.AddRange(GetSagaReplyMessageStates(sagaInfo, eventBus)); messageStore.SaveCommand(commandContext, commandContext.Reply, eventMessageStates.Select(s => s.MessageContext).ToArray()); transactionScope.Complete(); } needRetry = false; } catch (Exception e) { eventMessageStates.Clear(); messageStore.Rollback(); if (e is OptimisticConcurrencyException && needRetry) { eventBus.ClearMessages(); } else { if (needReply) { messageReply = _messageQueueClient.WrapMessage(e.GetBaseException(), commandContext.MessageID, commandContext.ReplyToEndPoint, producer: Producer, messageId: ObjectId.GenerateNewId().ToString()); eventMessageStates.Add(new MessageState(messageReply)); } eventBus.GetToPublishAnywayMessages() .ForEach(@event => { var topic = @event.GetFormatTopic(); var eventContext = _messageQueueClient.WrapMessage(@event, commandContext.MessageID, topic, @event.Key, sagaInfo: sagaInfo, producer: Producer); eventMessageStates.Add(new MessageState(eventContext)); }); if (e is DomainException exception) { var domainExceptionEvent = exception.DomainExceptionEvent; if (domainExceptionEvent != null) { var topic = domainExceptionEvent.GetFormatTopic(); var exceptionMessage = _messageQueueClient.WrapMessage(domainExceptionEvent, commandContext.MessageID, topic, producer: Producer); eventMessageStates.Add(new MessageState(exceptionMessage)); } _logger?.Warn(command.ToJson(), e); } else { _logger?.Error(command.ToJson(), e); //if we meet with unknown exception, we interrupt saga if (sagaInfo != null) { eventBus.FinishSaga(e); } } eventMessageStates.AddRange(GetSagaReplyMessageStates(sagaInfo, eventBus)); messageStore.SaveFailedCommand(commandContext, e, eventMessageStates.Select(s => s.MessageContext).ToArray()); needRetry = false; } } } while (needRetry); } } if (eventMessageStates.Count > 0) { var sendTask = _messagePublisher.SendAsync(eventMessageStates.ToArray()); // we don't need to wait the send task complete here. } } } catch (Exception ex) { _logger?.Fatal($"consume command failed", ex); } _internalConsumer.CommitOffset(commandContext); }
public void Start(string[] args) { _sw.Start(); var configuration = ConfigurationManager.OpenExeConfiguration("Cdev.Spartan.Sevice.Manager.exe"); var section = configuration.GetSection("gps") as GpsSectionConfig; if (section == null) { throw new NullReferenceException("配置错误!找不到配置节点 gps"); } var config = section.Gateways.FirstOrDefault(p => p.Name.ToLower() == args[0].ToLower()); if (config == null) { throw new NullReferenceException("配置错误!找不到任何网关配置"); } var logConfigPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Log4net", config.Name.ToLower() + ".config"); if (!File.Exists(logConfigPath)) { var text = File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Log4net", "log4net.config")); text = text.Replace(@"log\main\", @"log\" + config.Name.ToLower() + @"\"); File.WriteAllText(logConfigPath, text); } _logger = new Log4NetLogger(logConfigPath); _sw.Stop(); _logger.InfoFormat("加载配置信息[{0}毫秒]!", _sw.ElapsedMilliseconds); _sw.Restart(); try { DMContext.SetConnectionString(configuration.ConnectionStrings.ConnectionStrings["DefaultConnectionString"].ConnectionString); CdevContainer.Ins.SetContainer(new UnityObjectContainer()); _server = new DefaultAppSocketTcpServer(config.Host, config.Port, config.BufferSize, config.MaxConnect,CdevContainer.Ins.Container, (c) => { #region 注入基础服务 CdevContainer.Ins.RegisterInstance(_logger); #if DEBUG CdevContainer.Ins.RegisterInstance<IRawDataService>(new RawDataService(config.RawDataSavePath, 1)); #else CdevContainer.Ins.RegisterInstance<IRawDataService>(new RawDataService(config.RawDataSavePath)); #endif CdevContainer.Ins.RegisterType<IRepository, Repository>(); CdevContainer.Ins.RegisterType<ICacheService, CacheService>(); CdevContainer.Ins.RegisterType<IConfigService, ConfigService>(); CdevContainer.Ins.RegisterType<IStateService, StateService>(); CdevContainer.Ins.RegisterType<ISmsService, SmsService>(); CdevContainer.Ins.RegisterType<IEmailService, EmailService>(); CdevContainer.Ins.RegisterType<IUserService, UserService>(); CdevContainer.Ins.RegisterType<IMapService, MapService>(); _sw.Stop(); _logger.InfoFormat("加载基础服务[{0}毫秒]!", _sw.ElapsedMilliseconds); _sw.Restart(); #endregion 注入基础服务 #region 注入核心服务 CdevContainer.Ins.RegisterType<INodeService, NodeService>(); CdevContainer.Ins.RegisterType<IMileageService, MileageService>(); CdevContainer.Ins.RegisterType<IDeviceGroupService, DeviceGroupService>(); CdevContainer.Ins.RegisterType<IDeviceService, DeviceService>(); CdevContainer.Ins.RegisterType<IPositionService, PositionService>(); CdevContainer.Ins.RegisterType<IQueueService, QueueService>(); _sw.Stop(); _logger.InfoFormat("加载核心服务[{0}毫秒]!", _sw.ElapsedMilliseconds); _sw.Restart(); //指令 CdevContainer.Ins.RegisterType<IInstructionHandler, Gt06InstructionHandler>(); CdevContainer.Ins.RegisterInstance<IInstructionReceiveService>(new InstructionReceiveService(config.Name)); CdevContainer.Ins.RegisterType<IInstructionService, InstructionService>(); //处理器 CdevContainer.Ins.RegisterType<IAppSocketProtocol, Gt06Protocol>(); CdevContainer.Ins.RegisterType<IAppSocketServerEvent, Gt06ServerEvent>(); _sw.Stop(); _logger.InfoFormat("加载核心服务[{0}毫秒]!", _sw.ElapsedMilliseconds); _sw.Restart(); #endregion 注入核心服务 #region 加载缓存数据 //加载设备数据 CdevContainer.Ins.Resolve<IDeviceService>().LoadAllDeviceByDeviceGpsCodeToCache(); _sw.Stop(); _logger.InfoFormat("加载缓存数据[{0}毫秒]!", _sw.ElapsedMilliseconds); _sw.Restart(); #endregion #region 注入队列 if ("all".Equals(config.Queue.ToLower())) { foreach (var queueConfig in section.Queues) { CdevContainer.Ins.RegisterInstance<ISendQueue>(queueConfig.Name,new DefaultSendQueue(queueConfig.Name, queueConfig.Uri), IOCLife.Singleton); } } else { var queues = config.Queue.Split(','); foreach (var queueConfig in queues.Select(name => section.Queues.FirstOrDefault(p => p.Name == name)).Where(queueConfig => queueConfig != null)) { CdevContainer.Ins.RegisterInstance<ISendQueue>(queueConfig.Name,new DefaultSendQueue(queueConfig.Name, queueConfig.Uri), IOCLife.Singleton); } } _sw.Stop(); _logger.InfoFormat("加载发送数据服务[{0}毫秒]!", _sw.ElapsedMilliseconds); #endregion }); _server.Start(); } catch (Exception ex) { _logger.Error(ex); return; } _logger.Info("开启网关服务成功!"); }
protected virtual void ConsumeMessage(IMessageContext commandContext) { var command = commandContext.Message as ICommand; IMessageContext messageReply = null; if (command == null) { return; } var needRetry = command.NeedRetry; PerMessageContextLifetimeManager.CurrentMessageContext = commandContext; List <IMessageContext> eventContexts = new List <IMessageContext>(); var messageStore = IoCFactory.Resolve <IMessageStore>(); var eventBus = IoCFactory.Resolve <IEventBus>(); var commandHasHandled = messageStore.HasCommandHandled(commandContext.MessageID); if (commandHasHandled) { messageReply = _messageQueueClient.WrapMessage(new MessageDuplicatelyHandled(), commandContext.MessageID, commandContext.ReplyToEndPoint); eventContexts.Add(messageReply); } else { var messageHandler = _handlerProvider.GetHandler(command.GetType()); _logger.InfoFormat("Handle command, commandID:{0}", commandContext.MessageID); if (messageHandler == null) { messageReply = _messageQueueClient.WrapMessage(new NoHandlerExists(), commandContext.MessageID, commandContext.ReplyToEndPoint); eventContexts.Add(messageReply); } else { do { try { using (var transactionScope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted })) { ((dynamic)messageHandler).Handle((dynamic)command); messageReply = _messageQueueClient.WrapMessage(commandContext.Reply, commandContext.MessageID, commandContext.ReplyToEndPoint); eventContexts.Add(messageReply); eventBus.GetMessages().ForEach(@event => { var eventContext = _messageQueueClient.WrapMessage(@event, commandContext.MessageID); eventContexts.Add(eventContext); }); messageStore.SaveCommand(commandContext, eventContexts.ToArray()); transactionScope.Complete(); } needRetry = false; } catch (Exception e) { eventContexts.Clear(); if (e is OptimisticConcurrencyException && needRetry) { eventBus.ClearMessages(); } else { messageReply = _messageQueueClient.WrapMessage(e.GetBaseException(), commandContext.MessageID, commandContext.ReplyToEndPoint); eventContexts.Add(messageReply); if (e is DomainException) { _logger.Warn(command.ToJson(), e); } else { _logger.Error(command.ToJson(), e); } messageStore.SaveFailedCommand(commandContext, e, messageReply); needRetry = false; } } } while (needRetry); } } if (_messagePublisher != null && eventContexts.Count > 0) { _messagePublisher.Send(eventContexts.ToArray()); } }
public void CheckAppOffline() { try { if (this.checkOfflineTimer != null) { this.checkOfflineTimer.Dispose(); this.checkOfflineTimer = null; } if (!File.Exists(this.appOfflineFile)) { this.workloadController.ServerState = ServerState.Normal; if (log.IsInfoEnabled) { log.InfoFormat("Server state is set to online"); } return; } string[] serverStateFileContent; try { serverStateFileContent = File.ReadAllLines(this.appOfflineFile); } catch (IOException ioException) { var hresult = System.Runtime.InteropServices.Marshal.GetHRForException(ioException); // check for sharing violation if ((hresult & 0xFFFF) == 0x20) { // the file is still in use this.checkOfflineTimer = new Timer(this.OnCheckAppOfflineTimer, null, 1000, System.Threading.Timeout.Infinite); } else { log.Error(ioException); } return; } if (serverStateFileContent.Length == 0) { log.ErrorFormat("ServerState file is empty. Current Server state {0} is unchanged.", this.workloadController.ServerState); return; } var serverStateLine = serverStateFileContent[0]; int requestedState; if (int.TryParse(serverStateLine, out requestedState) == false) { log.WarnFormat("Invalid app state specified: {0}", serverStateLine); return; } if ((ServerState)requestedState == this.workloadController.ServerState) { return; } var offlineTime = TimeSpan.FromMinutes(15); var offlineTimeString = serverStateFileContent.Length > 1 ? serverStateFileContent[1] : string.Empty; if (!string.IsNullOrEmpty(offlineTimeString)) { if (TimeSpan.TryParse(offlineTimeString, out offlineTime) == false) { log.WarnFormat("Failed to parse offline time: {0}", offlineTimeString); return; } } if (log.IsInfoEnabled) { log.InfoFormat("Server will be taken offline in {0}", offlineTime); } this.appOfflineDate = DateTime.UtcNow.Add(offlineTime); var oldState = this.workloadController.ServerState; this.workloadController.ServerState = (ServerState)requestedState; if (this.OnNewServerState != null) { this.OnNewServerState(oldState, (ServerState)requestedState, offlineTime); } } catch (Exception ex) { log.Error(ex); } }
public void Start(string[] args) { _sw.Start(); var configuration = ConfigurationManager.OpenExeConfiguration("Cdev.Spartan.Sevice.Manager.exe"); var section = configuration.GetSection("gps") as GpsSectionConfig; if (section == null) { throw new NullReferenceException("配置错误!找不到配置节点 gps"); } var config = section.Storages.FirstOrDefault(p => p.Name.ToLower() == args[0].ToLower()); if (config == null) { throw new NullReferenceException("配置错误!找不到任何存储配置"); } var logConfigPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Log4net",config.Name.ToLower() + ".config"); if (!File.Exists(logConfigPath)) { var text =File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Log4net", "log4net.config")); text = text.Replace(@"log\main\", @"log\" + config.Name.ToLower() + @"\"); File.WriteAllText(logConfigPath, text); } _sw.Stop(); _logger = new Log4NetLogger(logConfigPath); _logger.InfoFormat("加载配置信息[{0}毫秒]!", _sw.ElapsedMilliseconds); _sw.Restart(); try { DMContext.SetConnectionString(configuration.ConnectionStrings.ConnectionStrings["DefaultConnectionString"].ConnectionString); CdevContainer.Ins.SetContainer(new UnityObjectContainer()); #region 注入基础服务 CdevContainer.Ins.RegisterInstance(_logger); CdevContainer.Ins.RegisterType<IRepository, Repository>(); CdevContainer.Ins.RegisterType<ICacheService, CacheService>(); CdevContainer.Ins.RegisterType<IConfigService, ConfigService>(); CdevContainer.Ins.RegisterType<IStateService, StateService>(); CdevContainer.Ins.RegisterType<ISmsService, SmsService>(); CdevContainer.Ins.RegisterType<IEmailService, EmailService>(); CdevContainer.Ins.RegisterType<IPushService, PushService>(); CdevContainer.Ins.RegisterType<IUserService, UserService>(); CdevContainer.Ins.RegisterType<IMapService, MapService>(); CdevContainer.Ins.RegisterType<ISiteMessageService, SiteMessageService>(); _sw.Stop(); _logger.InfoFormat("加载基础服务[{0}毫秒]!", _sw.ElapsedMilliseconds); _sw.Restart(); #endregion 注入基础服务 #region 注入核心服务 CdevContainer.Ins.RegisterType<INodeService, NodeService>(); CdevContainer.Ins.RegisterType<IAreaService, AreaService>(); CdevContainer.Ins.RegisterType<IDeviceGroupService, DeviceGroupService>(); CdevContainer.Ins.RegisterType<IDeviceService, DeviceService>(); CdevContainer.Ins.RegisterType<IPositionService, PositionService>(); CdevContainer.Ins.RegisterType<IAlarmService, AlarmService>(); _sw.Stop(); _logger.InfoFormat("加载核心服务[{0}毫秒]!", _sw.ElapsedMilliseconds); _sw.Restart(); #endregion 注入核心服务 #region 加载缓存数据 //加载区域数据 CdevContainer.Ins.Resolve<IAreaService>().LoadAllAreaByIdToCache(); //加载设备数据 CdevContainer.Ins.Resolve<IDeviceService>().LoadAllDeviceByDeviceGpsCodeToCache(); //加载报警数据 CdevContainer.Ins.Resolve<IAlarmService>().LoadAllAlarmSettingByDeviceIdToCache(); _sw.Stop(); _logger.InfoFormat("加载缓存数据[{0}毫秒]!", _sw.ElapsedMilliseconds); _sw.Restart(); #endregion foreach (var handlerConfig in config.Handlers) { var array = handlerConfig.Type.Split(','); var handler = AssemblyHelper.GetAssemblyByName(array[1].Trim()).CreateInstance(array[0].Trim()) as AbstractAlarmHandler; if (handler == null) throw new NullReferenceException("没有找到队里处理器!{0}".GetFormat(handlerConfig.Name)); CdevContainer.Ins.RegisterInstance(handlerConfig.Name, handler, IOCLife.Transient); var queueConfig = section.Queues.FirstOrDefault(p => p.Name == handlerConfig.Queue); if (queueConfig == null) throw new NullReferenceException("没有找到队列处理器的队列配置!{0},{1}".GetFormat(handlerConfig.Name, handlerConfig.Queue)); handler.SetPackageQueue(new DefaultReceiveQueue(queueConfig.Name, queueConfig.Uri)); handler.Start(); _handlers.Add(handler); } _sw.Stop(); _logger.InfoFormat("加载处理器[{0}毫秒]!", _sw.ElapsedMilliseconds); } catch (Exception ex) { _logger.Error(ex); return; } _logger.Info("开启报警服务成功!"); }
/// <summary> /// Generates a report using given configuration. /// </summary> /// <param name="reportConfiguration">The report configuration.</param> /// <param name="settings">The settings.</param> /// <param name="riskHotspotsAnalysisThresholds">The risk hotspots analysis thresholds.</param> /// <returns><c>true</c> if report was generated successfully; otherwise <c>false</c>.</returns> public bool GenerateReport( IReportConfiguration reportConfiguration, Settings settings, RiskHotspotsAnalysisThresholds riskHotspotsAnalysisThresholds) { if (reportConfiguration == null) { throw new ArgumentNullException(nameof(reportConfiguration)); } if (settings == null) { throw new ArgumentNullException(nameof(settings)); } if (riskHotspotsAnalysisThresholds == null) { throw new ArgumentNullException(nameof(riskHotspotsAnalysisThresholds)); } try { var pluginLoader = new ReflectionPluginLoader(reportConfiguration.Plugins); IReportBuilderFactory reportBuilderFactory = new ReportBuilderFactory(pluginLoader); // Set log level before validation is performed LoggerFactory.VerbosityLevel = reportConfiguration.VerbosityLevel; Logger.Debug($"{Resources.Executable}: {typeof(Program).Assembly.Location}"); Logger.Debug($"{Resources.WorkingDirectory}: {Directory.GetCurrentDirectory()}"); if (!new ReportConfigurationValidator(reportBuilderFactory).Validate(reportConfiguration)) { #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { Console.ReadKey(); } #endif return(false); } Logger.Debug(Resources.Settings); Logger.Debug(" " + JsonSerializer.ToJsonString(settings)); Logger.Debug(" " + JsonSerializer.ToJsonString(riskHotspotsAnalysisThresholds)); var stopWatch = Stopwatch.StartNew(); var parserResult = new CoverageReportParser( settings.NumberOfReportsParsedInParallel, settings.NumberOfReportsMergedInParallel, reportConfiguration.SourceDirectories, new DefaultFilter(reportConfiguration.AssemblyFilters), new DefaultFilter(reportConfiguration.ClassFilters), new DefaultFilter(reportConfiguration.FileFilters)) .ParseFiles(reportConfiguration.ReportFiles); PostProcessParserResult(parserResult); Logger.DebugFormat(Resources.ReportParsingTook, stopWatch.ElapsedMilliseconds / 1000d); this.GenerateReport( reportConfiguration, settings, riskHotspotsAnalysisThresholds, parserResult); stopWatch.Stop(); Logger.InfoFormat(Resources.ReportGenerationTook, stopWatch.ElapsedMilliseconds / 1000d); return(true); } catch (Exception ex) { Logger.Error(ex.GetExceptionMessageForDisplay()); Logger.Error(ex.StackTrace); #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { Console.ReadKey(); } #endif return(false); } }