Nicholas

Nicholas

  • NA
  • 1
  • 7.7k

C# Web Browser History Help

Dec 11 2011 7:07 PM
Earlier this semester in my basic programming class we made a simple web browser using C#. Now we're adding a History function to it. Our goals are, to quote my professor:

"When the browser is opened, its constructor runs. The constructor will open the history file and load it into a historical data container.

When the browser is closed, this historical data container is written to an external file for future use.

While the browser is in use, it navigates to pages. Each time the browser navigates to a new page, the URL is added to the historical data container.

When the user clicks History->Browse, the click event handler will call a method that builds the history web page. In order to build the page, the historical data container is required. This new history webpage is loaded into a webpage container one line at a time. Once the method is done building the webpage, the History->Browse button click event handler writes the webpage to a file and then makes the browser navigate to the file. This file is not on the web."

This professor has two habits. One is going over a project completely in class and the other is giving us code that doesn't work right and we then have to fix it
outside of class to finish. This is once again the case for me and now I need some help to get this project done as its worth a decent chunk of my grade. Here is all the code for a main web browser so far. The bolded parts are the bits we added in recently for the History:

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace WindowsFormsApplication1
{
public partial
class MainForm : Form
{
/// <summary>
/// Total history of browsing activity. It begins with the oldest and leads to the youngest.
///
</summary>
private List<string> _lstHistory = new List<string>();

/// <summary>
/// Container holding the webpage generated to display the history.
/// </summary>
private List<string> _lstWebPage = new List<string>();


public
String OpenURL
{
set
{
UrlLine.Text = value; //value is the name the
outside world is tring to give to UrlLine.Text
}
}

public MainForm()
{
// Stuff will go here later (event handlers, etc.)

InitializeComponent();
}

private void
sendLinkToolStripMenuItem_Click(object sender, EventArgs e)
{

}

private void sideBarToolStripMenuItem_Click(object
sender, EventArgs e)
{

}

private void newWindowToolStripMenuItem_Click(object sender, EventArgs e)
{
// Opens new window
MainForm MyForm = new MainForm();
MyForm.Visible = true;
MyForm.Show();
}

private void
toolStripStatusLabel1_Click(object sender, EventArgs e)
{

}

private void BackButton_Click(object sender, EventArgs e)
{
// Back button
MainWebBrowser.GoBack();
}

private void ForwardButton_Click(object sender, EventArgs e)
{
// Forward button
MainWebBrowser.GoForward();
}

private void RefreshButton_Click(object sender, EventArgs e)
{
// Refresh button
MainWebBrowser.Refresh();
}

private void StopButton_Click(object sender, EventArgs e)
{
// Stop button
MainWebBrowser.Stop();
}

private void HomeButton_Click(object sender, EventArgs e)
{
// Home button
MainWebBrowser.GoHome();
}

private void GoButton_Click(object sender, EventArgs e)
{
// Go button for url searches
MainWebBrowser.Navigate(UrlLine.Text);
}

private void UrlLine_KeyDown(object sender, KeyEventArgs e)
{
// Allows Enter key to be used on url searches
if (e.KeyData == Keys.Return)
{
MainWebBrowser.Navigate(UrlLine.Text);
}
}

private void MainWebBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
// Code added to put the title in the bar on browser
this.Text = MainWebBrowser.DocumentTitle + " | Missouri FireChip";
UrlLine.Text = MainWebBrowser.Url.OriginalString;
}

private void closeWindowToolStripMenuItem_Click(object sender, EventArgs e)
{
// Closes selected window
Close();
}

private void printToolStripMenuItem_Click(object sender, EventArgs e)
{
// Displays 'Print' Dialog
MainWebBrowser.ShowPrintDialog();
}

private void savePageAsToolStripMenuItem_Click(object sender, EventArgs e)
{
// Displays 'Save As' Dialog
MainWebBrowser.ShowSaveAsDialog();
}

private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
// Exits the program (closes all windows)
Application.Exit();
}

private void pageSetupToolStripMenuItem_Click(object sender, EventArgs e)
{
// Displays 'Show Page' Dialog
MainWebBrowser.ShowPageSetupDialog();
}

private void printPreviewToolStripMenuItem_Click(object sender, EventArgs e)
{
// Displays 'Print Preview' Dialog
MainWebBrowser.ShowPrintPreviewDialog();
}

private void openFileToolStripMenuItem_Click(object sender, EventArgs e)
{
// Displays 'Open File' pop up
OpenFileForm openFileForm1 = new
OpenFileForm();
openFileForm1.ShowDialog();
}

private void firechipHelpToolStripMenuItem_Click(object sender, EventArgs e)
{
// Shows FireFox support page in FireChip
MainWebBrowser.Navigate("http://support.mozilla.com/en-US/home?as=u");
}

private void aboutFirechipToolStripMenuItem_Click(object sender, EventArgs e)
{
// Displays 'About FireChip' pop up
AboutFireChip aboutFC = new
AboutFireChip();
aboutFC.ShowDialog();
}

private void GettingStarted_Click(object sender, EventArgs e)
{
// Shows FireChip getting started page in FireChip
MainWebBrowser.Navigate("http://i.imgur.com/5SZQo.png");
}

private void MainForm_Load(object sender, EventArgs e)
{
// Determines start-up page
MainWebBrowser.Navigate("http://www.google.com/");
}

private void MainWebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{

}

private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
// Copy button

if (UrlLine.SelectedText.Length > 0)
{
UrlLine.Copy();
}

//if (UrlLine.Text != String.Empty)
//{
// UrlLine.Copy();
//}

//if (String.IsNullOrEmpty(UrlLine.SelectedText))
//{
// UrlLine.Copy();
//}
}

private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{// Paste Button
if (Clipboard.GetDataObject().GetDataPresent(DataFormats.Text)) // DataFormats.Text is a Data Type
{ // not a Data Value
UrlLine.Paste(); // Data Type gives the way to interpret
}
}

private void cutToolStripMenuItem_Click(object sender, EventArgs e)
{// Cut Button
if (UrlLine.SelectedText.Length > 0)
{
UrlLine.Cut();
}
}

private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
{
// Delete Button
if (UrlLine.SelectedText.Length > 0)
{
int iStart = UrlLine.SelectionStart;
int iLength = UrlLine.SelectionLength;

UrlLine.Text = UrlLine.Text.Remove(iStart, iLength);
}
}

private void undoToolStripMenuItem_Click(object sender, EventArgs e)
{
// Undo Button
if (UrlLine.CanUndo)
{
UrlLine.Undo();
UrlLine.ClearUndo();
}
}

private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)
{
// Select All Button
UrlLine.SelectAll();
}

private void editToolStripMenuItem_Click(object sender, EventArgs e)
{
// Disables Cut, Copy, Paste, and Delete buttons when no text is selected
if (UrlLine.SelectedText.Length == 0)
{
cutToolStripMenuItem.Enabled = false;
copyToolStripMenuItem.Enabled = false;
pasteToolStripMenuItem.Enabled = false;
deleteToolStripMenuItem.Enabled = false;
}

// Enables Cut, Copy, Paste, and Delete buttons when text is selected
else
{
cutToolStripMenuItem.Enabled = true;
copyToolStripMenuItem.Enabled = true;
pasteToolStripMenuItem.Enabled = true;
deleteToolStripMenuItem.Enabled = true;
}
}

private void MainWebBrowser_ProgressChanged(object sender, WebBrowserProgressChangedEventArgs e)
{

{
if (e.CurrentProgress == -1)
{
ProgressBar.Value = 100;
}
else //current progress isn't -1
{
if ((e.MaximumProgress != 0) && (e.CurrentProgress >= 0) &&(e.CurrentProgress <= e.MaximumProgress))
{
ProgressBar.Value =(int)(((double)e.CurrentProgress / e.MaximumProgress) * 100);
}
}
}
}
//catch (Exception Mye)

//MessageBox.Show("Division Error " + Mye.Message);
//this.Close();

private string HistoryLine(string sUrl, string sTitle)
{
string sNewLine = String.Empty;
sNewLine = "<p>" + DateTime.Today.ToLongDateString() + " ";
sNewLine += @"<a
href=""" + sUrl + @""">"+sTitle+"</a></p>";

return
sNewLine;
}

private void HistoryWebPage()
{
_lstWebPage.Clear();

string s = @"<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Transitional//EN"" ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"">";
_lstWebPage.Add(s);

s= @"<HtmlDocument xmlns=""http://www.w3.org/1999/xhtml"">";
_lstWebPage.Add(s);

s = "<head>";
_lstWebPage.Add(s);

s = @"<meta content=""text/html; charset=utf-8"" http-equlv=""Content-Type"" />";
_lstWebPage.Add(s);

_lstWebPage.Add("</head>");
_lstWebPage.Add("<body>");

_lstHistory.Reverse();
// Make it neweset to oldest

foreach (string sLine in _lstHistory)
{
_lstWebPage.Add(sLine);
}

_lstHistory.Reverse();
// Make is oldest to newest

_lstWebPage.Add("</body>");
_lstWebPage.Add("</head>");
}

private
void showAllHistoryToolStripMenuItem_Click(object sender, EventArgs e)
{
HistoryWebPage(); // puts the webpage into _lstWebPage

string sPath = Directory.GetCurrentDirectory();
string sFile = @"HistoricalData.txt";
string sFilePath = sPath + sFile;

StreamWriter swHistory = new StreamWriter(sFilePath);

foreach (string s in _lstWebPage)
{
swHistory.WriteLine(s);
}

swHistory.Close();

string sUrl = @"file:///" + sFilePath;

MainWebBrowser.Navigate(sUrl);
}

private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
string cPath = Directory.GetCurrentDirectory();
string cFile = @"HistoricalData.txt";
string cFilePath = cPath + cFile;

StreamWriter clHistory = new StreamWriter(cFilePath);

foreach (string c in _lstHistory)
{
clHistory.WriteLine(c);
}
}

private void MainWebBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
// save the current page location
string s = HistoryLine(MainWebBrowser.Url.OriginalString, MainWebBrowser.DocumentTitle);

if (!_lstHistory.Contains(s))
_lstHistory.Add(s); // put the new link at the end of the list
}
}
}


When i run this the line string s = HistoryLine(MainWebBrowser.Url.OriginalString, MainWebBrowser.DocumentTitle); is highlighted and I get a message saying NullReferenceException was unhandled by user code.

I don't know if I'm missing something obvious here because I honestly don't know C# that well even after a full semester. I'm just shooting in the dark here, hoping I don't fail this class if I muck this up.

Bottom line, how do I get this working?


EDIT: When I look at this it says that MainWebBrowser.Url is null (this is not the only forum I'm seeking help on). The only other section where that line is used is in this one:

private void MainWebBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
// Code added to put the title in the bar on browser
this.Text = MainWebBrowser.DocumentTitle + " | Missouri FireChip";
UrlLine.Text = MainWebBrowser.Url.OriginalString;
}


That doesn't have anything to do with the History function and I don't recall having any problems with that code when we initially did the web browser project. This variable was never assigned anywhere and worked fine in the other code best I can tell but I'm not exactly knowledgeable about this code.

The line that is causing the problem was specifically given in the PDF that goes over the project but like I said in my original post this professor has given us code that doesn't work like he says it will quite often.