Clear history webbrowser in window phone 7? - c#

In my application, i use webbrowser control.
#region show adve....
public void ShowAd(string link)
{
linkFromservices = "http://ads.diadiem.com/www/delivery/afr.php?refresh=10&zoneid=66&...=";
client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
client.DownloadStringAsync(new Uri(linkFromservices, UriKind.RelativeOrAbsolute));
}
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
result = string.Empty;
try
{
result = e.Result;
if (!string.IsNullOrEmpty(result))
{
result = AddScripttoHTML(result);
webBrowser.NavigateToString(result);
}
}
catch (Exception ex) { }
finally
{
result = string.Empty;
client.DownloadStringCompleted -= new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
}
}
#endregion
in this link "http://ads.diadiem.com/www/delivery/afr.php?refresh=10&zoneid=66&..." you can see refesh=10 . Every 10 seconds the browser will automatically refresh and change the current advertising alone by random.....
but refresh the memory increased from 200KB to 400KB.
how to release or clear History webbrowser in window phone 7 ?
Thank you all ! please help me.......

The webbrowser controle for WP7 is unable to clear history, you need to create your own webbrowser :
http://franciscojf.wordpress.com/2011/03/27/full-web-browser-control-for-windows-phone-7/

Related

NET webbrowser - get HTML element ID by clicking on image

I have a C# winform project with a webbrowser control. I'm loading an HTML page with images into the webbrowser. Each image has a different ID:
<img src="F:\Temp\file12948.jpg" id="12948" width="180px">
Is there a way to pass the ID into a variable when clicking on the image so I can use the ID in my code? The path to the image can also be used as I can extract the number from there.
I have already searched here there and everywhere for a solution but can't find anything related.
You can dynamically attach to image's onClick event.
public class TestForm : Form
{
WebBrowser _WebBrowser = null;
public TestForm()
{
_WebBrowser = new WebBrowser();
_WebBrowser.ScriptErrorsSuppressed = true;
_WebBrowser.Dock = DockStyle.Fill;
this.Controls.Add(_WebBrowser);
WebBrowserDocumentCompletedEventHandler Completed = null;
Completed = (s, e) =>
{
//add onclick event dynamically
foreach (var img in _WebBrowser.Document.GetElementsByTagName("img").OfType<HtmlElement>())
{
img.AttachEventHandler("onclick", (_, __) => OnClick(img));
}
_WebBrowser.DocumentCompleted -= Completed;
};
_WebBrowser.DocumentCompleted += Completed;
var imgurl = "https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png";
//_WebBrowser.Navigate("http://edition.cnn.com/2017/09/09/us/hurricane-irma-cuba-florida/index.html");
_WebBrowser.DocumentText = $"<html> <img src='{imgurl}' id=123 /> </html>";
}
void OnClick(HtmlElement img)
{
MessageBox.Show(img.GetAttribute("id"));
}
}
On simple way would be to use browser navigation. When clicking you can navigate to a special URL, then you handle the Navigating event and if the url is the special url you cancel the navigation and handle the data.
public MainWindow()
{
InitializeComponent();
br.NavigateToString(#"<img src=""F:\Temp\file12948.jpg"" id=""12948"" width=""180px"" >");
br.Navigating += this.Br_Navigating;
}
private void Br_Navigating(object sender, NavigatingCancelEventArgs e)
{
if(e.Uri.Host == "messages")
{
MessageBox.Show(e.Uri.Query);
e.Cancel = true;
}
}
This works if you have some control over the HTML. You could also set the URL from JS if you don't want to add the anchor.
Edit
The above version is for a WPF application. The winforms version is as follows:
public Form1()
{
InitializeComponent();
webBrowser1.DocumentText = #"<img src=""F:\Temp\file12948.jpg"" id=""12948"" width=""180px"" >";
webBrowser1.Navigating += this.webBrowser1_Navigating;
}
private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
if (e.Url.Host == "messages")
{
MessageBox.Show(e.Url.Query);
e.Cancel = true;
}
}

Windows Phone 7.1 live tile background images not setting

I am trying to change the background images (front and back) of the live tile for a windows phone 7.1 app however the background images are never set. I've added the images to the project and have made sure to specify their names properly in the Uri() constructor. I can't seem to be able to detect the problem. Here's the code.
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
}
String result = "Default";
String company = "";
String image = "";
//Method That Executes After Every DownloadStringAsync() Call by WebClient
public void wb_DownloadStringCompleted(Object sender, DownloadStringCompletedEventArgs e)
{
result = e.Result;
int newCount = 1;
// Application Tile is always the first Tile, even if it is not pinned to Start.
ShellTile TileToFind = ShellTile.ActiveTiles.First();
// Application should always be found
if (TileToFind != null)
{
// Set the properties to update for the Application Tile.
// Empty strings for the text values and URIs will result in the property being cleared.
StandardTileData NewTileData = new StandardTileData
{
Title = "Stocks App",
BackgroundImage = new Uri(image, UriKind.Relative),
Count = newCount,
BackTitle = company,
BackBackgroundImage = new Uri(image, UriKind.Relative), //**The problem is here**
BackContent = result
};
// Update the Application Tile
TileToFind.Update(NewTileData);
}
}
//Method for Radio Button When Google is Selected
private void radioButton1_Checked(object sender, RoutedEventArgs e)
{
company = "Google Stock";
image = "google_icon.png";
WebClient wb = new WebClient();
wb.DownloadStringAsync(new Uri("http://finance.yahoo.com/d/quotes.csv?s=GOOG&f=a"));
wb.DownloadStringCompleted += wb_DownloadStringCompleted;
}
//Method for Radio Button When Yahoo is Selected
private void yahooRadioBtn_Checked(object sender, RoutedEventArgs e)
{
company = "Yahoo Stock";
image = "yahoo_icon.png";
WebClient wb = new WebClient();
wb.DownloadStringAsync(new Uri("http://finance.yahoo.com/d/quotes.csv?s=YHOO&f=a"));
wb.DownloadStringCompleted += wb_DownloadStringCompleted;
}
//Method for Radio Button When Apple is Selected
private void appleRadioBtn_Checked(object sender, RoutedEventArgs e)
{
company = "Apple Stock";
image = "apple_icon.png";
WebClient wb = new WebClient();
wb.DownloadStringAsync(new Uri("http://finance.yahoo.com/d/quotes.csv?s=AAPL&f=a"));
wb.DownloadStringCompleted += wb_DownloadStringCompleted;
}
}
Verify that the path of the image and the Build Action is as requested by the documentation
You can find out more at
http://msdn.microsoft.com/en-US/library/windowsphone/develop/microsoft.phone.shell.standardtiledata.backbackgroundimage(v=vs.105).aspx
and
http://msdn.microsoft.com/en-US/library/windowsphone/develop/ff402541(v=vs.105).aspx
Check your files Build Action property is set to Content before any other check

Duplex printing with WebBrowser control only printing 1 side

I'm having an issue with my .NET application only printing the second page of my HTML file, and completely ignoring the first page (no other page is printed, and the back of it is blank).
When I pull up my printer's queue window, it does show it go from "Spooling" to "Printing" and lists both pages, so I'm at a loss as to why it's not printing the first page.
(My printer IS set to duplex printing, and if I literally just print the HTML document from my browser, it works as expected)
Here's what I'm doing:
private void Form1_Load(object sender, EventArgs e)
{
// Create a FileSystemWatcher to monitor all files on drive C.
FileSystemWatcher fsw = new FileSystemWatcher("C:\\COAForms");
// Watch for changes in LastAccess and LastWrite times, and
// the renaming of files or directories.
fsw.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
// Register a handler that gets called when a
// file is created, changed, or deleted.
//fsw.Changed += new FileSystemEventHandler(OnChanged);
fsw.Created += new FileSystemEventHandler(OnChanged);
fsw.Error += new ErrorEventHandler(fsw_Error);
//fsw.Deleted += new FileSystemEventHandler(OnChanged);
fsw.EnableRaisingEvents = true;
fsw.SynchronizingObject = this;
PrinterSettings settings = new PrinterSettings();
label2.Text = settings.PrinterName;
Thread.CurrentThread.SetApartmentState(ApartmentState.STA);
}
void fsw_Error(object sender, ErrorEventArgs e)
{
MessageBox.Show(e.ToString());
}
private void OnChanged(object source, FileSystemEventArgs e)
{
notifyIcon1.BalloonTipText = "Printing document " + e.Name + "...";
notifyIcon1.BalloonTipTitle = "Printing Application";
notifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
notifyIcon1.ShowBalloonTip(500);
PrintCOAPage(e.Name);
}
private void PrintCOAPage(string name)
{
try
{
// Create a WebBrowser instance.
WebBrowser webBrowserForPrinting = new WebBrowser();
// Add an event handler that prints the document after it loads.
webBrowserForPrinting.DocumentCompleted +=
new WebBrowserDocumentCompletedEventHandler(PrintDocument);
// Set the Url property to load the document.
webBrowserForPrinting.Url = new Uri(#"C:\COAForms\" + name);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void PrintDocument(object sender,
WebBrowserDocumentCompletedEventArgs e)
{
try
{
PrinterSettings ps = new PrinterSettings();
ps.Duplex = Duplex.Vertical;
// Print the document now that it is fully loaded.
((WebBrowser)sender).Print();
// Dispose the WebBrowser now that the task is complete.
((WebBrowser)sender).Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
this.Show();
this.Activate();
if (this.WindowState == FormWindowState.Minimized)
{
this.WindowState = FormWindowState.Normal;
}
}
private void Form1_Resize(object sender, EventArgs e)
{
if (FormWindowState.Minimized == WindowState)
{
Hide();
}
}
I only just recently added the PrinterSettings to the code and it changed nothing.
I would greatly appreciate any help you guys can provide on this! Thank you!
Wow, didn't think the CSS would impact it, but for whatever reason the CSS I was using (involving z-index) made the first page NOT display when I print previewed under the WebBrowser control, but worked just fine in actual IE8.. after changing the CSS around a bit it now works as intended.

Error in web browser control navigating

In my web browser app for wp7, i have two xaml pages. One is mainpage.xaml and other is web.xaml.
I have a youtube button in mainpage.xaml, if i click on it, it navigates to youtube.com in web.xaml. But if i press the device back button(to navigate to mainpage) after the youtube is fully navigated, then there is no error. But if i press the back button while the youtube is navigating then it throws an error. Error in recording the history i think(I also have history page to record the history). The error is - "Cannot write to a closed TextWriter". This error will also occur sometime for someother sites too. I have also added the image of that error. Can anyone help me with this? Thanks in advance for your help!
public partial class Web : PhoneApplicationPage
{
List<Uri> HistoryStack;
int HistoryStack_Index;
bool fromHistory;
bool navigationcancelled = false;
public IsolatedStorageFile historyFile = null;
public IsolatedStorageFileStream filestream = null;
public StreamWriter stream = null;
public Web()
{
InitializeComponent();
HistoryStack = new List<Uri>();
historyFile = IsolatedStorageFile.GetUserStoreForApplication();
if (historyFile.FileExists("History.txt"))
{
Error in this line--->filestream = historyFile.OpenFile("History.txt", System.IO.FileMode.Append, FileAccess.Write);--->Error in this line
stream = new StreamWriter(filestream);
}
else
{
filestream = historyFile.OpenFile("History.txt", System.IO.FileMode.Create);
stream = new StreamWriter(filestream);
}
HistoryStack_Index = 0;
fromHistory = false;
browsers[this.currentIndex].Navigated += new EventHandler<System.Windows.Navigation.NavigationEventArgs>(browsers_Navigated);
browsers[this.currentIndex].Navigating += new EventHandler<NavigatingEventArgs>(browsers_Navigating);
}
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedFrom(e);
{
stream.Close();
}
}
private void browsers_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
if (!fromHistory)
{
if (HistoryStack_Index < HistoryStack.Count)
{
HistoryStack.RemoveRange(HistoryStack_Index, HistoryStack.Count - HistoryStack_Index);
}
HistoryStack.Add(e.Uri);
//HistoryURL temp = new HistoryURL();
//temp.URL = e.Uri.ToString();
//app.historyList.Add(temp);
Thread.Sleep(100);
Dispatcher.BeginInvoke(() =>
{
string title = (string)browsers[this.currentIndex].InvokeScript("eval", "document.title.toString()");
stream.WriteLine(title + ";" + e.Uri.ToString());---> **Error in this line.**
});
}
HistoryStack_Index += 1;
}
fromHistory = false;
navigationcancelled = false;
}
If I understand this correctly you are having 2 handlers for navigated event (OnNavigatedFrom and browsers_Navigated).
The problem probably is that in OnNavigatedFrom you are calling stream.Close(); so stream.WriteLine will fail the next time it is called since the stream was closed.
Try moving stream.Close(); to the application close event and use stream.Flush() after stream.WriteLine.

C#: Stop loop until an event

I have a for loop and inside there is a navigate method for a browser. and it's suppose to load diffrent sites, but the problem is that it will start to load 1 site and before it will load it, it'll load another site. so I need to like pause it until it's completed.
I started to write an event to when the ProgressChanged event is at 100%.. than I figured I don't have any idea what to do next but I think it's a start.
Please help, Thanks!
Edit: I am using Forms as Roland said.
I assume you are doing windows forms programming. The event you want is DocumentCompleted Here's an example:
public Uri MyURI { get; set; }
public Form1()
{
InitializeComponent();
MyURI = new Uri("http://stackoverflow.com");
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
webBrowser1.Url = MyURI;
}
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if(e.Url == MyURI)
MessageBox.Show("Page Loaded");
}
For a list of URIs it's straight forward.
public int CurrentIndex = 0;
List<Uri> Uris;
public Form1()
{
InitializeComponent();
Uris = new List<Uri> { new Uri("http://stackoverflow.com"), new Uri("http://google.com/") };
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
webBrowser1.Url = Uris[CurrentIndex];
}
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser browser = (WebBrowser)sender;
if (e.Url == Uris[CurrentIndex])
{
CurrentIndex++;
if (CurrentIndex < Uris.Count)
{
browser.Url = Uris[CurrentIndex];
}
}
}

Categories