Windows Service not trapping error from DLL - dll

I have a Windows Service that runs every 10 minutes. Whenever there is an error on the DLL, the service isn't throwing an error. How do I make it so the error propagates back to the Windows Service and have it generate an Event Viewer message, or even start the polling again?
catch (Exception ex)
{
var errorMessage = ex.Message;
if (ex.InnerException != null)
errorMessage += " " + ex.InnerException.Message;
eventLog1.WriteEntry(errorMessage, EventLogEntryType.Error);
new Logging().LogMessageToFile(errorMessage, true);
}

Problem solved! Throw it again AFTER catching it.
catch (Exception ex)
{
var errorMessage = ex.Message;
if (ex.InnerException != null)
errorMessage += " " + ex.InnerException.Message;
eventLog1.WriteEntry(errorMessage, EventLogEntryType.Error);
new Logging().LogMessageToFile(errorMessage, true);
throw;
}

Related

How to get the method name and line number in Exception in ASP Core 5

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.

Adding screenshot in extent report 4 for the failed scenarios

I'm using extent report 4.Actually I'm trying to add Screenshot in extent report when the test fails. I'm using below code to achieve this. Screenshot gets attached in the end of my report (please refer the screenshot), but I want screenshot to get attached in the appropriate step i.e. when the test cases fail. Please help me with solutions or workaround
case FAIL:
String path = WrapperMethods.captureScreenshot();
try
{
test.log(logStatus, message + test.addScreenCaptureFromPath(path));
} catch (IOException e)
{
e.printStackTrace();
}
break;
for version 4 you can work as below
if (result.getStatus() == ITestResult.FAILURE) {
test.fail(MarkupHelper.createLabel(result.getName() + "Test Failed", ExtentColor.RED));
test.fail(result.getThrowable());
String screencastPath = null;
try {
screencastPath = Screeshot.captureScreenshot(WebDriverManager.driver);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
test.fail("<b><font color=blue>" + "Screenshot Name: " + Screeshot.sendScreenName() + "</font></b>");
test.fail("<b><font color=red>"
+ " Click the below link OR check the report folder by above screenshot Name to get the Screenshot of failure "
+ "</font></b>", MediaEntityBuilder.createScreenCaptureFromPath(screencastPath).build());
} catch (IOException e) {
test.fail("Test Failed, Cannot attach screeshot");
}
WebDriverManager.driver.close();
}

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/

The request was aborted: Could not create SSL/TLS secure channel in Windows 8 Metro App

I have a list of 350 downloadable image urls. I download 10 images parallely at one shot by running multiple tasks. But after downloading N number of images suddenly my code throws the following exception.
Exception: "An error occurred while sending the request."
InnerException: "The request was aborted: Could not create SSL/TLS
secure channel."
StackTrace: "at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task)\r\n at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task)\r\n at
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n ...
I have created a sample project to reproduce this exception. I have 2 test-cases in my hand. You can download the running test project from My Sky Drive Here. Right click on the file HTTPClientTestCases1and2.zip and download.
Case 1: Using a single instance HttpClient for all image Download.
In this case I'm sending parallel request to 10 urls using same HttpClient. In this case download is successful for most of the time. After last successful download of an image wait for minimum 40 seconds (Max 1 minute 40 seconds) to send the next parallel download request for the next batch. One image will definitely fail due to this exception. But so many places its written and suggested to use single HttpClient for multiple request.
public async void DownloadUsingSingleSharedHttpClient(Int32 imageIndex)
{
Uri url = new Uri(ImageURLs[imageIndex]);
UnderDownloadCount++;
try
{
Byte[] contentBytes = null;
try
{
// Exception IS THROWN AT LINE BELOW
HttpResponseMessage response = await _httpClient.GetAsync(url);
contentBytes = await response.Content.ReadAsByteArrayAsync();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Download Failed at GetAsync() :" + ex.Message);
throw ex;
}
DownloadedCount++;
if (OnSuccess != null)
OnSuccess(this, new DownloadSuccessEventArgs() { Index = imageIndex, Data = contentBytes });
}
catch (HttpRequestException hre)
{
DownloadFailedCount++;
if (OnFailed != null)
OnFailed(hre, null);
}
catch (TaskCanceledException hre)
{
DownloadFailedCount++;
if (OnFailed != null)
OnFailed(hre, null);
}
catch (Exception e)
{
DownloadFailedCount++;
if (OnFailed != null)
OnFailed(e, null);
}
}
Case 2: Creating new instance of HttpClient for every image Download
In this case it just fails very frequently due to same exception while downloading images parallely.
public async void DownloadUsingCreatingHttpClientEveryTime(Int32 imageIndex)
{
Uri url = new Uri(ImageURLs[imageIndex]);
UnderDownloadCount++;
try
{
Byte[] contentBytes = null;
using (HttpClientHandler _handler = new HttpClientHandler())
{
_handler.AllowAutoRedirect = true;
_handler.MaxAutomaticRedirections = 4;
using (HttpClient httpClient = new HttpClient(_handler))
{
httpClient.DefaultRequestHeaders.ExpectContinue = false;
httpClient.DefaultRequestHeaders.Add("Keep-Alive", "false");
try
{
// Exception IS THROWN AT LINE BELOW
contentBytes = await httpClient.GetByteArrayAsync(url.OriginalString);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Download Failed :" + ex.Message);
throw ex;
}
}
_handler.Dispose();
}
DownloadedCount++;
if (OnSuccess != null)
OnSuccess(this, new DownloadSuccessEventArgs() { Index = imageIndex, Data = contentBytes });
}
catch (HttpRequestException hre)
{
DownloadFailedCount++;
if (OnFailed != null)
OnFailed(hre, null);
}
catch (TaskCanceledException hre)
{
DownloadFailedCount++;
if (OnFailed != null)
OnFailed(hre, null);
}
catch (Exception e)
{
DownloadFailedCount++;
if (OnFailed != null)
OnFailed(e, null);
}
}
Please edit the following function in MainPage.xaml.cs to check two cases
private void Send10DownloadRequestParallel()
{
for (Int32 index = 0; index < 10; index++)
{
Task.Run(() =>
{
Int32 index1 = rand.Next(0, myImageDownloader.ImageURLs.Count - 1);
UpdateDownloadProgress();
// Case 1: Download Using Single Shared HttpClient
// myImageDownloader.DownloadUsingSingleSharedHttpClient(index1);
// OR
// Case 2: Download Using Creating Http Client Every Time
myImageDownloader.DownloadUsingCreatingHttpClientEveryTime(index1);
});
}
}
My Question: What I'm doing wrong? What is the best way of implementing parallel downloader in WinRT by overcoming this exception.
I ran your sample application and am only get errors in a couple of scenarios:
When the image that your app is requesting does not exist, the .NET HTTP client throws an exception. Your handler doesn't quite handle this case, as the inner exception is NULL. I had to tweak that code just a little:
async void myImageDownloader_OnFailed(object sender, EventArgs e)
{
await App.CurrentDispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, delegate
{
TimeSpan time =(DateTime.Now -dateTimeSuccess);
String timeGap = "Ideal For:" + time.ToString() + "\n";
ErrorListBox.Text += "\n Failed When: " + DownloadInfo.Text + "\n";
ErrorListBox.Text += timeGap;
// CX - added null check for InnerException, as these are NULL on HTTP result status 404
var ex = sender as Exception;
if (ex.InnerException != null)
ErrorListBox.Text += ex.InnerException.Message;
else
ErrorListBox.Text += "Inner Exception null - Outer = (" + ex.ToString() + ")";
});
}
The only time I got your other error Could not create SSL/TLS secure channel in Windows 8 Metro App, is when I was using a HTTP debugging proxy (Fiddler). If I don't user Fiddler, which intercepts all HTTP(S) calls, then I have no problems downloading. I even started multiple downloads in rapid succession (by clicking the blue download area multiple times within one second). The result was that all items were downloaded (except for the 404 errors, as mentioned above).
Here is a screenshot of the successful downloads (again except for the 404s). This screenshot is running test case #2 (multiple instances of HttpClient). I did run test case #1 (single instance of HttpClient) and the results were also successful.
In short, I did not see the problems that you are experiencing. The only thing I can think of is for you to try your app from a different machine or location.

how to add a certificate to WCF ChannelFactory?

I need a simple WCF sample code or tutorial or a link that shows the steps on how to add a certificate to ChannelFactory?
Does this help?
// Create a proxy with the previously create binding and
// endpoint address
channelFactory =
new ChannelFactory<IEchoService>(
multipleTokensBinding, serviceAddress);
// configure the username credentials, the client
// certificate and the server certificate on the channel
// factory
channelFactory.Credentials.UserName.UserName = username;
channelFactory.Credentials.UserName.Password = password;
channelFactory.Credentials.ClientCertificate.SetCertificate(
"CN=client.com", StoreLocation.CurrentUser, StoreName.My);
channelFactory.Credentials.ServiceCertificate.SetDefaultCertificate(
"CN=localhost", StoreLocation.LocalMachine, StoreName.My);
client = channelFactory.CreateChannel();
Console.WriteLine("Echo service returned: {0}",
client.Echo());
((IChannel)client).Close();
channelFactory.Close();
}
catch (CommunicationException e)
{
Abort((IChannel)client, channelFactory);
// if there is a fault then print it out
FaultException fe = null;
Exception tmp = e;
while (tmp != null)
{
fe = tmp as FaultException;
if (fe != null)
{
break;
}
tmp = tmp.InnerException;
}
if (fe != null)
{
Console.WriteLine("The server sent back a fault: {0}",
fe.CreateMessageFault().Reason.GetMatchingTranslation().Text);
}
else
{
Console.WriteLine("The request failed with exception: {0}",e);
}
}
catch (TimeoutException)
{
Abort((IChannel)client, channelFactory);
Console.WriteLine("The request timed out");
}
catch (Exception e)
{
Abort((IChannel)client, channelFactory);
Console.WriteLine(
"The request failed with unexpected exception: {0}", e);
}
Console.WriteLine();
Console.WriteLine("Press <ENTER> to terminate client.");
Console.ReadLine();
}