The reason i need to do this is because of Facebook Connect - which is another story, so i'll save you the drama for that. =)
Anyway, i have this function that runs on window.onload:
function userAuth() {
SomeFunctionWhichGetsFacebookCookes();
if (!loggedInUsingFormsAuth && loggedInViaFacebook) {
window.location.reload(); // refresh page, so i can perform auto-login
}
}
So, i need help in getting the flag "loggedInUsingFormsAuth".
I dont care what is in the cookie, just need to know if the current user is authenticated.
Why am i doing this?
Well, on window load, if the user is logged into Facebook but not on my website (according to the Forms Authentication cookie), i want to reload the page - which allows my ASP.NET website to read the Facebook cookies in the HttpContext and log the user in. I need to do this in JavaScript, because i dont have the Facebook cookies until i call "SomeFunctionWhichGetsFacebookCookies" - which can only be done in JavaScript.
So, how can i work out if the current user is authenticated via JavaScript? Do i have to manually traverse through the cookies, find the one i want, and inspect it? Is this a safe thing to do?
Or should i alternatively write out the flag to the client from the server using RegisterClientScript?
You could add the following to your web.config file.
<system.web.extensions>
<scripting>
<webServices>
<!-- Allows for ajax.net user authentication -->
<authenticationService enabled="true" requireSSL="false" />
</webServices>
</scripting>
</system.web.extensions>
and then you are able to find out via javascript if you are authenticated
like so.
function isAuth() {
var result = Sys.Services.AuthenticationService.get_isLoggedIn();
return result;
}
A better way to do it than you have described inn your comment is to create a simple web service that you call to retrieve the value.
As i am registering the JavaScript via the server on every page load, i decided to set the HttpContext.Current.Request.IsAuthenticated property into the JavaScript itself.
In other words i had some JavaScript defined in the C# itself:
public class SomeClassWhichHasAccessToHttpContext
{
private const string MyScript = "var foo='{0}'";
public static string GetMyScript()
{
return string.Format(MyScript, HttpContext.Current.Request.IsAuthenticated);
}
}
Then on the HTML for my main master page:
<%= SomeClassWhichHasAcccessToHttpContext.GetMyScript() =>
Normally i would not opt for a solution like this, i would normally call an asynchronous web service (as Ben's answer's mentions). But the fact is that this property and JavaScript is evaluated on a page-request basis, so the evaluation of this property will never be stale for each given HTTP Request.
I have a solution that only needs code in one place:
Add the code below to Global.asax.cs
protected void Application_EndRequest(object sender, EventArgs e)
{
try
{
System.Web.UI.Page P = (System.Web.UI.Page)HttpContext.Current.Handler;//will throw error if request is not for a page
if (P.IsCallback) { return; }
if (P.IsPostBack)
{
try
{
//if using AjaxControlToolKit and UpdatePanels
if (AjaxControlToolkit.ToolkitScriptManager.GetCurrent(P).IsInAsyncPostBack)
{
//Async postback caused by update panel
return;
}
}
catch (Exception)
{
//will throw error if no scriptmanager- which doesn't matter
}
}
//skip this part if not using AjaxControlToolkit or if you have it set up to get scripts from a web handler: http://blogs.msdn.com/b/delay/archive/2007/06/20/script-combining-made-better-overview-of-improvements-to-the-ajax-control-toolkit-s-toolkitscriptmanager.aspx
foreach (string key in P.Request.QueryString)
{
//request is from AjaxControlToolkit to get scripts. Don't want to mess with the response for this
if (key.ToLower().Contains("TSM"))
{
if(P.Request.QueryString[key].ToLower().Contains("toolkitscriptmanager"))
return;
}
}
//dont want to inject this when a page is outputting a file
if (Response.ContentType != "text/html") { return; }
//still going: request is for a page and its a first load or a full page postback
Response.Write(" <script> try{ window.UserLoggedIn=" + HttpContext.Current.User.Identity.IsAuthenticated.ToString().ToLower()+ ";} catch(ex){} </script> ");
}
catch (Exception)
{
}
}
Now client side the variable UserLoggedIn is available on every page.
Related
I have an Angular + spring REST and Wicket hybrid application.
Wicket serves a UserPage class. This UserPage contains my javascript page.
public class UserPage extends WebPage {
public UserPage() {
super();
}
#Override
public void renderHead(IHeaderResponse response) {
super.renderHead(response);
response.render(JavaScriptHeaderItem.forUrl("https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"));
response.render(JavaScriptHeaderItem.forReference(new JavaScriptResourceReference(UserPage.class, "user.js")));
response.render(CssHeaderItem.forReference(new CssResourceReference(UserPage.class, "user.css")));
}
I have implemented a Filter to check if a session is active, if this is not the case, the page should redirect.
WicketSession s = WicketSession.get();
if (s == null) {
response.sendRedirect("/");
} else if (s.getUser() == null) {
response.sendRedirect("/");
} else {
filterChain.doFilter(request, response);
}
However, when i run this page without logging in, the browser receives 302 but does not redirect. This only happens when the page is served through wicket. If i manually go to UserPage.html, it does redirect.
Anyone know anyway why this is happening? It surely is wicket speficic, and im not that familiar with wicket yet.
When trying to reach /user, the page stays, and the html body is send as response data, which my script tries to parse and fails (hence all the empty checkboxes)
When manually going to UserPage.html, it does redirect.
Does anyone know why wicket does not redirect when its being sent a 302? Any clues on a possible fix?
1) If you keep the session data in WicketSession then it should be before Spring's Filter/Servlet in web.xml.
I would suggest to keep the user in Spring Security Authentication if you use it.
2) WicketSession.get() never returns null. It acts as "get or create". You need if (WicketSession.exists()) {...} instead.
This is sort of a Catch-22 with my ASP.NET (Sharepoint) WebPart/page. I need to respond to a button click, but doing that requires that the code be client-side (jQuery), because server-side/code-behind seems only to be available for the "Submit" process, and I don't want to submit the page in this scenario.
To be more clear, this is what I can do to have a button (an HtmlButton, to be more precise), and respond to clicking it without submitting the form:
Server-side (C#):
HtmlButton btnAddFoapalRow = null;
. . .
btnAddFoapalRow = new HtmlButton();
btnAddFoapalRow.Attributes["type"] = "button";
btnAddFoapalRow.InnerHtml = "+";
btnAddFoapalRow.ID = "btnAddFoapalRow";
this.Controls.Add(btnAddFoapalRow);
Client-side (jQuery):
$(document).on("click", '[id$=btnAddFoapalRow]', function (e) {
... script elided for brevity
});
This works fine.
I can do it all on the server side (in C#) for the "submit" button, like so:
Button btnSave = new Button();
btnSave.Text = "Save";
btnSave.Click += new EventHandler(btnSave_Click);
this.Controls.Add(btnSave);
. . .
private void btnSave_Click(object sender, EventArgs e)
{
. . . code elided for brevity
}
But the crux of the problem is that I need to respond to a button click without submitting the form, but then run some code on the server side. I can fulfill the first requirement in jQuery (as shown above with HtmlButton btnAddFoapalRow), but I need to ultimately call some C# code in response to the click - I need to carry out an action on the server side.
So my question is: How can I, from the client-side code, "poke" the server-side code to "wake up and call this (some) function"?
Maybe I can update a variable (HiddenField) that I create in C# like so:
HiddenField PDFGenBtnClicked = null;
. . .
PDFGenBtnClicked = new HiddenField();
PDFGenBtnClicked.ID = "pdfgenbtnclicked";
PDFGenBtnClicked.Value = "no";
this.Controls.Add(PDFGenBtnClicked);
...from the jQuery, like so:
$(document).on("click", '[id$=btnGeneratePDF]', function () {
$('[id$=pdfgenbtnclicked]').val("yes");
});
..and then have code like this on the server-side to kick off the calling of the method:
if (PDFGenBtnClicked.Value == "yes")
{
GeneratePDF(listOfListItems);
}
...but how can I cause this (last) bit of code to be called? Can I put a timer on the page, and have it check the status of PDFGenBtnClicked.Value every so often? This is probably possible, but almost certainly Goldberg-esque.
Who has a better idea?
UPDATE
Theoretically (I think!) this should work (non-Ajax way to indirectly run server-side code from client-side code):
0) Create the Timer
private Timer tmr = null;
1) Create the "Generate PDF" button and the Timer:
btnGeneratePDF = new HtmlButton();
btnGeneratePDF.Attributes["type"] = "button";
btnGeneratePDF.InnerHtml = "Generate PDF";
btnGeneratePDF.ID = "btnGeneratePDF ";
this.Controls.Add(btnGeneratePDF);
tmr = new Timer();
tmr.Interval = 3000; // three seconds
tmr.Tick += TickHandler;
tmr.Enabled = true;
2) Call the method when the Timer trips:
private void TickHandler(object sender, object e)
{
GeneratePDF(listOfListItems);
}
3) Run the code if the user selected the "Generate PDF" button:
private void GeneratePDF(List<ListColumns> listOfListItems)
{
if (PDFGenBtnClicked.Value != "yes")
{
return;
}
tmr.Enabled = false; // only run this once, after val has changed to "yes" by the user clicking the "btnGeneratePDF" button (set from "no" to "yes" in jQuery's response to the clicking of the button)
. . .
However, I have a breakpoint on the first line of GeneratePDF(), and I'm not reaching it, dod-durn it.
UPDATE 2
I even added another event handler, for init:
tmr.Tick += TickHandler;
tmr.Init += InitHandler;
tmr.Enabled = true;
message.Text = "Converting the data to a PDF file has been successful";
(I do see the message Text, although it's not true).
With breakpoints in both methods:
private void TickHandler(object sender, object e)
{
GeneratePDF(listOfListItems);
}
private void InitHandler(object sender, object e)
{
GeneratePDF(listOfListItems);
}
...neither is ever reached. Why not? Theoretically, this seems like it should work...(I know, everything works in theory).
What you're looking to accomplish can be done by webservices and ajax.
Jquery.ajax can be used to send a request to a webservice (or webpage, or whatever). Here is an example from one of my websites:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "FoamServices.asmx/GetFoamNames",
data: "{'term':'" + $("#txtFoamName").val() + "'}",
success: function (data) {
//whatever you want to do with the data
},
error: function (result) {
alert("Error");
}
});
More information on this example can be found at Jquery.ajax website, but the gist of it is that I have a webservice set up, FoamServices.asmx and the method GetFoamNames in that webservice. GetFoamNames takes "term" in for a parameter. Upon success, I take the data I've received from that website and do what I want (check a true value, inject it into the page, whatever).
On the server side, here's my webservice:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class FoamServices : System.Web.Services.WebService {
public FoamServices () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string[] GetFoamNames(string term) {
List<Foam> foams = Foam.Read(term);
string[] foamNames = new string[foams.Count];
for(int i = 0; i < foams.Count; i++)
{
foamNames[i] = foams[i].FoamName;
}
return foamNames;
}
}
This is the basic set up for a webservice that also allows it to accept parameters from a javascript (JQuery) request.
What my service is doing is querying a search term against a database and returning the results. This is the basic setup for an autocomplete JQuery box.
You can adapt this to whatever you like, or you can also use ajax to call a webpage instead of webservice and have it do something.
Hope this helps!
The short answer to your question is that you'll have to use ajax, jQuery has some information regarding using it - https://learn.jquery.com/ajax/.
The longer answer is you'll need to do something like this:
$(document).on("click", '[id$=btnGeneratePDF]', function () {
$.get('/some/route/', function(result) {
//do something with the response, or not depending on your needs
}
});
I'm not familiar with Sharepoint so I can't offer any help on that side, but the basics are that you'll need to create a new page that fires off your PDF generation and access it using ajax, then handle the results in whatever way is appropriate.
My only suggestion is that if you want to only refresh part of the page without doing a full postback, use either AJAX, a callback, or an update panel. Update panels are very simple, but depending on what your button actually does may not be the best option. Just in case though, here is an example
<asp:ScriptManager runat="server" ID="sm">
</asp:ScriptManager>
<asp:updatepanel runat="server">
<ContentTemplate>
<asp:button id="YourButton" runat="server" Text="clickme" onclick="function" />
</ContentTemplate>
</asp:updatepanel>
This will not cause a full postback, and IMO is simpler than AJAX, but like I said may not be the most appropiate solution depending on your exact situation
Here is a link you may find useful from the MSDN site if you want to read up on it.
I want to pass data from one user control to another one, but i've tried several things to do it, and non of them worked, such as sessionStorage in JS, Session in ASPX, cookies in both of them.
This data is dynamic so I don't now how to transfer it, to the other user control.
I even tried to put aspx code in the javascript function (then when I click in the button it could trigger the code, but it doesn't work as well).
This button i refereed above is written in a literal control.
JavaScript Functions
this function is the LoadUsers UserControl
function getID(ID) {
sessionStorage.setItem("userID", ID);
}
this function is in the Access UserControl
function catchIP() {
var ID = sessionStorage.getItem("userID");
$('#<%= value.ClientID %>').val(ID);
}
UserControls
Load Users:
...
string _str = "<a href'#lastAccess' css='btn btn-success' onclick='javascript:getID(" + _id[_contForeach] + "); catchID();'>Access</a>";
_loadUsers.Controls.Add(new LiteralControl(_str));
Access:
How can I get access to the ID in the JavaScript function and apply it without using Page_Load
To pass information between the server side code and the client side code (JavaScript) use ajax
Ajax
So using jquery, have something like this function:
$.get('getuserid.aspx', function(response) {
//Do something with return response
});
then in the code behind getuserid.aspx.cs
private void Page_Load(object sender, System.EventArgs e)
{
Response.Expires = -1;
//required to keep the page from being cached on the client's browser
//set userid
Response.ContentType = "text/plain";
Response.Write(userid);
Response.End();
}
I have written a java script function in the skin file of the visual web Gui application which returns some value too. Now i am invoking the java script method from code behind.
public void XYZ( string message)
{
this.InvokeMethodWithId("testCall", message);
}
And javascript function is:--
function testCall(strGuid, txt) {
alert("hai Java script fired..");
return txt+ 'returned from JavaScript';
}
I want the value returned from JavaScript in the application. how can i achieve it. Is there in other method to invoke the methods of JavaScript?
I want something like this:--
public void Conect( string message)
{
string returnedvalue = this.InvokeMethodWithId("testCall", message);
}
Javascript is executed on the client so the return won't make it to the server.
A solution could be to use AJAX to send that value to the server. Stack Overflow is full of answers about AJAX.
Here's a good example.
#Amish Kumar,
As noted by other replies already, the client-side and server-side are not directly connected in web programming. The client is always the initiator of every request, and the server-side's "purpose" is to render a response, which will then be returned to the client for processing, in Visual WebGui this is usually some UI update processing. This basically means that your client script will not execute until the server-side has finished rendering the response, and the only way the client can get some message back to the server is to issue another request.
Think about how you need to use the MessageBox in Visual WebGui for instance. In order to receive the "response" from the MessageBox, you need to supply a callback handler in your server-side code, and then your server-side code will have completed creating the response, which is returned to the client. The client updates its UI and on some action to the MessageBox dialog, it sends a new request to the server, which interpretes the action and invokes your callback handler. In the callback handler you use Form.DialogResult to get the user action.
A very basic way to make this work in custom Visual WebGui code could be like the following code on a Form:
private void button1_Click(object sender, EventArgs e)
{
SendClientMessage("This is a test");
}
public void SendClientMessage(string strMessage)
{
System.Text.StringBuilder sb = new StringBuilder();
sb.AppendLine("var objEvent = mobjApp.Events_CreateEvent('{0}', 'MessageEvent');");
sb.AppendLine("mobjApp.Events_SetEventAttribute(objEvent, 'Msg', '{1}');");
sb.AppendLine("mobjApp.Events_RaiseEvents();");
this.InvokeScript(string.Format(sb.ToString(), this.ID, strMessage));
}
protected override void FireEvent(Gizmox.WebGUI.Common.Interfaces.IEvent objEvent)
{
if (objEvent.Type == "MessageEvent")
MessageBox.Show(objEvent["Msg"]);
else
base.FireEvent(objEvent);
}
This code will not work unless you set your Visual WebGui applicaton for no Obscuring. In order for this code to work on an obscured application, you would need to add the JavaScript as an obscured JavaScript resource and it would work fine.
Palli
enter code here
I need to enable a script which is present in a .net master page, in only selected html pages that use this master page. can this be achieved by declaring a variable in javascript of html pages where I need this script and set the variable to some value, so that I can enable the scripts in master page only when variable is NotNullorEmpty? Does some one know if this works. If so how to get javascript variable in html, in to .net master page ?
There are 2 ways I can think of.
The first if to assign the variable to a hidden input field. Which can be accessed in the Request.Form.
html
<input type="hidden" value="your value" name="Hidden1" id="Hidden1"/>
javascript
document.getElementById('Hidden1').value = "an other value";
C#
var myValue = Request.Form["Hidden1"];
The second is saving the variable into a cookie which can be accessed in Request.Cookies.
var myValue = Response.Cookies["Cookie1"].Value;
The most flexible form of this that I have seen is to render a JSON object directly to the page as script (adding any other script you might need also), then making the javascript code fill in a hidden field with JSON data on form submit for the server to parse.
Here are the basic steps:
Create an empty hidden field for the server to read when the client submits, but send it to the client empty.
Create a string which is the script and JSON data you need to send to the client. (Use the JavaScriptSerializer .NET class.)
Fill a LiteralControl with the script tag and its contents. (This works well in the OnPreRender step, but you can do it elsewhere.)
Include JSON2.js (it's all over the web - get it from a trusted source)
Write javascript code to fill the hidden field on submit, using JSON2.stringify() to push any javascript object into that field.
On the server, you can again use JavaScriptSerializer to read the values from the submitted object.
What you are basically wanting to do is test for javascript.
There are a few ways to do this, but I would use both a server-side and client-side cookie.
In your global.asax's onbeginrequest, test for a server-side cookie of "js-test-s"
Cookie Exists, check for "js-test-c"
"js-test-c" Cookie Exists, JS enabled
"js-test-c" No Cookie, JS disabled
Cookie doesn't exist...
Set the "js-test-s" cookie
output a simple html document...
[html]
[head]
[meta refresh tag set to 1 second /]
[script to set "js-test-c" cookie, then force refresh /]
[/head]
[body][/body]
[html]
Browser will refresh the request with one or both cookies set.
WARNING: You may want to store the original request details, and redirect to another location in case cookies are disabled.
I might be not understanding the question correctly but as far as I can tell the easiest way to do this is by creating a property on the master page and then setting it on all pages that need to execute the script:
In Master page
public bool EnableScript
{
set
{
if (value == true)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "startup", "alert('test');", true);
}
}
}
In all pages that need to run javascript that use the current master page:
protected void Page_Load(object sender, EventArgs e)
{
this.Master.EnableScript = true;
}
If you have to output your JavaScript on every page, even on the once that don't execute it (why?) then just add it as a function and then inside your property add a code to call that function, and set your property to true on all pages that require JavaScript to execute.