Unsafe JavaScript error writing to C# variable - c#

I have some JavaScript in a page that takes the values passed by a module Window and assigns it to a C# variable, so it can be used within the code behind. So my JavaScript looks like:
The JavaScript
<script type="text/javascript">
function openSecure(args) {
var manager = $find("<%= rwmSecure.ClientID %>");
var domain = '<%=ConfigurationManager.AppSettings("CPCDomain").ToString %>';
var URL;
if (domain == 'localhost') {
URL = 'http://localhost';
}
URL += "/WindowPage.aspx?args=" + args;
manager.open(URL, "rwSecure");
}
function OnClientCloseSecure(oWnd, args) {
var arg = args.get_argument();
if (arg) {
var ResultCode = arg.ResultCode;
document.getElementById("hdnResultCode").value = ResultCode;
var AuthCode = arg.AuthCode;
var ReferenceNumber = arg.ReferenceNumber;
var TransactionID = arg.TransactionID;
var ErrorCode = arg.ErrorCode;
var ErrorDescription = arg.ErrorDescription;
var CardNumber = arg.CardNumber;
var PONumber = arg.PONumber;
//document.getElementById('<%=btn.ClientID %>').click();
__doPostBack('pnlComplete', '');
}
}
</script>
And to clarify this a bit more. The Module window is pulling in a page from localhost, but the Module window is being called from a page on localhost:61156. So once the javascript sets the variavle it also issues a click command on a asp.net button to run some code:
C# Code
protected void btn_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(hdnResultCode.Value)) {
dspConfirm();
pnlComplete.Visible = false;
pnlConfirm.Visible = true;
} else {
dspComplete();
pnlComplete.Visible = true;
pnlConfirm.Visible = false;
}
}
So when I run this I get a javascript error that says:
Unsafe JavaScript attempt to access frame with URL http://localhost/SecurePayment.aspx?args=H4sIAAAAAAAEAOy9B2AcSZYlJi9tynt%2fSvVK1%2bB0oQiAYBMk2JBAEOzBiM3mkuwdaUcjKasqgcplVmVdZhZAzO2dvPfee%2b%2b999577733ujudTif33%2f8%2fXGZkAWz2zkrayZ4hgKrIHz9%2bfB8%2fIr578jMnL09%2b5k3etG%2fqbNlk07aolj%2bzi%2bdndsY7u%2f9PAAAA%2f%2f8VkT5ZIQAAAA%3d%3d&rwndrnd=0.23641548841260374 from frame with URL http://localhost:65116/ShoppingCart.aspx. Domains, protocols and ports must match.
b.RadWindow._registerChildPageHandlersScriptResource.axd?d=vMihE91hOtu6KBE47c3D9AjqD9Il5YI4LpCLhSvp5YZn6p98cl2a_AbJJmNWVZfnmjtLnCnYEoaBHBC919OsikIEmKq8TGOzWNWN_HUBLLo8fW7DdN4EuN3Q076lAa_FOwh_Yk2b3DL-W2Fv0&t=38ec0598:1125
b.RadWindow._onIframeLoadScriptResource.axd?d=vMihE91hOtu6KBE47c3D9AjqD9Il5YI4LpCLhSvp5YZn6p98cl2a_AbJJmNWVZfnmjtLnCnYEoaBHBC919OsikIEmKq8TGOzWNWN_HUBLLo8fW7DdN4EuN3Q076lAa_FOwh_Yk2b3DL-W2Fv0&t=38ec0598:1143
(anonymous function)ScriptResource.axd:47
Sys$UI$DomEvent$addHandler.browserHandlerScriptResource.axd:4048
So is there any possible way around this or way to fix this? I've been scratching my head for two days and I'm ready to throw my keyboard. :) Thanks!

Your javascript error is pretty informative.
Unsafe JavaScript attempt to access frame with URL
http://localhost/SecurePayment.aspx?args=... from frame with URL
http://localhost:65116/ShoppingCart.aspx. Domains, protocols and
ports must match.
This sounds like an exception with the Same Origin Policy
The policy permits scripts running on pages originating from the same
site to access each other's methods and properties with no specific
restrictions, but prevents access to most methods and properties
across pages on different sites.[1]
and
The term "origin" is defined using the domain name, application layer
protocol, and (in most browsers) port number of the HTML document
running the script. Two resources are considered to be of the same
origin if and only if all these values are exactly the same.
Your script is running on your local machine in a site at a particular port, but trying to access a page on your local machine at a different port. I'd start there.

Related

Tuespechkin takes a long time to respond, and returns null

I'm currently using in my project TuesPechkin version 2.1.1, and also TuesPechkin.Wkhtmltox.AnyCPU v0.12.4.1
This is some of my code:
byte[] result = null;
try
{
var globalSettings = CreateGlobalSettings(portraitMode);
var objectSettings = CreateObjectSettings(websiteUrl, urlParameters);
var document = new HtmlToPdfDocument
{
GlobalSettings = globalSettings
};
document.Objects.Add(objectSettings);
CreateEventLog.CreateInformationLog("Ready to convert PDF");
result = Converter.Convert(document);
CreateEventLog.CreateInformationLog(result == null
? "Conversion failed using the Pechkin library"
: "PDF conversion finished");
I run this code in 3 different environments:
On my local machine it runs fine and it generates the file in 3 seconds.
On one of my servers (let's call it Server A) it runs fine and it generates the file in 3 seconds.
On the other of my servers (let's call it Server B) it holds for 1min (for some reason I don't understand) during the Converter.Convert part, and after that minute it returns null.
Server A and Server B have the same setup (CPU, RAM, etc)
There's no peak increase on Server B during conversion.
Any suggestions/ideas?
I found what the issue is.
The URL I'm trying to convert is in a Presentation Layer, which is deployed in a separate server. Pechkin converter is in a Business Layer.
In Server A, I can access the URL from the Business Server.
In Server B, I cannot access the URL from the Business Server.
This is probably some firewall exception that needs to be created.
It would be nice though to have TuesPechkin, returning an error saying it cannot access the URL.
It is important to check how you get the convert, dispose issue may cause problem
Just check code form here
public static IConverter GetConverter()
{
lock (Locker)
{
if (converter != null)
{
return converter;
}
var tempFolderDeployment = new TempFolderDeployment();
var winAnyCpuEmbeddedDeployment = new WinAnyCPUEmbeddedDeployment(tempFolderDeployment);
IToolset toolSet;
if (HostingEnvironment.IsHosted)
{
toolSet = new RemotingToolset<PdfToolset>(winAnyCpuEmbeddedDeployment);
}
else
{
toolSet = new PdfToolset(winAnyCpuEmbeddedDeployment);
}
converter = new ThreadSafeConverter(toolSet);
}
return converter;
}

Grabbing Dropbox access token on Windows Form using Dropbox API

I have done a class which already works with the Dropbox API uploading files, downloading, deleting and so on. It has been working quite well since I was just using my own access token, but I need to register other users and a single but "big" problem appeared: retrieving the access token.
1.- Redirect URI? I'm starting to doubt why do I need this. I finally used this URI (https://www.dropbox.com/1/oauth2/redirect_receiver) because "The redirect URI you use doesn't really matter" Of course I included this one on my app config on Dropbox.
2.- I reach the user's account (I can see the user's count increased and I see the app has access to the user's account.
3.- I have a breakpoint on my code to inspect the variables in order to apply the DropboxOAuth2Helper.ParseTokenFragment but I have no success on there.
This is my code, but on the if before the try catch is where it gets stuck:
string AccessToken;
const string AppKey = "theOneAtmyAppConfigOnDropbox";
const string redirectUrl = "https://www.dropbox.com/1/oauth2/redirect_receiver";
string oauthUrl =
$#"https://www.dropbox.com/1/oauth2/authorize?response_type=token&redirect_uri={redirectUrl}&client_id={AppKey}";
private string oauth2State;
private bool Result;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Start(AppKey, webBrowser1);
webBrowser1.Navigating += Browser_Navigating;
}
private void Start(string appKey, WebBrowser w)
{
this.oauth2State = Guid.NewGuid().ToString("N");
Uri authorizeUri = DropboxOAuth2Helper.GetAuthorizeUri(OauthResponseType.Token, appKey, redirectUrl, state: oauth2State);
w.Navigate(authorizeUri);
}
private void Browser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
if (!e.Url.ToString().StartsWith(redirectUrl, StringComparison.InvariantCultureIgnoreCase))
{
// we need to ignore all navigation that isn't to the redirect uri.
return;
}
try
{
OAuth2Response result = DropboxOAuth2Helper.ParseTokenFragment(e.Url);
if (result.State != this.oauth2State)
{
// The state in the response doesn't match the state in the request.
return;
}
this.AccessToken = result.AccessToken;
this.Result = true;
}
catch (ArgumentException)
{
// There was an error in the URI passed to ParseTokenFragment
}
finally
{
e.Cancel = true;
this.Close();
}
}
I've been fighting against this for hours and I'm starting to see the things a little cloudy at this point.
This is the tutorial I used, but I'm not moving forward. I would really appreciate any help!
EDIT: I finally made some steps forward. I changed the line which contains
Uri authorizeUri2 = DropboxOAuth2Helper.GetAuthorizeUri(appKey);
Now I'm showing the generated access token on the WebClient! Bad part comes when trying to get it (it gets inside the if) and it gets generated every time I ask the user for permission, so it gets overwrited.
EDIT 2: I noted the token I get generated on the browser is somehow malformed. I try to manually change it hardcored when I'm debugging and I get an exception when an AuthException when creating the DropboxClient object :( What the hell!
As Greg stated, the solution was using the event Browser_Navigated. Looks like the version of the embedded IE my Visual Studio (2015) uses didn't notice that if it's a redirect, it won't launch the event BrowserNavigating.

CoolUtils TotalPDFPrinterX causes ASP C# site to crash

My company has purchased the CoolUtils TotalPDFPrinterX from https://www.coolutils.com/TotalPDFPrinterX
I make an HTTP PUT from Postman to the API and I get “Could not get any response”.
When running on my Windows machine the PDF prints fine however on the server the site crashes and in the event log I get the error "A process serving application pool '[MY_APP_POOL]' failed to respond to a ping. The process id was '[MY_PROCESS_ID]'."
Here is my C# code:
PDFPrinterX ppx = new PDFPrinterX();
ppx.Print(fileName, printerName, "-ap Default");
if (ppx.ErrorMessage != null)
{
WriteToSQL(id, false, ppx.ErrorMessage, 2);
Console.WriteLine(ppx.ErrorMessage);
}
By writing to the event log I know the site crashes on this line: PDFPrinterX ppx = new PDFPrinterX(); I have also surrounded the above code with a try catch and no exception is thrown. The site still crashes.
Things I have tried:
Uninstalling and Reinstalling the CoolUtils software
Giving EVERYONE Full control to the site folder and the CoolUtils program folder
Creating a C# desktop application using the same code. THIS WORKS FINE ON THE SERVER. It's just the ASP site that crashes.
Does anyone know what might be causing this?
The more I research this thing online the more I'm inclined to say that ActiveX which is the X in PDFPrinterX doesn't seem to work well when hosted in IIS.
I've seen a few forums where they say it works fine when they debug on localhost but when deployed to server is crashes.
...works fine when used inside localhost(Visual studio)
One of their feature pages shows that it requires Win 2000/NT/XP/2003/Vista/7
You should look into whether your server supports ActiveX components that can work in conjunction with IIS.
Looking at one of their other products support page: TotalPDFConverterX:
the following note in my opinion may also apply to TotalPDFPrinterX, given its dependency on ActiveX as well.
Note: Pay attention to some details during installation Total PDF Converter X:
Do not forget to register ActiveX in your web-server account.
Total PDF Converter X supports only Internet Explorer, Mozilla and Firefox browsers.
ActiveX works only with 32-bit internet information server. 64-bit server is not supported. Use command line version instead.
Thanks to #Nkosi I was able to find a workaround.
ActiveX works only with 32-bit internet information server. 64-bit server is not supported. Use command line version instead.
Our IIS server is 64 bit so that is what probably caused the site to hang up.
Buttt... the command line still worked in printing the PDFs on the server.
Client side code (makes the HTTP POST):
private void SendToPrinter(string fileName, string printerName, int id, decimal documentSequence)
{
// use http client to make a POST to the print api
using (var client = new HttpClient())
{
// compile the values string to transfer in POST
// should finish to look something like this:
// C:\print.pdf&PRTFTW_OFIT&ValShip-155320-1
var values = new Dictionary<string, string>
{
{ "", fileName + "&" + printerName + "&ValShip-" + id + "-" + documentSequence},
};
// URL encode the values string
var content = new FormUrlEncodedContent(values);
// make the POST
// DEBUG
var response = client.PostAsync("http://localhost:54339/api/print", content);
// retrieve the response
var responseString = response.Result.ToString();
}
}
Server side code (receives the HTTP POST):
using System;
using System.Net.Http;
using System.Web;
using System.Web.Http;
namespace api.valbruna.print.Controllers
{
public class PrintController : ApiController
{
// POST api/print
public HttpResponseMessage Post(HttpRequestMessage request)
{
try
{
// parse the content recieved from the client
var content = request.Content.ReadAsStringAsync().Result;
// decode the content, certain characters such as
// '&' get encoded to URL lingo such as '%26'
content = HttpUtility.UrlDecode(content);
// split the string into 3 seperate parts
String[] str = content.Split('&');
// remove the equal sign from the first string
str[0] = str[0].Trim('=');
// compile the arguments command line string
// should finish to look something like this:
// "C:\Program Files (x86)\CoolUtils\Total PDF PrinterX\PDFPrinterX.exe" "C:\print.pdf" -p"\\PRINTERS\PRTFTW_OFIT" -ap Default -log "C:\inetpub\logs\CoolUtils\log-ValShip-155320-4.txt" -verbosity detail"
String arguments = "\"" + str[0] + "\" -p\"\\\\PRINTERS\\" + str[1] +
"\" -ap Default -log \"C:\\inetpub\\logs\\CoolUtils\\log-" + str[2] +
".txt\" -verbosity detail";
// file location for PDFPrinterX.exe
String file = #"C:\Program Files (x86)\CoolUtils\Total PDF PrinterX\PDFPrinterX.exe";
// start the process
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
startInfo.FileName = file;
startInfo.Arguments = arguments;
process.StartInfo = startInfo;
process.Start();
return new HttpResponseMessage() { Content = new StringContent(content) };
}
catch (Exception e)
{
return new HttpResponseMessage() { Content = new StringContent(e.Message) };
}
}
}
}

Capture Lightstreamer HTTP Data using Fiddler?

I am using Fiddler to catch updates sent to a page via LightStreamer. I am creating a FiddlerCore proxy and connecting a Selenium ChromeDriver instance to it. My automation navigates Chrome to the page, and data comes through the proxy.
Once loaded, the updates to the page (via LightStreamer) visibly appear on the page but they do not come through the AfterSessionComplete event.
If I run the Fiddler desktop application instead of launching my proxy (comment out "StartProxy()") all of the updates (via LightStreamer) come through and appear inside the application. They appear has HTTPS data, but other HTTPS data appears to come through.
I have also using tried the BeforeResponse event instead of AfterSessionCompleted.
Here's my code:
static void Main(string[] args)
{
StartProxy();
var seleniumProxy = new Proxy { HttpProxy = "localhost:8888", SslProxy = "localhost:8888" };
var chromeOptions = new ChromeOptions { Proxy = seleniumProxy };
var path = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) + "\\ChromeDriver\\";
var chromeService = ChromeDriverService.CreateDefaultService(path);
var driver = new ChromeDriver(chromeService, chromeOptions);
driver.Navigate().GoToUrl("https://mywebpage.com");
// page loads and updates start flowing
Console.ReadLine();
driver.Dispose();
StopProxy();
}
private static void FiddlerApplication_AfterSessionComplete(Session session)
{
// data comes through, just not the LightStreamer Data
var respBody = session.GetResponseBodyAsString();
Console.WriteLine(respBody);
// do something with the response body.
}
static void StartProxy()
{
if (FiddlerApplication.IsStarted())
FiddlerApplication.Shutdown();
FiddlerApplication.AfterSessionComplete += FiddlerApplication_AfterSessionComplete;
FiddlerApplication.Startup(8888, FiddlerCoreStartupFlags.DecryptSSL);
}
static void StopProxy()
{
FiddlerApplication.AfterSessionComplete -= FiddlerApplication_AfterSessionComplete;
if (FiddlerApplication.IsStarted())
FiddlerApplication.Shutdown();
}
Thanks for your help.
Update: I've also tried to use the flag: FiddlerCoreStartupFlags.Default instead of FiddlerCoreStartupFlags.DecryptSSL when starting fiddler with no luck.

How to intercept when user click on a link in a webbrowser

I'm trying to intercept tapping on a link in a WebBrowser control.
My HTML page contains custom links, for some starting with shared:// I'd like to intercept when the user tap on it.
On iPhone I would use the webView:shouldStartLoadWithRequest:navigationType: method, and look at the URL that is selected.
I haven't managed to reproduce a similar behaviour with Silverlight for Windows Phone.
I do something like:
{
webBrowser1.Navigating += new EventHandler<NavigatingEventArgs>(webBrowser1_Navigating);
}
void webBrowser1_Navigating(object sender, NavigatingEventArgs e)
{
string scheme = null;
try
{
scheme = e.Uri.Scheme; // <- this is throwing an exception here
}
catch
{
}
if (scheme == null || scheme == "file")
return;
// Not going to follow any other link
e.Cancel = true;
if (scheme == "shared")
{
}
But I guess an exception when reading some properties of the Uri, when it's a standard Uri with a default file:// URL
Additionally, the Navigating event isn't even triggered for links starting with shared://
Now that I'm able to capture tapping on a shared:// I do not care much, but at least I'd like to be able to retrieve the URL we're going to navigate to, and cancel the default operation for a particular URL.
Any ideas what's going on?
Thanks
Edit:
It turned out that the problem is that the Navigating event is only generated for the following links: file://, http:// or mailto://
The scheme attributes of the Uri is only available for the http:// and mailto:// links
so what I did in the end is replace the shared:// link with http://shared/blah ... And I look at the URL... This works for my purpose. I can now have links that have a different action (like opening an extra window) depending on the links in the html.
Here is my final code, in case this is useful for someone in the future:
For an about screen, I use an html file displayed in a WebBrowser component.
The about page has a "tell your friend about this app" link as well as links to external web site.
It also has local subpages.
Local sub-pages are linked to using a file:// link. Those can be navigated within the WebBrowser component.
External links are opened externally with Internet Explorer.
Tell your friend link is made of a http://shared link, that opens an email with a pre-set subject and body. Unfortunately, no other scheme than the standard ones are usable as they do not trigger a Navigating event
There's also a support link which is a mailto:// link and opens an EmailComposeTask
void webBrowser1_Navigating(object sender, NavigatingEventArgs e)
{
String scheme = null;
try
{
scheme = e.Uri.Scheme;
}
catch
{
}
if (scheme == null || scheme == "file")
return;
// Not going to follow any other link
e.Cancel = true;
if (scheme == "http")
{
// Check if it's the "shared" URL
if (e.Uri.Host == "shared")
{
// Start email
EmailComposeTask emailComposeTask = new EmailComposeTask();
emailComposeTask.Subject = "Sharing an app with you";
emailComposeTask.Body = "You may like this app...";
emailComposeTask.Show();
}
else
{
// start it in Internet Explorer
WebBrowserTask webBrowserTask = new WebBrowserTask();
webBrowserTask.Uri = new Uri(e.Uri.AbsoluteUri);
webBrowserTask.Show();
}
}
if (scheme == "mailto")
{
EmailComposeTask emailComposeTask = new EmailComposeTask();
emailComposeTask.To = e.Uri.AbsoluteUri;
emailComposeTask.Show();
}
}

Categories

Resources