Convert Sql Proc To A C# Class?
Dec 5, 2004Anyone have code to convert a sql proc to a C# class?
Specifially something to create the columns returned from the proc.
Thanks.
Anyone have code to convert a sql proc to a C# class?
Specifially something to create the columns returned from the proc.
Thanks.
I'm getting this error and I'm not really sure what is wrong. I'm using the sqlhelper class which was writen by microsoft, so I figure the code is right.
Here is code of me passing in the strings. Yes I tried puttinga .ToString() on the end of the sqlparameters.
public class LoginSelectData : DataAccessBase{private EndUser _enduser;public LoginSelectData(){ StoredProcedureName = StoredProcedure.Name.VERIFYUSER.ToString();}public DataSet Get(){DataSet ds;LoginSelectDataParameters _loginselectedataParameters = new LoginSelectDataParameters(this.Enduser);DataBaseHelper dbhelper = new DataBaseHelper(StoredProcedureName);ds = dbhelper.Run(base.ConnectionString, _loginselectedataParameters.Parameters);return ds;
}public EndUser Enduser{get { return _enduser; }set { _enduser = value; }}
}
public class LoginSelectDataParameters{private EndUser _enduser;private SqlParameter[] _parameters;public LoginSelectDataParameters(EndUser userinfo){this.Enduser = userinfo;
Build();
}
private void Build(){
SqlParameter[] parameters = {new SqlParameter("@username",this.Enduser.Username),new SqlParameter("@password",this.Enduser.Password)
};
Parameters = parameters;}public SqlParameter[] Parameters{get { return _parameters; set { _parameters = value; }
}public EndUser Enduser{get { return _enduser; }set { _enduser = value; }}
}
Hai Guys,
I have a doubt Regarding SqlDataReader
i can able to create object to Sqlconnection,Sqlcomand etc...
but i am unable to create object for SqlDataReader ?
Logically i understand that SqldataReader a way of reading a forward-only stream of rows from a SQL Server database. This class cannot be inherited.
sqlDatareader belongs to which class is it sealed or static class?
can we create own class like SqldataReader .......
Reply Me ...... if any one know the answer..............
Dear All,
Lately i have started to convert my sql code to stored procedures, however i am still a bit new on this matter.
I have the following Sql Statement which I wish to convert to a stored procedure:-
SELECT MAX(" & id & ") As maxID FROM " & table
where id and table are parameters that I am passing to this sql from a function which is called getMaxID
for example, in the vb.net code i call it as follows:-
getMaxID("personID", "persons")
Can anyone tell me how to convert it to a Stored Proc please
Thanks for your help and time
Johann
Hello,
I am using this sql script to achieve paging functionality for a site. IT works great for the most part, except when I need to return a result set that includes other tables.
How can I add another parameter to this to allow joined table to be a paramter? I'd like to pass in the join table name and columns to join on, or a custom select statement I guess?
CREATE PROCEDURE GetSortedPage(
@TableName VARCHAR(50),
@PrimaryKey VARCHAR(25),
@SortField VARCHAR(100),
@PageSize INT,
@PageIndex INT = 1,
@QueryFilter VARCHAR(100) = NULL
) AS
SET NOCOUNT ON
DECLARE @SizeString AS VARCHAR(5)
DECLARE @PrevString AS VARCHAR(5)
SET @SizeString = CONVERT(VARCHAR, @PageSize)
SET @PrevString = CONVERT(VARCHAR, @PageSize * (@PageIndex - 1))
IF @QueryFilter IS NULL OR @QueryFilter = ''
BEGIN
EXEC(
'SELECT * FROM ' + @TableName + ' WHERE ' + @PrimaryKey + ' IN
(SELECT TOP ' + @SizeString + ' ' + @PrimaryKey + ' FROM ' + @TableName + ' WHERE ' + @PrimaryKey + ' NOT IN
(SELECT TOP ' + @PrevString + ' ' + @PrimaryKey + ' FROM ' + @TableName + ' ORDER BY ' + @SortField + ')
ORDER BY ' + @SortField + ')
ORDER BY ' + @SortField
)
EXEC('SELECT (COUNT(*) - 1)/' + @SizeString + ' + 1 AS PageCount FROM ' + @TableName)
END
ELSE
BEGIN
EXEC(
'SELECT * FROM ' + @TableName + ' WHERE ' + @PrimaryKey + ' IN
(SELECT TOP ' + @SizeString + ' ' + @PrimaryKey + ' FROM ' + @TableName + ' WHERE ' + @QueryFilter + ' AND ' + @PrimaryKey + ' NOT IN
(SELECT TOP ' + @PrevString + ' ' + @PrimaryKey + ' FROM ' + @TableName + ' WHERE ' + @QueryFilter + ' ORDER BY ' + @SortField + ')
ORDER BY ' + @SortField + ')
ORDER BY ' + @SortField
)
EXEC('SELECT (COUNT(*) - 1)/' + @SizeString + ' + 1 AS PageCount FROM ' + @TableName + ' WHERE ' + @QueryFilter)
END
RETURN 0
Hi,
Can any one change this oracle proc. to SQL Server procedure.
Any help will be appreciated.
PROCEDURE CALC_PERC (DB_ID IN NUMBER, LAT_TYPE IN CHAR) IS
Tot_work_all number(12,2);
Bid_tot number(12,2);
Ewo number(12,2);
Overruns number(12,2);
Underruns number(12,2);
Contr_tot_all number(12,2);
sContractType ae_contract.contr_type%type;
BEGIN
select sum(nvl(tamt_ret_item,0) + nvl(tamt_paid_item,0))
into Tot_work_all
from valid_item
Where db_contract = db_id;
Select sum(Contq * Contr_Price) into Bid_tot
From Valid_item
Where nvl(New_Item,'N') <> 'Y'
and db_contract = db_id;
Select sum(Qtd * Contr_price) into Ewo
From Valid_item
Where nvl(New_item,'N') = 'Y'
and db_contract = db_id;
Select Sum((Qtd-Nvl(Projq,0))*Contr_Price) into Overruns
From Valid_item
Where Qtd > Nvl(Projq,0)
and db_contract = db_id
and nvl(New_Item,'N') = 'N';
IF LAT_type <> 'R' THEN
Select Sum((Nvl(Projq,0)-Contq) * Contr_Price) into Underruns
From Valid_item
Where Nvl(Projq,0) < Contq
and db_contract = db_id
and nvl(New_Item,'N') = 'N';
ELSE
Select Sum((Nvl(Qtd,0)-Contq) * Contr_Price) into Underruns
From Valid_item
Where Nvl(Qtd,0) < Contq
and db_contract = db_id
and nvl(New_Item,0) = 'N';
end if;
Contr_tot_all:= NVL(Bid_tot,0) +NVL(ewo,0) +NVL(overruns,0)
+NVL(underruns,0);
IF Contr_tot_all = 0 THEN
Select Contr_type into sContractType from ae_contract where db_contract = db_id;
IF sContractType = 'A' OR sContractType = 'T' THEN
--If the divisor is zero here, it's not an error.
update ae_contract set perc_compu = 0 where db_contract = db_id;
ELSE
--If the divisor is zero here, it would be an error
update ae_contract set perc_compu = 100 * tot_work_all/contr_tot_all where db_contract = db_id;
END IF;
Else
--Here we have a real number to calculate, so go ahead and do your stuff!
update ae_contract set perc_compu = 100 * tot_work_all/contr_tot_all where db_contract = db_id;
END IF;
END;
I have the following ASP code that builds part of the example SQL statement below (it's the same SQL as in my earlier thread here (http://www.dbforums.com/showthread.php?t=1214044) but a very different question):
if sFindTicketEventId > 0 then sSQL = sSQL & " AND [tblEvents].[id]=" & sFindTicketEventId
if sFindTicketStandId > 0 then sSQL = sSQL & " AND [tblStands].[id]=" & sFindTicketStandId
SELECT
[tblC].[id] AS CombinationID,
[tblC].[availability],
[tblC].[description],
[tblC].[price] AS combinationPrice,
[tblC].[combination_open],
[tblT].[TicketID] AS TicketID,
[tblT].[price] AS ticketPrice,
[tblT].[availability],
[tblT].[ticket_open],
[tblT].[quantity],
[tblT].[event_name],
[tblT].[event_open],
[tblT].[stand_name],
[tblT].[stand_open],
[tblT].[admission_start_date],
[tblT].[admission_end_date],
[tblT].[date_open],
[tblT].,
[tblT].,
[tblT2].[description],
[tblT2].[admin_description]
FROM(
SELECT
[tblCombinations].[id],
[tblTickets].[id] As TicketID, [tblTickets].[price], [tblTickets].[availability], [tblTickets].[ticket_open],
[tblCombinations_Tickets].[quantity],
[tblEvents].[event_name],
[tblEvents].[event_open],
[tblStands].[stand_name],
[tblStands].[stand_open],
[tblAdmissionDates].[admission_start_date],
[tblAdmissionDates].[admission_end_date],
[tblAdmissionDates].[date_open],
[tblBookingDates].[booking_start_date],
[tblBookingDates].[booking_end_date]
FROM [tblCombinations]
LEFT JOIN [tblCombinations_Tickets] ON [tblCombinations_Tickets].[combination_id] = [tblCombinations].[id]
LEFT JOIN [tblTickets] ON [tblCombinations_Tickets].[ticket_id] = [tblTickets].[id]
LEFT JOIN [tblEvents] ON [tblEvents].[id] = [tblTickets].[event_id]
LEFT JOIN [tblStands] ON [tblStands].[id] = [tblTickets].[stand_id]
LEFT JOIN [tblAdmissionDates] ON [tblAdmissionDates].[id] = [tblTickets].[admission_date_id]
LEFT JOIN [tblBookingDates] ON [tblBookingDates].[id] = [tblTickets].[booking_date_id]
LEFT JOIN [tblTicketConcessions] ON [tblTicketConcessions].[id] = [tblTickets].[ticket_concession_id]
LEFT JOIN [tblBookingQuantities] AS [tblBookingMinQuantities] ON [tblBookingMinQuantities].[id] = [tblTickets].[booking_min_quantity_id]
LEFT JOIN [tblBookingQuantities] AS [tblBookingMaxQuantities] ON [tblBookingMaxQuantities].[id] = [tblTickets].[booking_max_quantity_id]
LEFT JOIN [tblMemberships] ON [tblMemberships].[id] = [tblTickets].[membership_id]
WHERE 1=1
[B]AND [tblEvents].[id]=2
[B]AND [tblStands].[id]=3
--AND [tblAdmissionDates].[id]=@admissionDateId
--AND [tblBookingDates].[id]=@bookingDateId
--AND [tblTicketConcessions].[id]=@concessionId
--AND [tblBookingMinQuantities].[id]=@bookingMinQuantityId
--AND [tblBookingMaxQuantities].[id]=@bookingMaxQuantityId
--AND [tblMemberships].[id]=@membershipId
GROUP BY
[tblCombinations].[id],
[tblTickets].[id],
[tblTickets].[price], [tblTickets].[availability], [tblTickets].[ticket_open],
[tblCombinations_Tickets].[quantity],
[tblEvents].[event_name],
[tblEvents].[event_open],
[tblStands].[stand_name],
[tblStands].[stand_open],
[tblAdmissionDates].[admission_start_date],
[tblAdmissionDates].[admission_end_date],
[tblAdmissionDates].[date_open],
[tblBookingDates].[booking_start_date],
[tblBookingDates].[booking_end_date]
) as [tblT]
JOIN [tblCombinations] as [tblC] on [tblT].[id]=[tblC].[id]
LEFT JOIN [tblTickets] as [tblT2] on [tblT].[TicketID]=[tblT2].[id]
I want to turn this SQL into a stored proc; there are currently about 8 parameters that I want to pass into it. The field value for each will be either NULL or a positive integer, and the paramater will be passed in as an integer.
If the passed parameter value is a positive integer then it should return all records where the corresponding field value matches that integer. If the passed parameter is 0, it should return all rows regardless of whether the field value is an integer or NULL.
And I can't for the life of me figure out how to do it. Do I need an IF statement in there or something?
:confused:
Does any one inherit SqlDatasource class?
I treid it as :
public class MYDataSource : System.Web.UI.WebControls.SqlDataSource
{public MYDataSource(){
}
}
Debugger dont give any error or warning when i buld project. But when i use it in a page Visual studio is crashed.
Can any one help me ?
Hi All,Quick question, I have always heard it best practice to check for exist, ifso, drop, then create the proc. I just wanted to know why that's a bestpractice. I am trying to put that theory in place at my work, but they areasking for a good reason to do this before actually implementing. All Icould think of was that so when you're creating a proc you won't get anerror if the procedure already exists, but doesn't it also have to do withCompilation and perhaps Execution. Does anyone have a good argument fordoing stored procs this way? All feedback is appreciated.TIA,~CK
View 3 Replies View RelatedI have an ASP that has been working fine for several months, but itsuddenly broke. I wonder if windows update has installed some securitypatch that is causing it.The problem is that I am calling a stored procedure via an ASP(classic, not .NET) , but nothing happens. The procedure doesn't work,and I don't get any error messages.I've tried dropping and re-creating the user and permissions, to noavail. If it was a permissions problem, there would be an errormessage. I trace the calls in Profiler, and it has no complaints. Thedatabase is getting the stored proc call.I finally got it to work again, but this is not a viable solution forour production environment:1. response.write the SQL call to the stored procedure from the ASPand copy the text to the clipboard.2. log in to QueryAnalyzer using the same user as used by the ASP.3. paste and run the SQL call to the stored proc in query analyzer.After I have done this, it not only works in Query Analyzer, but thenthe ASP works too. It continues to work, even after I reboot themachine. This is truly bizzare and has us stumped. My hunch is thatwindows update installed something that has created this issue, but Ihave not been able to track it down.
View 1 Replies View RelatedIs it possible to retrieve the resultset of a stored procedure from another procedure in sql server 2000.
Basically I am calling proc2 from the inside of proc1.
proc2 returns 2 resultsets. I want to process these two resultsets
from within proc1.
If its possible , please provide sample code.
thanks in advance,
Alok.
Dear Experts,Ok, I hate to ask such a seemingly dumb question, but I'vealready spent far too much time on this. More that Iwould care to admit.In Sql server, how do I simply change a character into a number??????In Oracle, it is:select to_number(20.55)from dualTO_NUMBER(20.55)----------------20.55And we are on with our lives.In sql server, using the Northwinds database:SELECTr.regionid,STR(r.regionid,7,2) as a_string,CONVERT(numeric, STR(r.regionid,7,2)) as a_number,cast ( STR(r.regionid) as int ) as cast_to_numberFROM REGION R1 1.00112 2.00223 3.00334 4.0044SELECTr.regionid,STR(r.regionid,7,2) as a_string,CONVERT(numeric, STR(r.regionid,7,2) ) as a_number,cast (STR(r.regionid,7,2) as numeric ) as cast_to_numberFROM REGION R1 1.00112 2.00223 3.00334 4.0044Str converts from number to string in one motion.Isn't there a simple function in Sql Server to convertfrom string to number?What is the secret?Thanks
View 4 Replies View RelatedDoes anybody know of a good facility to take a SQL 2000 to SQL 2005 Admin course that is geared towards experienced DBAs, that is not so costly. I'm not the type that can sit and read on my own to learn, it has to be a real project or a classroom environment.
Also, the NYC area.
thanks,
Paul
Just started SQL Class and I am struggling with an assignment.
Would someone be kind to give me some help please?
your task is to make a stored procedure that will only billcustomers making monthly payments higher than $500.A Customer can have multiple Plans (services for which they pay amonthly fee).
You have to execute a billing procedure for each single active planunder an eligible customer account. Eligible customer account is anaccount that makes estimated monthly payment higher than $500.
You are given 2 tables, "Customers" and "Plans". Table "Customers" has columns: CustomerID, EmailAddressTable "Plans" has columns: PlanID, CustomerID, MonthlyPrice, isClosed,NextBillDate
Also, you are given two stored procedures named "Bill_Plan" and"Send_Email". All stored procedures returns 0 upon success and negativenumber upon failure.The "Bill_Plan" actually bills a customer for a plan. The storedprocedure takes one input parameter and have one output parameter.
Bill_Plan
@nPlanID = @PlanID,
@dtNewBillDate = @NextBillDate output
You have to use the output parameter @NextBillDate to updatePlans.NextBillDate with its new value.
Upon successful billing you have to send en email to the customer'semail address. The "Send_Email" stored procedure takes two inputparameters.
Send_Email
@sEmailAddress = @EmailAddress,
@sSubject = 'Your Invoice is Ready'
You have to rollback any single billing transaction upon any kind offailure and continue billing the remaining plans. (Important!!!)
Thank signed I don't want to flunk!
I am working with a large application and am trying to track down a bug. I believe an error that occurs in the stored procedure isbubbling back up to the application and is causing the application not to run. Don't ask why, but we do not have some of the sourcecode that was used to build the application, so I am not able to trace into the code.
So basically I want to examine the stored procedure. If I run the stored procedure through Query Analyzer, I get the following error message:
Msg 2758, Level 16, State 1, Procedure GetPortalSettings, Line 74RAISERROR could not locate entry for error 60002 in sysmessages.
(1 row(s) affected)
(1 row(s) affected)
I don't know if the error message is sufficient enough to cause the application from not running? Does anyone know? If the RAISERROR occursmdiway through the stored procedure, does the stored procedure terminate execution?
Also, Is there a way to trace into a stored procedure through Query Analyzer?
-------------------------------------------As a side note, below is a small portion of my stored proc where the error is being raised:
SELECT @PortalPermissionValue = isnull(max(PermissionValue),0)FROM Permission, PermissionType, #GroupsWHERE Permission.ResourceId = @PortalIdAND Permission.PartyId = #Groups.PartyIdAND Permission.PermissionTypeId = PermissionType.PermissionTypeId
IF @PortalPermissionValue = 0BEGIN RAISERROR (60002, 16, 1) return -3END
Hello,I created a class in my .Net code and I have an SQL 2005 table with a column of type image (I suppose I should use this type)After I define the class properties I need create a new record and save the class in the database.Can I do it the same way as I would save, for example, a string in a varchar field?Thanks,Miguel
View 1 Replies View RelatedHello,
I have the class below. And trying to execute it on a button click event.
What am i doing wrong ?
Thanks
Here is the button click event1 protected void Button1_Click(object sender, EventArgs e)
2 {
3 signup_data_entry signup = new signup_data_entry();
4 signup.signup_data_entry();
5
6 }
Here is my class file. please advice
1 public class signup_data_entry
2 {
3 public signup_data_entry()
4 {
5 //SqlConnection con = new SqlConnection("cellulant_ConnectionString");
6 SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["cellulant_ConnectionString"]);
7
8 SqlCommand command = new SqlCommand("Cellulant_Users_registration", con);
9 command.CommandType = CommandType.StoredProcedure;
10
11 con.Open();
12
13 //string IP = new string();
14
15
16 command.Parameters.Add(new SqlParameter("@RegionID", SqlDbType.Int, 0, "RegionID"));
17 command.Parameters.Add(new SqlParameter("@RegionDescription", SqlDbType.NChar, 50, "RegionDescription"));
18
19 command.Parameters[0].Value = 4;
20 command.Parameters[1].Value = "SouthEast";
21
22 int i = command.ExecuteNonQuery();
23
24
25 }
26 }
hiiiiiiiiii I am creating a web application using vb.net in which i m using the concept of classes. now i am done all the code for inserting the values in the database using the class but it is difficult to fetch the values from the database using select command and sending them to a WebForm . i want to know how i send send the values coming from the select command to a datagrid or another web controlif possible provide me a sample code thanks for your help
View 2 Replies View RelatedNot able to use Enterprise Mgr after updgrade. Getting Class not registered? Any idea what to do to correct? Thanks, A
View 1 Replies View RelatedCan anyone recommend a good SQL Server book or class forBeginner-Intermediate, please?Thanks
View 2 Replies View Related
there was a post some time ago but nobody answered. Maybe somebosy will answer now?
I have created a class which contains a few UDF's. The class has a static constructor that reads from the databse and loads a Dictionary<> collection.
What is the lifetime of the class?
What will cause the static constructor to be called again?
When will it be garbage collected?
If the life time is limited by default, can it be extended?
Thanks.
Good morning, all!
I'm tasked with creating POCO (C# Class Object) and XML definitions for three different kinds of records coming from my input file. The problem is that I'm not sure how to do this within the SSIS framework. It seems to me that I can somehow define a class and include XML element tags in the definition, but I'm not sure where to look/who to ask/how to do that!
The goal is to be able to assign the data types and class attributes for various parts of each input record based on position, and to serialize the data as XML (and therefore my inputs to my Data Flow will be XML objects instead of a flat file, as I had been doing it...).
Can anyone point me at a good tutorial? Or a simple example?
Also, is "DateTime" a recognized data type in C#?
Thanks a bunch!
Jim Work
Hi,
when i am trying to open a table from Microsoft Visua Studio 2005
I got the following error
Class Not Registered.Loking for object with classID:......
how resolve this?????
I recently took a class on SQL 2005. The classwork had lab files but I did not manage to hang on to the files. Are those files available for DL from MS?
I am specifically looking for the files from Module 7 "Planning for Source Control, Unit Testing, and Deployment"
TIA
Hi, I'm having trouble with the ReportingService2005 object
I'm trying to use the Get and SetPolicies methods and have used ideas from other snippets in order to get this:
...
Microsoft.SqlServer.ReportingServices2005.ReportingService2005 RS = new Microsoft.SqlServer.ReportingServices2005.ReportingService2005();
RS.Credentials = System.Net.CredentialCache.DefaultCredentials;
RS.Url = http://www.MyServer.co.uk/ReportServer/ReportService2005.asmx;
bool ip;
Policies = RS.GetPolicies("/", out ip);
RS.SetPolicies("/", Policies);
...
Does anyone have any experience with this object, or any working examples, I suspect I'm still missing some permissions thing but at the moment all I get is this annoyingly unhelpful message:
Client found response content type of 'text/html; charset=utf-8', but expected 'text/xml'. The request failed with the error message: --
BODY
{font-family:Verdana;font-weight:normal;font-size:8pt;color:black;}
H1
{font-family:Verdana;font-weight:700;font-size:15pt;}
LI
{font-family:Verdana;font-weight:normal;font-size:8pt;display:inline;}
.ProductInfo
{font-family:Verdana;font-weight:bold;font-size:8pt;color:gray;}
A:link
{font-size:8pt;font-family:Verdana;color:#3366CC;text-decoration:none;}
A:hover
{font-size:8pt;font-family:Verdana;color:#FF3300;text-decoration:underline;}
A:visited
{font-size:8pt;font-family:Verdana;color:#3366CC;text-decoration:none;}
Reporting Services Error
An internal error occurred on the report server. See the error log for more details. (rsInternalError) Get Online Help
For more information about this error navigate to the report server on the local server machine, or enable remote errors
SQL Server Reporting Services
--.
Thanks for your help,
Sean.
I created a new DataSet object using the
wizard and had no probs, it's very straightforward. I created a
GetProducts() method and also added a GetProductCount() method. I
read somewhere that when the DataSet is saved, it will generate the
TableAdapter classes and store them in the project nested under the
DataSet object. This isn't happening, the files aren't there and
yes I'm displaying all files. There *is* however the TableAdapter
class but it's in not in the project, it's a temporary file w/ the
following path:
C:WINDOWSMicrosoft.NETFrameworkv2.0.50727Temporary ASP.NET
Fileswebsitef38f8b5500014aeSources_App_Codepw_products.xsd.72cecc2a.cs.
I saved the DataSet several times, compiled the entire solution and
even closed the solution yet this temporary file isn't getting saved
where it should be. Does anyone have any ideas abt this?
I'm eager to start developing my DAL and def want to use these
TableAdapter classes.
Thx in advance,
-Pete
Hi,
I'm working on both VWDEE and VBEE and, in each, when I try to add a database diagram I get the following message (after the 'Do you want to create required objects' prompt) 'Invalid Class String'.
Any ideas?
Hello,
I put my stored procedure in my class and try to execute it but get this error
1st here is my class
1 public signup_data_entry()
2 {
3 SqlConnection con = new SqlConnection("cellulant_ConnectionString");
4
5
6 SqlCommand command = new SqlCommand("Cellulant_Users_registration", con);
7 command.CommandType = CommandType.StoredProcedure;
8
9 con.open();
10
11 command.Parameters.Add(new SqlParameter("@RegionID", SqlDbType.Int, 0, "RegionID"));
12 command.Parameters.Add(new SqlParameter("@RegionDescription", SqlDbType.NChar, 50, "RegionDescription"));
13
14 command.Parameters[0].Value = 4;
15 command.Parameters[1].Value = "SouthEast";
16
17 int i = command.ExecuteNonQuery();
18
19
20 }
and here is the error message on the testing server. Error line is line 27 below
Source Error:
Line 25: command.CommandType = CommandType.StoredProcedure;
Line 26:
Error >>> Line 27: con.open();
Line 28:
Line 29: command.Parameters.Add(new SqlParameter("@RegionID", SqlDbType.Int, 0, "RegionID"));
Source File: c:inetpubwwwrootcellulant1App_Codesignup_data-entry.cs Line: 27
HI,
I am going to make a big web application. so im going to use sql connection with class for example i have 100 web pages and i will make a slq connection in class.vb
Class1.vb(see the below code)
Imports System.Data
Imports System.Data.SqlClient
Imports Microsoft.VisualBasicPublic Class Class1
Private conn As New SqlConnection("Data Source=DANISHSQLEXPRESS;Initial Catalog=ARBASHHR.MDF;Integrated Security=True")Private cmd As New SqlCommand()
Private da As New SqlDataAdapter(cmd)
End Class
default.aspx(here is asp.net page i want to use the sql connection from that class.)
but this below page saying that Name "cmd" is not declared and connection
Try
cmd.Connection = conn
conn.Open()Dim ds As New DataSet
cmd.CommandText = "SELECT * FROM Users where (UserName = N'" & TextBox1.Text & "')" 'And (Password = N '" & TextBox2.Text & "')"da.Fill(ds, "data")
conn.Close()
For Each dt As DataTable In ds.Tables
For Each dr As DataRow In dt.RowsTextBox3.Text = dr.Item("Password")
Next drNext dt
If TextBox2.Text = TextBox3.Text ThenResponse.Redirect("Welcome.aspx")
Else
Label3.Text = "Invalid Username/password"
End IfCatch ex As Exception
' MsgBox(ex.Message) '("Error Loading Information From Database..", MsgBoxStyle.Critical, "Error")
End Try
End Sub
please let me know where im doing mistake.....
Thank in Advance
Can I use this class in ASP.NET web site with many visitors?SqlLayer.cs: public static class SqlLayer{ public static string ConnectionString = ConfigurationManager.ConnectionStrings["SomeConnectionString"].ConnectionString; public static int ExecuteNonQuery(string StoredProcedureName, string[] ParamNames, object[] ParamValues) { if (ParamNames.Length != ParamValues.Length) { throw new Exception("ParamNames.Length != ParamValues.Length"); } using (SqlConnection cSqlConnection = new SqlConnection(ConnectionString) { cSqlConnection.Open(); SqlCommand cSqlCommand = cSqlConnection.CreateCommand(); cSqlCommand.CommandType = CommandType.StoredProcedure; cSqlCommand.CommandText = StoredProcedureName; cSqlCommand.Parameters.Add("@ReturnValue", DbType.Int32); cSqlCommand.Parameters["@ReturnValue"].Direction = ParameterDirection.ReturnValue; for (int i = 0; i < ParamValues.Length; i++) { cSqlCommand.Parameters.AddWithValue(ParamNames[i], ParamValues[i]); } cSqlCommand.ExecuteNonQuery(); return (int) cSqlCommand.Parameters["@ReturnValue"].Value; } } public delegate void ActionForReader(SqlDataReader Reader); public static void ExecuteReader(string StoredProcedureName, string[] ParamNames, object[] ParamValues, ActionForReader cActionForReader) { using (SqlConnection SqlConnection1 = new SqlConnection(ConnectionString)) { SqlConnection1.Open(); SqlCommand SqlCommand1 = SqlConnection1.CreateCommand(); SqlCommand1.CommandType = CommandType.StoredProcedure; SqlCommand1.CommandText = StoredProcedureName; for (int i = 0; i < ParamValues.Length; i++) { SqlCommand1.Parameters.AddWithValue(ParamNames[i], (ParamValues[i] == null ? DBNull.Value : ParamValues[i])); } using (SqlDataReader Reader = SqlCommand1.ExecuteReader()) { if (cActionForReader != null) { //if (Reader.HasRows == false) throw new Exception("Reader has no rows"); //if (Reader.RecordsAffected == 0) throw new Exception("Reader RecordsAffected = 0"); while (Reader.Read()) { if(Reader!=null) cActionForReader(Reader); } } } } }} Using: SqlLayer.ExecuteNonQuery("SomeStoredProcedure", "ID", ID);---------SqlLayer.ExecuteReader("SomeStoredProcedure", new string[]{"Param1","Param2"}, new object[]{Value1,Value2}, Action);...void ActionForForumCollection(SqlDataReader Reader) {LabelContent.Text += Reader[0].ToString()+" - "+Reader[1].ToString();}
View 1 Replies View Relatedhi
i was reading book about asp.net and i found example for a dataacess class but i didn't understand this part
Private m_FieldData As New NameObjectCollection
Private _m_ConnectionString As String
Private m_dbConnection As SqlConnection
Private Sub AddParameters( _
ByVal objCommand As SqlCommand, _
ByVal objValues() As Object)
Dim objValue As Object
Dim I As Integer
Dim objParameter As SqlParameter
objCommand.Parameters.Clear()
SqlCommandBuilder.DeriveParameters(objCommand)
I = 0
For Each objParameter In objCommand.Parameters
If objParameter.Direction = ParameterDirection.Input _
Or objParameter.Direction = _
ParameterDirection.InputOutput Then
objValue = objValues(I)
objParameter.Value = objValue
I = I + 1
End If
Next
End Sub
Private Sub AddFieldParameters _
(ByVal objCommand As SqlCommand)
Dim objParameter As SqlParameter
objCommand.Parameters.Clear()
SqlCommandBuilder.DeriveParameters(objCommand)
For Each objParameter In objCommand.Parameters
objParameter.Value = _
_FieldData.Item(objParameter.ParameterName. _
Substring(1))
Next
End Sub
Public Function ExecDataReader _
(ByVal strStoredProc As String, _
ByVal ParamArray objValues() As Object) _
As SqlDataReader
Dim objCommand As SqlCommand
Dim objReader As SqlDataReader
objCommand = New SqlCommand
objCommand.CommandText = strStoredProc
objCommand.CommandType = CommandType.StoredProcedure
objCommand.Connection = dbConnection
Try
objCommand.Connection.Open()
If (objValues.Length = 0) Then
AddFieldParameters(objCommand)
Else
AddParameters(objCommand, objValues)
End If
objReader = objCommand. _
ExecuteReader(CommandBehavior.CloseConnection)
Catch ex As Exception
If objCommand.Connection.State.Open Then
objCommand.Connection.Close()
End If
End Try
Return objReader
End Function
can anybody help me what the author want to do
hate to gripe, but this was bad. I have taken several sql server classes over the years, and have always been happy with the class, but avoid the 2733a (upgrading you database administration skills to sql 2005). Class is poorly devloped and incomplete. Half of the examples were to do things such as mirroring and replication from a command prompt. I thought I was in an Oracle 8 class. It was clear much of this functionality is not complete. In fact most of the class was command prompt based. They had absolutley nothing about the upgrade process from SQL 2000 to SQL 2005. I hope MS is not taking a step backwards, I always thought the strong suite for MS was the enterprise manager tool suite. The instructor did tell me there was an upgrade to the class that just came out, but it has a long way to go.
View 1 Replies View RelatedToday morning i tried connecting to sql 6.5 through enterprise edition got the following error
SQL ole object could not be registered class not registered (80040154)
I did shut down and restart, stopped and restarted the services