how to prevent data overloading at different sessions using asp.net - c#

I wrote some code for search page as follows
I declared variables in above page load as follows
static String strsql = "";
in page load
if(!isPostback)
{
if(session["username"] != null)
{
loadprofiles(); // calling loadprofiles method
bindlist();//loading gridview data
}
}
now loadprofiles method wrote as follows
protected void loadprofiles()
{
strsql = "select * from admintable where userid = '"+session["username"].Tostring()+"'";
}
now bindlist method is as follows
private void bindlist()
{
SqlCommand comm1 = new SqlCommand(strsql, connection);
//and some code for binding data to gridview
}
the problem is while two different users are login into this page from two different computers the user getting the data from second login persions
please help me to solve this problem...
thanks in advance

I was having Session issue for multiple tabs in a single browser.
In Default.aspx/Index.aspx write below code to generate a Unique session Id's.
if (Page.IsPostBack == false) //If page loads for the first time
{
ViewState["_PageID"] = Guid.NewGuid();
}
To store any variable in session Use the following lines:
Session[ViewState["_PageID"].ToString() + "username"] = "testuserName";
To access anything stored based on the Session Id:
string userNameInSession = Session[ViewState["_PageID"].ToString() + "username"] as string;

You cannot declare strsql as static since it will store value for all users - user1 will have access to the user2 strsql value. You have to remember that static is a member of a type, not an instance - it will be accessible for all users until AppDomain is unloaded.
In my opinion you shouldn't store SQL query in a variable(it seems unnecessary since session is accessible everywhere in your code).
I'd change your code to the
private void bindlist()
{
SqlCommand comm1 = new SqlCommand("select * from admintable where userid = '"+session["username"].Tostring()+"'", connection);
//and some code for binding data to gridview
}
EDIT:
Since you want to reuse query, you can return it from loadprofiles() method like follows:
protected string loadprofiles()
{
strsql = "select * from admintable where userid = '"+session["username"].Tostring()+"'";
// Do your logic there...
return strsql;
}
and use it:
if(!isPostback)
{
if(session["username"] != null)
{
var strsql = loadprofiles(); // calling loadprofiles method
bindlist(strsql);//loading gridview data
}
}
I believe you get the point.

Related

Exception thrown while running MySQL query from class

Hie, I'm having a bit of a crisis trying to run an sql query from a C# class. It was working fine in the Login page it was in before and I changed very little of it when I moved it over.
SQL query in class:
namespace Masca
{
public class loginc
{
// Telling the class that the page 'Login' exists.
public Login login;
....
public void Login ()
{
// connection parameters
string sqlcon = "datasource=localhost;port=3306;username = root; password = root";
//Command to carry out -This is what the exception highlights when it's thrown.
string query = "SELECT * FROM logon.login where username = '" + login.username.Text + "' and password = '" + login.password.Password + "';";
MySqlConnection con = new MySqlConnection(sqlcon);
MySqlCommand cmd = new MySqlCommand (query,con);
MySqlDataReader rdr;
con.Open();
rdr = cmd.ExecuteReader();
int count = 0;
while (rdr.Read())
{
count = count + 1;
}
if (count == 1)
{
//If the username and password match those in the database table, run the method 'login' in the login page cs.
login.login();
}
else
{
// if they don't match, run the method 'failLogin' in the login page cs.
login.failLogin();
}
}
In login.cs I have two textboxes and a button. One for the username and one for the password. The button is supposed to trigger the above code:
public void Logon_Click(object sender, RoutedEventArgs e)
{
loginc.Login();
}
Which it does fine. However I get the classic "Object reference not set to an instance of an object" exception thrown on the query. When I enter the actual credentials instead of '+ login.username.Text +' and '+ login.password.Password +' then the exception gets thrown on 'login.Login()'.
I don't understand why the loginc.cs class refuses to relate to the login.cs but the login.cs clearly has no problem triggering the method in class the same way. Anyone know where I'm going wrong?
I see no code where you instantiate Login login. You should really do that.
Login login = new Login();
or something alike.

how to update data from table using C#.net

I've a form opened which is has loaded some sort of data (like username, CNIC, Contact no, etc etc) in Check boxes, now I want to update the data in such manner that I simply change the text in the text boxes and click on the save changes to save it. I've tried it but I am not able to do it in correct manner.
Let me show you how I've coded, the code I did in frmViewformList savechanges button is :
private void btnSaveChanges_Click(object sender, EventArgs e)
{
string sql;
string UserName;
UserName = txtUserName.Text; // saving data loaded on run time to UserName
sql = "";
sql += "UPDATE UserLogin";
sql += "SET Name = "+ //how to access data I've changed in TextBox after loading +"";
sql += "WHERE Name= " + //how to access data which was in text box right after loading + ""; //
}
I am a bit confused about how to refer to data, like the name already in the text box or the name which I have changed and how to write it in SQL query...
This question is a bit confusing, I know. Let me explain; the form is loaded, there are text boxes which is being populated with the data in database on load event, I change the data in text boxes and save on click so that the update query runs and changes the data in database as well.
I'm not able to create logic here how to do this, can any one help me out, I am sorry I am a new developer of C# that's why I am a bit confused.
You should use Sql Parameters in order to avoid SQL Injection which could leave your database vulnerable to malicious exploitation.
It's a good idea to separate the logic for performing the update to the logic where you create your query so you don't have to repeat code and so that you can maintain your code easier.
Here is an example you can reference:
public void DoWork()
{
// Build Query Use #Name Parameters instead of direct values to prevent SQL Injection
StringBuilder sql = new StringBuilder();
sql.Append("UPDATE UserLogin");
sql.Append("SET Name = #UpdatedName");
sql.Append("WHERE Name = #Name");
// Create parameters with the value you want to pass to SQL
SqlParameter name = new SqlParameter("#Name", "whatEverOldNameWas");
SqlParameter updatedName = new SqlParameter("#UpdatedName", txtUserName.Text);
Update(sql.ToString(), new [] { name, updatedName });
}
private static readonly string connectionString = "Your connection string"
private static readonly DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SqlClient");
public static int Update(string sql, SqlParameter[] parameters)
{
try
{
using (DbConnection connection = factory.CreateConnection())
{
connection.ConnectionString = connectionString;
using (DbCommand command = factory.CreateCommand())
{
command.Connection = connection;
command.CommandText = sql;
foreach (var parameter in parameters)
{
if (parameter != null)
command.Parameters.Add(parameter);
}
connection.Open();
return command.ExecuteNonQuery();
}
}
}
catch (Exception)
{
throw;
}
}
You will want to strip all ', ", and ` characters out of your input so that people can't inject SQL. When you do SET Name = " +, you'll want to actually wrap whatever you're including in quotes because it's a string: SET Name = '" + UserName "' " +...
This is probably best done using
string.Format("UPDATE UserLogin SET Name = '{0}' WHERE Name = '{1}'", UserName, FormerUserName);
Then you will execute your query by using System.Data.SqlClient; and then work with SqlConnection to establish a connection to the server, and execute a SqlCommand of some kind; take a look at: http://www.codeproject.com/Articles/4416/Beginners-guide-to-accessing-SQL-Server-through-C
The following is a code snippet to insert data into database using ADO.NET and assuming SQL Server database.
At the top of your .cs file you should have.
using System.Data.SqlClient; // for sql server for other data bases you should use OleClient instead.
And inside your button click event you could put the following.
// to know how to get the right connection string please check this site: http://www.connectionstrings.com
string connString = "database connection string here";
using (SqlConnection con = new SqlConnection(connString))
{
con.Open();
//insert text into db
string sql_insert = "INSERT INTO ....."; // Use parameters here.
SqlCommand cmd_insert = new SqlCommand(sql_insert, con);
int rowsAffected = cmd_insert.ExecuteNonQuery();
}
Hopefully this is enough to get you started.

how to check if value exists in database from textbox c#

ok so i have a text box and a button where i will enter a number and press the button. I then want a message box to display if the value has been found or not.
I put all my functions in a model class then call them for the GUI part.
heres what i tried so the sql function (ticket is the name of the table and ID is the value im trying to find):
public void rebateslip(int ticketID)
{
SqlCommand myCommand = new SqlCommand("SELECT ID FROM ticket WHERE ID = #ticketID", con);
SqlDataAdapter sqlDa = new SqlDataAdapter(myCommand);
myCommand.Parameters.AddWithValue("#ID", ticketID);
}
and than for the button event handler i have this:
private void buttonPrintRebateSlip_Click(object sender, EventArgs e)
{
if (textBoxRebateSlip = model.rebateslip(ticketID)
{
MessageBox.Show("Found ticket");
}
else
{
MessageBox.Show("Ticket not in database");
}
}
but it says ticketID does not exist
Your parameter is named ticketID, not ID
So, you should change to:
myCommand.Parameters.AddWithValue("#ticketID", ticketID);
you should change your model.rebateslip method so that it return a bool, and execute your command, then it should look more or less like this: (don't have the SqlCommand methods in mind, nor the reader's ones, but according to my memory it looks like this)
public bool rebateslip(int ticketID)
{
SqlCommand myCommand = new SqlCommand("SELECT ID FROM ticket WHERE ID = #ticketID", con);
SqlDataAdapter sqlDa = new SqlDataAdapter(myCommand);
myCommand.Parameters.AddWithValue("#ticketID", ticketID);
var reader = myCommand.Execute();
return reader.HasRows;
}
then you should do something like #Ezekiel said in his answer:
int id;
if (!int.TryParse(textBoxRebateSlip.Text, out id)) return;
if (model.rebateslip(id))
...
if (textBoxRebateSlip == model.rebateslip(ticketID)
The If statement is not correct, you are missing a closing paren and the comparison is not valid either. Use == for comparison. Furthermore, ticketID variable is not initialized anywhere. From your description it sounds like you are getting it from the textbox? If so it should be something like this:
int id = Convert.ToInt32(textBoxRebateSlip .Text);
if (model.rebateslip(ticketID) == id)
...
Another thing I noticed, you are not executing the sql command anywhere?
Also, the rebateslip method has return type void, so it will not work.
With all these errors, this code would not even compile.

C# passing information

Sorry in advance im going to try and explain this as best as possible....
I have 2 asp.net pages one named membermaster and the second named memberdetails. I created a class library which contains 2 functions
My first function returns a list depending on the search result...
I added a linkbutton to the gridviews first column which when clicked it passes through querystring the membershipgen. What i wanted to do is for my second function i created this
public DataTable GetMembers(int MEMBERSHIPGEN)
{
DataTable table = null;
SqlConnection con = null;
SqlCommand cmd = null;
SqlDataAdapter ad = null;
SqlParameter prm = null;
try
{
table = new DataTable();
using (con = new SqlConnection(connectionString))
{
using (cmd = new SqlCommand("usp_getmemberdetail", con))
{
using (ad = new SqlDataAdapter(cmd))
{
prm = new SqlParameter("#MEMBERSHIPGEN", SqlDbType.Int);
prm.Value = MEMBERSHIPGEN;
cmd.Parameters.Add(prm);
ad.Fill(table);
}
}
}
}
catch (Exception ex)
{
//write your exception code here
}
return table;
}
In the attempt to try and send the membershipgen to this and it return the results. But once i compile the DLL and add it to my project I am not sure how i would reference this function to populate individual textboxes and labels with the information.
What I am trying to do is when a user clicks the viewdetails button on the gridview I can then use that membershipgen that I passed through querystring to populate the page through a stored procedure but the smarts would be stored in a DLL.
You probably want your method to return a value. Currently the return type is void, so the values it populates internally just go away when the call stack leaves the method. It sounds like you want something like this:
public DataTable GetMembers(int MEMBERSHIPGEN)
Then, in your method, after you've populated the DataTable and exited the using blocks, you'd do something like this:
return table;
This would return the DataTable to whatever called the method. So your page would have something like this:
DataTable table = GetMembers(membershipgen);
So the page would be responsible for:
Get the membershipgen value from the input (query string)
Call the method and get the result of the method
Display the result from the method (bind to a grid? or whatever you're doing to display the data)
And the method is responsible for:
Interact with the database
This is a good first step toward the overall goal of "separation of concerns" which is a very good thing to do. You can continue down this path by always asking yourself what each method, class, etc. should be responsible for. For example, your GetMembers method should also be responsible for ensuring that the value passed to it is valid, or that the value returned from it is not null.
You need to change GetMembers to return data instead of void. If you want to use DataTables, you can just modify your code to this:
public DataTable GetMembers(int MEMBERSHIPGEN)
{
DataTable table = new DataTable();
SqlConnection con = new SqlConnection(connectionString);
using (SqlCommand cmd = new SqlCommand("usp_getmemberdetail", con))
{
using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
{
SqlParameter prm = new SqlParameter("#MEMBERSHIPGEN", SqlDbType.Int);
prm.Value = MEMBERSHIPGEN;
cmd.Parameters.Add(prm);
ad.Fill(table);
return table;
}
Then in your Page_Load it might be something like this (more robust than this hopefully):
{
DataTable table = yourDll.GetMembers(Convert.ToInt32(Request.QueryString["membership"]));
label1.Text = Convert.ToString(table.rows[0]["Name"]);
}
One way to go might be to construct the button so that it navigates to a url along the lines of:
http://localhost/DetailPage.aspx?membershipgen=4
Then in the load of the DetailPage.aspx:
Page_Load(Object sender, EventArgs e)
{
if (!this.IsPostback)
{
int membershipgen;
if (int.TryParse(Request.QueryString["membershipgen"], out membershipgen)
{
//Get the data (replace DataAccess with the name of your data access class).
//Also, you probably want to change GetMembers so it returns the data.
DataTable table = DataAccess.GetMembers(membershipgen);
//TODO: Display the results
}
}
else
{
//Display an error
}
}

teaching about sessions?

Can any one teach me how to use sessions? I have a login page which refers to mysql db table named User which includes UserID="variable number", username and password. Id like to be able to store the userid in a session so I can call it inside the users profile when he logs in.
How is this done? Any relevant coding and placement of specific coding would be helpful as Im just not picking it up at all. Does it go inside the code behind (.cs file) or is it held in the html of the aspx page? or both and how? How does the session work across multiple inner pages (once logged in you can broswe more than one page related to your own profile)
using System.Data.Odbc;
partial class login : System.Web.UI.Page
{
protected void Login1_Authenticate(object sender, System.Web.UI.WebControls.AuthenticateEventArgs e)
{
OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver};Server=localhost;Database=mydb; User=root;Password=;");
cn.Open();
OdbcCommand cmd = new OdbcCommand("Select * from login where username=? and password=?", cn);
//Add parameters to get the username and password
cmd.Parameters.Add("#username", OdbcType.VarChar);
cmd.Parameters["#username"].Value = this.Login1.UserName;
cmd.Parameters.Add("#password", OdbcType.VarChar);
cmd.Parameters["#password"].Value = this.Login1.Password;
OdbcDataReader dr = default(OdbcDataReader);
// Initialise a reader to read the rows from the login table.
// If row exists, the login is successful
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
e.Authenticated = true;
// Event Authenticate is true
}
}
}
In C#, to store a variable in a Session variable:
Session["usrID"]="myUserName";
Later, to retrieve the Session variable:
string usrName = Convert.ToString(Session["usrID"]);
http://msdn.microsoft.com/en-us/library/ms178581.aspx
Basically, give yourself a property for each variable in the page class, eg.
private int SelectedYear
{
get
{
object obj = Session["SelectedYear"];
if (obj != null)
{
return int.Parse(obj.ToString());
}
else
{
return 0;
}
}
set { Session["SelectedYear"] = value; }
}
if you need something for user management, you should go with a membershipprovider. http://msdn.microsoft.com/en-us/library/f1kyba5e.aspx
to get userinformation you can use
Membership.GetUser()
if you just want to use sessions to store variables, you can easily use
Session["name"] = value;
var value = Session["name"];
like others already mentionend
When should you call the code to set the Session variable value?
You can do that in the Login_Authenticate method. That it where you have first retrieved the ID.
Or, you can do it in the Global.asax file, in the Session_Start event. Then, you will always have the value available on every page.

Categories

Resources