Пример #1
0
        public SharedDirectoryInfo(LocalDirectory dir)
        {
            m_Name = dir.Name;

            // FIXME: Ugly: Remove '/local' from begining of path
            m_FullPath = "/" + String.Join("/", dir.FullPath.Split('/').Slice(2));
        }
Пример #2
0
        internal SftpSynchronizer(string username, string password, SecurityIdentifier userSid)
        {
            ConnectionInfo connectionInfo = new ConnectionInfo(Settings.ProfileServerAddress, Settings.ProfileServerPort, username, new PasswordAuthenticationMethod(username, password));

            if (Settings.HostKey == string.Empty)
            {
                remote = new RemoteContext(connectionInfo);
            }
            else
            {
                byte[] expectedHostKey = Convert.FromBase64String(Settings.HostKey);
                remote = new RemoteContext(connectionInfo, expectedHostKey);
            }
            remote.Connect();

            this.username       = username;
            this.userSid        = userSid.Value;
            serverBaseDirectory = Settings.ProfileServerBaseDirectory;

            SyncInformation syncInformation    = GetSyncInformation();
            bool            remoteProfileExist = syncInformation.Status != SyncInformation.SyncStatus.DoesNotExist;
            string          localProfilePath   = GetLocalProfilePath(username, password, userSid, remoteProfileExist);
            string          remoteProfilePath  = string.Format("{0}/{1}", serverBaseDirectory, username);

            uploadExclusionList = CreateUploadExclusionList(localProfilePath);
            localProfile        = new LocalDirectory(localProfilePath, uploadExclusionList, username);
            remoteProfile       = new RemoteDirectory(remote, remoteProfilePath, syncInformation.SidInLastHost, this.userSid);
        }
Пример #3
0
        private void PushDirectory(LocalDirectory localDirectory, FtpPath ftpParentPath)
        {
            var ftpPath = ftpParentPath.GetChildPath(localDirectory.Name);

            FtpRetry.ConnectedCall(_mainClient, ftpParentPath.Absolute, c => c.CreateDirectory(localDirectory.Name));
            PushDirectoryContents(localDirectory, ftpPath);
        }
Пример #4
0
        //
        // File Open
        //
        public void OpenCodeFile(string file)
        {
            long siz = LocalDirectory.GetFileSize(file);

            if (siz <= 1)
            {
                return;
            }

            //do not open very large files
            if (siz > MaxFileSIZ)
            {
                _ShowMaxExceedMessage(codeTextBox);
            }
            else
            {
                if (file.CompareTo(codeTextBox.Tag) == 0)
                {
                    codeTextBox.Text = File.ReadAllText(file);
                }
                else
                {
                    codeTextBox.Clear();
                    codeTextBox.Text = File.ReadAllText(file);
                    codeTextBox.ClearUndo();
                    codeTextBox.Tag = file;
                }
            }
        }
Пример #5
0
        public void OpenOutputFile(string file)
        {
            long siz = LocalDirectory.GetFileSize(file);

            if (siz <= 1)
            {
                return;
            }

            if (OpenedOutput != file)
            {
                outputTextBox.Clear();
                progOutputTextBox.Clear();
            }

            //do not open very large files
            if (siz > MaxFileSIZ)
            {
                _ShowMaxExceedMessage(outputTextBox);
            }
            else
            {
                outputTextBox.Text = File.ReadAllText(file);
            }

            progOutputTextBox.Text = outputTextBox.Text;
        }
Пример #6
0
        private void MakeInputOutput(string dir)
        {
            try
            {
                //open input file
                string input = Path.Combine(dir, "input.txt");
                LocalDirectory.CreateFile(input);
                inputTextBox.ReadOnly = false;
                OpenedInput           = input;
                OpenInputFile(input);

                //open output file
                string output = Path.Combine(dir, "output.txt");
                LocalDirectory.CreateFile(output);
                OpenedOutput = output;
                OpenOutputFile(output);

                //open correct output file
                string correct = Path.Combine(dir, "correct.txt");
                LocalDirectory.CreateFile(correct);
                correctOutputTextBox.ReadOnly = false;
                OpenedCorrect = correct;
                OpenCorrectFile(correct);
            }
            catch { }
        }
Пример #7
0
        /// <summary>
        /// Expand up to path of given problem number and select top file inside that folder
        /// Prompt for new file if none exist
        /// </summary>
        /// <param name="pnum">Problem number</param>
        public void ShowCode(object pnum)
        {
            if (!Directory.Exists(RegistryAccess.CodesPath))
            {
                return;
            }
            if (!IsReady || folderTreeView.Nodes.Count == 0)
            {
                if (this.IsDisposed)
                {
                    return;
                }
                TaskQueue.AddTask(ShowCode, pnum, 1000);
                return;
            }

            //create code file if doesn't exist
            string path = LocalDirectory.GetCodesPath((long)pnum);

            if (!Directory.Exists(path) || Directory.GetFiles(path).Length == 0)
            {
                this.BeginInvoke((MethodInvoker)(() => AddProblem((long)pnum)));
                return;
            }

            this.BeginInvoke((MethodInvoker) delegate
            {
                //select code file path
                TreeNode tn = GetNode(new DirectoryInfo(path));
                CodesBrowser.ExpandAndSelect(tn, CodesBrowser.ExpandSelectType.SelecFirstChild);
            });
        }
 /// <summary>
 /// Gets the absolute path of the variable passed in
 /// </summary>
 /// <param name="Path">Path to convert to absolute</param>
 /// <returns>The absolute path of the path passed in</returns>
 protected override string AbsolutePath(string Path)
 {
     Path = Path.Replace("/", "\\");
     string BaseDirectory = "";
     string ParentDirectory = "";
     if (HttpContext.Current == null)
     {
         BaseDirectory = new System.IO.DirectoryInfo(".").FullName;
         ParentDirectory = new LocalDirectory(BaseDirectory).Parent.FullName;
     }
     else
     {
         BaseDirectory = HttpContext.Current.Server.MapPath("~/");
         ParentDirectory = new LocalDirectory(BaseDirectory).Parent.FullName;
     }
     if (Path.StartsWith("..\\", StringComparison.OrdinalIgnoreCase))
     {
         Path = ParentDirectory + Path.Remove(0, 2);
     }
     else if (Path.StartsWith(".\\", StringComparison.OrdinalIgnoreCase))
     {
         Path = BaseDirectory + Path.Remove(0, 1);
     }
     else if (Path.StartsWith("~\\", StringComparison.OrdinalIgnoreCase))
     {
         Path = BaseDirectory + Path.Remove(0, 1);
     }
     return Path;
 }
Пример #9
0
        public void Move()
        {
            IDirectory Temp  = new ResourceDirectory("resource://FileCurator.Tests/");
            IDirectory Temp2 = new LocalDirectory("./Testing/");

            Temp2.Create();
            while (!Temp2.Exists)
            {
            }
            Temp = Temp.MoveTo(Temp2);
            Assert.True(Temp.Exists);
            Assert.True(Temp2.Exists);
            Assert.Equal(Temp2.FullName, Temp.Parent.FullName + "\\");
            int Count = 0;

            foreach (var Files in Temp.EnumerateFiles())
            {
                Assert.NotEqual(0, Files.Length);
                ++Count;
            }
            Assert.Equal(1, Count);
            Temp2.Delete();
            while (Temp2.Exists)
            {
            }
        }
Пример #10
0
        //
        // Tab Control
        //
        private void tabControl1_Selecting(object sender, TabControlCancelEventArgs e)
        {
            if (current == null)
            {
                e.Cancel = true;
                MessageBox.Show("Select a problem first");
                return;
            }

            if (e.TabPage == submissionTab)
            {
                LoadSubmission();
            }
            else if (tabControl1.SelectedTab == discussTab)
            {
                ShowDiscuss();
            }
            else if (tabControl1.SelectedTab == htmlTab)
            {
                problemWebBrowser.Navigate(LocalDirectory.GetProblemHtml(current.pnum));
            }
            else if (tabControl1.SelectedTab == pdfTab)
            {
                setPdfFile(LocalDirectory.GetProblemPdf(current.pnum));
            }
        }
    public void PrepareForWriting_CreatesDirectory()
    {
        var localDirectory = new LocalDirectory(_dirPath);

        localDirectory.PrepareForWriting();

        Assert.IsTrue(Directory.Exists(_dirPath));
    }
Пример #12
0
        private void DownloadFinished(DownloadTask task)
        {
            if (task.Error != null)
            {
                Logger.Add(task.Error.Message, "ProblemViewer | DownloadFinished()");
                return;
            }

            /*
             * this.BeginInvoke((MethodInvoker)delegate
             * {
             *  problemWebBrowser.Refresh();
             * });
             */

            bool finish = false;
            long pnum   = (long)task.Token;

            if (current == null || current.pnum != pnum)
            {
                finish = true;
            }

            if (!finish) //if no error occured
            {
                string ext = Path.GetExtension(task.FileName);
                if (ext == ".pdf")
                {
                    if (LocalDirectory.GetFileSize(task.FileName) > 200)
                    {
                        setPdfFile(task.FileName);
                        finish = true;
                    }
                }

                /*
                 * else if (ext == ".html")
                 * {
                 *  if (LocalDirectory.GetFileSize(task.FileName) > 100)
                 *  {
                 *      problemWebBrowser.Navigate(task.FileName);
                 *      int cnt = DownloadContents(pnum);
                 *      if (cnt == 0) finish = true;
                 *  };
                 *
                 * }
                 * else
                 * {
                 *  finish = true;
                 * }
                 */
            }

            if (finish)
            {
                reloadButton.Enabled = true;
            }
        }
Пример #13
0
        private void ProcessDirectory(LocalDirectory parentDirectory, IO.DirectoryInfo directoryInfo)
        {
            if (parentDirectory == null)
            {
                throw new ArgumentNullException(nameof(parentDirectory));
            }

            if (directoryInfo == null)
            {
                throw new ArgumentNullException(nameof(directoryInfo));
            }

            try
            {
                LocalDirectory directory = (LocalDirectory)parentDirectory.GetSubdirectory(directoryInfo.Name);

                if (directory == null)
                {
                    directory = parentDirectory.CreateSubDirectory(directoryInfo.Name, directoryInfo.FullName);
                }

                foreach (var fileInfo in directoryInfo.EnumerateFiles().Where(f => !f.Name.StartsWith(".")))
                {
                    IndexingFile?.Invoke(this, new FilenameEventArgs(fileInfo.FullName));

                    LocalFile file = (LocalFile)directory.GetFile(fileInfo.Name);
                    if (file == null)
                    {
                        file = directory.CreateFile(fileInfo);
                    }
                    else
                    {
                        // XXX: Update file info
                    }

                    if (string.IsNullOrEmpty(file.InfoHash))
                    {
                        this.hasher.HashFile(file);
                    }
                }

                foreach (var subDirectoryInfo in directoryInfo.EnumerateDirectories().Where(d => !d.Name.StartsWith(".")))
                {
                    //ProcessDirectory(directory, subDirectoryInfo);
                    this.queue.Add(new QueueItem(directory, subDirectoryInfo), this.cancellation.Token);
                }
            }
            catch (ThreadAbortException)
            {
                // Canceled, ignore error.
            }
            catch (Exception ex)
            {
                this.loggingService.LogError("Error while re-indexing shared files:", ex);

                ErrorIndexing?.Invoke(this, new ErrorEventArgs(ex));
            }
        }
Пример #14
0
        void webClient1_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
        {
            if (this.IsDisposed)
            {
                return;
            }
            try
            {
                Interactivity.SetProgress();
                if (e.Cancelled)
                {
                    throw new OperationCanceledException();
                }
                if (e.Error != null)
                {
                    throw e.Error;
                }

                string result = System.Text.Encoding.UTF8.GetString(e.Result);

                if (currentUser != null)
                {
                    if (currentUser.uname != (string)e.UserState)
                    {
                        return;
                    }
                    currentUser.AddSubmissions(result);
                }
                else
                {
                    currentUser = JsonConvert.DeserializeObject <UserInfo>(result);
                    currentUser.Process();
                }

                string file = LocalDirectory.GetUserSubPath(currentUser.uname);
                string data = currentUser.GetJSONData();
                File.WriteAllText(file, data);

                ShowDataByTab();

                string msg = string.Format("Downloaded {0}'s submissions", e.UserState);
                Interactivity.SetStatus(msg);
                if (currentUser.LastSID == 0)
                {
                    Logger.Add(msg, "User Statistics");
                }
            }
            catch (Exception ex)
            {
                Interactivity.SetStatus(string.Format("Error while downloading {0}'s submissions.", e.UserState));
                Logger.Add(ex.Message, "UserStat | webClient1_DownloadDataCompleted");
            }
            finally
            {
                LastUpdate = DateTime.Now;
            }
        }
Пример #15
0
        private void DoStart()
        {
            LoggingService.LogInfo("Started re-index of shared files...");

            if (StartedIndexing != null)
            {
                StartedIndexing(this, EventArgs.Empty);
            }

            LocalDirectory myDirectory = core.FileSystem.RootDirectory.MyDirectory;

            // Remove files/directories from db that no longer exist on the filesystem.
            core.FileSystem.PurgeMissing();

            // If any dirs were removed from the list in settings, remove them from db.
            foreach (LocalDirectory dir in myDirectory.Directories)
            {
                if (!((IList)core.Settings.SharedDirectories).Contains(dir.LocalPath))
                {
                    dir.Delete();
                }
            }

            var lastScanAgo = (DateTime.Now - core.Settings.LastShareScan);

            if (Math.Abs(lastScanAgo.TotalHours) >= 1)
            {
                LoggingService.LogDebug("Starting directory scan. Last scan was {0} minutes ago.", Math.Abs(lastScanAgo.TotalMinutes));
                foreach (var directoryName in core.Settings.SharedDirectories)
                {
                    var info = new DirectoryInfo(directoryName);
                    if (Directory.Exists(directoryName))
                    {
                        ProcessDirectory(myDirectory, info);
                    }
                    else
                    {
                        LoggingService.LogWarning("Directory does not exist: {0}.", info.FullName);
                    }
                }

                core.Settings.LastShareScan = DateTime.Now;
            }
            else
            {
                LoggingService.LogDebug("Skipping directory scan because last scan was {0} minutes ago.", Math.Abs(lastScanAgo.TotalMinutes));
            }

            LoggingService.LogInfo("Finished re-index of shared files...");

            thread = null;

            if (FinishedIndexing != null)
            {
                FinishedIndexing(this, EventArgs.Empty);
            }
        }
Пример #16
0
        private void ProcessDirectory(LocalDirectory parentDirectory, DirectoryInfo directoryInfo)
        {
            if (parentDirectory == null)
            {
                throw new ArgumentNullException("parentDirectory");
            }
            if (directoryInfo == null)
            {
                throw new ArgumentNullException("directoryInfo");
            }

            try {
                if (directoryInfo.Name.StartsWith(".") == false)
                {
                    var directory = (LocalDirectory)parentDirectory.GetSubdirectory(directoryInfo.Name);

                    if (directory == null)
                    {
                        directory = parentDirectory.CreateSubDirectory(core.FileSystem, directoryInfo.Name, directoryInfo.FullName);
                    }

                    foreach (var fileInfo in directoryInfo.GetFiles())
                    {
                        if (fileInfo.Name.StartsWith(".") == false)
                        {
                            if (IndexingFile != null)
                            {
                                IndexingFile(this, fileInfo.FullName);
                            }

                            var file = (LocalFile)directory.GetFile(fileInfo.Name);
                            if (file == null)
                            {
                                file = directory.CreateFile(fileInfo);
                            }
                            if (string.IsNullOrEmpty(file.InfoHash))
                            {
                                core.ShareHasher.HashFile(file);
                            }
                        }
                    }

                    foreach (var subDirectoryInfo in directoryInfo.GetDirectories())
                    {
                        ProcessDirectory(directory, subDirectoryInfo);
                    }
                }
            } catch (ThreadAbortException) {
                // Canceled, ignore error.
            } catch (Exception ex) {
                LoggingService.LogError("Error while re-indexing shared files:", ex);
                if (ErrorIndexing != null)
                {
                    ErrorIndexing(this, new ErrorEventArgs(ex));
                }
            }
        }
Пример #17
0
        //
        // Problem Category Index
        //
        public static void DownloadCategoryIndex()
        {
            //problem category index
            string url  = "https://raw.githubusercontent.com/dipu-bd/uva-problem-category/master/data/INDEX";
            string file = LocalDirectory.GetCategoryIndexFile();

            DownloadFileAsync(url, file, null, Priority.Normal,
                              __DownloadCategoryIndexProgress, __DownloadProblemCategoryCompleted, 1);
        }
Пример #18
0
        public void AddProblem(long pnum)
        {
            //get code path
            string path = LocalDirectory.GetCodesPath(pnum);

            if (string.IsNullOrEmpty(path))
            {
                return;
            }

            //get language
            CodeFileCreator cfc = new CodeFileCreator();

            if (cfc.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            Structures.Language lang = cfc.Language;
            cfc.Dispose();

            //get file extension
            string ext = ".cpp";

            if (lang == Structures.Language.C)
            {
                ext = ".c";
            }
            else if (lang == Structures.Language.Java)
            {
                ext = ".java";
            }
            else if (lang == Structures.Language.Pascal)
            {
                ext = ".pascal";
            }

            //create code file
            string name = Path.GetFileName(path);

            CreateFile(path, name, ext);

            //create input-output
            string input   = Path.Combine(path, "input.txt");
            string output  = Path.Combine(path, "output.txt");
            string correct = Path.Combine(path, "correct.txt");

            LocalDirectory.CreateFile(input);
            LocalDirectory.CreateFile(output);
            LocalDirectory.CreateFile(correct);
            ParseInputOutput(pnum, input, correct);

            //select created problem
            this.BeginInvoke((MethodInvoker) delegate
            {
                ExpandAndSelect(LocateProblem(pnum), ExpandSelectType.SelecFirstChild);
            });
        }
Пример #19
0
        private static async Task EncryptDirectoryAsync()
        {
            IDirectory          directory = new LocalDirectory(_args.Path);
            IEnumerable <IFile> files     = directory.GetFilesIncludingSubdirectories();

            foreach (var file in files)
            {
                await _encryptor.EncryptAsync(file);
            }
        }
Пример #20
0
        //
        // Download User Info
        //

        public static void DownloadDefaultUserInfo(long LastSID = 0)
        {
            //user submission info
            string url = "http://uhunt.felix-halim.net/api/subs-user/{0}/{1}";

            url = string.Format(url, LocalDatabase.GetUserid(RegistryAccess.DefaultUsername), LastSID);
            string file = LocalDirectory.GetUserSubPath(RegistryAccess.DefaultUsername);

            DownloadFileAsync(url, file, RegistryAccess.DefaultUsername, Priority.Normal,
                              __DownloadUserInfoProgress, __DownloadUserInfoCompleted, 1);
        }
Пример #21
0
        /// <summary>
        /// Formats the code directory with default files and folders
        /// </summary>
        /// <param name="background">True to run this process on background</param>
        public void FormatCodeDirectory(object background)
        {
            if (!IsReady)
            {
                return;
            }

            //gather all files
            string path = RegistryAccess.CodesPath;

            if (!Directory.Exists(path))
            {
                return;
            }

            if ((bool)background)
            {
                System.Threading.ThreadPool.QueueUserWorkItem(FormatCodeDirectory, false);
                return;
            }

            IsReady = false;

            Interactivity.SetStatus("Formatting code directory started...");

            this.BeginInvoke((MethodInvoker) delegate
            {
                selectDirectoryPanel.Visible = false;
                folderTreeView.UseWaitCursor = true;
            });

            //create codes-path and check them
            if (!LocalDatabase.IsReady)
            {
                Logger.Add("Problem Database is not ready.", "Codes | FormatCodeDirectory()");
                return;
            }

            //just call codesPath. it will create directory automatically
            foreach (Structures.ProblemInfo prob in LocalDatabase.problemList)
            {
                LocalDirectory.GetCodesPath(prob.pnum);
            }

            //now create files for precode
            LocalDirectory.GetPrecode(Structures.Language.C);
            LocalDirectory.GetPrecode(Structures.Language.CPP);
            LocalDirectory.GetPrecode(Structures.Language.Java);
            LocalDirectory.GetPrecode(Structures.Language.Pascal);

            IsReady = true;
            LoadCodeFolder(false);
            Interactivity.SetStatus("Formatting code directory finished.");
        }
Пример #22
0
 //
 // Precode
 //
 private void precodeToolButton_ButtonClick(object sender, EventArgs e)
 {
     if (CurrentFile == null)
     {
         MessageBox.Show("Create a code file first.");
     }
     else
     {
         string file = LocalDirectory.GetPrecode(CustomLang);
         codeTextBox.Text = File.ReadAllText(file);
     }
 }
Пример #23
0
 private void cancelBrowseButton_Click(object sender, EventArgs e)
 {
     try
     {
         RegistryAccess.CodesPath = LocalDirectory.DefaultCodesPath();
         FormatCodeDirectory(true);
     }
     catch (Exception ex)
     {
         this.BeginInvoke((MethodInvoker)CheckCodesPath);
         Logger.Add(ex.Message, "Codes|CancelBrowserButton()");
     }
 }
Пример #24
0
        public Message CreateRespondDirListingMessage(Node messageTo, LocalDirectory directory)
        {
            SharedDirectoryInfo info = new SharedDirectoryInfo(directory);

            info.Files       = directory.Files.Select(f => new SharedFileListing((LocalFile)f, false)).ToArray();
            info.Directories = directory.Directories.Select(d => d.Name).ToArray();

            Message message = new Message(network, MessageType.RespondDirListing);

            message.To      = messageTo.NodeID;
            message.Content = info;
            return(message);
        }
Пример #25
0
        public MainWindowViewModel(ISynchronizationContext synchronizationContext, LocalDirectory localDirectory)
        {
            this.synchronizationContext = synchronizationContext;
            this.localDirectory         = localDirectory;

            localDirectory.FileFinded += (sender, e) =>
            {
                synchronizationContext.Invoke(() =>
                {
                    searchResults.Add(new FileViewModel(e.FileEntry));
                });
            };

            localDirectory.SearchStarted += (sender, e) =>
            {
                synchronizationContext.Invoke(() =>
                {
                    SearchInProcess = true;
                });
            };

            localDirectory.SearchFinished += (sender, e) =>
            {
                synchronizationContext.Invoke(() =>
                {
                    SearchInProcess = false;
                });
            };

            localDirectory.SearchPaused += (sender, e) =>
            {
                synchronizationContext.Invoke(() =>
                {
                    SearchIsPaused = true;
                });
            };

            localDirectory.SearchResumed += (sender, e) =>
            {
                synchronizationContext.Invoke(() =>
                {
                    SearchIsPaused = false;
                });
            };

            searchCommand = new DelegateCommand(Search, () => CanSearch);
            pauseCommand  = new DelegateCommand(() => localDirectory.PauseSearch(), () => CanPause);
            resumeCommand = new DelegateCommand(() => localDirectory.ResumeSearch(), () => CanResume);
            stopCommand   = new DelegateCommand(() => localDirectory.StopSearch(), () => CanStop);
        }
Пример #26
0
        private void ShowCurrent()
        {
            if (current == null)
            {
                return;
            }

            //unload previous data first
            setPdfFile(null);
            problemWebBrowser.Navigate(string.Empty);

            //load meta info
            LoadTopBar();
            markButton.Checked = current.Marked;

            //check pdf and html description files
            string pdf       = LocalDirectory.GetProblemPdf(current.pnum);
            string html      = LocalDirectory.GetProblemHtml(current.pnum);
            bool   htmlAvail = LocalDirectory.GetFileSize(html) > 100;
            bool   pdfAvail  = LocalDirectory.GetFileSize(pdf) > 200;

            //show data
            if (htmlAvail && this.tabControl1.SelectedTab == htmlTab)
            {
                problemWebBrowser.Navigate(html);
            }
            else if (pdfAvail && this.tabControl1.SelectedTab == pdfTab)
            {
                setPdfFile(pdf);
            }
            else if (htmlAvail)
            {
                this.tabControl1.SelectedTab = htmlTab;
            }
            else if (pdfAvail)
            {
                this.tabControl1.SelectedTab = pdfTab;
            }

            //download if necessary
            if (!pdfAvail)
            {
                DownloadPdf(current.pnum);
            }
            if (!htmlAvail)
            {
                DownloadHtml(current.pnum);
            }
        }
Пример #27
0
 private void DownloadHtml(long pnum)
 {
     try
     {
         string format = "http://uva.onlinejudge.org/external/{0}/{1}.html"; // 0 = vol; 1 = pnum
         string url    = string.Format(format, pnum / 100, pnum);
         string file   = LocalDirectory.GetProblemHtml(pnum);
         Downloader.DownloadFileAsync(url, file, pnum,
                                      Internet.Priority.Normal, ProgressChanged, DownloadFinished);
     }
     catch (Exception ex)
     {
         Logger.Add(ex.Message, "Problem Viewer | DownloadHtml()");
     }
 }
Пример #28
0
        private void DownloadFinished(DownloadTask task)
        {
            problemWebBrowser.Refresh();
            if (task.Error != null)
            {
                Logger.Add(task.Error.Message, "ProblemViewer | DownloadFinished()");
                return;
            }

            bool finish = false;
            long pnum   = (long)task.Token;

            if (current == null || current.pnum != pnum)
            {
                finish = true;
            }

            if (!finish) //if no error occured
            {
                string ext = Path.GetExtension(task.FileName);
                if (ext == ".pdf")
                {
                    System.Diagnostics.Process.Start(task.FileName);
                    finish = true;
                }
                else if (ext == ".html")
                {
                    string file = LocalDirectory.GetProblemHtml(pnum);
                    problemWebBrowser.Navigate(file);
                    int cnt = DownloadContents(pnum);
                    if (cnt == 0)
                    {
                        finish = true;
                    }
                }
                else
                {
                    finish = true;
                }
            }

            if (finish)
            {
                problemWebBrowser.Refresh();
                reloadButton.Enabled = true;
            }
        }
Пример #29
0
        public static void DownloadProblemDatabase()
        {
            if (_DownloadingProblemDatabase)
            {
                return;
            }
            _DownloadingProblemDatabase = true;

            //problem database
            string url       = "http://uhunt.felix-halim.net/api/p";
            string alternate = "https://raw.githubusercontent.com/dipu-bd/uva-problem-category/master/problems.json";

            string file = LocalDirectory.GetProblemInfoFile();

            DownloadFileAsync(url, file, alternate, Priority.High,
                              __DownloadProblemDatabaseProgress, __DownloadProblemDatabaseCompleted, 0);
        }
Пример #30
0
        public static void CreateDirectory(string par, string name, bool trial = true)
        {
            if (par == null)
            {
                par = RegistryAccess.CodesPath;
            }

            int    tcount = 1;
            string path   = Path.Combine(par, name);

            while (trial && Directory.Exists(path))
            {
                path = Path.Combine(par, string.Format("{0} ({1})", name, tcount));
                ++tcount;
            }
            LocalDirectory.CreateDirectory(path);
        }
Пример #31
0
        private async void SetLocalRootDirectory()
        {
            var folderPicker = new FolderPicker();

            folderPicker.FileTypeFilter.Add("*");
            var folder = await folderPicker.PickSingleFolderAsync();

            var localDirectory = new LocalDirectory(folder);

            var items = FtpService.CreatDirectoryItemViewModels(localDirectory);

            LocalWorkingDirectory = new LocalWorkingDirectoryViewModel
            {
                WorkingDirectory = localDirectory,
                Items            = new ObservableCollection <ILocalDirectoryItemViewModel>(items)
            };
        }
Пример #32
0
 public LocalModel()
 {
     string dir = Environment.CurrentDirectory;
     Directory.EnumerateDirectories(dir,"*", SearchOption.AllDirectories).ToList().ForEach(s =>
     {
         var cat = new LocalDirectory() {Name = Path.GetFileName(s), Directory = s, Id = s.GetHashCode()};
         Categories.Add(cat);
         var files = Directory.GetFiles(s);
         foreach (string file in files)
         {
             WriteLine(file);
             Book book = new Book();
             book.Category = cat;
             book.Name = Path.GetFileNameWithoutExtension(file);
             Books.Add(book);
         }
         WriteLine($"subDir : {s}");
     }
     );
     WriteLine($"Directory : {dir}");
 }
Пример #33
0
        public void RemoveItems(IEnumerable<ConflictInfo> conflicts)
        {
            if (conflicts == null)
            {
                throw new ArgumentNullException(nameof(conflicts));
            }

            conflicts = conflicts.ToArray();

            if (!conflicts.Any())
            {
                return;
            }

            if (!GitGroup.Repository.LocalBranchExists(BranchName))
            {
                throw new ItemNotFoundException($"There is no ConflictInfo for file '{conflicts.First().FilePath}'");
            }


            var root = new GitDirectory(null, "root", GitGroup.Repository.GetLocalBranch(BranchName).Tip);

            // verify conflicts
            foreach (var conflict in conflicts)
            {             
                var relativePath = GetRelativeConflictInfoFilePath(conflict.FilePath);
                if (!root.FileExists(relativePath))
                {
                    throw new ItemNotFoundException($"There is no ConflictInfo for file '{conflict.FilePath}'");
                }
            }


            // delete conflict info files
            using (var workingDirectory = new TemporaryWorkingDirectory(GitGroup.Repository.Info.Path, BranchName.ToString()))
            {
                var localDirectory= new LocalDirectory(null, workingDirectory.Location);

                foreach (var conflict in conflicts)
                {
                    var relativePath = GetRelativeConflictInfoFilePath(conflict.FilePath);
                    System.IO.File.Delete(((ILocalFile)localDirectory.GetFile(relativePath)).Location);
                }

                workingDirectory.Commit($"{nameof(GitConflictService)}: Removed {conflicts.Count()} items");
                workingDirectory.Push();
            }                
        }
Пример #34
0
        public void RemoveItems(IEnumerable<SyncAction> syncActions)
        {
            syncActions = syncActions.ToList();

            if (!syncActions.Any())
            {
                return;
            }

            // make sure all to be updated actions exist (otherwise we cannot remove them)
            AssertSyncActionsExist(syncActions, true);

            using (var workingDir = new TemporaryWorkingDirectory(GitGroup.Repository.Info.Path, BranchName.ToString()))
            {
                var localDirectory = new LocalDirectory(null, workingDir.Location);

                // delete the file                 
                foreach (var syncAction in syncActions)
                {
                    PathValidator.EnsureIsRootedPath(syncAction.Path);

                    var directory = localDirectory.GetDirectory(GetRelativeSyncActionDirectoryPath(syncAction));
                    var file = (ILocalFile) directory.GetFile(SyncActionFile.GetFileName(syncAction));
                    System.IO.File.Delete(file.Location);
                }

                workingDir.Commit($"{nameof(GitSyncActionService)}: Removed {syncActions.Count()} items");
                workingDir.Push();
            }
        }