Ejemplo n.º 1
0
		public MainWindow()
		{
			InitializeComponent();
			Instance = this;

			Title = Title.Put("Multi connection");

			_ordersWindow.MakeHideable();
			_myTradesWindow.MakeHideable();
			_tradesWindow.MakeHideable();
			_securitiesWindow.MakeHideable();
			_stopOrdersWindow.MakeHideable();
			_portfoliosWindow.MakeHideable();

			var logManager = new LogManager();
			logManager.Application.LogLevel = LogLevels.Debug;
			logManager.Listeners.Add(new FileLogListener("sample.log"));

			var entityRegistry = ConfigManager.GetService<IEntityRegistry>();
			var storageRegistry = ConfigManager.GetService<IStorageRegistry>();

			Connector = new Connector(entityRegistry, storageRegistry);
			logManager.Sources.Add(Connector);

			InitConnector();
		}
Ejemplo n.º 2
0
		public MainWindow()
		{
			InitializeComponent();

			Title = TypeHelper.ApplicationNameWithVersion;

			InitializeDataSource();

			Directory.CreateDirectory(BaseApplication.AppDataPath);

			var compositionsPath = Path.Combine(BaseApplication.AppDataPath, "Compositions");
			var strategiesPath = Path.Combine(BaseApplication.AppDataPath, "Strategies");
			var logsPath = Path.Combine(BaseApplication.AppDataPath, "Logs");

			_settingsFile = Path.Combine(BaseApplication.AppDataPath, "settings.xml");

			var logManager = new LogManager();
			logManager.Listeners.Add(new FileLogListener
			{
				Append = true,
				LogDirectory = logsPath,
				MaxLength = 1024 * 1024 * 100 /* 100mb */,
				MaxCount = 10,
				SeparateByDates = SeparateByDateModes.SubDirectories,
			});
			logManager.Listeners.Add(new GuiLogListener(Monitor));

			_strategiesRegistry = new StrategiesRegistry(compositionsPath, strategiesPath);
			logManager.Sources.Add(_strategiesRegistry);
			_strategiesRegistry.Init();

			_layoutManager = new LayoutManager(DockingManager);
			_layoutManager.Changed += SaveSettings;
			logManager.Sources.Add(_layoutManager);

			var entityRegistry = ConfigManager.GetService<IEntityRegistry>();
			var storageRegistry = ConfigManager.GetService<IStorageRegistry>();

			_connector = new Connector(entityRegistry, storageRegistry)
			{
				StorageAdapter =
				{
					DaysLoad = TimeSpan.Zero
				}
			};
			_connector.Connected += ConnectorOnConnectionStateChanged;
			_connector.Disconnected += ConnectorOnConnectionStateChanged;
			_connector.ConnectionError += ConnectorOnConnectionError;
			logManager.Sources.Add(_connector);

			ConfigManager.RegisterService(logManager);
			ConfigManager.RegisterService(_strategiesRegistry);
			ConfigManager.RegisterService(_layoutManager);
			ConfigManager.RegisterService<IConnector>(_connector);
			ConfigManager.RegisterService<ISecurityProvider>(_connector);

			SolutionExplorer.Compositions = _strategiesRegistry.Compositions;
			SolutionExplorer.Strategies = _strategiesRegistry.Strategies;
		}
Ejemplo n.º 3
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="logManager"></param>
 public LogSaver(LogManager logManager)
 {
     if (logManager == null)
     {
         throw new ArgumentNullException("logManager");
     }
     _logManager = logManager;
 }
Ejemplo n.º 4
0
	public FileCache(LogManager log, IMethodFilter methodFilter, FileCacheManager manager, IFileObject file, int blockSize) {
		_log = log;
		_dirty = false;
		_manager = manager;
		_file = file;
		_blockSize = blockSize;
		_methodFilter = methodFilter;
	}
 public void CanHandleNullDataValue()
 {
     var logManager = new LogManager();
     var log = logManager.GetLoggerForCallingType();
     var lb = log.Data("a", null);
     var s = new DefaultStringConverter().Convert(lb.Entry);
     Assert.True(s.Contains("a: null"));
 }
Ejemplo n.º 6
0
        public TcpServer(int port, LogManager log) {
            this.port = port;
            this.log = log.GetLogFor(GetType());

            listener = new TcpListener(
                IPAddress.Any,
                this.port);
        }
Ejemplo n.º 7
0
        public void ApplicationLogFileNotCreatedWhenLogManagerIsInstantiated()
        {
            // Act
              var logManager = new LogManager(this.mockDateTimeStamper, this.applicationLogFilePath);
              logManager.Close();

              // Assert
              File.Exists(this.applicationLogFilePath).Should().BeFalse();
        }
        public void TestDataIndention()
        {
            var logManager = new LogManager();
            var log = logManager.GetLoggerForCallingType();

            var lb = log.Data("a","happy test").Data("test", "abc\r\nxyz\r\n123").Data("test2", "abc\r\nxyz\r\n123").Data("test3", "abc\r\nxyz\r\n123");

            var s = new DefaultStringConverter().Convert(lb.Entry);

            Console.WriteLine(s);
        }
	// Constructor.
	protected XmlParserInputBase
				(XmlNameTable nameTable,
				 EOFHandler eof,
				 ErrorHandler error)
			: base(error)
			{
				this.nameTable = nameTable;
				this.eofHandler = eof;
				this.currChar = '\0';
				this.peekChar = '\0';
				this.logger = new LogManager();
			}
        public void CanHandleAnonTypes()
        {
            using (var logManager = new LogManager(new[]{new ConsoleTarget()}))
            {
                logManager.UnhandledLoggingException += (s, e) => Console.WriteLine(e.Exception.ToString());

                var log = logManager.GetLoggerForCallingType();

                log.Info(new { Abc = 123 });
                log.Info(new { Abc = 123 }.ToString());
                log.Info("{0}", new { Abc = 123 });
            }
        }
Ejemplo n.º 11
0
        public static void Main(String[] args)
        {
            var commandLineOptions = new CommandLineOptions();
              var result = Parser.Default.ParseArguments(args, commandLineOptions);

              Application.EnableVisualStyles();
              Application.SetCompatibleTextRenderingDefault(false);

              var logManager = new LogManager(commandLineOptions.ApplicationLog);
              var controller = CreateController(commandLineOptions.ControllerName, logManager);
              var mainForm = controller.CreateMainForm();
              Application.Run(mainForm);
        }
Ejemplo n.º 12
0
        public void ChangingApplicationLogFilePathResultsInANewLogBeingCreated()
        {
            // Act
              var logManager = new LogManager(this.mockDateTimeStamper, this.applicationLogFilePath);
              logManager.WriteMessageToApplicationLog("Application log file.");
              logManager.Close();

              logManager.ApplicationLogFilePath = this.alternativeApplicationLogFilePath;
              logManager.WriteMessageToApplicationLog("Alteranative application log file.");
              logManager.Close();

              // Assert
              File.Exists(this.applicationLogFilePath).ShouldBeTrue();
              File.Exists(this.alternativeApplicationLogFilePath).ShouldBeTrue();
        }
Ejemplo n.º 13
0
		public MainWindow()
		{
			InitializeComponent();

			_logManager = new LogManager();
			_logManager.Listeners.Add(new GuiLogListener(Log));

			var area = new ChartArea();
			Chart.Areas.Add(area);

			_candlesElem = new ChartCandleElement();
			area.Elements.Add(_candlesElem);

			GuiDispatcher.GlobalDispatcher.AddPeriodicalAction(ProcessCandles);
		}
Ejemplo n.º 14
0
		public MainWindow()
		{
			InitializeComponent();
			Instance = this;

			Title = Title.Put("Multi connection");

			_ordersWindow.MakeHideable();
			_securitiesWindow.MakeHideable();

			var logManager = new LogManager();
			logManager.Listeners.Add(new FileLogListener("sample.log"));
			logManager.Sources.Add(Connector);

			InitConnector();
		}
Ejemplo n.º 15
0
		public MainWindow()
		{
			InitializeComponent();

			_logManager = new LogManager();
			_logManager.Listeners.Add(new GuiLogListener(Log));

			var area = new ChartArea();
			Chart.Areas.Add(area);

			_candlesElem = new ChartCandleElement();
			area.Elements.Add(_candlesElem);

			GuiDispatcher.GlobalDispatcher.AddPeriodicalAction(ProcessCandles);

			Level1AddressCtrl.Text = IQFeedAddresses.DefaultLevel1Address.To<string>();
			Level2AddressCtrl.Text = IQFeedAddresses.DefaultLevel2Address.To<string>();
			LookupAddressCtrl.Text = IQFeedAddresses.DefaultLookupAddress.To<string>();
		}
Ejemplo n.º 16
0
        public void BasicEmail()
        {
            var email = new EmailTarget
            {
                From = "*****@*****.**",
                To = "*****@*****.**",
                Interval = LoggingInterval.Parse("1 second")
            };

            var mgr = new LogManager(new[] { email });
            mgr.UnhandledLoggingException += (sender, args) => { throw args.Exception; };

            var log = mgr.GetLoggerForCallingType();

            for (var i = 0; i < 10000; i++)
                log.Info("test");

            mgr.Dispose();
        }
Ejemplo n.º 17
0
        protected void Application_Error(object sender, EventArgs e)
        {
            try
            {
                Exception error = Server.GetLastError();

                string message = (error.InnerException ?? error).Message;

                LogManager logManager = new LogManager();

                logManager.CreateLog(message);

                CustomApplicationManager.MessageApplication = @message;

                Response.Redirect("~/Error.aspx");

            }
            catch
            {

            }
        }
Ejemplo n.º 18
0
        public RequestLogger(AppFunc next, LogManager logManager)
        {
            if (next == null) throw new ArgumentNullException("next");
            if (logManager == null) throw new ArgumentNullException("logManager");

            _next = next;
            _log = logManager.CreateLogger();

            _keys = new[]
            {
                "owin.RequestPath",
                "owin.ResponseStatusCode",
                "owin.RequestQueryString",
                "owin.RequestMethod",
                "owin.RequestScheme",
                "owin.RequestPathBase",
                "owin.RequestProtocol",
                "server.User",
                "server.RemoteIpAddress",
                "server.RemotePort",
            };
        }
Ejemplo n.º 19
0
		public MainWindow()
		{
			ConfigManager.RegisterService<IStorage>(new InMemoryStorage());

			InitializeComponent();

			if (AutomaticUpdater.ClosingForInstall)
			{
				Application.Current.Shutdown();
				return;
			}

			AutomaticUpdater.Translate();
			
			_totalPnL = EquityCurveChart.CreateCurve("P&L", Colors.Green, Colors.Red, EquityCurveChartStyles.Area);
			_unrealizedPnL = EquityCurveChart.CreateCurve(LocalizedStrings.Str3261, Colors.Black);
			_commission = EquityCurveChart.CreateCurve(LocalizedStrings.Str159, Colors.Red, EquityCurveChartStyles.DashedLine);
			_stoppedBg = ConnectBtn.Background;
			_startedBg = Brushes.Pink;

			_logManager = new LogManager();
			_logManager.Listeners.Add(new FileLogListener { SeparateByDates = SeparateByDateModes.SubDirectories });

			_connector = new StrategyConnector();
			_connector.Connected += ConnectionChanged;
			_connector.Disconnected += ConnectionChanged;

			LoadSettings();

			_logManager.Listeners.Add(new GuiLogListener(Monitor));
			_logManager.Sources.Add(_connector);

			ConfigManager.RegisterService(_connector);
			ConfigManager.RegisterService<IConnector>(_connector);
			ConfigManager.RegisterService(new FilterableSecurityProvider(_connector.SecurityList));

			InitializeCompositions();
		}
Ejemplo n.º 20
0
 public bool RunWebServicesQuery(string aURL, string aToken, bool aIsPost)
 {
     try
     {
         HttpWebRequest lRequest = (HttpWebRequest)WebRequest.Create(aURL);
         if (!aIsPost)
         {
             lRequest.Method = "GET";
         }
         else
         {
             lRequest.Method = "POST";
             lRequest.Headers.Add("token", aToken);
         }
         HttpWebResponse lResponse = (HttpWebResponse)lRequest.GetResponse();
         StreamReader lStreamRead = new StreamReader(lResponse.GetResponseStream(), System.Text.Encoding.UTF8);
         string lResult = lStreamRead.ReadToEnd();
         lStreamRead.Close();
         lResponse.Close();
         if (lResponse.StatusCode.ToString() == "OK")
         {
             gReturnData = lResult;
             return true;
         }
         else
         {
             gReturnData = "System returned HTTP Result " + lResponse.StatusCode.ToString();
             return false;
         }
     }
     catch (SystemException ex)
     {
         LogManager ErrManager = new LogManager();
         ErrManager.Log(ex.Message.ToString(), false);
         gReturnData = ex.Message.ToString();
         return false;
     }
 }
Ejemplo n.º 21
0
        public FormLog(LogManager.LogManager logManager)
        {
            InitializeComponent();
            //非表示でもウィンドウハンドルを生成させる。さもなくば、Invokeが失敗する
            IntPtr wndHandle = Handle;

            lvBattle.DoubleBuffer(true);
            lvItem.DoubleBuffer(true);
            lvMaterials.DoubleBuffer(true);
            lvMission.DoubleBuffer(true);
            lvShip.DoubleBuffer(true);

            chartMaterial.DataSource = logManager.InitMaterialDataTable();
            chartMaterial.DataBind();

            /* フォームは開かれていないのでLoadは呼ばれないが、
             * フォームが開かれる前にログ追加が行われるとデータの順番が腐る
             */

            if (!Properties.Settings.Default.LogFormBounds.IsEmpty)
                Bounds = Properties.Settings.Default.LogFormBounds;

            lvBattle.LoadColumnWithOrder(Properties.Settings.Default.LogBattleColumnWidth);
            lvItem.LoadColumnWithOrder(Properties.Settings.Default.LogItemColumnWidth);
            lvMaterials.LoadColumnWithOrder(Properties.Settings.Default.LogMaterialColumnWidth);
            lvMission.LoadColumnWithOrder(Properties.Settings.Default.LogMissionColumnWidth);
            lvShip.LoadColumnWithOrder(Properties.Settings.Default.LogShipColumnWidth);

            logManager.AttachLogControls(lvShip, lvItem, lvBattle, lvMission, lvMaterials,chartMaterial,this);
            _logManager = logManager;

            Text += string.Format("(Store:{0})", logManager.LogStore.StoreType);

            var sm = new SystemMenu(this);
            sm.InsertMenuItem(3, "ウィンドウ復帰", 6);
        }
Ejemplo n.º 22
0
		public MainWindow()
		{
			InitializeComponent();
			CandleType.SetDataSource<CandleTypes>();
			CandleType.SetSelectedValue<CandleTypes>(CandleTypes.TimeFrame);

			TimeFrame.Value = new DateTime(TimeSpan.FromMinutes(5).Ticks);

			// попробовать сразу найти месторасположение Quik по запущенному процессу
			Path.Text = QuikTerminal.GetDefaultPath();

			//Добавим логирование
			_logManager = new LogManager
			{
				Application = { LogLevel = LogLevels.Debug }
			};

			_logManager.Listeners.Add(new FileLogListener
			{
				LogDirectory = @"Logs\",
				SeparateByDates = SeparateByDateModes.SubDirectories,
				Append = false,
			});
		}
Ejemplo n.º 23
0
 public TcpServer2(int port, LogManager log) {
     this.port = port;
     this.log = log.GetLogFor(GetType());
     this.endpoint = new IPEndPoint(IPAddress.Any, this.port);
 }
Ejemplo n.º 24
0
		private void ConnectClick(object sender, RoutedEventArgs e)
		{
			if (!_isConnected)
			{
				if (Connector == null)
				{
					var isDde = IsDde.IsChecked == true;

					if (SmartLogin.Text.IsEmpty())
					{
						MessageBox.Show(this, LocalizedStrings.Str2965);
						return;
					}
					if (SmartPassword.Password.IsEmpty())
					{
						MessageBox.Show(this, LocalizedStrings.Str2966);
						return;
					}
					if (isDde && QuikPath.Text.IsEmpty())
					{
						MessageBox.Show(this, LocalizedStrings.Str2967);
						return;
					}

					// создаем агрегирующее подключение (+ сразу инициализируем настройки переподключения)
					Connector = InitReconnectionSettings(new Connector());

					// добавляем подключения к SmartCOM и Quik
					var quikTs = new LuaFixTransactionMessageAdapter(Connector.TransactionIdGenerator)
					{
						Login = "******",
						Password = "******".To<SecureString>(),
						Address = QuikTrader.DefaultLuaAddress,
						TargetCompId = "StockSharpTS",
						SenderCompId = "quik",
						ExchangeBoard = ExchangeBoard.Forts,
						Version = FixVersions.Fix44_Lua,
						RequestAllPortfolios = true,
						MarketData = FixMarketData.None,
						TimeZone = TimeHelper.Moscow
					};
					var quikMd = new FixMessageAdapter(Connector.TransactionIdGenerator)
					{
						Login = "******",
						Password = "******".To<SecureString>(),
						Address = QuikTrader.DefaultLuaAddress,
						TargetCompId = "StockSharpMD",
						SenderCompId = "quik",
						ExchangeBoard = ExchangeBoard.Forts,
						Version = FixVersions.Fix44_Lua,
						RequestAllSecurities = true,
						MarketData = FixMarketData.MarketData,
						TimeZone = TimeHelper.Moscow
					};
					quikMd.RemoveTransactionalSupport();

					Connector.Adapter.InnerAdapters[quikMd] = 1;
					Connector.Adapter.InnerAdapters[quikTs] = 1;

					var smartCom = new SmartComMessageAdapter(Connector.TransactionIdGenerator)
					{
						Login = SmartLogin.Text,
						Password = SmartPassword.Password.To<SecureString>(),
						Address = SmartAddress.SelectedAddress,
					};
					Connector.Adapter.InnerAdapters[smartCom] = 0;

					// очищаем из текстового поля в целях безопасности
					//SmartPassword.Clear();

					var logManager = new LogManager();
					logManager.Listeners.Add(new FileLogListener("sample.log"));
					logManager.Sources.Add(Connector);

					// подписываемся на событие успешного соединения
					Connector.Connected += () =>
					{
						// возводим флаг, что соединение установлено
						_isConnected = true;

						// разблокируем кнопку Экспорт
						this.GuiAsync(() => ChangeConnectStatus(true));
					};

					// подписываемся на событие разрыва соединения
					Connector.ConnectionError += error => this.GuiAsync(() =>
					{
						// заблокируем кнопку Экспорт (так как соединение было потеряно)
						ChangeConnectStatus(false);

						MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2959);	
					});

					// подписываемся на ошибку обработки данных (транзакций и маркет)
					Connector.Error += error =>
						this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2955));

					// подписываемся на ошибку подписки маркет-данных
					Connector.MarketDataSubscriptionFailed += (security, type, error) =>
						this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2956Params.Put(type, security)));

					Connector.NewSecurities += securities => _securitiesWindow.SecurityPicker.Securities.AddRange(securities);
					Connector.NewOrders += orders => _ordersWindow.OrderGrid.Orders.AddRange(orders);

					// подписываемся на событие о неудачной регистрации заявок
					Connector.OrdersRegisterFailed += OrdersFailed;
					// подписываемся на событие о неудачном снятии заявок
					Connector.OrdersCancelFailed += OrdersFailed;

					// подписываемся на событие о неудачной регистрации стоп-заявок
					Connector.StopOrdersRegisterFailed += OrdersFailed;
					// подписываемся на событие о неудачном снятии стоп-заявок
					Connector.StopOrdersCancelFailed += OrdersFailed;

					// устанавливаем поставщик маркет-данных
					_securitiesWindow.SecurityPicker.MarketDataProvider = Connector;

					ShowSecurities.IsEnabled = ShowOrders.IsEnabled = true;
				}

				Connector.Connect();
			}
			else
			{
				Connector.Disconnect();
			}
		}
Ejemplo n.º 25
0
		public LogcatLogWriter(LogManager logManager, Func<LogEvent, string> logFormatter = null)
			: base(logManager, logFormatter)
		{
		}
Ejemplo n.º 26
0
		public IosInformUserLogWriter(LogManager logManager, Func<LogEvent, string> logFormatter = null)
			: base(logManager, logFormatter)
		{
		}
Ejemplo n.º 27
0
		public MainWindow()
		{
			CheckIsRunning();

			_logManager = UserConfig.Instance.CreateLogger();

			Mouse.OverrideCursor = Cursors.Wait;

			InitializeComponent();

			_logManager.Listeners.Add(new GuiLogListener(MonitorControl));
			_logManager.Listeners.Add(this);

			_emailListener = new HydraEmailLogListener(this);
			_logManager.Listeners.Add(_emailListener);

			MemoryStatMenuItem.IsChecked = MemoryStatistics.IsEnabled;

			Title = TypeHelper.ApplicationNameWithVersion;

			if (AutomaticUpdater.ClosingForInstall)
			{
				Application.Current.Shutdown();
				return;
			}

			AutomaticUpdater.MenuItem = MnuCheckForUpdates;
			AutomaticUpdater.Translate();

			//DockSite.DocumentWindows.CollectionChanged += DocumentWindows_OnCollectionChanged;

			_logManager.Sources.Add(UserConfig.Instance);

			Instance = this;

			UserConfig.Instance.Load();
		}
Ejemplo n.º 28
0
 public HttpClient()
 {
     LogManager lm = new LogManager();
     Logger = lm.GetLogger<HttpClient>();
 }
Ejemplo n.º 29
0
 public void Flush(LogManager logMgr)
 {
     Trace.Flush();
 }
Ejemplo n.º 30
0
		public LogManager CreateLogger()
		{
			var logManager = new LogManager();

			var serializer = new XmlSerializer<SettingsStorage>();

			if (File.Exists(_logSettingsFile))
			{
				logManager.Load(serializer.Deserialize(_logSettingsFile));

				var listener = logManager
					.Listeners
					.OfType<FileLogListener>()
					.FirstOrDefault(fl => !fl.LogDirectory.IsEmpty());

				if (listener != null)
					LogsDir = listener.LogDirectory;
			}
			else
			{
				logManager.Listeners.Add(new FileLogListener/*(LoggerErrorFileName)*/
				{
					Append = true,
					LogDirectory = LogsDir,
					MaxLength = 1024 * 1024 * 100 /* 100mb */,
					MaxCount = 10,
					SeparateByDates = SeparateByDateModes.SubDirectories,
				});

				//logManager.Listeners.Add(new FileLogListener(LoggerFileName)
				//{
				//	Append = true,
				//	LogDirectory = LogsDir,
				//	SeparateByDates = SeparateByDateModes.SubDirectories,
				//});

				serializer.Serialize(logManager.Save(), _logSettingsFile);
			}

			//logManager.Listeners
			//	.OfType<FileLogListener>()
			//	.Where(fl => fl.FileName == Path.GetFileNameWithoutExtension(LoggerErrorFileName))
			//	.ForEach(fl =>
			//	{
			//		fl.Filters.Add(LogListener.AllWarningFilter);
			//		fl.Filters.Add(LogListener.AllErrorFilter);
			//	});

			return logManager;
		}