Thursday, March 29, 2012
Please evaluate C# code - Beginner level
In order to expand my knowledge, my goal is to write a class that will encapsulate this code. I understand that writing a class for my tiny website may be a bit excessive, but its more for the knowledge of "how-to" than practicality.
The class that I have written does somewhat work:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.Sql;
public class Database
{
private String DatabaseConnectionString = "Data source=*;" +
"Database=*;" +
"uid=*;" +
"pwd=*";
private SqlConnection objConnection;
private SqlCommand objCommand;
public SqlDataReader objReader;
public String dbError;
public String GetConnectionString()
{
return DatabaseConnectionString;
}
private SqlConnection CreateConnection()
{
SqlConnection objConnection = new SqlConnection(DatabaseConnectionString);
return objConnection;
}
private SqlCommand CreateCommand(String p_Command, SqlConnection p_Connection)
{
SqlCommand objCommand = new SqlCommand(p_Command, p_Connection);
return objCommand;
}
//Article Related
public void GetArticleByID(String p_CategoryID, String p_ArticleID)
{
objConnection = CreateConnection();
objCommand = CreateCommand("SELECT * FROM tblArticle " +
"WHERE tblArticle.charArticleID=@dotnet.itags.org.Article " +
"AND tblArticle.charCategoryID=@dotnet.itags.org.Category", objConnection);
SqlDataReader objReader;
try
{
objConnection.Open();
objCommand.Parameters.AddWithValue("@dotnet.itags.org.Article",p_ArticleID);
objCommand.Parameters.AddWithValue("@dotnet.itags.org.Category",p_CategoryID);
objReader = objCommand.ExecuteReader();
}
catch(System.Exception ex)
{
dbError = ex.Message;
objReader= null;
}
}
//End Articles
}
The class is used like this:
<script runat="server" language="c#">
protected void Page_Load(Object sender, EventArgs e)
{
String strCategoryID = Request.QueryString["ci"];
String strArticleID = Request.QueryString["ai"];
Database objDatabase = new Database();
objDatabase.GetArticleByID(strCategoryID,strArticleID);
if(objDatabase.objReader != null)
{
while(objDatabase.objReader.Read());
{
label1.Text += objDatabase.objReader["charTitle"].ToString();
}
}
else
label1.Text = objDatabase.dbError;
}
</script>
Question 1: Is my method even correct? Am I taking the right approach to this?
I'm trying to create shortcuts by making functions that create the connectionstring and command for me without me having to type it out each time. The idea behind the class is that, it will do all the work for me and store a SqlDataReader object in itself, that I will then manipulate in my Page_Load event.
Any input in regards to this question is greatly appreciated. Thanks!What you've created is called a DAL - Data Access Layer. It's a class which encapsulates the database-specific methods. You're doing fine. Your approach is right, but the datareader isn't required here. In addition, your GetArticleById method is returning void. So, you need to make it return a dataset, and change its function signature to return a dataset.
In the code that calls this method, assign a dataset to the method, and use that dataset to... whatever.
when is it best to use the DataAdapter/DataSet approach and when is it best to use a DataReader?
I mean the DataAdapter/DataSet just seems like the long way instead of just using a DataReader.
It depends on what you need... if you need to get some records, manipulate the data in memory and then send the changes back, a DataSet/Table would be the candidate. But if you are doing something like filling a combobox, then a Reader is ideal. Any time you need to loop through the data quickly and use it for something other than modifying the data, odds are, a reader will suffice. They come at a small price: 1) they create an exclusive lock on the connection, meaning you cannot use it for anything else. If you need to connect to do another db operation, a second connection will be needed. 2) They are read-only and forward only. You can't change the data and cannot move backwards in the data. But that's also where thier power comes from. By being what's called a Firehose cursor, it is very fast and efficient.
-tg
awesome... that is great to know, thanks tg!
I'll add to that. In a situation when you need to work with and update a very, very, very large set of data, do not use a dataset. Instead, use a datareader, and use separate code for the database manipulation.
Mendhak & TechGnome,
Thanks so much for the reply. Your opinions are appreciated!
In addition, your GetArticleById method is returning void.
This is true. I actually changed the code without making the correct change in my question. Instead of returning something, I attached the Datareader to the object itself.
Instead of doing:
DataReader MyObject = GetArticleByID(X,Y)
I am manipulating the DataReader as part of the object:
objDatabase.DataReader
I think this is the best way to do it. I will update my initial post.
but the datareader isn't required here
I guess I'm a little confused about what TechGnome said.
t depends on what you need... if you need to get some records, manipulate the data in memory and then send the changes back, a DataSet/Table would be the candidate. But if you are doing something like filling a combobox, then a Reader is ideal.
Since in the example I am only getting one article, its title, and the picture that is associated with it, would a DataReader not be the best? I only need a read only connection that retrieves data, I do not manipulate it in any way.
It seems to me that the dataset would be more appropriate for functions that modify the data such as:
AddNewArticle(X,Y);
EditArticle(X,Y);
Thanks again for the replies.
Actualy if all you are returning is a single record... you should look into using output parameters and use the ExecuteNonQuery method.
-tg
Since in the example I am only getting one article, its title, and the picture that is associated with it, would a DataReader not be the best?
Nope. A dataset would be ideal here. You have a chunk of text, a string, and an image. You are not moving anywhere within the data. So, you need a dataset.
Have your method GetArticleById() return a dataset.
Got it, thanks for the replies all. I will use a DataSet!
Monday, March 26, 2012
Please Help
Let me start by saying that this is a custom shopping cart application, built using Visual Web Developer with an SQL 2005 Express database. This is my first real project so most of these things are new to me. For the most part, everything works, you can log in, navigate around and whatever, but the process of adding products to your cart and viewing your cart seems just that bit too hard.
The database has Products, Categories, Manufacturers, Customers and Orders tables (you'll find out the important fields later) and a membership provider has been implemented to store user details in the Customers table, those being Name, Password and E-Mail along with an automatically incremented ID.
An "Administration" section has been set up to allow people to create and modify the products, categories and manufacturers. This generates a menu on the left hand side which has links to "~/Details.aspx?CategoryID={0}" which brings up a page with a GridView control showing information about every item that belongs to the category specified in the QueryString. In this GridView, the important columns are ProductID (which has a Label), Quantity (which has a TextBox) and Add (which has a Button).
In order to add products to a customer's cart, we must do the following, which is where it gets too complicated for me...
- get the user's CustomerName and corresponding CustomerID and enter that in the Orders table
- get the ProductID of the appropriate row (the one where the button was clicked)
- get the value from the Quantity of the appropriate row
For example, finding the CustomerName is easy...
Dim CustomerNameAs String = Context.User.Identity.Name
...but then finding the CustomerID of that user and using it as a parameter in SQL is too hard.
My only idea as far as the ProductID and Quantity goes was to make the "Add" button select the row, then find the information from the selected row.
Answering the above problems would also solve this one, but then when the user goes to view their cart, we have to filter the data to only show the orders with their CustomerID. Again, that means finding the CustomerName, then corresponding CustomerID, then saying "WHERE (Orders.CustomerID = *insert parameter here*).
If someone could help me figure out these issues it would be much appreciated.
Thanks.
Managed to fix the issue regarding the CustomerID and CustomerName, but it's not the nicest of solutions.
Dim UserAs String = Context.User.Identity.NameCustomerName.Text = UserJust takes a hidden TextBox, assigns it the value of the user's name and that's used as a ControlParameter. But, as above, there should be a cleaner way of doing this and besides, it only helps with the "View Cart" page, not adding items to your cart. This is because of the following clause in the SQL...
WHERE (Customers.CustomerName = @.CustomerName AND Orders.CustomerID = Customers.CustomerID)
...but the corresponding CustomerID is still needed for adding products.
Can somebody please help me out here?
It seems a "INSERT INTO...SELECT" statement is required, we're reading up on it at the moment and trying to get it working, but some assistance would still be welcome.
For example, what is the syntax for using "INSERT INTO...SELECT" to get values from another table, while also using parameters from the page in the same statement, something like this?
INSERT INTO Orders (CustomerID, ProductID, Quantity) VALUES ("SELECT CustomerID FROM Customers WHERE CustomerName = @.CustomerName", @.ProductID, @.Quantity)
Obviously, that's the wrong syntax, but it should help to understand what we're trying to do.
Made some progress here, managing to figure out the correct SQL statement (which is below if you're interested).
The problem is, we must use controls from the corresponding row of the GridView, according to which "Add" button was clicked. To do this, we thought it would be easy to just select the row and use GridView.Rows(GridView.SelectedIndex).FindControl and to an extent that works. However, with CommandName="Select" and OnClick="Add", the latter is fired first, which means that the row is not selected.
How can we get the row to be selected before the OnClick event is triggered?
Thanks.
"INSERT INTO [Orders] ([CustomerID], [ProductID], [Quantity]) SELECT [CustomerID], @.ProductID, @.Quantity FROM [Customers] WHERE ([CustomerName] = @.User)"
Wednesday, March 21, 2012
please help i need help urgently
Hi
I am working on asp.net application using vb.net as its language
I want to displaysystem date in a textbox and enter the value into sql database when a button "submit" is clicked
how can do it?when ever this webpage is started the textbox should automatically take the date in the text box and when i click a button submit that date should enter into the sql database
how can i do this?
please help i have an urgent project to be submitted on this plzzzz
You can get the current date by using System.DateTime.Now, however, I suggest you go through the video's and tutorials fromhttp://asp.net/learn to learn how to use ASP.NET before starting on any "urgent" projects.
Hi,
In the Page Load event
first check
if(!ispostback)
then
textbox.text=datetime.now.tostring()
also same for the submit button accept send the value in the insert query rather then textbox
You can also implement it in database level by using getdate()(for SQL server) function in the insert query or stored procedure whatever used by you to insert the value in databaseYou can also implement it in database level by using getdate()(for SQL server) function in the insert query or stored procedure whatever used by you to insert the value in database.
You can also implement it in database level by using getdate()(for SQL server) function in the insert query or stored procedure whatever used by you to insert the value in database.
"please help i have an urgent project to be submitted on this plzzzz"#
sounds like homework..
Please help me improve this class for accessing database data
I've just written my first class that attempts to perform the following actions:
1. Connect to SQL Server 2000 using the connection defined in web.config
2. Execute a stored procedure (passed as a parameter) using any number of SQL parameters
3. Return the data as a dataTable back to the calling page
I need some really general advice from you experts to help improve it in the following ways if possible:
1. Reliability
2. Performance
Although it does work, it's probably quite badly written as to be honest I don't really know what I'm doing. Any help would be really appreciated!
Namespace myNS
Public Class dataGrabber
Private Shared myConn As New SqlConnection(ConfigurationManager.ConnectionStrings("myConnString").ConnectionString)
Private Shared mySQLCommand As New SqlCommand
Private Shared myDataReader As SqlDataReader
Public Sub New(ByVal storedProcedureToRun As String)
mySQLCommand.Connection = myConn
mySQLCommand.CommandText = storedProcedureToRun
mySQLCommand.CommandType = CommandType.StoredProcedure
End Sub
Public Sub AddParam(ByVal paramName As String, ByVal paramDataType As SqlDbType, ByVal paramValue As String)
Dim tmpParam As New SqlParameter(paramName, paramDataType)
tmpParam.Value = paramValue
mySQLCommand.Parameters.Add(tmpParam)
End Sub
Public ReadOnly Property getData() As DataTable
Get
Dim myDataTable As New DataTable
mySQLCommand.Connection.Open()
myDataReader = mySQLCommand.ExecuteReader(CommandBehavior.CloseConnection)
myDataTable.Load(myDataReader)
mySQLCommand.Parameters.Clear()
mySQLCommand.Dispose()
Return myDataTable
End Get
End Property
End Class
End Namespace
With my expereince, I always make my data layers static, there is really no need to maintain class instances in the data layer, however there are exceptions depending on the requirements of your project.
In my data layers, I execute a command like so: MyDataLayer.ExecuteDataSet(cn, "SP_NAME", object[] args);
notice the last parameter is an object array that will hold the parameters for the stored proc.
If you want some good ideas and good practices, download microsofts data access application block and look through the code. They have some good code in there that uses caching for parameters and connections, which speeds up the datalayer.
Also take a look at patterns & practices on msdn. there is alot of good info on there.
You shouldn't make your class-level variables (myConn etc) shared. And if you want to return a DataTable you could use the DataAdapter rather than getting a Reader and loading it into a DataTable.
Thanks both for your help.
>> You shouldn't make your class-level variables (myConn etc) shared
I thought Shared just meant that other subs and functions in the class could access these once they had been declared. Obviously not. What is Shared therefore?
>> if you want to return a DataTable you could use the DataAdapter rather than getting a Reader and loading it into a DataTable
Could you please provide an example of this that would fit the code above?
Thanks again guys!
Shared means there is only one instance of the object that spans all classes. So if you create two instances of your data class they both share the same connection and command object. So if one user on your site is running SPA and at the same time another user is running SPB you will get unexpected results.
For the DataAdapter;
http://authors.aspalliance.com/aspxtreme/sys/data/Common/DataAdapterClassFill.aspx
Hi Aidy
From the examples I can see online, all use a dataAdapter to fill adataTable or dataSet. Therefore (from my basic understanding
I'm using the class in my pages as follows;
Dim DBAccess As New myNS.dataGrabber("sp_getlogin") ' instance of class
DBAccess.AddParam("username", SqlDbType.NVarChar, loginControl.UserName) ' add param username
DBAccess.AddParam("password", SqlDbType.NVarChar, loginControl.Password) ' add param password
Dim loginTable As DataTable = DBAccess.getData() ' returns values from database to use for this user