Catching SqlDataSource Connection Exceptions?

Feb 14, 2008

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! 

View 2 Replies


ADVERTISEMENT

Catching SQL Exceptions For ConnStrings In Web.Config

Aug 25, 2006

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

View 2 Replies View Related

Catching Errors And Row Cnt From SQLdataSource

Mar 7, 2007

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
 
 
 

View 2 Replies View Related

SQLServer JDBC Exceptions :Controlling Exceptions Text Format

Sep 28, 2006

Hi,

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 ?

Thank you for your answers,
Ben

View 1 Replies View Related

Does SqlDataSource Hold The Connection ?

Mar 9, 2006

If we bind a GridView to a SQLDataSource, is it not a connected usage, which locks up one connection thread ?

View 2 Replies View Related

Closing A Connection Created From A SQLDataSource

Jun 20, 2006

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.

View 1 Replies View Related

Problem Creating A Sqldatasource Connection

Sep 19, 2006

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

View 1 Replies View Related

Connection Pooling Not Working With SqlDataSource

Jun 14, 2008

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();

reader.Close();
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:myConnectionString %>"
DataSourceMode="DataReader"></asp:SqlDataSource>
</div>
</form>
</body>
</html>
 

View 2 Replies View Related

SQLDataSource Connection String From WebConfig

Feb 21, 2006

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

View 2 Replies View Related

Getting The List Of Connection Strings To Display In The SqlDataSource Wizard

May 15, 2007

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 

View 3 Replies View Related

Catching Events

Aug 30, 2007

Hi,

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?

Thanks

View 6 Replies View Related

How To Use ProviderName, User ID, Password, And Connection Saved In Web.config And SqlDataSource

Jun 1, 2008

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 %>"               

View 1 Replies View Related

Catching Return Values Of A SP

Feb 4, 2004

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?

View 6 Replies View Related

Error Catching In SSIS

Jun 26, 2007

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?

View 4 Replies View Related

Catching A General Exception

Sep 11, 2007

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

View 1 Replies View Related

Catching A Return From SQL Stored Procedure

Sep 6, 2006

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

View 1 Replies View Related

.NET 2005 TRY..CATCH With SQL RAISERROR Not Catching

May 28, 2008

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
 

View 4 Replies View Related

Execute SQL Task (catching Results)

Aug 7, 2007

Hi,

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?

Thanks!

View 6 Replies View Related

Catching An Exception From A Web Service Task

Aug 30, 2006

Hi!

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.



Regards



Geir F

View 1 Replies View Related

Error Catching On Data Duplication In A Sql2005 Db

Apr 15, 2007

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.
 
Antonio

View 4 Replies View Related

Catching Primary Key Violation On Insert Error

Aug 9, 2007

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 

View 4 Replies View Related

Catching Exception In Stored Proc And Logging

Dec 7, 2005

Hi,

I am new to SQL Server and hence asking this.....

I have a requirement to catch any problem within my code and log it into a table with structure:

CREATE TABLE ERROR_LOG
(MSG varchar(1000),
ERROR_CODE varchar(1000)
)

As an example:

declare @test int
begin
--deliberately assigning a char into an int variable
set @test='ABC'
end

This, as expected throws an error like:

Msg 245, Level 16, State 1, Line 2
Conversion failed when converting the varchar value 'ABC' to data type int.


I want to catch the first line to ERROR_CODE field and the second line to MSG field in ERROR_LOG table

I also need to do it such that this proc seems SUCCEDED with logging into error log

How can I do this in SQL Server?

Please suggest.......

[From Oracle background, actually I am speaking about EXCEPTION Block in Pl/SQL]

Best Regards,

Ayan

View 4 Replies View Related

Transactions And Exceptions

Nov 1, 2006

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

View 4 Replies View Related

Unknown Exceptions

Jan 22, 2008

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
 

View 2 Replies View Related

Transactions And Exceptions

Dec 10, 2005

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?

View 3 Replies View Related

Exceptions In Sql Server

Aug 23, 2001

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.

View 1 Replies View Related

Exceptions Info

Jan 11, 2007

Vikas writes "can any one help me in getting the list of exceptions and there types and how to tackle them."

View 1 Replies View Related

Migration Exceptions

Nov 29, 2006

Hi,
How should one deal with exceptions generated by the DTS to SSIS conversion wizard in sql server 2005?
Thanks

View 1 Replies View Related

Custom Sql Exceptions Through The CLR

Jan 9, 2006

Friends,

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.

Shaun C McDonnell

View 5 Replies View Related

Self Join- Exceptions

Jan 3, 2008

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'


View 3 Replies View Related

Want To Log CLR Exceptions In SQL Table

Jul 22, 2006

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.

I have the following example:



public partial class UserDefinedFunctions

{



[Microsoft.SqlServer.Server.SqlFunction(FillRowMethodName = "FillRow2", DataAccess = DataAccessKind.None, SystemDataAccess = SystemDataAccessKind.Read,



TableDefinition = "fld_colname NVARCHAR(4000)")]

public static IEnumerable ExceptionTest()

{

// Some example from a website

List<string> names = new List<string>();

using (SqlConnection connection = new SqlConnection("context connection=true"))

{

connection.Open();

SqlCommand sqlCommand = connection.CreateCommand();

sqlCommand.CommandText = "select NAME from dbo.SYSCOLUMNS";

SqlDataReader sqlDataReader = sqlCommand.ExecuteReader(); // No exceptions

while (sqlDataReader.Read())

{

names.Add(sqlDataReader.GetValue(0).ToString()); // This works fine

}

Exception e = new Exception("foo");

MyExceptionLoggingClass.Log(e,connection); // This doesn't

}

return names;

}

public static void FillRow2(object row, out string str2)

{

str2 = (string)row;

}

}



public class MyExceptionLoggingClass

{

public static void Log(Exception ex, SqlConnection conn)

{

LogException(ex, conn);

}

private static void LogException(Exception ex, SqlConnection connection)

{



SqlCommand cmd = new SqlCommand("LogException", connection);



cmd.CommandType = System.Data.CommandType.StoredProcedure;



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.



Thanks!

View 17 Replies View Related

Catching Violation Of UNIQUE KEY Constraint In Stored Procedure

Dec 20, 2005

Dear All,

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!

View 2 Replies View Related

Catching Errors In SSIS Backup Database Task

Aug 28, 2006

Hi,

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.

Am I missing anything here?

Thanks in advance,
Srikanth.

View 4 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved