Beispiel #1
0
        public static byte[] renderSnaphot(List <Camera> cameras, int width, int height)
        {
            PluginLogger.debug("RENDERING SNAPSHOT");

            /*RenderTexture rt = new RenderTexture(width, height, 24);
             *
             * foreach(Camera camera in cameras) {
             *  camera.targetTexture = rt;
             *  //camera.Render();
             * } */

            Texture2D screenShot = new Texture2D(width, height, TextureFormat.RGB24, false);

            //RenderTexture backupRenderTexture = RenderTexture.active;
            //RenderTexture.active = rt;
            screenShot.ReadPixels(new Rect(0, 0, width, height), 0, 0);

            foreach (Camera camera in cameras)
            {
                camera.targetTexture = null;
            }

            //RenderTexture.active = backupRenderTexture;

            byte[] result = screenShot.EncodeToJPG();
            Destroy(screenShot);
            //Destroy(rt);

            return(result);
        }
Beispiel #2
0
        /// <summary>
        /// The get plugin settings paths.
        /// </summary>
        /// <param name="pluginPath">
        /// The plugin path.
        /// </param>
        /// <param name="assembly">
        /// The assembly.
        /// </param>
        /// <returns>
        /// The <see cref="IList{T}"/>.
        /// </returns>
        private IList <string> GetPluginSettingsPaths(string pluginPath, Assembly assembly)
        {
            if (Regex.Match(pluginPath, @"^\.$").Success)
            {
                pluginPath = Directory.GetCurrentDirectory();
            }

            const string FileNameFormat     = "{0}.PluginSettings.Xml";
            var          assemblyLocation   = assembly.Location;
            var          pluginPathFileName = Path.GetFileName(assemblyLocation);

            if (string.IsNullOrEmpty(pluginPathFileName))
            {
                PluginLogger.LogError($"Couldn't get filename() of {assemblyLocation}");

                return(new List <string>());
            }

            var pluginPathFileNameFullPath = Path.Combine(pluginPath, pluginPathFileName);
            var settingsPaths = new List <string> {
                string.Format(FileNameFormat, pluginPathFileNameFullPath)
            };

            if (!pluginPathFileNameFullPath.Equals(assemblyLocation, StringComparison.CurrentCultureIgnoreCase))
            {
                settingsPaths.Add(string.Format(FileNameFormat, assembly.Location));
            }

            return(settingsPaths);
        }
Beispiel #3
0
    public static void LogAsDebug(this object message)
    {
        var    method = new StackFrame(1).GetMethod();
        string caller = method.DeclaringType.ToString() + "." + method.Name;

        PluginLogger.Debug(caller + "|" + message ?? "<null>");
    }
Beispiel #4
0
    //very expensive performance wise so call it only for errors
    public static void LogAsError(this object error)
    {
        var    method = new StackFrame(1).GetMethod();
        string caller = method.DeclaringType.ToString() + "." + method.Name;

        PluginLogger.Error(caller + "|" + error ?? "<null>");
    }
Beispiel #5
0
        public IEnumerator NewScreenshot()
        {
            if (mutex)
            {
                yield return(true);
            }
            PluginLogger.debug("BYPASSED MUTEX");
            mutex = true;
            PluginLogger.debug("WAITING FOR END OF FRAME");
            yield return(new WaitForEndOfFrame());

            UpdateCameras();

            List <Camera> renderingCameras = new List <Camera>();

            foreach (string cameraName in activeCameras)
            {
                PluginLogger.debug("GETTING CAMERA" + cameraName);
                renderingCameras.Add(cameraDuplicates[cameraName]);
            }

            this.imageBytes = SnapshotRenderer.renderSnaphot(renderingCameras, camerares, camerares);
            this.didRender  = true;
            mutex           = false;
        }
Beispiel #6
0
        public void OnClick(object sender, EventArgs e)
        {
            IMenuMetadata meta = PluginManager.GetMedadata();

            MessageBox.Show(string.Format("{0} has been pressed", meta.Text), this.GetType().Assembly.GetName().Name, MessageBoxButtons.OK);
            PluginLogger.Debug("{0} has been pressed", meta.Text);
        }
Beispiel #7
0
        /// <summary>
        /// The overlay plugin settings.
        /// </summary>
        /// <param name="pluginPath">
        /// The plugin Path.
        /// </param>
        private void OverlayPluginSettings(string pluginPath)
        {
            if (PluginAssemblies.Count == 0)
            {
                PluginLogger.LogInfo("No plugins detected so no pluginsettings to overlay");
            }

            foreach (var assembly in PluginAssemblies)
            {
                var locations = GetPluginSettingsPaths(pluginPath, assembly);

                foreach (var settingsFile in locations)
                {
                    if (!File.Exists(settingsFile))
                    {
                        PluginLogger.LogDebug($"Skipping plugin settings file [{settingsFile}]: It does not exist");
                        continue;
                    }

                    if (!PerformOverlay(settingsFile))
                    {
                        PluginLogger.LogFail("OverlayPluginSettings", $"Failed to overlay [{settingsFile}]. Check config file");
                    }
                }
            }
        }
Beispiel #8
0
        public void OnClick(object sender, EventArgs e)
        {
            IButtonMetadata meta = PluginManager.GetMedadata();

            MessageBox.Show(string.Format("{0} has been pressed\r\n\r\nDataGrid contains {1} rows", meta.Text, PluginManager.DataGrid.Rows.Count), this.GetType().Assembly.GetName().Name, MessageBoxButtons.OK);
            PluginLogger.Debug("{0} has been pressed", meta.Text);
        }
Beispiel #9
0
        public void OnClick(object sender, EventArgs e)
        {
            IButtonMetadata meta = PluginManager.GetMedadata();

            PluginLogger.Trace("{0} has been pressed", meta.Text);

            if (PluginManager.DataGrid.Rows.Count > 0)
            {
                SaveFileDialog saveFile = new SaveFileDialog()
                {
                    FileName = "SingleCopy Export", Filter = "Excel Spreadsheet (*.xlsx)|*.xlsx"
                };
                if (saveFile.ShowDialog(PluginManager.Form) == DialogResult.OK)
                {
                    IWorkbook workbook = new XSSFWorkbook();
                    ISheet    sheet    = workbook.CreateSheet("SingleCopy Export");

                    IRow sheetRow = sheet.CreateRow(0);
                    //Output Column Headers
                    foreach (DataGridViewColumn col in PluginManager.DataGrid.Columns)
                    {
                        if (col.Visible)
                        {
                            ICell cell = sheetRow.CreateCell(sheetRow.LastCellNum >= 0 ? sheetRow.LastCellNum : 0);
                            cell.SetCellValue(col.HeaderText);
                        }
                    }
                    int LastCellNum = sheetRow.LastCellNum - 1;

                    //Output Table Content
                    foreach (OutlookGridRow row in PluginManager.DataGrid.Rows)
                    {
                        if (!row.IsGroupRow)
                        {
                            sheetRow = sheet.CreateRow(sheet.LastRowNum + 1);

                            foreach (DataGridViewCell col in row.Cells)
                            {
                                if (col.Visible)
                                {
                                    ICell cell = sheetRow.CreateCell(sheetRow.LastCellNum >= 0 ? sheetRow.LastCellNum : 0);
                                    cell.SetCellValue(col.Value?.ToString() ?? "");
                                }
                            }
                        }
                    }

                    //Formating
                    sheet.SetAutoFilter(new NPOI.SS.Util.CellRangeAddress(0, sheet.LastRowNum, 0, LastCellNum));

                    //Save
                    using (FileStream s = new FileStream(saveFile.FileName, FileMode.Create))
                    {
                        workbook.Write(s);
                        s.Close();
                    }
                }
            }
        }
        public void Start()
        {
            PluginCommons.init(new PlanItinearyForRoversProperties());

            GameEvents.onPlanetariumTargetChanged.Add(new EventData <MapObject> .OnEvent(onPlanetariumTargetChanged));

            PluginLogger.logDebug("Start " + DateTime.Now);
        }
 public void Info_CreatesLogFile()
 {
     InitializeLogger();
     PluginLogger.GetInstance().Info("Info");
     PluginLogger.GetInstance().DeInit();
     Assert.IsTrue(File.Exists(Path.Combine(LogDirPath, LogFileName)));
     File.Delete(Path.Combine(LogDirPath, LogFileName));
 }
Beispiel #12
0
 public static RawImage getStageTexture(StageIcon stageIcon)
 {
     if (stageIcon.GetType().GetField("iconImage", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public) == null)
     {
         PluginLogger.logDebug("field null!");
     }
     return((RawImage)stageIcon.GetType().GetField("iconImage", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public).GetValue(stageIcon));
 }
 public void Update()
 {
     try
     {
     }
     catch (Exception ex)
     {
         PluginLogger.PluginFatal(ex.ToString());
     }
 }
Beispiel #14
0
        public void Should_handle_case_where_stacktrace_is_null()
        {
            var p = new PluginLogger(null);

            Assert.DoesNotThrow(() =>
            {
                var args = new FirstChanceExceptionEventArgs(new COMException("blerg"));
                p.LogFirstChanceException(args);
            });
        }
Beispiel #15
0
 public static void LogAsDebugAsync(this object message, int asyncDelay = 0)
 {
     Task.Factory.StartNew(() =>
     {
         if (asyncDelay > 0)
         {
             System.Threading.Thread.Sleep(asyncDelay);
         }
         PluginLogger.Debug(message);
     });
 }
Beispiel #16
0
        /// <summary>
        /// The load stf plugins.
        /// </summary>
        /// <param name="stfPluginPath">
        /// The stf plugin path.
        /// </param>
        /// <param name="pluginPatterns">
        /// The plugin Patterns.
        /// </param>
        /// <returns>
        /// The <see cref="int"/>.
        /// </returns>
        public int LoadStfPlugins(string stfPluginPath, string pluginPatterns = "*stf.*.dll")
        {
            if (!Directory.Exists(stfPluginPath))
            {
                return(0);
            }

            PluginLogger.LogHeader("looking for plugins at [{0}]", stfPluginPath);

            var patterns = pluginPatterns.Split(';');

            foreach (var pattern in patterns)
            {
                var stfPluginDllFileNames = Directory.GetFiles(stfPluginPath, pattern);
                var assemblies            = new List <Assembly>(stfPluginDllFileNames.Length);

                foreach (var stfPluginDllFileName in stfPluginDllFileNames)
                {
                    var stfPluginDllAssemblyName = AssemblyName.GetAssemblyName(stfPluginDllFileName);
                    var assembly = Assembly.Load(stfPluginDllAssemblyName);
                    assemblies.Add(assembly);
                }

                foreach (var assembly in assemblies)
                {
                    if (assembly == null)
                    {
                        continue;
                    }

                    var types = assembly.GetTypes();

                    foreach (var type in types)
                    {
                        if (type.IsInterface || type.IsAbstract)
                        {
                            continue;
                        }

                        if (type.GetInterface(typeof(IStfPlugin).FullName) != null)
                        {
                            RegisterPlugin(type);
                            PluginAssemblies.Add(assembly);
                        }
                    }
                }
            }

            OverlayPluginSettings(stfPluginPath);

            PluginLogger.LogInfo("Done looking for plugins");

            return(container.Registrations.Count());
        }
        public void IsEnabled_WhenLoggingIsNotEnabled_ReturnsTrue()
        {
            var environmentVariableReader = CreateEnvironmentVariableReaderMock(isLoggingEnabled: false);

            using (var logger = new PluginLogger(environmentVariableReader.Object))
            {
                Assert.False(logger.IsEnabled);
            }

            environmentVariableReader.VerifyAll();
        }
        public void Error_CreatesLogFile()
        {
            var exception =
                new Exception("message",
                              new Exception("inner message",
                                            new Exception("inner most message")));

            InitializeLogger();
            PluginLogger.GetInstance().Error(exception);
            PluginLogger.GetInstance().DeInit();
            Assert.IsTrue(File.Exists(Path.Combine(LogDirPath, LogFileName)));
            File.Delete(Path.Combine(LogDirPath, LogFileName));
        }
Beispiel #19
0
        public MainWindow()
        {
            this.Closing += new System.ComponentModel.CancelEventHandler(MainWindow_Closing);
            InitializeComponent();

            _networkLogs = new NetworkLogger(this.Dispatcher);
            _networkLogs.SessionStart += new NetworkLoggerSessionUpdatedHandler(network_NetworkSessionStart);
            _networkLogs.SessionEnd   += new NetworkLoggerSessionUpdatedHandler(network_NetworkSessionEnd);
            _networkLogs.Initialize();

            _pluginLogs = new PluginLogger(this.Dispatcher);
            _pluginLogs.ActiveLogChanged += new PluginLoggerActiveLogChangedHandler(_pluginLogs_ActiveLogChanged);
            _pluginLogs.Initialize();
        }
Beispiel #20
0
        private void CleanUp()
        {
            PluginLogger.logDebug("CleanUp in " + EditorDriver.editorFacility);

            foreach (ApplicationLauncherButton button in appLauncherButtons)
            {
                ApplicationLauncher.Instance.RemoveModApplication(button);
            }

            foreach (BaseWindow window in windows)
            {
                window.hideWindow();
            }
        }
Beispiel #21
0
 private KaptureConfig(string appDataFolder)
 {
     try
     {
         Config = new Model.Config();
         var configFilePath = Path.Combine(appDataFolder, KaptureConfigConstants.ConfigDirName);
         ConfigManager.Initialize(configFilePath, KaptureConfigConstants.ConfigFileName, Config);
         ConfigManager = (ConfigManager)ConfigManager.GetInstance();
         ConfigManager.LoadSettings();
     }
     catch (Exception ex)
     {
         PluginLogger.GetInstance().Error(ex);
     }
 }
Beispiel #22
0
        void  MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (_networkLogs != null)
            {
                _networkLogs.DeInitialize(null);
                _networkLogs.SessionStart -= network_NetworkSessionStart;
                _networkLogs.SessionEnd   -= network_NetworkSessionEnd;
                _networkLogs = null;
            }

            if (_pluginLogs != null)
            {
                _pluginLogs.DeInitialize();
                _pluginLogs = null;
            }
        }
        public void IsEnabled_WhenLoggingIsEnabled_ReturnsTrue()
        {
            using (var testDirectory = TestDirectory.Create())
            {
                var environmentVariableReader = CreateEnvironmentVariableReaderMock(
                    isLoggingEnabled: true,
                    testDirectory: testDirectory);

                using (var logger = new PluginLogger(environmentVariableReader.Object))
                {
                    Assert.True(logger.IsEnabled);
                }

                environmentVariableReader.VerifyAll();
            }
        }
Beispiel #24
0
        /// <summary>
        /// The perform overlay.
        /// </summary>
        /// <param name="settingsFilePath">
        /// The settings file path.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        private bool PerformOverlay(string settingsFilePath)
        {
            PluginLogger.LogInfo($"Applying plugin settings: [{settingsFilePath}]");

            try
            {
                StfConfiguration.OverLay(settingsFilePath);
            }
            catch (Exception ex)
            {
                PluginLogger.LogError($"Error when overlaying plugin settings: {ex.Message}");

                return(false);
            }

            return(true);
        }
        public void Write_WhenLoggingIsEnabled_WritesToStringResult()
        {
            using (var testDirectory = TestDirectory.Create())
            {
                var environmentVariableReader = CreateEnvironmentVariableReaderMock(
                    isLoggingEnabled: true,
                    testDirectory: testDirectory);
                RandomLogMessageWithTime logMessage;
                DateTimeOffset           loggerInitLoggedAt;
                DateTimeOffset           randomMessageLoggedAt;
                using (var logger = new PluginLogger(environmentVariableReader.Object))
                {
                    loggerInitLoggedAt = DateTimeOffset.UtcNow;
                    Thread.Sleep(10000); // Enough for potential accuracy issues to arise.
                    logMessage            = new RandomLogMessageWithTime(logger.Now);
                    randomMessageLoggedAt = DateTimeOffset.UtcNow;
                    logger.Write(logMessage);
                }

                var logFile = GetLogFile(testDirectory);

                Assert.NotNull(logFile);
                Assert.True(logFile.Exists);

                var actualLines = File.ReadAllLines(logFile.FullName);

                Assert.Collection(actualLines,
                                  actualLine =>
                {
                    var message = VerifyOuterMessageAndReturnInnerMessage(actualLine, loggerInitLoggedAt.AddSeconds(-1), loggerInitLoggedAt.AddSeconds(1), "stopwatch");

                    Assert.Equal(1, message.Count);
                    Assert.Equal(Stopwatch.Frequency, message["frequency"].Value <long>());
                },
                                  actualLine =>
                {
                    var message = VerifyOuterMessageAndReturnInnerMessage(actualLine, randomMessageLoggedAt.AddSeconds(-1), randomMessageLoggedAt.AddSeconds(1), "random");

                    Assert.Equal(1, message.Count);
                    Assert.Equal(logMessage.Message, message["message"]);
                });

                environmentVariableReader.VerifyAll();
            }
        }
Beispiel #26
0
        protected void Initialize(IPluginLoader loader, FileInfo dataFolder, FileInfo file, Assembly assm)
        {
            if (!initialized)
            {
                this.initialized = true;
                this.loader      = loader;
                this.server      = server;
                this.file        = file;
                this.dataFolder  = dataFolder;
                this.assembly    = assm;
                this.configFile  = new FileInfo(Path.Combine(dataFolder.FullName, "config.yml"));
                this.logger      = new PluginLogger(this);
                ServerConfig db = new ServerConfig();

                if (!dataFolder.Exists)
                {
                    dataFolder.Create();
                }
            }
        }
Beispiel #27
0
        public void Install(TinyIoCContainer container)
        {
            var outputWindow = container.Resolve <IOutputWindow>();
            var config       = new LoggingConfiguration();

            var outputWindowTarget = new OutputWindowTarget(outputWindow);

            outputWindowTarget.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${exception:ToString}";
            config.AddTarget("mail", outputWindowTarget);

            var rule1 = new LoggingRule("NBehave.*", LogLevel.Fatal, outputWindowTarget);

            config.LoggingRules.Add(rule1);

            LogManager.Configuration = config;

            var pluginLogger = new PluginLogger(LogManager.GetLogger("default"));

            container.Register <IPluginLogger>(pluginLogger);
        }
        public void Write_WhenLoggingIsNotEnabled_DoesNotCreateLogFile()
        {
            using (var testDirectory = TestDirectory.Create())
            {
                var environmentVariableReader = CreateEnvironmentVariableReaderMock(
                    isLoggingEnabled: false,
                    testDirectory: testDirectory);
                var logMessage = new RandomLogMessage();

                using (var logger = new PluginLogger(environmentVariableReader.Object))
                {
                    logger.Write(logMessage);
                }

                var files = Directory.GetFiles(testDirectory.Path, "*", SearchOption.TopDirectoryOnly);

                Assert.Empty(files);

                environmentVariableReader.VerifyAll();
            }
        }
Beispiel #29
0
        /// <summary>
        /// The register type.
        /// </summary>
        /// <param name="typeToRegister">
        /// The type to register.
        /// </param>
        private void RegisterPlugin(Type typeToRegister)
        {
            var interfaceName = $"I{typeToRegister.Name}";
            var mainInterface = typeToRegister.GetInterface(interfaceName);

            if (mainInterface == null)
            {
                PluginLogger.LogWarning("Registering type [{0}] with no matching interface", typeToRegister.Name);

                container.RegisterType(
                    typeToRegister,
                    new InjectionProperty("StfContainer"),
                    new InjectionProperty("StfLogger"));

                return;
            }

            PluginLogger.LogInfo("Registering type [{0}] with matching interface [{1}]", typeToRegister.Name, interfaceName);

            container.RegisterMyType(mainInterface, typeToRegister);
        }
Beispiel #30
0
        public void UpdateCameras()
        {
            if (CameraManager.Instance != null)
            {
                PluginLogger.debug("CURRENT CAMERA MODE: " + CameraManager.Instance.currentCameraMode);
            }

            activeCameras = new List <string>();

            foreach (Camera camera in Camera.allCameras)
            {
                debugCameraDetails(camera);
                // Don't duplicate any cameras we're going to skip
                if (skippedCameras.IndexOf(camera.name) != -1)
                {
                    continue;
                }

                Camera cameraDuplicate;

                if (!cameraDuplicates.ContainsKey(camera.name))
                {
                    var cameraDuplicateGameObject = new GameObject(cameraContainerNamePrefix + camera.name);
                    cameraDuplicate = cameraDuplicateGameObject.AddComponent <Camera>();
                    cameraDuplicates[camera.name] = cameraDuplicate;
                }
                else
                {
                    cameraDuplicate = cameraDuplicates[camera.name];
                }

                cameraDuplicate.CopyFrom(camera);
                cameraDuplicate.enabled     = false;
                cameraDuplicate.fieldOfView = fovAngle;
                cameraDuplicate.aspect      = aspect;

                //Now that the camera has been duplicated, add it to the list of active cameras
                activeCameras.Add(camera.name);
            }
        }
Beispiel #31
0
        public Server()
        {
            ChraftConfig.Load();
            BanSystem = new BanSystem();
            BanSystem.LoadBansAndWhiteList();
            ClientsConnectionSlots = 30;
            Packet.Role = StreamRole.Server;
            Rand = new Random();
            UseOfficalAuthentication = ChraftConfig.UseOfficalAuthentication;
            ServerHash = GetRandomServerHash();
            EncryptionEnabled = ChraftConfig.EncryptionEnabled;
            EnableUserSightRadius = ChraftConfig.EnableUserSightRadius;
            Clients = new ConcurrentDictionary<int, Client>();
            AuthClients = new ConcurrentDictionary<int, Client>();
            Logger = new Logger(this, ChraftConfig.LogFile);
            PluginLogger = new PluginLogger(Logger);
            PluginManager = new PluginManager(this, ChraftConfig.PluginFolder);
            Items = new ItemDb(ChraftConfig.ItemsFile);
            Recipes = Recipe.FromXmlFile(ChraftConfig.RecipesFile);
            SmeltingRecipes = SmeltingRecipe.FromFile(ChraftConfig.SmeltingRecipesFile);
            ClientCommandHandler = new ClientCommandHandler();
            ServerCommandHandler = new ServerCommandHandler();
            PacketMap.Initialize();

            _AcceptEventArgs = new SocketAsyncEventArgs();
            _AcceptEventArgs.Completed += Accept_Completion;

            _Listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            for(int i = 0; i < 10; ++i)
            {
                MapChunkPacket.DeflaterPool.Push(new Deflater(5));
            }

            PlayersToSave = new ConcurrentQueue<Client>();
            PlayersToSavePostponed = new ConcurrentQueue<Client>();
            _generators = new Dictionary<string, IChunkGenerator>();


            ServerKey = PacketCryptography.GenerateKeyPair();

        }