object reference not set to an instance of an object, when using session variable in MVC4 - c#

NOTE
it is not duplicate question I am asking, I have read 3 different links from stack as showed below, but none of them shows resolution for my question (or) reason, so please let me know what i am doing wrong
link1
link2
link 3
I developed MVC application, where username from login page taken to controller to pull the data, where it loads up the value of that username, so I want that Username to be exist until i quit my application, so what I did was did some R&D what to use to store and save the data and pass it to another page,
first I used "TempData" which works fine to my scenario , where it pulls the data as I needed, but the error occurs when application is idle for 5 min then, if i press the Refresh button or F5, I get the above error, username is null generating error message "object reference not set to instance of an object" I know why this error generates.
later I searched it again, used session variable to store and send it, even it does works fine same as tempdata but after few mins like 5 mins and more, if page refreshes generates same message, I believe the syntax used in tempdata and session are correct since it works fine, I am posting code of the way I am using it in MVC, please let me know any mistakes I have done, or let me know what should I do to fix this problem, which should work for longer duration of idle, unless I use session time to quit the application.
NOTE
I have not used any session time, like if application is idle for 5 mins it should quit the application.
CODE
public ActionResult ValidateLogIn(FormCollection postedFormData)
{
LoginViewModel.LoginDataModel.UserName = Convert.ToString(postedFormData["UserName"]);
LoginViewModel.LoginDataModel.Password = Convert.ToString(postedFormData["Password"]);
// ViewBag.Message = LoginViewModel.LoginDataModel.UserName;
// TempData["UsrName"] = LoginViewModel.LoginDataModel.UserName;
TempData.Keep();
Session["UsrName"] = LoginViewModel.LoginDataModel.UserName;
// with some code..........
}
public ActionResult LandingPage()
{
//////ViewData["message"] = TempData["UsrName"].ToString();
Session["message"] = Session["UsrName"].ToString();
ViewData["person"] = Convert.ToInt32(TempData["UserTypeID"]);
TempData.Keep();
String PatID = Convert.ToString(Session["message"].ToString());
int PersonType = Convert.ToInt32(ViewData["person"]);
PatientDetailsViewModel = PatientDetailsDataAccessService.LogInEnquiry(PatID);
return View("../PatientDetails/PatientDetailsView", PatientDetailsViewModel.ServiceList.AsEnumerable());
}
and this is the error which generates when refreshed

You can use User.Identity.Name once the user has logged to get the user name. This way you dont have to mess about with temp data, viewbag or viewdata.

Related

How pass a values from a web form to another in ASP.NET?

I am trying to send string data from one web form to another, however it throws the System.NullReferenceException error. I read in the Postgress documentation that this error means there is no data to work with. This is the code for the first form:
protected void Button2_Click(object sender, EventArgs e)
{
editar ed = new editar(tname.Text.ToString());
//ed.putId(tname.Text.ToString());
String url = "editar.aspx";
Response.Redirect(url);
}
Creating the object of the second form was one of the ways I found to send the data, but it keeps throwing the error. In the second form you should receive it.
public editar(string name)
{
this.tname.Text = name;
}
The basic idea is that the string is received in the second form to put it in a text box and there, by means of a button, the information of a database can be updated.
protected void Button2_Click(object sender, EventArgs e)
{
upt = new NpgsqlCommand("update usuario set cedula = '" + tcedula.Text.ToString() + "' where nombre = '" + tname.Text.ToString() + "'", conn);
upt.ExecuteNonQuery();
}
I have already tried through the POST and Session method, the problem with these two methods is that although the data arrives correctly every time the page is reloaded the data is reloaded and that happens each time the button, therefore the SQL statement to update the information is null, that is, it executes it, but it does not update the database. I use Visual Studio 2019, ASP.NET, and Postgres.
There are two things to understand here:
Web Forms still use HTTP requests for each page view and even for each server event like button clicks.
Form class instances do not persist between requests. Your
code runs for long enough to send some html or javascript to the
browser, and then everything is immediately thrown away; nothing
stays in memory. Even if the same user requests the same page again
(ie, clicks refresh in their browser), you still get an entirely new
instance of your page class that doesn't know anything of what has come before.
Therefore, if you have a value you want to use across HTTP requests, as in this case when you have two different forms, you have to put it somewhere that will be available when the later http request is processed. You can do that several ways: the session, a GET (url) or POST parameter, or save to a database during the first request and receive on the second.
In this case, a session value seems most appropriate, but it's hard to be sure without knowing more of what you're doing.
And for God's sake, fix that glaring SQL injection issue. You shouldn't be writing database code for the web without knowing about that.

How to fix error while logging into account of site from different network

I have written code which retrieves data from ClientID and modifies it to Int32. There's no error while debugging. I've deployed the site to network. It is working as intended when accessed through same LAN where server is located. However is throwing an error when others (outside this Network) are trying to login to site.
The error is:
Server Error in '/' Application
Exception Details: System.FormatException : Input string was not in a correct format.
PS: The site is accessible. They are able to register, change password and redirect to different pages from home page. However, when profile loads they are seeing the error.
I've tried to debug again, check with db (mySQL) connectivity, refreshed the IIS server manager completely, Checked with the permissions, tried to change the "Int to Var" in cs code, remove "value=" and ".text()" from the error line and deployed the site again multiple times with modifications each time debugging.
function getdays(date){
var days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
var d = new Date(date);
var dayName = days[d.getDay()];
var selecteddays = value = $('#<%=lblweekoff.ClientID%>').text();
var selectedSplittedDays = selecteddays.split(',');
}
C#
string MyConString = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
var dayColumns = new[] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
var selectedDayColumn = dayColumns[(int)nextDate.DayOfWeek];
var sp = (dr["p"].ToString());
Int sp1 = Convert.ToInt32(sp);
MySqlConnection connection = new MySqlConnection(MyConString);
The code should be able to accept the number and load the page with the calculation with respect to number given and split the days which are divided by "," stored in database.
It should allow the user to login in and show the page without any error.
As it is running as intended with in same LAN, I don't think there is a serious problem with the code. However, all the suggestions would be highly appreciated.
UPDATE :
To explain further, there are 2 sets of predefined users, lets say set A has 100 users and set B has 100 users. When I place myself as a user in set A, I'm able to login to the site. When I'm in set B, I'm unable to login and its casting same error.
I've removed entire set B and added inserted updated details. Still it's posing same error for all the users in set B. Set A however doesn't have any problem logging in and accessing the features.
I think the error is with $('#<%=lblweekoff.ClientID%>'). Further with all the ClientID functions. I've tried to comment the error line and tried to execute where I've received error with another .ClientID function. So, would the issue be with the code interacting with db?
If that's the case, they are able to register or change password which links to the same db.
I got it!
The input was in int form.
Int sp1 = Convert.ToInt32(sp);
However, the inputs data were float(decimal numbers).
Corrected it to:
float sp1= math.round(Convert.ToInt32(sp));
It actually worked. Thank you all for suggestions and help.

Check Whether the login is done or not in Xamarin.forms

Please help me out how we will check in xamarin.forms whether the login is been done or not .
when ever we open the app we check the login is been done or not if login is not been done then it should move to login page or else it should move to main page.
If we logout then only it should move to login page
Same Like facebook and Gmail login
please help me out i m new to xamarin.forms in xamarin.forms we cannot use local storage also how to resolve these issue
Finally I got the answer of these solution
App.Current.Properties["IsLoggedIn"] = true
https://github.com/conceptdev/xamarin-forms-samples/tree/master/LoginDemo
We can resolve these issue by setting using IsLoggedIn to true
The Application-properties in .forms are used, to save data persistent.
Saved data are restored automatically by the app-start, but you first have to create them and - important - to save them.
Example for a integer value (from my app):
In startup-code:
if (!Application.Current.Properties.ContainsKey("iBenutzerSuchParameter")) // Key don't exist
{ Application.Current.Properties["iBenutzerSuchParameter"] = 0; } // create it an fill a value
// overtake the setting in a global variable and convert it
GV.iBenutzerSuchParameter = Convert.ToInt32(Application.Current.Properties["iBenutzerSuchParameter"]);
Save the property's exlicitely:
await Application.Current.SavePropertiesAsync();
So... if you really want to store the "login-state" persistent and reload it by every app-start (means, that the user only have to login one time in "his live"), you should:
Define and create a key for store the state in your startup-code (if not exist already -> see my example code)
Maybe save the value for state "not-logged-in" and save the properties a first time.
Show your login-page
Check, if successful:
If yes, change the key to "logged-in" and save the properties.
There are 3 possible options:
You can save it in a local database
You can save it in App.Current.Properties
You can save it in the native api's of each platform, all 3 platforms have an api to save preferences

passing values to pages

What i am trying here is to pass values to other pages. When i include the following code
private void Button1_Click(object sender, System.EventArgs e)
{
Response.Redirect("WebForm5.aspx?Name="+txtName.Text);
}
if (Request.QueryString["Name"]!= null)
Response.write( Request.QueryString["Name"]);
everything works fine the name gets displayed. Now if use MemberId instead, though i can see the Id in the Url, but while checking for Null in other page, its true i.e.
if (Request.QueryString["MemberId"]!= null)
Response.write( Request.QueryString["MemberId"]); doesnt gets printed. Whats wrong??
Now I tried the same thing using session i.e.
Session["MemberId"] = this.TxtEnterMemberId.Text;
if (MemberSex.Equals("M"))
Response.Redirect("PatientDetailsMale.aspx",false );
Page_load event of the other page
if (Session["MemberId"] != null)
mid = Session["MemberId"].ToString();
IT Works..Could u guys explain the behaviour please?
P.S. Can anyone give a breif in layman words about SessionId and its usage.
Thanking you,
Indranil
if you have MemberId in the Url then it will be available by Request["MemberId "] and there is no exception to that.
please make sure you are checking for the correct name in Request["holderName"]
Well first of all you use querystring for unimportant information. You should use a session variable if you don't want the user to see the value. The session is saved on server side!
Querystring usage:
Response.Redirect("Default.aspx?id=4");
After that you can read it on other page:
if (Request.QueryString.Count > 0)
Int32 i = Convert.ToInt32(Request.QueryString("id"));
Session usage:
Session["id"] = 5;
After that you can read it on other page:
if (Session["id"] != null)
Int32 i = Convert.ToInt32(Session["id"]);
Hope this helps you
To give you a brief explaination about Session State, by default config they are stored as live objects in the IIS worker process (called InProc), being user-isolated (one user cannot access another user's session). You can change this behavior to define the session data to be stored in other places like a SQL Server database or a State Server by using, in the configuration file, the element . Being that, webfarms have a problem with InProc session storing, so in this case SQL or StateServer can solve it.
Refer to http://msdn.microsoft.com/en-us/library/ms972429.aspx for further info.

TempData and patterns

TempData persists for one more future request, isn't this anti REST ?
and what situations it's desired to use it ?
Kind of, we us it to show messages to the user when the page is redirected.
ie when a new object is created, the user is redirected to the edit page showing the new id
POST /Person/Create
Update and save the new person, get their id
set message in temp data "Person Created Successfully"
Redirect to /Person/Edit/1234
This is a kind of skip though another state
e.g.
/Person/Created/1234
it just saves a click I suppose.

Categories

Resources