How to get the method name and line number in Exception in ASP Core 5 - asp.net-core

I want to get the method name and line number when an error occur, I am using Core 5.
try
{
//My code
}
catch (Exception ex)
{
_logger.LogError(ex, "Method Name / Line Number");
}
Update:
I found a Solution like this:
_logger.LogError(ex, "\n=> ex Error: " + ex + "\n=> Action Name: " + ex.TargetSite.ReflectedType.Name + "\n=> Error Message: " + ex.Message + "\n=> Line Number: " + ex.LineNumber());

A simple call to ToString() on exception will give you the complete information needed. For example when we run the following code:
public static void Main()
{
try
{
//my code
throw new ArgumentException();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
The output would be somewhat like:
System.ArgumentException: Value does not fall within the expected range.
at ConsoleApp.Program.Main() in C:\Users\USER\source\Playground\ConsoleApp1\Program.cs:line 20
where Main() is the method name and 20 is the line number.
To get the format as required in question we can write a wrapper around the exception and fetch the line number from it:
using System;
using System.Reflection;
namespace ConsoleApp
{
class Program
{
public static void Main()
{
try
{
//my code
throw new ArgumentException();
}
catch (Exception ex)
{
Console.WriteLine(MethodBase.GetCurrentMethod().Name + "/" + GetLineNumber(ex));
}
}
public static int GetLineNumber(Exception ex)
{
var lineNumber = 0;
const string lineSearch = ":line ";
var index = ex.StackTrace.LastIndexOf(lineSearch);
if (index != -1)
{
var lineNumberText = ex.StackTrace.Substring(index + lineSearch.Length);
if (int.TryParse(lineNumberText, out lineNumber))
{
}
}
return lineNumber;
}
}
}
Note: In the extract line method, we are fetching the top most exception. This comes in handy when we have a chain of exceptions in our stack trace.

Related

What exception type does C++ see when a C# class marked ComVisible throws an exception?

I have a C# class marked ComVisible that has a function that writes to a file. If the folder the file is supposed to be written to does not exist, it throws a System.IO.DirectoryNotFoundException. If I use throw; to raise it back to the C++ client, it doesn't get caught by any handler I know of except a generic (...) one. What is the type of the exception object that the handler will get?
Here is the client method:
void CRXReport::Export(CCOMString Destination)
{
CWaitCursor Wait;
// m_Report->Export("c:/misc/report2.pdf");
CCOMString message;
message << _T("Trying to export a report to ") << Destination;
AfxMessageBox(message);
if ( m_Report != NULL )
{
try
{
m_Report->Export(Destination.AllocSysString());
}
catch (CException& ex)
{
AfxMessageBox(_T("Failed to export the report; caught a CException reference."));
}
catch (CException* pEx)
{
AfxMessageBox(_T("Failed to export the report; caught a CException pointer."));
}
catch (_com_error* e)
{
AfxMessageBox(_T("Failed to export the report; caught a _com_error reference."));
}
catch (...)
{
AfxMessageBox(_T("Failed to export the report; caught something else."));
}
}
}
And, although I don't think it matters, here's the server method:
public void Export(string destination)
{
LogOnToTables();
try
{
_report.ExportToDisk(ExportFormatType.PortableDocFormat, destination);
}
catch (Exception ex)
{
MessageBox.Show("Failed to export report: " + ex.Message);
throw;
}
}
The first comment contains the answer. I needed to catch a _com_error reference, not a pointer.

data provider mismatch error

I am using below code for data provider but it's not working. Please help to me how to resolve data provider mismatch issue. here mentioned complete details about all the methods reading xls , test , data provider .
#DataProvider
public Object[][] getgbTestData(){
Object data[][] = testutil.getTestData(sheetName);
return data;
}
#Test(dataProvider="getgbTestData")
public void addnewuser(String fname,String lname,String email,String pass,String conpass) throws IOException{
newuser.newregistration1(fname, lname, email, pass, conpass);
}
**method:**
public Personaldetails newregistration1(String fsname,String lsname,String email1,String pass1,String conpass1) throws IOException {
Account.click();
Registerlink.click();
Firstname.sendKeys(fsname);
Lastname.sendKeys(lsname);
useremail.sendKeys(email1);
password.sendKeys(pass1);
confirmpassword.sendKeys(conpass1);
submit.click();
//return person;
return new Personaldetails();
}
//using below method to read data from excel
public static Object[][] getTestData(String sheetName) {
FileInputStream file = null;
try {
file = new FileInputStream(TESTDATA_SHEET_PATH);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
book = WorkbookFactory.create(file);
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
sheet = book.getSheet(sheetName);
Object[][] data = new Object[sheet.getLastRowNum()][sheet.getRow(0).getLastCellNum()];
// System.out.println(sheet.getLastRowNum() + "--------" +
// sheet.getRow(0).getLastCellNum());
for (int i = 0; i < sheet.getLastRowNum(); i++) {
for (int k = 0; k < sheet.getRow(0).getLastCellNum(); k++) {
data[i][k] = sheet.getRow(i + 1).getCell(k).toString();
// System.out.println(data[i][k]);
}
}
return data;
}
Looks like the test has required 5 arguments but your data provider method getTestData passing less/greater no of arguments.
You are passing the wrong number of arguments. The method addnewuser() expects 5 arguments, but receives only one. You can see it in the last line in the error message
Arguments: [(java.lang.String)fname]
If you want to pass different number of parameters you can use String[] instead of single arguments. And if you expect 5 arguments each time check what data holds in getTestData()

NullReferenceException was unhandledby user code

I am making a registration page and while using an input tag to upload image of the user, it is giving an error while running the website: "NullReferenceException was unhandledby user code". Please help me to sort this out. The method which is giving error is:
protected void Button2_Click(object sender, EventArgs e)
{
var path = "Memberimg";
string fn = System.IO.Path.GetFileName(f1.PostedFile.FileName);
string SaveLocation = Server.MapPath("Memberimg") + "\\" + fn;
if ((f1.PostedFile != null) && (f1.PostedFile.ContentLength > 0))
{
try
{
f1.PostedFile.SaveAs(SaveLocation);
Response.Write("The file has been uploaded.");
}
catch (Exception ex)
{
Response.Write("Error: " + ex.Message);
}
}
else
{
Response.Write("Please select a file to upload.");
}
}
You are referring to f1.PostedFile before checking to see if it is null, in the line with:
string fn = System.IO.Path.GetFileName(f1.PostedFile.FileName);

why pwcb.getPassword is null in this code

I try to add the rampart security to my axis2 web service using rampart module.
So here is what I have made:
I have stored in a database the hashed value of "bobWWW" password and the salt
In my PWCBHandler.java class
•I select the stored in the database password and hash
•I try to hash with same algorithm pwcb.getPassword() with the same stored salt
•check if this new hashed password is equal to the stored password
But I constantly was receiving nullpointerexception so I decide to check and wrote this code
if(pwcb.getPassword()==null)
{
try {
throw new Exception ("passwordget pass null" +pwcb.getPassword());
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And I see that pwcb.getPassword() is empty. So here is the code of PWCBHandler.java
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException
{
for (int i = 0; i < callbacks.length; i++)
{
WSPasswordCallback pwcb = (WSPasswordCallback)callbacks[i];
try {
pasandsalt = getdataforChecking();
if(pwcb.getPassword()==null)
{
try {
throw new Exception ("passwordget pass null" +pwcb.getPassword());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
passwordforchecking = hash(pwcb.getPassword(),Base64.decodeBase64(pasandsalt[1]));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if((pwcb.getIdentifier().equals("bob")) && (passwordforchecking.equals(pasandsalt[0])) )
{
return;
}
}
And here is my soaprequest with the sequeiry header
var sr =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soapenv:Envelope " +
"xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" " +
"xmlns:nilo=\"http://nilo\">"+
"<soapenv:Header>"+
'<wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\" soapenv:mustUnderstand="1">'+
'<wsse:UsernameToken xmlns:wsu="http://docs.oasisopen.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="123">'+
'<wsse:Username>bob</wsse:Username>'+
'<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">bobWWW</wsse:Password>'+
'</wsse:UsernameToken>'+
'</wsse:Security>'+
"</soapenv:Header>"+
"<soapenv:Body>" +
"<nilo:getdataForChecking>" +
'<nilo:data>'+tranXml+'</nilo:data>' +
' </nilo:getdataForChecking>'+
'</soapenv:Body>' +
'</soapenv:Envelope>';
According to your soap headers i can see you are using a Plain text password instead of Password Digest. You might need to change the rampart configuration
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">bobWWW</wsse:Password>
this might be helpful to you. http://wso2.com/library/240/

How do I force a method in Groovy to throw an exception

I wanted to write a test for a method in Groovy that throws an IOException. The only way for me to simulate this in the test is to force the method to throw this exception
This is what the original code looks like:
public void cleanUpBermudaFiles(RequestMessage requestMessage)
{
final File sourceDirectory = new File(preferenceService.getPreference("bermuda.landingstrip") + File.separator + requestMessage.getWorkflowId().getValue());
if(sourceDirectory!=null && sourceDirectory.exists())
{
deleteDirectory(sourceDirectory);
}
else
{
LOG.error("Directory must exist in order to delete");
}
}
private void deleteDirectory(File directoryToDelete)
{
try {
FileUtils.deleteDirectory(directoryToDelete);
} catch (Exception e) {
LOG.error("Failed to delete Bermuda files directory located at:" + directoryToDelete.getPath() + "with an exception" + e.getMessage());
}
}
MY TEST: (I'm looking for a way to make deleteDirectory throw IOException)
public void testCleanUpBermudaFailure()
{
workflowId = new WorkflowId("123456")
workflowDirectory = new File(srcDirectory, workflowId.value)
workflowDirectory.mkdir()
File.createTempFile('foo','.lst', workflowDirectory)
def exception = {throw new IOException()}
expect(mockRequestMessage.getWorkflowId()).andReturn(workflowId)
expect(mockPreferenceService.getPreference("bermuda.landingstrip")).andReturn(srcDirectory.path)
replay(mockPreferenceService, mockRequestMessage)
fileCleanUpService.preferenceService = mockPreferenceService
fileCleanUpService.metaClass.deleteDirectory = exception
fileCleanUpService.cleanUpBermudaFiles(mockRequestMessage)
verify(mockPreferenceService, mockRequestMessage)
assert srcDirectory.listFiles().length == 0, 'CleanUp failed'
}
If the service class is a Groovy class, you would want to mock FileUtils like:
FileUtils.metaClass.static.deleteDirectory = { File f -> throw new IOException() }
However, as ataylor pointed out, you cannot intercept calls if it's a Java class. You can find a nice blog post about it here.
You are mocking a no-arg call to deleteDirectory, but the real deleteDirectory takes one argument of type File. Try this:
def exception = { File directoryToDelete -> throw new IOException() }
...
fileCleanUpService.metaClass.deleteDirectory = exception