Esempio n. 1
0
        public MainWindow()
        {
            InitializeComponent();

            DataBaseAuth init = new DataBaseAuth();

            init.Init();

            DataBaseMobilePhone initDbMbp = new DataBaseMobilePhone();

            initDbMbp.Init();


            ReadDataBaseMobilePhone();

            lvMobilePhone.Visibility = Visibility.Hidden;
            //lvMobilePhone.ContextMenu.
            //Правильная версия



            Window   = new Log2(dialogLW, thread);
            dialogLW = Window.ShowWindow("Ошибка");

            Thread.Sleep(3000);
            dialogLW.tbError.Dispatcher.Invoke(DispatcherPriority.Background, new Action(() => { dialogLW.tbError.Text += "Получил управление потоком \n"; }));

            Thread.Sleep(3000);

            ErrorWithThread errwiththread = new ErrorWithThread("Главное окно загружено\nНажмите кнопку \"ДОБАВИТЬ\" для демонстрации работы консоли\n", dialogLW);

            errwiththread.LogWindow();
        }
Esempio n. 2
0
        public void NormalTest()
        {
            var buf = Rand.NextBytes(1024);

            var log = new Log2
            {
                Category = "test",
                Action   = "abc",
                Remark   = buf,
            };

            log.Insert();

            Assert.True(log.ID > 0);

            var log2 = Log2.FindByID(log.ID);

            Assert.NotNull(log2);
            Assert.Equal(buf, log2.Remark);

            var buf2 = Rand.NextBytes(1024);

            log2.Remark = buf2;
            log2.Update();

            var log3 = Log2.FindByID(log.ID);

            Assert.NotNull(log3);
            Assert.Equal(buf2, log3.Remark);

            log.Delete();
        }
Esempio n. 3
0
        public async Task <IActionResult> Edit(int id, [Bind("ActivityId,MemberId,UserName,ipAddr,Action,createdTS")] Log2 log2)
        {
            if (id != log2.ActivityId)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(log2);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!Log2Exists(log2.ActivityId))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(log2));
        }
Esempio n. 4
0
        public void Calculate()
        {
            Log2   calculator = new Log2();
            double result     = calculator.Calculate(4);

            Assert.AreEqual(2, result, 0.001);
        }
        public DedicatedClient(string source, IPEndPoint ip)
        {
            string[]      parts = source.Split('\\');
            List <string> keys  = new List <string>();
            List <string> vals  = new List <string>();

            for (int i = 1; i < parts.Length; i++)
            {
                if (i % 2 == 1)
                {
                    keys.Add(parts[i]);
                }
                else
                {
                    vals.Add(parts[i]);
                }
            }
            if (keys.Count == vals.Count)
            {
                for (int i = 0; i < keys.Count; i++)
                {
                    Configuration.Add(keys[i], vals[i]);
                }
            }
            else
            {
                Log2.Error("Couldn't properly parse client info.");
            }
            IP      = ip;
            IP.Port = (int)ChanllegeServer.SwapShort(BitConverter.GetBytes((short)IP.Port));
        }
Esempio n. 6
0
 private void LinkSendLogToDev_Click(object sender, EventArgs e)
 {
     try
     {
         string subject = InputBox.Input("Any comment? (optional)", settings.StyleColor);
         if (subject != null)
         {
             WaitingOverlay waitingOverlay = new WaitingOverlay(this, "Please wait...", settings.StyleColor).Show();
             Task.Factory.StartNew(() =>
             {
                 try
                 {
                     Log2.UploadLog(subject);
                 }
                 catch (Exception ex)
                 {
                     log.Error("Can't send log: " + ex.Message);
                     this.TaskDialog("Can't send log", ex.Message, NotifyUserType.Error);
                 }
                 finally
                 {
                     BeginInvoke(new Action(waitingOverlay.Close));
                 }
             });
         }
     }
     catch (Exception ex)
     {
         log.Info("Can't send log file: " + ex.Message);
         this.TaskDialog("Log file sending error", ex.Message, NotifyUserType.Error);
     }
 }
            public HashTable(byte[] input)
            {
                this.input = input;

                this.table = GetHashTable(input.Length);
                this.shift = 64 - Log2.Floor(table.Length);
            }
Esempio n. 8
0
        public void ShardTestSQLite2()
        {
            // 配置自动分表策略,一般在实体类静态构造函数中配置
            var shard = new TimeShardPolicy("ID", Log2.Meta.Factory)
            {
                //Field = Log2._.ID,
                ConnPolicy  = "{0}_{1:yyyy}",
                TablePolicy = "{0}_{1:yyyyMMdd}",
            };

            Log2.Meta.ShardPolicy = shard;

            // 拦截Sql,仅为了断言,非业务代码
            var sqls = new List <String>();

            DAL.LocalFilter = s => sqls.Add(s);

            var time = DateTime.Now;
            var log  = new Log2
            {
                Action   = "分表",
                Category = Rand.NextString(8),

                CreateTime = time,
            };

            // 添删改查全部使用新表名
            log.Insert();
            Assert.StartsWith($"[test_{time:yyyy}] Insert Into Log2_{time:yyyyMMdd}(", sqls[^ 1]);
        public static void Main(string[] args)
        {
            Log2 log2 = (level, msg) => Console.WriteLine(string.Format("{0} {1}", level, msg));

            log2(Error, "abort abort !");

            log2.Level(Error)("abort abort !");
        }
Esempio n. 10
0
        public static void Main(string[] args)
        {
            Log2 log2 = (level, msg) => Console.WriteLine(string.Format("{0} {1}", level, msg));

            log2(Error, "abort abort !");

#pragma warning disable CS0219
            Log log = null; // how to use Log2 here?
#pragma warning restore CS0219
        }
Esempio n. 11
0
        public void CalculateTest(
            double firstValue,
            double expected)

        {
            var calculator   = new Log2();
            var actualResult = calculator.Calculate(firstValue);

            Assert.AreEqual(expected, actualResult, 0.001);
        }
        public void Test_Adapter1()
        {
            string logOutput;

            Log2 log2 = (level, msg) => logOutput = string.Format("{0} {1}", level, msg);

            logOutput = null;
            log2(Error, "abort abort !");
            Assert.Equal("Error abort abort !", logOutput);
        }
Esempio n. 13
0
        public async Task <IActionResult> Create([Bind("ActivityId,MemberId,UserName,ipAddr,Action,createdTS")] Log2 log2)
        {
            if (ModelState.IsValid)
            {
                _context.Add(log2);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(log2));
        }
Esempio n. 14
0
 void xrun()
 {
     while (true)
     {
         IPEndPoint clientIP = new IPEndPoint(IPAddress.Any, 20700);
         byte[]     data     = udp.Receive(ref clientIP);
         string     str      = Encoding.ASCII.GetString(data);
         Log2.Data(str);
         udp.Send(data, data.Length, clientIP);
     }
 }
 void xrun()
 {
     while (true)
     {
         IPEndPoint   clientIP = new IPEndPoint(IPAddress.Any, 28960);
         byte[]       data     = udp.Receive(ref clientIP);
         MemoryStream memsr    = new MemoryStream(data);
         BinaryReader reader   = new BinaryReader(memsr);
         Log2.Info("Header_Int: " + reader.ReadInt32().ToString());
         Log2.Info("Body: " + reader.ReadString());
     }
 }
Esempio n. 16
0
 private static void SendLogToDeveloper()
 {
     if (Settings2.Instance.SendLogToDeveloperOnShutdown && log.HaveErrors && Utils.InternetAvailable && File.Exists(Globals.LogFileName))
     {
         try
         {
             Log2.UploadLog(null);
         }
         catch (Exception ex)
         {
             TaskDialog.Show("Log file sending error", ex.Message);
         }
     }
 }
        int SendChallenge(IPEndPoint ip, UdpClient udp)
        {
            int          c       = new Random().Next();
            MemoryStream getChng = new MemoryStream();
            BinaryWriter w       = new BinaryWriter(getChng);

            w.Write(new byte[] { 0xFF, 0xFF, 0xFF, 0xFF });
            w.Write(string.Format("getchallenge {0}", c));
            w.Flush();
            byte[] data = getChng.ToArray();
            udp.Send(data, data.Length, ip);
            Log2.Info("Sending challange data to " + ip.ToString() + "...");
            return(c);
        }
Esempio n. 18
0
        /// <summary>
        /// Initializes a new ring buffer, with the values and size of the provided <paramref name="values"/>.
        /// </summary>
        /// <param name="values">Initial values placed into the buffer. Element at [0] is at the back of the queue.</param>
        public RingBufferFast(T[] values)
        {
            int length = values.Length;

            if (length == 0)
            {
                throw new ArgumentException("Ring buffer size cannot be zero.");
            }
            else if (length != 1 << Log2.Floor(length))
            {
                throw new ArgumentException("Fast ring buffer size must be a power of 2.");
            }

            this.values = values;
            this.mask   = length - 1;
        }
Esempio n. 19
0
        private static bool TryGetSavedOffsets(byte[] hash)
        {
            Log2   log          = new Log2(nameof(WowBuildInfoX64));
            string hashAsString = BitConverter.ToString(hash);
            var    directory    = Directory.CreateDirectory(Path.Combine(AppFolders.DataDir, "wow-builds"));
            var    filePath     = Path.Combine(directory.FullName, hashAsString + ".json");

            log.Info($"TryGetSavedOffsets: filepath: '{filePath}'");
            if (File.Exists(filePath))
            {
                log.Info($"TryGetSavedOffsets: file exists, trying to deserialize...");
                try
                {
                    var offsets = JsonConvert.DeserializeObject <Dictionary <string, IntPtr> >(File.ReadAllText(filePath, Encoding.UTF8));
                    if (offsets.Count == patterns.Length)
                    {
                        log.Info("TryGetSavedOffsets: deserialization is successful!");
                        WoWHash             = hash;
                        BlackMarketNumItems = offsets[nameof(BlackMarketNumItems)].ToInt32();
                        BlackMarketItems    = offsets[nameof(BlackMarketItems)].ToInt32();
                        LastHardwareAction  = offsets[nameof(LastHardwareAction)].ToInt32();
                        TickCount           = offsets[nameof(TickCount)].ToInt32();
                        MouseoverGUID       = offsets[nameof(MouseoverGUID)].ToInt32();
                        ChatIsOpened        = offsets[nameof(ChatIsOpened)].ToInt32();
                        FocusedWidget       = offsets[nameof(FocusedWidget)].ToInt32();
                        ObjectManager       = offsets[nameof(ObjectManager)].ToInt32();
                        GlueState           = offsets[nameof(GlueState)].ToInt32();
                        GameState           = offsets[nameof(GameState)].ToInt32();
                        KnownSpellsCount    = offsets[nameof(KnownSpellsCount)].ToInt32();
                        KnownSpells         = offsets[nameof(KnownSpells)].ToInt32();
                        UIFrameBase         = offsets[nameof(UIFrameBase)].ToInt32();
                        PlayerZoneID        = offsets[nameof(PlayerZoneID)].ToInt32();
                        PlayerIsLooting     = offsets[nameof(PlayerIsLooting)].ToInt32();
                        PlayerGUID          = offsets[nameof(PlayerGUID)].ToInt32();
                        NotLoadingScreen    = offsets[nameof(NotLoadingScreen)].ToInt32();
                        IsChatAFK           = offsets[nameof(IsChatAFK)].ToInt32();
                        ChatBuffer          = offsets[nameof(ChatBuffer)].ToInt32();
                        return(true);
                    }
                }
                catch (Exception ex)
                {
                    log.Error($"TryGetSavedOffsets: deserialization is failed: {ex.Message}");
                }
            }
            return(false);
        }
Esempio n. 20
0
        static void Main(string[] args)
        {
            Log2.Initialize("Log2.txt", LogLevel.All, false);
            string ip = Console.ReadLine();

            client.Connect(IPAddress.Parse(ip), 57852);
            sr = client.GetStream();
            Log2.Info("Updating client size...");
            UpdateClientSize();
            new Thread(WaitForIt).Start();
            new Thread(SendPicture).Start();
            Log2.Debug("Systems up!");
            while (true)
            {
                Log2.WriteAway();
            }
        }
Esempio n. 21
0
 public override bool Execute()
 {
     // In more advanced cases we can override the Execute method as well.
     // We can perform additional checks, or even entirely bypass weaving
     // by not calling the base Execute method.
     if (new Random().Next(0, 10) == 11)
     {
         // Log2 is a property introduced in MSBuildWeaver.
         // It exposes a Serilog ILogger that logs any event to MSBuild.
         // An error raised either by Log2 or Log will fail the build
         // if the base Execute method is called.
         Log2.Error("Sorry, something went wrong with the laws of math :-(");
         return(false);
     }
     // Calling the base method will eventually call the DoWeave method below.
     return(base.Execute());
 }
Esempio n. 22
0
 internal GameInterface(WowProcess wow)
 {
     wowProcess = wow ?? throw new ArgumentNullException(nameof(wow));
     Memory     = wow.Memory ?? throw new ArgumentNullException(nameof(wow), "Memory is null");
     log        = new Log2($"GameInterface - {wow.ProcessID}");
     if (!chatLocks.ContainsKey(wowProcess.ProcessID))
     {
         chatLocks[wowProcess.ProcessID] = new object();
     }
     if (!readChatLocks.ContainsKey(wowProcess.ProcessID))
     {
         readChatLocks[wowProcess.ProcessID] = new object();
     }
     if (!luaLocks.ContainsKey(wowProcess.ProcessID))
     {
         luaLocks[wowProcess.ProcessID] = new object();
     }
 }
Esempio n. 23
0
        static void WaitForIt()
        {
            BinaryReader reader = new BinaryReader(sr);

            while (true)
            {
                if (sr != null)
                {
                    int typ = reader.ReadInt32();
                    if (typ == 0x12)
                    {
                        int x = reader.ReadInt32();
                        int y = reader.ReadInt32();
                        Cursor.Position = ClientToScreen(ClientSize, Screen.PrimaryScreen.WorkingArea.Size, new Point(x, y));
                        Log2.Info("Cursor position has been updated..");
                    }
                }
            }
        }
Esempio n. 24
0
        static void Main(string[] args)
        {
            Console.Title           = "IW3 Master Server";
            Console.BackgroundColor = ConsoleColor.White;
            Console.Clear();
#if BETA
            Console.ForegroundColor = ConsoleColor.Black;
            Console.WriteLine("WARNING THIS VERSION IS PRETTY BUGGY!");
#endif
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine(GetHeader());
            Log2.Initialize("Log2_Server.txt", LogLevel.All, false);

            ChanllegeServer cSer = new ChanllegeServer();
            cSer.Start();
            WelcomeServer wcmSer = new WelcomeServer();
            wcmSer.Start();
            while (true)
            {
                Log2.WriteAway();
            }
        }
 public static Log Level(this Log2 log2, Level level)
 {
     return(msg => log2(level, msg));
 }
 public void Start()
 {
     Log2.Debug("Challenge server is now running!");;
     new Thread(xrun).Start();
 }
Esempio n. 27
0
        public void ExceptionTest()
        {
            var calculator = new Log2();

            Assert.Throws <Exception>(() => calculator.Calculate(0));
        }
 void Done(IAsyncResult state)
 {
     Log2.Info("Sending message to client! [" + state.AsyncState.ToString() + "]");
 }
Esempio n. 29
0
        private static void Zip()
        {
            Log2 vssLog = new Log2(nameof(AddonsBackup) + " - VSS Service");
            // get free drive letter
            string driveLetter = new string[] { "P:", "Q:", "R:", "S:", "T:", "U:", "V:", "W:" }.FirstOrDefault(l => !DriveInfo.GetDrives().Select(m => m.RootDirectory.Name).Contains(l));

            if (driveLetter == default(string))
            {
                throw new IOException("Can't find free drive letter!");
            }
            vssLog.Info($"Free drive letter: {driveLetter}");
            // making VSS snapshot
            IVssImplementation   vssImplementation = VssUtils.LoadImplementation();
            IVssBackupComponents backupComponents  = vssImplementation.CreateVssBackupComponents();

            backupComponents.InitializeForBackup(null);
            vssLog.Info("VssBackupComponents is initialized");
            Guid backupGuid1 = Guid.Empty;

            try
            {
                backupComponents.GatherWriterMetadata();
                backupComponents.SetContext(VssVolumeSnapshotAttributes.Persistent | VssVolumeSnapshotAttributes.NoAutoRelease);
                backupComponents.SetBackupState(false, true, VssBackupType.Full, false);
                vssLog.Info("VssBackupComponents is set up");
                backupComponents.StartSnapshotSet();
                backupGuid1 = backupComponents.AddToSnapshotSet(new DirectoryInfo(_settings.WoWDirectory).Root.Name, Guid.Empty);
                backupComponents.PrepareForBackup();
                backupComponents.DoSnapshotSet();
                vssLog.Info("Snapshot is taken");
                backupComponents.ExposeSnapshot(backupGuid1, null, VssVolumeSnapshotAttributes.ExposedLocally, driveLetter);
                // zipping
                string zipPath = $"{_settings.WoWAddonsBackupPath}\\AddonsBackup_{DateTime.UtcNow:yyyyMMdd_HHmmss}.zip";
                log.Info("Zipping to file: " + zipPath);
                using (ZipFile zip = new ZipFile(zipPath, Encoding.UTF8))
                {
                    zip.CompressionLevel = (CompressionLevel)_settings.WoWAddonsBackupCompressionLevel;
                    foreach (string dirName in FoldersToArchive)
                    {
                        zip.AddDirectory(_settings.WoWDirectory.Replace(new DirectoryInfo(_settings.WoWDirectory).Root.Name, $"{driveLetter}\\") + "\\" + dirName, "\\" + dirName);
                    }
                    zip.SaveProgress += AddonsBackup_SaveProgress;
                    var processPriority = Process.GetCurrentProcess().PriorityClass;
                    Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.BelowNormal;
                    zip.Save();
                    Process.GetCurrentProcess().PriorityClass = processPriority;
                    zip.SaveProgress -= AddonsBackup_SaveProgress;
                }
            }
            finally
            {
                VssSnapshotProperties existingSnapshot = backupComponents.QuerySnapshots().FirstOrDefault(l => l.SnapshotId == backupGuid1);
                if (existingSnapshot == default(VssSnapshotProperties))
                {
                    vssLog.Error($"Can't delete snapshot {backupGuid1}");
                }
                else
                {
                    backupComponents.DeleteSnapshot(existingSnapshot.SnapshotId, true);
                    backupComponents.Dispose();
                    vssLog.Info($"Snapshot is deleted ({existingSnapshot.SnapshotId})");
                }
                GC.Collect();
            }
        }
Esempio n. 30
0
        private static void Legacy()
        {
            var legacyLog = new Log2(nameof(Legacy));

            // 08.10.2015
            try
            {
                var mySettingsDir  = AppFolders.PluginsSettingsDir + "\\Fishing";
                var mySettingsFile = mySettingsDir + "\\FishingSettings.json";
                if (File.Exists(mySettingsFile))
                {
                    File.Move(mySettingsFile, mySettingsDir + "\\settings.json");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            // 11.07.2016
            try
            {
                if (Directory.Exists(Application.StartupPath + "\\wowheadCache"))
                {
                    Directory.Delete(Application.StartupPath + "\\wowheadCache", true);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            // 12.01.2018
            try
            {
                foreach (string hotkeyName in new[] { "ClickerHotkey", "WoWPluginHotkey" })
                {
                    var cfg   = File.ReadAllText(AppFolders.ConfigDir + "\\settings.json", Encoding.UTF8);
                    var regex = new Regex($"\"{hotkeyName}\": (\\d+)");
                    var match = regex.Match(cfg);
                    if (match.Success)
                    {
                        var oldKey = JsonConvert.DeserializeObject <Keys>(match.Groups[1].Value);
                        var alt    = false;
                        var ctrl   = false;
                        var shift  = false;
                        if ((oldKey & Keys.Alt) == Keys.Alt)
                        {
                            alt = true;
                        }
                        if ((oldKey & Keys.Control) == Keys.Control)
                        {
                            ctrl = true;
                        }
                        if ((oldKey & Keys.Shift) == Keys.Shift)
                        {
                            shift = true;
                        }
                        oldKey = oldKey & ~Keys.Control & ~Keys.Shift & ~Keys.Alt;
                        var newCfg = cfg.Replace(match.Value, $"\"{hotkeyName}\": " + JsonConvert.SerializeObject(new KeyboardWatcher.KeyExt(oldKey, alt, shift, ctrl)));
                        File.WriteAllText(AppFolders.ConfigDir + "\\settings.json", newCfg, Encoding.UTF8);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            // 17.04.2017
            try
            {
                if (Settings2.Instance.LastUsedVersion <= new VersionExt(12, 2, 46))
                {
                    var fileName = AppFolders.DataDir + "\\wowhead.ldb";
                    if (File.Exists(fileName))
                    {
                        File.Delete(fileName);
                        legacyLog.Info("Old db file is deleted");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            // 17.01.2018
            try
            {
                var fileName = AppFolders.DataDir + "\\wowhead.ldb";
                if (File.Exists(fileName))
                {
                    File.Delete(fileName);
                    legacyLog.Info($"Old db file is deleted ({fileName})");
                }
                fileName = AppFolders.DataDir + "\\players.ldb";
                if (File.Exists(fileName))
                {
                    File.Delete(fileName);
                    legacyLog.Info($"Old db file is deleted ({fileName})");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            // 10.08.2018
            try
            {
                if (Settings2.Instance.LastUsedVersion <= new VersionExt(12, 3, 46))
                {
                    var fileName = Path.Combine(AppFolders.ConfigDir, "lua-console.json");
                    if (File.Exists(fileName))
                    {
                        File.Delete(fileName);
                        legacyLog.Info($"{fileName} is deleted");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            // 10.08.2018
            try
            {
                if (Settings2.Instance.LastUsedVersion <= new VersionExt(12, 3, 46))
                {
                    var fileName = Path.Combine(AppFolders.ConfigDir, "wow-radar.json");
                    if (File.Exists(fileName))
                    {
                        var newFilePath = Path.Combine(AppFolders.PluginsSettingsDir, "Radar\\settings.json");
                        if (File.Exists(newFilePath))
                        {
                            File.Delete(newFilePath);
                        }
                        var rawConfig = File.ReadAllText(fileName, Encoding.UTF8);
                        var config    = rawConfig.Replace(Path.Combine(AppFolders.ResourcesDir, "alarm.wav").Replace(@"\", @"\\"), Path.Combine(Settings2.Instance.PluginSourceFolder, "Radar\\alarm.wav").Replace(@"\", @"\\"));
                        File.WriteAllText(fileName, config, Encoding.UTF8);
                        File.Move(fileName, newFilePath);
                        legacyLog.Info($"{fileName} is moved to {newFilePath}");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }