Convert awesomium webview to String - awesomium

I am new to awesomium and I only want to load a page using webview and get the current document to sting
webView.Source = New Uri("http://www.google.com")

// somewhere in your code that initializes your webView...
webView.LoadingFrameComplete += new FrameEventHandler(WebView_LoadFramingComplete);
private void WebView_LoadFramingComplete(object sender, FrameEventArgs e)
{
if (e.IsMainFrame)
{
JSValue html = view.ExecuteJavascriptWithResult("document.getElementsByTagName('html')[0].innerHTML");
}
}

Related

Creating a local database in windows phone app 8 using vs2012

I want to develop an app in windows phone 8.
I am totally new to this. I want to create a database for that app from which I can perform CRUID Operations.
I found some information while browsing and watching videos but I did't understand much of it.
Some Steps I did:
Installed windows phone app 8 sdk for vs2012
Added some Sqlite extension from Manage Nuget Packages.
Developed a basic interface for the app.
Copied and pasted the code with few changes
What I want:
Permanently Insert and Fetch data from database (I had downloaded a code from some website but after running it when I close the emulator and try to view the data previously entered, it won't return it)
Like it should be stored in phone memory or any such place
Display the fetched data in listview or grid
Please send me the link that i can go through or any such resembling question asked here
The MainPage.xaml.cs Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using CustomerPhoneApp.Resources;
using SQLite;
using System.IO;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.UI.Popups;
using System.Data.Linq;
using System.Diagnostics;
namespace CustomerPhoneApp
{
public partial class MainPage : PhoneApplicationPage
{
[Table("Users")]
public class User
{
[PrimaryKey, Unique]
public string Name { get; set; }
public string Age { get; set; }
}
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
try
{
var path = ApplicationData.Current.LocalFolder.Path + #"\users.db";
var db = new SQLiteAsyncConnection(path);
await db.CreateTableAsync<User>();
}
catch (Exception)
{
}
}
// Constructor
public MainPage()
{
InitializeComponent();
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
if (txtName.Text != "" && txtAge.Text != "")
{
var path = ApplicationData.Current.LocalFolder.Path + #"\users.db";
var db = new SQLiteAsyncConnection(path);
var data = new User
{
Name = txtName.Text,
Age = txtAge.Text,
};
int x = await db.InsertAsync(data);
}
else
{
MessageBox.Show("enter the title and Notes");
}
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
RetriveUserSavedData();
}
private async void RetriveUserSavedData()
{
string Result = "";
var path = ApplicationData.Current.LocalFolder.Path + #"\users.db";
var db = new SQLiteAsyncConnection(path);
List<User> allUsers = await db.QueryAsync<User>("Select * From Users");
var count = allUsers.Any() ? allUsers.Count : 0;
foreach (var item in allUsers)
{
Result += "Name: " + item.Name + "\nAge: " + item.Age.ToString() + "\n\n";
}
if (Result.ToString() == "")
{
MessageBox.Show("No Data");
}
else
{
MessageBox.Show(Result.ToString());
}
}
private void txtName_TextChanged(object sender, TextChangedEventArgs e)
{
}
private void txtName_GotFocus(object sender, RoutedEventArgs e)
{
txtName.Text = "";
}
private void txtAge_GotFocus(object sender, RoutedEventArgs e)
{
txtAge.Text = "";
}
}
}
1.-Permanently Insert and Fetch data from database (I had downloaded a code from some website but after running it when I close the emulator and try to view the data previously entered, it won't return it)
When you close the emulator you lost all apps installet on it, so if you close it, you lost all. If you want test your data save, you can close the application (only de app, not the emulator) and open it from your app list in the WP emulator.
Like it should be stored in phone memory or any such place
With SQL lite you canĀ“t store the data in the SD, it will be stored in your app directory, if you want use the SD to store data, you can use binary files
Display the fetched data in listview or grid
To show your data in the listview or grid, you need create a ViewModel or DataContext and then use Binding to "send" the data to de view.

Downloads with JavaFX WebView

my web application offers a download. Javascript creats at the click the url (it depends on the user input) and the browser should open it, so that the page isn't reloaded.
For that, I think I have to alternatives:
// Alt1:
window.open(pathToFile);
// Alt2:
var downloadFrame = document.getElementById('downloads');
if (downloadFrame === null) {
downloadFrame = document.createElement('iframe');
downloadFrame.id = 'downloads';
downloadFrame.style.display = 'none';
document.body.appendChild(downloadFrame);
}
downloadFrame.src = pathToFile;
Both works under Firefox. Problem with open new window method: If the creation of the file at the server needs more time, the new empty tab will be closed late.
Problem with iframe: If there is an error at the server, no feedback is given.
I think at firefox the iframe is the better solution. But the web application must run with an JavaFX WebView, too. JavaFX haven't a download feature, I have to write it. One possible way is to listen on the location property:
final WebView webView = new WebView();
webView.getEngine().locationProperty().addListener(new ChangeListener<String>() {
#Override public void changed(ObservableValue<? extends String> observableValue, String oldLoc, String newLoc) {
if (newLoc.cotains("/download")) {
FileChooser chooser = new FileChooser();
chooser.setTitle("Save " + newLoc);
File saveFile = chooser.showSaveDialog(webView.getEngine().getScene().getWindow());
if (saveFile != null) {
BufferedInputStream is = null;
BufferedOutputStream os = null;
try {
is = new BufferedInputStream(new URL(newLoc).openStream());
os = new BufferedOutputStream(new FileOutputStream(saveFile));
while ((readBytes = is.read()) != -1) {
os.write(b);
}
} finally {
try { if (is != null) is.close(); } catch (IOException e) {}
try { if (os != null) os.close(); } catch (IOException e) {}
}
}
}
}
}
There are some problems:
The download start depends on a part of the url, because JafaFX supports no access to the http headers (that is bearable)
If the user starts the download with the same url two times, only the first download works (the change event only fires, if the url is new). I can crate unique urls (with #1, #2 and so on at the end). But this is ugly.
Only the "window.open(pathToFile);" method works. Loading an iframe don't fire the change location event of the website. That is expectable but I haven't found the right Listener.
Can someone help me to solve 2. or 3.?
Thank you!
PS: Sorry for my bad english.
edit:
For 2. I found a way. I don't know if it is a good one, if it is performant, if the new webview is deleted or is in the cache after download, ....
And the user don't get an feedback, when some a problem is raised:
webView.getEngine().setCreatePopupHandler(new Callback<PopupFeatures, WebEngine>() {
#Override public WebEngine call(PopupFeatures config) {
final WebView downloader = new WebView();
downloader.getEngine().locationProperty().addListener(/* The Listener from above */);
return downloader.getEngine();
}
}
I think you may just need to use copyURLtoFile to get the file...call that when the location changes or just call that using a registered java class. Something like this:
org.apache.commons.io.FileUtils.copyURLToFile(new URL(newLoc), new File(System.getProperty("user.home")+filename));
Using copyURLToFile the current page doesn't have to serve the file. I think registering the class is probably the easiest way to go... something like this:
PHP Code:
Download $filename
Java (in-line class in your javafx class/window... in this case my javafx window is inside of a jframe):
public class JavaApp {
JFrame cloudFrameREF;
JavaApp(JFrame cloudFrameREF)
{
this.cloudFrameREF = cloudFrameREF;
}
public void getfile(String filename) {
String newLoc = "http://your_web_site.com/send_file.php?filename=" + filename;
org.apache.commons.io.FileUtils.copyURLToFile(new URL(newLoc), new File(System.getProperty("user.home")+filename));
}
}
This part would go in the main javafx class:
Platform.runLater(new Runnable() {
#Override
public void run() {
browser2 = new WebView();
webEngine = browser2.getEngine();
appREF = new JavaApp(cloudFrame);
webEngine.getLoadWorker().stateProperty().addListener(
new ChangeListener<State>() {
#Override public void changed(ObservableValue ov, State oldState, State newState) {
if (newState == Worker.State.SUCCEEDED) {
JSObject win
= (JSObject) webEngine.executeScript("window");
// this next line registers the JavaApp class with the page... you can then call it from javascript using "app.method_name".
win.setMember("app", appREF);
}
}
});
You may not need the frame reference... I was hacking some of my own code to test this out and the ref was useful for other things...

webbrowser control does not "render" html

I am having problem using webbrowser control to correctly display html. My goal is to add custom html to a webbrowser control, have it displayed, and save the screenshot of that as png. Currently I am using Document.OpenNew and Document.Write(htmlText) and Application.DoEvents(). However since I am running this in a background thread, sometimes it deadlocks. I know the culprit is Application.DoEvents() which is giving me troubles.
However, if I remove that and set the html directly to DocumentText property, how do I know when it is fully "rendered" or loaded. I used the DocumentCompleted Event but that does not seem to work since the image that is saved is still empty even after the event fires.
I also have the thread as STA.
Here is the existing code:
Thread th = new Thread(new ThreadStart(createImage));
th.SetApartmentState(ApartmentState.STA);
th.Start();
th.Join(TIMEOUT);
private void createImage() {
var browser = new WebBrowser();
var doc = browser.Document;
doc.OpenNew(false);
doc.Write("<html><body>....</body><html>)");
//loop for few seconds
for(int i=0; i<20; i++)
{
Application.DoEvents();
Thread.Sleep(100);
}
//save to file as png.
}
Here is the code I am trying:
private void createImage() {
var browser = new WebBrowser();
bool docComplete = false;
browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(
(Object sender, WebBrowserDocumentCompletedEventArgs args) =>
{ docComplete = true; }
);
browser.DocumentText = "<html>.....";
while (!_docComplete)
{
Thread.Sleep(100);
}
// save image
// :-( not working
}
You have to create thread as STA, that is only the way to run WebBrowser in a background thread.
bw.SetApartmentState(ApartmentState.STA);
There is no information about waiting in HtmlDocument.Write Method. If is yet required then you can add DocumentCompleted handler instead of DoEvents
private void captureImageThread(string html) {
var thread = new Thread(() => {
var browser = new WebBrowser();
browser.DocumentCompleted += browser_DocumentCompleted;
browser.DocumentText = html;
Application.Run();
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) {
var br = sender as WebBrowser;
// save image here
Application.ExitThread(); // Stops the thread
}

How to control flow of multiple Rss Files

I developed RssFeed Application using LWUIT j2me(java) for 2 xml files, now I want to show those 2 xml files on LWUIT Tabs.
That means, when my application runs, default tab will be displayed (on that tab my first Rss xml file Titles should be displayed), and when the user click on tab2 my second Rss xml titles should be displayed.
I am able to display the same titles of one rss files on both the tabs, how to control my flow to achieve my task?
Here my code:
public class XMLMidlet extends MIDlet implements ActionListener {
public XMLMidlet() {
Display.init(this);
news = new Vector();
m_backCommand = new Command("Back");
cmdExit = new Command("EXIT");
cmdDetails = new Command("Details");
}
public void startApp() {
//RssFeed URL's
String urls[] = {"http://topnews-23.rss",
"http://topstory-12.rss"};
for(int i=0;i<urls.length;i++){
ParseThread myThread = new ParseThread(this,urls[i]);
//this will start the second thread
myThread.getXMLFeed(urls[i]);
}
}
//method called by the parsing thread
public void addNews(News newsItem,String url) {
try{
news.addElement(newsItem);
form1 = new Form();
myNewsList = new List(newsVector);
newsList =new List(newsVector);
myNewsList.setRenderer(new NewsListCellRenderer());
newsList.setRenderer(new NewsListCellRenderer());
tabs=new Tabs(Component.TOP);
tabs.addTab("TopNews", myNewsList);
tabs.addTab("Topstory",newsList);
form1.addComponent(tabs);
form1.show();
}
catch(Exception e){
e.printStackTrace();
}
}
You should move below code
myNewsList = new List(newsVector);
newsList =new List(newsVector);
myNewsList.setRenderer(new NewsListCellRenderer());
newsList.setRenderer(new NewsListCellRenderer());
tabs=new Tabs(Component.TOP);
form1 = new Form();
tabs=new Tabs(Component.TOP);
tabs.addTab("TopNews", myNewsList);
tabs.addTab("Topstory",newsList);
from addNews method to constructor XMLMidlet. addNews method should use url parameter to differ for which list the newsItem is directed.
Update
Below is how I think you should implement addNews method:
public void addNews(News newsItem, String url) {
if (url.endsWith("topnews-20.rss")) {
myNewsList.addElement(newsItem);
} else if (url.endsWith("topstory-25.rss")) {
newsList.addElement(newsItem);
}
}
serRenderer does not need to be called from addNews and form1.show() should be moved to startApp.

Outlook add in , text box , delete\backspace not working

I developed an outlook add in (custom task pane), with web browser in the user control.
All the things working well beside the backspace or the delete button when I am writing something in text box in the web browser, I can't use those keys, am I missing something?
I am a few years late to the party but I managed to fix this. The easiest way to fix this is to ensure proper focus is given to the input fields, so you will need to be able to run your own javascript on whatever page is being loaded.
The javascript I run on the page is as follows (using jQuery):
$(document).on("click", function (e) {
// first let the add-in give focus to our CustomTaskPane
window.external.focus();
// then in our web browser give focus to whatever element was clicked on
$(e.target).focus();
});
the window.external variable contains code run from the plugin (c# or VB I assume) which is exposed so we can interact from web page back to the add-in.
In the add-in code for the custom taskpane set the context of window.external:
// event when webBrowser is finished loading document
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
// sets context of window.external to functions defined on this context
webBrowser1.ObjectForScripting = this;
}
And a public method for focusing:
// can be called by the web browser as window.external.focus()
public void focus()
{
this.Focus();
}
This worked for me, and I hope it helps others. Although do note that this probably doesn't work if the user keyboard navigates using tab, but you can either extend this code for that use case, or safely assume that the average outlook user will have his hand glued to the mouse.
Ok I solved the problem ,
The problem is that the custom task pane in not always gets fucos from the outlook.
So, I raised an event every time that there is "onclick" for all the pane, and then forced the pane to be in focus.
spent a lot of time trying to get this working in Outlook v16.0.13801.20288 the above did not work for me. I ended up with this working code.
Create a user control and add your webbrowser control to it then customize the .cs as below
private void CreateTaskPane() {
MyWinFormUserControl webBrowser = new MyWinFormUserControl();
webBrowser.webBrowser3.Url = new Uri("https://google.com");
webBrowser.webBrowser3.Width = 500;
webBrowser.webBrowser3.Dock = DockStyle.Fill;
webBrowser.webBrowser3.Visible = true;
webBrowser.Width = 500;
webBrowser.Dock = DockStyle.Fill;
webBrowser.Visible = true;
this.CRMTaskPaneControl = CustomTaskPanes.Add(webBrowser, "My App");
//Components.WebViewContainerWPFUserControl webView = (Components.WebViewContainerWPFUserControl)_eh.Child;
//webView.webview.Source = new Uri("https://localhost:3000");
this.CRMTaskPaneControl.Width = 500;
System.Windows.Forms.Application.DoEvents();
this.CRMTaskPaneControl.Control.Focus();
this.CRMTaskPane.Visible = true;
}
public partial class MyWinFormUserControl : UserControl
{
public WebBrowser webBrowser3;
public System.Windows.Forms.WebBrowser webBrowser1;
public MyWinFormUserControl()
{
InitializeComponent();
}
private void InitializeComponent()
{
this.webBrowser3 = new System.Windows.Forms.WebBrowser();
this.SuspendLayout();
//
// webBrowser3
//
this.webBrowser3.Dock = System.Windows.Forms.DockStyle.Fill;
this.webBrowser3.Location = new System.Drawing.Point(0, 0);
this.webBrowser3.MinimumSize = new System.Drawing.Size(20, 20);
this.webBrowser3.Name = "webBrowser3";
this.webBrowser3.Size = new System.Drawing.Size(500, 749);
this.webBrowser3.TabIndex = 0;
this.webBrowser3.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(this.webBrowser3_DocumentCompleted);
//
// MyWinFormUserControl
//
this.Controls.Add(this.webBrowser3);
this.Name = "MyWinFormUserControl";
this.Size = new System.Drawing.Size(500, 749);
this.Load += new System.EventHandler(this.MyWinFormUserControl_Load);
this.ResumeLayout(false);
}
void webBrowser3_DocumentCompleted(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)
{
HtmlDocument doc;
doc = webBrowser3.Document;
doc.Click += doc_Click;
}
void doc_Click(object sender, HtmlElementEventArgs e)
{
this.Focus(); // force user control to have the focus
HtmlElement elem = webBrowser3.Document.GetElementFromPoint(e.ClientMousePosition);
elem.Focus(); // then let the clicked control to have focus
}
private void MyWinFormUserControl_Load(object sender, EventArgs e)
{
//Control loaded
}
Turns out this is an easy issue to fix.
Just write
class MyBrowser : WebBrowser {}
Then use MyBrowser instead of the .NET one.

Resources