Quickest way to setup this asp.net page against MS Access DB . . - asp.net

I have an access database with 3 tables.
People
Gifts
PeopleGifts
Using VS 2008, what is the quickest way to get a page up and running which allows me to run queries against these tables and do basic inserts.
I want to have comboboxs bound to fields in the table so a user can click on a person and click on a gift and they click "Add".

The quickest way? Iron Speed

try using an oleDBDataAdapter and a formview

public interface IOleDbDataGateway
{
void ExecuteNonQuery(string sql, params object[] args);
object ExecuteScalar(string sql, params object[] args);
DataTable FillDataTable(string sql, params object[] args);
}
public class OleDbDataGateway : IOleDbDataGateway
{
private readonly string connectionString;
public OleDbDataGateway(string connectionString)
{
this.connectionString = connectionString;
}
public void ExecuteNonQuery(string sql, params object[] args)
{
if (args != null)
{
sql = string.Format(sql, args);
}
var connection = new OleDbConnection(connectionString);
var command = new OleDbCommand(sql, connection);
connection.Open();
try
{
command.ExecuteNonQuery();
}
finally
{
connection.Close();
}
}
public object ExecuteScalar(string sql, params object[] args)
{
if (args != null)
{
sql = string.Format(sql, args);
}
var connection = new OleDbConnection(connectionString);
var command = new OleDbCommand(sql, connection);
connection.Open();
try
{
return command.ExecuteScalar();
}
finally
{
connection.Close();
}
}
public DataTable FillDataTable(string sql, params object[] args)
{
if (args != null)
{
sql = string.Format(sql, args);
}
var connection = new OleDbConnection(connectionString);
var adapter = new OleDbDataAdapter(sql, connection);
var table = new DataTable();
connection.Open();
try
{
adapter.Fill(table);
}
finally
{
connection.Close();
}
return table;
}
}

Related

Populating a dropdown list from the database c# aspx

I am struggling a bit to populate my dropdown list, can anybody tell me where I am going wrong?
ASPX CODE it keeps looping after getting the connection string - back into the connection string method.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDropDownList();
}
}
private string GetConnectionString()
{
using (DataManager dmgr = new DataManager())
{
dmgr.Connect(ConfigurationManager.AppSettings["ProductionKey"]);
return BindDropDownList();
}
}
public string BindDropDownList()
{
DataTable dt = new DataTable();
SqlConnection connection = new SqlConnection(GetConnectionString());
try
{
connection.Open();
string sqlStatement = "SELECT * FROM Itemseriesmaster";
SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
DropDownList1.DataSource = dt;
DropDownList1.DataTextField = "Description"; // the items to be displayed in the list items
DropDownList1.DataValueField = "ID"; // the id of the items displayed
DropDownList1.DataBind();
}
}
catch (SqlException ex)
{
string msg = "Fetch Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
connection.Close();
}
return AppRelativeTemplateSourceDirectory;
}
DataManager Code - where the code calls into
public DataSet ItemSeriesMaster(int id, string description)
{
object[] args = new object[2] { id, description };
return CallSp(MethodBase.GetCurrentMethod(), args) as DataSet; // i know this is not an sp call.. just testing
}
}
}
I am trying to go to my database and bring out the list.

Using Dapper to select data from MS SQL

I use Dapper to select data form Mssql, It result display "null"
(use stored procedure态 List to get data, and "myDictionary[0].Account" and myDictionary[0].Password to get detail information) ,
but MS SQL database have data.
How can I fix code ? thanks.
public void Do_Click(object sender, EventArgs e)
{
string strAccount = Request.Form["userAccount"];
string strPassword = Request.Form["userPwd"];
using (var conn = new SqlConnection(strConn))
{
try
{
conn.Open();
List<LoginModel> myDictionary =
conn.Query<LoginModel>(#"uspSelectLoginChk",
new { LoginAcc = strAccount, LoginPsd = strPassword }, commandType: CommandType.StoredProcedure).ToList();
string strAccountChk = myDictionary[0].Account;
string strPASChk = myDictionary[0].Password;
conn.Close();
if (strAccountChk != null && strAccountChk != null)
{
Response.Redirect("test.aspx");
}
else
{
}
}
catch (Exception ex)
{
response.write( ex.ToString());
}
}
}
Try this one,
// Modified your code
public void Do_Click(object sender, EventArgs e)
{
string strAccount = Request.Form["userAccount"];
string strPassword = Request.Form["userPwd"];
var _para = new DynamicParameters();
_para.Add("#LoginAcc", strAccount);
_para.Add("#LoginPsd", strPassword);
var _list = _con.Query<LoginModel>("uspSelectLoginChk", _para, commandType: CommandType.StoredProcedure); // _con is SqlConnection _con = new SqlConnection("your connection string")
if(_list != null) {
Response.Redirect("test.aspx");
}
}
you need to check:
execute sp in sql with parameter which can view in debug the code.
example:
exec uspSelectLoginChk 'LoginAccValue', 'LoginPsdValue'
if a any data in sql execute,your code is error,if no data, you can insert data before with a data debug result.
Thanks

Transaction Management in asp.net

I am doing a web application in asp.net.
I have a class CommonDB to save data.
public class CommonDB
{
private static string GetConnectionString = ConfigurationManager.ConnectionStrings["Db"].ToString();
public static SqlConnection GetConnection()
{
SqlConnection Con = new SqlConnection(GetConnectionString);
if (Con.State == ConnectionState.Open)
{
Con.Close();
}
return Con;
}
public static int ExecuteNonquery(SqlCommand cmd)
{
SqlConnection Con = GetConnection();
Con.Open();
try
{
cmd.Connection = Con;
Con.Close();
return ReturnVal;
}
catch
{
Con.Close();
return 0;
}
}
}
}
I am using the following function to save data
public int AddGroupMaster() //Inserting
{
try
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "NV_Group_Master_Add";
cmd.Parameters.AddWithValue("#Group_ID", iGroupId);
cmd.Parameters.AddWithValue("#Group_Code", strGroupName);
cmd.Parameters.AddWithValue("#Group_Name", strGroupName);
cmd.Parameters.AddWithValue("#Created_On", strCreatedOn);
cmd.Parameters.AddWithValue("#Modified_On", strModifiedOn);
iReturn = CommonDB.ExecuteNonquery(cmd);
return iReturn;
}
catch { return 0; }
}
This function is called from code behind like :
protected void btnSave_Click(object sender, EventArgs e)
{
try
{
objGroup.strGroupName = txtGroupName.Text.Trim();
objGroup.strCreatedOn = DateTime.Today.ToString();
objGroup.strModifiedOn = "";
objGroup.AddGroupMaster();
}
catch
{
}
}
I want to use Commit and rollback. How it is possible in my coding??
Please suggest a solution
In your scenario, you will have to do that in your CommonDB library.
For example, your ExecuteNonQuery method would look like this:
public static int ExecuteNonquery(SqlCommand cmd) {
int retVal;
SqlConnection Con = GetConnection();
DbTransaction tran;
try {
cmd.Connection = Con;
cmd.Connection.Open();
tran = cmd.Connection.BeginTransaction;
cmd.Transaction = tran;
retVal = cmd.ExecuteNonQuery;
tran.Commit()
} catch {
tran.Rollback();
throw;
} finally {
cmd.Connection.Close()
}
return retVal;
}
And yes, do not forget to get a reference to System.Data.Common.

Is it properly closing connection from ASP.Net to SQL SERVER

Is the below piece of code closing the connection properly..
public static bool Hello(string sqlQuery)
{
SqlDataReader dataReader = null;
var isExist = false;
using (var aeConnection = new SqlConnection(ConnectionString))
{
try
{
var aeCommand = new SqlCommand(sqlQuery, aeConnection)
{
CommandType = CommandType.Text
};
aeConnection.Open();
dataReader = aeCommand.ExecuteReader(CommandBehavior.Default);
while (dataReader.Read())
{
int vinCount;
int.TryParse(dataReader["VINCount"].ToString(), out vinCount);
if (vinCount == 0)
{
isExist = true;
}
}
}
catch (Exception ex)
{
if (dataReader != null)
{
dataReader.Close();
}
}
}
return isExist;
}
Yes it is properly closing connection.When the using block is exited (either by successful completion or by error) it is closed.
The using statement gets compiled into a try/finally block
using (var aeConnection = new SqlConnection(ConnectionString))
{
}
It will treated as
SqlConnection aeConnection = null;
try
{
aeConnection = new SqlConnection(ConnectionString);
}
finally
{
if(aeConnection!= null)
((IDisposable)aeConnection).Dispose();
}

Calling Stored procedure inside a thread to update multiple records

I am trying to calla stored procedure for various unique entities . The stored procedure for a single entity takes about 33 secs. So I decided to call it using threads.
Here are some of trials I have done :
public bool ExecuteTaxRateLinkingParallel(int mapID, int createdBy)
{
try
{
int snapshotID = (int)(HttpContext.Current.Session[GlobalConstant.snapShotID]);
List<TaxEntity> taxEntities = new List<TaxEntity>();
List<Task> tasks = new List<Task>();
using (var ctx = new TopazDbContainer())
{
taxEntities = ctx.TaxEntities.AsParallel().Where(t => t.IsActive == true).ToList<TaxEntity>();
}
Parallel.ForEach<TaxEntity>(taxEntities, (entity) =>
{
//SqlConnection connection; SqlTransaction trans; SqlCommand command;
// break this into pieces of 5
var task = Task.Factory.StartNew(() =>
{
using (var pctx = new TopazDbContainer())
{
try
{
int taxEntityID = entity.TaxEntityID;
pctx.CommandTimeout = 5000;
//string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["TOPAZDBConnectionStringParallel"].ConnectionString;
//connection = new SqlConnection(connectionString);
//command = new SqlCommand("dbo.[Usp_TaxRatesLinkingParallel]", connection);
//trans = connection.BeginTransaction();
//command.CommandType = CommandType.StoredProcedure;
//command.Parameters.AddWithValue("#MapID", mapID);
//command.Parameters.AddWithValue("#UserID", createdBy);
//command.Parameters.AddWithValue("#TaxEntityID", taxEntityID);
//command.Parameters.AddWithValue("#SnapshotID", snapshotID);
//connection.Open();
//command.CommandTimeout = 5000;
//command.ExecuteReader().AsParallel();
pctx.ContextOptions.LazyLoadingEnabled = true;
//pctx.ExecuteStoreCommand("Exec [Usp_TaxRatesLinkingParallel] #MapID={0},#UserID={1},#TaxEntityID={2},#SnapshotID{3}", new SqlParameter("MapID", mapID), new SqlParameter("UserID", createdBy), new SqlParameter("TaxEntityID", taxEntityID), new SqlParameter("SnapshotID", snapshotID));
var param = new DbParameter[] { new SqlParameter("UserID", createdBy), new SqlParameter("TaxEntityID", taxEntityID), new SqlParameter("SnapshotID", snapshotID) };
pctx.ExecuteStoreCommand("Exec [Usp_TaxRatesLinkingParallel] #MapID,#UserID,#TaxEntityID,#SnapshotID", param);
//var result = output.FirstOrDefault();
}
catch (TaskCanceledException tx)
{
}
catch (Exception e)
{
}
finally
{
pctx.SaveChanges();
pctx.Connection.Close();
}
}
}, TaskCreationOptions.PreferFairness);
tasks.Add(task);
try
{
Task.WaitAll(tasks.ToArray());
}
catch (AggregateException ae)
{
ae.Handle((x) =>
{
if (x is UnauthorizedAccessException)
{
return true;
}
else
{
return false;
}
});
}
catch (Exception ex)
{
throw ex;
}
});
return true;
}
catch (Exception ex)
{
TopazErrorLogs.AddTopazErrorLogBL(ex, 1, 1);
throw new TopazCustomException(GlobalConstant.errorMessage);
}
}
For some the above statements the SP seems like it runs fine but when I check from the application or from backend the records doesn't get updated.
Need help!
If you are not on .NET 4.5 yet, you can use these extension methods to execute your commands async.
using System.Diagnostics.Contracts;
using System.Threading.Tasks;
using System.Xml;
namespace System.Data.SqlClient
{
public static class SqlCommandExtensions
{
public static Task<SqlDataReader> ExecuteReaderAsync(this SqlCommand command)
{
Contract.Requires(command != null);
return ExecuteReaderAsync(command, null);
}
public static Task<SqlDataReader> ExecuteReaderAsync(this SqlCommand command, object state)
{
Contract.Requires(command != null);
return Task.Factory.FromAsync<SqlDataReader>(command.BeginExecuteReader, command.EndExecuteReader, state);
}
public static Task<XmlReader> ExecuteReaderXmlAsync(this SqlCommand command)
{
Contract.Requires(command != null);
return ExecuteReaderXmlAsync(command, null);
}
public static Task<XmlReader> ExecuteReaderXmlAsync(this SqlCommand command, object state)
{
Contract.Requires(command != null);
return Task.Factory.FromAsync<XmlReader>(command.BeginExecuteXmlReader, command.EndExecuteXmlReader, state);
}
public static Task<int> ExecuteNonQueryAsync(this SqlCommand command)
{
Contract.Requires(command != null);
return ExecuteNonQueryAsync(command, null);
}
public static Task<int> ExecuteNonQueryAsync(this SqlCommand command, object state)
{
Contract.Requires(command != null);
return Task.Factory.FromAsync<int>(command.BeginExecuteNonQuery, command.EndExecuteNonQuery, state);
}
}
}
It is not an asynchronous database query that you are doing here. Please have a look:
Asynchronous Database Calls With Task-based Asynchronous Programming Model (TAP) in ASP.NET MVC 4
Here is an example of an asynchronous database call with new async / await features:
public async Task<IEnumerable<Car>> GetCarsAsync() {
var connectionString =
ConfigurationManager.ConnectionStrings["CarGalleryConnStr"].ConnectionString;
var asyncConnectionString = new SqlConnectionStringBuilder(connectionString) {
AsynchronousProcessing = true
}.ToString();
using (var conn = new SqlConnection(asyncConnectionString)) {
using (var cmd = new SqlCommand()) {
cmd.Connection = conn;
cmd.CommandText = selectStatement;
cmd.CommandType = CommandType.Text;
conn.Open();
using (var reader = await cmd.ExecuteReaderAsync()) {
return reader.Select(r => carBuilder(r)).ToList();
}
}
}
}
You may find the detailed info inside the blog post.

Resources