public void Call_to_Elasticsearch_propagates_Trace_Context_when_HttpDiagnosticsSubscriber_subscribed() { using var localServer = LocalServer.Create(context => { var traceparent = context.Request.Headers.Get("traceparent"); traceparent.Should().NotBeNullOrEmpty(); var elasticTraceparent = context.Request.Headers.Get("elastic-apm-traceparent"); elasticTraceparent.Should().NotBeNullOrEmpty().And.Be(traceparent); var tracestate = context.Request.Headers.Get("tracestate"); tracestate.Should().NotBeNullOrEmpty().And.Contain("es=s:1"); context.Response.StatusCode = 200; }); using var agent = new ApmAgent(new TestAgentComponents(payloadSender: new MockPayloadSender())); using var subscribe = agent.Subscribe(new ElasticsearchDiagnosticsSubscriber(), new HttpDiagnosticsSubscriber()); var client = new ElasticLowLevelClient(new ConnectionConfiguration(new Uri(localServer.Uri))); agent.Tracer.CaptureTransaction("Transaction", ApiConstants.TypeDb, t => { var response = client.Cat.Indices <StringResponse>(); }); }
public async Task HttpCallWithW3CActivityFormar() { Activity.DefaultIdFormat = ActivityIdFormat.W3C; var mockPayloadSender = new MockPayloadSender(); using var localServer = LocalServer.Create(); using var agent = new ApmAgent(new TestAgentComponents(payloadSender: mockPayloadSender)); agent.Subscribe(new HttpDiagnosticsSubscriber()); await agent.Tracer.CaptureTransaction("Test", "Test", async() => { var httpClient = new HttpClient(); try { await httpClient.GetAsync(localServer.Uri); } catch { //ignore - we don't care about the result } }); mockPayloadSender.WaitForSpans(); mockPayloadSender.Spans.Should().HaveCount(1); }
[NetCoreFact] //see: https://github.com/elastic/apm-agent-dotnet/issues/516 public async Task HttpRequestDuration() { var(listener, payloadSender, _) = RegisterListenerAndStartTransaction(); using (listener) using (var localServer = LocalServer.Create(ctx => { ctx.Response.StatusCode = 200; Thread.Sleep(5); //Make sure duration is really > 0 })) { var httpClient = new HttpClient(); var res = await httpClient.GetAsync(localServer.Uri); res.IsSuccessStatusCode.Should().BeTrue(); payloadSender.WaitForSpans(); var firstSpan = payloadSender.FirstSpan; firstSpan.Should().NotBeNull(); firstSpan.Context.Http.Url.Should().Be(localServer.Uri); firstSpan.Context.Http.StatusCode.Should().Be(200); firstSpan.Context.Http.Method.Should().Be(HttpMethod.Get.Method); firstSpan.Duration.Should().BeGreaterThan(0); } }
private async Task SetupBasic() { colClient = await Utils.GetEmptyCollection(tempFolder); var f = colClient.NewNote(); f.SetItem("Front", "foo"); f.SetItem("Back", "bar"); f.Tags.Add("foo"); colClient.AddNote(f); colClient.Reset(); colClient.Sched.AnswerCard(colClient.Sched.PopCard(), Sched.AnswerEase.Easy); colServer = await Utils.GetEmptyCollection(tempFolder2, true); f = colServer.NewNote(); f.SetItem("Front", "bar"); f.SetItem("Back", "bar"); f.Tags.Add("bar"); colServer.AddNote(f); colServer.Reset(); colServer.Sched.AnswerCard(colServer.Sched.PopCard(), Sched.AnswerEase.Easy); //Start with same schema and sync time colClient.Scm = 0; colServer.Scm = 0; //And same modified time, so sync does nothing long t = DateTimeOffset.Now.ToUnixTimeMilliseconds(); colClient.Save(mod: t); colServer.Save(mod: t); server = new LocalServer(colServer); client = new Syncer(colClient, server); }
private async void startLocal_Click(object sender, EventArgs e) { string nick; if (Settings.Nickname == null) { InputForm nickname = new InputForm(); if (nickname.ShowDialogOnFormThread(this) == DialogResult.Cancel) { return; } nick = nickname.Input.Text.Trim(); } else { nick = Settings.Nickname; } await LocalServer.StartAsync(); this.DialogResult = DialogResult.OK; this.Entry = new ServerEntry(0) { Host = Target.LoopbackIP, Port = 42912, UserName = nick, UserNickname = nick, UserPassword = "******" }; }
public async Task SubscriptionOnlyRegistersSpansDuringItsLifeTime() { var agent = new ApmAgent(new TestAgentComponents()); StartTransaction(agent); var spans = Agent.TransactionContainer.Transactions.Value.Spans; using (var localServer = new LocalServer()) using (var httpClient = new HttpClient()) { Assert.True(spans.Length == 0, $"Expected 0 spans has count: {spans.Length}"); using (agent.Subscribe(new HttpDiagnosticsSubscriber())) { var res = await httpClient.GetAsync(localServer.Uri); Assert.True(res.IsSuccessStatusCode); res = await httpClient.GetAsync(localServer.Uri); Assert.True(res.IsSuccessStatusCode); } spans = Agent.TransactionContainer.Transactions.Value.Spans; Assert.True(spans.Length == 2, $"Expected 2 but spans has count: {spans.Length}"); foreach (var _ in Enumerable.Range(0, 10)) { await httpClient.GetAsync(localServer.Uri); } Assert.True(localServer.SeenRequests > 10, "Make sure we actually performed more than 1 request to our local server"); } Assert.True(spans.Length == 2, $"Expected 1 span because the listener is disposed but spans has count: {spans.Length}"); }
public static void SendPkgToServer <T>(ENUM_CMD cmdID, T obj, Action <object> callback = null) { //Debug.Log("SendPkgToServer,cmd=" + cmdID); if (IsSingle && LocalServer.ProcessRequest(cmdID, obj, callback)) { return; } byte[] data = Serialize(obj); int length = data.Length; List <byte> bytes = new List <byte>(); bytes.AddRange(BitConverter.GetBytes((ushort)cmdID)); bytes.AddRange(BitConverter.GetBytes((uint)length)); bytes.AddRange(data); _message.Enqueue(bytes.ToArray()); if (callback != null) { if (!callbackDict.ContainsKey(cmdID)) { callbackDict[cmdID] = new List <NetworkCallback>(); } callbackDict[cmdID].Add(new NetworkCallback { func = callback, isDelete = true }); } }
public ServerActor() { Context.ActorOf(ClientServer.Props(), "ClientServer"); Context.ActorOf(LocalServer.Props(), "LocalServer"); Context.ActorOf(DataBaseServer.Props(), "DataBaseServer"); Receive <MessageOfListViewUpdateLocalList>(updatedLocal => LocalToClient_Send_CreatedLocalID(updatedLocal)); Receive <MessageOfRequestLocalIDs>(requestedLocalID => RequestAllLocalID(requestedLocalID)); Receive <MessageOfReturnLocalID>(returnLocal => ReturnAllLocalID(returnLocal)); Receive <UpdateMonitor>(receivedLocalData => SendToClient_DataOfLocal(receivedLocalData)); Receive <UnsubscribeMonitorLocal>(deletedLocal => DeleteLocal(deletedLocal)); Schedule = Context .System .Scheduler .ScheduleTellRepeatedlyCancelable( TimeSpan.Zero, // The time period that has to pass before the first message is sent. TimeSpan.FromSeconds(1), // The interval, i.e. the time period that has to pass between messages are being sent. Self, // The receiver. new Start(), // The message. Self); // The sender. Receive <Start>(_ => Handle(_)); }
public async Task HttpCallWithoutRegisteredListener() { var mockPayloadSender = new MockPayloadSender(); var agent = new ApmAgent(new TestAgentComponents(payloadSender: mockPayloadSender)); using (var localServer = new LocalServer()) { await agent.Tracer.CaptureTransaction("TestTransaction", "TestType", async t => { Thread.Sleep(5); var httpClient = new HttpClient(); try { await httpClient.GetAsync(localServer.Uri); } catch (Exception e) { t.CaptureException(e); } }); mockPayloadSender.Transactions.Should().NotBeEmpty(); mockPayloadSender.SpansOnFirstTransaction.Should().BeEmpty(); } }
[NetCoreFact] //see: https://github.com/elastic/apm-agent-dotnet/issues/516 public async Task HttpCallWithRegisteredListener() { var mockPayloadSender = new MockPayloadSender(); var agent = new ApmAgent(new TestAgentComponents(payloadSender: mockPayloadSender)); var subscriber = new HttpDiagnosticsSubscriber(); using (var localServer = new LocalServer()) using (agent.Subscribe(subscriber)) { var url = localServer.Uri; await agent.Tracer.CaptureTransaction("TestTransaction", "TestType", async t => { Thread.Sleep(5); var httpClient = new HttpClient(); try { await httpClient.GetAsync(url); } catch (Exception e) { t.CaptureException(e); } }); mockPayloadSender.Transactions.Should().NotBeEmpty(); mockPayloadSender.SpansOnFirstTransaction.Should().NotBeEmpty(); mockPayloadSender.SpansOnFirstTransaction[0].Context.Http.Should().NotBeNull(); mockPayloadSender.SpansOnFirstTransaction[0].Context.Http.Url.Should().Be(url); } }
public async Task NoUserNameAndPasswordInLogsForHttp() { var payloadSender = new NoopPayloadSender(); var logger = new TestLogger(LogLevel.Trace); var agent = new ApmAgent(new TestAgentComponents(payloadSender: payloadSender, logger: logger)); agent.Subscribe(new HttpDiagnosticsSubscriber()); StartTransaction(agent); using (var localServer = new LocalServer()) using (var httpClient = new HttpClient()) { var uriBuilder = new UriBuilder(localServer.Uri) { UserName = "******", Password = "******" }; var res = await httpClient.GetAsync(uriBuilder.Uri); res.IsSuccessStatusCode.Should().BeTrue(); logger.Lines.Should().NotBeEmpty(); logger.Lines.Should().NotContain(n => n.Contains("TestUser289421")); logger.Lines.Should().NotContain(n => n.Contains("Password973243")); // looking for lines with "localhost:8082" and asserting that those contain [REDACTED]. foreach (var lineWithHttpLog in logger.Lines.Where(n => n.Contains($"{uriBuilder.Host}:{uriBuilder.Port}"))) { lineWithHttpLog.Should().Contain("[REDACTED]"); } } }
[NetCoreFact] //see: https://github.com/elastic/apm-agent-dotnet/issues/516 public async Task SubscriptionOnlyRegistersSpansDuringItsLifeTime() { var payloadSender = new MockPayloadSender(); var agent = new ApmAgent(new TestAgentComponents(payloadSender: payloadSender)); StartTransaction(agent); var spans = payloadSender.Spans; using (var localServer = new LocalServer()) using (var httpClient = new HttpClient()) { spans.Should().BeEmpty(); using (agent.Subscribe(new HttpDiagnosticsSubscriber())) { var res = await httpClient.GetAsync(localServer.Uri); res.IsSuccessStatusCode.Should().BeTrue(); res = await httpClient.GetAsync(localServer.Uri); res.IsSuccessStatusCode.Should().BeTrue(); } spans = payloadSender.Spans; spans.Should().NotBeEmpty().And.HaveCount(2); foreach (var _ in Enumerable.Range(0, 10)) { await httpClient.GetAsync(localServer.Uri); } localServer.SeenRequests.Should() .BeGreaterOrEqualTo(10, "Make sure we actually performed more than 1 request to our local server"); } spans.Should().HaveCount(2); }
public async Task TestUrlSanitization() { var(listener, payloadSender, _) = RegisterListenerAndStartTransaction(); using (listener) using (var localServer = new LocalServer()) { var uri = new Uri(localServer.Uri); var uriBuilder = new UriBuilder(uri) { UserName = "******", Password = "******" }; var httpClient = new HttpClient(); var res = await httpClient.GetAsync(uriBuilder.Uri); res.IsSuccessStatusCode.Should().BeTrue(); var firstSpan = payloadSender.FirstSpan; firstSpan.Should().NotBeNull(); firstSpan.Context.Http.Url.Should() .Be(uriBuilder.Uri.ToString() .Replace("TestUser", "[REDACTED]") .Replace("TestPassword", "[REDACTED]")); firstSpan.Context.Http.StatusCode.Should().Be(200); firstSpan.Context.Http.Method.Should().Be(HttpMethod.Get.Method); firstSpan.Context.Destination.Address.Should().Be(new Uri(localServer.Uri).Host); firstSpan.Context.Destination.Port.Should().Be(new Uri(localServer.Uri).Port); } }
void OnClickQuit() { NBTHelper.Save(); LocalServer.SaveData(); NetworkManager.Clear(); SceneManager.LoadScene("LoginScene"); }
static void Main(string[] args) { FieldInfo assetManagerField = typeof(GameEnvironment).GetField("assetManager", BindingFlags.Static | BindingFlags.NonPublic); assetManagerField.SetValue(null, new EmptyAssetManager()); LocalServer server = new LocalServer(); RemoteClient rc = new RemoteClient(server); //JoinServerEvent jse = new JoinServerEvent(); //jse.clientName = "test"; LevelUpdatedEvent lue = new LevelUpdatedEvent(); lue.updatedLevel = server.Level; rc.Send(lue); IFormatter formatter = new BinaryFormatter(); Stream stream = new FileStream("MyTestFile.bin", FileMode.Open, FileAccess.Read, FileShare.Read); Event obj = (Event)formatter.Deserialize(stream); stream.Close(); startTime = DateTime.UtcNow; playingState = new PlayingState(); Timer timer = new Timer(tick, null, 0, (int)(1000f / 60f)); Console.Read(); }
public CloudConnection(CloudSocket cloudSocket) { mCloudSocket = cloudSocket; mLocalServer = new LocalServer(cloudSocket); mRemoteClient = new RemoteClient(cloudSocket); }
static void Main(string[] args) { Tools.OverrideLogToFile(); // активируем запись консольных сообщений в файл RenderNodeSettings RNS = new RenderNodeSettings(); // запускаем ноду и создаем первичный файл настроек если его нет LocalServer.StartListen(); // запускаем локальный сервер для прослушки команд с клиента }
public WebSocketServer(LocalServer server) { _localServer = server; Connections = new List <WebSocketConnection>(); _tmrBroadcast = new Timer(1000); _tmrBroadcast.Elapsed += TmrBroadcastElapsed; _tmrBroadcast.Start(); }
static void Main(string[] args) { //ForTest(ref args); if (args.Length == 4) { LocalServer server = new LocalServer(); server.Start(args[0], int.Parse(args[1]), args[2], int.Parse(args[3])); } }
public virtual object GetFolders(HttpContext context) { YZRequest request = new YZRequest(context); string serverName = request.GetString("serverName"); string path = request.GetString("node", null); if (YZStringHelper.EquName(path, "root")) { path = null; } LocalServer localServer = new LocalServer(); localServer.Name = "localhost"; JObject rv = new JObject(); using (BPMConnection cn = new BPMConnection()) { cn.WebOpen(); JArray children = new JArray(); rv[YZJsonProperty.children] = children; if (String.IsNullOrEmpty(path)) { FSSDriveInfoCollection drivers = FileStoreManager.GetDrivers(cn, serverName); foreach (FSSDriveInfo driveInfo in drivers) { JObject item = new JObject(); children.Add(item); item["iconCls"] = "bdisk"; item["text"] = driveInfo.VolumeLabel + " (" + driveInfo.Name.Substring(0, 2) + ")"; item["path"] = driveInfo.Path; item["leaf"] = false; item["expanded"] = false; item["enpandable"] = true; } } FSSFolderInfoCollection folders = FileStoreManager.GetFolders(cn, serverName, path); foreach (FSSFolderInfo folderInfo in folders) { JObject item = new JObject(); children.Add(item); item["iconCls"] = "folder"; item["text"] = folderInfo.Name; item["path"] = folderInfo.Path; item["leaf"] = false; item["expanded"] = false; item["enpandable"] = true; } } //输出数据 return(rv); }
/// <summary> /// 处理多余的数据 /// </summary> /// <param name="tblName">表名</param> /// <param name="key">键值</param> /// <param name="maxKey">最大键值</param> /// <param name="minKey">最小键值</param> private void ProcessRemainData(string tblName, string key, string maxKey, string minKey) { string sql = string.Format("delete from {0} where {1}<@minKey or {1}>@maxKey", tblName, key); Dictionary <string, object> pms = new Dictionary <string, object>(); pms.Add("@maxKey", maxKey); pms.Add("@minKey", minKey); LocalServer.QueryInt(sql, pms); }
private void ClientApp_ToggleStateChanged(object sender, Telerik.WinControls.UI.StateChangedEventArgs args) { ResetAll(); ToggleEnableDisableMainServer(false); isSubServer = false; LocalServer.Clear(); LocalServer.Enabled = true; }
public CloudConnection(CloudSocket cloudSocket, CTSMarker cTSMarker) { mCloudSocket = cloudSocket; mCTSMarker = cTSMarker; mLocalServer = new LocalServer(cloudSocket, cTSMarker); mRemoteClient = new RemoteClient(cloudSocket); }
// Token: 0x0600003F RID: 63 RVA: 0x000027AC File Offset: 0x000009AC public void EnsureLocalMailbox(ADUser user, bool forceRefresh) { AnchorUtil.ThrowOnNullArgument(user, "user"); string mailboxServerFqdn = this.GetMailboxServerFqdn(user, forceRefresh); if (!string.Equals(mailboxServerFqdn, LocalServer.GetServer().Fqdn, StringComparison.OrdinalIgnoreCase)) { throw new AnchorMailboxNotFoundOnServerException(mailboxServerFqdn, LocalServer.GetServer().Fqdn, user.DistinguishedName); } }
public Server GetLocalServer() { Server localServer = null; this.DoAdCallAndTranslateExceptions(delegate { localServer = LocalServer.GetServer(); }, "DirectoryAccessor::GetLocalServer"); return(localServer); }
/// <summary> /// 获取需要同步的表 /// </summary> /// <returns>表实体列表</returns> public List <Model.TableModel.Sys_tbl_operate> GetTableModelNeedSync() { try { return(LocalServer.QueryList <Model.TableModel.Sys_tbl_operate>("tbl_operate_type='download' and status_no='310'")); } catch (Exception) { return(null); } }
public static void Main(string[] args) { try { App app = new App { ShutdownMode = System.Windows.ShutdownMode.OnExplicitShutdown }; CultureInfo.DefaultThreadCurrentCulture = CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo("en-US"); Server.OnOperation += Server.OnOperation_SaveCurrentCulture; if (RunLocally()) { LocalServer.Start(Settings.Default.LocalDatabaseConnectionString); Server.OfflineMode = true; Program.GetServer = LocalServer.GetLocalServer; DisconnectedClient.GetTransferServer = LocalServer.GetLocalServerTransfer; } else //Run remotely { Program.GetServer = RemoteServer; DisconnectedClient.GetTransferServer = RemoteServerTransfer; } Server.SetNewServerCallback(NewServerAndLogin); Server.Connect(); App.Start(); if (!Server.OfflineMode) { UploadIfNecessary(); } app.ShutdownMode = ShutdownMode.OnMainWindowClose; app.Run(new Main()); } catch (NotConnectedToServerException) { } catch (Exception e) { HandleException("Start-up error", e, null); } finally { Server.Disconnect(); if (Server.OfflineMode) { LocalServer.Stop(); } } }
static bool StartServer(Guid serverClassGuid) { Trace.WriteLine("[Enter]StartServer"); using (var server = new LocalServer()) { server.RegisterClass <HidemaruLspBackEndServer>(serverClassGuid); SleepForever(); } Trace.WriteLine("[Leave]StartServer"); return(true); }
private void btnConnect_Click(object sender, EventArgs e) { if (this.gablarski.IsConnected || this.gablarski.IsConnecting) { this.reconnecting = false; this.gablarski.DisconnectAsync(); LocalServer.Shutdown(); } this.ShowConnect(true); }
public async void InitServer() { IsBusy = true; _localServer = new LocalServer(); await _localServer.InitlizeServer(AppManager.Setting.Server.ServerUrl); ServerInitialized = true; await LoadTagsAndSorts(); await LoadWallpapers(); IsBusy = false; }
private void ConnectClientToServerAndCheckState(LocalClient client, LocalServer server) { client.Connect(server.Address); Assert.IsTrue(client.IsConnected); }
private void MainFormLoad(object sender, EventArgs e) { UISync.Init(this); try { File.WriteAllText(Program.AppDataPath + "exit.txt", "RUNNING"); } catch (Exception ex) { Log.Error("",ex); } InitLogging(); EncoderParams = new EncoderParameters(1); EncoderParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, Conf.JPEGQuality); //this initializes the port mapping collection NATUPNPLib.IStaticPortMappingCollection map = NATControl.Mappings; if (Conf.MediaDirectory == null || Conf.MediaDirectory == "NotSet") { Conf.MediaDirectory = Program.AppDataPath + @"WebServerRoot\Media\"; } if (!Directory.Exists(Conf.MediaDirectory)) { string notfound = Conf.MediaDirectory; //Conf.MediaDirectory = Program.AppDataPath + @"WebServerRoot\Media\"; Log.Warn("Media directory could not be found (" + notfound + ") - reset it to " + Program.AppDataPath + @"WebServerRoot\Media\" + " in settings if it doesn't attach."); } if (!VlcHelper.VlcInstalled) { Log.Warn( "VLC not installed - install VLC (x86) for extra connectivity and inbuilt video playback."); } else { var v = VlcHelper.VlcVersion; if (v.CompareTo(VlcHelper.VMin) < 0) { Log.Warn( "Old VLC installed - update VLC (x86) for extra connectivity and inbuilt video playback."); } else { if (v.CompareTo(new Version(2, 0, 2)) == 0) { Log.Warn( "VLC v2.0.2 detected - there are known issues with this version of VLC (HTTP streaming is broken for a lot of cameras) - if you are having problems with VLC connectivity we recommend you install v2.0.1 ( http://download.videolan.org/pub/videolan/vlc/2.0.1/ ) or the latest (if available)."); } } } _fsw = new FileSystemWatcher { Path = Program.AppDataPath, IncludeSubdirectories = false, Filter = "external_command.txt", NotifyFilter = NotifyFilters.LastWrite }; _fsw.Changed += FswChanged; _fsw.EnableRaisingEvents = true; GC.KeepAlive(_fsw); Menu = mainMenu; notifyIcon1.ContextMenuStrip = ctxtTaskbar; Identifier = Guid.NewGuid().ToString(); MWS = new LocalServer(this) { ServerRoot = Program.AppDataPath + @"WebServerRoot\", }; if (Conf.Monitor) { var w = Process.GetProcessesByName("ispymonitor"); if (w.Length == 0) { try { var si = new ProcessStartInfo(Program.AppPath + "/ispymonitor.exe", "ispy"); Process.Start(si); } catch { } } } GC.KeepAlive(MWS); SetBackground(); toolStripMenu.Visible = Conf.ShowToolbar; statusStrip1.Visible = Conf.ShowStatus; Menu = !Conf.ShowFileMenu ? null : mainMenu; if (Conf.Fullscreen && !SilentStartup) { WindowState = FormWindowState.Maximized; FormBorderStyle = FormBorderStyle.None; WinApi.SetWinFullScreen(Handle); } if (SilentStartup) { WindowState = FormWindowState.Minimized; } statusBarToolStripMenuItem.Checked = menuItem4.Checked = Conf.ShowStatus; toolStripToolStripMenuItem.Checked = menuItem6.Checked = Conf.ShowToolbar; fileMenuToolStripMenuItem.Checked = menuItem5.Checked = Conf.ShowFileMenu; fullScreenToolStripMenuItem1.Checked = menuItem3.Checked = Conf.Fullscreen; alwaysOnTopToolStripMenuItem1.Checked = menuItem8.Checked = Conf.AlwaysOnTop; mediaPaneToolStripMenuItem.Checked = menuItem7.Checked = Conf.ShowMediaPanel; menuItem22.Checked = Conf.LockLayout; TopMost = Conf.AlwaysOnTop; Iconfont = new Font(FontFamily.GenericSansSerif, Conf.BigButtons ? 22 : 15, FontStyle.Bold, GraphicsUnit.Pixel); double dOpacity; Double.TryParse(Conf.Opacity.ToString(CultureInfo.InvariantCulture), out dOpacity); Opacity = dOpacity/100.0; if (Conf.ServerName == "NotSet") { Conf.ServerName = SystemInformation.ComputerName; } notifyIcon1.Text = Conf.TrayIconText; notifyIcon1.BalloonTipClicked += NotifyIcon1BalloonTipClicked; autoLayoutToolStripMenuItem.Checked = Conf.AutoLayout; _updateTimer = new Timer(500); _updateTimer.Elapsed += UpdateTimerElapsed; _updateTimer.AutoReset = true; _updateTimer.SynchronizingObject = this; GC.KeepAlive(_updateTimer); _houseKeepingTimer = new Timer(1000); _houseKeepingTimer.Elapsed += HouseKeepingTimerElapsed; _houseKeepingTimer.AutoReset = true; _houseKeepingTimer.SynchronizingObject = this; GC.KeepAlive(_houseKeepingTimer); //load plugins var plugindir = new DirectoryInfo(Program.AppPath + "Plugins"); Log.Info("Checking Plugins..."); foreach (var dll in plugindir.GetFiles("*.dll")) { AddPlugin(dll); } foreach (DirectoryInfo d in plugindir.GetDirectories()) { Log.Info(d.Name); foreach (var dll in d.GetFiles("*.dll")) { AddPlugin(dll); } } resetLayoutToolStripMenuItem1.Enabled = mnuResetLayout.Enabled = false; //reset layout NetworkChange.NetworkAddressChanged += NetworkChangeNetworkAddressChanged; mediaPaneToolStripMenuItem.Checked = Conf.ShowMediaPanel; ShowHideMediaPane(); if (!String.IsNullOrEmpty(Conf.MediaPanelSize)) { string[] dd = Conf.MediaPanelSize.Split('x'); int d1 = Convert.ToInt32(dd[0]); int d2 = Convert.ToInt32(dd[1]); try { splitContainer1.SplitterDistance = d1; splitContainer2.SplitterDistance = d2; } catch { } } //load in object list if (_startCommand.Trim().StartsWith("open")) { ParseCommand(_startCommand); _startCommand = ""; } else { if (!File.Exists(Program.AppDataPath + @"XML\objects.xml")) { File.Copy(Program.AppPath + @"XML\objects.xml", Program.AppDataPath + @"XML\objects.xml"); } ParseCommand("open " + Program.AppDataPath + @"XML\objects.xml"); } if (_startCommand != "") { ParseCommand(_startCommand); } StopAndStartServer(); var t = new Thread(ConnectServices) {IsBackground = false}; t.Start(); if (SilentStartup) { _mWindowState = new PersistWindowState {Parent = this, RegistryPath = @"Software\ispy\startup"}; } _updateTimer.Start(); _houseKeepingTimer.Start(); if (Conf.RunTimes == 0) ShowGettingStarted(); if (File.Exists(Program.AppDataPath+"custom.txt")) { string[] cfg = File.ReadAllText(Program.AppDataPath + "custom.txt").Split(Environment.NewLine.ToCharArray()); foreach(string s in cfg) { if (!String.IsNullOrEmpty(s)) { string[] nv = s.Split('='); if (nv.Length>1) { switch (nv[0].ToLower().Trim()) { case "business": Conf.Vendor = nv[1].Trim(); break; case "link": PurchaseLink = nv[1].Trim(); break; case "manufacturer": IPTYPE = Conf.DefaultManufacturer = nv[1].Trim(); break; case "model": IPMODEL = nv[1].Trim(); break; case "affiliateid": case "affiliate id": case "aid": int aid = 0; if (Int32.TryParse(nv[1].Trim(), out aid)) { AFFILIATEID = aid; } break; } } } } string logo = Program.AppDataPath + "logo.jpg"; if (!File.Exists(logo)) logo = Program.AppDataPath + "logo.png"; if (File.Exists(logo)) { try { var bmp = Image.FromFile(logo); var pb = new PictureBox {Image = bmp}; pb.Width = pb.Image.Width; pb.Height = pb.Image.Height; pb.Left = _pnlCameras.Width/2 - pb.Width/2; pb.Top = _pnlCameras.Height/2 - pb.Height/2; _pnlCameras.Controls.Add(pb); _pnlCameras.BrandedImage = pb; } catch (Exception ex) { Log.Error("",ex); } } } else { if (!String.IsNullOrEmpty(Conf.Vendor)) { var pb = new PictureBox(); switch (Conf.Vendor.ToLower()) { case "ensidio": pb.Image = Resources.ensidio; PurchaseLink = "http://www.ensidio.com/"; break; case "tenvis": pb.Image = Resources.TENVIS; PurchaseLink = "http://www.tenvis.com/"; break; case "smartisp": pb.Image = Resources.smartisp; break; case "addplus": pb.Image = Resources.Addplus; break; case "foscam": pb.Image = Resources.foscam; PurchaseLink = "http://www.foscam.com/"; break; case "phyxius": pb.Image = Resources.phyxius; break; case "bigdipper": pb.Image = Resources.bigdipper; break; case "allnet gmbh": pb.Image = Resources.ALLNET; PurchaseLink = "http://www.allnet.de/"; break; case "eos": pb.Image = Resources.EOSLogo; PurchaseLink = "http://nowyoucansee.com/"; break; } pb.Width = pb.Image.Width; pb.Height = pb.Image.Height; pb.Left = _pnlCameras.Width/2 - pb.Width/2; pb.Top = _pnlCameras.Height/2 - pb.Height/2; _pnlCameras.Controls.Add(pb); _pnlCameras.BrandedImage = pb; } } Text = string.Format("iSpy v{0}", Application.ProductVersion); if (!String.IsNullOrEmpty(Conf.Vendor)) { Text += string.Format(" with {0}", Conf.Vendor); } LoadCommands(); if (!SilentStartup && Conf.ViewController) { ShowViewController(); viewControllerToolStripMenuItem.Checked = menuItem14.Checked = true; } pTZControllerToolStripMenuItem.Checked = menuItem18.Checked = pTZControllerToolStripMenuItem1.Checked = Conf.ShowPTZController; if (Conf.ShowPTZController) ShowHidePTZTool(); Conf.RunTimes++; try { _cputotalCounter = new PerformanceCounter("Processor", "% Processor Time", "_total", true); _cpuCounter = new PerformanceCounter("Process", "% Processor Time", Process.GetCurrentProcess().ProcessName, true); try { _pcMem = new PerformanceCounter("Process", "Working Set - Private", Process.GetCurrentProcess().ProcessName, true); } catch { //no working set - only total available on windows xp try { _pcMem = new PerformanceCounter("Memory", "Available MBytes"); _pcMemAvailable = true; } catch (Exception ex2) { Log.Error("",ex2); _pcMem = null; } } } catch (Exception ex) { Log.Error("",ex); _cputotalCounter = null; } }