public static void RunLoadAsync(object background) { if (!IsReady) { return; } if ((bool)background) { bool back = System.Threading.ThreadPool.QueueUserWorkItem(RunLoadAsync, false); if (back) { return; } } try { IsReady = false; //initialize global values problemList = new List <ProblemInfo>(); problemId = new SortedDictionary <long, long>(); problemNum = new SortedDictionary <long, ProblemInfo>(); categoryRoot = new CategoryNode("Root", "All Categories"); //get object data from json data string text = File.ReadAllText(LocalDirectory.GetProblemInfoFile()); var data = JsonConvert.DeserializeObject <List <List <object> > >(text); if (data == null || data.Count == 0) { throw new NullReferenceException("Problem database was empty"); } //load all lists from object data LoadList(data); LoadOthers(); data.Clear(); IsAvailable = true; } catch (Exception ex) { Logger.Add(ex.Message, "Problem Database|RunLoadAsync()"); if (!IsAvailable) { Internet.Downloader.DownloadProblemDatabase(); } } //load categories LoadCategories(); //load default user LoadDefaultUser(); IsReady = true; Interactivity.CategoryDataUpdated(); Interactivity.ProblemDatabaseUpdated(); }
private void openCodeFile_Click(object sender, EventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); ofd.CheckFileExists = true; ofd.Filter = "All Files|*.*"; if (cppRadioButton.Checked) { ofd.Filter = "CPP Files|*.cpp|Header Files|*.h*|All Files|*.*"; } if (ansiCradioButton.Checked) { ofd.Filter = "C Files|*.c|Header Files|*.h*|All Files|*.*"; } if (JavaRadioButton.Checked) { ofd.Filter = "Java Files|*.java|All Files|*.*"; } if (PascalRadioButton.Checked) { ofd.Filter = "Pascal Files|*.pascal|All Files|*.*"; } if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { if (LocalDirectory.GetFileSize(ofd.FileName) < 1024 * 512) { codeTextBox.OpenFile(ofd.FileName); } else { MessageBox.Show("File is too big. Please select a valid file"); } } }
public static void LoadDefaultUser() { try { string user = RegistryAccess.DefaultUsername; if (!ContainsUser(user)) { throw new KeyNotFoundException(); } string file = LocalDirectory.GetUserSubPath(user); string data = File.ReadAllText(file); DefaultUser = JsonConvert.DeserializeObject <UserInfo>(data); if (DefaultUser != null) { DefaultUser.Process(); } else { DefaultUser = new UserInfo(RegistryAccess.DefaultUsername); } } catch (Exception ex) { DefaultUser = new UserInfo(RegistryAccess.DefaultUsername); Logger.Add(ex.Message, "LocalDatabase|LoadDefaultUser()"); } }
private static void LoadList(List <List <object> > datalist) { //Load problem from list foreach (List <object> lst in datalist) { ProblemInfo plist = new ProblemInfo(lst); problem_list.Add(plist); SetProblem(plist.pnum, plist); SetNumber(plist.pid, plist.pnum); //add problem to volume string vol = string.Format("Volume {0:000}", plist.volume); category_root[VolRoot][vol].AddProblem(plist, false); } //load book categories string file = LocalDirectory.GetCategoryPath(); string data = File.ReadAllText(file); List <ContextBook> catlist = JsonConvert.DeserializeObject <List <ContextBook> >(data); foreach (ContextBook book in catlist) { book.Process(); } }
private void descriptionFolderToolStripMenuItem_Click(object sender, EventArgs e) { try { System.Diagnostics.Process.Start(LocalDirectory.GetProblemDescritionPath()); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
static void Main() { //enable application styles Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); //add header to log file string dat = Environment.NewLine; for (int i = 0; i < 80; ++i) { dat += '*'; } dat += Environment.NewLine; System.IO.File.AppendAllText(LocalDirectory.GetLogFile(), dat); //load user-names LocalDatabase.usernames = RegistryAccess.GetAllUsers(); if (string.IsNullOrEmpty(RegistryAccess.DefaultUsername) || Properties.Settings.Default.AskForUsernameEverytime) { UsernameForm uf = new UsernameForm(); Application.Run(uf); } //task queue TaskQueue.StartTimer(); try { //launch application Interactivity.mainForm = new MainForm(); Application.Run(Interactivity.mainForm); } catch (Exception ex) { Logger.Add("Error in main form => ", ex.Message + " => " + ex.StackTrace); Application.Exit(); } //end of application works Interactivity.CloseAllOpenedForms(); Properties.Settings.Default.Save(); UVA_Arena.Elements.CodeCompiler.ForceStopTask(); }
private static void LoadList(List <List <object> > datalist) { SortedDictionary <int, List <ProblemInfo> > catData = new SortedDictionary <int, List <ProblemInfo> >(); //Load problem from list foreach (List <object> lst in datalist) { ProblemInfo plist = new ProblemInfo(lst); problemList.Add(plist); //set the file size string file = LocalDirectory.GetProblemHtml(plist.pnum); if (File.Exists(file)) { plist.FileSize = (new System.IO.FileInfo(file)).Length; } SetProblem(plist.pnum, plist); SetNumber(plist.pid, plist.pnum); //Categorize if (!catData.ContainsKey(plist.Volume)) { catData.Add(plist.Volume, new List <ProblemInfo>()); } catData[plist.Volume].Add(plist); } //add volume category var volCat = new CategoryNode("Volumes", "Problem list by volumes"); categoryRoot.branches.Add(volCat); foreach (var data in catData.Values) { string vol = string.Format("Volume {0:000}", data[0].Volume); var nod = new CategoryNode(vol, "", volCat); volCat.branches.Add(nod); foreach (var p in data) { nod.problems.Add(new CategoryProblem(p.pnum)); } } volCat.ProcessData(); }
public static bool LoadCategoryData(string key) { try { string file = LocalDirectory.GetCategoryDataFile(key); string json = File.ReadAllText(file); var node = (CategoryNode)JsonConvert.DeserializeObject <CategoryNode>(json); node.ProcessData(); categoryRoot.RemoveCategory(node.name); categoryRoot.branches.Add(node); return(true); } catch (Exception ex) { Logger.Add(ex.Message, "LoadCategoryData(" + key + ")"); return(false); } }
/// <summary> /// Parse HTML file and find all local contents to download. /// </summary> /// <param name="pnum">Problem number</param> /// <param name="replace">True, if you want to replace old files.</param> /// <returns>List of files to download</returns> public static List <DownloadTask> ProcessHtmlContent(long pnum, bool replace) { try { string external = string.Format("http://uva.onlinejudge.org/external/{0}/", pnum / 100); string filepath = LocalDirectory.GetProblemHtml(pnum); if (!File.Exists(filepath)) { return(new List <DownloadTask>()); } List <string> urls = new List <string>(); List <DownloadTask> tasks = new List <DownloadTask>(); HtmlAgilityPack.HtmlDocument htdoc = new HtmlAgilityPack.HtmlDocument(); htdoc.Load(filepath); DFS(htdoc.DocumentNode, urls); htdoc.Save(filepath); foreach (string str in urls) { string url = str.StartsWith("./") ? str.Remove(0, 2) : str; while (url.StartsWith("/")) { url = url.Remove(0, 1); } string file = url.Replace('/', Path.DirectorySeparatorChar); file = LocalDirectory.GetProblemContent(pnum, file); if (replace || LocalDirectory.GetFileSize(file) < 10) { tasks.Add(new DownloadTask(external + url, file, pnum)); } } urls.Clear(); return(tasks); } catch (Exception ex) { Logger.Add(ex.Message, "Internet"); return(new List <DownloadTask>()); } }
public static bool UpdateAll() { const double PROBLEM_ALIVE_DAY = 1; const double USER_SUB_ALIVE_DAY = 0.5; bool result = true; //if database file is too old redownload string file = LocalDirectory.GetProblemInfoFile(); if (LocalDirectory.GetFileSize(file) < 100 || (new TimeSpan( DateTime.Now.Ticks - new FileInfo(file).LastWriteTime.Ticks ).TotalDays > PROBLEM_ALIVE_DAY)) { UVA_Arena.Internet.Downloader.DownloadProblemDatabase(); result = false; } //update user submissions if not available if (LocalDatabase.ContainsUser(RegistryAccess.DefaultUsername)) { file = LocalDirectory.GetUserSubPath(RegistryAccess.DefaultUsername); if (LocalDirectory.GetFileSize(file) < 50 || (new TimeSpan( DateTime.Now.Ticks - new FileInfo(file).LastWriteTime.Ticks ).TotalDays > USER_SUB_ALIVE_DAY)) { long sid = 0; if (LocalDatabase.DefaultUser != null) { sid = LocalDatabase.DefaultUser.LastSID; } UVA_Arena.Internet.Downloader.DownloadDefaultUserInfo(sid); } } //download category index if too old UVA_Arena.Internet.Downloader.DownloadCategoryIndex(); return(result); }
// // Precode Settings // private string getFile() { Structures.Language lang = Language.CPP; if (ansiCradioButton.Checked) { lang = Language.C; } else if (JavaRadioButton.Checked) { lang = Language.Java; } else if (PascalRadioButton.Checked) { lang = Language.Pascal; } else { lang = Language.CPP; } return(LocalDirectory.GetPrecode(lang)); }
public static void Add(string text, string source) { //add to current context LogData ld = new LogData(); ld.time = DateTime.Now; ld.source = source; ld.status = text; LOG.Add(ld); //save log string dat = ""; dat += DateTime.Now.ToLongDateString() + " | " + DateTime.Now.ToLongTimeString(); dat += " => " + text + " => " + source + Environment.NewLine; if (LOG.Count == 0) { text = Environment.NewLine + text; } System.IO.File.AppendAllText(LocalDirectory.GetLogFile(), dat); }
/// <summary> /// Parse a Category Index data file and returns a dictonary /// </summary> public static Dictionary <string, long> GetCategoryIndex() { var result = new Dictionary <string, long>(); try { string file = LocalDirectory.GetCategoryIndexFile(); if (!File.Exists(file)) { return(result); } var arr = (JArray)JsonConvert.DeserializeObject(File.ReadAllText(file)); foreach (JToken tok in arr) { result.Add( tok.Value <string>("file"), tok.Value <long>("ver")); } } catch { } return(result); }
private string DownloadFile(string url, string file, int minSiz, int tryCount = 2) { try { string tmp = Path.GetTempFileName(); webClient.DownloadFile(url, tmp); LocalDirectory.CreateFile(file); if (LocalDirectory.GetFileSize(tmp) >= minSiz) { File.Copy(tmp, file, true); File.Delete(tmp); return("Success."); } else { File.Delete(tmp); return("File doesn't have desired length."); } } catch (Exception ex) { if (tryCount > 0) { System.Threading.Thread.Sleep(300); return(DownloadFile(url, file, minSiz, tryCount - 1)); } //if couldn't be downloaded if (File.Exists(file) && LocalDirectory.GetFileSize(file) < minSiz) { File.Delete(file); } Logger.Add(ex.Message, this.Name); return("Download Failed."); } }
private void DownloadProblem() { //initial data int total = 2; int finished = 0; long vol = current / 100; string status = ""; FileInfo pdffile = new FileInfo(LocalDirectory.GetProblemPdf(current)); FileInfo htmlfile = new FileInfo(LocalDirectory.GetProblemHtml(current)); string pdf = string.Format("http://uva.onlinejudge.org/external/{0}/{1}.pdf", vol, current); string html = string.Format("http://uva.onlinejudge.org/external/{0}/{1}.html", vol, current); //download HTML file if (ReplaceOldFiles == 0 || ReplaceOldFiles == 1 || !htmlfile.Exists || htmlfile.Length < 100) { status = "Downloading " + htmlfile.Name + "... "; backgroundWorker1.ReportProgress(100 * finished / total, status); status = DownloadFile(html, htmlfile.FullName, 100); ++finished; backgroundWorker1.ReportProgress(100 * finished / total, status); } if (!Internet.Downloader.IsInternetConnected()) { status = "Not connected to the Internet"; backgroundWorker1.ReportProgress(0, status); CurrentState = State.Cancelling; } if (CurrentState != State.Running) { return; } //download PDF file if (ReplaceOldFiles == 0 || ReplaceOldFiles == 2 || !pdffile.Exists || pdffile.Length < 200) { status = "Downloading " + pdffile.Name + "... "; backgroundWorker1.ReportProgress(100 * finished / total, status); status = DownloadFile(pdf, pdffile.FullName, 200); ++finished; backgroundWorker1.ReportProgress(100 * finished / total, status); } if (!Internet.Downloader.IsInternetConnected()) { status = "Not connected to the Internet"; backgroundWorker1.ReportProgress(0, status); CurrentState = State.Cancelling; } if (CurrentState != State.Running) { return; } //download HTML contents var list = Functions.ProcessHtmlContent(current, ReplaceOldFiles == 0 || ReplaceOldFiles == 3); finished = 0; total = list.Count; foreach (var itm in list) { if (CurrentState != State.Running) { return; } if (Internet.Downloader.IsInternetConnected()) { status = "Downloading " + Path.GetFileName(itm.FileName) + "... "; backgroundWorker1.ReportProgress(100 * finished / total, status); status = DownloadFile(itm.Url.ToString(), itm.FileName, 10); ++finished; backgroundWorker1.ReportProgress(100 * finished / total, status); } else { status = "Not connected to the Internet"; backgroundWorker1.ReportProgress(0, status); CurrentState = State.Cancelling; } } }
private void DelayInitialize(object background) { //run in background if ((bool)background) { this.Cursor = Cursors.AppStarting; System.Threading.ThreadPool.QueueUserWorkItem(DelayInitialize, false); return; } //load problem database LocalDatabase.RunLoadAsync(false); //load controls bool _initialized = false; this.BeginInvoke((MethodInvoker) delegate { //add controls AddControls(); //add buttons to the top right beside control buttons //AddActiveButtons(); _initialized = true; this.Cursor = Cursors.Default; Logger.Add("Initialized all controls", "Main Form"); loadingPanel.Visible = false; }); //update problem database if not available if (LocalDirectory.GetFileSize(LocalDirectory.GetProblemInfoFile()) < 100) { while (!_initialized) { System.Threading.Thread.Sleep(1000); } System.Threading.Thread.Sleep(2000); this.BeginInvoke((MethodInvoker) delegate { UVA_Arena.Internet.Downloader.DownloadProblemDatabase(); }); } //update user submissions if not available if (LocalDatabase.ContainsUser(RegistryAccess.DefaultUsername)) { string file = LocalDirectory.GetUserSubPath(RegistryAccess.DefaultUsername); if (LocalDirectory.GetFileSize(file) < 50) { System.Threading.Thread.Sleep(1000); this.BeginInvoke((MethodInvoker) delegate { Interactivity.userstat.DownloadUserSubs(RegistryAccess.DefaultUsername); }); } } //check for updates System.Threading.Thread.Sleep(10000); UpdateCheck.CheckForUpdate(); }