cshtml file - Locate current windows user, then query database - asp.net

I am working on a localhost site that queries, and updates a database. I have not worked with ASP.NET very much.
I am wondering if it would be possible to find out the current windows user, then select all records in the database that match the located username.
I know how to do this with vbscript, but I need to make it work in a cshtml file.
How do I locate the user?
What would my select sentence look like?
Any help or suggestions are appreciated.
Thanks.
Edit:
Here is the code that I use to display data from a specific user:
#{
var db = Database.Open("Database") ;
var selectCommand = "SELECT * FROM Table WHERE UserID = 'asmith'";
var searchTerm = "";
var selectedData = db.Query(selectCommand, searchTerm);
var grid = new WebGrid(source: selectedData, defaultSort: "Team", rowsPerPage:20);
}
When I change WHERE UserID = 'asmith' to WHERE UserID = #Environment.UserName, I receive the error:
There was an error parsing the query. [ Token line number = 1,Token line offset = 48,Token in error = . ] and the below is highlighted in red.
Line 15: var selectedData = db.Query(selectCommand, searchTerm);
Edit #2:
This Successfully queries the database and returns the correct data, but isn't clean and is causing an issue with another query on the page.
var CurrUser = Environment.UserName;
var db = Database.Open("Database") ;
var selectCommand = "SELECT * FROM Table WHERE UserID = #0";
var searchTerm = #CurrUser;

You're missing the single quotes:
var selectCommand = "SELECT * FROM Table WHERE UserID = 'asmith'";
should be:
var selectCommand = "SELECT * FROM Table WHERE UserID = '#" + Environment.UserName + "'";
Environment.UserName is a string. You're querying where UserID. Are you sure UserID shouldn't be an int or some uniqueidentifier?

Just to clean up and resolve an old post, I would change the select to something more like this:
var currentUser = Request.LogonUserIdentity.Name.Substring(Request.LogonUserIdentity.Name.LastIndexOf(#"\") + 1);
var selectCommand = "SELECT * FROM Table WHERE UserID = #0";
var selectedData = db.Query(selectCommand, currentUser);

Related

Convert date in SQLite?

I created an scheduler application with SQL server and now i want to make another one using SQLite. I have a convert query in SQL and it does not work in SQLite. Can anyone help?
try
{
ObservableCollection<Classes.EventClass> listEvents = new ObservableCollection<EventClass>();
SQLiteConnection conn = new SQLiteConnection(#"Data Source=Scheduler.db;Version=3;");
string query= "Select * from Sche_Event where CONVERT(DATE,Event_TimeFrom) = CONVERT(DATE,'" +d.ToString("yyyy-MM-dd HH:mm:ss") + "') ORDER BY Event_TimeFrom ASC";
SQLiteCommand command= new SQLiteCommand(query, conn);
conn.Open();
SQLiteDataReader dr = command.ExecuteReader();
while (dr.Read())
{
EventClass dog = new EventClass();
dog.DogID = dr.GetInt32(0);
dog.DogName = dr.GetString(1);
dog.DogText = dr.GetString(2);
dog.DogPriority = dr.GetInt32(3);
dog.DogTimeFrom = dr.GetDateTime(4);
dog.DogTimeTo = dr.GetDateTime(5);
dog.KliID = dr.GetInt32(6);
listEvents .Add(dog);
}
return listEvents ;
}
catch (Exception)
{
return null;
}
I expect that my code goes to While() and read the information about the Event but all it does it goes to Catch() and returns nothing.
The query in SQL works just fine but i dont not work with SQLite :(
Of course the statement doesn't work in SQLite, because convert() is not a known function there. But if you're lucky you don't even need it, depending on the format in which the timestamp is stored in your SQLite table. As you didn't provide any sample data nor described what you actually want to do, you could either read the SQLite doc about date and time functions or rephrase your question to "How do I do X in SQLite?".

Can an IOrderedEnumerable bindingsource be created from a DBSet?

I want to dynamically specify a number of columns to sort by.
My code is as follows
var dset = Context.People;
var QuickSearch = "a";
var qry = dset.Where( p => p.LastName.Contains(QuickSearch) );
qry.Load();
BindingSource bindingsource;
bindingSource.DataSource = dset.Local.ToBindingList();
I want to use the technique in the answer outlined
here
Thus I should be able to do something like ( simplified )
IQueryable<Person> qry = null;
qry = base.Context.People.OrderBy(x=>x.FirstName); // this is OK
qry = qry.ThenBy(y=>y.LastName); // This wont compile
However it doesn't compile.
[Update]
Since ThenBy is an extension method for IOrderable My question becomes
Can an IOrderedEnumerable bindingsource be created from a DBSet?
change it to be like this:
var qry = base.Context.People.OrderBy(x=>x.FirstName);
qry = qry.ThenBy(...)
or
IOrderedQueryable<Person> qry = null;
qry = base.Context.People.OrderBy(x=>x.FirstName);
qry = qry.ThenBy(y=>y.LastName);
The reason is that you are declaring qry as IQueryable, when ThenBy is an extension method for IOrderedQueryable (which is what OrderBy returns)

SQL SELECT using a variable condition after WHERE

I am using ASP.NET with the Webpages model and have created a database for users to post to, which is all great, then I created a page so users can edit their posts, however I want it so users can only edit their own posts.
To do this, I tried the following:
I made a variable
var EmailMatch = WebSecurity.CurrentUserName;
so if I put #EmailMatch anywhere in the html markup it will display the email address of the user who is currently logged in. Now in order to display only the posts that this user has made, I used this select statement:
var selectAllString = "SELECT * FROM SaleData WHERE Email = '#EmailMatch'";
In theory I am thinking this should work, because when the user makes a post it sends their email address to the database under the field 'Email' and it should display records that are equal to the user currently logged in. However this statement returns 0 results, I have tried all I can think of with no success, this is my last resort, can someone please tell me what I am missing? Thanks in advance..
The correct way to do this is through parameterized queries. Never ever concat strings that you do not have control over in to a query.
var EmailMatch = WebSecurity.CurrentUserName;
var selectAllString = "SELECT * FROM SaleData WHERE Email = #EmailMatch";
SqlCommand cmd = new SqlCommand(s);
cmd.Parameters.Add("#EmailMatch", EmailMatch);
var resultsTable = cmd.ExecuteReader();
var selectAllString = "SELECT * FROM SaleData WHERE Email = '" + EmailMatch + "'";
Note: This could possibly expose you to SQL Injection attacks.
cmd = new MySqlCommand("SELECT * FROM SaleData WHERE Email = #EmailMatch", MySqlConn.conn);
cmd.Parameters.AddWithValue("#EmailMatch", EmailMatch);
cmd.Prepare();
cmd.ExecuteReader();
Try this:
var selectAllString = "SELECT * FROM SaleData WHERE Email = '"+EmailMatch+"'";
or to avoid SQL Injecton, your SQL statement is correct but you have to add this in your code:
using (OleDbConnection CON = new OleDbConnection("your connection string")) {
OleDbCommand Com = CON.CreateCommand();
Com.CommandText = "SELECT * FROM SaleData WHERE Email = #EmailMatch";
Com.CommandType = CommandType.Text;
Com.CommandTimeout = 0;
Com.Connection.Open();
Com.Parameters.AddWithValue("EmailMatch",EmailMatch);
...
// continue your code from here...
}

updating a row gives error Operation must use an updateable query

I'm getting this error when I'm trying to update a record:
ERROR [HY000] [Microsoft][ODBC Microsoft Access Driver]
Operation must use an updateable query
However when I add a new record, it would add just fine.
I did some searching and found out that the problem is because The ASP.NET worker process does not have permission to update the database. But how am I being able to insert a new record (Isn't inserting updating the database!) but not update (set a record to a different value).
OdbcConnection DbConnection = new OdbcConnection("DSN=inv");
DbConnection.Open();
try
{
string newPassword = password1.Text;
OdbcCommand DbCommand = new OdbcCommand("UPDATE Users" + " SET [Password] = '" + newPassword + "'" + " Where Name = '" + Session["LoginId"] + "'" + ";", DbConnection);
DbCommand.ExecuteNonQuery();
Server.Transfer("Default.aspx", true);
}
You will often get that error if you don't have a primary key declared on that table.
Your code is also pretty ugly, at the very least you should be using a parameterized query:
OdbcCommand DbCommand = new OdbcCommand("UPDATE Users SET [Password] = #Password Where Name = #Name", DbConnection);
var param = DbCommand.Parameters.Add("#Password", OdbcType.Text);
param.Value = passWord;
param = DbCommand.Parameters.Add("#Name", OdbcType.Text);
param.Value = Session["LoginId"];
And I hope this isn't anything more than a toy/demo app -- storing passwords in the clear is bad. Storing passwords in access in the clear is a double bad.

(Asp.net) I can't Insert a new row using Linq to Sql

So I'm trying to do a simple insert using Linq but i'm running into trouble.
code:
TestDatacontext db = new TestDatacontext ();
Comment com = new Comment();
com.UserID = userId;
com.TaskID = taskId;
com.Description = Server.HtmlEncode(txtComments.Text);
com.DateCreated = DateTime.Now;
Now at this point, from what I've read I should be able to do this:
db.Comments.Add(com);
db.Submitchanges();
However, when I write db.Comments. [There is no Add method]
So...how do I insert?
You're looking for db.Comments.InsertOnSubmit(com);

Resources