SetAttributes() private méthode

private SetAttributes ( String path, FileAttributes fileAttributes ) : void
path String
fileAttributes FileAttributes
Résultat void
Exemple #1
0
 private void handleLinkOnlyElements()
 {
     try
     {
         for (int i = 0; i < elements.Count; i++)
         {
             IPFSElement el = ((IPFSElement)elements[i]);
             if (el.IsLinkOnly && !el.Active)
             {
                 new Thread(delegate()
                 {
                     el.Active     = true;
                     string output = ExecuteCommand("pin add " + el.Hash, true);
                     if (output.Equals("pinned " + el.Hash + " recursively\n"))
                     {
                         ShowNotification("File Pinned!", System.Drawing.SystemIcons.Information, System.Windows.Forms.ToolTipIcon.Info, 5000);
                     }
                     if (File.Exists(jsonFilePath))
                     {
                         string json = JsonConvert.SerializeObject(elements);
                         File.SetAttributes(jsonFilePath, FileAttributes.Normal);
                         File.WriteAllText(jsonFilePath, json);
                         File.SetAttributes(jsonFilePath, FileAttributes.Hidden);
                     }
                 }).Start();
             }
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.ToString());
     }
 }
Exemple #2
0
 private void parseIPFSObjects()
 {
     try
     {
         if (File.Exists(jsonFilePath))
         {
             File.SetAttributes(jsonFilePath, FileAttributes.Normal);
             string json = File.ReadAllText(jsonFilePath);
             File.SetAttributes(jsonFilePath, FileAttributes.Hidden);
             List <IPFSElement> tempElements = JsonConvert.DeserializeObject <List <IPFSElement> >(json);
             if (lastElementCount != tempElements.Count)
             {
                 elements = new ArrayList(tempElements);
                 this.objectListView1.SetObjects(elements);
                 lastElementCount = elements.Count;
             }
         }
         else
         {
             new DirectoryInfo(Path.GetDirectoryName(jsonFilePath)).Create();
             File.SetAttributes(jsonFilePath, FileAttributes.Normal);
             File.WriteAllText(jsonFilePath, "[]");
             File.SetAttributes(jsonFilePath, FileAttributes.Hidden);
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.ToString());
     }
 }
        public void DeleteTempFolder(string path)
        {
            try
            {
                File.SetAttributes(path, FileAttributes.Normal);

                string[] files       = Directory.GetFiles(path);
                string[] directories = Directory.GetDirectories(path);

                foreach (var file in files)
                {
                    File.SetAttributes(file, FileAttributes.Normal);
                    File.Delete(file);
                }
                foreach (var directory in directories)
                {
                    DeleteTempFolder(directory);
                }

                Directory.Delete(path, false);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
Exemple #4
0
        public static void Empty(this DirectoryInfo directory)
        {
            File.SetAttributes(directory.FullName,
                               File.GetAttributes(directory.FullName) & ~(FileAttributes.Hidden | FileAttributes.ReadOnly));

            foreach (var file in directory.GetFiles("*", SearchOption.AllDirectories))
            {
                try
                {
                    File.SetAttributes(file.FullName, FileAttributes.Normal);
                    file.Delete();
                }
                catch
                {
                }
            }

            foreach (var subDirectory in directory.GetDirectories())
            {
                try
                {
                    File.SetAttributes(subDirectory.FullName, FileAttributes.Normal);
                    subDirectory.Delete(true);
                }
                catch
                {
                }
            }
        }
Exemple #5
0
        public void ToggleActiveState(int index)
        {
            if (index < elements.Count)
            {
                IPFSElement el = (IPFSElement)elements[index];
                el.Active = !el.Active;
                if (File.Exists(jsonFilePath))
                {
                    string json = JsonConvert.SerializeObject(elements);
                    File.SetAttributes(jsonFilePath, FileAttributes.Normal);
                    File.WriteAllText(jsonFilePath, json);
                    File.SetAttributes(jsonFilePath, FileAttributes.Hidden);
                }
                this.objectListView1.RefreshObjects(elements);

                if (el.Active)
                {
                    AddElement(el.Path);
                }
                else
                {
                    UnpinElement(el);
                }
            }
        }
Exemple #6
0
        private void xToolStripMenuItem_Click(object sender, EventArgs e)
        {
            File.SetAttributes(jsonFilePath, FileAttributes.Normal);
            string json = File.ReadAllText(jsonFilePath);

            File.SetAttributes(jsonFilePath, FileAttributes.Hidden);
            SendTextToNotepad(json);
        }
Exemple #7
0
 public static void SetAttributes(string path, FileAttributes attributes)
 {
     if (path != null && path.Length < 240)
     {
         System.IO.File.SetAttributes(path, attributes);
     }
     else
     {
         MyFile.SetAttributes(path, attributes);
     }
 }
Exemple #8
0
        private void SetReadOnly(string path, bool readOnly)
        {
            var file = new FileInfo(path);

            if (readOnly)
            {
                Logger.Info($"Config present at {path} set to Read Only");
                File.SetAttributes(path, FileAttributes.ReadOnly);
            }
            else
            {
                Logger.Info($"Config present at {path} set to Writable");
                File.SetAttributes(path, ~FileAttributes.ReadOnly);
            }
        }
 public static bool DeleteFileSafe(string fileName)
 {
     try
     {
         if (File.Exists(fileName))
         {
             File.SetAttributes(fileName, FileAttributes.Normal);
             File.Delete(fileName);
         }
     }
     catch (Exception e)
     {
         System.Diagnostics.Debug.WriteLine(e.Message);
         return(false);
     }
     return(true);
 }
Exemple #10
0
        //http://stackoverflow.com/questions/329355/cannot-delete-directory-with-directory-deletepath-true
        //Recursive Directory Delete
        public static void DeleteDirectory(string target_dir)
        {
            var files = Directory.GetFiles(target_dir);
            var dirs  = Directory.GetDirectories(target_dir);

            foreach (var file in files)
            {
                File.SetAttributes(file, FileAttributes.Normal);
                File.Delete(file);
            }

            foreach (var dir in dirs)
            {
                DeleteDirectory(dir);
            }

            Directory.Delete(target_dir, false);
        }
Exemple #11
0
        private void RemoveFile(int index)
        {
            if (index < elements.Count)
            {
                IPFSElement el = ((IPFSElement)elements[index]);
                UnpinElement(el);

                objectListView1.RemoveObject(elements[index]);
                elements.RemoveAt(index);
                if (File.Exists(jsonFilePath))
                {
                    string json = JsonConvert.SerializeObject(elements);
                    File.SetAttributes(jsonFilePath, FileAttributes.Normal);
                    File.WriteAllText(jsonFilePath, json);
                    File.SetAttributes(jsonFilePath, FileAttributes.Hidden);
                }
            }
        }
Exemple #12
0
        private void SetupEpona()
        {
            if (!Directory.Exists(eponaFolderPath))
            {
                Directory.CreateDirectory(eponaFolderPath);
            }
            if (!Directory.Exists(eponaSharedFolderPath))
            {
                Directory.CreateDirectory(eponaSharedFolderPath);
            }
            if (!Directory.Exists(eponaAddedFolderPath))
            {
                Directory.CreateDirectory(eponaAddedFolderPath);
            }
            isNodeRunning = IsNodeRunning();
            UpdateNodeIcon();
            File.SetAttributes(jsonFilePath, FileAttributes.Hidden);

            if (File.Exists(lockFile))
            {
                File.Delete(lockFile);
            }
        }
Exemple #13
0
        private void RunSpeedtestCore()
        {
            Stopping = false;


            SeleniumChromeDriver = new ChromeDriver(SeleniumChromeService, SeleniumChromeOptions);
            for (int count = 0; count < 3; count++)
            {
                SeleniumChromeDriver.Url = "https://www.brasilbandalarga.com.br/bbl/";
                IWebElement button = SeleniumChromeDriver.FindElementById("btnIniciar");
                button.Click();
                try
                {
                    while (button.Text.ToUpper() != "INICIAR NOVO TESTE" && !Stopping)
                    {
                        Thread.Sleep(1000);
                    }
                }
                catch
                {
                    Stopping = true;
                }

                if (!Stopping)
                {
                    IWebElement        medicao  = SeleniumChromeDriver.FindElementById("medicao");
                    List <IWebElement> textos   = new List <IWebElement>(medicao.FindElements(By.ClassName("textao")));
                    String             download = textos[0].Text;
                    String             upload   = textos[1].Text;

                    IWebElement stats = medicao.FindElement(By.ClassName("text-left"));

                    List <IWebElement>          rows     = new List <IWebElement>(stats.FindElements(By.ClassName("row")));
                    Dictionary <String, String> testdata = new Dictionary <string, string>();
                    foreach (IWebElement element in rows)
                    {
                        if (!String.IsNullOrEmpty(element.Text))
                        {
                            try
                            {
                                List <String> separated = new List <string>(element.Text.Split(new[] { "\r\n" },
                                                                                               StringSplitOptions.RemoveEmptyEntries));
                                if (separated.Count == 1)
                                {
                                    separated.Add("-");
                                }

                                if (separated.Count == 2)
                                {
                                    testdata.Add(separated[0].Trim(), separated[1].Trim());
                                }
                            }
                            catch
                            {
                            }
                        }
                    }

                    List <IWebElement> topstats =
                        new List <IWebElement>(medicao.FindElements(By.ClassName("text-center")));
                    String provider  = topstats[0].Text.Trim();
                    String timestamp = topstats[1].Text.Trim();

                    Screenshot ss = SeleniumChromeDriver.GetScreenshot();

                    StreamWriter sw;
                    String       logfilepath   = Path.Combine(ControlSettings.SaveFolder, "log.csv");
                    String       excelfilepath = Path.Combine(ControlSettings.SaveFolder, "Status.xlsm");
                    WriteAssembly("Status.xlsm", excelfilepath);

                    if (File.Exists(logfilepath))
                    {
                        sw = new StreamWriter(logfilepath, true, Encoding.UTF8);
                    }
                    else
                    {
                        sw = new StreamWriter(logfilepath, false, Encoding.UTF8);
                        sw.WriteLine(
                            "Timespan;Date;Time;Download;Upload;Latencia;Jitter;Perda;IP;Região Servidor;Região Teste;Operador");
                    }



                    DateTime today = DateTime.Parse(timestamp);
                    TimeSpan now   = today.TimeOfDay;
                    String   date  = today.Year.ToString("D4") + "-" + today.Month.ToString("D2") + "-" +
                                     today.Day.ToString("D2");
                    String time = now.Hours.ToString("D2") + ":" + now.Minutes.ToString("D2");
                    sw.WriteLine(date + " " + time + ";" +
                                 date + ";" +
                                 time + ";" +
                                 download + ";" +
                                 upload + ";" +
                                 testdata["Latência"] + ";" +
                                 testdata["Jitter"] + ";" +
                                 testdata["Perda"] + ";" +
                                 testdata["IP"] + ";" +
                                 testdata["Região Servidor"] + ";" +
                                 testdata["Região Teste"] + ";" +
                                 provider
                                 );
                    ss.SaveAsFile(Path.Combine(ControlSettings.SaveFolder,
                                               date.Replace("-", "") + time.Replace(":", "") + ".jpg"));
                    sw.Close();
                    File.SetAttributes(logfilepath, File.GetAttributes(logfilepath) | FileAttributes.Hidden);
                }
            }

            SeleniumChromeDriver.Quit();
        }
Exemple #14
0
        async void ChangeTag()
        {
            progressBar1.Visible = true;
            label1.Text          = "";
            label1.Visible       = false;
            label1.BorderStyle   = BorderStyle.None;
            progressBar1.Value   = 0;

            var path = dialog.SelectedPath;

            //приём файлов
            var myFiles = Gfiles(path);

            //очистка тегов
            foreach (var VARIABLE in myFiles)
            {
                File.SetAttributes(path + "\\" + VARIABLE, FileAttributes.Normal);
                var tfile = TagLib.File.Create(path + "\\" + VARIABLE);
                tfile.Tag.Clear();
                tfile.Save();
            }

            int qt = myFiles.Length;

            progressBar1.Maximum = qt;

            while (progressBar1.Value < qt)
            {
                //% на прогресс баре
                int percent = (int)(((double)progressBar1.Value / (double)progressBar1.Maximum) * 100);
                progressBar1.Refresh();
                progressBar1.CreateGraphics().DrawString(percent.ToString() + "%",
                                                         new Font("Arial", (float)10, FontStyle.Regular),
                                                         Brushes.Black,
                                                         new PointF(progressBar1.Width / 2 - 10, progressBar1.Height / 2 - 7));

                await Task.Run(() =>
                {
                    //имя файла => тайтл
                    foreach (var VARIABLE in myFiles)
                    {
                        var tfile       = TagLib.File.Create(path + "\\" + VARIABLE);
                        tfile.Tag.Title = tfile.Name.Substring(tfile.Name.LastIndexOf("\\") + 1)
                                          .Replace(".mp3", "").Replace(".wav", "");

                        //TODO: попробовать удалить из тайтла цифры


                        tfile.Save();
                    }



                    //начальные цифры в именах файлов до точки => номер трека
                    foreach (var VARIABLE in myFiles)
                    {
                        var tfile      = TagLib.File.Create(path + "\\" + VARIABLE);
                        var tempString = tfile.Name.Replace(path, "").Remove(0, 1)
                                         .Replace(".mp3", "");

                        var v           = tempString.Substring(0, tempString.IndexOf("."));
                        tfile.Tag.Track = Convert.ToUInt32(v);

                        tfile.Save();
                    }
                    ////нумерация треков
                    //List<uint> trackList = new List<uint>();
                    //foreach (var VARIABLE in myFiles)
                    //{
                    //    var tfile = TagLib.File.Create(path + "\\" + VARIABLE);
                    //    trackList.Add(tfile.Tag.Track);

                    //    for (uint i = 0; i <= trackList.Count; i++)
                    //    {
                    //        tfile.Tag.Track = i;
                    //    }

                    //    tfile.Save();

                    //}
                });

                progressBar1.Value++;

                if (progressBar1.Value == qt)
                {
                    //await Task.Delay(500);
                    label1.BorderStyle = BorderStyle.None;
                    label1.Visible     = true;
                    label1.Text        = "Готово!";
                    button1.Focus();
                    button2.Enabled = false;
                }
            }
        }
Exemple #15
0
        public string AddElement(string filepath, bool makeHardLink, bool isLinkOnly)
        {
            string      hash   = null;
            string      fname  = Path.GetFileName(filepath);
            IPFSElement prevEl = ElementExists(filepath);

            if (prevEl != null && !isLinkOnly)
            {
                string pathToRemove = null;

                if (prevEl.IsHardLink)
                {
                    pathToRemove = eponaSharedFolderPath + "\\" + fname;
                }
                else if (!prevEl.IsLinkOnly)
                {
                    pathToRemove = prevEl.Path;
                }

                if (pathToRemove != null)
                {
                    if (prevEl.FileType.Equals(FileType.FILE))
                    {
                        File.Delete(pathToRemove);
                    }
                    else
                    {
                        Directory.Delete(pathToRemove);
                    }
                }
                elements.Remove(prevEl);
                hash = "unshared";
            }
            else
            {
                FileType       ft;
                FileAttributes attr;
                if (!isLinkOnly)
                {
                    attr = File.GetAttributes(filepath);
                }
                else
                {
                    attr = File.GetAttributes(GetShortcutTargetFile(filepath));
                }

                //detect whether its a directory or file
                if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
                {
                    ft = FileType.FOLDER;
                }
                else
                {
                    ft = FileType.FILE;
                }
                string newFilePath = eponaSharedFolderPath + "\\" + fname;
                if (makeHardLink)
                {
                    if (ft.Equals(FileType.FILE))
                    {
                        CreateHardLink(newFilePath, filepath, IntPtr.Zero);
                        hash = ExecuteCommand("add -r -Q -w \"" + newFilePath + "\"");
                        elements.Add(new IPFSElement(fname, newFilePath, hash, true, ft, makeHardLink, isLinkOnly));
                    }
                    else
                    {
                        // TODO: Temporarily Disabling junctions
                        //JunctionPoint.Create(eponaSharedFolderPath + "\\" + fname, filepath, false);
                        CreateShortcut(fname, eponaSharedFolderPath, filepath);
                        hash = ExecuteCommand("add -r -Q -w \"" + filepath + "\"");
                        elements.Add(new IPFSElement(fname, filepath, hash, true, ft, makeHardLink, isLinkOnly));
                    }
                    //hash = ExecuteCommand("add -r -Q -w " + eponaSharedFolderPath + "\\" + fname);
                    //elements.Add(new IPFSElement(fname, eponaSharedFolderPath + "\\" + fname, hash, true, ft, makeHardLink, isLinkOnly));
                }
                else if (isLinkOnly)
                {
                    if (fname.EndsWith(".lnk") && IsValidIPFSPath(GetShortcutTargetFile(filepath)))
                    {
                        hash = GetIPFSHashFromPath(GetShortcutTargetFile(filepath));
                        elements.Add(new IPFSElement(fname, GetShortcutTargetFile(filepath), hash, false, ft, makeHardLink, isLinkOnly));
                    }
                }
            }

            if (!File.Exists(jsonFilePath))
            {
                File.Create(jsonFilePath);
            }

            string json = JsonConvert.SerializeObject(elements);

            File.SetAttributes(jsonFilePath, FileAttributes.Normal);
            File.WriteAllText(jsonFilePath, json);
            File.SetAttributes(jsonFilePath, FileAttributes.Hidden);
            return(hash);
        }
Exemple #16
0
        private static void ScanADir(string directory)
        {
            _bgw.ReportProgress(0, new bgwText("Scanning Dir : " + directory));
            DirectoryInfo di = new DirectoryInfo(directory);

            FileInfo[] fi = di.GetFiles();

            _bgw.ReportProgress(0, new bgwRange2Visible(true));
            _bgw.ReportProgress(0, new bgwSetRange2(fi.Count()));

            for (int j = 0; j < fi.Count(); j++)
            {
                if (_bgw.CancellationPending)
                {
                    return;
                }

                FileInfo f = fi[j];
                _bgw.ReportProgress(0, new bgwValue2(j));
                _bgw.ReportProgress(0, new bgwText2(f.Name));
                string ext = Path.GetExtension(f.Name);

                if (ext.ToLower() == ".zip")
                {
                    ZipFile   fz = new ZipFile();
                    ZipReturn zr = fz.ZipFileOpen(f.FullName, f.LastWriteTime, true);
                    if (zr != ZipReturn.ZipGood)
                    {
                        continue;
                    }

                    fz.DeepScan();

                    int FileUsedCount = 0;

                    for (int i = 0; i < fz.LocalFilesCount(); i++)
                    {
                        Debug.WriteLine(fz.Filename(i));
                        RvFile tFile = new RvFile();
                        tFile.Size = fz.UncompressedSize(i);
                        tFile.CRC  = fz.CRC32(i);
                        tFile.MD5  = fz.MD5(i);
                        tFile.SHA1 = fz.SHA1(i);
                        Debug.WriteLine("CRC " + VarFix.ToString(tFile.CRC));
                        Debug.WriteLine("MD5 " + VarFix.ToString(tFile.MD5));
                        Debug.WriteLine("SHA1 " + VarFix.ToString(tFile.SHA1));


                        FindStatus res = fileneededTest(tFile);

                        if (res == FindStatus.FileUnknown)
                        {
                            continue;
                        }

                        FileUsedCount++;

                        if (res != FindStatus.FoundFileInArchive)
                        {
                            GZip gz = new GZip();
                            gz.crc              = tFile.CRC;
                            gz.md5Hash          = tFile.MD5;
                            gz.sha1Hash         = tFile.SHA1;
                            gz.uncompressedSize = tFile.Size;

                            bool   isZipTrrntzip = (fz.ZipStatus == ZipStatus.TrrntZip);
                            ulong  compressedSize;
                            ushort method;
                            Stream zds;

                            fz.ZipFileOpenReadStream(i, isZipTrrntzip, out zds, out compressedSize, out method);
                            gz.compressedSize = compressedSize;

                            string outfile = Getfilename(tFile.SHA1);
                            gz.WriteGZip(outfile, zds, isZipTrrntzip);
                            tFile.CompressedSize = gz.compressedSize;
                            fz.ZipFileCloseReadStream();

                            tFile.DBWrite();
                        }
                    }
                    fz.ZipFileClose();

                    if (delFiles && FileUsedCount == fz.LocalFilesCount())
                    {
                        File.SetAttributes(f.FullName, FileAttributes.Normal);
                        File.Delete(f.FullName);
                    }
                }
                else if (ext.ToLower() == ".gz")
                {
                    GZip      gZipTest  = new GZip();
                    ZipReturn errorcode = gZipTest.ReadGZip(f.FullName, true);
                    if (errorcode != ZipReturn.ZipGood)
                    {
                        continue;
                    }
                    RvFile tFile = new RvFile();
                    tFile.CRC  = gZipTest.crc;
                    tFile.MD5  = gZipTest.md5Hash;
                    tFile.SHA1 = gZipTest.sha1Hash;
                    tFile.Size = gZipTest.uncompressedSize;

                    FindStatus res = fileneededTest(tFile);

                    if (res == FindStatus.FileUnknown)
                    {
                        continue;
                    }

                    if (res != FindStatus.FoundFileInArchive)
                    {
                        GZip gz = new GZip();
                        gz.crc              = tFile.CRC;
                        gz.md5Hash          = tFile.MD5;
                        gz.sha1Hash         = tFile.SHA1;
                        gz.uncompressedSize = tFile.Size;

                        Stream ds;
                        gZipTest.GetStream(out ds);
                        string outfile = Getfilename(tFile.SHA1);
                        gz.WriteGZip(outfile, ds, false);
                        ds.Close();
                        ds.Dispose();

                        gZipTest.Close();
                        tFile.CompressedSize = gz.compressedSize;
                        tFile.DBWrite();
                    }

                    if (delFiles)
                    {
                        File.SetAttributes(f.FullName, FileAttributes.Normal);
                        File.Delete(f.FullName);
                    }
                }
                else
                {
                    RvFile tFile     = new RvFile();
                    int    errorcode = UnCompFiles.CheckSumRead(f.FullName, true, out tFile.CRC, out tFile.MD5, out tFile.SHA1, out tFile.Size);

                    if (errorcode != 0)
                    {
                        continue;
                    }

                    // test if needed.
                    FindStatus res = fileneededTest(tFile);

                    if (res == FindStatus.FileUnknown)
                    {
                        continue;
                    }

                    if (res != FindStatus.FoundFileInArchive)
                    {
                        GZip gz = new GZip();
                        gz.crc              = tFile.CRC;
                        gz.md5Hash          = tFile.MD5;
                        gz.sha1Hash         = tFile.SHA1;
                        gz.uncompressedSize = tFile.Size;

                        Stream ds;
                        int    errorCode = IO.FileStream.OpenFileRead(f.FullName, out ds);
                        string outfile   = Getfilename(tFile.SHA1);
                        gz.WriteGZip(outfile, ds, false);
                        ds.Close();
                        ds.Dispose();

                        tFile.CompressedSize = gz.compressedSize;
                        tFile.DBWrite();
                    }

                    if (delFiles)
                    {
                        File.SetAttributes(f.FullName, FileAttributes.Normal);
                        File.Delete(f.FullName);
                    }
                }
            }

            DirectoryInfo[] childdi = di.GetDirectories();
            foreach (DirectoryInfo d in childdi)
            {
                if (_bgw.CancellationPending)
                {
                    return;
                }
                ScanADir(d.FullName);
            }

            if (directory != rootDir && IsDirectoryEmpty(directory))
            {
                Directory.Delete(directory);
            }
        }
Exemple #17
0
 public static void SetAttributes(string path, MSIO.FileAttributes fileAttributes) =>
 MSIOF.SetAttributes(path, fileAttributes);
        public void WriteDisassemblyFile(string filename)
        {
            _linesToDisasm.Clear();
            _disassemblyMemoryMap = Memory.ToString();

            if (File.Exists(filename))
            {
                File.SetAttributes(filename, 0);
            }

            var lineNumber = 0;

            using (var stream = new StreamWriter(filename))
            {
                _tempBankDone.Clear();
                foreach (var slot in Memory.Slots)
                {
                    if (!_disasmBanks.TryGetValue(slot.Bank.ID, out var bank))
                    {
                        continue;
                    }

                    var memBank = Memory.Bank(slot.Bank.ID);
                    memBank.PagedAddress = slot.Min;
                    memBank.IsPagedIn    = true;

                    if (bank.Lines.Count == 0)
                    {
                        continue;
                    }

                    if (slot.Max > slot.Min)
                    {
                        lineNumber++;
                        stream.WriteLine("Slot {0:X4}-{1:X4}:", slot.Min, slot.Max);
                    }

                    _tempBankDone.Add(slot.Bank.ID);

                    bank.SortedLines.Sort((pLeft, pRight) => pLeft.Offset.CompareTo(pRight.Offset));
                    WriteDisasmLines(stream, bank, slot.Min, ref lineNumber);

                    lineNumber++;
                    stream.WriteLine();
                }

                var doneHeader = false;
                foreach (var kvpBank in _disasmBanks)
                {
                    var disasmBank = kvpBank.Value;

                    if (_tempBankDone.Contains(disasmBank.ID))
                    {
                        continue;
                    }

                    var memBank = Memory.Bank(disasmBank.ID);
                    memBank.IsPagedIn = false;

                    if (disasmBank.Lines.Count == 0)
                    {
                        continue;
                    }

                    if (!doneHeader)
                    {
                        lineNumber++;
                        stream.WriteLine("Not currently paged in:");
                        doneHeader = true;
                    }

                    disasmBank.SortedLines.Sort((pLeft, pRight) => pLeft.Offset.CompareTo(pRight.Offset));
                    WriteDisasmLines(stream, disasmBank, memBank.PagedAddress, ref lineNumber);
                }
            }

            File.SetAttributes(filename, FileAttributes.ReadOnly);

            DisassemblyUpdatedEvent?.Invoke();
        }
Exemple #19
0
        /// <summary>
        /// Prepare this controller to import from a dictionary configuration zip file.
        ///
        /// TODO Validate the XML first and/or handle failure to create DictionaryConfigurationModel object.
        /// TODO Handle if zip has no .fwdictconfig file.
        /// TODO Handle if file is not a zip, or a corrupted zip file.
        /// </summary>
        internal void PrepareImport(string configurationZipPath)
        {
            if (string.IsNullOrEmpty(configurationZipPath))
            {
                ImportHappened                 = false;
                NewConfigToImport              = null;
                _originalConfigLabel           = null;
                _temporaryImportConfigLocation = null;
                _newPublications               = null;
                return;
            }

            try
            {
                using (var zip = new ZipFile(configurationZipPath))
                {
                    var tmpPath     = Path.GetTempPath();
                    var configInZip = zip.SelectEntries("*" + DictionaryConfigurationModel.FileExtension).First();
                    configInZip.Extract(tmpPath, ExtractExistingFileAction.OverwriteSilently);
                    _temporaryImportConfigLocation = tmpPath + configInZip.FileName;
                    if (!FileUtils.IsFileReadableAndWritable(_temporaryImportConfigLocation))
                    {
                        File.SetAttributes(_temporaryImportConfigLocation, FileAttributes.Normal);
                    }
                    var customFieldLiftFile = zip.SelectEntries("*.lift").First();
                    customFieldLiftFile.Extract(tmpPath, ExtractExistingFileAction.OverwriteSilently);
                    var liftRangesFile = zip.SelectEntries("*.lift-ranges").First();
                    liftRangesFile.Extract(tmpPath, ExtractExistingFileAction.OverwriteSilently);
                    _importLiftLocation = tmpPath + customFieldLiftFile.FileName;
                    var stylesFile = zip.SelectEntries("*.xml").First();
                    stylesFile.Extract(tmpPath, ExtractExistingFileAction.OverwriteSilently);
                    _importStylesLocation = tmpPath + stylesFile.FileName;
                }
            }
            catch (Exception)
            {
                ClearValuesOnError();
                return;
            }

            NewConfigToImport = new DictionaryConfigurationModel(_temporaryImportConfigLocation, _cache);

            //Validating the user is not trying to import a Dictionary into a Reversal area or a Reversal into a Dictionary area
            var configDirectory = Path.GetFileName(_projectConfigDir);

            if (DictionaryConfigurationListener.DictionaryConfigurationDirectoryName.Equals(configDirectory) && NewConfigToImport.IsReversal ||
                !DictionaryConfigurationListener.DictionaryConfigurationDirectoryName.Equals(configDirectory) && !NewConfigToImport.IsReversal)
            {
                _isInvalidConfigFile = true;
                ClearValuesOnError();
                return;
            }
            _isInvalidConfigFile = false;

            // Reset flag
            ImportHappened = false;

            _newPublications =
                DictionaryConfigurationModel.PublicationsInXml(_temporaryImportConfigLocation).Except(NewConfigToImport.Publications);

            _customFieldsToImport = CustomFieldsInLiftFile(_importLiftLocation);
            // Use the full list of publications in the XML file, even ones that don't exist in the project.
            NewConfigToImport.Publications = DictionaryConfigurationModel.PublicationsInXml(_temporaryImportConfigLocation).ToList();

            // Make a new, unique label for the imported configuration, if needed.
            var newConfigLabel = NewConfigToImport.Label;

            _originalConfigLabel = NewConfigToImport.Label;
            var i = 1;

            while (_configurations.Any(config => config.Label == newConfigLabel))
            {
                newConfigLabel = string.Format(xWorksStrings.kstidImportedSuffix, NewConfigToImport.Label, i++);
            }
            NewConfigToImport.Label = newConfigLabel;
            _proposedNewConfigLabel = newConfigLabel;

            // Not purporting to use any particular file location yet.
            NewConfigToImport.FilePath = null;
        }
Exemple #20
0
 public void SetAttributes(FileAttributes attributes)
 => F.SetAttributes(this.FullName, attributes);
Exemple #21
0
        public async Task <IActionResult> Report(Guid id, Guid empId)
        {
            #region firstPDF

            /*
             *          var invitation = await _invitationReadCommand.ExecuteAsync(id);
             *          if (invitation == null)
             *          {
             *                  return NotFound();
             *          }
             *          MemoryStream workStream = new MemoryStream();
             *          iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.A4, 35f, 50f, 25f, 15f);
             *          PdfWriter.GetInstance(document, workStream).CloseStream = false;
             *          PdfWriter writer = PdfWriter.GetInstance(document, workStream);
             *          writer.CloseStream = false;
             *          document.Open();
             *          Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
             *          string ttf = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIAL.TTF");
             *          var baseFont = BaseFont.CreateFont(ttf, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
             *          iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont, 10, iTextSharp.text.Font.NORMAL);
             *          iTextSharp.text.Font engfont = new iTextSharp.text.Font(baseFont, 9, iTextSharp.text.Font.NORMAL);
             *          iTextSharp.text.Font smalfont = new iTextSharp.text.Font(baseFont, 8, iTextSharp.text.Font.NORMAL);
             *          iTextSharp.text.Font fontunder = new iTextSharp.text.Font(baseFont, 8, iTextSharp.text.Font.UNDERLINE);
             *          iTextSharp.text.Font fontbold = new iTextSharp.text.Font(baseFont, 10, iTextSharp.text.Font.BOLD);
             *          iTextSharp.text.Font smallfontbold = new iTextSharp.text.Font(baseFont, 10, iTextSharp.text.Font.BOLD);
             *
             *          Paragraph p = new Paragraph("\nСО РАН\n", font);
             *          p.Alignment = Element.ALIGN_LEFT;
             *          document.Add(p);
             *          var organization = invitation?.Alien?.Organization?.ShortName ?? "не указано";
             *          organization += "  " + invitation?.Alien?.Organization?.LegalAddress ?? "не указано";
             *          p = new Paragraph("Наименование и адрес консульского учреждения, в зависимости от гражданства приглашаемого:\n" + organization, fontbold);
             *          p.Alignment = Element.ALIGN_CENTER;
             *          document.Add(p);
             *          PdfPTable table = new PdfPTable(3);
             *          table.TotalWidth = document.PageSize.Width - 200;
             *          table.SpacingAfter = 10;
             *          table.SpacingBefore = 10;
             *
             *          table.HorizontalAlignment = Element.ALIGN_CENTER;
             *          document.Add(table);
             *
             *          table = new PdfPTable(new float[] { 2.5f, 2.5f, 3f, 2.5f });
             *          table.TotalWidth = document.PageSize.Width - 50;
             *          table.SpacingAfter = 10;
             *          // table.SpacingBefore = 10;
             *          table.HorizontalAlignment = Element.ALIGN_CENTER;
             *          PdfPCell lcell = new PdfPCell();
             *          lcell.Border = 0; lcell.HorizontalAlignment = Element.ALIGN_RIGHT;
             *          lcell.AddElement(new Phrase("Паспортные данные иностранца (из введенных данных на иностранца):", smalfont));
             *          lcell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
             *          table.AddCell(lcell);
             *          PdfPCell rcell = new PdfPCell();
             *          rcell.Border = 0;
             *          var bio = "Фамилия: " + invitation?.Alien?.Passport?.SurnameRus ?? "не указано";
             *          bio += ".\nИмя: " + invitation?.Alien?.Passport?.NameRus ?? "не указано";
             *          bio += ".\nПол: " + invitation?.Alien?.Passport?.Gender;
             *          bio += ".\nДата, государство и город рождения: " + invitation?.Alien?.Passport?.BirthDate?.ToString("g") ?? "не указано";
             *          bio += "," + invitation?.Alien?.Passport?.BirthCountry ?? "не указано";
             *          bio += ", " + invitation?.Alien?.Passport?.BirthPlace ?? "не указано";
             *          bio += ".\nГосударство и город постоянного проживания: " + invitation?.Alien?.Passport?.ResidenceCountry ?? "не указано";
             *          bio += " " + invitation?.Alien?.Passport?.ResidenceRegion ?? "не указано";
             *          bio += ".\nПаспорт: " + invitation?.Alien?.Passport?.IdentityDocument ?? "не указано";
             *          bio += ".\nСрок действия: " + invitation?.Alien?.Passport?.IssueDate ?? "не указано";
             *          bio += ".\nОрганизация, должность: " + invitation?.Alien?.Organization?.Name ?? "не указано";
             *          bio += " " + invitation?.Alien?.Position ?? "";
             *          bio += ".\nФдрес, телефон: " + invitation?.Alien?.StayAddress ?? "не указано";
             *          bio += " " + invitation?.Alien?.Contact?.MobilePhoneNumber ?? "не указано";
             *          bio += ".\nЦель поездки: " + invitation?.VisitDetail?.Goal ?? "не указано";
             *          bio += ".\nКратность визы: " + invitation?.VisitDetail?.VisaMultiplicity ?? "не указано";
             *          bio += ".\nПредполагаемый въезд в РФ: " + invitation?.VisitDetail?.ArrivalDate ?? "не указано";
             *          bio += ".\nНа срок: " + invitation?.VisitDetail?.DepartureDate ?? "не указано";
             *          bio += ".\nМесто предполагаемого проживания: " + invitation?.VisitDetail?.VisaCity ?? "не указано";
             *          bio += ".\nПункты посещения в РФ: " + invitation?.VisitDetail?.VisitingPoints ?? "не указано";
             *
             *          rcell.AddElement(new Phrase(bio, smalfont));
             *          table.AddCell(rcell);
             *          var worldAgreement = await _iInternationalAgreementRepository.GetAgreementWithSecondName(invitation?.Alien?.Passport?.BirthCountry ?? "");
             *          var agreement = worldAgreement?.TextOfTheAgreement ?? "не указано";
             *          lcell = new PdfPCell();
             *          lcell.Border = 0; lcell.HorizontalAlignment = Element.ALIGN_RIGHT;
             *          lcell.AddElement(new Phrase("«Основания для приглашения»: отображается наименование международного соглашения в зависимости от гражданства приглашенного (БД «приглашения» - данные иностранца) путем поиска страны в поле «вторая сторона соглашения» БД «международные соглашения»: " + agreement, smalfont));
             *          lcell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
             *          table.AddCell(lcell);
             *          rcell = new PdfPCell();
             *          rcell.Border = 0;
             *          rcell.AddElement(new Phrase("Должность начальника ОВС СО РАН", smalfont));
             *          table.AddCell(rcell);
             *          document.Add(table);
             *          document.Close();
             *
             *          byte[] byteInfo = workStream.ToArray();
             *          workStream.Write(byteInfo, 0, byteInfo.Length);
             *          workStream.Position = 0;
             *          return File(workStream, "application/pdf");
             */
            #endregion

            // TODO: подумать, куда лучше вынести
            const string invitationtemplateName = "Приглашение.docx";
            var          templateDirectory      = Path.Combine("Resources", "Templates");

            var employee = await _employeeRepository.GetAsync(empId);

            var invitation = await _invitationReadCommand.ExecuteAsync(id);

            string invitationTemplateDirectorty = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, templateDirectory);
            string invitationTemplateFullPath   = Path.Combine(invitationTemplateDirectorty, invitationtemplateName);
            string dummyInvitationTemplatePath  = Path.Combine(invitationTemplateDirectorty, "Приглашение_Заглушка.docx");

            try
            {
                // настраиваем заглушку
                FileHelper.Copy(invitationTemplateFullPath, dummyInvitationTemplatePath, true);
                FileHelper.SetAttributes(dummyInvitationTemplatePath, FileAttributes.Normal);

                var valuesToFill = await GetContentAsync(invitation, employee);

                using (var outputDocument = new TemplateProcessor(dummyInvitationTemplatePath))
                {
                    outputDocument.SetRemoveContentControls(true);
                    outputDocument.FillContent(valuesToFill);
                    outputDocument.SaveChanges();
                }

                var filledInvitationTemplateBinary = FileHelper.ReadAllBytes(dummyInvitationTemplatePath);
                var fileNameWithoutExtention       = invitation !.Alien?.Passport?.ToFio() ?? $"{DateTime.Now:dd_MM_yyyy}";
                var fileName = $"{fileNameWithoutExtention}.docx";

                // удаляем заглушку приглашения
                FileHelper.Delete(dummyInvitationTemplatePath);

                return(File(filledInvitationTemplateBinary, DOCX_FILE_MIME_TYPE, fileName));
            }
            catch (Exception exception)
            {
                Logger.LogError($"{exception}");
            }

            // TODO: Костыль! Нужно сделать нормальную обработку ошибок
            return(File(Array.Empty <byte>(), DOCX_FILE_MIME_TYPE));
        }
Exemple #22
0
        public ActionResult UploadChunk(int?chunk, int?chunks, string name, string destinationUrl)
        {
            if (name.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0)
            {
                var errorMsg = $"File to upload: \"{name}\" has invalid characters";
                Logger.Log.Warn(errorMsg);
                return(Json(new { message = errorMsg, isError = true }));
            }

            destinationUrl = HttpUtility.UrlDecode(destinationUrl);
            if (string.IsNullOrEmpty(destinationUrl))
            {
                throw new ArgumentException("Folder Path is empty");
            }

            if (!Directory.Exists(destinationUrl))
            {
                Directory.CreateDirectory(destinationUrl);
            }

            chunk  = chunk ?? 0;
            chunks = chunks ?? 1;
            PathSecurityResult securityResult;

            var fileUpload = Request.Files[0];
            var tempPath   = Path.Combine(QPConfiguration.TempDirectory, name);
            var destPath   = Path.Combine(destinationUrl, name);

            if (chunk == 0 && chunks == 1)
            {
                securityResult = PathInfo.CheckSecurity(destinationUrl);
                if (!securityResult.Result)
                {
                    var errorMsg = string.Format(PlUploadStrings.ServerError, name, destinationUrl, $"Access to the folder (ID = {securityResult.FolderId}) denied");
                    Logger.Log.Warn(errorMsg);
                    return(Json(new { message = errorMsg, isError = true }));
                }

                try
                {
                    using (var fs = new FileStream(destPath, FileMode.Create))
                    {
                        var buffer = new byte[fileUpload.InputStream.Length];
                        fileUpload.InputStream.Read(buffer, 0, buffer.Length);
                        fs.Write(buffer, 0, buffer.Length);
                    }
                }
                catch (Exception ex)
                {
                    var errorMsg = string.Format(PlUploadStrings.ServerError, name, destinationUrl, ex.Message);
                    Logger.Log.Error(errorMsg, ex);
                    return(Json(new { message = errorMsg, isError = true }));
                }
            }
            else
            {
                try
                {
                    using (var fs = new FileStream(tempPath, chunk == 0 ? FileMode.Create : FileMode.Append))
                    {
                        var buffer = new byte[fileUpload.InputStream.Length];
                        fileUpload.InputStream.Read(buffer, 0, buffer.Length);
                        fs.Write(buffer, 0, buffer.Length);
                    }
                }
                catch (Exception ex)
                {
                    var errorMsg = string.Format(PlUploadStrings.ServerError, name, tempPath, ex.Message);
                    Logger.Log.Error(errorMsg, ex);
                    return(Json(new { message = errorMsg, isError = true }));
                }

                try
                {
                    var isTheLastChunk = chunk.Value == chunks.Value - 1;
                    if (isTheLastChunk)
                    {
                        securityResult = PathInfo.CheckSecurity(destinationUrl);
                        var actionCode = securityResult.IsSite ? ActionCode.UploadSiteFile : ActionCode.UploadContentFile;

                        if (!securityResult.Result)
                        {
                            var errorMsg = string.Format(PlUploadStrings.ServerError, name, destinationUrl, $"Access to the folder (ID = {securityResult.FolderId}) denied");
                            Logger.Log.Warn(errorMsg);
                            return(Json(new { message = errorMsg, isError = true }));
                        }

                        if (FileIO.Exists(destPath))
                        {
                            FileIO.SetAttributes(destPath, FileAttributes.Normal);
                            FileIO.Delete(destPath);
                        }

                        FileIO.Move(tempPath, destPath);
                        BackendActionContext.SetCurrent(actionCode, new[] { name }, securityResult.FolderId);

                        var logs = BackendActionLog.CreateLogs(BackendActionContext.Current, _logger);
                        _logger.Save(logs);

                        BackendActionContext.ResetCurrent();
                    }
                }
                catch (Exception ex)
                {
                    var errorMsg = string.Format(PlUploadStrings.ServerError, name, destinationUrl, ex.Message);
                    Logger.Log.Error(errorMsg, ex);
                    return(Json(new { message = errorMsg, isError = true }));
                }

                return(Json(new { message = $"chunk#{chunk.Value}, of file{name} uploaded", isError = false }));
            }

            return(Json(new { message = $"file{name} uploaded", isError = false }));
        }
Exemple #23
0
        internal static XFile CreateFileForSystemType(XPETypeSymbol petype, XPESymbol element)
        {
            asmName = petype.Assembly;
            bool mustCreate = false;

            if (Semaphore == null)
            {
                // we create a semaphore file in the workfolder to make sure that if 2 copies of VS are running
                // that we will not delete the files from the other copy
                var tempFolder = Path.GetTempPath();
                tempFolder = Path.Combine(tempFolder, folderName);
                var semFile = Path.Combine(tempFolder, semName);
                // clean up files from previous run
                if (Directory.Exists(tempFolder))
                {
                    if (File.Exists(semFile))
                    {
                        try
                        {
                            File.Delete(semFile);
                            DeleteFolderRecursively(new DirectoryInfo(tempFolder));
                        }
                        catch
                        {
                            // if deletion fails, other copy of VS is running, so do not delete the folder
                        }
                    }
                }
                if (!Directory.Exists(tempFolder))
                {
                    Directory.CreateDirectory(tempFolder);
                }
                WorkFolder = tempFolder;
                if (!File.Exists(semFile))
                {
                    Semaphore = File.Create(semFile);
                }
            }
            var ns     = petype.Namespace + "." + petype.Assembly.Version;
            var name   = petype.Name;
            var nspath = Path.Combine(WorkFolder, ns);

            if (!Directory.Exists(nspath))
            {
                Directory.CreateDirectory(nspath);
            }
            var temp = Path.Combine(nspath, petype.Name) + ".prg";

            mustCreate = !File.Exists(temp);
            if (mustCreate)
            {
                VS.StatusBar.ShowMessageAsync("Generating reference source for " + petype.FullName).FireAndForget();
                VS.StatusBar.StartAnimationAsync(StatusAnimation.General).FireAndForget();
                var aLines = XClassCreator.Create(petype, LookupXml);
                File.WriteAllLines(temp, aLines, System.Text.Encoding.UTF8);
                File.SetAttributes(temp, FileAttributes.ReadOnly);
                VS.StatusBar.ClearAsync().FireAndForget();
                VS.StatusBar.EndAnimationAsync(StatusAnimation.General).FireAndForget();
            }
            var xFile = XSolution.AddOrphan(temp);

            return(xFile);
        }