private void Authenticate() { AwfulDebugger.AddLog(this, AwfulDebugger.Level.Debug, "START Authenticate"); // first, check iso storage for cookies. // TODO: the above. // else, login using the supplied username and password. var login = new AwfulLoginClient(); int tries = 0; while (!AwfulWebRequest.CanAuthenticate && tries < 3) { AwfulDebugger.AddLog(this, AwfulDebugger.Level.Info, "Authentication failed, attempting to try again..."); var loginArgs = OnLoginRequired(this); if (loginArgs == null) { throw new Exception("You need to attach an event listener for login required!"); } loginArgs.Signal.WaitOne(); if (loginArgs.Ignore) { AwfulDebugger.AddLog(this, AwfulDebugger.Level.Info, "Ignoring authentication request. Moving on..."); return; } else if (!loginArgs.Cancel) { AwfulDebugger.AddLog(this, AwfulDebugger.Level.Info, "User has input credentials; retrying..."); Username = loginArgs.Username; Password = loginArgs.Password; AwfulWebRequest.SetCookieJar(login.Authenticate(Username, Password)); tries++; } // automatically fail on cancel else { throw new Exception("User cancelled authentication."); } } // after too many tries throw the white flag. if (tries > 3) { throw new Exception("User failed to authenticate."); } AwfulDebugger.AddLog(this, AwfulDebugger.Level.Debug, "END Authenticate()"); }
private Uri HandleGetResponse(IAsyncResult result) { //Logger.AddEntry("ThreadReplyService - GetResponse initiated."); HttpWebRequest webRequest = result.AsyncState as HttpWebRequest; HttpWebResponse response = webRequest.EndGetResponse(result) as HttpWebResponse; string html = string.Empty; using (StreamReader reader = new StreamReader(response.GetResponseStream())) { string text = reader.ReadToEnd(); html = text; } // Check if response was successful - Look for redirect data. AwfulDebugger.AddLog(this, AwfulDebugger.Level.Verbose, "Begin server response..."); AwfulDebugger.AddLog(this, AwfulDebugger.Level.Verbose, html); AwfulDebugger.AddLog(this, AwfulDebugger.Level.Verbose, "...End server response."); HtmlDocument responseHtml = new HtmlDocument(); responseHtml.LoadHtml(html); HtmlNode responseRedirectMeta = responseHtml.DocumentNode.Descendants("meta") .Where(meta => meta.GetAttributeValue("http-equiv", "").Equals("Refresh")) .SingleOrDefault(); // try to parse redirect url AwfulDebugger.AddLog(this, AwfulDebugger.Level.Debug, "Attempting to parse redirect url..."); Uri redirect = null; try { string delim = "URL="; string contentValue = responseRedirectMeta.GetAttributeValue("content", ""); var tokens = contentValue.Split(new string[] { delim }, StringSplitOptions.RemoveEmptyEntries); string redirectValue = tokens[1]; redirectValue = HttpUtility.HtmlDecode(redirectValue); redirect = new Uri(string.Format("{0}/{1}", CoreConstants.BASE_URL, redirectValue)); AwfulDebugger.AddLog(this, AwfulDebugger.Level.Debug, string.Format("Url: '{0}'", redirect.AbsoluteUri)); } catch (Exception ex) { AwfulDebugger.AddLog(this, AwfulDebugger.Level.Critical, "Redirect parsing failed."); AwfulDebugger.AddLog(this, AwfulDebugger.Level.Critical, ex); } return(redirect); }
/* * public static ThreadPageMetadata ParseThreadPage(Uri threadPageUri) * { * var client = new AwfulWebClient(); * var htmlDoc = client.FetchHtml(threadPageUri.AbsoluteUri); * return ParseThreadPage(htmlDoc); * } */ private static ThreadPageMetadata ProcessThreadPage(HtmlNode top) { AwfulDebugger.AddLog(top, AwfulDebugger.Level.Debug, "Parsing HTML for posts..."); // first, let's generate data about the thread ThreadPageMetadata page = new ThreadPageMetadata() .ProcessParent(top) .ParsePageNumberAndMaxPages(top) .ParsePostTable(top) .ParseTargetPostIndex(); return(page); }
public static byte[] ReadFileFromResourceStore(string filePath) { byte[] result = null; try { Stream stream = Application.GetResourceStream(new Uri(filePath, UriKind.RelativeOrAbsolute)).Stream; using (BinaryReader reader = new BinaryReader(stream)) { result = reader.ReadBytes((int)stream.Length); } } catch (Exception ex) { AwfulDebugger.AddLog(new object(), AwfulDebugger.Level.Critical, ex); } return(result); }
private static ThreadPageMetadata ParsePageNumberAndMaxPages(this ThreadPageMetadata page, HtmlNode top) { // now, let's parse page number AwfulDebugger.AddLog(top, AwfulDebugger.Level.Debug, "Parsing page number..."); int pageNumber = -1; int lastPage = -1; var currentPageNode = top.Descendants(THREAD_PAGE_NUMBER_ELEMENT_1) .Where(node => node.GetAttributeValue(THREAD_PAGE_NUMBER_ATTRIBUTE_1, "").Contains(THREAD_PAGE_NUMBER_VALUE_1)) .FirstOrDefault(); if (currentPageNode != null) { var currentPageOptions = currentPageNode.Descendants(THREAD_PAGE_NUMBER_ELEMENT_2); var currentPageOption = currentPageOptions .Where(node => node.GetAttributeValue(THREAD_PAGE_NUMBER_ATTRIBUTE_2, "").Equals(THREAD_PAGE_NUMBER_VALUE_2)) .FirstOrDefault(); AwfulDebugger.AddLog(top, AwfulDebugger.Level.Debug, "Parsing total number of pages..."); var lastPageOption = currentPageOptions.LastOrDefault(); if (currentPageOption != null) { int.TryParse(currentPageOption.GetAttributeValue(THREAD_PAGE_NUMBER_ATTRIBUTE_3, ""), out pageNumber); } if (lastPageOption != null) { int.TryParse(lastPageOption.GetAttributeValue(THREAD_PAGE_NUMBER_ATTRIBUTE_3, ""), out lastPage); } page.PageNumber = pageNumber; page.LastPage = lastPage; } else { AwfulDebugger.AddLog(top, AwfulDebugger.Level.Debug, "Page number parsing failed."); // set page number page.PageNumber = 1; page.LastPage = 1; } return(page); }
private void InitThreadTagCache(object state) { string tagListUrl = state as string; // download the tag list HttpWebRequest request = HttpWebRequest.CreateHttp(tagListUrl); try { request.BeginGetResponse(InitThreadTagCacheResponse, request); } catch (Exception ex) { AwfulDebugger.AddLog(this, AwfulDebugger.Level.Critical, ex); ThreadTagNextUpdate = 0; } }
private Uri InitiateReply(ThreadReplyData data, int timeout = DEFAULT_TIMEOUT) { // create request AwfulDebugger.AddLog(this, AwfulDebugger.Level.Debug, "Creating Reply Request..."); string url = "http://forums.somethingawful.com/newreply.php"; var request = AwfulWebRequest.CreateFormDataPostRequest(url, REPLY_CONTENT_TYPE); if (request == null) { throw new NullReferenceException("request is not an http request."); } request.AllowAutoRedirect = true; // begin request stream AwfulDebugger.AddLog(this, AwfulDebugger.Level.Debug, "Beginning Request Stream..."); var signal = new AutoResetEvent(false); var result = request.BeginGetRequestStream(callback => { signal.Set(); }, request); signal.WaitOne(); // process request AwfulDebugger.AddLog(this, AwfulDebugger.Level.Debug, "Creating Form Data..."); FormDataDelegate replyFormData = () => { return(GetReplyMultipartFormData(data)); }; var success = ProcessReplyRequest(result, replyFormData); // begin response AwfulDebugger.AddLog(this, AwfulDebugger.Level.Debug, "Waiting for response..."); request = result.AsyncState as HttpWebRequest; result = request.BeginGetResponse(callback => { signal.Set(); }, request); signal.WaitOne(timeout); if (!result.IsCompleted) { throw new TimeoutException("Thread Reply: timeout reached"); } // process response and return status value AwfulDebugger.AddLog(this, AwfulDebugger.Level.Debug, "Processing response..."); Uri redirect = HandleGetResponse(result); return(redirect); }
public static bool CopyResourceFileToIsoStore(string source, string destination) { bool success = false; try { var bytes = ReadFileFromResourceStore(source); success = bytes.SaveBinaryToIsoStore(destination); } catch (Exception ex) { AwfulDebugger.AddLog(new object(), AwfulDebugger.Level.Critical, ex); success = false; } return(success); }
protected virtual string ParseNode(HtmlNode node) { StringBuilder builder = new StringBuilder(); while (node != null) { try { ProcessNode(node, builder); } catch (Exception ex) { AwfulDebugger.AddLog(this, AwfulDebugger.Level.Critical, ex); } node = node.NextSibling; } return(builder.ToString()); }
public void SaveStateToIsoStorage() { try { MainDataSource.Instance.Pins.SaveToFile("pins.xml"); MainDataSource.Instance.Bookmarks.SaveToFile("bookmarks.xml"); MainDataSource.Instance.ThreadTable.SaveToFile("threads.xml"); MainDataSource.Instance.Forums.SaveToFile("forums.xml"); } catch (Exception ex) { AwfulDebugger.AddLog(this, AwfulDebugger.Level.Critical, ex); } finally { AwfulDebugger.SaveAndDispose(); } }
private Uri InitiateEditRequest(PostEditData data, int timeout = CoreConstants.DEFAULT_TIMEOUT_IN_MILLISECONDS) { AwfulDebugger.AddLog(this, AwfulDebugger.Level.Debug, "Begin Edit Request..."); string url = "http://forums.somethingawful.com/editpost.php"; var request = AwfulWebRequest.CreateFormDataPostRequest(url, EDIT_CONTENT_TYPE); if (request == null) { throw new NullReferenceException("request is not an http request."); } request.AllowAutoRedirect = true; // begin request stream AwfulDebugger.AddLog(this, AwfulDebugger.Level.Debug, "Processing request stream..."); var signal = new AutoResetEvent(false); var result = request.BeginGetRequestStream(callback => { signal.Set(); }, request); signal.WaitOne(); // process request AwfulDebugger.AddLog(this, AwfulDebugger.Level.Debug, "Creating form data..."); FormDataDelegate editFormData = () => { return(GetEditMultipartFormData(data)); }; var success = ProcessReplyRequest(result, editFormData); // begin response AwfulDebugger.AddLog(this, AwfulDebugger.Level.Debug, "Waiting for server response..."); request = result.AsyncState as HttpWebRequest; result = request.BeginGetResponse(callback => { signal.Set(); }, request); signal.WaitOne(timeout); if (!result.IsCompleted) { throw new TimeoutException("The timeout was reached while trying to send an edit request."); } // process response and return status value AwfulDebugger.AddLog(this, AwfulDebugger.Level.Debug, "Processing server response..."); Uri redirect = HandleGetResponse(result); return(redirect); }
public static bool DeleteFileFromStorage(string filepath) { bool deleted = false; try { IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication(); if (storage.FileExists(filepath)) { storage.DeleteFile(filepath); deleted = true; } } catch (Exception ex) { AwfulDebugger.AddLog(new object(), AwfulDebugger.Level.Critical, ex); } return(deleted); }
// Code to execute on Unhandled Exceptions private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e) { string stackTrace = e.ExceptionObject.StackTrace == null ? e.ExceptionObject.InnerException.StackTrace.ToString() : e.ExceptionObject.StackTrace.ToString(); string message = e.ExceptionObject.Message == null ? e.ExceptionObject.InnerException.Message : e.ExceptionObject.Message; AwfulDebugger.AddLog(sender, AwfulDebugger.Level.Critical, e.ExceptionObject); MessageBox.Show(stackTrace, message, MessageBoxButton.OK); if (System.Diagnostics.Debugger.IsAttached) { // An unhandled exception has occurred; break into the debugger System.Diagnostics.Debugger.Break(); } }
private void LoadFromQuery() { var query = NavigationContext.QueryString; if (query.ContainsKey("link")) { string value = query["link"]; try { this.threadSlideView.ControlViewModel.LoadPageFromUri(new Uri(value)); } catch (Exception ex) { AwfulDebugger.AddLog(this, AwfulDebugger.Level.Critical, ex); NavigationService.GoBack(); } } else if (query.ContainsKey("id") && query.ContainsKey("nav")) { string ThreadID = query["id"]; ThreadMetadata thread = new ThreadMetadata() { ThreadID = ThreadID }; switch (query["nav"]) { case "unread": this.threadSlideView.ControlViewModel.LoadFirstUnreadPost(thread); break; case "last": this.threadSlideView.ControlViewModel.LoadLastPost(thread); break; case "page": int pageNumber = -1; int.TryParse(query["pagenumber"], out pageNumber); this.threadSlideView.ControlViewModel.LoadPageNumber(thread, pageNumber); break; } } }
private static bool BuildPath(this IsolatedStorageFile storage, string path) { bool success = false; try { var folders = path.Split('/'); for (int i = 0; i < folders.Length - 1; i++) { if (!storage.DirectoryExists(folders[i])) { storage.CreateDirectory(folders[i]); } } success = true; } catch (Exception ex) { AwfulDebugger.AddLog(new object(), AwfulDebugger.Level.Critical, ex); success = false; } return(success); }
public static bool SaveToFile <T>(this T item, string filePath) { AwfulDebugger.AddLog(item, AwfulDebugger.Level.Debug, "START SaveToFile()"); AwfulDebugger.AddLog(item, AwfulDebugger.Level.Debug, "Filepath: " + filePath); bool result = false; try { AwfulDebugger.AddLog(item, AwfulDebugger.Level.Debug, "Getting application user store..."); var storage = IsolatedStorageFile.GetUserStoreForApplication(); if (storage.BuildPath(filePath)) { AwfulDebugger.AddLog(item, AwfulDebugger.Level.Debug, "Creating DataContractSerializer..."); DataContractSerializer dcs = new DataContractSerializer(item.GetType()); using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(filePath, System.IO.FileMode.Create, System.IO.FileAccess.Write, storage)) { AwfulDebugger.AddLog(item, AwfulDebugger.Level.Debug, "Writing serlialized object to filestream..."); dcs.WriteObject(fileStream, item); result = true; AwfulDebugger.AddLog(item, AwfulDebugger.Level.Debug, "Write complete."); AwfulDebugger.AddLog(item, AwfulDebugger.Level.Info, "Save successful!"); } } } catch (Exception ex) { AwfulDebugger.AddLog(item, AwfulDebugger.Level.Info, "Save failed."); AwfulDebugger.AddLog(item, AwfulDebugger.Level.Critical, ex); result = false; #if DEBUG throw ex; #endif } AwfulDebugger.AddLog(item, AwfulDebugger.Level.Debug, "END SaveToFile()"); return(result); }
private static ThreadMetadata ParseColorCategory(this ThreadMetadata thread, HtmlNode node) { // code block example: <td class="star bm0"> var colorNode = node.Descendants("td").Where(aNode => aNode.GetAttributeValue("class", "") .Contains("star")).FirstOrDefault(); if (colorNode != null) { try { string colorValue = colorNode.GetAttributeValue("class", ""); string categoryToken = colorValue.Split(new char[] { ' ' })[1]; thread.ColorCategory = ConvertColorValueToBookmarkCategory(categoryToken); } catch (Exception ex) { AwfulDebugger.AddLog(thread, AwfulDebugger.Level.Info, ex); thread.ColorCategory = BookmarkColorCategory.Unknown; } } return(thread); }
public static T LoadFromFile <T>(string file) { AwfulDebugger.AddLog(file, AwfulDebugger.Level.Debug, "START LoadFromFile()"); AwfulDebugger.AddLog(file, AwfulDebugger.Level.Info, string.Format("Loading file '{0}' of type '{1}' from storage...", file, typeof(T))); T result = default(T); try { AwfulDebugger.AddLog(file, AwfulDebugger.Level.Debug, "Getting application user store..."); var storage = IsolatedStorageFile.GetUserStoreForApplication(); if (!storage.FileExists(file)) { return(result); } DataContractSerializer dcs = new DataContractSerializer(typeof(T)); using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(file, System.IO.FileMode.Open, System.IO.FileAccess.Read, storage)) { AwfulDebugger.AddLog(file, AwfulDebugger.Level.Debug, "Reading serlialized object from filestream..."); result = (T)dcs.ReadObject(fileStream); AwfulDebugger.AddLog(file, AwfulDebugger.Level.Debug, "Read complete."); AwfulDebugger.AddLog(file, AwfulDebugger.Level.Info, "Load successful!"); } } catch (Exception ex) { AwfulDebugger.AddLog(file, AwfulDebugger.Level.Critical, ex); AwfulDebugger.AddLog(file, AwfulDebugger.Level.Info, "Load failed."); result = default(T); } AwfulDebugger.AddLog(file, AwfulDebugger.Level.Debug, "END LoadFile()"); return(result); }
private void OnErrorGenerated(string response) { AwfulDebugger.AddLog(this, AwfulDebugger.Level.Critical, response); }
private void PageBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e) { AwfulDebugger.AddLog(this, AwfulDebugger.Level.Debug, "Event: PageBrowser_Navigated"); }