How to organize Data Access Layer (DAL) in ASP.NET - asp.net

I have an ASP.NET Web Forms application developed in C#.
I would like to give structure my application by separating the DAL tasks from the code behind.
I created a class in App_Code, DBUtilities that takes care of the communication with the database, in order not to have duplicated code all along the application. The class has methods to get datatables, scalar values, etc... and they accept as parameters the connection string name and the query command as string.
The problem is that I have still all the queries' commands in my code behind. Many of them are duplicated all around the pages and this cause maintanance problems.
I was wondering if it is a good practice to create a (static) class QueryRepository that contains many string properties and associate to each of them a specific query command. Everytime I want to execute the query command MyCommand I pass to the DBUtilities class the QueryRepository.MyCommand property instaed of the string. Morevoer if I need to change a query command I do it just on the QueryRepository class.
Is it a good way to organize my DAL?

For ASP.NET web forms implementing Model-View-Presenter (MVP) pattern can be one good approach to separate your logic and database queries from the UI code behind. You have to write a Presenter class that has a generic reference to a view interface and has a model in it which has database queries, logic etc. The presenter will call functions of the generic view interface in all its functions. Then you can write the actual ASP.net view. In the view you instantiates and reference this presenter and while instantiating the presenter you inject the self object i.e the ASP view itself (using "this" keyword) to the Presenter. You can design proper inheritance for your presenter classes based on your need so that they are reusabe and can be unit tested.
Addition in response to CiccioMiami's query:
Here are couple of links to start
http://www.codeproject.com/KB/aspnet/AspNet_MVP.aspx
http://wiki.asp.net/page.aspx/340/mvp-pattern/
The difference in the MVC and MVP pattern is explained here: http://www.codeproject.com/KB/architecture/DotNetMVPFramework_Part1.aspx
To add to this, for ASP.net Web form architecture, the Requests are tightly coupled with the page life cycle. You have series of page life cycle events and developers write code in each of these events. Thus the business logic becomes tightly coupled to the UI view. Over the period of time this is not a good situation for code maintainability and unit testing. Unit testing is difficult in ASP.net web forms as it is difficult to simulate the requests and page life cycle events. In MVC the requests first comes to a controller. The controller uses the model for business logic and passes the model to view. The view renders using the model data and is returned back as the response to the user. The controller has greater control on the work-flow. You can test the model, DTO transfers etc. as you could do in a standalone app. With web forms there is no controller the request directly comes to ASP.net page which is a view. There is nothing much user can do. Good that Microsoft realized this problem and we have ASP.net MVC. The MVP pattern for ASP.net webforms will solve the code separation problem to some extent. The best option is to use ASP.net MVC if not then you can use MVP with Webforms.

Long term answer: I can really recommend you read Professional Enterprise .NET
The ASP.NET website has a good example of the repository pattern which is worth looking at.
I'm no expert, but if your DAL can conform to a best-practise patterns it's more likely to be a good way for it to be organised.
I'm struggling to follow your DAL design without a concrete example, so not sure I can help there.

Few steps to follow:
It is good practice to separate the DAL, BLL code from presentation(UI) layer, however to go accordingly below steps would be helpful.
Create DTO (Data Transfer Object) or Entity
Fill the DTO/Entity from presentation layer
Pass it to a public method to your BLL layer and validate Business Logic
Then pass the DTO/Entity to DAL layer (at DAL layer, create a method which return Command, then put your CommandText, CommandType and then Set value, data type and size to all the parameters, also create execute method which get Command and return results).
Finally, execute your desired execute method ( created at DAL layer)

namespace DAL
{
public class DBAccess
{
private IDbCommand cmd = new SqlCommand();
private string strConnectionString = "";
private bool handleErrors = false;
private string strLastError = "";
public DBAccess()
{
ConnectionStringSettings objConnectionStringSettings = ConfigurationManager.ConnectionStrings["connectionString"];
strConnectionString = objConnectionStringSettings.ConnectionString;
SqlConnection cnn = new SqlConnection();
cnn.ConnectionString = strConnectionString;
cmd.Connection = cnn;
cmd.CommandType = CommandType.StoredProcedure;
}
public SqlConnection OpenSqlConnection()
{
try {
SqlConnection Conn = new SqlConnection(strConnectionString);
Conn.Open();
return Conn;
} catch (SqlException e) {
throw e;
} catch (Exception ex) {
throw ex;
}
}
public IDataReader ExecuteReader()
{
IDataReader reader = null;
try {
this.Open();
reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
} catch (Exception ex) {
if (handleErrors) {
strLastError = ex.Message;
} else {
throw;
}
}
return reader;
}
public IDataReader ExecuteReader(string commandtext)
{
IDataReader reader = null;
try {
cmd.CommandText = commandtext;
reader = this.ExecuteReader();
} catch (Exception ex) {
if ((handleErrors)) {
strLastError = ex.Message;
} else {
throw;
}
}
return reader;
}
public object ExecuteScalar()
{
object obj = null;
try {
this.Open();
obj = cmd.ExecuteScalar();
this.Close();
} catch (Exception ex) {
if (handleErrors) {
strLastError = ex.Message;
} else {
throw;
}
}
return obj;
}
public object ExecuteScalar(string commandtext)
{
object obj = null;
try {
cmd.CommandText = commandtext;
obj = this.ExecuteScalar();
} catch (Exception ex) {
if ((handleErrors)) {
strLastError = ex.Message;
} else {
throw;
}
}
return obj;
}
public int ExecuteNonQuery(SqlConnection DBConnection, SqlTransaction DBTransaction, bool IsTransRequired)
{
int i = -1;
try {
if ((DBTransaction != null)) {
cmd.Transaction = DBTransaction;
}
i = cmd.ExecuteNonQuery();
} catch (Exception ex) {
if (handleErrors) {
strLastError = ex.Message;
} else {
throw;
}
}
return i;
}
public int ExecuteNonQuery(string commandtext, bool IsTransRequired)
{
SqlConnection DBConnection = null;
SqlTransaction DBTransaction = null;
int i = -1;
try {
cmd.CommandText = commandtext;
if (((DBConnection == null))) {
this.Open();
DBConnection = (SqlConnection)this.cmd.Connection;
if (IsTransRequired == true) {
if (((DBTransaction == null))) {
DBTransaction = DBConnection.BeginTransaction();
}
}
i = this.ExecuteNonQuery(DBConnection, DBTransaction, IsTransRequired);
if ((DBTransaction != null)) {
DBTransaction.Commit();
}
}
} catch (Exception ex) {
if ((DBTransaction != null)) {
DBTransaction.Rollback();
}
if (handleErrors) {
strLastError = ex.Message;
} else {
throw;
}
} finally {
this.Close();
}
return i;
}
public DataSet ExecuteDataSet()
{
SqlDataAdapter da = null;
DataSet ds = null;
try {
da = new SqlDataAdapter();
da.SelectCommand = (SqlCommand)cmd;
ds = new DataSet();
da.Fill(ds);
} catch (Exception ex) {
if ((handleErrors)) {
strLastError = ex.Message;
} else {
throw;
}
}
return ds;
}
public DataSet ExecuteDataSet(string commandtext)
{
DataSet ds = null;
try {
cmd.CommandText = commandtext;
ds = this.ExecuteDataSet();
} catch (Exception ex) {
if (handleErrors) {
strLastError = ex.Message;
} else {
throw;
}
}
return ds;
}
public string CommandText{
get {
return cmd.CommandText;
}
set {
cmd.CommandText = value;
cmd.Parameters.Clear();
}
}
public IDataParameterCollection Parameters{
get {return cmd.Parameters;}
}
public void AddParameter(string paramname, object paramvalue)
{
SqlParameter param = new SqlParameter(paramname, paramvalue);
cmd.Parameters.Add(param);
}
public void AddParameter(IDataParameter param)
{
cmd.Parameters.Add(param);
}
public string ConnectionString {
get { return strConnectionString; }
set { strConnectionString = value; }
}
private void Open()
{
cmd.Connection.Open();
}
private void Close()
{
cmd.Connection.Close();
}
public bool HandleExceptions{
get {return handleErrors;}
set {handleErrors = value;}
}
public string LastError{
get {return strLastError;}
}
public void Dispose()
{
cmd.Dispose();
}
}
}

Related

How to save objects in a proper way with the stream writer?

In the program.cs the user is asked if he wanna read the data, if he types y then the method Doc.ReadDoc starts is there any proper way:
class Program
{
static void Main(string[] args)
{
do
{
var path = "C:\\Users\\ks\\Desktop\\C#";
string fileName = path + #"\TestFile.txt";
Console.WriteLine("Do you want to read it? y/n");
string yesorno = Console.ReadLine();
if (yesorno=="y")
{
Console.Clear();
Doc.ReadDoc();
}
Console.WriteLine("Which type of vehicle");
string type = Console.ReadLine();
Console.WriteLine("how many tires");
int raeder = Convert.ToInt32( Console.ReadLine());
var Vehicle = new Used_Cars(type, raeder);
Doc.Write(Vehicle);
} while (true);
}
}
The Class with the methods (Read, Write):
public static List<string> ReadDoc()
{
var list = new List<string>();
var pfad = "C:\\Users\\ks\\Desktop\\C#";
string fileName = path+ #"\TestFile.txt";
try
{
using (StreamReader sr = new StreamReader(fileName))
{
Console.WriteLine("Data found");
string line;
Console.WriteLine(sr.ReadToEnd());
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("Data not found");
Console.WriteLine(e.Message);
list = null;
}
return list;
}
And the last Method is the Write method, is this a good code to save properties in a file? How could i stop the program with ESC or smth like that, so if the user presses ESC it should stop.
public static void Write(Used_Cars vehicle)
{
var pfad = "C:\\Users\\ks\\Desktop\\C#";
string fileName = path+ #"\TestFile.txt";
Console.WriteLine("Is it correct?");
Console.WriteLine("y/n");
string yeahorno= Console.ReadLine();
if (jaodernein == "y")
{
try
{
using (StreamWriter writer = new StreamWriter(fileName))
{
writer.WriteLine(vehicle.Vehicle);
writer.WriteLine(vehicle.Wheels);
Console.WriteLine();
}
}
catch (Exception exp)
{
Console.Write(exp.Message);
}
}
}

Spring MVC returns 405 for api call made from my android client

I have an android app which is making api requests to my server running Spring MVC. The RestController works fine when I make a request from the browser but it responds with 404 when I am making requests from android. Not sure why
Here is code snippet from Android app making requests
public class AsyncFetch extends AsyncTask<Pair<String, String>, String, String> {
public ProgressDialog pdLoading;
private HttpURLConnection conn;
private String urlStr;
private String requestMethod = "GET";
public AsyncFetch(String endpoint, Context ctx)
{
pdLoading = new ProgressDialog(ctx);
Properties reader = PropertiesReader.getInstance().getProperties(ctx, "app.properties");
String host = reader.getProperty("host", "10.0.2.2");
String port = reader.getProperty("port", "8080");
String protocol = reader.getProperty("protocol", "http");
String context = reader.getProperty("context", "");
this.urlStr = protocol+"://"+host+":"+port+context+endpoint;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(Pair<String, String>... params) {
URL url;
try {
url = new URL(urlStr);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod(requestMethod);
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made`enter code here`
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
Spring MVC Controller
#RestController
public class ApiController {
#RequestMapping(value = "homefeed", method=RequestMethod.GET)
public String homefeed(#RequestParam(value="userId", required = false) Integer id, #RequestParam(value="search", required = false) String search, #RequestParam(value="page", required = false, defaultValue = "0") Integer page) { ... }
}
localhost:8080/api/homefeed -- works
127.0.0.1:8080/api/homefeed -- works
My Public IP:8080/api/homefeed -- does not works
10.0.2.2:8080/api/homefeed -- android emulator to localhost -- does not work
10.0.2.2:8080/Some resource other than the api endpoint -- works
Any help is highly appreciable, have wasted quiet some time in debugging.

throw exception to change password in ASP.NET

i wanna ask again. How can i resolve this problem
Eror Picture
always find error, and i won't stop. I must be try with help from you guys.
after you look my error, this is my code:
using System;
using System.Web;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Web.SessionState;
namespace FormsAuthAd
{
public class ChangePasswordPSI
{
public bool ChangePass(HttpSessionState Session, string OldPassword, string NewUPassword)
{
string Domain = Session["domain"].ToString();
string Username = Session["username"].ToString();
try
{
string ldapPath = "LDAP://MyDomain.com";
DirectoryEntry user = new DirectoryEntry(ldapPath, Domain + "\\" + Username, OldPassword);
if (user != null)
{
DirectorySearcher search = new DirectorySearcher(user);
search.Filter = "(SAMAccountName=" + Username + ")";
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
if (result != null)
{
object ret = user.Invoke("ChangeUserPassword", new object[] { OldPassword, NewUPassword });
user.CommitChanges();
return true;
}
}
}
catch (Exception ex)
{
throw ex;
}
return false;
}
}
}
can somebody tell me, what should i do?
thank you
If you are using try..catch and cannot find where exactly the exception occurred, delete try and catch and execute the code again. In your example, it might happen on Invoke("ChangeUserPassword"... - as far as I see the method name should be "ChangePassword"
https://msdn.microsoft.com/en-us/library/ms180896(v=vs.80).aspx

Why is my connection object null?

private static final String DB_URL = "jdbc:derby://localhost:1527/ShopDB";
private static final String DB_CLOSE = DB_URL + ";shutdown=true";
private static final String DB_DRIVER = "org.apache.derby.jdbc.ClientDriver";
private static Connection con = null;
public WebshopDAO() {
try {
Class.forName(DB_DRIVER).newInstance();
con = DriverManager.getConnection(DB_CLOSE);
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException e) {
e.printStackTrace();
}
}
I created a WebshopDAO object in another class. After that, I called a method in the WebDAO:
public CatalogDTO createCatalogDTO() {
String query = "SELECT * FROM Catalog";
CatalogDTO catalog = new CatalogDTO();
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while(rs.next()) {
Catalog c = new Catalog();
c.setCName(rs.getString("CName"));
c.setCategoryNr(rs.getInt("CategoryNr"));
c.setSupercategoryNr(rs.getInt("SupercategoryNr"));
catalog.addCatalog(c);
}
} catch (SQLException e) {
e.getMessage();
}
return catalog;
}
So when I call the createCatalogDTO method, I get a NullPointerException. I don't know why. I checked the driver url and the db url and they are correct. I am using servlets for the first time. The class that uses this WebshopDAO is a servlet and I have a bit of a problem using the debugger.
Can you guys tell me the possible mistakes? I am looking for hours but I just can't find it.
EDIT:
Here is what I get:
java.lang.NullPointerException
WebshopDAO.createCatalogDTO(WebshopDAO.java:96)
Navigation.doGet(Navigation.java:28)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

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