Got a weekly problem when our ISeries DB goes down for maintenence i get ODBC connection errors when the SqlDataSource tries to connect. Is there a method I can use to catch the exception? If so, what event from SqlDataSource can i use, and what approach should I take?
Thanks in advance!
Hi,I have a connection string in my web.config - to which I then refer to in my code through all my controls, they're all databound to it.Anyway - how do I catch any errors - such as when I want to view the website on a train, if I'm working on it.I don't want it to crash and burn [the site, not the train] - if I dont have access to the sql server.How can I wrap it in a try block!?- How do i then deal with controls which refer to the connection string?One solution I thought of - is to programmatically set all the databinding - and not just with the GUI. As that way I can wrap everything in a try{}catch{} block.Any other - site-wide way of doing this?Thank you,R
I'm new to using SQL Data Source, so bare with me on the newbie question. Is there a way to do a Try...Catch type scenario on the SDS? I have a grid and a SDS that is mapped together but previously I use to use a Try...Catch and show any errors. What can I do to display a message if there is an error with the SDS? Try 'Call to DBCatch label1.txt = "Error: " & ex.Message.ToStringEnd Try And is the best way to determine if there are any records to display is to use the SDS_Selected event?Dim Rec as Integer = e.AffectedRowsIf Rec = 0 Then label1.text = "No Records Found."End If
Using RAISERROR from within a stored prcedure will result in a SQLException being thrown at the client side of a JDBC connection. I am trying to provide a meaningfull error message to be shown to the end user. However, all exceptions thrown will inevitably start with : "[Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]". The following questions then arise :
- Is there a way of configuring SQL Server not to display this header ?
alternatively,
- Is there another way of conveying error messages to the client through JDBC ?
I'm new to ASP.NET and I've searched before posting. I have a simple form containing a FormView control. The FormView uses a SQLDataSource. This works fine and in 30 seconds I have a working form without writing any code.A form built this way causes problems with connection pooling because I am not closing the connection. What is the best method for me to remedy this? Every resource I've found explains that I have to explicitly close the connection. How do I do that in this case? Dispose the SQLDataSource in the FormView DataBound event? Rewrite the form so I can control opening and closing of the connection?Thanks in advance.
I am able to connect but when I try to use the advanced sql generation options the two check boxes are non enabled (generate insert, update, and delete statementsuse optimistic concurrencywhat is happening the user id has permissions to update/delete/select from the selected table
My total test page is shown below. I monitor the connections by SP_WHO2. Without the second call, connection pooling seems to be working, ie I refresh my browser repeately but the number of connections as seen from SP_WHO2 does not increase. However, if I have the second call, every time I refresh the page at the browser, the number of connections increases by one. This is obviously not acceptable in a real world application. I tried both Integrated Authentication (with no impersonation) and using a hardcoded service account. Both have the exact same results. In fact this test is not about multi-user yet, it is the same single user just refreshing the same page. May I know what have I done wrong? All the documentation from Microsoft says close the connection after using it. In the case of SqlDataSource how do I close the connection? Thanks <%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server"> protected void Page_Load(object sender, EventArgs e) { SqlDataSource1.SelectCommand = "Select ID from Master"; System.Data.SqlClient.SqlDataReader reader = (System.Data.SqlClient.SqlDataReader)SqlDataSource1.Select(DataSourceSelectArguments.Empty); if (reader.HasRows && reader.Read()) Label1.Text = reader["ID"].ToString(); SqlDataSource1.Dispose();
//second call: read from another table SqlDataSource1.SelectCommand = "Select Name from Students"; reader = (System.Data.SqlClient.SqlDataReader)SqlDataSource1.Select(DataSourceSelectArguments.Empty); if (reader.HasRows && reader.Read()) Label1.Text += reader["Name"].ToString();
I have a connection string in the connection string section of my web.config, when I add a SqlDataSource to my page and click the ConnectionString property, My connection string does not appear in the drop down list, the only option I have is New Connection String... Are you supposed to be able to select a connection string from your web.config or am I supposed to do this on page_load? TIA,Jason
I've added an SqlDataSource control to my web page and selected "Configure Data Source" on it. This brings up a "Choose Your Data Connection" wizard, and it asks you to select from a dropdown list of presumably pre-existing connection strings in my web.config file. However none of my connection strings will display in that dropdown list. The only thing i can do is hit the "Create New Connection" button and this adds yet another connection string to my web.config file. I've already ran through the wizard once, created a new connection string, but when i run through the wizard again, even the new connection string - the one created by the last wizard will not appear in the dropdown list. Any suggestions? Jason
I'm trying to catch an error and trigger a control flow to handle it. I introduce a control flow to catch "OnError" event, but , despite muy package has some errors it doesnt work...
Another issue, if i omit an error on a transformation object ( in order let the flow continue executing), can this error be managed by an event or record it in a log?
Just downloaded and installed the VS 2008 Express and created/tested some websites. I have done several aspx websites using VS 2005 during the last 2 years. Still I don't quite understand the details of coding the database connection and DataBing. For example, what does 'providerName',and Integrated Security really mean?Why in the Web.config file these are providerName="System.Data.SqlClient" and Integrated Security=True? Why in Default.aspxthere are both ntegrated Security=True;and USER ID=WEB; Password=webwebweb1". I know these may deal with the authentication mode of my SQL Serverdatabase.For the VS 2008 Express and SQL Server 2005 Express, I installed in my XP home PC, I used the file system websites, If I upgrade to XP Pro and install IIS web server, and use SQL Server 2005, what might be different? Jeffrey Web.config <connectionStrings> <add name="NorthwindConnectionString" connectionString="Data Source=D5MRY6G1SQLExpress;Initial Catalog=Northwind;Integrated Security=True" providerName="System.Data.SqlClient" /> </connectionStrings>Default.aspx <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="Data Source=D5MRY6G1SQLExpress;Initial Catalog=Northwind;Integrated Security=True; USER ID=WEB; Password=webwebweb1" ProviderName="<%$ ConnectionStrings:NorthwindConnectionString.ProviderName %>"MasterDetail.aspx <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
I have calling a stored procedure that returns two values, and I want to catch these values and to store them into a variable.
Here is a piece of my SP inside SQL Server that shows the returned values:
… SELECT @Id = SCOPE_IDENTITY() SELECT @Id AS user_id SELECT 1 AS Value END GO
In my aspx page I am trying to call the first value like this:
Dim nID CmdInsert.Parameters.Add(New SqlParameter("@RETURN_VALUE", SqlDbType.bigint, 8, "user_id")) CmdInsert.Parameters("@RETURN_VALUE").Direction = ParameterDirection.ReturnValue CmdInsert.Parameters("@RETURN_VALUE").Value = nID
And to check if the right value is returned I use:
strConnection.open() cmdInsert.ExecuteNonQuery 'Set the value of a textbox ident.text = nID strConnection.close()
But now no value appears in the textbox, How can I achieve it? What is wrong?
I have a package that is failing parsing a CSV file. I want to write the failing line to an error file and continue processing. I've added error output to the flat file source, that didn't work. I've added an onerror event handler to the data flow task, that didn't work. I've added an event handler to the package, that didn't work. How can i output the offending line but not have the process fail?
I am trying to write a query that I only want to run on sql server 2005 databases. If a server isn't 2005, it will throw an exception. I would like to catch this general exception. Here is the query...
DECLARE @Server [nchar] (100) SET @Server = (CONVERT(char(100), (SELECT SERVERPROPERTY('Servername'))))
INSERT INTO [tempdb].[dbo].[User_Auditing] (Server, UserName, WinAuth, SQL_Auth_UserName, PassPolicyOn) SELECT @Server, s.name, isntuser, q.name, is_policy_checked FROM sys.syslogins s FULL OUTER JOIN sys.sql_logins q ON (s.name = q.name)
The errors I would get are as follows...
Msg 208, Level 16, State 1, Line 4 Invalid object name 'sys.syslogins'. Msg 208, Level 16, State 1, Line 4 Invalid object name 'sys.sql_logins'.
I know in Java, I would just put a try before the declare and a catch("Invalid object name") after the statement, however, I'm not sure if this is even possible in T-SQL. Thanks for any help. -Kyle
Hi AllHere is my SPALTER PROCEDURE dbo.InsertPagerDays @ReportEndDate datetime, @PagerDays int,@UserID varchar(25)ASIF EXISTS(-- you cannot add a pager days more than once per report dateSELECT ReportEndDate, UserId from ReportPagerDays where ReportEndDate = @ReportEndDate and UserId = @UserID)Return 1 elseSET NOCOUNT OFF;INSERT INTO [ReportPagerDays] ([ReportEndDate], [PagerDays], [UserID]) VALUES (@ReportEndDate, @PagerDays, @UserID)RETURNMy Question is, this SP will not let you enter in a value more than once (which is what i want) but how do I write my code to inform the user? Here is my VB code becuase the SP does not error out (becuase it works it acts as if the record updates)How can I catch the Return 1'set parameters for SPDim cmdcommand = New SqlCommand("InsertPagerDays", conn)cmdcommand.commandtype = CommandType.StoredProcedurecmdcommand.parameters.add("@ReportEndDate", rpEndDate)cmdcommand.parameters.add("@PagerDays", PagerDays)cmdcommand.parameters.add("@UserId", strUserName)Try'open connection hereconn.Open()'Execute stored proccmdcommand.ExecuteNonQuery()Catch ex As Exceptionerrstr = ""'An exception occured during processing.'Print message to log file.errstr = "Exception: " & ex.Messagelblstatus.ForeColor = Drawing.Color.Redlblstatus.Text = "Exception: " & ex.Message'MsgBox(errstr, MsgBoxStyle.Information, "Set User Report Dates")FinallyIf errstr = "" Thenlblstatus.ForeColor = Drawing.Color.Whitelblstatus.Text = "Pager Days Successfully Added!"End If'close the connection immediatelyconn.Close()End Try
Is there a reason why the following code does not raise an error in my .NET 2005 application? Basically I have a try..catch in my stored procedure. Then I have a try...catch in my .NET application that I want to display the error message. But, when the stored proc raisses the error, the .net code doesn't raise it's error. The .NET code DOES raise an error if I remove the try..catch from the SQL proc and let it error (no error handling), but not if I catch the error and then use RAISERROR to bubble-up the error to .NET app. (I really need to catch the error in my SQL proc and rollback the transaction before I raise the error up to my .NET app...) SQL BEGIN TRYBEGIN TRANSACTION trnName DO MY STUFF.... <---- Error raisedCOMMIT TRANSACTION trnName END TRY BEGIN CATCHROLLBACK TRANSACTION trnName RAISERROR('There was an error',10,1)
END CATCH ASP.NET CODE (No error raised) Try daAdapter.SelectCommand.ExecuteNonQuery()Catch ex As SqlException Err.Raise(50001, "ProcName", "Error:" + ex.Message) End Try
I'm trying to use an execute SQL task with a simple select to get results and scan them. I have to create a variable for each column to get results? or may i create something like a resultset variable? Does this task return only one row and i have to loop manually? (maybe on al script task..) or can i get all returned data on a result set to be the input for next step?
I am quite new using SSIS and I have a problem with catching an (SOAP) exception from a Web service task. Some times my web service task can fail and when the web service is failing, it is throwing an exception. When the task succeeds the result is being put into a variable, That part is not a problem.
But catching an exception is. I have tried to use a script task and tried to get exception from the dts object model. I have not yet succeeded on that. But it might be a possible way to go. A different approach might be creating an OnError event on my web service task which I can create a task when triggered. But I have not found any solution yet and I hope some people out there have done this before or have a solution on this.
Hello, everyone. I am having problems catching a data duplication issue. I hope I can get an answer in this forum. If not, I would appreciate it if someone can direct me to the right forum. I am working on a vs2005 app which is connected to a sql2005 db. Precisely, I am working on a registration form. Users go to the registration page, enter the data, ie. name, address, email, etc. and submit to register to the site. The INSERT query works like a charm. The only problem is that I am trying to reject registrations for which an email address was used. I put a constraint on the email field in the table and now if I try to register using an e-mail address that already exists in the database I get a violation error (only visible on the local machine) on the sql's email field, which is expected. How can I catch that there is already an email address in the database and stop the execution of the code and possibly show a message to the user to use a different address? Thank you for all your help.
I've read a few different articticles wrt how the handle this error gracefully. I am thinking of wrapping my sql insert statement in a try catch and have the catch be something likeIF ( e.ToString() LIKE '% System.Data.SqlClient.SqlException: Violation of PRIMARY KEY constraint 'PK_PS_HR_Hrs'. Cannot insert duplicate key in object %'){lable1.text = "Sorry, you already have reported hours for that day, please select anothe rdate" } Is there a better way?TIA Dan
if i have a loop that runs through records in a dataset like thisfor(int i=0;i<ds.Tables[0].Rows.Count;++i) and in this loop i have several sql commands that run as a transaction in a try / catch block like : try{ // do stuff}catch{ trans.RollBack();}how can i keep the loop going even if a transaction failed. So the transaction works for each individual row. if row 100 fails for whatever i would like the loop to continue running, do i just simply remove the "throw" and it will continue looping ? my catch block currently looks like catch(Exception ex){transaction.Rollback();activity.Log("Transaction aborted, rolling back. Error Message: " + ex.Message + " Stack Trace: " + ex.StackTrace.ToString());throw; }thanks,mcm
I'm sure that the try part of following code are all executedand the session("isLogin") has set to Truebut it always catch a exceptionand redirect to error1.aspx can't figure it out 1 Try 2 mySqlCon = New SqlConnection(strMySqlCon) 3 mySqlCmd = New SqlCommand(strMySqlCmd, mySqlCon) 4 5 mySqlCon.Open() 6 myDataReader = mySqlCmd.ExecuteReader() 7 8 If myDataReader.Read() = True Then 9 10 11 webPwdMd5 = System.Web.Security.FormsAuthentication. _ 12 HashPasswordForStoringInConfigFile(Me.TextBox1.Text, "MD5") 13 14 If webPwdMd5 = myDataReader.Item("password") Then 15 Session("isLogin") = True 16 'Me.TextBox1.Text = "ppp" 17 Response.Redirect("main.aspx") 18 Else 19 Session("islogin") = False 20 Me.Label1.Visible = True 21 End If 22 Else 23 Session("isLogin") = False 24 Me.Label1.Visible = True 25 End If 26 27 mySqlCon.Close() 28 29 Catch Myexception As Exception 30 Session("isLogin") = False 31 Response.Redirect("error1.aspx") 32 33 Finally 34 35 End Try
I am a novice with SQL, and I am failing to understand an aspect of Transactions. The following is the code I have created, having referred to a handful of resources including MSDN documentation. public void CreateSection(Section section) { string sql = @"INSERT INTO sectiontable (nodeid, title) VALUES (@nodeid, @title) SELECT Scope_Identity() FROM sectiontable"; SqlConnection connection = new SqlConnection(this.connectionString); SqlCommand command = new SqlCommand(sql, connection); command.Parameters.AddWithValue("@nodeid", section.Node.Id); command.Parameters.AddWithValue("@title", section.Title); connection.Open(); SqlTransaction transaction = connection.BeginTransaction(); try { command.Transaction = transaction; object result = command.ExecuteScalar(); if (result == null) throw new DataException("Returned identity was invalid."); section.Id = Convert.ToInt32(result); transaction.Commit(); } catch (Exception exception) { string message = "Could not create section."; try { transaction.Rollback(); message += " Transaction was reversed."; } catch (SqlException booboo) { message += " An exception of type " + booboo.GetType(); message += " occurred while attempting to roll back the transaction."; } // Note: DataAccessException below is a custom class. throw new DataAccessException(message, exception); } finally { connection.Close(); } } What seems clumsy is that we must have connection.Open() outside the try-catch block. The following cannot work, because the compiler notes the "Use of unassigned local variable 'transaction'" at the location shown below: SqlConnection connection = new SqlConnection(this.connectionString); SqlTransaction transaction; try { connection.Open(); transaction = connection.BeginTransaction(); // commands execute transaction.Commit(); } catch (Exception exception) { transaction.Rollback(); // <-- Compiler notes use of unassigned variable. // (First testing the variable does not help.) // handle exception. } finally { connection.Close(); } The following also does not work, as the BeginTransaction() method must be called against an open connection. SqlConnection connection = new SqlConnection(this.connectionString); SqlTransaction transaction = connection.BeginTransaction(); try { connection.Open(); // commands execute transaction.Commit(); } catch (Exception exception) { transaction.Rollback(); // handle exception. } finally { connection.Close(); } So, in MSDN documentation, the connection.Open() method is called outside the try-catch block (as shown in my full code). Yet, that same documentation notes that this method can lead to two types of exceptions. So it seems that the use of transactions forces an exception-throwing method to be used outside of a try-catch block. My question, then: is this unavoidable?
we are converting Informix Stored procedures to SQL Server stored procedures.. In Informix they have handled the exceptions as shown below, ON EXCEPTION LET @l_status = 1; RETURN @l_delete,@l_status; END EXCEPTION
We have to convert this to the corresponding SQL server statements.. How to ahbdle exceptions in SQL Server.
First off, congrats and thank you to everyone at Microsoft for all of the hard work they have put into Sql Server 2005 and .NET 2.0 - it is simply amazing technology.
On that note, I was wondering if it was possible to create my own custom exceptions that I can throw in my stored procedures and then catch in my application code?
For example, say I wanted to create a Custom Sql Exception called "DuplicateEmailInSqlDatabaseTableException" and then, within a stored procedure where data is being attempted to be inserted, I could check for a duplicate email record and then throw the exception. At that point, I would like to be able to catch that exception in my C# data layer and work from there.
Is this possible? I feel like it could be but am unsure where to start.
I am trying to write a query that will only give me the data that is not in both queries. I need a query that will give me the data that is in the first query but not in the second query. I tried a union but that does not work. The date and PosType are important.
SELECT Symbol,PosType,HistDate
FROM EntityView
WHERE Histdate >'01/01/07' and PosType = 'S'
union
SELECT Symbol,PosType,HistDate FROM EntityView
WHERE Histdate >'01/01/07' and PosType = 'S' and EntityCode = 'HIS'
So I have some SQLCLR stored procedures, that use some .NET classes. I have a table in the database for exceptions, and I want to log all exceptions (except SqlExceptions of course) to that table.
SqlParameter param = new SqlParameter("@message", ex.Message);
cmd.Parameters.Add(param);
param = new SqlParameter("@stackTrace", "test");
cmd.Parameters.Add(param);
param = new SqlParameter("@localtime", DateTime.UtcNow);
cmd.Parameters.Add(param);
try
{
cmd.ExecuteNonQuery(); // always throws IOE, as does SqlContext.Pipe.ExecuteAndSend(cmd);
}
catch (InvalidOperationException)
{
return;
}
}
The exception is: _COMPlusExceptionCode = -532459699 (couldn't find anything useful on that)
Ideally I don't want to be passing the connection to my class all the time, which is why I wanted to have overloaded methods, some that take the connection, others that don't, and open their own. Neither scenario works unfortunately.
If I run the code under LogException in my caller class (ExceptionTest) it works fine (I mean doesn't throw this exception, but I can't call from a SqlFunction - different issue, SQLCLR restriction).
I've been trying to debug this for a while now, and I'm running out of ideas, so any suggestion(s) would be highly appreciated.
I have a stored procedure which bulk inserts records into a table based on a passed in variable that contains comma separated values of record Ids.
However I have a constraint on the table ensuring that value-pairs in 2 columns must be unique (as a person can not be twice on the same project)
Since I insert the passed in person Ids in a loop, I’d like to catch if this constraint has been violated and skip that specific cycle if it has but do commit the rest.
Not sure if this can be done, and if yes could someone let me know the SQL syntax and structure please?
Am I explaining this clearly?
Thanks in advance all comments are much appreciated!
In my SSIS package, I have a backup database task. When I run the package with DestinationAutoFolderPath set to a folder ("Network Service" account has full permission on this folder) and DestinationCreationType set to Auto, the task works just fine creating a backup with its own name. (similar to database_date<count>).
But what I want is in my front-end I am allowing the user to specify the name of the backup file. So I want the task to create the backup file in the name I supply. I set the DestinationCreationType to manual and in the application code added the DestinationManualList with the path from the UI.
Now the pacakge runs fine but does not take any backup. There is no errors as well. If I set the FailPackageOnFailure and FailParentOnFailure to true, then I am getting the DTSExecResult.Failure but I am not getting the actual error from the backup database task.