i'm using geckofx 29. how i can call c# function on javascript event ?
i search and find this solution, but its not working:
public void AddEventListener_JScriptFiresEvent_ListenerIsCalledWithMessage()
{
string payload = null;
browser.AddMessageEventListener("callMe", ((string p) => payload = p));
browser.LoadHtml(
#"<!DOCTYPE html>
<html><head>
<script type='text/javascript'>
window.onload= function() {
event = document.createEvent('MessageEvent');
var origin = window.location.protocol + '//' + window.location.host;
event.initMessageEvent ('callMe', true, true, 'some data', origin, 1234, window, null);
document.dispatchEvent (event);
}
</script>
</head><body></body></html>");
browser.NavigateFinishedNotifier.BlockUntilNavigationFinished();
Assert.AreEqual("some data", payload);
}
event.initMessageEvent can not execute ...
please help me
The message event interface has been updated. The initMessageEvent method no longer exists. Look here at bottom of the thread. According to that body of your onload function should be:
var event = new MessageEvent('callMe', { 'view': window, 'bubbles': false, 'cancelable': false, 'data': 'some data' });
document.dispatchEvent(event);
Hope this helps.
Related
I have an old VB6 application - I need to shell out to a ASP.net site via a web browser. I have the browser opening and calling the ASP site successfully. I need the VB6 app to know when the Web Browser session is closed. The VB app form (or save button) needs to be disabled when the web browser session is open. (I don't want to use the process Id of the windows process to check this.)
My thought are:
Cross domain cookies perhaps? (security?)
I have my VB6 app able to call server WebMethods
Saving a session ID in the database which is usedbut both apps?
Some advice would be excellent. Many thanks.
Internal Company Applications.
Desktop App (VB6)
Code to allow VB6 apps to contact Asp service. On any Asp.Net page create an extra [WebMethod] in this case a ‘IsWindowOpen’ method has been added to the test.aspx page (see red text beow)
Send a JSON message to the ASP.Net service to query if a WINDOWS_STATUS Session variable is set (this tells us if a browser window is open\closed).
When shelling out to the Asp.Net site with parameters (plan Id etc.) we’ll send in an extra param for ‘Session Id’.
Randomly generate a Session Id in VB6 app [random: 24 char long, lower case, and digits between 0-5], this is replicating how the Asp.Net framework is going to generate its own Session Id for communication between the HTML and C#. We will then override the Asp.Net Session Id given to us by Asp.Net with our own random generated Session ID.
Check if ASP.Net session variable is set in VB6:
Private Sub Command1_Click()
Dim objHTTP As Object
Dim Json As String
Dim result As String
' === Check if Browser Session is open ===
Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
url = "http://dub-iisdev/SessionTest/test.aspx/IsWindowOpen"
objHTTP.open "POST", url, False
objHTTP.setRequestHeader("cookie") = "ASP.NET_SessionId=" + txtCookie.Text ' Required twice
objHTTP.setRequestHeader("cookie") = "ASP.NET_SessionId=" + txtCookie.Text ' Required twice
objHTTP.setRequestHeader "Content-type", "application/json"
objHTTP.send (Json)
result = objHTTP.responseText
txtOutput.Text = result
Set objHTTP = Nothing
End Sub
ASP.Net
We’ll need a few pieces of plumbing here :
A small method for setting ASP.Net session IDs
A small closing aspx page which will run some code when we leave the browser, and
Some extra C# methods and JavaScript in our existing pages.
1. Setting Session ID:
Copy variable from old session to new location
protected void ReGenerateSessionId(string newsessionID)
{
SessionIDManager manager = new SessionIDManager();
string oldId = manager.GetSessionID(Context);
string newId = manager.CreateSessionID(Context);
bool isAdd = false, isRedir = false;
manager.RemoveSessionID(Context);
manager.SaveSessionID(Context, newsessionID, out isRedir, out isAdd);
HttpApplication ctx = (HttpApplication)HttpContext.Current.ApplicationInstance;
HttpModuleCollection mods = ctx.Modules;
System.Web.SessionState.SessionStateModule ssm = (SessionStateModule)mods.Get("Session");
System.Reflection.FieldInfo[] fields = ssm.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
SessionStateStoreProviderBase store = null;
System.Reflection.FieldInfo rqIdField = null, rqLockIdField = null, rqStateNotFoundField = null;
SessionStateStoreData rqItem = null;
foreach (System.Reflection.FieldInfo field in fields)
{
if (field.Name.Equals("_store")) store = (SessionStateStoreProviderBase)field.GetValue(ssm);
if (field.Name.Equals("_rqId")) rqIdField = field;
if (field.Name.Equals("_rqLockId")) rqLockIdField = field;
if (field.Name.Equals("_rqSessionStateNotFound")) rqStateNotFoundField = field;
if ((field.Name.Equals("_rqItem")))
{
rqItem = (SessionStateStoreData)field.GetValue(ssm);
}
}
object lockId = rqLockIdField.GetValue(ssm);
if ((lockId != null) && (oldId != null))
{
store.RemoveItem(Context, oldId, lockId, rqItem);
}
rqStateNotFoundField.SetValue(ssm, true);
rqIdField.SetValue(ssm, newsessionID);
}
Your first landing page will set the new Session ID (from VB6) param sent into the server– using out ReGenerateSessionId class above.
After this code executes out instance to Asp.Net and our instance of VB6 will have the same Session Id for HTTP communication
protected void Page_Load(object sender, EventArgs e)
{
// Simulate Session ID coming in from VB6...
string sessionId;
Random rnd = new Random();
sessionId = "asdfghjklqwertyuiop12345" [24 char - a to z (small) & 0-5]
// Set new session variable and copy variable from old session to new location
ReGenerateSessionId(sessionId);
// Put something into the session
HttpContext.Current.Session["SOME_SESSION_VARIABLE_NAME"] = "Consider it done!";
}
2. Open\Closing Browser
One of the ASP.Net pages needs to have three new WebMethods: SetOpenWindow, SetClosingWindow and IsWindowOpen
Opening the Browser:
C#. SetOpenWindow:
This will be called from your first (or any required) HTML pages via the .ready JavaScript. When the page has loaded the JavaScript will simply fire an Ajax call to the SetOpwnWindow web method. The method will set a Session variable WINDOW_STATUS to OPEN.
[WebMethod()]
[ScriptMethod(UseHttpGet = false)]
public static string SetOpenWindow()
{
HttpContext.Current.Session["WINDOW_STATUS"] = "OPEN";
return "Status:" + HttpContext.Current.Session["WINDOW_STATUS"];
}
ASPX. Call SetOpenWindow from Ajax once the page has loaded. This sets the WINDOW_STATUS to OPEN
<script src=”Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
jQuery.ajax({
url: 'test.aspx/SetOpenWindow',
type: "POST",
dataType: "json",
data: "",
contentType: "application/json; charset=utf-8",
success: function (data) {}//alert(JSON.stringify(data));
});
$("#form1").submit(function () {
submitted = true;
});
});
</script>
Closing the Browser:
On pages where the browser window can be closed call JavaScript to catch when the browser window is closing (handy to add this to your master page instead of to each page!). This calls the ClosingSessionPage aspx page to run the SetClosingWndow webmethod:
<script type=”text/javascript”>
var submitted = false;
function wireUpWindowUnloadEvents() {
$(document).on('keypress', function (e) { if (e.keyCode == 116) { callServerForBrowserCloseEvent(); } }); // Attach the event keypress to exclude the F5 refresh
$(document).on("click", "a", function () { callServerForBrowserCloseEvent(); }); // Attach the event click for all links in the page
}
$(window).bind("onunload", function () { if (!submitted) { callServerForBrowserCloseEvent(); event.preventDefault(); } });
$(window).bind("beforeunload", function () { if (!submitted) { callServerForBrowserCloseEvent(); event.preventDefault(); } });
window.onbeforeunload = function () { if (!submitted) { callServerForBrowserCloseEvent(); } };
window.onunload = function () { if (!submitted) { callServerForBrowserCloseEvent(); } };
$(window).bind("onunload", function () { if (!submitted) { callServerForBrowserCloseEvent();event.preventDefault();} });
function callServerForBrowserCloseEvent() {
window.open("ClosingSessionPage.aspx", "Closing Page", "location=0,menubar=0,statusbar=1,width=1,height=1"); }
function btn_onclick() { open(location, '_self').close(); }
</script>
The close JavaScript method above redirects to a closing aspx page to run some ajax and then close itself – The Ajax calls SetClosingWindow the session WINDOW_STATUS variable to CLOSED.
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server" title="Closing Session">
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
jQuery.ajax({
url: 'test.aspx/SetClosingWndow',
type: "POST",
dataType: "json",
data: "",
contentType: "application/json; charset=utf-8",
success: function (data) {
window.close();
} }); });
</script>
</head>
<body>
<form id="form1" runat="server">
<p>Closing browser session, please wait.</p>
</form>
</body>
</html>
C# SetClosingWindow
Called from Ajax JavaScript when the Browser window is closing and sets WINDOW_STATUS to CLOSED:
[WebMethod()]
[ScriptMethod(UseHttpGet = false)]
public static string SetClosingWndow()
{
HttpContext.Current.Session["WINDOW_STATUS"] = "CLOSED";
ScriptManager.RegisterClientScriptBlock((Page)(HttpContext.Current.Handler), typeof(Page), "closePage", "window.close();", true);
return "Status:" + HttpContext.Current.Session["WINDOW_STATUS"];
}
3. Is Browser Open?
ASP.Net WebMethod called by VB6 whenever it needs to know if the Browser window is Open or Closed.
[WebMethod()]
[ScriptMethod(UseHttpGet = false)]
public static string IsWindowOpen()
{
string isWindowOpen = HttpContext.Current.Session["WINDOW_STATUS"] != null ? HttpContext.Current.Session["WINDOW_STATUS"].ToString() : "CLOSED";
return "IsWindowOpen:" + isWindowOpen;
}
I have a webmethod that returns a json string and populates a jstree and all works perfectly the 1st click of a text box. Each time a user clicks a different text box, it passes different values in the jquery but the webmethod actually doesn't get called after the 1st time it's called. So I'm wondering what I need to clear in order for it do call the webmethod each time.
function showtree1(thisID, line) {
$('#jstree_demo_div').jstree.empty;
$('#jstree_demo_div').jstree({
"core": {
"data": //data - jquery
{
type: "POST"
, dataType: "json"
, contentType: "application/json; charset=utf-8"
, url: "FlowCycleReport.aspx/populateTree"
//, data: "{'imgID':'" + thisID + "'}"
, data: JSON.stringify({ imgID: thisID, line: line })
//, "data": function (node) {
// //return "{'id':'" + $(node).attr("id") + "'}";
// return node.d;
//}
, success: function (node) {
var ReturnString = node.d;
// alert(ReturnString);
return { "id": node.id };
}///success
, error: function (msg) {
alert("Error: " + msg.responseText);
}///error
}//data
}///core
,
"plugins": ["themes", "json_data", "search", "contextmenu", "types"]
});
}
WebMethod:
[WebMethod]
//public static string populateTree(string imgID, int node)
public static string populateTree(string imgID, string line)
{
DAL_Flow DL = new DAL_Flow();
//string line = "278";
string nodevalues = DL.JsonNav(imgID, line);
return nodevalues;
}
onclick event:
$(function () {
$(".textbox").click(function (e) {
var thisID = $(e.target).attr("ID");
var csID = thisID.substr(thisID.lastIndexOf("_") + 1);
$('#posDetailDiv').hide();
var line = $('#dlLine').val();
// Reset the header:
$('#PartHeaderDiv').empty();
$('#PartHeaderDiv').append('Line Number: ' + line + ': Control Station ' + csID);
showtree1(csID, line);
$('#posDetailDiv').show();
});
});
script manager:
<asp:toolkitscriptmanager runat="server" EnablePageMethods="true" ></asp:toolkitscriptmanager>
The values for CSID and line changes on my header each click but the treeview values don't.
I've put a breakpoint on the webmethod to verify that the webmethod isn't getting hit.
I'm sure I'm just missing something.
Can anyone help?
First thing i can think of is that since you wipe out everything and rebuild it every time it is clicked, your .click event gets wiped out too since it is not dynamically bonded. So instead of doing:
$(".textbox").click(function (e) {
you can do:
$(".textbox").on('click', function (e) {
//click event code goes here
});
so your click event would be registered all the time even for the dynamic .textbox elements that are added later on.
I need to fire this script from code behind only on certain dates specified in the database
I need to show an image as a fancybox based on the date specified in CMS system.
I will write my logic to show image or not in the Default.aspx and then somehow pass this piece of code from default.cs to MarterPage Javascript $(window).load(function () Code Block
<Script>
$(window).load(function () {
I want this code to fire at a particular location of master page. I am not sure suppose here.
///HERE???
});
</Script>
I want to pass below script as a value so that it js execute ///HERE??? part of code
Page.ClientScript.RegisterStartupScript(this.GetType(), "MyScript", "$('a.fancybox-messageboard').fancybox({ width: 600, height: 440,closeClick: true, hideOnOverlayClick: true, href: 'http://upload.wikimedia.org/wikipedia/commons/1/1a/Bachalpseeflowers.jpg' }).trigger('click');", true);
I am bit lost with this ...
I simple want to do my logic check in Default.aspc file and show image as a fancy box only in default.aspx page. But my ' $(window).load(function () { });code block is in MasterPage file if i write another ' $(window).load(function () { }); in default.aspx file then fancy box is not showing properly.
How can i achieve this without any issue
UPDATE:
I managed to pull it off.. this is based on the solution posted by Irina Bogomaz.
So far this is working I can add full logic to code-behind later on.
$(window).load(function () {
if (window.showMessage) {
// alert(imgPath);
//logic to create fancybox
$("a.fancybox-messageboard").fancybox({
width: 600,
height: 440,
closeClick: true,
hideOnOverlayClick: true,
href: imgPath
}).trigger('click');
}
});
CODE BEHIND
protected override void OnPreRender(EventArgs e)
{
string imgMB = "'http://upload.wikimedia.org/wikipedia/commons/1/1a/Bachalpseeflowers.jpg'";
string sScript = "var showMessage = true; var imgPath=" + imgMB;
Page.ClientScript.RegisterStartupScript(this.GetType(), "MyScript", sScript, true);
}
Try this:
string myscript = "$('a.fancybox-messageboard').fancybox({ width: 600, height: 440,closeClick: true, hideOnOverlayClick: true, href: 'http://upload.wikimedia.org/wikipedia/commons/1/1a/Bachalpseeflowers.jpg' }).trigger('click');"
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), Guid.NewGuid().ToString(), "<script>" + myscript + "</script>", false);
You can achieve this in the following way:
Master page:
<script type="text/javascript">
$(window).load(function () {
if (window.isFancybox) {
//logic to create fancybox
}
});
</script>
Default.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
var fanceBoxDate = new DateTime(2013, 11, 20); //get date from CMS system
if (DateTime.Today == fanceBoxDate)
{
ScriptManager.RegisterClientScriptBlock(this, GetType(), "fancyBox", "var isFancybox = true", true);
}
}
may be u will use this way
first make aspx page to get service and use web method (_service.aspx)
public partial class _service : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string binddata(yourObject yourDatabaseObject)//tbl_BI_mant[]
{
//connect to Database
//and add your Date filter
return Data.getpictureWithDateFilter(yourDatabaseObject.datefilter)
}
}
then in your default.aspx page call that service with jquery ajax
$(function () {
$.ajax({
url: '../_service.aspx/binddata',
type: 'POST',
data: " {'yourDatabaseObject':" + JSON.stringify(Parameters) + "}",
datatype: 'html',
contentType: 'application/json; charset=utf-8',
success: function (data) {
$('a.fancybox-messageboard').fancybox({ width: 600, height: 440,closeClick: true, hideOnOverlayClick: true, href: 'http://upload.wikimedia.org/wikipedia/commons/1/1a/Bachalpseeflowers.jpg' }).trigger('click');;
},
error: function (request, status, err) {
// alert(status);
//alert(err);
}
});
});
I've installed the Stack Exchange MiniProfiler, and View Source shows that it is rendering the expected HTML. However it does not show the little profile detail box in the corner - what could be wrong?
<script src="/v2/Scripts/jquery-1.6.1.min.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="/v2/mini-profiler-includes.css?v=1.7.0.0">
<script type="text/javascript" src="/v2/mini-profiler-yepnope.1.0.1.js"></script>
<script type="text/javascript">
yepnope([
{ test: window.jQuery, nope: '/v2/mini-profiler-jquery.1.6.1.js' },
{ test: window.jQuery && window.jQuery.tmpl, nope: '/v2/mini-profiler-jquery.tmpl.beta1.js' },
{ load: '/v2/mini-profiler-includes.js?v=1.7.0.0',
complete: function() {
jQuery(function() {
MiniProfiler.init({
ids: ["025bbb91-9605-44b7-b33d-d8b196326dbc","2c74ce3e-8de6-4f8d-920a-e8708b22231b"],
path: '/v2/',
version: '1.7.0.0',
renderPosition: 'left',
showTrivial: false,
showChildrenTime: false,
maxTracesToShow: 15
});
});
}
}]);
</script>
And in my Global.asax.cs:
protected void Application_BeginRequest()
{
if (Request.IsLocal)
{
MiniProfiler.Start();
}
}
protected void Application_EndRequest()
{
MiniProfiler.Stop();
}
EDIT: Thanks to Sam's input I've tracked the problem to my .ajaxSetup() method. When it is commented out the profile box shows again. But I can't see why this is a problem:
$.ajaxSetup({
data: "{}",
dataFilter: function (data) {
var msg;
if (data == "") {
msg = data;
}
else if (typeof (JSON) !== 'undefined' && typeof (JSON.parse) === 'function') {
msg = JSON.parse(data);
}
else {
msg = eval('(' + data + ')');
}
if (msg.hasOwnProperty('d')) {
return msg.d;
}
else {
return msg;
}
}
});
My guess is that the global dataFilter is interfering with MiniProfiler's $.get() for jQuery Templates template files. Calling JSON.parse() on an HTML fragment will definitely throw an error.
Since you're using a recent version of jQuery, the optimized JSON parsing isn't something you need to add manually. That functionality was included in jQuery core in 1.4.
So, most simply, try changing your global dataFilter to this:
$.ajaxSetup({
data: "{}",
dataFilter: function (msg) {
if (msg.hasOwnProperty('d')) {
return msg.d;
}
else {
return msg;
}
}
});
If that doesn't fix it, you might want to look into jQuery 1.5's converters instead of the global dataFilter, which allow you to apply a dataFilter-like operation to responses of certain Content-Type. Some good examples from the guy that actually did the jQuery 1.5 AJAX rewrite here: http://encosia.com/jquery-1-5s-ajax-rewrite-and-asp-net-services-all-is-well/#comments
This sort of makes sense, perhaps your filter is mangling the results.
Adding a conditional that bypasses the filtering if you see it is a MiniProfiler JSON result should fix it.
This is my jquery and javascript code :
<script type="text/javascript">
$(document).ready(function () {
//setup new person dialog
$('#dialog').dialog({
modal: true,
modal: true,
// show: "clip",
// hide: "explode",
autoOpen: false,
title: "انتخاب فاکتور",
open: function (type, data) {
$(this).parent().appendTo("form");
}
});
//setup edit person dialog
$('#editPerson').dialog({
autoOpen: false,
draggable: true,
title: "Edit Person",
open: function (type, data) {
$(this).parent().appendTo("form");
}
});
});
function showDialog(id) {
$('#' + id).dialog("open");
}
function closeDialog(id) {
$('#' + id).dialog("close");
}
The Code Is in UserControl .
i can show Dialog client Side :
and i can register code from server with this code :
Page.ClientScript.RegisterClientScriptBlock(GetType(String), "script", "$(function() {showDialog('dialog');});", True)
this code works in page but not in user control.
how can i fix it?
HTML Code :
'>
' runat="server" />
Not sure whether this is the issue or not. Since UserCOntrol is a naming container your element id might have changed. So you need to get the id using ClientID.
Change your code to something like this
$("#<%=yourbuttonid.ClientID%>").dialog("open");
Check the rendered HTML code of your page. Is the order of your script blocks correct? The setup block should be first there, and the showDialog call block should be rendered somewhere below it. Is it your case?