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;
}
}
}
Related
I was able to set Master Page programmatically in Page_PreInit like:
Page.MasterPageFile = "Site.Master";
Since I can't read a session variable just set and change in every page load before or while this phase a code like the following didn't work to set different Master Page according to session variable which based on a URL query string:
if (Session["PageLayout"] != null) {
if (Session["PageLayout"].ToString() == "1") {
Page.MasterPageFile = "FullWidth.Master";
} else if (Session["PageLayout"].ToString() == "2") {
Page.MasterPageFile = "SideBar.Master";
} else {
Page.MasterPageFile = "Site.Master";
}
}
Wonder how to set Page Master in ASP.NET C# based on session or query string passed on page load!
Update: I have tried using the solution in this question
but the problem is that in the other question the session generated while login and is used in another page while in my case the session value only available after visiting the page and based on the URL query / page ID or maybe I couldn't implement it the same way.
i am new to asp.net. my question is that how one can save login userid in asp.net webform?
code i am writing in asp.net webform is:
foreach (var s in db.Users)
{
if (tbUserName.Text==s.user_name && tbPassword.Text == s.user_password)
{
if (string.IsNullOrEmpty(Request.QueryString["ReturnUrl"]))
{
FormsAuthentication.SetAuthCookie(tbUserName.Text, false);
Response.Redirect("~/");
}
else
{
FormsAuthentication.RedirectFromLoginPage(tbUserName.Text, false);
}
flag = 1;
break;
}
else
flag=0;
}
if(flag==0)
{
tbUserName.ErrorText = "Invalid user";
tbUserName.IsValid = false;
}
}
As Tim said, you can get the authenticated user with
User.Identity.Name
You can also get the AuthenticationType and IsAuthenticated properties from the same object.
A suggestion would be to NOT query your DB for all of the users and then loop through them for the correct one. Based off of the user input, you should query the db for the one and only user which matches the form post.
Based off of what you wrote, it looks like the passwords are in clear text and not encrypted, which is a huge security issue. Being new to .Net, take a look at the .Net Membership Providers or SimpleMembership or a comparable pattern.
Good luck!
I would suggest you look at using the Session object to store the user ID. A Session will be available throughout that user's session on the site. Thus, you can call Session anywhere in your site's code to reference that user ID.
For example, to store the id, simply do this, pretend we're in Page_Load()
Session["UserId"] = userID // Or wherever you get the ID from.
then in your code behind, you can do this:
string userId = Session["UserId"]
If the user ID is a number, say an int, then you will need to cast the userID:
int userId = 0;
int.TryParse(Session["UserID"], out userID)
Quick dirty link to a Session example :
http://asp.net-tutorials.com/state/sessions/
I started programming in c# for a few days ago, so I am a total newbeginner at this. Based on my experience in other languages, I found it somewhat "simple".
I am building a system where users are logging in to my application, which is working. I want to have a "remember me"-setting where the information is stored locally. What is the best way to do this? I'll only save the username and the password-hash.
Edit: This is a desktop-application. The login-information is sent to a php-script simply using HttpWebRequest
You can use the ConfigurationManager Class to manage your application's settings.
you can use this function to add new Keys to your configuration file:
public bool setSetting(string pstrKey, string pstrValue)
{
Configuration objConfigFile =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
bool blnKeyExists = false;
foreach (string strKey in objConfigFile.AppSettings.Settings.AllKeys)
{
if (strKey == pstrKey)
{
blnKeyExists = true;
objConfigFile.AppSettings.Settings[pstrKey].Value = pstrValue;
break;
}
}
if (!blnKeyExists)
{
objConfigFile.AppSettings.Settings.Add(pstrKey, pstrValue);
}
objConfigFile.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
return true;
}
and then save up your username (for example)
setSetting("username", usernameTextBox.Text);
Once your application starts up, you can read the information you saved earlier from your ConfigurationManager
usernameTextBox.Text = ConfigurationManager.AppSettings["username"];
you can create Application Settings in C#
here's what you will do.
don't forget to encrypt it.
If you're using ASP .NET,you can set authentication cookie when you're logged in user by second parameter
FormsAuthentication.SetAuthCookie(model.UserName, true);
Second parameter sets cookie to your request and makes "Remeber Me" option.
What I understand from your question is, php file is server and for client you are using windows form. Your are doing some kind of HTML scrapping and displaying the result HTML in your win-form. If this is the what you are doing then
//1. Create a dictionary to store cookie collection
public static Dictionary<string, Cookie> CookieCollection { get; set; }
//2. Store cookie in that collection
foreach (Cookie clientcookie in response.Cookies)
{
if (!CookieCollection.ContainsKey("AuthCookieName"))
CookieCollection .Add(userName, clientcookie);
else
CookieCollection ["userName"] = clientcookie;
}
//3. If remember me is clicked then send the same while creating request
request.CookieContainer.Add(request.RequestUri,
new Cookie("AuthCookieName", CookieCollection ["userName"]));
Where AuthCookieName is the name of authentication cookie. The only downside is when the application exists all the cookie stored in the dictionary would be gone. The solution could be serializing the cookie and storing it in database, if remember me is checked.
in my app. there's a log in mechanism which save a cookie with the info of the user who just logged in
private void CreateCookie(LoginEventArgs args)
{
HttpCookie cookie = new HttpCookie("user");
cookie.Values["name"] = args.User_Name;
cookie.Values["id"] = args.ID;
cookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(cookie);
}
on my master page load i perform a check to see if this cookie exists or not :
HttpCookie cookie = Request.Cookies["user"] ;
if( (cookie != null) && (cookie.Value != ""))
{
if (Session["user"] == null)
Login_Passed(this, new LoginEventArgs(cookie.Values["name"].ToString(), int.Parse(cookie.Values["id"])));
}
now if i Log in ( Create A cookie ) , close the browser , and run my app. again the cookie
exists it's values are correct and the user is "automatically" logged in .
if i first redirect to a different content page from the start up content page
the cookies values are also intact ,
the problem is when i redirect back to a different content page a second time,
the master page loads , makes the check
the cookie exists but the values are deleted ...
any ideas on why this happens ?
btw maybe the way i log out could be the reason for this problem :
when i log-out i create a cookie with the same name that expires 1 day ago .
private void Remove_Cookie()
{
HttpCookie cookie = new HttpCookie("user");
cookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(cookie);
}
in the case iv'e described i don't log-out formally , i just end my app , so this shouldn't
have any effect .
o'k , the problem was unthinkable
special thanks to Peter Bromberg
http://www.eggheadcafe.com/tutorials/aspnet/198ce250-59da-4388-89e5-fce33d725aa7/aspnet-cookies-faq.aspx
in the section of the Article " The Disappearing Cookie "
the author states that if you have a watch on Response.Cookies["cookie_name"]
the browser creates a new empty cookie that overrides your cookie .
i used such a watch which made my cookie loose it's values ,and when i took it off the cookie kept its values.
the moral is DON't WATCH Response.Cookies[" "]
also i read in some other post that if you check
if( Response.Cookies["cookie_name"] != null )
for example it also gets overridden.
To reiterate and build upon what has already been stated (yes, I know this is a 4 year old question) I have found it best to build a utility to handle this - mostly because I want to check that specific cookie often.
This will not touch the Response but only read from the Request.
public static HttpCookie GetCookie(string cookieName)
{
HttpCookie rqstCookie = HttpContext.Current.Request.Cookies.Get(cookieName);
/*** NOTE: it will not be on the Response!
* this will trigger the error noted in the original question and
* create a new, empty cookie which overrides it
*
HttpCookie respCookie = HttpContext.Current.Response.Cookies.Get(cookieName);
*
*/
if (rqstCookie != null && !String.IsNullOrEmpty(rqstCookie.Value))
{
// is found on the Request
return rqstCookie;
}
else
{
return null;
}
}
rule-of-thumb
Always read from the Request and write to the Response.
Thanks eran! this post was exactly what I needed
try the following:
If you are developing on your local machine, put your app on some free web page, so there will be no 'special treatment' because you're in the local host.
If you already are on a web-server, and if the re-directions are between tow different domains, you may want to search google for 'same origin policy' or read this: http://en.wikipedia.org/wiki/Same_origin_policy (the document talks about javascript, but its true also for cookies).
Use the following approach to get a value from cookies:
public string GetValueFromCookies(HttpCookieCollection cookies)
{
if (cookies == null)
{
throw new ArgumentNullException(nameof(cookies));
}
// check the existence of key in the list first
if (Array.IndexOf(cookies.AllKeys, key) < 0)
{
return null;
}
// because the following line adds a cookie with empty value if it's not there
return cookies[key].Value;
}
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.