Beispiel #1
0
 public SendMessage(string ServerName)
 {
     _servername = ServerName;
     #if DEBUG
     _debuglog = new DebugLog("IrcWrite_" + _servername + ".log");
     #endif
 }
Beispiel #2
0
		private void SaveDebugLogEntity(DebugLog entity)
		{
			using (LoggerContext db = new LoggerContext())
			{
				db.DebugLogs.Add(entity);
				db.SaveChanges();
			}
		}
 public WatchThreadSerializer(WatchThreadManager argWatchThreadManager, DownloadManager argDownloadManager, DispatchedObservableCollection<WatchThreadViewItem> argwatchThreadViewCollection)
 {
     this.debugLogText = new DebugLog();
       this.watchThreadManager = argWatchThreadManager;
       this.downloadManager = argDownloadManager;
       this.watchThreadViewCollection = argwatchThreadViewCollection;
       string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).ToString(), "InBefore404");
       try {
     Directory.CreateDirectory(path);
       } catch {
       }
       this.serializeFilePath = Path.Combine(path, "WatchThreadList.xml");
 }
        public static void ExportCityCoordinates()
        {
            var log = new DebugLog(typeof(BikeServiceProvider));
            foreach (var city in GetAllCities())
            {
                //if (city.Latitude != 0 && city.Longitude != 0)
                if (city.Radius > 1)
                    continue;

                List<StationLocation> _stations = null;
                try
                {
                    _stations = city.Provider.DownloadStations(city.UrlCityName).Wait();
                }
                catch (WebExceptionEx e)
                {
                    log.Warn("Service: {0}, City: {1}, Error: {2}\n{3}", city.Provider.ServiceName, city.UrlCityName, e.URL, e.ToString());
                    _stations = null;
                }
                catch (WebException e)
                {
                    log.Warn("Service: {0}, City: {1}, Error: {2}", city.Provider.ServiceName, city.UrlCityName, e.ToString());
                    _stations = null;
                }
                catch (Exception e)
                {
                    log.Warn("Service: {0}, City: {1}, Error: {2}", city.Provider.ServiceName, city.UrlCityName, e.ToString());
                    _stations = null;
                }
                if (_stations == null)
                    continue;
                _stations = FilterInvalidStations(_stations);
                if (_stations.Count > 0)
                {
                    var stationsArea = LocationHelper.GetLocationRect(_stations);
                    city.Latitude = stationsArea.Center.Latitude;
                    city.Longitude = stationsArea.Center.Longitude;
                    city.Radius = (stationsArea.Center.GetDistanceTo(stationsArea.Northeast)
                        + stationsArea.Center.GetDistanceTo(stationsArea.Northwest)
                        + stationsArea.Center.GetDistanceTo(stationsArea.Southeast)
                        + stationsArea.Center.GetDistanceTo(stationsArea.Southwest)) / 4;
                    city.Radius = Math.Max(city.Radius, 1000);
                }
            }
            SaveCityCoordinates(allCities);
        }
Beispiel #5
0
        static void Main( string[] args )
        {
            DebugKompositum kompositum = new DebugKompositum ();

            DebugLog debLog = new DebugLog ();

            DebugMail debMail = new DebugMail ();

            DebugSMS debSMS = new DebugSMS ();

            kompositum.addDebugger ( debLog );
            kompositum.addDebugger ( debMail );
            kompositum.addDebugger ( debSMS );

            kompositum.debug ( "C# ist gut!" );

            Console.ReadKey ();
        }
        public bool GetStatus(StatusLevel statusLevel, string fstatArgs, string path)
        {
            //D.Log( "Processing " + path );

            string arguments = "status -aedf \"" + path + "\"";

            CommandLineOutput statusCommandLineOutput = null;

            if (statusLevel == StatusLevel.Local)
            {
                using (var p4StatusTask = P4Util.Instance.CreateP4CommandLine(arguments))
                {
                    statusCommandLineOutput = P4Util.Instance.ExecuteOperation(p4StatusTask);
                }
            }

            arguments = fstatArgs + " \"" + path + "\"";
            CommandLineOutput fstatCommandLineOutput = null;

            using (var p4FstatTask = P4Util.Instance.CreateP4CommandLine(arguments))
            {
                fstatCommandLineOutput = P4Util.Instance.ExecuteOperation(p4FstatTask);
            }

            if (statusCommandLineOutput == null || statusCommandLineOutput.Failed || string.IsNullOrEmpty(statusCommandLineOutput.OutputStr) || !active)
            {
                return(false);
            }
            if (fstatCommandLineOutput == null || fstatCommandLineOutput.Failed || string.IsNullOrEmpty(fstatCommandLineOutput.OutputStr) || !active)
            {
                return(false);
            }
            try
            {
                var statusDB = statusCommandLineOutput != null?P4StatusParser.P4ParseStatus(statusCommandLineOutput.OutputStr, P4Util.Instance.Vars.userName) : null;

                var fstatDB = P4StatusParser.P4ParseFstat(fstatCommandLineOutput.OutputStr, P4Util.Instance.Vars.workingDirectory);
                lock (statusDatabaseLockToken)
                {
                    if (statusDB != null)
                    {
                        foreach (var statusIt in statusDB)
                        {
                            var status = statusIt.Value;
                            status.reflectionLevel = statusLevel == StatusLevel.Remote ? VCReflectionLevel.Repository : VCReflectionLevel.Local;
                            statusDatabase[new ComposedString(statusIt.Key.Compose().Replace(P4Util.Instance.Vars.workingDirectory + "/", ""))] = status;
                        }
                    }

                    foreach (var statusIt in fstatDB)
                    {
                        VersionControlStatus status = null;
                        ComposedString       aPath  = new ComposedString(statusIt.Key.Compose().Replace(P4Util.Instance.Vars.workingDirectory + "/", ""));
                        statusDatabase.TryGetValue(aPath, out status);
                        if (status == null || status.reflectionLevel == VCReflectionLevel.Pending)
                        {
                            // no previous status or previous status is pending, so set it here
                            status = statusIt.Value;
                        }
                        else
                        {
                            // probably got this status from the "status -a -e -d" command, merge it with whatever we got back from fstat
                            if (status.fileStatus == VCFileStatus.Modified && statusIt.Value.remoteStatus == VCRemoteFileStatus.Modified)
                            {
                                // we have modified locally and file is out of date with server - mark as a conflict (might not be, but at
                                // least this will raise a flag with the user to make sure they get up to date before going any further)
                                status.fileStatus         = VCFileStatus.Conflicted;
                                status.treeConflictStatus = VCTreeConflictStatus.TreeConflict;
                            }
                        }
                        status.reflectionLevel = statusLevel == StatusLevel.Remote ? VCReflectionLevel.Repository : VCReflectionLevel.Local;
                        statusDatabase[aPath]  = status;
                    }
                }
                lock (requestQueueLockToken)
                {
                    if (statusDB != null)
                    {
                        foreach (var assetIt in statusDB.Keys)
                        {
                            if (statusLevel == StatusLevel.Remote)
                            {
                                remoteRequestQueue.Remove(assetIt.Compose());
                            }
                            localRequestQueue.Remove(assetIt.Compose());
                        }
                    }
                    foreach (var assetIt in fstatDB.Keys)
                    {
                        if (statusLevel == StatusLevel.Remote)
                        {
                            remoteRequestQueue.Remove(assetIt.Compose());
                        }
                        localRequestQueue.Remove(assetIt.Compose());
                    }
                }
                OnStatusCompleted();
            }
            catch (Exception e)
            {
                DebugLog.ThrowException(e);
                return(false);
            }

            return(true);
        }
Beispiel #7
0
        public static void Main(string[] args)
        {
            try {
                string name = args.Length > 0 ? args[0] : "Ze-rone";

                Networking networking = new Networking();
                GameMap    gameMap    = networking.Initialize(name);

                List <Move> moveList = new List <Move>();
                int         step     = 1;
                for (;;)
                {
                    DebugLog.AddLog($"New Move: {step++}----------------------------------------------------------------------");
                    moveList.Clear();
                    gameMap.UpdateMap(Networking.ReadLineIntoMetadata());

                    List <Planet> ownedPlanets   = new List <Planet>();
                    List <Planet> unOwnedPlanets = new List <Planet>();

                    foreach (Planet planet in gameMap.GetAllPlanets().Select(kvp => kvp.Value))
                    {
                        if (planet.IsOwnedBy(gameMap.GetMyPlayerId()))
                        {
                            ownedPlanets.Add(planet);
                        }
                        else
                        {
                            unOwnedPlanets.Add(planet);
                        }
                        planet.ShipsByDistance = gameMap.NearbyEntitiesByDistance(planet).Where(e => e.Value.GetType() == typeof(Ship) && e.Value.GetOwner() == gameMap.GetMyPlayerId()).OrderBy(kvp => kvp.Key).ToList();
                    }

                    // To prevent wasted movements from ships, if a ship starts toward a planet it will continue to that planet to complete it's mission.
                    // If the planet is taken over then the bots are no longer "claimed" by it and they can redirect, this happens when we're attacking and in the
                    // constructor for the planet.
                    foreach (var kvp in Planet.ShipsClaimed)
                    {
                        var toRemove = new List <Ship>();
                        foreach (var ship in kvp.Value)
                        {
                            // Make sure the ship is still around.
                            var realShip = gameMap.GetAllShips().FirstOrDefault(s => s.GetId() == ship.GetId());
                            if (realShip == null)
                            {
                                toRemove.Add(ship);
                            }
                            else
                            {
                                // Don't try to redock docking ships.
                                if (realShip.GetDockingStatus() != Ship.DockingStatus.Undocked)
                                {
                                    continue;
                                }
                                var planet = gameMap.GetPlanet(kvp.Key);
                                // We own this planet, or it is not owned, so we must have been flying to it to dock, continue doing so.
                                if (!planet.IsOwned() || planet.IsOwnedBy(gameMap.GetMyPlayerId()))
                                {
                                    NavigateToDock(planet, null, null, moveList, gameMap, false, realShip);
                                }
                                else
                                {
                                    NavigateToAttack(planet, null, null, moveList, gameMap, false, realShip);
                                }
                                realShip.ClaimStateless();
                            }
                        }
                        foreach (var ship in toRemove)
                        {
                            kvp.Value.Remove(ship);
                        }
                    }
                    ownedPlanets.Sort(PlanetComparer);
                    unOwnedPlanets.Sort(PlanetComparer);

                    CalculateMoves(ownedPlanets, unOwnedPlanets, moveList, gameMap);

                    Networking.SendMoves(moveList);
                }
            }
            catch (Exception ex) {
                DebugLog.AddLog($"{ex.Message}: {ex.StackTrace}");
                Networking.SendMoves(new List <Move>());
            }
        }
 public IEnumerable <string> GetIgnore(string path)
 {
     DebugLog.LogWarning("P4Commands.GetIgnore not implemented");
     return(null);
 }
Beispiel #9
0
 // private string outpath;
 public void Awake()
 {
     instance = this;
 }
Beispiel #10
0
        public static void Load(ref byte[] saveData)
        {
            int i = 0;

            SaveAndRestore.LoadData(ref i, saveData, ref citizenExpensePerFamily);
            SaveAndRestore.LoadData(ref i, saveData, ref citizenExpense);


            SaveAndRestore.LoadData(ref i, saveData, ref totalCitizenDrivingTime);
            SaveAndRestore.LoadData(ref i, saveData, ref totalCitizenDrivingTimeFinal);
            SaveAndRestore.LoadData(ref i, saveData, ref publicTransportFee);
            SaveAndRestore.LoadData(ref i, saveData, ref allTransportFee);
            SaveAndRestore.LoadData(ref i, saveData, ref level2HighWealth);
            SaveAndRestore.LoadData(ref i, saveData, ref level1HighWealth);
            SaveAndRestore.LoadData(ref i, saveData, ref level3HighWealth);
            SaveAndRestore.LoadData(ref i, saveData, ref familyWeightStableHigh);
            SaveAndRestore.LoadData(ref i, saveData, ref familyWeightStableLow);
            SaveAndRestore.LoadData(ref i, saveData, ref minimumLivingAllowance);
            SaveAndRestore.LoadData(ref i, saveData, ref minimumLivingAllowanceFinal);
            SaveAndRestore.LoadData(ref i, saveData, ref unfinishedTransitionLost);
            SaveAndRestore.LoadData(ref i, saveData, ref unfinishedTransitionLostFinal);


            SaveAndRestore.LoadData(ref i, saveData, ref govermentSalary);

            SaveAndRestore.LoadData(ref i, saveData, ref updateMoneyCount);
            SaveAndRestore.LoadData(ref i, saveData, ref currentTime);
            SaveAndRestore.LoadData(ref i, saveData, ref prevTime);
            SaveAndRestore.LoadData(ref i, saveData, ref citizenCount);
            SaveAndRestore.LoadData(ref i, saveData, ref familyCount);
            SaveAndRestore.LoadData(ref i, saveData, ref citizenSalaryPerFamily);
            SaveAndRestore.LoadData(ref i, saveData, ref citizenSalaryTotal);
            SaveAndRestore.LoadData(ref i, saveData, ref citizenSalaryTaxTotal);

            SaveAndRestore.LoadData(ref i, saveData, ref outsideTouristMoney);
            SaveAndRestore.LoadData(ref i, saveData, ref outsideGovermentMoney);
            SaveAndRestore.LoadData(ref i, saveData, ref randomEventTime);
            SaveAndRestore.LoadData(ref i, saveData, ref noImport);
            SaveAndRestore.LoadData(ref i, saveData, ref noExport);
            SaveAndRestore.LoadData(ref i, saveData, ref noTourist);
            SaveAndRestore.LoadData(ref i, saveData, ref noDummyTraffic);

            //avoid save data error:
            if (citizenCount != 0)
            {
                govermentSalary = (int)(citizenSalaryTotal / citizenCount);
            }
            else
            {
                govermentSalary = 10;
            }

            if (govermentSalary > 100)
            {
                govermentSalary = 100;
            }

            if (i != saveData.Length)
            {
                DebugLog.LogToFileOnly($"MainDataStore Load Error: saveData.Length = {saveData.Length} actually = {i}");
            }
        }
Beispiel #11
0
 private bool Initialize(string file)
 {
     try
     {
     #if DEBUG
         _debuglog = new DebugLog("SQLite.log");
     #endif
         Connection = new SQLiteConnection(string.Format("Data Source={0}", file));
         Connection.Open();
         return true;
     }
     catch(SQLiteException s)
     {
         Log.Error("SQLite", s.Message);
         return false;
     }
 }
Beispiel #12
0
    IEnumerator LoadPrefabModel(string path, string name, Action count_load = null)
    {
        load_error_flag = false;
        //防止卡死
        yield return(new WaitForEndOfFrame());

        DebugLog.DebugLogInfo("00FF00", "assetbundle loading ---" + path + name);

        string temp_path = PublicClass.tempPath + name + "temp.dat";
        AssetBundleCreateRequest assetBundleCreateRequest = null;

        try
        {
            Vesal_DirFiles.GetAbfile2(path, temp_path);
            assetBundleCreateRequest = AssetBundle.LoadFromFileAsync(temp_path);

            //assetBundleCreateRequest = AssetBundle.LoadFromMemoryAsync(Vesal_DirFiles.GetAbfile(path, temp_path));
        }
        catch (Exception ex)
        {
            load_error_flag = true;
            vesal_log.vesal_write_log("assetbundle load error in :" + name);
            vesal_log.vesal_write_log("error message:" + ex.Message);
        }


        if (assetBundleCreateRequest != null && load_error_flag == false)
        {
            yield return(assetBundleCreateRequest);

            GameObject         CurrentObj = null;
            GameObject         realObj    = null;
            AssetBundleRequest abr        = null;
            try
            {
                abr = assetBundleCreateRequest.assetBundle.LoadAssetAsync(name, typeof(GameObject));
            }
            catch (Exception ex)
            {
                load_error_flag = true;
                vesal_log.vesal_write_log("assetbundle load error in :" + name);
                vesal_log.vesal_write_log("error message:" + ex.Message);
            }
            yield return(abr);

            if (abr != null && abr.asset != null)
            {
                CurrentObj = (GameObject)abr.asset;
                realObj    = Instantiate(CurrentObj);
            }
            else
            {
                load_error_flag = true;
                vesal_log.vesal_write_log("assetbundle load error in :" + name);
            }
            if (CurrentObj != null && realObj != null & load_error_flag == false)
            {
                realObj.name = realObj.name.Replace("(Clone)", "");

                ReadModel(realObj);

                Transform Transform_parent = PublicClass.Transform_parent;
                realObj.transform.SetParent(Transform_parent);

                assetBundleCreateRequest.assetBundle.Unload(false);
                //Transform_parent.gameObject.SetActive(false);

                load_list[load_count].source   = CurrentObj;
                load_list[load_count].instance = realObj;
                if (File.Exists(temp_path))
                {
                    try
                    {
                        Vesal_DirFiles.DelFile(temp_path);
                    }
                    catch { }
                }
            }
        }
        if (count_load != null)
        {
            count_load();
        }
    }
 public override void Before(System.Reflection.MethodInfo methodUnderTest)
 {
     DebugLog.ClearListeners();
 }
Beispiel #14
0
 public ILog GetLog(string name)
 {
     var log = new DebugLog();
     return log;
 }
Beispiel #15
0
 public void Initialize()
 {
     #if DEBUG
     _debuglog = new DebugLog("IrcRead_" + _servername + ".log");
     #endif
     InitHandler();
     InitializeCommandHandler();
     InitializeCommandMgr();
     Task.Factory.StartNew(() => sMyChannelInfo.ChannelList());
     sIgnoreNickName.LoadConfig();
     sIgnoreNickName.LoadSql();
     sIgnoreChannel.LoadConfig();
     sIgnoreChannel.LoadSql();
     sIgnoreAddon.LoadConfig();
     sIgnoreAddon.LoadSql();
     sIgnoreCommand.LoadSql();
     sIgnoreIrcCommand.LoadSql();
 }
 void Start()
 {
     debugLog = GameObject.FindGameObjectWithTag ( "DebugLog" ).GetComponent<DebugLog>();
     preferencesManager = GameObject.FindGameObjectWithTag ( "Manager" ).GetComponent<PreferencesManager>();
     externalInformation = GameObject.FindGameObjectWithTag ( "ExternalInformation" ).GetComponent<ExternalInformation> ();
     deckManager = GameObject.FindGameObjectWithTag ( "Manager" ).GetComponent<DeckManager>();
     userInterface = GameObject.FindGameObjectWithTag ( "UserInterface" ).GetComponent<UserInterface>();
 }
 public WatchThreadSerializer()
 {
     this.debugLogText = new DebugLog();
 }
Beispiel #18
0
        public MOS6510(C64 c64, byte[] ram, byte[] basic_rom, byte[] kernel_rom, byte[] char_rom, byte[] color_ram)
        {
            TheC64 = c64;
            this.ram = ram;
            this.basic_rom = basic_rom;
            this.kernel_rom = kernel_rom;
            this.char_rom = char_rom;
            this.color_ram = color_ram;

            a = x = y = 0;
            sp = 0xff;

            n_flag = z_flag = 0;
            v_flag = c_flag = d_flag = b_flag = i_flag = false;

            dfff_byte = 0x55;
            BALow = false;
            first_irq_cycle = first_nmi_cycle = 0;
            #if DEBUG_INSTRUCTIONS
            debugLogger = new DebugLog(this, false);
            #endif
        }
Beispiel #19
0
 void Awake()
 {
     instance = (DebugLog)this;
     Application.logMessageReceived += OnLog;
 }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try {
            System.Windows.Data.Binding binding = new System.Windows.Data.Binding("TheLog")
            {
              Source = this.debugLogText
            };
            this.txtDebug.SetBinding(System.Windows.Controls.TextBox.TextProperty, binding);
            this.theWatchManager = new WatchThreadManager();
            this.theDownloadManager = new DownloadManager();
            this.theDownloadManager.RegisterDebugLog(ref this.debugLogText);
            this.theDownloadManager.RegisterDownloadTaskViewCollection(this.DownloadTaskViewCollection);
            this.theDownloadManager.RefreshDownloadListViewCallback = new RefreshDownloadListDelegate(this.RefreshDownloadsListView);
            this.theWatchManager.RegisterDebugLog(this.debugLogText);
            this.theWatchManager.RegisterDownloadManager(this.theDownloadManager);
            this.theWatchManager.RegisterWatchThreadViewCollection(this.WatchThreadViewCollection);
            this.theWatchManager.RefreshListViewCallback = new RefreshWatchListDelegate(this.RefreshWatchThreadsListView);
            this.wts = new WatchThreadSerializer(this.theWatchManager, this.theDownloadManager, this.WatchThreadViewCollection);
            this.wts.RefreshListViewCallback = this.theWatchManager.RefreshListViewCallback;
            this.wts.debugLogText = this.debugLogText;

            lvWatchList.ItemsSource = WatchThreadViewCollection;
            lvDownloadManager.ItemsSource = DownloadTaskViewCollection;

            if (Properties.Settings.Default.AutoLoadWatchList) {
              try {
            this.theWatchManager = this.wts.Deserialize();
              } catch {
              }
            }
            if (Properties.Settings.Default.MinimizeToTray) {
              this.CreateNotifyIcon();
            }
              } catch (Exception exception) {
            System.Windows.MessageBox.Show("Error Creating Watch Manager\r\n" + exception.Message);
            System.Windows.Application.Current.Shutdown();
              }
              try {
            this.txtURL.Focus();
              } catch {
              }
        }
Beispiel #21
0
 public MyLogger(Type type)
 {
     _debug = new DebugLog(type);
 }
Beispiel #22
0
 public void OnToggleDebugLog()
 {
     DebugLog.Toggle();
 }
Beispiel #23
0
        private static async Task InitGlobalDatabaseAndServices()
        {
            string globalDatabaseFile = ASF.GetFilePath(ASF.EFileType.Database);

            if (string.IsNullOrEmpty(globalDatabaseFile))
            {
                ASF.ArchiLogger.LogNullError(nameof(globalDatabaseFile));

                return;
            }

            if (!File.Exists(globalDatabaseFile))
            {
                ASF.ArchiLogger.LogGenericInfo(Strings.Welcome);
                await Task.Delay(10 * 1000).ConfigureAwait(false);

                ASF.ArchiLogger.LogGenericWarning(Strings.WarningPrivacyPolicy);
                await Task.Delay(5 * 1000).ConfigureAwait(false);
            }

            GlobalDatabase globalDatabase = await GlobalDatabase.CreateOrLoad(globalDatabaseFile).ConfigureAwait(false);

            if (globalDatabase == null)
            {
                ASF.ArchiLogger.LogGenericError(string.Format(Strings.ErrorDatabaseInvalid, globalDatabaseFile));
                await Task.Delay(5 * 1000).ConfigureAwait(false);
                await Exit(1).ConfigureAwait(false);

                return;
            }

            ASF.InitGlobalDatabase(globalDatabase);

            // If debugging is on, we prepare debug directory prior to running
            if (Debugging.IsUserDebugging)
            {
                if (Debugging.IsDebugConfigured)
                {
                    ASF.ArchiLogger.LogGenericDebug(globalDatabaseFile + ": " + JsonConvert.SerializeObject(ASF.GlobalDatabase, Formatting.Indented));
                }

                Logging.EnableTraceLogging();

                DebugLog.AddListener(new Debugging.DebugListener());
                DebugLog.Enabled = true;

                if (Directory.Exists(SharedInfo.DebugDirectory))
                {
                    try {
                        Directory.Delete(SharedInfo.DebugDirectory, true);
                        await Task.Delay(1000).ConfigureAwait(false);                         // Dirty workaround giving Windows some time to sync
                    } catch (Exception e) {
                        ASF.ArchiLogger.LogGenericException(e);
                    }
                }

                try {
                    Directory.CreateDirectory(SharedInfo.DebugDirectory);
                } catch (Exception e) {
                    ASF.ArchiLogger.LogGenericException(e);
                }
            }

            WebBrowser.Init();
        }
Beispiel #24
0
 public void Deinitialize()
 {
     MeshRenderer.Shutdown();
     PhysicsDebugRenderer.Shutdown();
     DebugLog.Log($"Shutdown", "Viewport");
 }
 public void onSetCustomRoomDataDone(LiveRoomInfoEvent eventObj)
 {
     DebugLog.Log("onSetCustomRoomDataDone : " + eventObj.getResult());
 }
Beispiel #26
0
    void Start()
    {
        switch (SceneManager.GetActiveScene().name)
        {
        case "WeiKePlayer":
        case "totalScence":
        case "PPTPlayer":
            PublicClass.appstate = App_State.Running;
            UnityMessageManager.Instance.SendMessageToRN(new UnityMessage()
            {
                name     = "title",
                callBack = (data) => { DebugLog.DebugLogInfo("message : " + data); }
            });
            break;

        case "MotorAnatomy":
            obj  = new GameObject("SceneModels");
            temp = obj.AddComponent <SceneModels>();
            DebugLog.DebugLogInfo("加载模型管理器------------------");
            InitData(PublicClass.app.app_id);
            break;

        default:
            // model_ui.SetActive(false);
            // sign_ui.SetActive(false);
            if (ssp_ui != null)
            {
                RaycastInCanvas = ssp_ui.GetComponent <GraphicRaycaster>();
                ssp_ui.SetActive(false);
            }
            obj  = new GameObject("SceneModels");
            temp = obj.AddComponent <SceneModels>();
            DebugLog.DebugLogInfo("加载模型管理器------------------");
            InitData(PublicClass.app.app_id);


            Debug.Log("JumpState:" + PublicClass.app.JumpState);

            //if (PublicClass.app.JumpState == "return")
            //    StateData.Instance.isReturn = true;

            //PublicClass.app.signModelName = "CFD008,CFD007";
            //     PublicClass.app.tissueModelName = "股直肌";
            if (!string.IsNullOrEmpty(PublicClass.app.signModelName))
            {
                if (PublicClass.app.app_type == "model" || PublicClass.app.app_type == "medical" || PublicClass.app.app_type == "acu")
                {
                    isShowSignModel = true;
                }
                else if (SceneManager.GetActiveScene().name == "UI_sign_all")
                {
                    isShowNewSignModel = true;
                }
                else if (SceneManager.GetActiveScene().name == "CFD")
                {
                    isSelectCFD = true;
                }
            }

            if (!string.IsNullOrEmpty(PublicClass.app.tissueModelName) && (PublicClass.app.app_type == "model" || PublicClass.app.app_type == "medical" || PublicClass.app.app_type == "acu"))
            {
                isShowTissueModel = true;
            }
            break;
        }
        if (AsyncLoadModel.instance == null)
        {
            AsyncLoadModel.instance = new AsyncLoadModel();
        }
    }
 //ChatRequestListener
 public void onSendChatDone(byte result)
 {
     DebugLog.Log("onSendChatDone result : " + result);
 }
Beispiel #28
0
        public static bool HighSpeedImpactSensor_FixedUpdate(
            HighSpeedImpactSensor __instance
            )
        {
            if (__instance._isPlayer && (PlayerState.IsAttached() || PlayerState.IsInsideShuttle() || PlayerState.UsingNomaiRemoteCamera()))
            {
                return(false);
            }

            if (__instance._dieNextUpdate && !__instance._dead)
            {
                __instance._dead          = true;
                __instance._dieNextUpdate = false;
                if (__instance.gameObject.CompareTag("Player"))
                {
                    Locator.GetDeathManager().SetImpactDeathSpeed(__instance._impactSpeed);
                    Locator.GetDeathManager().KillPlayer(DeathType.Impact);
                }
                else if (__instance.gameObject.CompareTag("Ship"))
                {
                    __instance.GetComponent <ShipDamageController>().Explode();
                }
            }

            if (__instance._isPlayer && PlayerState.IsInsideShip())
            {
                var shipCenter       = Locator.GetShipTransform().position + (Locator.GetShipTransform().up * 2f);
                var distanceFromShip = Vector3.Distance(__instance._body.GetPosition(), shipCenter);
                if (distanceFromShip > 8f)
                {
                    __instance._body.SetPosition(shipCenter);
                }

                if (!__instance._dead)
                {
                    var a = __instance._body.GetVelocity() - Locator.GetShipBody().GetPointVelocity(__instance._body.GetPosition());
                    if (a.sqrMagnitude > __instance._sqrCheckSpeedThreshold)
                    {
                        __instance._impactSpeed = a.magnitude;
                        __instance._body.AddVelocityChange(-a);
                    }
                }

                return(false);
            }

            var passiveReferenceFrame = __instance._sectorDetector.GetPassiveReferenceFrame();

            if (!__instance._dead && passiveReferenceFrame != null)
            {
                var relativeVelocity = __instance._body.GetVelocity() - passiveReferenceFrame.GetOWRigidBody().GetPointVelocity(__instance._body.GetPosition());
                if (relativeVelocity.sqrMagnitude > __instance._sqrCheckSpeedThreshold)
                {
                    var hitCount = Physics.RaycastNonAlloc(__instance.transform.TransformPoint(__instance._localOffset), relativeVelocity, __instance._raycastHits, (relativeVelocity.magnitude * Time.deltaTime) + __instance._radius, OWLayerMask.physicalMask, QueryTriggerInteraction.Ignore);
                    for (var i = 0; i < hitCount; i++)
                    {
                        if (__instance._raycastHits[i].rigidbody.mass > 10f && !__instance._raycastHits[i].rigidbody.Equals(__instance._body.GetRigidbody()))
                        {
                            var owRigidbody = __instance._raycastHits[i].rigidbody.GetComponent <OWRigidbody>();
                            if (owRigidbody == null)
                            {
                                DebugLog.ToConsole("Rigidbody does not have attached OWRigidbody!!!", OWML.Common.MessageType.Error);
                                Debug.Break();
                            }
                            else
                            {
                                relativeVelocity = __instance._body.GetVelocity() - owRigidbody.GetPointVelocity(__instance._body.GetPosition());
                                var a2 = Vector3.Project(relativeVelocity, __instance._raycastHits[i].normal);
                                if (a2.sqrMagnitude > __instance._sqrCheckSpeedThreshold)
                                {
                                    __instance._body.AddVelocityChange(-a2);
                                    __instance._impactSpeed = a2.magnitude;
                                    if (!PlayerState.IsInsideTheEye())
                                    {
                                        __instance._dieNextUpdate = true;
                                    }

                                    break;
                                }
                            }
                        }
                    }
                }
            }

            return(false);
        }
 public void onSendPrivateChatDone(byte result)
 {
     DebugLog.Log("onSendPrivateChatDone : " + result);
 }
Beispiel #30
0
        public bool CanCreateTempTables = false;                            // true if the associated account can create temp tables

        /// <summary>
        /// Load metadata describing connections and associated schemas
        /// </summary>
        /// <param name="dsFileName"></param>
        /// <returns></returns>

        public static int LoadMetadata()
        {
            XmlAttributeCollection atts;

            // Get some inifile parameters first

            if (ServicesIniFile.IniFile == null)
            {
                throw new Exception("ServicesIniFile.IniFile is null");
            }

            SessionConnection.Pooling            = ServicesIniFile.ReadBool("Pooling", true);
            SessionConnection.MinPoolSize        = ServicesIniFile.ReadInt("MinPoolSize", 1);
            SessionConnection.IncrPoolSize       = ServicesIniFile.ReadInt("IncrPoolSize", 5);
            SessionConnection.MaxPoolSize        = ServicesIniFile.ReadInt("MaxPoolSize", 100);
            SessionConnection.DecrPoolSize       = ServicesIniFile.ReadInt("DecrPoolSize", 1);
            SessionConnection.ConnectionLifetime = ServicesIniFile.ReadInt("ConnectionLifetime", 0);

            string tok     = ServicesIniFile.Read("KeyListPredType", "Parameterized");
            int    enumInt = EnumUtil.Parse(typeof(KeyListPredTypeEnum), tok);

            if (enumInt >= 0)
            {
                DbCommandMx.DefaultKeyListPredType = (KeyListPredTypeEnum)enumInt;
            }

            DbCommandMx.DbFetchRowCount = ServicesIniFile.ReadInt("DbFetchRowCount", DbCommandMx.DbFetchRowCount);
            DbCommandMx.DbFetchSizeMax  = ServicesIniFile.ReadInt("DbFetchSizeMax", DbCommandMx.DbFetchSizeMax);

            DataSources = new Dictionary <string, DataSourceMx>(StringComparer.OrdinalIgnoreCase);
            Schemas     = new Dictionary <string, DbSchemaMx>(StringComparer.OrdinalIgnoreCase);

            string dsFileName = ServicesDirs.MetaDataDir + @"\" + "DataSources.xml";

            StreamReader sr  = new StreamReader(dsFileName);
            XmlDocument  doc = new XmlDocument();

            doc.Load(sr);
            XmlNode node = doc.FirstChild;

            while (node != null)
            {
                if (node.NodeType == XmlNodeType.Element)
                {
                    break;
                }
                node = node.NextSibling;
                if (node == null)
                {
                    throw new Exception("No initial element found");
                }
            }

            if (!Lex.Eq(node.Name, "DataSources"))
            {
                throw new Exception("Expected DataSources node: " + node.Name);
            }

            atts = node.Attributes;             // datasources attributes
            for (int i = 0; i < atts.Count; i++)
            {
                XmlNode att = atts.Item(i);

                if (Lex.Eq(att.Name, "DblinkConnName"))
                {
                }                                                           // obsolete key word

                else
                {
                    throw new Exception
                              ("Unexpected DataSources attribute: " + att.Name);
                }
            }

            node = node.FirstChild;
            while (node != null)
            {
                if (node.NodeType != XmlNodeType.Element)
                {
                    ;                                                       // ignore non-elements
                }
                else if (Lex.Eq(node.Name, "DataSource") ||                 // connection element
                         Lex.Eq(node.Name, "Connection"))
                {
                    DataSourceMx cd = new DataSourceMx();

                    atts = node.Attributes;
                    for (int i = 0; i < atts.Count; i++)
                    {
                        XmlNode att = atts.Item(i);

                        if (Lex.Eq(att.Name, "DatabaseType") || Lex.Eq(att.Name, "DbType"))
                        {
                            if (!Enum.TryParse <DatabaseType>(att.Value, true, out cd.DbType))
                            {
                                throw new Exception("Invalid Database type: " + att.Value);
                            }
                        }

                        else if (Lex.Eq(att.Name, "Name"))
                        {
                            cd.DataSourceName = att.Value.ToUpper().Trim();
                        }

                        else if (Lex.Eq(att.Name, "DatabaseName") || Lex.Eq(att.Name, "OracleName"))
                        {
                            cd.DatabaseLocator = att.Value.ToUpper().Trim();
                        }

                        else if (Lex.Eq(att.Name, "ConnectionString"))                         // keep case if connection string
                        {
                            cd.DatabaseLocator = att.Value.Trim();
                        }

                        else if (Lex.Eq(att.Name, "UserName"))
                        {
                            cd.UserName = att.Value.Trim();                             // keep case as is (Oracle 11g)
                        }
                        else if (Lex.Eq(att.Name, "Password"))
                        {
                            cd.Password = att.Value.Trim();                           // keep case as is (Oracle 11g)
                        }
                        else if (Lex.Eq(att.Name, "MdlInit"))                         // mdl initialization
                        {
                            cd.InitCommand = "select cdcaux.ctenvinit('" + att.Value.Trim() + "') from dual";
                        }

                        else if (Lex.Eq(att.Name, "InitCommand"))
                        {
                            cd.InitCommand = att.Value.Trim();
                        }

                        else if (Lex.Eq(att.Name, "KeyDataSource"))
                        {
                            bool.TryParse(att.Value.Trim(), out cd.IsKeyDataSource);
                        }

                        else if (Lex.Eq(att.Name, "CanCreateTempTables"))
                        {
                            bool.TryParse(att.Value.Trim(), out cd.CanCreateTempTables);
                        }

                        else if (Lex.Eq(att.Name, "AlwaysUseDbLink"))
                        {
                        }                                                                         // obsolete

                        else
                        {
                            throw new Exception
                                      ("Unexpected Connection attribute: " + att.Name);
                        }
                    }

                    if (cd.DataSourceName == "")
                    {
                        DebugLog.Message("Connection is missing name: " + cd.DatabaseLocator);
                    }
                    else if (DataSourceMx.DataSources.ContainsKey(cd.DataSourceName))
                    {
                        DebugLog.Message("Data source defined twice: " + cd.DataSourceName);
                    }
                    else
                    {
                        DataSourceMx.DataSources.Add(cd.DataSourceName, cd);
                    }
                }

                else if (Lex.Eq(node.Name, "SchemaToDataSource") ||                 // schema map element
                         Lex.Eq(node.Name, "SchemaToConnection"))
                {
                    DbSchemaMx schema = new DbSchemaMx();
                    atts = node.Attributes;
                    for (int i = 0; i < atts.Count; i++)
                    {
                        XmlNode att = atts.Item(i);

                        if (Lex.Eq(att.Name, "Schema"))
                        {
                            schema.Name = att.Value.ToUpper().Trim();
                        }

                        else if (Lex.Eq(att.Name, "AliasFor"))
                        {
                            schema.AliasFor = att.Value.ToUpper().Trim();
                        }

                        else if (Lex.Eq(att.Name, "Connection"))
                        {
                            schema.DataSourceName = att.Value.ToUpper().Trim();
                        }

                        else if (Lex.Eq(att.Name, "Label") || Lex.Eq(att.Name, "L"))
                        {
                            schema.Label = att.Value.Trim();
                        }

                        else
                        {
                            throw new Exception
                                      ("Unexpected Connection attribute: " + att.Name);
                        }
                    }

                    if (schema.Name == "")
                    {
                        throw new Exception("Missing schema name");
                    }
                    if (schema.DataSourceName == "")
                    {
                        throw new Exception("Missing data source/connection name");
                    }
                    Schemas[schema.Name] = schema;
                }

                else
                {
                    throw new Exception("Expected Connection or SchemaToDataSource element but saw " +
                                        node.Name);
                }

                node = node.NextSibling;
            }
            sr.Close();

            return(DataSources.Count);
        }
    //NotifyListener
    public void onRoomCreated(RoomData eventObj)
    {
        DebugLog.Log("onRoomCreated");

//		FireRoomCreationSuccess (eventObj);
    }
Beispiel #32
0
        public static int Main(string[] args)
        {
            Thread.CurrentThread.Name = "Main";

            Instance = new Titan
            {
                Options = new Options()
            };

            Logger = LogCreator.Create();

            #if __UNIX__
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                Logger.Fatal("Titan has been compiled to run under Linux but is running on " +
                             "Windows. Please use the correct Titan version for your operating system. Exiting.");

                Console.Write("Press any key to exit Titan...");
                Console.Read();
                return((int)ExitCodes.WrongOS);
            }
            #else
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                Logger.Fatal("Titan has been compiled to run under Windows but is running on " +
                             "Linux. Please use the correct Titan version for your operating system. Exiting.");
                return((int)ExitCodes.WrongOS);
            }
            #endif

            if (Environment.CurrentDirectory != Instance.Directory.ToString())
            {
                Logger.Debug("Run from {currentDir}, switching to work directory in {workingDir}.",
                             Environment.CurrentDirectory, Instance.Directory.ToString());
            }

            // Windows users run the program by double clicking Titan.exe (and then it opens a console window)
            // and in case of exception occurence, this window gets immediatly closed which is bad because
            // they're unable to attach the stacktrace then. Prevent it by waiting until the user presses a key.
            #if !__UNIX__
            AppDomain.CurrentDomain.UnhandledException += (sender, eventArgs) =>
            {
                if (eventArgs.IsTerminating)
                {
                    Logger.Error((Exception)eventArgs.ExceptionObject, "An error occured.");

                    // Don't use logging object here incase the exception was thrown by a logger
                    Console.Write("Press any key to exit Titan...");
                    Console.Read();
                }
            };
            #endif

            // The bridge between Common Logging and Serilog uses the global Logger (Log.Logger).
            // As Quartz.NET is the only dependency using Common Logging (and because of our bridge the global logger)
            // we're creating the global logger as Quartz logger (which hides annoying debug messages).
            Log.Logger = LogCreator.CreateQuartzLogger();

            // Quartz.NET
            Instance.Scheduler = StdSchedulerFactory.GetDefaultScheduler().Result;
            Instance.Scheduler.Start();

            Instance.JsonSerializer = new JsonSerializer();

            Instance.HttpClient = new HttpClient();
            Instance.HttpClient.DefaultRequestHeaders.Add(
                "User-Agent", "Titan Report & Commend Bot (https://github.com/Marc3842h/Titan)"
                );

            var parser = new Parser(config =>
            {
                config.IgnoreUnknownArguments = true;
                config.EnableDashDash         = true;
                config.HelpWriter             = TextWriter.Null;
            });

            // Default
            parser.ParseArguments <Options>(args)
            .WithParsed(options =>
            {
                Instance.Options = options;
            });

            // Verbs
            parser.ParseArguments <ReportOptions, CommendOptions>(args)
            .WithParsed <ReportOptions>(options =>
            {
                Instance.EnableUI     = false;
                Instance.ParsedObject = options;
            })
            .WithParsed <CommendOptions>(options =>
            {
                Instance.EnableUI     = false;
                Instance.ParsedObject = options;
            })
            .WithNotParsed(error =>
            {
                if (Instance.ParsedObject == null)
                {
                    Instance.EnableUI = true;
                    Logger.Information("No valid verb has been provided while parsing. Opening UI...");
                }
            });

            new Config.Config().Load();

            // Reinitialize logger with new parsed debug option
            Logger = LogCreator.Create();

            #if __UNIX__
            Instance.IsAdmin = Linux.getuid() == 0;     // UID of root is always 0
            #else
            Instance.IsAdmin = new WindowsPrincipal(WindowsIdentity.GetCurrent())
                               .IsInRole(WindowsBuiltInRole.Administrator);
            #endif

            if (Instance.IsAdmin)
            {
                if (!Instance.Options.AllowAdmin)
                {
                    Logger.Error("Titan is running as administrator or root.");
                    Logger.Error("This is not supported. Titan will refuse to start until you start it as normal " +
                                 "user. If you are unable to do this for any reason, start Titan with the --admin " +
                                 "option to force the usage of administrator rights.");

                    #if !__UNIX__
                    Console.Write("Press any key to exit Titan...");
                    Console.Read();
                    #endif

                    Instance.Scheduler.Shutdown();
                    return((int)ExitCodes.RunningAsAdmin);
                }

                Logger.Warning("Titan has been started as Administrator but will continue to run as the " +
                               "--admin option has been passed. Please note that Steam also doesn't allow to be " +
                               "run from root and that it may be insecure.");
            }

            if (Instance.Options.Debug)
            {
                Instance.DebugDirectory = new DirectoryInfo(Path.Combine(Instance.Directory.ToString(), "debug"));

                if (!Instance.DebugDirectory.Exists)
                {
                    Instance.DebugDirectory.Create();
                }

                if (Instance.Options.SteamKitDebug)
                {
                    DebugLog.AddListener(new TitanListener());
                    DebugLog.Enabled = true;
                }
            }

            if (Instance.Options.Secure)
            {
                Logger.Debug("Secure mode has been enabled. Titan will output no sensitive data.");
            }

            if (Instance.Options.DisableBlacklist)
            {
                Logger.Debug("Blacklist has been disabled by passing the --noblacklist option.");
            }

            Instance.ProfileSaver = new ProfileSaver();

            if (Instance.EnableUI)
            {
                try
                {
                    Instance.UIManager = new UIManager();
                }
                catch (InvalidOperationException ex)
                {
                    if (!string.IsNullOrEmpty(ex.Message) && ex.Message.ToLower().Contains("could not detect platform"))
                    {
                        Logger.Error("---------------------------------------");
                        Logger.Error("A fatal error has been detected!");
                        Logger.Error("Eto.Forms could not detect your current operating system.");

                        #if __UNIX__
                        Logger.Error("Please install {0}, {1}, {2} and {3} before submitting a bug report.",
                                     "Mono (\u22655.4)",
                                     "Gtk 3",
                                     "libNotify",
                                     "libAppindicator3");
                        #else
                        Logger.Error("Please install {0} before submitting a bug report.",
                                     ".NET Framework (\u22654.6.1)");
                        #endif

                        Logger.Error("Contact {Marc} on Discord if the issue still persists after installing " +
                                     "the dependencies listed above.", "Marc3842h#7312");
                        Logger.Error("---------------------------------------");
                        Logger.Debug(ex, "Include the error below if you\'re contacting Marc on Discord.");

                        #if !__UNIX__
                        Console.Write("Press any key to exit Titan...");
                        Console.Read();
                        #endif

                        Instance.Scheduler.Shutdown();
                        return((int)ExitCodes.UIInitFailed);
                    }

                    Logger.Error(ex, "A error occured while loading UI.");
                    throw;
                }
            }


            Instance.AccountManager = new AccountManager(new FileInfo(
                                                             Path.Combine(Instance.Directory.ToString(), Instance.Options.AccountsFile))
                                                         );

            Instance.ThreadManager = new ThreadManager();

            Instance.WebHandle = new SWAHandle();
            Instance.WebHandle.Preload();

            Instance.VictimTracker = new VictimTracker();

            AppDomain.CurrentDomain.ProcessExit += OnShutdown;

            Instance.AccountManager.ParseAccountFile();

            Task.Run(() => TimeAligner.AlignTime());

            if (Instance.EnableUI)
            {
                Instance.UIManager.InitializeForms();
            }

            // Load after Forms were initialized
            Instance.WebHandle.Load();

            // VictimTracker depends on the web api key being loaded correctly.
            Instance.VictimTracker.InitTrigger();

            var attribute = Assembly.GetEntryAssembly().GetCustomAttribute <AssemblyInformationalVersionAttribute>();
            var version   = attribute != null ? attribute.InformationalVersion :
                            Assembly.GetEntryAssembly().GetName().Version.Major + "." +
                            Assembly.GetEntryAssembly().GetName().Version.Minor + "." +
                            Assembly.GetEntryAssembly().GetName().Version.Build;

            Logger.Information("Hello and welcome to Titan {version}.", "v" + version);

            if (Instance.EnableUI && Instance.ParsedObject == null || Instance.DummyMode)
            {
                Instance.UIManager.ShowForm(UIType.General);
            }
            else
            {
                if (Instance.ParsedObject.GetType() == typeof(ReportOptions))
                {
                    var opt = (ReportOptions)Instance.ParsedObject;

                    var steamID = SteamUtil.Parse(opt.Target);
                    if (steamID.IsBlacklisted(opt.Game.ToAppID()))
                    {
                        Instance.UIManager.SendNotification(
                            "Restriction applied",
                            "The target you are trying to report is blacklisted from botting " +
                            "in Titan.",
                            () => Process.Start("https://github.com/Marc3842h/Titan/wiki/Blacklist")
                            );
                    }
                    else
                    {
                        Instance.AccountManager.StartReporting(Instance.AccountManager.Index,
                                                               new ReportInfo
                        {
                            SteamID = SteamUtil.Parse(opt.Target),
                            MatchID = SharecodeUtil.Parse(opt.Match),
                            AppID   = opt.Game.ToAppID(),

                            AbusiveText  = opt.AbusiveTextChat,
                            AbusiveVoice = opt.AbusiveVoiceChat,
                            Griefing     = opt.Griefing,
                            AimHacking   = opt.AimHacking,
                            WallHacking  = opt.WallHacking,
                            OtherHacking = opt.OtherHacking
                        });
                    }
                }
                else if (Instance.ParsedObject.GetType() == typeof(CommendOptions))
                {
                    var opt = (CommendOptions)Instance.ParsedObject;

                    Instance.AccountManager.StartCommending(Instance.AccountManager.Index,
                                                            new CommendInfo
                    {
                        SteamID = SteamUtil.Parse(opt.Target),
                        AppID   = TitanAccount.CSGO_APPID,

                        Friendly = opt.Friendly,
                        Leader   = opt.Leader,
                        Teacher  = opt.Teacher
                    });
                }
                else
                {
                    Instance.UIManager.ShowForm(UIType.General);
                }
            }

            Instance.Scheduler.ScheduleJob(Instance.VictimTracker.Job, Instance.VictimTracker.Trigger);

            Logger.Debug("Startup done. Active threads: {threads}", Process.GetCurrentProcess().Threads.Count + 1);

            Instance.StartMainLoop();

            // The Shutdown handler gets only called after the last thread finished.
            // Quartz runs a Watchdog until Scheduler#Shutdown is called, so we're calling it
            // before Titan will be calling the Shutdown Hook.
            Logger.Debug("Shutting down Quartz.NET Scheduler.");

            Instance.Scheduler.Shutdown();

            return((int)ExitCodes.Ok);
        }
 public void onRoomDestroyed(RoomData eventObj)
 {
     DebugLog.Log("onRoomDestroyed");
 }
 public bool SetIgnore(string path, IEnumerable <string> assets)
 {
     DebugLog.LogWarning("P4Commands.SetIgnore not implemented");
     return(false);
 }
 public void onUserJoinedLobby(LobbyData eventObj, string username)
 {
     DebugLog.Log("onUserJoinedLobby : " + username);
 }
 public string GetRevision()
 {
     DebugLog.LogWarning("P4Commands.GetRevisionNumber not implemented");
     return(null);
 }
 public void onUserChangeRoomProperty(RoomData roomData, string sender, Dictionary <string, object> properties, Dictionary <string, string> lockedPropertiesTable)
 {
     DebugLog.Log("onUserChangeRoomProperty : " + sender);
 }
        public void SetVisible(bool visible)
        {
            DebugLog.Finer(this, $"{_prefix} Updating visibility of {gameObject.name} to {visible}");

            _panel.SetActive(visible);
        }
 public void onPrivateChatReceived(string sender, string message)
 {
     DebugLog.Log("onPrivateChatReceived : " + sender);
 }
 public override void After(System.Reflection.MethodInfo methodUnderTest)
 {
     DebugLog.Enabled = false;
     DebugLog.ClearListeners();
 }
    private void Log(string msg)
    {
        debug = msg + "\n" + debug;
        DebugLog.Log(msg);
//		DebugLog.Log ("-> " + msg);
    }
Beispiel #42
0
 public ILog GetLog(Type type)
 {
     var log = new DebugLog();
     return log;
 }
        public BackupJournalObject LoadBackupJournalObject(string pathToJournal, DebugLog debugLog)
        {
            BackupJournalObject backupJournalObject = new BackupJournalObject();

            try
            {
                r = new StreamReader(pathToJournal);
                debugLog.WriteToLog("Loading relative paths from backup journal...", 7);
                backupJournalObject.RelativePaths = new List <string>(1);
                while (r.Peek() != '!')
                {
                    backupJournalObject.RelativePaths.Add(r.ReadLine());
                }
                r.ReadLine();
                debugLog.WriteToLog("Loading list of files from backup journal...", 7);
                List <FileInfoObject> tmpListFiles = new List <FileInfoObject>(100);
                string[] tmp;
                while (r.Peek() != '?')
                {
                    tmp = r.ReadLine().Split('|');
                    if (tmp.Length == 7)
                    {
                        tmpListFiles.Add(new FileInfoObject()
                        {
                            FullPath = tmp[0], Length = Convert.ToInt64(tmp[1]), CreationTimeUtc = DateTime.FromBinary(Convert.ToInt64(tmp[2])), LastWriteTimeUtc = DateTime.FromBinary(Convert.ToInt64(tmp[3])), Attributes = tmp[4], MD5 = tmp[5], HashRow = Convert.ToInt32(tmp[6])
                        });
                    }
                    else
                    {
                        string tmpRow = "";
                        for (int i = 0; i < tmp.Length; i++)
                        {
                            tmpRow += ('|' + tmp[i]);
                        }
                        debugLog.WriteToLog("Error when trying to load file row from backup journal, the row is: " + tmpRow, 3);
                    }
                }
                r.ReadLine();
                backupJournalObject.BackupJournalFiles = tmpListFiles;

                debugLog.WriteToLog("Loading list of deleted files from backup journal...", 7);
                List <string> tmpListDeletedFiles = new List <string>(100);
                while (r.Peek() != ':')
                {
                    tmpListDeletedFiles.Add(r.ReadLine());
                }
                r.ReadLine();
                backupJournalObject.BackupJournalFilesDelete = tmpListDeletedFiles;

                debugLog.WriteToLog("Loading list of folders from backup journal...", 7);
                List <FolderObject> tmpListFolders = new List <FolderObject>(100);
                while (r.Peek() != '?')
                {
                    tmp = r.ReadLine().Split('|');
                    if (tmp.Length == 4)
                    {
                        tmpListFolders.Add(new FolderObject()
                        {
                            FullPath = tmp[0], CreationTimeUtc = DateTime.FromBinary(Convert.ToInt64(tmp[1])), Attributes = tmp[2], HashRow = Convert.ToInt32(tmp[3])
                        });
                    }
                    else
                    {
                        string tmpRow = "";
                        for (int i = 0; i < tmp.Length; i++)
                        {
                            tmpRow += ('|' + tmp[i]);
                        }
                        debugLog.WriteToLog("Error when trying to load folder row from backup journal, row has different values, number of values is" + tmp.Length + " and the row is: " + tmpRow, 3);
                    }
                }
                r.ReadLine();
                backupJournalObject.BackupJournalFolders = tmpListFolders;



                debugLog.WriteToLog("Loading list of deleted folders from backup journal...", 7);
                List <string> tmpListDeletedFolders = new List <string>(100);
                while (!r.EndOfStream)
                {
                    tmpListDeletedFolders.Add(r.ReadLine());
                }
                backupJournalObject.BackupJournalFoldersDelete = tmpListDeletedFolders;
            }
            catch (Exception ex)
            {
                debugLog.WriteToLog("Fatal error loading backup journal, backup cannot continue: " + ex.Message, 2);
            }

            return(backupJournalObject);
        }
 public void RegisterDebugLog(ref DebugLog argDebugLog)
 {
     this.debugLogText = argDebugLog;
 }
        /// <summary>
        /// Fuction that writes backup journal (that can be later build on) to drive and also saves the backup journal to local cache named as ID of the task so it can be automatically selected by daemon when communicating with the server
        /// </summary>
        /// <param name="backupJournalObject">The backup journal you want to save to disk</param>
        /// <param name="pathToJournalFile">Path to location including the filename where the backup journal should by saved</param>
        /// <param name="TaskID">ID of the task that you are saving, if null not saving it</param>
        /// <param name="debugLog"><c>DebugLog</c> instance for logging performed actions</param>
        public void CreateBackupJournal(BackupJournalObject backupJournalObject, string pathToJournalFile, int TaskID, DebugLog debugLog)
        {
            try
            {
                tmpList = new List <string>();

                debugLog.WriteToLog("Writing relative paths to backup journal...", 7);
                for (int i = 0; i < backupJournalObject.RelativePaths.Count; i++)
                {
                    tmpList.Add(backupJournalObject.RelativePaths[i]);
                }
                tmpList.Add("!");
                debugLog.WriteToLog("Writing list of files to backup journal...", 7);
                List <FileInfoObject> fileBackupJournalHash = this.ReturnHashCodesFiles(backupJournalObject.BackupJournalFiles);
                for (int i = 0; i < fileBackupJournalHash.Count; i++)
                {
                    tmpList.Add(fileBackupJournalHash[i].FullPath + '|' + fileBackupJournalHash[i].Length.ToString() + '|' + fileBackupJournalHash[i].CreationTimeUtc.ToBinary().ToString() + '|' + fileBackupJournalHash[i].LastWriteTimeUtc.ToBinary().ToString() + '|' + fileBackupJournalHash[i].Attributes + '|' + fileBackupJournalHash[i].MD5 + '|' + fileBackupJournalHash[i].HashRow.ToString());
                }
                tmpList.Add("?");
                if (backupJournalObject.BackupJournalFilesDelete != null)
                {
                    debugLog.WriteToLog("Writing list of deleted files to backup journal...", 7);
                    for (int i = 0; i < backupJournalObject.BackupJournalFilesDelete.Count; i++)
                    {
                        tmpList.Add(backupJournalObject.BackupJournalFilesDelete[i]);
                    }
                }

                debugLog.WriteToLog("Writing list of folders to backup journal...", 7);
                List <FolderObject> folderBackupJournalHash = this.ReturnHashCodesFolders(backupJournalObject.BackupJournalFolders);
                tmpList.Add(":");
                for (int i = 0; i < folderBackupJournalHash.Count; i++)
                {
                    tmpList.Add(folderBackupJournalHash[i].FullPath + '|' + folderBackupJournalHash[i].CreationTimeUtc.ToBinary().ToString() + '|' + folderBackupJournalHash[i].Attributes.ToString() + '|' + folderBackupJournalHash[i].HashRow.ToString());
                }
                tmpList.Add("?");
                if (backupJournalObject.BackupJournalFoldersDelete != null)
                {
                    debugLog.WriteToLog("Writing list of deleted folders to backup journal...", 7);
                    for (int i = 0; i < backupJournalObject.BackupJournalFoldersDelete.Count; i++)
                    {
                        tmpList.Add(backupJournalObject.BackupJournalFoldersDelete[i]);
                    }
                }



                debugLog.WriteToLog("Writing backup journal to disk...", 7);

                w1 = new StreamWriter(pathToJournalFile);
                for (int i = 0; i < tmpList.Count; i++)
                {
                    w1.WriteLine(tmpList[i]);
                }
                w1.Close();
                w1.Dispose();

                if (TaskID > 0)
                {
                    Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + @"\KoFrMa\journalcache\");
                    File.Copy(pathToJournalFile, Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + @"\KoFrMa\journalcache\" + TaskID.ToString() + ".dat", true);
                    //w2 = new StreamWriter(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + @"\KoFrMa\journalcache\" + TaskID.ToString() + ".dat", false);
                    //for (int i = 0; i < tmpList.Count; i++)
                    //{
                    //    w2.WriteLine(tmpList[i]);
                    //}
                    //w2.Close();
                    //w2.Dispose();
                }
            }
            catch (Exception ex)
            {
                debugLog.WriteToLog("Fatal error when trying to create backup journal: " + ex, 2);
                throw;
                //zde už nelze pokračovat, nutno shodit celý proces zálohování, nekompletní log znamená vadnou zálohu!
            }
        }
Beispiel #46
0
 private bool Initialize(string host, int port, string username, string password, string database, string charset)
 {
     try
     {
     #if DEBUG
         _debuglog = new DebugLog("MySql.log");
     #endif
         Connection = new MySqlConnection(string.Format("Server={0};Port={1};Database={2};Uid={3};Pwd={4};CharSet={5};SslMode=Preferred;", host, port, database, username, password, charset));
         Connection.Open();
         return true;
     }
     catch(MySqlException m)
     {
         Log.Error("MySql", m.Message);
         return false;
     }
 }
Beispiel #47
0
        // Death checking phase
        internal void RunDeathCreationStepIfNeeded()
        {
#if _GAME_DEBUG
            DebugLog.WriteLine("Game " + GameId + ": Checking for death creation step");
#endif
            if (_deathCheckQueue.Count == 0)
            {
                return;
            }

            // We only have to check health because ToBeDestroyed cannot be reversed without the minion leaving play
            var dyingEntities =
                _deathCheckQueue.Where(
                    id => ((ICharacter)Entities[id]).MortallyWounded && Entities[id].Zone.Type == Brimstone.Zone.PLAY)
                .Select(id => (ICharacter)Entities[id]).ToList();

            if (dyingEntities.Count > 0)
            {
#if _GAME_DEBUG
                DebugLog.WriteLine("Game " + GameId + ": Running death creation step");
#endif
                PowerHistory?.Add(new BlockStart(BlockType.DEATHS, this));
            }

            // Death Creation Step
            bool gameEnd = false;
            foreach (var e in dyingEntities)
            {
#if _ACTIONS_DEBUG
                DebugLog.WriteLine("Game {0}: {1} dies", GameId, e.ShortDescription);
#endif
                // Queue deathrattles and OnDeath triggers before moving mortally wounded minion to graveyard
                // (they will be executed after the zone move)
                // TODO: Test that each queue resolves before the next one populates. If it doesn't, we can make queue populating lazy
                if (e is Minion)
                {
                    ActiveTriggers.Queue(TriggerType.OnDeath, e);
                }

                // NumMinionsPlayerKilledThisTurn seems to be the number of minions that died this turn
                // regardless of who or what killed what
                e.Controller.NumMinionsPlayerKilledThisTurn++;
                NumMinionsKilledThisTurn++;
                e.IsExhausted = false;

                // Move dead character to graveyard
                e.Zone = e.Controller.Graveyard;

                // TODO: Reset all minion tags to default
                if (e is Minion)
                {
                    var minion = ((Minion)e);
                    minion.Damage = 0;
                }

                // Hero death
                if (e is Hero)
                {
                    e.Controller.PlayState = PlayState.LOSING;
                    gameEnd = true;
                }
            }
            if (gameEnd)
            {
                GameWon();
            }

            if (dyingEntities.Count > 0)
            {
                PowerHistory?.Add(new BlockEnd(BlockType.DEATHS));
            }
            _deathCheckQueue.Clear();
        }