EO.WebBrowser set referer C# - javascript

Trying to find a way to set the referer in EO.WebBrowser.
I saw that the User-Agent can be changed with:webView1.CustomUserAgent but looks like there is no method for the referer. Are there any other ways to get this working in javascript or by other means?
I can "capture" the beforesendheaders event, with this: webView1.BeforeSendHeaders += new EO.WebBrowser.RequestEventHandler(webView1_BeforeSendHeaders);, but doesn't help that much.
I'm working on a project, and I started with awesomium, but... looks like some websites are not loaded, it's just showing a blank screen. I've managed to change both referer and user agent in awesomium, but I really need both to move on.
Any suggestions are appreciated.

Looks like I've found it myself, using javascript.
Here's the code:
public partial class Form1 : Form
{
private const string JS_referer_function = "function navigateToUrl(url) {var f = document.createElement(\"FORM\"); f.action = url; var indexQM = url.indexOf(\"?\"); if (indexQM>=0) { var params = url.substring(indexQM+1).split(\"&\"); for (var i=0; i<params.length; i++) { var keyValuePair = params[i].split(\"=\"); var input = document.createElement(\"INPUT\"); input.type=\"hidden\"; input.name = keyValuePair[0]; input.value = keyValuePair[1]; f.appendChild(input); } } document.body.appendChild(f); f.submit(); }";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
webView1.LoadUrlAndWait("http://referer.com");
webView1.EvalScript(JS_referer_function);
webView1.EvalScript("navigateToUrl(\"http://192.168.0.108/referer\");");
}
}
It's basically loading http://referer.com first, and using javascript, goes to http://192.168.0.108/referer using the referer http://referer.com.

Related

How to call Export PDF with Reserved.ReportViewerWebControl.axd....URL from BackEnd C# Code

My Aim is to call ExportBaseUrl Link , that is given by Rdlc Exprot PDF button , on C# side, i want to do that because there are 285 reports and each one have diff parameters so this will take a lot time.
I have worked on one solution but that take 15 min to load 2 page RDLC to pdf.
Its taking time due to Response coming late or some deadlock is happening,
This is what i am doing.
JS file
var reportViewerName = ControlName; //Name attribute of report viewer control.
var src_url = $find(reportViewerName)._getInternalViewer().ExportUrlBase + 'PDF';
var contentDisposition = 'AlwaysInline'; //Content Disposition instructs the server to either return the PDF being requested as an attachment or a viewable report.
var src_new = src_url.replace(/(ContentDisposition=).*?(&)/, '$1' + contentDisposition + '$2');
window.open("/printPDF.asx?url=" + encodeURIComponent("http://localhost:5402"+src_new));
PrintPDF.aspx File is like this
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Action;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace WebApp.WebAPI
{
/// <summary>
/// Summary description for printPDF
/// </summary>
public class printPDF : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World");
string url = context.Request.QueryString["url"];
// Download data.
DownloadFile(url, context.Server.MapPath("~/pdf/pdffile.pdf"), context.Request).Wait();
PdfDocument pdfDoc = new PdfDocument(new PdfReader(context.Server.MapPath("~/pdf/pdffile.pdf")), new PdfWriter(context.Server.MapPath("~/pdf/pdffileAuto.pdf")));
// add content
PdfAction action = PdfAction.CreateJavaScript("this.print({bUI: true, bSilent: true, bShrinkToFit: true});");
pdfDoc.GetCatalog().SetOpenAction(action);
pdfDoc.Close();
context.Response.Clear();
context.Response.ContentType = "application/pdf";
context.Response.AddHeader("Content-Disposition",
"AlwaysInline;filename=\"FileName.pdf\"");
context.Response.BinaryWrite(File.ReadAllBytes(context.Server.MapPath("~/pdf/pdffileAuto.pdf")));
context.Response.Flush();
context.Response.End();
}
public async Task DownloadFile(string url, string destinationPath, HttpRequest req)
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
var encoding = new UTF8Encoding();
request.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-IN");
request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
request.Accept = "text/html, application/xhtml+xml, image/jxr, */*";
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko";
request.KeepAlive = true;
request.Proxy = null;
request.CookieContainer = new CookieContainer();
Uri target = new Uri("http://localhost:5402/");
foreach (String item in req.Cookies)
{
request.CookieContainer.Add(new Cookie(item, req.Cookies[item].Value) { Domain = target.Host });
}
await request.GetResponseAsync().ContinueWith(t1 =>
{
using (var responseStream = t1.Result.GetResponseStream())
{
if (responseStream == null)
return;
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int bytesRead = 0;
using (FileStream fileStream = File.Create(destinationPath))
{
while ((bytesRead = responseStream.Read(buffer, 0, bufferSize)) != 0)
{
fileStream.Write(buffer, 0, bytesRead);
}
}
}
t1.Result.Close();
});
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
line
await request.GetResponseAsync().ContinueWith(t1 =>
with async and without async takes around 15 min time once, second time it go to deadlock/Freez
also i had to add cookie due to the url was throwing 500 internal server error.
And if i call url direct on browser it runs in 1 sec.
So if anyone know what is issue or can help then that would be really big help.
Thanks for Help in Advance.
Ok
I found what issue is,
Issue is tab request PrintPDF.aspx and that page request other URL on same site.
So untill PrintPDF.aspx response complete to tab that (HttpWebRequest) is not being called.
Any reason why? i set maxconnection in web.config though
I had to fix it by making 2 diff files, first ASPX file which show page and generate pdf in thread and on page load call Ashx file which checks if file is generated or not, if generated then return file.
there was not other way, so i fixed it by 2 links redirect call.
Thank Everyone who helped me.

I cannot execute ShellExecute from javascript to run a Windows Form with parameters

is it really possible to run an application installed on a users machine with parameters using an activex control. I can successfully run the application in this form:
$('#ejecutarActivo').click(function () {
var Comando = $('#Comando').val();
if (Comando.trim() != "") {
try {
var objShell = new window.ActiveXObject("shell.application");
objShell.ShellExecute('C:\\Users\\Jerry\\Documents\\visual studio 2012\\Projects\\PruebaComandos\\PruebaComandos\\bin\\Debug\\PruebaComandos.exe', '', '', 'open',1);
}
catch (e) {
alert('Active opciones de seguridad y utilice el navegador Internet Explorer');
}
}
});
However I don't seem to be able to run it with parameters. I really need to run it that way and I'm able to run it with the parameters from the command line, but I've tried almost every combination of single and double quotes, and also simply putting the variable name (e.g. "Comando") in the invocation but everytime I put something inside the parameter section, (which according to Microsoft documentation MSDN is the second parameter to ShellExecute) the application starts in my computer but nothing is displayed on the screen (I mean, I see the application is running in the Task Manager but something goes wrong and nothing displays).
I need to check also the application to see if something is going wrong in the windows form. But I would like to know what's wrong in the way I'm invoking the activex.
Can anybody help?
I found the answer, it wasn't a problem with ShellExecute javascript method. Actually, oops!, it was a problem with my Windows Form, I guess I will better gain a better understanding of Serial Ports before I ask.
I left the javascript like so:
$('#ejecutarActivo').click(function () {
var Comando = $('#Comando').val();
if (Comando.trim() != "") {
try {
var objShell = new window.ActiveXObject("shell.application");
if (Comando.indexOf('"') != -1) {
Comando = Comando.replace(/"+/g, '"""');
}
objShell.ShellExecute('C:\\Users\\Jerry\\Documents\\visual studio 2012\\Projects\\PruebaComandos\\PruebaComandos\\bin\\Debug\\PruebaComandos.exe', Comando , '', 'open', 1);
}
catch (e) {
alert('Active opciones de seguridad y utilice el navegador Internet Explorer');
}
}
});
And the code of the Windows Form goes like so: (It was a problem related to the port not closing before another invocation, which crashed the application. It's surprisingly simple)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;
namespace PruebaComandos
{
public partial class Form1 : Form
{
SerialPort Puerto = new SerialPort();
string buffer = String.Empty;
Thread DemoThread;
byte[] Existen;
public Form1(string argumento)
{
InitializeComponent();
Puerto.PortName = "Com4";
Puerto.BaudRate = 9600;
this.textoComandoLinea.Text = argumento;
Puerto.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
CloseSerial();
OpenSerial();
Puerto.Write(argumento + "\r\n");
}
public Form1()
{
InitializeComponent();
Puerto.PortName = "Com4";
Puerto.BaudRate = 9600;
Puerto.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
CloseSerial();
OpenSerial();
Puerto.Write("Inicio");
}
private void botonSend_Click(object sender, EventArgs e)
{
string Input = textoComandoLinea.Text;
OpenSerial();
Puerto.Write(Input);
}
void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
switch (e.EventType)
{
case SerialData.Chars:
buffer += sp.ReadExisting();
this.DemoThread = new Thread(new ThreadStart(ThreadProcSafe));
this.DemoThread.Start();
break;
case SerialData.Eof:
CloseSerial();
break;
}
}
void OpenSerial()
{
if (!Puerto.IsOpen)
{
Puerto.Open();
}
}
void CloseSerial()
{
if (Puerto.IsOpen)
{
Puerto.Close();
}
}
private void ThreadProcSafe()
{
this.SetText(buffer);
//CloseSerial();
}
delegate void SetTextCallback(string text);
private void SetText(string text)
{
if (this.textoRecibido.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.BeginInvoke(d, new object[] { text });
}
else
{
if (text.EndsWith("\r\n"))
{
this.textoRecibido.Text = text;
if (MessageBox.Show(this, text, "", MessageBoxButtons.YesNo, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, (MessageBoxOptions)0x40000) == DialogResult.Yes)
{
Application.Exit();
}
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Minimized;
}
}
}
Anyway, the question was dumb enough to be closed in a day, I only post my code in case it helps someone. Goodbye.

UWP WebView calls dynamic JavaScript

I have studied Window Universal App these days. When working with WebView, I see it can invoke a script inside the html file, but how about executing an external JavaScript script?
WebView webview = new WebView();
webview.Navigate(new Uri("https://www.google.com"));
string script = #"
function getBodyHTML()
{
var innerHTML = document.getElementsByTagName('body')[0].innerHTML;
return innerHTML;
}
";
I want to get the bodyHTML, possibly using something like this:
// pseudo code
webview.IncludeScript(script);
string bodyHTML = webview.ExecuteScript("getBodyHTML()");
oops, just realize that the similar question was answered.
I could do my thing by:
string[] arguments = new string[] {#"document.getElementsByTagName('body')[0].innerHTML;"};
try
{
string bodyHTML = await webview.InvokeScriptAsync("eval", arguments);
}
catch (Exception ex)
{
}

Create application based on Website

I searched and tried a lot to develop an application which uses the content of a Website. I just saw the StackExchange app, which looks like I want to develop my application. The difference between web and application is here:
Browser:
App:
As you can see, there are some differences between the Browser and the App.
I hope somebody knows how to create an app like that, because after hours of searching I just found the solution of using a simple WebView (which is just a 1:1 like the browser) or to use Javascript in the app to remove some content (which is actually a bit buggy...).
To repeat: the point is, I want to get the content of a website (on start of the app) and to put it inside my application.
Cheers.
What you want to do is to scrape the websites in question by getting their html code and sorting it using some form of logic - I recomend xPath for this. then you can implement this data into some nice native interface.
You need however to be very aware that the data you get is not allways formated the way you want so all of your algorithems have to be very flexible.
the proccess can be cut into steps like this
retrive data from website (DefaultHttpClient and AsyncTask)
analyse and retrive relevant data (your relevant algorithm)
show data to user (Your interface implementation)
UPDATE
Bellow is some example code to fetch some data of a website it implements html-cleaner libary and you will need to implement this in your project.
class GetStationsClass extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET, "iso-8859-1");
HttpPost httppost = new HttpPost("http://ntlive.dk/rt/route?id=786");
httppost.setHeader("Accept-Charset", "iso-8859-1, unicode-1-1;q=0.8");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "utf-8"));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
int status = response.getStatusLine().getStatusCode();
String data = "";
if (status != HttpStatus.SC_OK) {
ByteArrayOutputStream ostream = new ByteArrayOutputStream();
response.getEntity().writeTo(ostream);
data = ostream.toString();
} else {
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(),
"iso-8859-1"));
String line = null;
while ((line = reader.readLine()) != null) {
data += line;
}
XPath xpath = XPathFactory.newInstance().newXPath();
try {
Document document = readDocument(data);
NodeList nodes = (NodeList) xpath.evaluate("//*[#id=\"container\"]/ul/li", document,
XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++) {
Node thisNode = nodes.item(i);
Log.v("",thisNode.getTextContent().trim);
}
} catch (XPathExpressionException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//update user interface here
}
}
private Document readDocument(String content) {
Long timeStart = new Date().getTime();
TagNode tagNode = new HtmlCleaner().clean(content);
Document doc = null;
try {
doc = new DomSerializer(new CleanerProperties()).createDOM(tagNode);
return doc;
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return doc;
}
to run the code above use
new getStationsClass.execute();

Capturing console.log within a UIWebView

I'm writing an iOS application with MonoTouch that does some javascript interaction with a UIWebView. For debugging purposes, it would be nice to be able to "capture" console.log in the javascript that runs in the UIWebView together with the rest of the application output. Is this possible? Examples using regular Objective-C code is also OK.
After some more googling, I came about this answer: Javascript console.log() in an iOS UIWebView
Converting it to MonoTouch yields this solution:
using System;
using System.Web;
using System.Json;
using MonoTouch.UIKit;
namespace View
{
public class JsBridgeWebView : UIWebView
{
public object BridgeDelegate {get;set;}
private const string BRIDGE_JS = #"
function invokeNative(functionName, args) {
var iframe = document.createElement('IFRAME');
iframe.setAttribute('src', 'jsbridge://' + functionName + '#' + JSON.stringify(args));
document.documentElement.appendChild(iframe);
iframe.parentNode.removeChild(iframe);
iframe = null;
}
var console = {
log: function(msg) {
invokeNative('Log', [msg]);
}
};
";
public JsBridgeWebView ()
{
ShouldStartLoad += LoadHandler;
LoadFinished += (sender, e) => {
EvaluateJavascript(BRIDGE_JS);
};
}
public bool LoadHandler (UIWebView webView, MonoTouch.Foundation.NSUrlRequest request, UIWebViewNavigationType navigationType)
{
var url = request.Url;
if(url.Scheme.Equals("jsbridge")) {
var func = url.Host;
if(func.Equals("Log")) {
// console.log
var args = JsonObject.Parse(HttpUtility.UrlDecode(url.Fragment));
var msg = (string)args[0];
Console.WriteLine(msg);
return false;
}
return true;
}
}
}
}
Now all console.log statements in javascript in a UIWebView will be sent to Console.WriteLine. This could of course be extended to any kind of output one would want.
Can you add javascript code that does something like this to overwrite the method:
console.log = function(var text) {
consoleforios += text;
}
Then from the web view, call:
string console = webView.EvaluatingJavaScript("return consoleforios;");
This might not be something I'd leave in permanently, but it should work.

Categories

Resources