how to handle all sql exceptions throughout the page [closed] - c#

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 12 years ago.
"I DONOT WANT TO use the default error page tachnique, because i donot want the webpage to redirect!"
yes there is the try and catch
yes there are way to add exception handling mathods overwrite for controls
but what i need is,
it may just be a simple sql command,it may be a control such as formview, it may be a control such as datagrid, whatever it may be, when an illegal entry is done into the table of the database,
"THE BIG ERROR PAGE SHOULD NOT COME!!"
instead
a label at the top of the same page (where the illegal operation is performed) should display the error like
"error caused by "this control" and the error message is "null is not allowed in this field blah blah"
thank you
note:- am i asking for the complete code! well yes please guide me thanks

I think the bottom line is that you need to validate your data before you try to put it in your database.
Each control contains its own validation hooks. Check the documentation for the controls you are using on MSDN in order to find out how to properly validate the data contained in them. In your validation procedure you can then determine the controls containing the bad data and update your label.
The default error page is not an error handling technique as such. It is a failsafe for when your application fails. Your updates to the database are throwing boneheaded exceptions - exceptions which your code should never cause to happen - you shouldn't even handle them - they represent bugs in your code which need to be fixed.
Simply grabbing plain user input without validating, trying to get it into your database, and then trying to detect problems is a recipe for disaster. I hope that you're at least wrapping your database commands in transactions if you're doing this, otherwise you could end up with who knows what in your database.

Use a try and catch construct around your SQL queries: if the code in the catch block is hit, then call a method which makes your error label visible, and sets some error text relevant to the part of the code that failed.
This is the cleanest and most widely-accepted way of dealing with this; although you should have separation and encapsulation too. The user interface (ASP.NET pagebehind code, for example) shouldn't usually call straight through to a database; it would call business logic methods or Data Access Layer methods which would update the database. You'd still want to catch exceptions that are thrown from these layers, though. The 'best' you can do is to create a method that manages the state of your 'error' label.
Hope that helps.

Related

How to design the code that builds an sql query statement from a 'user friendly' UI? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I have inherited a c# (wpf) project where part of the code is a user friendly UI (list boxes, radio buttons,sliders, etc.) for a non SQL person that creates a SQL query statement ... then queries a DB and returns the results.
The code to create the SQL basically walks thru the UI components and concatenates a string.
I'm slowing finding either bugs in the code and\or misinterpretations of the what was needed.
I want to update the code to a more elegant and maintainable state. Are there any:
'design patterns' for this?
best practices?
examples of good code?
Thanks
Many wrote code like that when .net started; there are indeed many design patterns to move on from this.
Firstly, the project mixes c# and sql syntax. Separate those to halve the code size and double the elegance. Also to remove sql injection possibilities.
identify what the final sql typically looks like. Might be
select a,b,c from d join e join f where x and y and z
write a stored procedure on the sql side to encapsulate this, passing parameters x, y , z
change the c# code to call the stored procedure instead of the sql statement
c# debugging can now involve just viewing the parameters you end up with when you get to call the sql statement
on the sql side, the next step is to move the table joins and any static where clauses into a view, which will further simplify the stored procedure and also give the sql server more opportunity to pre-optimise the data selection.
Good luck
I don't have any particular design-patterns for this, but if I was to implement something of this kind, I think I would try to create a sort of abstract representation of each SQL-operation that I would need to work with; perhaps something like the way SQLite documents it's queries.
Thinking in this way may be helpful when creating data structures to represent your queries.

Expected 1 Actual 0 [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
i am developing a Spring .net Application.
I have a Login Page with fields - LoginID Password
On Login-There is a form to be filled by the candidate
so after Login I check if the candidate has already filled form then the values are fetched from the database and shown in the form fields.
Now When the Candidate hasn't filled the form the database null rows for it and hence it gives me the above error..please tell me how should I resolve this error.
I tried checking if the obj is null but it does not go to to the next line to check of the obj is NULL it immediately throws the above mentioned exception
IT GIVES ERROR IN LINE 6 OF THE PAGE_LOAD FUNCTION
EXCEPTION:EmptyResultDataAccessException was caught
Incorrect Resultsize Expected 1 Actual 0
As I said above, I've never worked with Spring.NET, but taking a look at the documentation I believe you may be using the wrong method of the AdoTemplate class. QueryForObject, per the documentation, will `Execute a query mapping the result set to an object using a IRowMapper. Exception is thrown if the query does not return exactly one object.'
In your example, if the user is not registered, they won't be in the database, so 0 results will be returned. Hence the error Incorrect Resultsize Expected 1 Actual 0.
Try using the QueryWithRowMapper method, as it is (again, per the documentation) one of the methods for Mapping result sets to objects:
return (CandidateSession)template.QueryWithRowMapper(CommandType.StoredProcedure, "spGetCandidateSession", candidateMapper, parameters);
If the cast to CandidateSession does not fail, I would expect a null object to be returned.
Again, I've never worked in Spring.NET, so this is based on a fairly cursory reading of the documentation. Hopefully it will at least get you going down the right path.

can storing data in a database sometimes lead to corrupted data? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have a field that's stored in the database as a string. It's actually a comma-separated string of numbers that I convert to a list of longs. The lines of code that do the conversion look somewhat like this:
TheListOfLongs = (from string s in StringFromDB.Split(',')
select Convert.ToInt64(s)).ToList<long>();
The code that creates the database storage string looks like this:
return String.Join(",", TheListOfLongs.Select(x=> x.ToString()).ToArray());
This works fine but as you can see, if for some reason there's a problem with the string, the code in the first line of code breaks on Convert.ToInt64(s).
Now I know I can wrap all this around a try statement but my question is this: can storing and retrieving a string in the database corrupt the string (in which case I definitely need the try statement) or is this a one a trillion odd type of event?
I wouldn't worry about corrupt data per se. However, you definitely need to handle the more general case where you can't parse what should be numeric data.
Even in the most controlled situations it is good programming practice to provide conditions for when you can't process data as you're expecting to be able to. What that means to your application is something you'll need to decide. Wrapping the statement with a try..catch will prevent your application from choking, but may not be appropriate if the parsed list is critical later on.
Selecting from the DB shouldn't corrupt your string.
If the connection is dropped mid transfer or something like that then an exception is thrown.

C# why throw errors [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Im not getting the throw keyword, why use it? What are the benefits of it?
As of now I've got this in my UI class:
try
{
Classreference.MethodToRun();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
This works but I guess with throw I could make the method I am calling throw the error instead and catch it in my UI class? But why? What is better about it? Is it done to make the classes more object oriented or what? I am guessing if I just catch the error in my UI class I wont need to change the code if I change the method I am calling, but instead change the error message in the method being changed?
You use throw to indicate that an error has occured or to pass an existing error on to a higher level.
You use catch when you want to handle the error (Exception).
Throwing the exception is an improvement over the older procedural way of handling errors where you would return error codes.
The reason it is better is because you can write your logic for the simple success case, and when things go wrong you simply throw an exception, no error handling in your lower level code. It is then up to the higher levels of the application to decide what to do when a particular exception is throw.
asawyer is right, you need to google and read up on error handling, it is a wide subject and you only really 'get it' after practice, talking, and reading about it. throw is something you probably won't need to use overly often, but you can occasionally use it to stop unwanted behaviour and create clearer errors for programmers using your methods. I know it is quite contrived but take this example:
public string WriteToFile(FileStream fs) {
if (fs == null) {
throw new ApplicationException("you passed a null filestream");
}
// write to file
}
You could just attempt to write the FileStream to a file without validating it, but in doing so you create a more understandable error for anyone consuming your method.
You can use the throw keyword to throw an exception to the higher method.
Using this way, you can ocassionally make a better use of the exception, like closing database-access or something like that.
What you are doing here is effectively masking a lot of information that you could get from the exception.
what you regularly want to do is catch the exception, log the relevant information to some place where you can review it (logfile, db, eventlog) and then either throw(), which will keep you stack trace intact, or throw another "user friendly" exception which is masking the technical implementation.

print keyword for C# ...why not? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 12 years ago.
My reasons for the idea/proposal are following:
1) Console.WriteXX() is possibly used more often than many keywords in C#
2) The Console as an I/O device is not going away anytime soon.
3) I cannot think of any general purpose programming language which doesn't provide the "write to console" facility in one form or another.
4) aesthetics (i.e. clean, simple, short , direct )
5) print "Hello" ; doesn't make me think that I am typing more than whats needed. Every time I have to write Console.WritXX() ... or even read it in code , its a chore.
6) Its closer to the C/C++ family values and tradition of providing special status to the basic text based I/O
7) Its hard to conceive of a future scenario when the decision to make "print" a keyword will be regretted.
8) print as in { print "hello"; } instead of print as in { print("hello");} is unlikely to break any existing code.
Because C# isn't only is generally not used in a console. Wether it's ASP.NET, WinForms or WPF, there are many uses for the langage where "printing" does not make any sense.
In C# we have a lot of ways to output the data. It's very confusing if you change Console.Write to print, because programmers may ask "print to what? to the screen? to the printer?". While using Console.Write is quite clear, we know it's writing data to the Console. And also FileStream.Write make us know that it's writing to a file. A MemoryStream.Write is writing to the memory... It's so nice, isn't it? So why do we need a confusing print?
Why not create an alias for System.out.WriteLine() to save your wrist?
using c = System.Console;
c.WriteLine("Hello World");
Or use a code snippet in your IDE?
Console.WriteLine is a .NET Framework method, so all .NET languages use it consistently. Why add additional keywords to c# which is only one of many .NET languages?
Print is too generic to describe what is really going on, and it only really applies to the console itself. There are several different methods for outputting information to various interfaces, and WriteXX (as you put it) is more descriptive of what is actually occurring. You're not printing anything, you're writing it to the interface. C# was made to be more descriptive of what is going on, not to latch onto holdovers of other languages.

Categories