SQL Try..Catch..Finally Errors Not Displaying - asp.net-mvc

How can I get the SQLException error messages below to display?
I have a site where users upload a data file. I have intentionally added incorrect data (text to a field that only allows integers) as a test of my error handling. Nothing is rendering in the view. I am sure that an exception is being thrown, as none of the data is in the database. If I remove the incorrect field, everything uploads fine. I have also tried both ex.toString() and ex.message with no success.
In my view, I have:
#ViewBag.ErrorMessage
Controller:
using (SqlCommand command = new SqlCommand(sql2, con))
{
try
{
// long SQL statement
con.Open();
command.ExecuteNonQuery();
TempData["shortMessage"] = "Dataset Uploaded Successfully.";
}
catch (SqlException ex)
{
ViewBag.ErrorMessage = ex.ToString();
}
catch (Exception ex)
{
ViewBag.ErrorMessage = ex.ToString();
}
finally
{
con.Close();
}
}

Related

How to make two insertion all successful and failure?

In my recent project, for each user's payment, it needs to insert a Receipt and an Invoice into the SQL DB. I have 2 functions for it, InsertReceipt() and InsertInvoice(), so the code is like:
void DoPayment()
{
InsertReceipt();
InsertInvoice();
}
bool InsertReceipt()
{
// insert to SQL with a ReceiptId
// return true or false;
}
bool InsertInvoice()
{
// insert to SQL with an InvoiceId
// return true or false;
}
ReceiptId and InvoiceId have to be unique and consecutive here.
My question is, how can I do to make InsertReceipt() and InsertInvoice() all successful or all failure? Or I have to make a new function InsertReceiptAndInvoice(), and use SQL Transaction?
If you use a stored procedure, you absolutely can use transaction. You can read about transaction in Microsoft docs:
https://learn.microsoft.com/en-us/sql/t-sql/language-elements/begin-transaction-transact-sql?view=sql-server-ver15
With C#, you can use transaction with SqlConnection. Code example:
private static void ExecuteSqlTransaction(string connectionString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = connection.CreateCommand();
SqlTransaction transaction;
// Start a local transaction.
transaction = connection.BeginTransaction("SampleTransaction");
// Must assign both transaction object and connection
// to Command object for a pending local transaction
command.Connection = connection;
command.Transaction = transaction;
try
{
command.CommandText =
"Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')";
command.ExecuteNonQuery();
command.CommandText =
"Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')";
command.ExecuteNonQuery();
// Attempt to commit the transaction.
transaction.Commit();
Console.WriteLine("Both records are written to database.");
}
catch (Exception ex)
{
Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
Console.WriteLine(" Message: {0}", ex.Message);
// Attempt to roll back the transaction.
try
{
transaction.Rollback();
}
catch (Exception ex2)
{
// This catch block will handle any errors that may have occurred
// on the server that would cause the rollback to fail, such as
// a closed connection.
Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
Console.WriteLine(" Message: {0}", ex2.Message);
}
}
}
}
You can read docs: https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlconnection.begintransaction?view=dotnet-plat-ext-3.1

want to get rid of Overwriting in filehandling

My code is perfect but still my cursor is on the beginning of text my and keep overwriting previous input whenever I give new input
String username=Cuser.getText();
String password=Cpass.getText();
FileWriter filewriter;
try{
filewriter=new FileWriter("Record.txt");
try (BufferedWriter bufferedWriter = new BufferedWriter(filewriter)) {
bufferedWriter.write("Username"+" :" + username+" Password"+" :" + password+"\n");
// bufferedWriter.write();
JOptionPane.showMessageDialog(null, "Account Created Successfully!");
bufferedWriter.close();
}
} catch (IOException ex){
JOptionPane.showMessageDialog(null, "Error!");
System.out.println("Error! ");
}
So I found out my error
try (BufferedWriter bufferedWriter = new BufferedWriter(filewriter) Visible )
that visible was at end was not in my program which was causing to create new data each timing

blackberry unable to send url request to server continuously

this is the code i wrote to send the url request using a thread:
while(true)
{
String url="http://192.168.1.7:8084/SFTS/updateLocation.jsp?empid=12304&lat=16.23&lon=21.998;interface=wifi";
try{
StreamConnection conn = (StreamConnection)Connector.open(url, Connector.READ_WRITE);
conn.openInputStream();
Thread.sleep(30*1000);
conn.close();
}catch(Exception e)
{
e.printStackTrace();
}
try {
Thread.sleep(30*1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
the code i used to this thread:
Calendar cal=Calendar.getInstance();
long time=cal.get(Calendar.HOUR);
add(new RichTextField(String.valueOf(time)));
(new test()).start();
by using this code i am able to send one request successfully but after that server is not receiving other request. please provide me a solution.
Firstly, when you're using a while loop like this, you shouldn't put the sleep within the try method.
while(true)
{
try{
String url="http://192.19.18.10:8084/SFTS/updateLocation.jsp?empid=12304&lat="+lan+".23&lon=21.998;interface=wifi";
StreamConnection conn = (StreamConnection)Connector.open(url, Connector.READ_WRITE);
conn.openInputStream();;
}catch(Exception e)
{
e.printStackTrace();
}
try {
Thread.sleep(30*1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Secondly, you're constantly trying to create a new stream without first closing the previous connection. Either read up on how StreamConnection works effectively, or simply use ConnectionFactory and not StreamConnection.
ConnectionFactory connFact = new ConnectionFactory();
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection(url);
if (connDesc != null) {
try {
HttpConnection httpConn;
httpConn = (HttpConnection) connDesc.getConnection();
httpConn.close();
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
}
The above is for OS 5 and above, in your case... as the connection seems to work the first time, in your existing code I would try simply closing the connection using:
conn.close();

Blackberry InputStream Closes Prematurely

The following code is used to get an XML file from a web server, and today, for the last few runs, this throws an exception with an error message "stream close." I have not modified this code since yesterday, nor have I modified any methods that handle the parsing.
The idea is this builds a list of item from the XML file pulled from the fullurl. There should 20 items in the list (based on the XML file I am using right now). In the last few runs, the parsing operation has thrown the exception mentioned above, and only stores 5 items. The method public void endDocument() never gets called.
Any thoughts would be helpful, since this will have to be moved to a background task, and I would like to have solved before I do that.
public void getAndParseXML() {
HttpConnection xmlcon = null;
InputStream xmlinput = null;
SAXParserFactory spf = null;
String fullurl = this.getNewsUrl() + NewsListBuilderTask.CONNECTION_STRING; // URL of XML file along specification for connection type
if ( (TransportInfo.isTransportTypeAvailable(TransportInfo.TRANSPORT_TCP_WIFI)) && (TransportInfo.hasSufficientCoverage(TransportInfo.TRANSPORT_TCP_WIFI)) )
fullurl += NewsListBuilderTask.WIFI_STRING;
try {
xmlcon = (HttpConnection)Connector.open( fullurl, Connector.READ, false ); // open connection to XML source
spf = SAXParserFactory.newInstance(); // set up xml parsers
xmlinput = xmlcon.openInputStream(); // set up input stream
SAXParser saxparser = spf.newSAXParser(); // create a new parser object
saxparser.parse( xmlinput, this ); // parse operations start here
}
catch( IOException ex ) {
System.out.println( "IOException Caught:\t" + ex.getMessage() ); // set a default item if any exception occurs with retreiving or parsing XML file
this.createDefaultItem();
}
catch (SAXException ex) {
System.out.println( "SAXException Caught:\t" + ex.getMessage() );
ex.printStackTrace();
this.createDefaultItem();
}
catch ( IllegalArgumentException ex ) {
System.out.println( "IllegalArgumentException Caught:\t" + ex.getMessage() );
ex.printStackTrace();
this.createDefaultItem();
}
catch (ParserConfigurationException ex) {
System.out.println( "ParserConfigurationException Caught:\t" + ex.getMessage() );
ex.printStackTrace();
this.createDefaultItem();
}
finally {
if ( xmlinput != null) {
try {
xmlinput.close(); // attempt to close all connections
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if ( xmlcon != null ) {
try {
xmlcon.close();
}
catch ( IOException ex ) {
ex.printStackTrace();
}
}
}
}
NOTE: The fullurl used ends up bieng "http://somexmlfile.com?type=photo;deviceside=true" with ";interface=wifi" appended if available.

SubSonic - Is it necessary to/how to explicitly close the database connection?

Traditionally when using a DbCommand when retrieving data from a sproc, something like the following is good practice:
DbCommand cmdDbCommand...
dbGetData = DatabaseFactory.CreateDatabase("MyDatabase");
cmdDbCommand = dbGetData.GetStoredProcCommand("MySproc");
.
.
.
try
{
...
}
catch (System.Exception ex)
{
if (cmdDbCommandcmdDbCommand != null)
{
if (cmdDbCommand.Connection.State == ConnectionState.Open)
{
cmdDbCommand.Connection.Close();
cmdDbCommand.Dispose();
}
}
}
Now, given the following type of SubSonic call:
try
{
StoredProcedure sp = SPs.GetSprocData(someID, result, errorMessage);
dsResults = sp.GetDataSet();
intResGetUserDetails = (int)sp.OutputValues[0];
errorMessage = (string)sp.OutputValues[1];
}
catch (System.Exception ex)
{
...
}
How can I explicitly ensure that the database connection has been closed?
The connection closes after the sproc is complete. This is built into Sobsonic 2.

Resources