Null Reference Exception During Synch (can't Trap With Try-catch)
Mar 12, 2007
Dear all,
I am running into a null reference exception on replication with SQL Server 2005 Compact Edition. The problem occurs at repl.synchronize(). Even though the statement is inside a try-catch block, the exception is not caught, and the application quits.
Device O/S: Windows Mobile 5.0 v 5.1.195 Build 14957.2.3.1
Hardware: Dell Axim X51v, Intel PXA270
Database: SQL 2005 SP2 (no post SP2-patches)
Exception shows as "an unexpected error has occured in AppName.exe. Select Quit and then restart this program, or select Details for more information." Details:
.. at NullReferenceException at AppName.Form1.Synch()
.. at .... (various lines)
.. at AppName.Form1.Main()
The application is based on the tutorial (Creating a Mobile Application with SQL Server Compact Edition) at http://msdn2.microsoft.com/en-us/library/ms171908.aspx.
The application was successfully working initially but then stopped working on replication after some minor modifications which were not related to the replication code, e.g. adding some buttons to the form.
Three things are puzzling me here..
1. The fact that this is a NullReferenceException and not a SqlCeException
2. Why the try-catch block doesn't work
3. Why the exception occurs
On my aspx Web page, I want to delete a member from database table 'tblMember', but if this MemberID is used as FK in another table, I want to display a user friendlier message like "You cannot delete this member, ....." I am using Try, Catch blocks in my Web Page.
Currently it display this message: "DELETE statement conflicted with COLUMN REFERENCE constraint 'FK_..._....' The conflict occurred in database '...', table 'tblMembers', column 'MemberID'. The statement has been terminated. "
So how should I precisely trap this error? Does anybody know what Exception is it? or what error number in SQL server?
All of a sudden my application started crashing when trying execute dml statements on sql server mobile database (sdf file). Frustating thing is that whole application crashes without any error message. this happens for all kinds for DML statement but not all the time. Sometimes it would fail for delete statement such as delete from table; or for insert into statement
my problem catch does not catch the error. There is no way to find out teh what is causing this error
SqlCeConnection sqlcon = new SqlCeConnection("
Data Source = '\Program Files\HISSymbol\HISSymboldb.sdf';"
);
SqlCeCommand sqlcmd = new SqlCeCommand();
sqlcmd.CommandText = Insert into company('AA', 'Lower Plenty Hotel');
sqlcmd.Connection = sqlcon;
SqlCeDataReader sqldr = null;
try
{
sqlcon.Open();
//use nonquery if result is not needed
sqlcmd.ExecuteNonQuery(); // application crashes here
}
catch (Exception e)
{
base.myErrorMsg = e.ToString();
}
finally
{
if (sqlcon != null)
{
if (sqlcon.State != System.Data.ConnectionState.Closed)
Protected Sub detailsview1_ItemDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewDeleteEventArgs) Dim label2 As Label = CType(detailsview1.FindControl("label2"), Label) Try
Catch sqlEx As SqlClient.SqlException If sqlEx.Message.Contains("DELETE statement conflicted with COLUMN REFERENCE") Then label2.Visible = True label2.Text = "You cannot delete this Agent Type as it has a call weighting assigned to it, remove the weightings before you try to delete it" e.Cancel = True End If End Try End Sub Hi, Im using vb.net sql2005 and visual studio 2005 I have 2 tables which have a foregin key relationship. When i try to delete information from within one of my aspx pages it rightly comes up with an application errror, something along the lines of DELETE statement conflicted with COLUMN REFERENCE constraint 'FK_callScore_agentType'. The conflict occurred in database 'Merlin_####', table 'callScores', column 'typeID'.The statement has been terminated. I have looked around and can see people talking about using a try catch excpetion however i need to know how id implement this using the detailsview1_itemdeleting event. Ive never used this before and havent found a decent tutorial to help.So far i have this code but im stuck as im not sure that this is correct but more importantly what i put in the try method. Protected Sub detailsview1_ItemDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewDeleteEventArgs) Dim label2 As Label = CType(detailsview1.FindControl("label2"), Label) Try (WHAT GOES HERE) Catch sqlEx As SqlClient.SqlException If sqlEx.Message.Contains("DELETE statement conflicted with COLUMN REFERENCE") Then label2.Visible = True label2.Text = "You cannot delete this Agent Type as it has a call weighting assigned to it, remove the weightings before you try to delete it" e.Cancel = True End If End Try End Sub Your help would be greatly appreciated
Is there something like exception handling in T-SQL?For example, how to catch an error of convertion at thissample:CREATE PROCEDURE SP@param VARCHAR(50)AS BEGINDELCARE @var INT-- try {SET @var = CONVERT( int, @param)-- } catch (error#245) {-- handle an error right here-- }ENDIt must be invisible for a caller of SP if something wrong inside SP.*** Sent via Developersdex http://www.developersdex.com ***Don't just participate in USENET...get rewarded for it!
Is there any way to clear out the exception from a previous Try/Catch block if I am nesting another Try/Catch block within it. I am executing a SQL Command and based on the Error number coming back decide whether or not to execute various other Sql commands. Now the Outer exception seems to be taking precedence over the Inner try block, and even though the code is stepped through for the inner try block it is never executed due to the Parent Exception. Is there any way to clear the exception received from the outer Try block? Here is a snippet of code:
I am using sql2k5. I just wanted to throw an error from stored procedure with some message to C# to rollback my transaction. Here is how i wnated to do ( in sequence )
C# ===== Open a connection Begin the transaction Execute the command
In the Stored Proc =========== do multiple operations one by one if error stop processing further Throw the error C# ======== if exception rollback the transaction else commit the transaction
I have tried using raise error in stored proc but never thrown exception
Can any one let me know how to achieve this scenario??
I add selected rows from table1 to table2 have all the code working for that. When updating the changes I noticed that for somereason the CustomerID field was autoincrementing. Can't have that. Changed the properties to autoincrement false. Now I get an exception saying cannot add null to column. Problem is, the field is not null. When i copy the row the "CustomerID" value is 2. For some reason it is not seeing this field.
The CustomeID field is not a key. I don't want it set to autoincrement as it is in a table set on the many side of a one to many relation. The field is not set to read only. If I do set it to autoincrement it sees the field fine and updates the table with autoincrementing numbers.
I'm having trouble with a Script Component in a data flow task. I have code that does a SqlCommand.ExecuteReader() call that throws an 'Object reference not set to an instance of an object' error. Thing is, the SqlCommand.ExecuteReader() call is already inside a Try..Catch block. Essentially I have two questions regarding this error:
a) Why doesn't my Catch block catch the exception? b) I've made sure that my SqlCommand object and the SqlConnection property that it uses are properly instantiated, and the query is correct. Any ideas on why it is throwing that exception?
A report I maintain has an extensive footer that appears on each page, populated with information I've stashed into invisible cells in the table's header. This works great, except in rare circumstances where the report includes a page that doesn't display the table at all--in which case the report errors when it attempts to print ("Object reference not set to an instance of an object").
Due to the requirements of the report, I cannot guarantee that the table will appear on every page, every time. Is there a way I can safely refer to the reportItems collection, in case of Nulls? I'll be okay with blank values in the footer in the cases where the page has no reportItems to work with, but I can't have the report blow up when printing.
I have a custom assembly that uses a config file to obtain database connection settings. This dll is then used by my sql report. I have added refrerenced to all the required dll's in my report and added the required code groups to all the necessary files. I have also placed my app.config file in C:Program FilesMicrosoft SQL ServerMSSQL.3Reporting ServicesReportServer and C:Program FilesMicrosoft Visual Studio 8Common7IDEPrivateAssemblies However when I actually run the report in the designer (vs2005) I am receiving Null reference exceptions when my code tries to read my config file because it is reading the machine.config file and not my app.config file. If I hard code my connection string everything works fine.
Can anyone tell me why the machine.config file would be referenced instead of my app.config file and how I can stop it from doing this?
Greetings everyone, I am attempting to build my first application using Microsofts Sql databases. It is a Windows Mobile application so I am using Sql Server Compact 3.5 with Visual Studio 2008 Beta 2. When I try and insert a new row into one of my tables, the app throws the error message shown in the title of this topic. '((System.Exception)($exception)).Message' threw an exception of type 'System.NotSupportedException'
My table has 4 columns (i have since changed my FavoriteAccount datatype from bit to Integer) http://i85.photobucket.com/albums/k71/Scionwest/table.jpg
Account type will either be "Checking" or "Savings" when a new row is added, the user will select what they want from a combo box.
Next is a snap shot of my startup form. http://i85.photobucket.com/albums/k71/Scionwest/form.jpg
Where it says "Favorite Account: None" in the top panel, I am using a link label. When a user clicks "None" it will go to a account creation wizard, and set the first account as it's primary/favorite. As more accounts are added the user can select which will be his/her primary/favorite. For now I am just creating a sample account when the label is clicked in an attempt to get something working. Below is the code used.
account.FavoriteAccount = 1;//datatype is an integer, I have changed it since I took the screenshot.
financesDataSet.BankAccount.Rows.Add(account); //The next three lines where added while I was trying to get this to work. //I don't know if I really need them or not, I receive the error regardless if these are here or not.
catch (global:ystem.InvalidCastException e) { //Stops at the following line, this error was caused by 'if (this.financesDataSet.BankAccount[num].FavoriteAccount == 1)'
throw new global:ystem.Data.StrongTypingException("The value for column 'FavoriteAccount' in table 'BankAccount' is DBNull.", e);
I have no idea what I am doing wrong, all of the code I used I retreived from Microsofts help documentation included with VS2008. I have tried used my TableAdapter.Insert() method and it still failed when it got to
if (this.financesDataSet.BankAccount[num].FavoriteAccount == 1)
in my refreshDatabase() method it still failed.
When I look, the data has been added into the database, it's just when I try to retreive it now, it bails on me. Am I retreiving the information wrong?
When running the package in VisualStudio it runs properly, but if I let this package run as part of an SQL-Server Agent job, I got the message "The script threw an exception: Exception of type 'System.OutOfMemoryException' was thrown." on my log and the package ends up with an error.
Both times it is exactly the same package on the same server, so I don't know how the debug or even if there is anything I need to debug?
I would like to request you to kindly point me to a location where I may obtain more ideas/suggetions/details on how synchronization may be performed in a real world scenario ?
MS has been promoting smart clients and offline availability, but I cant seem to find any material that outlines some ideas/techniques/pointers as to how this may be acheived sans SQL Server replication
Essentially, what I'm looking for is someting that would guide a not-so-solid-with-databases person like me through how synchronization (sans sql replication engine) may be implemented - any watchouts etc..
Hi all, here are my goals: Have the same DB on two different stand-alone computers, and keep them up-to-date from each other.
Basically a user would input to a DB for a week. Then every week or two, update the other stand alone DB with the new input. The DB would be exactly the same.
What are my options for this? I'd like it as easy as possible! Are there any software packages that deal with this type of transfer, etc.? Thank you!
I have to schedule the automatic restore the standby database fortesting backups . The database was already in log shipping mode. Up towhat point do I need to restore the database without affecting the logshipping sequence? Can we query the log shipping tables for the lastscn applied and recover up to that point? Any suggestoions are welcome.ThanksTram
All,I have an Access DB. On a nightly basis, I want to look at an OtherDB (not Access, but SQL) and:+ Add any new records from Other.Clients into Access.Clients
I am trying to create a trap to catch one of my developers which is messing around on my Live system, where he doesn't belong. I have already created a trigger which is logging and catching the guy out, but i need to know which queries he is executing on this table.
Here is my trigger:
Code Block ALTER TRIGGER [dbo].[ctr_SQLTrapDelete] ON [dbo].[Members] AFTER DELETE AS INSERT INTO SQLTrap ([User], TYPE, DateValue, HostName, SystemUser, TableName) SELECT USER_NAME(), 'DELETE', GETDATE(), HOST_NAME(), SYSTEM_USER, 'Members'
I want to add a Query field at the end of the table with the query that the guy executed.
Will anyone be able to tell me how where i am going to find the query that he executed, i am unsure of where it will reside.
I think possible in the Master.dbo.syscomments table but i'm unsure of how i am going to track the query to insert it into the table with the timestamp.
I am using vs 2010 to write my dtsx import scripts.I use a script component as a source to create a flat file destination file.Everything have been working fine,but then my development machine crashed and we have to install everything again.Now when i use the execute package utility to test my scripts i get the following error:
Error system.NullReferenceException: Object refrence not set to an instance reference.
In PreExecute section TextReader = new system.io.streamreader(" file name") In the CreateNewOutputRows: dim nextLine as string nextLine = textReader.ReadLine
[code]...
is there something which i did not install or what can be the error?
Hi, I have a page with only a Datasource and a Gridview that allows Delete. In the database there is a referential integrity (RI) to the one of the columns. When a user tries to delete the row, the RI stops the delete and throws an error message the way it should. But it also create a hard failure on the page. How do I trap the error message so I can display a message "Referential Integrity denied deletion of this record." rather than having it fail ?
We are running SQL 2000 sp3a on Win2003 Server with all patches and SPs applied.
I want to run a stored procedure from a SQL Agent job. I want the stored procedure to run as a TRANSACTION to force a ROLLBACK in case of failure. However, if execute the procedure and an error of severity level 20 (I think) or greater happens I get blown out of the job immediately. Therefore I cannot call RAISEERROR or use @@ERROR. So, how do I assure that I can ROLLBACK the TRANSACTION?
I have searched the web and BOL and cannot find anything that addresses this specifically.
we have a merg replication running in three regions UK,USA and AU
my question is in one of our test environment testers managed to get a few tables out of synch while the replication is out.
we have re-established the replication since then and it worked fine untill they try to update records from those out of synch tables. as usual we get conflicts.
we don't really know how many tables are out of synch either. we have about 500 tables.
is there a way to synch tables from with in the merge replication??
I'm using System.Net.Mail in a script task to send HTML email via SMPT client as follows:
Imports System Imports Microsoft.SqlServer.Dts.Runtime Imports System.Net.Mail Imports System.Net
Public Class ScriptMain
Public Sub Main()
Dim myHtmlMessage As MailMessage Dim mySmtpClient As SmtpClient
myHtmlMessage = New MailMessage("<from>", _ "<to>, _ "Test HTML Message", _ Dts.Variables("HtmlText").Value.ToString) myHtmlMessage.IsBodyHtml = True mySmtpClient = New SmtpClient("<smtpservername") mySmtpClient.Credentials = CredentialCache.DefaultNetworkCredentials mySmtpClient.Send(myHtmlMessage)
Dts.TaskResult = Dts.Results.Success
End Sub
End Class
I need to be able to trap an error when the email address is undeliverable. Is there a way to do this in SSIS? I am validating the email address before sending, but it can still come back as undeliverable. I need to be able to catch this.
I have a system using asp pages & ADO & SQL Server 2000, which processes files, builds a SQL insert statement from the file content and then executes it.
If the insert SQL fails, I need to know whether there was something wrong with the insert SQL, or something wrong with the database (e.g. SQL Server times out), and handle those differently,
Questions ======= 1. Is there an easy way to do this without checking against a list of error codes? 2. Can anyone point me to a list of errorcodes? Can't find this anywhere
hi i am running a stored procedure and i want to trap the error of that stored procedure and pass it on the user in the asp.net prog.
my stored procedure are running thru a class library using C#. i tried various options of creating a new sql connnection with out using the classlibrary, but i dont get any errors. the code s used is as follows Dim conn As New SqlConnection(System.Configuration.ConfigurationManager.AppSettings("dbconnection1"))
Dim cmd As New SqlCommand("usp_ImportPlanDetails", conn)
and also tried doing this oImportPlan = New ImportPlan(System.Configuration.ConfigurationManager.AppSettings(APPSETTINGS_CONNECTION))
With oImportPlan Try .ClientID = Session("ClientId") ' .FileName = strFilePath1 .save() Catch sqlex1 As SqlException LogException(sqlex1) End Try
End With Catch sqlex As SqlException LogException(sqlex) End Try Catch ex As Exception lblErrorMsg.Text = "Error: Import Failed" + ex.Message lblErrorMsg.Visible = True
End Try but have no luck in displaying the errors, My stored procedure has raiseerrors, Please help me out
Is there any way to prevent unimportant errors in a stored procedure from causing exceptions in my C# code? This is preventing the SqlAdapter from filling the query results into my DataSet.
The Setup:
I have a Stored Procedure in Sql Server 2000 which has a text parameter called @Xml. I send in an Xml document to process. This document contains several "records" to process. The format of the xml really isn't important.
I create a temporary table called #Results to hold the results of processing each record in the xml.
To process the xml I have a Cursor which loops over a SELECT from the xml.
For each record, the sproc attempts to make a series of INSERTs and UPDATEs inside of a transaction. Any one of these commands may fail because of constraint violations or attempts to insert NULL into non-null columns, or such. After each command I check @@ERROR. If it is not zero, I stop processing the record and rollback the transaction. The cursor loops around and tries the next record. Each time the success or failure of the transaction is recorded into the #Results table.
When the cursor is done looping I 'SELECT * FROM #Results'.
I've tested this many times in the Query Analyzer and each time, regardless of any errors, I can see the result set from the SELECT of the #Results table in the Grids tab. The Messages tab shows each of the errors that occurred.
I try to call this stored procedure using the following code:
The value of c will always be zero, if there were any errors during the execution of the stored procedure. The DataSet does not get filled, even though the stored procedure is returning a result set. This is a problem for me because I expect errors to occur, and I need to know which records from the Xml caused those errors.
Is there any way to clear the errors in my stored procedure so that they don't turn into exceptions in my code? Or, is there anyway to get the Adapter to fill the DataSet regardless of any errors that were encountered?
I've also tried this with a SqlDataReader. The reader never gets assigned to because SqlCommand.ExecuteReader() throws an exception.
As most of you do, I am eagerly awaiting the ability to synchronize my sql mobile database on the hand held to a local sql express database on my local machine
I know users in Microsoft have pointed out to us that we are getting things for free.
At the same time, Microsoft is getting our patience for free and at a cost to us developers.
Its nearly April and as one article says Microsoft will release a fix for this inadequacy
Microsoft...we are happy to pay for this. Palm offers it so what is the big deal. Its not the
reinvention of the wheel. We would have liked that instead of the server synchronization
that bypasses the local sql express database
I as many others are happy to pay
Please let us know when you will be addressing this problem.
I would appreciate the feedback and frustration of other developers. Maybe this will show them we are really running out of time with our clients
Hi ... I am converting SqlServer 2000 databases to SqlServer 2005. It is working great for the most part. The issue I am having is that a user with a schema that owns objects is established in the database and no user is defined in the instance logins. I can see where if I add the instance login then the Principal_id does not match. Cannot drop the user/schema as there are referenced objects.
I got around this in SqlServer 2000 by updating the IDs to match but now they are views and updating is not allowed.
Is there a straightforward way to resynch the database user to a newly created login?
I have an SSIS package that fires an OnTaskFailed event whenever any of my tasks fail. I would like to put any SSIS task failure message into a user defined variable. Any idea how to do this? Any help appreciated. Regards, Paul.
I have a database with primary and Unique key contraints on SQL Server 2000. I'm front ending it with Access 2k.
I want to trap the error when the Unique key constraint is hit, but i can't capture the error number. All attempts return error 0.
The error i get is [Microsoft][ODBC SQL Server Driver][SQL Server]Violation of UNIQUE KEY constraint 'IX_lut_Referral_Source'. Cannot insert duplicate key in object 'lut_Referral_Source'. (#2627)[Microsoft][ODBC SQL Server Driver][SQL Server]The statement has been terminated. (#3621)
I've tried the soultion given here http://support.microsoft.com/kb/q185384 but now get a Type mismatch error on errStored
SaveRecODBCErr: ' The function failed because of an ODBC error. ' Below are a list of some of the known error numbers. ' If you are not receiving an error in this list, ' add that error to the Select Case statement. For Each errStored In DBEngine.Errors