I changed the code from this
public override IDataReader getData(int pageId, string pageName)
{
try
{
return ((IDataReader)(SqlHelper.ExecuteReader(ConnectionStringConnectorPool, GetFullyQualifiedName("PageModuleGetAll"),pageId, pageName)));
}
catch (Exception ex)
{
ExceptionController.WriteExceptionToLog(string.Format("SqlDataProvider.cs/GetPageByIdAndName: pageId:{0}, pageName{1}", pageId, pageName), -2, ex);
return null;
}
}
To this
public override IDataReader getData(string sqlMethod, int pageId, string pageName)
{
try
{
return ((IDataReader)(SqlHelper.ExecuteReader(ConnectionStringConnectorPool, GetFullyQualifiedName(sqlMethod),pageId, pageName)));
}
catch (Exception ex)
{
ExceptionController.WriteExceptionToLog(string.Format("SqlDataProvider.cs/GetPageByIdAndName: pageId:{0}, pageName{1}", pageId, pageName), -2, ex);
return null;
}
}
Im calling the method like this
public List<PageModuleInfo> GetAllPageModules(int pageId, string paneName)
{
try
{
return Common.Utilities.CBO.FillCollection<PageModuleInfo>(BLL.Data.DataProvider.Instance().getData("PageModuleGetAll", pageId, paneName));
}
catch (Exception ex)
{
ExceptionController.WriteExceptionToLog(new Exception("PageModuleController.cs/GetAllPageModules:" + System.Environment.NewLine + ex));
return null;
}
}
And now im getting Parameter count does not match Parameter Value count error and im wondering why.
The error indicates that you are using a stored procedure, and have supplied more parameter values than there are parameters declared on the stored procedure.
So: check each of the 3 stored procedures, and double-check how many parameters each takes. If one of them does not take at least 2, that is the problem. In particular, also check for different versions of the same stored procedure; for example, there could be dbo.PageModuleGetAll and johndev.PageModuleGetAll - where johndev.PageModuleGetAll is the updated version with 2 parameters. But if your application is running in with different identity (integrated security, a dedicated sql account, etc) - then it will still be running dbo.PageModuleGetAll
Your method is an override of a base class method, so it's likely that the derived classes function signature does not match the base classes signature.
That would give you a 'Parameter Value count error' because the base classes number of parameters is less than the derived class.
Related
I am trying to generate a try catch method in a class, But I am facing this error message, Please help me to solve this.
My class is
public string Countryadd(string country, string id)
{
try
{
string data="0";
string qry1 = "select Country from Country where Country='" + country + "'";//Checking weather txtcountry(Country Name) value is already exixst or not. If exist return 1 and not exists go to else condition
SqlDataReader dr = conn.query(qry1);
if (dr.Read())
{
return data = "1";
}
else//If Country Name Not Exists
{
string qry = "insert into Country values('" + id + "','" + country + "')";//Insertin data into database Table Country
conn.nonquery(qry);
}
}
catch (Exception Ex)
{
ShowPopUpMsg(Ex.Message);
}
return data;
}
You need to put the definition of data before the try block:
string data="0";
try {
The {} brackets define the scope of a variable.
You can only access a variable within that scope.
Since you define your data variable in try block, it doesn't seems outside of this blocks. It is only available in try block and any child scope.
You can move it's definition outside of your try-catch block.
string data="0";
try
{
...
}
catch (Exception Ex)
{
ShowPopUpMsg(Ex.Message);
}
return data;
Read: 3.7 Scopes (C#) from MSDN
All variables created between the { } symbols are inside the scope of the symbols themselves.
If you need to use data outside of it, declare it before the try.
string data = string.Empty; // or initialize the value to "0" if that's the default you want.
try
{
// Don't declare data here or it won't be visible outside the try block.
// You can set the "0" or whatever value you want here though.
...
}
catch (Exception Ex)
{
...
}
return data;
data is currently defined within the scope of the try block, you need to move it outside
string data = "0";
try
{
...
}
catch(NullReferenceException ex)
{
}
catch(SomethingRelatedToDataReaderException ex)
{
}
return data;
Also, you shouldn't really try to catch Exception, you should try to catch the specific types of exceptions. This helps to avoid covering up issues as well as giving you more control
The scoping of your variable data is only inside the Try/Catch block because you defined in it.
Try to define the variable data outsiude the block.
How do I check to see if the ObjectResult<> has a value or not? Right now it's returning values but will it throw an exception is there is nothing to return?
This is the section of code that I need to check so I do not have to depend on a try catch block
iProjInfo.ProjectLeafs = db.proc_GetProjectLeafs(projectID).ToList<IProjectLeafs>();
public static Task<IProjectInfo> GetProjectInfo(int projectID)
{
return Task.Run(() =>
{
using (var db = new StorefrontSystemEntities())
{
IProjectInfo iProjInfo = db.proc_GetProject_ForDrawings(projectID).Single<IProjectInfo>();
try
{
iProjInfo.ProjectLeafs = db.proc_GetProjectLeafs(projectID).ToList<IProjectLeafs>();
}
catch (Exception ex)
{
}
return iProjInfo;
};
});
}
As long as the stored procedure is getting executed and returning a result set; even if it is empty (no records returned by the stored procedure), you can be sure of an empty list being returned.
I would like to know which is the best way to make a Exception treatment, because inside my Try statement, I have a lot of validations, and if I get some Exception there, my Catch statement can tell me what happens, but how could I know in which field occurs the Exception ?
Sample Code
try
{
// If I get a Exception when converting to number,
// I will understand the error
// but how could I know where in my `Try` statement was the error ?
int valor = Convert.ToInt32(xmlnode[i].ChildNodes.Item(2).InnerText.Trim());
// A Lot of another validations here
}
Catch(Exception e)
{
this.LogInformation(e.Message);
}
Best practises would be not to use Try-Catch at all when you convert strings to numbers. Therefore you should use the TryParse methods like int.TryParse.
// note that here is also a possible error-source
string valorToken = xmlnode[i].ChildNodes.Item(2).InnerText.Trim();
int valor;
if(!int.TryParse(valorToken, out valor))
{
// log this
}
// else valor was parsed correctly
Apart from that, if you want to provide exact error messages you have to use multiple try-catch or handle different exception types (the most general Exception type must be the last).
Don't use Convert.ToInt32 if you're unsure of the value. Use Int32.TryParse instead:
int valor;
if (Int32.TryParse(xmlnode[i].ChildNodes.Item(2).InnerText.Trim(), out valor))
{
// Worked! valor contains value
}
else
{
// Not a valid Int32
}
In addition you should not be using Exceptions to catch validation errors. Your validation code should calculate if the value is correct, rather than failing when it isn't. A validation class should expect to receive both valid and invalid data as input. Because you expect invalid input you should not be catching exceptions when it's invalid.
Come up with a test that checks if the data is valid and return true or false. Pretty much all numeric types have a TryParse method like the above. For your custom rules for other validation methods come up with a specification that defines exactly what valid and invalid input is and then write a method to implement that specification.
Move try..catch inside loop. Thus you will know which item exactly caused exception
foreach(var xmlNode in nodes)
{
try
{
//
int valor = Convert.ToInt32(xmlNode.ChildNodes.Item(2).InnerText.Trim());
// A Lot of another validations here
}
catch(Exception e)
{
LogInformation(e.Message); // current item is xmlNode
return;
}
}
If there is even the remotest possibility that the value you're tring to parse will not be parsable, it is therefore not an exceptional circumstance, vis. should not be treated as an exception.
In this case, there is TryParse, which allows you to determine that the value is not valid for parsing:
int valor;
if(int.TryParse(xmlnode[i].ChildNodes.Item(2).InnerText.Trim(), out valor))
{
// "valor" is sucessfully parsed
}
else
{
// invalid parse - do something with that knowledge
}
Unless its different Exceptions that get created (i.e. different classes) then you will need to handle this with different try catches.
Typically you can do:
try
{
// If I get a Exception when converting to number,
// I will understand the error
// but how could I know where in my `Try` statement was the error ?
int valor = Convert.ToInt32(xmlnode[i].ChildNodes.Item(2).InnerText.Trim());
// A Lot of another validations here
}
Catch(IOException ioe) {
// Handle, log
}
Catch(ArgumentNullException ane) {
// Handle, log
}
Catch(Exception e)
{
// Handle, log and potentially rethrow
}
You could also have individual try catches (which is kind of what most people would do I think) or nested try catches in your try block:
Like
// First block
try {
// Convert here once
} catch (Exception ex) {
// Handle and log
}
// Second block
try {
// Convert here once
} catch (Exception ex) {
// Handle and log
}
Not sure if that helps at all.
try
{
}
catch (Exception ex)
{
var stackTrace = new StackTrace(ex, true);
var frame = stackTrace.GetFrame(0);
var line = frame.GetFileLineNumber();
var method = frame.GetMethod();
}
I am trying to create a method in which I can exequte mysql UPDATE, DELETE or INSERT query. The method must work when with an INSERT I ask or do not ask the last_insert_id(). Below is the code that I have at the moment:
public int executeUID(MySqlCommand msCommand)
{
try
{
this.Open();
msCommand.Connection = this.msCon;
return int.Parse(msCommand.ExecuteScalar().ToString());
}
catch (MySqlException ex)
{
throw ex;
}
finally
{
this.Close();
}
}
The problem with this is is that when I use an insert query that returns a last_insert_id() the method works greatly. But when the query doesn't return an last_insert_id() the method malfunctions. How can I get this method to work?
why not u use OUTPUT parametres, it will return the last inserted id. SqlParamet
and if you know when LastInsertID can generate, then you can pass one more parameter to method, to tell that it is retriving insertedID, based on that parameter you can do some thing like this .
public int executeUID(MySqlCommand msCommand, bool Mode) //Mode==true means insertandRetriveLastID, false means =dont retrive last insertedit
{
try
{
this.Open();
msCommand.Connection = this.msCon;
if(Mode) //for getting last inserted id
{
SqlParameter outParams= new SqlParameter("#ID", SqlDbType.Int);
outParams.Direction = ParameterDirection.Output;
msCommand.Parameters.Add(outParams)
msCommand.ExecuteNonQuery();
var outputValue = cmd.Parameters["#ID"].Value;
}
else //if no inserted id is not there
{
return msComand.ExecuteNonQuery(); // it will return No of Rows Affected.
}
}
catch (MySqlException ex)
{
throw ex;
}
finally
{
this.Close();
}
}
PS : you need to tune it some more for better efficiency, as i gave some basic ideas how we can do it with out parameter
I have been writing .NET applications and have been impressed with the error handling included in the framework.
When catching an error that has been throw by the processes or somewhere in the code I like to include the message (ex.Message, which is usually pretty general) but also the stacktrace (ex.stacktrace) which helps to trace the problem back to a specific spot.
For a simple example let's say for instance that we are recording numbers to a log in a method:
public void ExampleMethod(int number){
try{
int num = number
...open connection to file
...write number to file
}
catch(Exception ex){
.... deal with exception (ex.message,ex.stacktrace etc...)
}
finally{
...close file connection
}
}
Is there any way to see the method called (in this case ExampleMethod) with the specific number that was passed that potentially crashed the method call? I believe you could log this perhaps in the catch block but I am interested essentially in catching the method call and parameters that caused the system to throw the exception.
Any ideas?
I suggest stuffing the parameter values into the exception's Data dictionary, e.g.
public void ExampleMethod(int number) {
try {
int num = number
...open connection to file
...write number to file
}
catch(Exception ex) {
ex.Data["number"] = number;
//.... deal with exception (ex.message,ex.stacktrace etc...)
}
finally {
//...close file connection
}
Another advantage of this method is that you can stuff the parameters in the catch block, then re-throw the exception and log it somewhere else without losing the stack trace, e.g.
catch(Exception ex) {
ex.Data["number"] = number;
throw;
}
If you want to know the value of the parameters in your method, then there is only one way, IMO, to do it - you need to repackage the exception with data.
For example:
int param1 = 10;
string param2 = "Hello World";
try
{
SomeMethod(param1, param2)
}
catch(SomeExpectedException e)
{
throw new MyParameterSensitiveException(e, param1, param2);
}
You basically repackage the original exception as the inner exception of another exception, and additionally supply the parameters you used to call the method. Then you could inspect that in some way to figure out what went wrong.
The accepted answer and many of the solutions described will work fine but what you're doing is littering your source with a slightly different blob of code depending on what parameters are in your method signature.
When it comes time to add a new parameter you need to remember to update your handler to add that new parameter. Or if you remove a parameter then you need to remember to remove the parameter from your exception handler.
What if you have a two or more try..catch blocks? Then you now have two blocks of code to keep up to date. Definitely not refactor friendly.
Another approach is to remove the logging code use a technique called Aspect Oriented Programming.
One such tool to facilitate this is a product called PostSharp.
With PostSharp you can write a logger than is invoked whenever an exception is thrown without the need for messy method and parameter specific code. For example (using version 1.5 of PostSharp):
LoggerAttribute.cs -
[Serializable]
public class LoggerAttribute : OnExceptionAspect
{
public override void OnException(MethodExecutionEventArgs eventArgs)
{
Console.WriteLine(eventArgs.Method.DeclaringType.Name);
Console.WriteLine(eventArgs.Method.Name);
Console.WriteLine(eventArgs.Exception.StackTrace);
ParameterInfo[] parameterInfos = eventArgs.Method.GetParameters();
object[] paramValues = eventArgs.GetReadOnlyArgumentArray();
for (int i = 0; i < parameterInfos.Length; i++)
{
Console.WriteLine(parameterInfos[i].Name + "=" + paramValues[i]);
}
eventArgs.FlowBehavior = FlowBehavior.Default;
}
}
You then decorate your classes with the LoggerAttribute:
[Logger]
public class MyClass
{
public void MyMethod(int x, string name)
{
// Something that throws an exception
}
}
Anything that throws an exception in MyMethod will cause the OnException method to be executed.
There are two versions of PostSharp. Version 1.5 is free and open sourced under the GPL and is targeted at .NET 2.0. PostSharp 2.0 is not entirely free but its community edition will support the basic functionality described above.
In order to do this:
public void MyProblematicMethod(int id, string name)
{
try
{
object o = null;
int hash = o.GetHashCode(); // throws NullReferenceException
}
catch (Exception ex)
{
string errorMessage = SummarizeMethodCall(MethodBase.GetCurrentMethod(), id, name);
// TODO: do something with errorMessage
}
}
...and get this:
"MyProblematicMethod invoked: id = 1, name = Charlie"
...you could do something like this:
public static string SummarizeMethodCall(MethodBase method, params object[] values)
{
var output = new StringBuilder(method.Name + " invoked: ");
ParameterInfo[] parameters = method.GetParameters();
for (int i = 0; i < parameters.Length; i++)
{
output.AppendFormat("{0} = {1}",
parameters[i].Name,
i >= values.Length ? "<empty>" : values[i]
);
if (i < parameters.Length - 1)
output.Append(", ");
}
return output.ToString();
}
You could make a class that inherits Exception and add some arguments to it so you could pass the number to it.
You can get the method name and the parameters like this,
try
{
int a = 0;
int i = 1 / a;
}
catch (Exception exception)
{
StackTrace s = new StackTrace(exception);
StackFrame stackFrame = s.GetFrame(s.FrameCount - 1);
if (stackFrame != null)
{
StringBuilder stackBuilder = new StringBuilder();
MethodBase method = stackFrame.GetMethod();
stackBuilder.AppendFormat("Method Name = {0}{1}Parameters:{1}", method.Name, Environment.NewLine);
foreach (ParameterInfo parameter in method.GetParameters())
{
stackBuilder.AppendFormat("{0} {1}", parameter.ParameterType.FullName, parameter.Name);
stackBuilder.AppendLine();
}
// or use this to get the value
//stackBuilder.AppendLine("param1 = " + param1);
//stackBuilder.AppendLine("param2 = " + param2);
}
}
I am not sure whether you can get the parameter values directly off the stack like a debugger.
The Automatic Exception Handling from Crypto Obfuscator can do what you need.
The exception reports include all pertinent information including full stack trace info along with the values of all method arguments and local variables, plus the system information, the time of the exception, the build number, and optional developer defined custom data like log files, screenshots, etc.
DISCLAIMER: I work for LogicNP Software, the developer of Crypto Obfuscator.