예제 #1
0
 public override string ToString()
 {
     return("VID = " + Vid.ToString("X4") +
            " PID = " + Pid.ToString("X4") +
            " Product: " + Product +
            " Path " + Path);
 }
예제 #2
0
 public override string ToString()
 {
     return("-- " + Name + " -- " + "\n" +
            Utils.ToStringProp("Pid", Pid.ToString()) +
            Utils.ToStringProp("Coords", X + "," + Y) +
            Utils.ToStringProp("Visible", (Visible ? "Yes" : "No")));
 }
예제 #3
0
        public string GetField(int field)
        {
            switch (field)
            {
            case 0:
                return(Name);

            case 1:
                return(Score.ToString());

            case 2:
                return(Ping.ToString());

            case 3:
                return(Team.ToString());

            case 4:
                return(Deaths.ToString());

            case 5:
                return(Pid.ToString());

            case 6:
                return(Kills.ToString());

            case 7:
                return((IsBot ? 1 : 0).ToString());

            default:
                return("");
            }
        }
예제 #4
0
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine("----------- ECM INFO -----------");
            sb.Append("Service ID: 0x");
            sb.AppendLine(ServiceId.ToString("x4"));
            sb.Append("PID:        0x");
            sb.AppendLine(Pid.ToString("x4"));
            sb.Append("Caid:       0x");
            sb.AppendLine(CaId.ToString("x4"));
            sb.Append("ProvId:     0x");
            sb.AppendLine(ProviderId.ToString("x6"));
            sb.Append("Cardsystem: ");
            sb.AppendLine(CardSystem);
            sb.Append("Reader:     ");
            sb.AppendLine(ReaderName);
            sb.Append("Source:     ");
            sb.AppendLine(SourceName);
            sb.Append("Protocol:   ");
            sb.AppendLine(ProtocolName);
            sb.Append("Hops:       ");
            sb.AppendLine(HopsCount.ToString());
            sb.Append("Time:       ");
            sb.Append(EcmTime.ToString());
            sb.AppendLine("ms");
            sb.AppendLine("----------- ECM INFO -----------");

            return(sb.ToString());
        }
        internal string GetDiagnosticStringData()
        {
            string result = "NTA event for PID: " + Pid.ToString() + "\r\n";

            result += "Entry: " + DebugEntry + "\r\n";
            result += "Index: " + AssignedIndex.ToString() + "\r\n";
            result += ViewData.GetDiagnosticStringData();
            return(result);
        }
예제 #6
0
 public override string ToString()
 {
     return("-- " + Name + " -- " + "\n" +
            Utils.ToStringProp("Pid", Pid.ToString()) +
            Utils.ToStringProp("FileName", FileName.ToString()) +
            Utils.ToStringProp("ScriptName", ScriptName.ToString()) +
            Utils.ToStringProp("SoundString", SoundString.ToString()) +
            Utils.ToStringProp("NoLogout", NoLogout.ToString()));
 }
예제 #7
0
파일: Process.cs 프로젝트: PetarMih/ORS3-OS
        public String[] Info()
        {
            String[] res = new String[5];
            res[0] = Name;
            res[1] = Pid.ToString();
            res[2] = Status;
            res[3] = CPU_usage.ToString();
            res[4] = Memory.ToString();

            return(res);
        }
예제 #8
0
            /// <summary>
            /// Short string general information about this device.
            /// </summary>
            public override string ToString()
            {
                string __desc = Description.Truncate(25);

                if (Description == "")
                {
                    __desc = Type.Truncate(25);
                }
                return($"V/PID: {Vid.ToString("X4")}-{Pid.ToString("X4")} [{__desc}] SN: {Serial}"
                       .Truncate(Const.DEV_STR_MAX_LEN));
            }
예제 #9
0
    protected void Bar_Btn_Click(object sender, EventArgs e)
    {
        M_GuestBookCate cateMod = bookBll.GetCate(Cid);
        int             uid     = buser.GetLogin().UserID;
        string          ids     = Request.Form["idchk"];

        if (cateMod.IsBarOwner(uid) && !string.IsNullOrWhiteSpace(ids))
        {
            switch ((sender as Button).CommandArgument)
            {
            case "Del":
                barBll.UpdateStatus(Cid, ids, (int)ZLEnum.ConStatus.Recycle);
                if (ids.Contains(Pid.ToString()))
                {
                    Response.Redirect("/" + CreateUrl(1, Cid));
                }
                break;

            case "AddTop":
                barBll.UpdateTop(ids, true);
                break;

            case "RemoveTop":
                barBll.UpdateTop(ids, false);
                break;

            case "AddRecom":
                barBll.UpdateRecommend(ids, true);
                break;

            case "RemoveRecom":
                barBll.UpdateRecommend(ids, false);
                break;

            case "AddBottom":
                barBll.UpdateDown(ids, true);
                break;

            case "RemoveBottom":
                barBll.UpdateDown(ids, false);
                break;

            case "Hidden":
                barBll.UpdateStatus(Cid, ids, -2);
                break;

            case "CancelHidden":
                barBll.UpdateStatus(Cid, ids, (int)ZLEnum.ConStatus.Audited);
                break;
            }
        }
        MyBind();
    }
예제 #10
0
 protected void DelMsg_Btn_Click(object sender, EventArgs e)
 {
     if (Pid > 0)
     {
         M_UserInfo mu = barBll.GetUser();
         barMod = barBll.SelReturnModel(Pid);
         int    cateId = barMod.CateID;
         string result = barBll.UpdateStatus(barBll.SelReturnModel(Pid).CateID, Pid.ToString(), -1) ? "ok" : "failed";
         if (result == "ok")
         {
             function.Script(this, "<script>alert('删除成功!')</script>");
             Response.Redirect("/PClass?uid=" + mu.UserID);
         }
         else
         {
             function.Script(this, "<script>alert('删除失败!')</script>");
             Response.Redirect("/PItem?id=" + Pid);
         }
     }
 }
예제 #11
0
        /// <summary>
        /// Проверить наличие обновлений на сервере.
        /// </summary>
        /// <returns></returns>
        public Task <bool> CheckUpdateAsync()
        {
            return(Task.Factory.StartNew(() =>
            {
                //Уведомляем подписчиков, что проверка наличия новой версии запущена.
                OnUpdateStateChanged(UpdateState.Checking);

                string localPidFile = _localPidFile;
                string localPidHash = null;
                if (File.Exists(localPidFile)) //если локальный файл с хэшем версии обновления найден
                {
                    localPidHash = Pid.FromTextFile(localPidFile).Hash;
                }

                WebClient web = _webClientFactory.Create();
                string pidText = web.DownloadString(_serverPidFile);
                Pid downloadedPid = Pid.FromString(pidText);

                if (localPidHash == null)
                {
                    Pid newLocalPid = Pid.FromVersionNumber(-1);
                    localPidHash = newLocalPid.Hash;
                    using (StreamWriter writer = File.CreateText(localPidFile))
                    {
                        writer.Write(newLocalPid.ToString());
                    }
                }

                OnUpdateStateChanged(UpdateState.None);
                if (downloadedPid.Hash != localPidHash)
                {
                    _pidFromServer = downloadedPid;
                    return true;
                }

                //Уведомляем подписчиков, что обновление не требуется.
                OnUpdateStateChanged(UpdateState.NotNeeded);
                OnUpdateStateChanged(UpdateState.None);
                return false;
            }));
        }
        private void Search(Object o)
        {
            ManagementScope            connectionScope = new ManagementScope();
            SelectQuery                mosQuery        = new SelectQuery($@"SELECT * FROM Win32_PnPEntity where DeviceID like '%VID_{Vid.ToString("X4")}&PID_{Pid.ToString("X4")}%'");
            ManagementObjectSearcher   searcher        = new ManagementObjectSearcher(connectionScope, mosQuery);
            ManagementObjectCollection results         = searcher.Get();

            ManagementObjectCollection.ManagementObjectEnumerator enumerator = results.GetEnumerator();

            DeviceCount = results.Count;
            if (DeviceCount > 0)
            {
                enumerator.MoveNext();
                InitDevice((ManagementObject)enumerator.Current);
            }

            if (DeviceCount == 0 && !String.IsNullOrWhiteSpace(DeviceId))
            {
                Disconnect();
            }
        }
예제 #13
0
 ///<summary>
 ///Returns a <see cref="T:System.String"/> that represents the current <see cref="UsbSymbolicName"/>.
 ///</summary>
 ///
 ///<returns>
 ///A <see cref="System.String"/> that represents the current <see cref="UsbSymbolicName"/>.
 ///</returns>
 public override string ToString()
 {
     object[] o = new object[] { FullName, Vid.ToString("X4"), Pid.ToString("X4"), SerialNumber, ClassGuid };
     return(string.Format("FullName:{0}\r\nVid:0x{1}\r\nPid:0x{2}\r\nSerialNumber:{3}\r\nClassGuid:{4}\r\n", o));
 }
예제 #14
0
        public void Update()
        {
            if (_currentState != UpdateState.None)
            {
                OnUpdateStateChanged(_currentState);
                return;
            }

            // Pour changer l'état le plus rapidement possible sans permettre de vérifier l'état avant qu'il ne change d'un autre flux
            _currentState = UpdateState.Started;

            // Démarrer l'exécution du code dans un thread à partir d'un pool de threads.
            ThreadPool.QueueUserWorkItem(async unused =>
            {
                // Informer les abonnés que la mise à jour a été lancée.
                OnUpdateStateChanged(UpdateState.Started);

                Task <string> task = Task.Factory.StartNew(() => _webClient.DownloadString(_serverPatchListFile));
                string patchlist   = await task;

                var patch = new PatchInfo(patchlist);

                // Obtenez le chemin d'accès au dossier dans lequel les données du client sont mises à jour (le dossier où se trouve le dispositif de mise à jour/le lanceur et les données à mettre à jour).
                string dataDirectory = Path.Combine(_rootDirectory);
                if (!Directory.Exists(dataDirectory))
                {
                    Directory.CreateDirectory(dataDirectory);
                }

                // Obtenir tous les fichiers mpq situés sur le disque local (y compris tous les sous-dossiers).
                string[] localFiles = Directory.GetFiles(dataDirectory, ".", SearchOption.AllDirectories);

                // Filtrer uniquement les fichiers locaux dont les noms coïncident avec les noms de fichiers dans le patch
                Dictionary <string, FileInfo> matchingFiles =
                    localFiles.Where(                                                     // Filtre où
                        f => patch.UpdateFiles.Any(                                       // le fichier local f correspond
                            pf => pf.FileName == Path.GetFileName(f) && !File.Exists(f))) // avec un fichier dans le patch nommé
                    .Select(mf => new FileInfo(mf))                                       // Projeter chaque élément de collection dans un nouveau type de données
                    .ToDictionary(info => info.Name);                                     // convertir la collection filtrée en dictionnaire avec la clé "nom de fichier"

                // Dernier pourcentage d'avancement de la mise à jour
                int lastPercentValue = 0;

                // Créer un dossier temporaire s'il n'existe pas. Dossier où nous allons télécharger les nouveaux fichiers de mise à jour
                if (!Directory.Exists(TempFolder))
                {
                    Directory.CreateDirectory(TempFolder);
                }

                // Créer une liste comparable de fichiers téléchargés avec des informations sur ce fichier
                // précédemment reçu du serveur (à partir d'une feuille de patch)
                var downloaded = new List <Tuple <string, UpdateFile> >(patch.UpdateFiles.Length);

                // créer un compteur variable du nombre d'octets téléchargés de tous les fichiers
                long downloadedBytesLength = 0L;
                // Télécharger tous les fichiers
                for (int i = 0; i < patch.UpdateFiles.Length; i++)
                {
                    UpdateFile updateFile = patch.UpdateFiles[i];

                    string tempFile = Path.Combine(TempFolder, updateFile.FileName);

                    if (matchingFiles.ContainsKey(updateFile.FileName))
                    {
                        FileInfo file        = matchingFiles[updateFile.FileName];
                        string localFileHash = HashHelper.GetMD5HashOfFile(file.FullName);
                        if (localFileHash == updateFile.Hash)
                        {
                            // on ajoute sa taille à la somme des octets téléchargés,
                            // que le pourcentage de progression du téléchargement est correctement pris en compte
                            downloadedBytesLength += updateFile.FileSize;
                            lastPercentValue       = UpdateProgress(downloadedBytesLength, updateFile.FileName, patch.PatchLength, lastPercentValue, updateFile.FileSize);
                            continue; // quitter l'itération en cours du cycle et le cycle passe à l'étape suivante
                        }
                    }

                    long offset = 0L;
                    // Si le fichier existe (a été téléchargé plus tôt) et qu'il est entièrement téléchargé (le hachage correspond au hachage de la feuille de patch)
                    if (File.Exists(tempFile))
                    {
                        string hash = HashHelper.GetMD5HashOfFile(tempFile);
                        if (hash == updateFile.Hash) // vérifier les hashes.
                        {
                            // on ajoute sa taille à la somme des octets téléchargés,
                            // que le pourcentage de progression du téléchargement est correctement pris en compte
                            downloadedBytesLength += updateFile.FileSize;
                            downloaded.Add(Tuple.Create(tempFile, updateFile));
                            lastPercentValue = UpdateProgress(downloadedBytesLength, updateFile.FileName, patch.PatchLength, lastPercentValue, updateFile.FileSize);
                            continue; // quitter l'itération en cours du cycle et le cycle passe au cycle suivant
                        }
                        /*-------------   pompant -------------------------*/
                        else
                        {
                            var fileInfo           = new FileInfo(tempFile);
                            offset                 = fileInfo.Length; // Combien d'octets ont été téléchargés. Combien vous devez déplacer lors du téléchargement.
                            downloadedBytesLength += fileInfo.Length; // les progrès seront désormais dûment pris en compte
                        }
                    }

                    Uri url = new Uri(UrlHelper.Combine(_serverFilesRoot, updateFile.FileName));
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

                    if (offset > 0L) // L signifie que les littéraux de type 0 sont longs ou Int64, ce qui est la même chose. Sans L, il y aura un type int.
                    {
                        request.AddRange(offset);
                    }
                    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                    {
                        if (response.StatusCode != HttpStatusCode.OK)
                        {
                            string message = string.Format("POST failed. Received HTTP {0}", response.StatusCode);
                            MessageBox.Show(message);
                            //throw new ApplicationException(message); Don't crash
                        }

                        Stream source = response.GetResponseStream();
                        if (source != null)
                        {
                            // пытаемся создать папки, которые отсутствуют из пути
                            var address      = new Uri(Path.Combine(_rootDirectory + '/' + updateFile.FileName), UriKind.Absolute);
                            string directory = Path.GetDirectoryName(address.LocalPath);
                            Debug.Assert(directory != null);
                            if (!Directory.Exists(directory))
                            {
                                Directory.CreateDirectory(directory);
                            }

                            byte[] buffer = new byte[400]; //102400 байт = 100 Килобайт  (400)

                            if (!FileExists(_rootDirectory + "/" + "d3dcompiler_47.dll"))
                            {
                                using (FileStream fs = new FileStream(_rootDirectory + '/' + updateFile.FileName, FileMode.OpenOrCreate, FileAccess.Write))
                                {
                                    fs.Position = offset;
                                    while (true)
                                    {
                                        //кол-во реально прочитанных байт (буфер может быть больше,
                                        //чем на последней итерации цикла "do while" реально прочитали)
                                        int readed = await source.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false);
                                        if (readed == 0)
                                        {
                                            break;
                                        }

                                        await fs.WriteAsync(buffer, 0, readed).ConfigureAwait(false);
                                        downloadedBytesLength += readed;
                                        lastPercentValue       = UpdateProgress(downloadedBytesLength, updateFile.FileName, patch.PatchLength, lastPercentValue, updateFile.FileSize, fs.Length);
                                    }
                                }
                            }
                            else if (updateFile.FileName != "d3dcompiler_47.dll")
                            {
                                using (FileStream fs = new FileStream(_rootDirectory + '/' + updateFile.FileName, FileMode.OpenOrCreate, FileAccess.Write))
                                {
                                    fs.Position = offset;
                                    while (true)
                                    {
                                        //кол-во реально прочитанных байт (буфер может быть больше,
                                        //чем на последней итерации цикла "do while" реально прочитали)
                                        int readed = await source.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false);
                                        if (readed == 0)
                                        {
                                            break;
                                        }

                                        await fs.WriteAsync(buffer, 0, readed).ConfigureAwait(false);
                                        downloadedBytesLength += readed;
                                        lastPercentValue       = UpdateProgress(downloadedBytesLength, updateFile.FileName, patch.PatchLength, lastPercentValue, updateFile.FileSize, fs.Length);
                                    }
                                }
                            }

                            downloaded.Add(Tuple.Create(tempFile, updateFile));
                        }
                    }
                }

                /*
                 * foreach (Tuple<string, UpdateFile> tuple in downloaded) //<путь к временному файлу, соответствующее описание этому файлу>
                 * {
                 *  UpdateFile updateFile = tuple.Item2;
                 *  string tempFile = tuple.Item1;
                 *  string directory = string.Empty;
                 *
                 *  if (updateFile.FolderName == Path.Combine(AppDomain.CurrentDomain.BaseDirectory))
                 *  {   // ../Data
                 *      directory = Path.Combine(_rootDirectory);
                 *  }
                 *  if (!Directory.Exists(directory))
                 *  {
                 *      Directory.CreateDirectory(directory);
                 *  }
                 *
                 *  string file = Path.Combine(directory, updateFile.FileName);
                 *  if (File.Exists(file))
                 *  {
                 *      File.Delete(file);
                 *  }
                 *  File.Move(tempFile, file);
                 * }
                 */

                if (_pidFromServer != null)
                {
                    using (StreamWriter writer = File.CreateText(_localPidFile))
                    {
                        await writer.WriteAsync(_pidFromServer.ToString()).ConfigureAwait(false);
                        writer.Dispose();
                    }
                }

                OnUpdateStateChanged(UpdateState.Completed);
                OnUpdateStateChanged(UpdateState.None);
            });
        }
 public override string ToString()
 {
     return(Pid.ToString() + "." + Seq.ToString());
 }
예제 #16
0
        public void Update()
        {
            if (_currentState != UpdateState.None)
            {
                OnUpdateStateChanged(_currentState);
                return;
            }
            //Чтобы максимально быстро сменить состояние не дав выполнить проверку до того, как состояние изменится из другого потока
            _currentState = UpdateState.Started;

            //Запускаем выполнение кода в потоке из пула потоков.
            ThreadPool.QueueUserWorkItem(unused =>
            {
                //Уведомляем подписчиков, что обновление запущено.
                OnUpdateStateChanged(UpdateState.Started);
                string patchList = _webClient.DownloadString(_serverPatchListFile);
                var patch        = new PatchInfo(patchList);

                //Получить путь до папки с данными обновляемого клиента (папка, в которой находится апдейтер/лаунчер и данные для обновления).
                string dataDirectory = Path.Combine(_rootDirectory);
                if (!Directory.Exists(dataDirectory))
                {
                    Directory.CreateDirectory(dataDirectory);
                }

                //Получить все mpq файлы, находящиеся на локальном диске (включая все подпапки).
                string[] localFiles = Directory.GetFiles(dataDirectory, ".", SearchOption.AllDirectories);

                //Отфильтровать оставив только те локальные файлы, имена которых совпадают с именами файлов в патче
                Dictionary <string, FileInfo> matchingFiles =
                    localFiles.Where(                                  //Отфильтровать, где
                        f => patch.UpdateFiles.Any(                    //локальный файл f совпадает
                            pf => pf.FileName == Path.GetFileName(f))) //с хоть одним файлом в патче по имени
                    .Select(mf => new FileInfo(mf))                    //Каждый элемент коллекции проецировать в новый тип данных
                    .ToDictionary(info => info.Name);                  //отфильтрованную коллекцию конвертировать в словарь с ключом "имя файла"

                //последнее значение прогресса выполнения в процентах
                int lastPercentValue = 0;

                //Создаём временную папку, если не существует. Папка, в которую будем качать новые файлы обновления
                if (!Directory.Exists(TempFolder))
                {
                    Directory.CreateDirectory(TempFolder);
                }

                //Создаём сопоставимый список скачанных файлов с информацией об этом файле
                //ранее полученной с сервера (из патч листа)
                var downloaded = new List <Tuple <string, UpdateFile> >(patch.UpdateFiles.Length);

                //создаём переменную счётчик кол-ва скачанных байт всех файлов
                long downloadedBytesLength = 0L;
                //скачиваем все файлы
                for (int i = 0; i < patch.UpdateFiles.Length; i++)
                {
                    UpdateFile updateFile = patch.UpdateFiles[i];

                    string tempFile = Path.Combine(TempFolder, updateFile.FileName);

                    if (matchingFiles.ContainsKey(updateFile.FileName))
                    {
                        FileInfo file        = matchingFiles[updateFile.FileName];
                        string localFileHash = HashHelper.GetMD5HashOfFile(file.FullName);
                        if (localFileHash == updateFile.Hash)
                        {
                            //то к сумме скачанных байтов добавляем его размер,
                            //чтобы далее правильно считался прогресс выполнения скачивания в процентах
                            downloadedBytesLength += updateFile.FileSize;
                            //lastPercentValue = UpdateProgress(downloadedBytesLength, updateFile.FileName, patch.PatchLength, lastPercentValue, updateFile.FileSize);
                            continue; //выходим из текущей итерации цикла и цикл переходит к следующей
                        }
                    }

                    long offset = 0L;
                    //Если файл существует (был скачан ранее) и скачан полностью (хэш совпадает с хэшем из патч листа)
                    if (File.Exists(tempFile))
                    {
                        string hash = HashHelper.GetMD5HashOfFile(tempFile);
                        if (hash == updateFile.Hash) //сверяем хэши
                        {
                            //то к сумме скачанных байтов добавляем его размер,
                            //чтобы далее правильно считался прогресс выполнения скачивания в процентах
                            downloadedBytesLength += updateFile.FileSize;
                            downloaded.Add(Tuple.Create(tempFile, updateFile));
                            lastPercentValue = UpdateProgress(downloadedBytesLength, updateFile.FileName, patch.PatchLength, lastPercentValue, updateFile.FileSize);
                            continue; //выходим из текущей итерации цикла и цикл переходим к следующей
                        }
                        /*-------------   докачка-------------------------*/
                        else
                        {
                            var fileInfo           = new FileInfo(tempFile);
                            offset                 = fileInfo.Length; //Сколько скачано байт. На сколько надо сдвинуть при скачивании.
                            downloadedBytesLength += fileInfo.Length; //теперь прогресс будет правильно считаться
                        }
                    }

                    Uri url = new Uri(UrlHelper.Combine(_serverFilesRoot, updateFile.FileName));
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

                    if (offset > 0L) //L - значит, что литерал 0 типа long или Int64, что одно и тоже. Без L будет типа int.
                    {
                        request.AddRange(offset);
                    }
                    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                    {
                        //if (response.StatusCode != HttpStatusCode.OK)
                        //{
                        //    string message = String.Format("POST failed. Received HTTP {0}",
                        //    response.StatusCode);
                        //   // throw new ApplicationException(message);
                        //    MessageBox.Show(message);
                        //}

                        Stream source = response.GetResponseStream();
                        if (source != null)
                        {
                            // пытаемся создать папки, которые отсутствуют из пути
                            var address      = new Uri(Path.Combine(_rootDirectory + '/' + updateFile.FileName), UriKind.Absolute);
                            string directory = Path.GetDirectoryName(address.LocalPath);
                            Debug.Assert(directory != null);
                            if (!Directory.Exists(directory))
                            {
                                Directory.CreateDirectory(directory);
                            }

                            byte[] buffer = new byte[400]; //102400 байт = 100 Килобайт  (400)
                            using (FileStream fs = new FileStream(_rootDirectory + '/' + updateFile.FileName, FileMode.OpenOrCreate, FileAccess.Write))
                            {
                                fs.Position = offset;
                                while (true)
                                {
                                    //кол-во реально прочитанных байт (буфер может быть больше,
                                    //чем на последней итерации цикла "do while" реально прочитали)
                                    int readed = source.Read(buffer, 0, buffer.Length);
                                    if (readed == 0)
                                    {
                                        break;
                                    }

                                    fs.Write(buffer, 0, readed);
                                    downloadedBytesLength += readed;
                                    lastPercentValue       = UpdateProgress(downloadedBytesLength, updateFile.FileName, patch.PatchLength, lastPercentValue, updateFile.FileSize, fs.Length);
                                }
                            }

                            downloaded.Add(Tuple.Create(tempFile, updateFile));
                        }
                    }
                }


                //foreach (Tuple<string, UpdateFile> tuple in downloaded) //<путь к временному файлу, соответствующее описание этому файлу>
                //{
                //    UpdateFile updateFile = tuple.Item2;
                //    string tempFile = tuple.Item1;
                //    string directory = string.Empty;


                //    if (updateFile.FolderName == Path.Combine(AppDomain.CurrentDomain.BaseDirectory))
                //    {   // ../Data
                //        directory = Path.Combine(_rootDirectory);
                //    }
                //    if (!Directory.Exists(directory))
                //    {
                //        Directory.CreateDirectory(directory);
                //    }


                //    string file = Path.Combine(directory, updateFile.FileName);
                //    if (File.Exists(file))
                //    {
                //        Debug.WriteLine("Файл удалён:{0}{1}", Environment.NewLine, file);
                //        File.Delete(file);
                //    }
                //    Debug.WriteLine("Файл перемещён{0}Из: {1}{0}в: {2}", Environment.NewLine, tempFile, file);
                //    File.Move(tempFile, file);
                //}

                if (_pidFromServer != null)
                {
                    using (StreamWriter writer = File.CreateText(_localPidFile))
                    {
                        writer.Write(_pidFromServer.ToString());
                    }
                }

                OnUpdateStateChanged(UpdateState.Completed);
                OnUpdateStateChanged(UpdateState.None);
            });
        }
예제 #17
0
 public override string ToString()
 {
     return($"taakId: {TaakId.ToString()} pid: {Pid.ToString()} uur: {Uur} functie: {Functie.ToString()}");
 }
 public override string ToString()
 {
     return(Pid.ToString() + "\t\t" + firstName + "\t\t" + lastName + "\t\t" + address.zipcode + "\t\t" + address.city + "\t\t" + phone.number);
 }
예제 #19
0
 public override string ToString()
 {
     return(string.Join("; ", new[] { Method, ExecutingApp, Machine, Pid.ToString(), InsertedOn.ToString() }));
 }
예제 #20
0
 public override string ToString()
 {
     return($"pid: {Pid.ToString()} naam: {Naam} ");
 }
예제 #21
0
        private bool NetworkProviders()
        {
            UInt64 Pid;
            string timestart        = LogonTime.ToString("s");
            string StartQueryString =
                "<QueryList>\n" +
                "  <Query Id=\"0\" Path=\"Security\">\n" +
                "    <Select Path=\"Security\">\n" +
                "        *[System[(EventID=4688) and  TimeCreated[@SystemTime &gt; '" + timestart + "']]]\n" +
                "        and *[EventData[Data[@Name = 'ProcessId'] and (Data = \"0x" + WinlogonPid.ToString("X") + "\")]]\n" +
                "        and *[EventData[Data[@Name = 'NewProcessName'] and(Data = \"C:\\Windows\\System32\\mpnotify.exe\")]]\n" +
                "    </Select>\n" +
                "  </Query>\n" +
                "</QueryList>";

            EventLogQuery  eventsQuery = new EventLogQuery("Security", PathType.FilePath, StartQueryString);
            EventLogReader logReader   = new EventLogReader(eventsQuery);

            EventRecord e = logReader.ReadEvent();

            if (e == null)
            {
                return(false);
            }

            npStart = (DateTime)e.TimeCreated;
            Pid     = (UInt64)e.Properties[4].Value;
            string EndQueryString =
                "<QueryList>\n" +
                "  <Query Id=\"0\" Path=\"Security\">\n" +
                "    <Select Path=\"Security\">\n" +
                "        *[System[(EventID=4689) and  TimeCreated[@SystemTime &gt; '" + npStart.ToString("s") + "']]]\n" +
                "        and *[EventData[Data[@Name = 'ProcessId'] and (Data = \"0x" + Pid.ToString("X") + "\")]]\n" +
                "        and *[EventData[Data[@Name = 'ProcessName'] and(Data = \"C:\\Windows\\System32\\mpnotify.exe\")]]\n" +
                "    </Select>\n" +
                "  </Query>\n" +
                "</QueryList>\n";

            eventsQuery = new EventLogQuery("Security", PathType.FilePath, EndQueryString);
            logReader   = new EventLogReader(eventsQuery);
            e           = logReader.ReadEvent();
            if (e == null)
            {
                return(false);
            }

            npEnd = (DateTime)e.TimeCreated;
            return(true);
        }
예제 #22
0
 /// <summary>
 /// Short string general information about this device.
 /// </summary>
 public override string ToString()
 {
     return($"V/PID: {Vid.ToString("X4")}-{Pid.ToString("X4")} [{Manufacturer.Truncate(25)}] SN: {Serial}"
            .Truncate(Const.DEV_STR_MAX_LEN));
 }