How to read session values using jQuery - c#

I am using c# and jQuery.
I have below code where I am setting the Session Variable using C# code.
if (!string.IsNullOrEmpty(results))
{
string[] array = results.Split(',');
string firstName = array[0];
string lastName = array[1];
string activeCardNo = array[2];
string memberShipTier = array[3];
string accessToken = array[4];
Session["skyFirstName"] = firstName.ToString();
Session["skyLastName"] = lastName.ToString();
Session["skyActiveCardNo"] = activeCardNo.ToString();
Session["skyMemberShipTier"] = memberShipTier.ToString();
Session["boolSignOn"] = "true";
Response.Redirect(fromPage);
Response.End();
}
Now I want to read these values (Session["skyFirstName"]) using jQuery so that I can set in my elements. Please suggest.

Session values are stored on the server and it is impossible to read them with client side javascript. One way to achieve this would be to expose some server side script or generic handler which would return the corresponding session value given a key and then use jQuery to send an AJAX request to this handler and read the value. You should be aware that by doing this the user can read all his session values. Be warned that exposing the same script for writing session values could be catastrophic from security standpoint.
Here's an example:
public class ReadSession : IHttpHandler, IReadOnlySessionState
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
context.Response.Write(new JavaScriptSerializer().Serialize(new
{
Key = context.Request["key"],
Value = context.Session[context.Request["key"]]
}));
}
public bool IsReusable
{
get { return true; }
}
}
and then query it:
$.getJSON('/ReadSession.ashx', { key: 'skyFirstName' }, function(result) {
alert(result.Value);
});

jquery runs on the client, which cannot directly access your server-side-session values. one solution is to provide a webservice which returns these values and use the webservice, another one would be to include the values in the page-response as JSON (e.g.) and access them on the client.

You cannot access the session variables with javascript as the session variables are server side rather than client side.
One work around that has already been mentioned is to use ajax to allow the javascript to communicate with the server side. This is fine, but possibly overly complicated for what you need.
Another, simpler solution would be to output the session variables into hidden input fields or as javascript variables in script tags which you can then access with the javascript.

jQuery is javascript, so in order to have those variables available you need to print out html code (at least one script tag) where you set the read-out session variables from C# as javascript variable.
An alternative would be to use an ajax request to get the session variables from a server script.

Related

how to make cookie in asp.net that takes url query string

intern in company working with asp.net and sitecore here
My very first assignment has to do with adding support for a query parameter that can will enable the editor to see some key names of some buttons for a page.
Now i was thinking that i would make a cookie with httpcookie in the correct controller and somehow get the query parameter into the cookie, could that be done in a way?
many thanks?
You can use a URL querystring parameter to get the value you need on Page Load and then set controls accordingly. As for storing Values you can store whatever you need in ViewState or SessionState and look them up when you need to.
Example below:
private void Page_Load()
{
if(Request.QueryString["switch"] !== null)
{
if(Request.QueryString["switch"].ToString()) == "on")
{
button.Visible = true;
ViewState["someval"] = hiddenVal.Text;
}
else
{
button.Visible = false;
}
}
}

How to extract the X-XSRF_TOKEN in a web performance test

I had written a web performance test which was earlier working fine. Developers now have added a CSRF token validation (to prevent CSRF attack on the website). After this the test has started to fail (Error, Bad Request). I dug into it and found that the server is generating an XSRF-TOKEN on login request which has to be passed in every request there after.
Now to extract the token we need to parse response to the login request. How can we do it?
My coded tests looks like this:
WebTestRequest request4 = new WebTestRequest("https://servertest:8080/WebConsole/Account/Login");
request4.Method = "POST";
request4.Headers.Add(new WebTestRequestHeader("Accept", "application/json, text/plain, */*"));
request4.Headers.Add(new WebTestRequestHeader("Referer", "https://servertest:8080/WebConsole/index.html#/"));
StringHttpBody request4Body = new StringHttpBody();
request4Body.ContentType = "application/json;charset=utf-8";
request4Body.InsertByteOrderMark = false;
request4Body.BodyString = "{\"UserName\":\"pkdomain\\\\administrator\",\"Password\":\"sqa#123\"}";
request4.Body = request4Body;
yield return request4;
request4 = null;
WebTestRequest request5 = new WebTestRequest("https://servertest:8080/WebConsole/scripts/home/Pages/home-view.html");
request5.ThinkTime = 4;
request5.Headers.Add(new WebTestRequestHeader("Accept", "text/html"));
request5.Headers.Add(new WebTestRequestHeader("Referer", "https://servertest:8080/WebConsole/index.html#/"));
yield return request5;
request5 = null;
I believe the XSRF-TOKEN is returned in a cookie. Assuming that this is true in your case then the Set-Cookie header field contains the value and the required cookie must be extracted from it and saved to a context parameter. Subsequently that context parameter can be used wherever needed.
I suggest you create a sandbox .webtest file, do the steps below then convert it to coded test and copy the useful lines into the real test.
In more detail the steps are:
Add an Extract HTTP Header extraction rule for the Set-Cookie header field to the request that returns the XSRF-TOKEN value. Save the extracted value to a context parameter of your choice, give its name in one of the properties of the extraction rule; see the image below.
Add a call of the plugin below to the first request after the one with the above extraction rule. It extracts the required field from the cookie header field. The image below shows setting the properties of the call. (You might change the plugin to be a PostRequest and add it to the same request as the one with the extraction rule.)
public class ExtractCookieField : WebTestRequestPlugin
{
public string AllCookiesCP { get; set; }
public string FieldWantedCP { get; set; }
public string SavedFieldCP { get; set; }
// Expected to be called with AllCookiesCP containing text similar to:
// SomeHeader=639025785406236250; path=/; XSRF-TOKEN=somestring; secure; HttpOnly
public override void PreRequestDataBinding(object sender, PreRequestDataBindingEventArgs e)
{
string AllCookiesText = e.WebTest.Context[AllCookiesCP].ToString();
foreach (string nameValuePair in AllCookiesText.Split(';'))
{
string[] nameAndValue = nameValuePair.Split(new char[] { '=' }, 2);
if (nameAndValue[0].Trim() == FieldWantedCP)
{
string sessionTokenId = nameAndValue[1].Trim();
e.WebTest.Context[SavedFieldCP] = sessionTokenId;
e.WebTest.AddCommentToResult(string.Format("Setting {{{0}}} to '{1}'", SavedFieldCP, sessionTokenId));
return;
}
}
// Dropping out of the loop means that the field was not found.
throw new WebTestException(string.Format("Cannot extract cookie field '{0}' from '{1}'", FieldWantedCP, AllCookiesText));
}
}
The value of the XSRF-TOKEN should now be in the context parameter specified in the SavedFieldCP property of the plugin call.
This image shows the add extraction rule dialogue and setting the context parameter where the extracted header field is saved, ie into CookieValues. It also show the add plugin and setting the three properties. After the plugin runs, assuming it is successful, the token value should be saved into the context parameter XsrfToken. The parameter values can be modified in the .webtest file via the properties panels of the extraction rule and the plugin. The values should also be clearly seen as simple variables and strings in a coded webb test.

C# Get Values from two different websites

I am using HTMLElementCollection, HtmlElement to iterate through a website and using Get/Set attributes of a website HTML and returning it to a ListView. Is it possible to get values from website a and website b to return it to the ListView?
HtmlElementCollection oCol1 = oDoc.Body.GetElementsByTagName("input");
foreach (HtmlElement oElement in oCol1)
{
if (oElement.GetAttribute("id").ToString() == "search")
{
oElement.SetAttribute("value", m_sPartNbr);
}
if (oElement.GetAttribute("id").ToString() == "submit")
{
oElement.InvokeMember("click");
}
}
HtmlElementCollection oCol1 = oDoc.Body.GetElementsByTagName("tr");
foreach (HtmlElement oElement1 in oCol1)
{
if (oElement1.GetAttribute("data-mpn").ToString() == m_sPartNbr.ToUpper())
{
HtmlElementCollection oCol2 = oElement1.GetElementsByTagName("td");
foreach (HtmlElement oElement2 in oCol2)
{
if (oElement2 != null)
{
if (oElement2.InnerText != null)
{
if (oElement2.InnerText.StartsWith("$"))
{
string sPrice = oElement2.InnerText.Replace("$", "").Trim();
double dblPrice = double.Parse(sPrice);
if (dblPrice > 0)
m_dblPrices.Add(dblPrice);
}
}
}
}
}
}
As one of the comments mentioned the better approach would be to use HttpWebRequest to send a get request to www.bestbuy.com or whatever site. What it returns is the full HTML code (what you see) which you can then parse through. This kind of approach keeps you from seinding too many requests and getting blacklisted. If you need to click a button or type in a text field its best to mimic human input to avoid being blacklisted also. I would suggest injecting a simple javascript into the page header or body and execute it from the app to send a 'onClick' event from the button (which would then reply with a new page to parse or display) or to modify the text property of something.
this example is in c++/cx but it originally came from a c# example. the script sets the username and password text fields then clicks the login button:
String^ script = "document.GetElementById('username-text').value='myUserName';document.getElementById('password-txt').value='myPassword';document.getElementById('btn-go').click();";
auto args = ref new Platform::Collections::Vector<Platform::String^>();
args->Append(script);
create_task(wv->InvokeScriptAsync("eval", args)).then([this](Platform::String^ response){
//LOGIN COMPLETE
});
//notes: wv = webview
EDIT:
as pointed out the absolute best approach would be to get/request an api. I was surprised to see that site mason pointed out for bestbuy developers. Personally I have only tried to work with auto part stores who either laugh while saying I can't afford it or have no idea what I'm asking for and hang up (when calling corporate).
EDIT 2: in my code the site used was autozone. I had to use chrome developer tools (f12) to get the names of the username, password, and button name. From the developer tools you can also watch what is sent from your computer to the site/server. This allows you to recreate everything and mimic javascript input and actions using post/get with HttpWebRequest.

Invoke JavaScript from C# code behind [duplicate]

This question already has answers here:
Calling JavaScript Function From CodeBehind
(21 answers)
Closed 9 years ago.
I am trying to learn asp.net. Assuming that I have this code:
if (command.ExecuteNonQuery() == 0)
{
// JavaScript like alert("true");
}
else
{
// JavaScript like alert("false");
}
How to I can invoke JavaScript from C# code behind? How to do that by putting that JavaScript in Scripts directory which is created by default in MS Visual Studio?
Here is method I will use from time to time to send a pop message from the code behind. I try to avoid having to do this - but sometimes I need to.
private void LoadClientScriptMessage(string message)
{
StringBuilder script = new StringBuilder();
script.Append(#"<script language='javascript'>");
script.Append(#"alert('" + message + "');");
script.Append(#"</script>");
Page.ClientScript.RegisterStartupScript(this.GetType(), "messageScript", script.ToString());
}
You can use RegisterStartupScript to load a javascript function from CodeBehind.
Please note that javascript will only run at client side when the page is render at client's browser.
Regular Page
Page.ClientScript.RegisterStartupScript(this.GetType(), "myfunc" + UniqueID,
"myJavascriptFunction();", true);
Ajax Page
You need to use ScriptManager if you use ajax.
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "myfunc" + UniqueID,
"myJavascriptFunction();", true);
Usually these "startupscripts" are handy for translations or passing settings to javascript.
Although the solution Mike provided is correct on the .Net side I doubt in a clean (read: no spaghetti code) production environment this is a good practice. It would be better to add .Net variables to a javascript object like so:
// GA example
public static string GetAnalyticsSettingsScript()
{
var settings = new StringBuilder();
var logged = ProjectContext.CurrentUser != null ? "Logged" : "Not Logged";
var account = Configuration.Configuration.GoogleAnalyticsAccount;
// check the required objects since it might not yet exist
settings.AppendLine("Project = window.Project || {};");
settings.AppendLine("Project.analytics = Project.analytics || {};");
settings.AppendLine("Project.analytics.settings = Project.analytics.settings || {};");
settings.AppendFormat("Project.analytics.settings.account = '{0}';", account);
settings.AppendLine();
settings.AppendFormat("Project.analytics.settings.logged = '{0}';", logged);
settings.AppendLine();
return settings.ToString();
}
And then use the common Page.ClientScript.RegisterStartupScript to add it to the HTML.
private void RegisterAnalyticsSettingsScript()
{
string script = GoogleAnalyticsConfiguration.GetAnalyticsSettingsScript();
if (!string.IsNullOrEmpty(script))
{
Page.ClientScript.RegisterStartupScript(GetType(), "AnalyticsSettings", script, true);
}
}
On the JavaScript side it might look like this:
// IIFE
(function($){
// 1. CONFIGURATION
var cfg = {
trackingSetup: {
account: "UA-xxx-1",
allowLinker: true,
domainName: "auto",
siteSpeedSampleRate: 100,
pluginUrl: "//www.google-analytics.com/plugins/ga/inpage_linkid.js"
},
customVariablesSetup: {
usertype: {
slot: 1,
property: "User_type",
value: "Not Logged",
scope: 1
}
}
};
// 2. DOM PROJECT OBJECT
window.Project = window.Project || {};
window.Project.analytics = {
init: function(){
// loading ga.js here with ajax
},
activate: function(){
var proj = this,
account = proj.settings.account || cfg.trackingSetup.account,
logged = proj.settings.logged || cfg.customVariablesSetup.usertype.value;
// override the cfg with settings from .net
cfg.trackingSetup.account = account;
cfg.customVariablesSetup.usertype.value = logged;
// binding events, and more ...
}
};
// 3. INITIALIZE ON LOAD
Project.analytics.init();
// 4. ACTIVATE ONCE THE DOM IS READY
$(function () {
Project.analytics.activate();
});
}(jQuery));
The advantage with this setup is you can load an asynchronous object and override the settings of this object by .Net. Using a configuration object you directly inject javascript into the object and override it when found.
This approach allows me to easily get translation strings, settings, and so on ...
It requires a little bit knowledge of both.
Please note the real power of tis approach lies in the "direct initialization" and "delayed activation". This is necessary as you might not know when (during loading of the page) these object are live. The delay helps overriding the proper objects.
This might be a long shot, but sometimes I need a c# property/value from the server side displaying or manipulated on the client side.
c# code behind page
public string Name {get; set;}
JavaScript on Aspx page
var name = '<%=Name%>';
Populating to client side is generally easier, depending on your issue. Just a thought!

how to passing value codebehind C# to javascript

Any one can help me..I want to pass the C# value to javascript..I only get pass 2 values only to the javascript..I dont know how to pass a tbSTime,tbETime and tbIndo2..Please help me..Thank You
This is code behind:
{
// get the meeting info based on the id
int id = Convert.ToInt32(Request["id"]);
MeetingClass.MeetingInfo m = MeetingClass.MeetingInfo.GetInfo(id);
// fill data
tbtitle2.Value = m.Title;
tbdate2.Value = m.Date.ToShortDateString();
tbSTime.Value = m.StartTime.ToShortTimeString();
tbETime.Value = m.EndTime.ToShortTimeString();
tbIndo2.Value = m.Desc;
}
And this is javascript:
function getInfo() {
$('#<%=tbtitle.ClientID%>').val($('#<%=tbtitle2.ClientID%>').val());
$('#<%=tbdate.ClientID%>').val($('#<%=tbdate2.ClientID%>').val());
}
From what I can tell on your code, you are setting an asp:HiddenField (since you are using .Value) and then using that to populate your asp:TextBox w/ jQuery. If that is the case, then you need to do something like this.
$('#<%=aspTextBoxName1.ClientID%>').val($('#<%=tbSTime.ClientID%>').val());
$('#<%=aspTextBoxName2.ClientID%>').val($('#<%=tbETime.ClientID%>').val());
$('#<%=aspTextBoxName3.ClientID%>').val($('#<%=tbIndo2.ClientID%>').val());
Where aspTextBoxName1, aspTextBoxName2, aspTextBoxName3 are the names of your new textboxes.
I don't know if you really need those hidden form fields, there are easier ways to do this if you don't.
in controller:
ViewBag.tbSTime = tbSTime;
in view:
$('#<%=tbtitle.ClientID%>').val("<%= ViewBag.tbSTime %>");
Iam sorry but iam not sure what exactly you need, but from what i understood i can provide you with this:
If You want to send some value from Server side variables to Javascript function one way you can do this as follows,
function abc(x,y)
{
//Do you things here
}
and from server side call javascript code as follows
string a=textbox1.text;
string b=textbox2.text;
ScriptManager.RegisterStartupScript(this, GetType(), "displayalertmessage", "abc("+a+","+b+");", true);

Categories