I have a desktop application, which verifies the finger and prompt the result
I am calling that app in wpf, then this all is showing in asp.net
On asp.net user put the finger, results comes to him how is that done?
On asp.net I created a static class & a web service having a two static members which gets 'query' & connection string, these both member set by asp.net i.e
button1_click() {
string query = "select * from employee where userid='123'";
string connString = "Data Source=mypc;Initial Catalog=abc;Persist Security Info=True;User ID=re;Password=12345";
StaticClass.Query = query;
StaticClass.ConnStr = connString;
}
Value setting in web service
[WebMethod]
public string Query()
{
string SelectDataQuery = StaticClass.Query;
return SelectDataQuery;
}
Desktop application subscribed the web-service which gets and give data. All is well, NOW then I hosted the application on IIS, multiple users are using the application now, on the same time, user1 set the query while user2 gets it.
I want to make it multi user, so whats the suggestion, should i create static strings dynamically as much as users create requests which uniqueness or any thing else?
You could try to create an instance object holding the query and connection and then pass it along to the query method. this way each user will have their own instance.
something like this
[WebMethod]
public string Query(StaticClass query)
{
string SelectDataQuery = query.Query;
return SelectDataQuery ;
}
Just use String.Format to place in the current user id.
button1_click() {
string query = "select * from employee where userid='{0}'";
string connString = "Data Source=mypc;Initial Catalog=abc;Persist Security Info=True;User ID=re;Password=12345";
StaticClass.Query = String.Format(query, currentUserId);
StaticClass.ConnStr = connString;
}
Related
I am kind of new to this environment. What we want to do is to have the end user login with their Login name that is stored in the Security/Logins section. I am not sure where I can go to add this:
SELECT * FROM sys.sysusers WHERE name = variablename
any idea on where to go?
We are using Visual Studio 2013 / Framework 4.6 / SQL Server 2005
To log in with the SQL accounts you must build the provided username and password into the database connection string. If the user is able to successfully open an SqlConnection object, they can log in.
You'll have a saved connection string that looks something like this:
Server=MyServer;Database=MyDatabase;User ID={0};Password={1};
When the user tries to log in, you do something like this:
//pull this from web.config or similar
private string LoginCnString = "Server=MyServer;Database=MyDatabase;User ID={0};Password={1};";
public bool Login(string Username, string Password)
{
using (var cn = new SqlConnection(string.Format(LoginCnString, Username, Password)))
{
try
{
cn.Open();
//Login succeeds
return true;
}
catch
{
//Login fails
return false;
}
}
}
You might also have a generic connection string you use for more of the mundane work of the application, but this is how you validate the login.
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.
I'v created a "Login" windows form app with WCF,
How to send the input username and password to WCF and check if the username in SQL?
private void loginbt_Click(object sender, EventArgs e)
{
string username = textBox1.Text;
string password = textBox2.Text;
//check username and password are not empty
if (username.Trim().Length != 0 && password.Trim().Length != 0)
{
checkPassword.CustomerServiceClient service= new checkPassword.CustomerServiceClient();
var enterPassword = service.checkPassword(username, password);
//check input value here with WCF?
}
}
I'm getting Index was outside the bounds of the array. exception when I add string getUsername = enterPassword[0].name;. It looks like the WCF did not get the input value from textbox, in other words checkPassword(null, null).
public Customer[] checkPassword(string name, string password){
List<Customer> customers = new List<Customer>();
SqlConnection connection = new SqlConnection(
"Data Source = 11111; Initial Catalog = 1111;" +
"User ID = 1111; Password = 11111");
connection.Open();
SqlCommand command = new SqlCommand("select customerId, customerName, address, password, phone from Customer where customerName='"+name+"'", connection);
SqlDataReader reader = command.ExecuteReader();
if (reader.Read()){
Customer newCustomer = new Customer(reader.GetString(1), reader.GetString(3));
string correctPW = reader.GetString(3);
if (correctPW == password)
{
customers.Add(newCustomer);
}
}
reader.Close();
connection.Close();
return customers.ToArray();
}
sorry, I am really confuse with this question, hope you can understand my question, thanks for help.
It is not possible that the service call got executed as checkPassword(null, null) because you call Trim on username and password further up in the execution sequence. You would have received a NullReferenceException before the service call if both variables were null.
One red flag that I see is that you are testing the trimmed (whitespace truncated) versions of username and password when deciding to make the service call, but yet you go ahead and used the unadulterated versions when passing them as parameters to the service call. Could it be that the service is not behaving the way you think it should because there is whitespace in the parameters?
What you really need to do is verify the values of username and password just prior to calling to the service. Ask yourself, "Does my service respond correctly using the parameter values specified?" The problem may be with the service and not the caller. You are going to have to do some old fashioned debugging here. That is something we cannot do for you so take off those socks and shoes and get your feet wet!
As a side note, it appears that you are passing a password in plain text across the network. It is not terribly difficult (actually it could be quite easy) for a middle man to intercept this information. And along the same lines I can see that you are open to SQL injection attacks as well. Knowing that you are using parameterless inline SQL I could tell you my username is x' or 'a'='a and that would cause all rows from the Customer table to be returned. I do not know if that would necessarily cause a security breach in your cases, but I hope you at least can imagine the kinds of havoc this could cause. I only mention all of this because your WCF appears to be security related.
Fixed my problem.
It is because I use the input username to select data from sql, so when I input a not exist username, it will give a error.
Thanks all.
I am a new developer and trying to develop a web service in C# by following this tutorial. I did everything as explained in that tutorial, however, I did not get any data from the Northwind database and I got the following page when I pressed the Invoke button:
As you will see in the tutorial, I did not add the ConnectionString to the web.config file. Should I do that?
My code:
public class WSGetCustomerCountryWise : System.Web.Services.WebService
{
public WSGetCustomerCountryWise()
{
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod(Description = "It will generate Customer List, CountryWise")]
public System.Xml.XmlElement
GetCustomerCountryWise(string sCountry)
{
string sConn = ConfigurationManager.ConnectionStrings["connStr"].ToString();
string sSQL = "select CustomerId, CompanyName, ContactTitle, City from Customers where country = '"+sCountry+"'";
SqlConnection connCustomer = new SqlConnection(sConn);
DataSet dsCustomer = new DataSet();
SqlDataAdapter sda = new SqlDataAdapter(sSQL, sConn);
sda.Fill(dsCustomer);
System.Xml.XmlDataDocument xdd = new System.Xml.XmlDataDocument(dsCustomer);
System.Xml.XmlElement docElem = xdd.DocumentElement;
return docElem;
}
}
You are trying to load the connection string with ConfigurationManager.ConnectionStrings["connStr"].ToString(), but you didn't add it to the configuration (=web.config), so yes you should do that.
For starters; yes, you need to add the connectionstring to your web.config. Otherwise it will throw an exception. You cannot ToString() an null object.
To find out where your code breaks: what happens if you put a breakpoint at the line starting with string sConn? You should be able to find the bug with 'debugging'...
I am trying to develop a simple user management system for the admin of the web application. I am using ASP.NET Wizard Control for this task.
I just put a TextBox for writing the username and when the admin clicks on the Next button, the system should check if the username existed in the database or not. If it is existed, the system should display his information in a placeholder for the admin.
I am struggling with this task. I did the following in the code-behind:
//For checking the user
if (Request.QueryString["Username"] != null)
{
String strUserName = Request.QueryString["Username"];
//Check userName Here
String strReturnStatus = "false";
if (CheckUsername(Request.QueryString["Username"]) == true)
{
strReturnStatus = "true";
}
Response.Clear();
Response.Write(strReturnStatus);
Response.End();
}
Now, I think to create a second method called CheckUsername which I don't know what I should put it inside it:
private bool CheckUsername(string p)
{
//throw new NotImplementedException();
}
It may seem that this question is simple or stupid, but I am a new developer and I could not be able to find a simple resource that could help me in this issue particularly.
I believe the following method is what you're after:
private bool CheckUsername(string username)
{
string connString = "";
string cmdText = "SELECT COUNT(*) FROM Users WHERE Username = #username";
using(SqlConnection conn = new SqlConnection(connString))
{
conn.Open(); // Open DB connection.
using(SqlCommand cmd = new SqlCommand(cmdText, conn))
{
cmd.Parameters.AddWithValue("#username", username)); // Add the SQL parameter.
int count = (int)cmd.ExecuteScalar();
// True (> 0) when the username exists, false (= 0) when the username does not exist.
return (count > 0);
}
}
}
You can fill in the blanks (e.g specify a connection string connString and modify cmdText). The SQL query I specified in cmdText is under the assumption of a typical user management system where you have common table names and columns; Users (table) and Username (column). It's hard to justify as you haven't specified the structure. Modify it to suit your applications needs.
The method of counting how many records exist is quite common in most cases. I frequently use that method of checking/validating things as I see fit.
Further information about the code (classes) I used in my example above:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.aspx
I also advise you read about data access (not that link). I'll leave you to that.
I adjust some point in your code:
if (!string.IsNullOrEmpty(Request.QueryString["Username"]))
{
---
---
if (CheckUsername(Request.QueryString["Username"]))
{
---
---
}
Refer to this link as tutorial for your task: http://www.codeproject.com/KB/database/sql_in_csharp.aspx