throw new Exception statement not working in MVC3 application - c#

I am trying to import details from an access database into my sql application database. I have a check to make sure that it has imported all the rows, and if it hasn't then I want it to stop the process and throw an error.
However, despite it going into the correct function, and hitting the "throw" line, it doesn't throw the error, and instead just carries on with the process.
Should this code block not work?
AccessRepository details = new AccessRepository();
if (numRows != details.GetDetailsRowCount(periodsInFreq, payDate))
{
throw new DataException("Some data is missing from the Details table (only " + numRows.ToString() + " rows) - Please try again. If this problem persists, please contact the system administrator");
}
Thanks

Thanks to Varun and Zenwalker.
It turned out I had some nested catch statements which were cancelling each other out. I've since taken out the nested try/catches out and the errors now make a lot more sense.
Thanks

Related

Cannot read all users from Active Directory - [DirectoryServicesCOMException] MoveNext()

My team is using a program written in C# to read all users from a specific OU. The program behaves very strange. Sometimes it is working for a couple of weeks and then without any big changes on our AD or any other related component, it throws an exception. Then it is not working for a couple of weeks and after some time it start to run normally again.
Code
DirectoryEntry searchRoot = new DirectoryEntry("<LDAP string>")
searchRoot.AuthenticationType = AuthenticationTypes.None;
DirectorySearcher search = new DirectorySearcher(searchRoot);
search.Filter = <our filter>;
search.PropertiesToLoad.Add("<some property>");
search.PageSize = 1;
SearchResult result;
SearchResultCollection resultCol = null;
try
{
resultCol = search.FindAll();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
if (resultCol != null)
{
Console.WriteLine("Result Count: " + resultCol.Count); //.Count throws the Exception
}
Exception
Unhandled Exception: System.DirectoryServices.DirectoryServicesCOMException: An operations error occurred.
at System.DirectoryServices.SearchResultCollection.ResultsEnumerator.MoveNext()
at System.DirectoryServices.SearchResultCollection.get_InnerList()
at System.DirectoryServices.SearchResultCollection.get_Count()
Data: System.Collections.ListDictionaryInternal
Error Code: -2147016672
Extended Error: 8431
Extended Error Message: 000020EF: SvcErr: DSID-020A07A7, problem 5012 (DIR_ERROR), data -1018
HResult: -2147016672
Message: An operations error occured.
Source: System.DirectoryServices
Stack Trace: at System.DirectoryServices.SearchResultCollection.ResultsEnumerator.MoveNext()
Target Site: Boolean MoveNext()
Additional Information
Target Framework: .Net Framework 4.6.1 (no additional libraries)
The program is executed on a domain controller
What I have tried
I have created a loop to use the MoveNext() function of the
enumerator and found out that it loads results up to a specific
element and then crashes
It is always the same element
After the first exception all retries fail as well
The user that starts it is a domain admin (but I
have also tried it with an enterprise admin account, so it is
probably not a permission issue)
I have deleted the user that should be read when the exception happens but dring the next run the exception was thrown for a previous user
I have come to a point, where I have no more ideas on solving this problem. I would appreciate all your support.
This answer just summarizes our conversation in comments.
This thread partially matches the error you are getting:
problem 5012 (DIR_ERROR) data -1018
And the answer from a Microsoft MVP is:
That is a checksum error in the database, you have corruption in your
database which is usually due to a failing disk or disk subsystem or
possibly a system crash and data not being written from a write cache.
So it sounds like you might have the same thing going on.
But it may only be one DC that has the problem. So to help you narrow down which one, you can specify the DC in the LDAP path like so:
LDAP://dc1.example.com/OU=Target,OU=My User Group,OU=My Users,DC=example,DC=com
This can help you in two ways:
It can identify the bad DC so you know which one you need to fix (and possibly take it offline until it is fixed), and
You can specifically target a good DC so your script will keep working.

How can I check a file for an IndexOutOfRangeException and log it?

UPDATE
try
{
//Attemps string conversion for each of the point's variables
int.TryParse(row[0], out q.pointID); //Checks for existence of data on the line...
float.TryParse(row[1], out q.xValue); //Input x-value
float.TryParse(row[2], out q.yValue); //Input y-value
float.TryParse(row[3], out q.zValue); //Input z-value
float.TryParse(row[4], out q.tempValue); //Input temp-value
}
catch (IndexOutOfRangeException)
{
Debug.Log("File out of range...");
errorLogScript.errorCode = 1100;
SceneManager.LoadScene(4);
}
This is the current code that I have but it seems to be freezing whenever I attempt to transfer the scene to the errorScreen. That being said, I am not getting an error but my code is freezing and Unity crashes whenever I attempt to test this bug.
Does anyone have any ideas on how I can fix this?
OP
I am currently working on an application in Unity and I wanted to create a bug/crash-reporting system that shows the user a unique error code upon a failure to load. Being that this specific application will be used by many people with many different skill-sets, I wanted to break it as much as I can before I release it later this year. In doing so I wanted to make a quick reference that the user will be able to look up in the documentation.
The following code demostrates what happens if the user-input filepath does not exist...
if (File.Exists(dropDownMenuScript.dataFileName + ".csv"))
{
Debug.Log("File found, loading..."); //Debugs success to console
}
else
{
Debug.Log("File not found, aborting..."); //Debugs the problem to console
errorLogScript.errorCode = 1000; //Shows the code "E1000"
SceneManager.LoadScene(4); //Loads the error-screen which displays the code
}
I recently found another error that reads; "IndexOutOfRangeException" -- in this case this pertains to the parsing of the file, meaning it exists but it does not conform to the data format compatible with the program. I would like to create another error-log for this problem but I do know how to do this as it is a Unity Editor error.
I apologize if this isn't crystal-clear, but I will provide any context needed if you need it. Thanks!
Can't you use a try-catch block and specifically traps for IndexOutOfRangeException?
try
{
//Your code...
}
catch(IndexOutOfRangeException iore)
{
//Log here
}

C# Exception Include Event Details

I am new to C# and Windows development in general. I need to use it to build an integration between our data in MySQL to Microsoft Dynamics GP (using eConnect). That part is not really relevant, but adds a little context to the examples below.
Ok, so when I connect to the service:
eConnectClient client = new eConnectClient();
string newCustomerDocument = "SOME_XML_HERE";
string connectionString = "Data Source=localhost;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=GPVPM;";
try
{
client.Open();
bool result = client.CreateEntity(connectionString, newCustomerDocument);
}
catch (FaultException<eConnectFault> e)
{
Console.Write("ECONNECT FAULT: " + e.ToString() + "\n");
}
Now, if I have an error in my XML, it will cause a FaultException to be thrown, but the resulting exception message is useless:
ECONNECT FAULT: System.ServiceModel.FaultException`1[GPConnect.eConnect.eConnectFault]: The creator of this fault did not specify a Reason. (Fault Detail is equal to GPConnect.eConnect.eConnectFault).
I found that if I look in the Event Viewer for Windows, it paints an entirely different picture of what happened:
Specifically:
Error Number = 250 Stored Procedure= taUpdateCreateCustomerRcd Error Description = The Tax Schedule does not exist in the Tax Schedule Master Table
So that is something actionable that can help me identify the problem and fix it.
The question:
With C#, how can I get the same level of details from an Exception as is recorded by the Event Manager?
The server may and may not return the detailed exception to the client. You may want to check
e.Detail /* of type GPConnect.eConnect.eConnectFault */
and
e.InnerException
inside the catch block for potential details.

Ignore exception and add file to a list?

I asked a question yesterday, and recieved great help (especially from #AviTurner).
I have further developed the program I was working on yesterday, and I have encountered a new problem.
The code of my program can be found here.
Basicly what it does, is:
The user can select a path of a directory, and the program scans all files for read-only attribute.
It sets the read-only attribute on those files that does not currently have it.
Now the problem occurs, when it encounters a file that is currently in use (such as system files).
I have been told there is no way around this, but I thought:
Is there a way to ignore the error (by this I mean continue the program, just skip this file); and add the name of the file to a list for later tracking purposes?
I hope I made my problem clear.
Thanks.
try surrounding your code in try/catch:
try
{
System.IO.FileAttributes attr = System.IO.File.GetAttributes(file);
}
catch(Exception ex)
{
files.add(file)
}
basically if you get an exception in the try block, the program executes the catch block
I suggest...
try
{
System.IO.File.SetAttributes(file, attr);
}
catch // You can specify a specific error with catch(UnauthorizedAccessException ex) for instance.
{
filesInError.Add(file); // A list<string>() to keep track of errors.
}
Here the details, and exceptions raised, by the SetAttributes().
SetAttributes on MSDN
And some explanations about try catch if you're not familiar with.
try ... catch on MSDN

How can I get the actual SQL that caused an SqlException in C#? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Obtain the Query/CommandText that caused a SQLException
I am working on some error handling code (using elmah) and the default setup only sends the error message. I would like to know the actual SQL that throws an error (i.e. "SELECT * FROM thisTableDoesNotExist")
This is what I have so far:
if (e.Error.Exception is SqlException)
{
//if SQL exception try to give some extra information
SqlException sqlEx = e.Error.Exception as SqlException;
e.Mail.Body = e.Mail.Body + "<div>" +
"<h1>SQL EXCEPTION</h1>" +
"<b>Message</b>: " + sqlEx.Message +
"<br/><b>LineNumber:</b> " + sqlEx.LineNumber +
"<br/><b>Source:</b> " + sqlEx.Source +
"<br/><b>Procedure:</b> " + sqlEx.Procedure +
"</div>";
}
And I would like to be able to also show the actual SQL. The database is SQL Server 2008 and SqlException is of type System.Data.SqlClient.SqlException.
Not possible. You'll need to catch the exception where the SQL command was executed, and then include your command text in your own custom exception. See Obtain the Query/CommandText that caused a SQLException.
You could have error handling code in your SQL, and when it encounters an error, you can send back the SQL that it attempted to run with a print or returns statement or however you want to return it to your application.
The best way to examine the exception is to put a breakpoint in your code where the exception happens and examine the values of the exception object graph.
Try the Message member of the InnerException like this:
sqlEx.InnerException.Message
It may not provide the exact SQL that failed but may give you more specific information such as the operation and the table name. The StackTrace member may also have some information.
If you can't get enough information on C# side you can use "SQL profiler" (part of complete MS SQL) to see what commands where executed.
Information on SQL Profiler http://msdn.microsoft.com/en-us/library/ms181091.aspx . You should also be able to use underlying Tracing API if you don't have profiler - http://msdn.microsoft.com/en-us/library/ms191006.aspx

Categories