connect to Access database in asp.net and Join statement - asp.net

Let say there is an Asp.ne5 3.5 web application with an Access database. The database has two tables like this:
In some pages I can get the username with `"page.users.identity.name". In this Application, each user can create so many pages. My question is how to write a statement to get pages created with specific username (the Group_ID in joined).
NOTE: This is what i tried and i got "error reading database".
SELECT Pages.* FROM
Pages INNER JOIN Users ON Pages.Group_ID = Users.Group_ID
WHERE Users.Username = page.users.identity.name

Have you tried using a parametrized query:
public ActionResult SomeAction()
{
// get the username of the currently connected user
string username = User.Identity.Name;
string cs = WebConfigurationManager.ConnectionStrings["MyConnStr"].ConnectionString;
using (var conn = new OleDbConnection(cs))
using (var cmd = conn.CreateCommand())
{
conn.Open();
var sql =
#"SELECT Pages.* FROM Pages
INNER JOIN Users
ON Pages.Group_ID = Users.Group_ID
WHERE Users.Username = ?";
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("Username", username);
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
...
}
}
}
...
}

Try with this query,
SELECT Pages.* FROM
Pages,Users where Pages.Group_ID = Users.Group_ID
and Users.Username = page.users.identity.name

I Missed the Single quote "' " in the statement for page.users.identity.name. now this should be like this:
dim lasts as string= "'"
"SELECT Pages.* FROM
Pages INNER JOIN Users ON Pages.Group_ID = Users.Group_ID
WHERE Users.Username ='" & page.users.identity.name & lasts

Related

How to build correct query notification?

could someone please help me, I'm trying to set up alerts with the total amount of records for some tables that I want. In this example, I'm just trying to return COUNT as a result of one of the tables to say how many records don't have schedules for the customer, however with all these exceptions
Creating a Query for Notification
,I couldn't think of a solution for my case.
SELECT COUNT(A.CODREF)QTDEAGENDSEMAGENDA FROM REGISTROS A INNER JOIN ATENDENTES U ON U.CODUSUARIO = A.CODUSUARIO WHERE A.CODUSUARIO = 11 AND A.STATUS IS NULL AND A.CODREF NOT IN ( SELECT CODREF FROM RETORNOS WHERE CODDIALOGO IS NULL AND AGEND_INTERNO IS NULL ) AND DATEDIFF(DAY, A.INICIO, GETDATE())> 11
All the queries I'm going to assemble will look like this in the example. I had thought of creating a view.
Calling my view:
SELECT QTDEAGENDSEMAGENDA FROM ALERTS
then the query would be simple and it would work, but I saw that it is also on the list not to be used.
This is my code and does not work with this query that I set up or with the View
public class NotificationHub : Hub
{
string qtdeAgendSemAgenda = string.Empty;
[HubMethodName("sendNotifications")]
public string SendNotifications()
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
string query = #"SELECT COUNT(A.CODREF)QTDEAGENDSEMAGENDA FROM REGISTROS A INNER JOIN ATENDENTES U ON U.CODUSUARIO = A.CODUSUARIO WHERE A.CODUSUARIO = 11 AND A.STATUS IS NULL AND A.CODREF NOT IN ( SELECT CODREF FROM RETORNOS WHERE CODDIALOGO IS NULL AND AGEND_INTERNO IS NULL ) AND DATEDIFF(DAY, A.INICIO, GETDATE())> 11";
connection.Open();
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Notification = null;
DataTable dt = new DataTable();
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
var reader = command.ExecuteReader();
dt.Load(reader);
if (dt.Rows.Count > 0)
{
qtdeAgendSemAgenda = (dt.Rows[0]["QTDEAGENDSEMAGENDA"].ToString());
}
}
}
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
return Tratar.String(context.Clients.All.RecieveNotification(qtdeAgendSemAgenda));
}

How to execute stored procedure in EF7 beta8?

I'm trying to run stored procedure in EF7 beta8 to return me a specific data. I'm trying to do it via FromSQL command, but not sure if this is right command.
strSQL = wt.DataSource.StoredProc;
foreach (var p in prms)
{
strSQL = strSQL + " #" + p.Name + " = '" + p.Value + "',";
}
strSQL = strSQL.Remove(strSQL.Length - 1); //removes last comma
var test = _dbContext.Widgets.FromSql("EXEC " + strSQL).ToList();
var test2 = _dbContext.Widgets.FromSql("SELECT * FROM Widgets").ToList();
Where test 2 works and returns data correctly, test1 is returning error:
The required column 'Id' was not present in the results of a 'FromSql' operation.
I'm assuming that the data I'm returning is not part of the model. If that's the case, how can I execute stored procedure and return the raw data to List or to DataTable?
EDIT:
I'm trying with SQLCommand:
var connection = (SqlConnection)_dbContext.Database.GetDbConnection();
var command = connection.CreateCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = strSQL;
foreach(var p in prms)
{
command.Parameters.Add("#" + p.Name, p.Value);
}
connection.Open();
var test = command.ExecuteNonQuery();
connection.Close();
Bus still no luck:
No mapping exists from object type Newtonsoft.Json.Linq.JValue to a known managed provider native type.
Is there any other way to execute stored procedure without mapping the entity?
You should be able to use normal SqlCommand and ExecuteReader method to get data from a stored procedure.
Quick sample.
This code executes a stored procedure called GetWidgets which expects 2 parameters, #name and #categoryId and returns a result set which has 2 columns, Id and Name. We are reading the value from the DataReader and creating an object of WidgetDto and appending to a list of WidgetDto.
Your WidgetDto is a simple POCO
public class WidgetDto
{
public int Id {set;get;}
public string Name {set;get;}
}
And the code to execute stored proc is
private List<WidgetDto> GetWidgets(d)
{
var catId= 1;
var name ="test"
//The above values are hard coded for demo. you may replace it
// with whatever your stored proc is expecting.
var list = new List<WidgetDto>();
const string sqlQry = "exec GetWidgets #name,#categoryId";
using (var db = new StudentsEntities())
{
using (var con = (SqlConnection) db.Database.Connection)
{
using (var cmd = new SqlCommand(sqlQry, con))
{
cmd.Parameters.AddWithValue("#name", name);
cmd.Parameters.AddWithValue("#categoryId", catId);
con.Open();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var s = new GoodVm();
s.Id = reader.GetInt32(reader.GetOrdinal("Id"));
s.Name = reader.GetString(reader.GetOrdinal("Name"));
list.Add(s);
}
}
}
}
}
return list;
}
In this example, I am using db.DataBase.Connection (Available in ED 6.13 version) property of my DbContext to build the connection. You can build your connection from the legacy way also by using the connection string.

My update query doesn't work on database

I wrote this code in my login page. My code doesn't any error but update query doesn't apply on my database.
Fist query works and I redirect to index.aspx but update query (second query) doesn't apply!!!!
protected void btnLogin_Click(object sender, EventArgs e)
{
Database db1 = new Database();
string query = "select * from Admins where UserName=#username and cast(Password as varbinary)=cast(#password as varbinary)";
SqlCommand smd = new SqlCommand(query, db1.sc);
smd.Parameters.AddWithValue("#username", txtUsername.Text);
smd.Parameters.AddWithValue("#password", General.CreatePasswordHash(txtPassword.Text));
SqlDataReader sdr = smd.ExecuteReader();
smd.Parameters.Clear();
if (sdr.Read())
{
Session.Add("username", sdr[0].ToString());
string nowEnter = sdr[5].ToString();
query = "update Admins set LastEnter=#lastEnter, NowEnter=#nowEnter where UserName=#username";
string now = General.getPersianDateNow() + " ساعت " + General.getPersianTimeNow();
smd.CommandText = query;
smd.Parameters.AddWithValue("#lastEnter", nowEnter);
smd.Parameters.AddWithValue("#nowEnter", now);
smd.Parameters.AddWithValue("#username", sdr[1].ToString());
sdr.Close();
smd.ExecuteNonQuery();
Response.Redirect("~/admin/Index.aspx", false);
}
else
{
lblError.Visible = true;
}
}
In my opinion the problem is with index of sdr. First one you invoke
Session.Add("username", sdr[0].ToString());
Two lines below you use
smd.Parameters.AddWithValue("#username", sdr[1].ToString());
Anyway the safest way is to create select statement with named colums instead of using *
Check that the value you are using for the username exists in the table.
You're also adding the same parameter twice. I don't know how the SqlCommand class will handle that and I can't test it right now, but I think it might be a good idea to clear your parameters (smd.Parameters.Clear()) between executions.

Need help reading multiple values back from sql server database in asp code

here is my codebehind for grabbing data from database:
public static string getTestimonial()
{
string username = "xxxxx";
SqlConnection Conn = new SqlConnection(ConfigurationManager.ConnectionStrings["xxxxxxx"].ConnectionString);
Conn.Open();
string sql = "select testimonial,submitname from (SELECT TOP 1 * FROM dbo.testimonials where username='" + username + "' ORDER BY newid()) as answer;";
SqlCommand cmd = new SqlCommand(sql, Conn);
string test=cmd.ExecuteScalar().ToString();
Conn.Close();
return test;
}
yet when I try to display the data on my aspx page all I get is the first value:
<div class="span3">
<%= getTestimonial() %>
</div>
can you please help me with a method of getting both the testimonial and the submitname from the query into variables?
Thanks!
Thanks! Solved! using:
public static string getTestimonial()
{
string username = "xxxxxx";
SqlConnection Conn = new SqlConnection(ConfigurationManager.ConnectionStrings["xxxxxxx"].ConnectionString);
Conn.Open();
string sql = "select testimonial,submitname from (SELECT TOP 1 * FROM dbo.testimonials where username='" + username + "' ORDER BY newid()) as answer;";
SqlCommand cmd = new SqlCommand(sql, Conn);
var test = new StringBuilder();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
test.Append(reader.GetString(0));
test.Append(" and ");
test.Append(reader.GetString(1));
}
}
Conn.Close();
return test.ToString();
}
ExecuteScalar() will always return first column of the first row - a single value. You may want to rethink your approach, meanwhile the simplest way is to make your query return combined value:
string sql = "select testimonial + ' and ' + submitname from ....
As an aside, you probably should rewrite that function to not use inline SQL, as you are making your site vulnerable to SQL injection attacks potentially in writing it this way. (presumably, userid is not set as a constant XXXXX in the actual function and is instead passed in somehow).

Execute select query from code behind

How can i execute a SELECT query from my Code Behind file and then iterate through it?
I want to do something like this (just a simple pseudo example):
// SQL Server
var results = executeQuery("SELECT title, name FROM table");
foreach (var row in results)
{
string title = row.title;
string name = row.name;
}
How can i do this within code?
Something like this:
string queryString =
"SELECT OrderID, CustomerID FROM dbo.Orders;";
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(
queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader["OrderID"], reader["CustomerID"]));
}
}
}
Source: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx
The connectionString will vary depending on the Database product and the authentication mechanism used (Windows Auth, username/password, etc.). The example above assumes you are using SQL Server. For a complete list of different ConnectionStrings, go to http://www.connectionstrings.com/

Resources