.Net Framework Web Api SelfHost service stopped suddenly - asp.net-mvc

I created a simple Web Api selfHost as windows service which listens to an address which is dynamically loads from the database and normally it includes port number( like : http://localhost:1900)
When I change the address( for example port number, something like http://localhost:1901) the service can catch the requests on the new port but the requests on old port ( http:localhost:1900) leads to crashing the service and it will be stopped.
I just could debug my service and saw just NullReference Error and not any more info about it.
I don't know even where this error happened and non of my logs could help me.
what do you think about this error? Have you ever seen this kind of error before?
For more info I should say just some errors I can see in Event Viewer window :
Application: {Service.exe}
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.NullReferenceException
at System.Web.Http.SelfHost.HttpSelfHostServer+d__35.MoveNext()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)
at System.Web.Http.SelfHost.HttpSelfHostServer+d__34.MoveNext()
at System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.b__6_1(System.Object)
at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(System.Object)
at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
Faulting application name: {Service.exe}, version: 1.0.0.0, time stamp: 0xc594704b
Faulting module name: KERNELBASE.dll, version: 10.0.14393.3383, time stamp: 0x5ddcb9ff
Exception code: 0xe0434352
Fault offset: 0x000dc232
Faulting process id: 0x7370
Faulting application start time: 0x01d72886545b1d41
Faulting application path: {Service PhysicalAddress}
Faulting module path: C:\Windows\System32\KERNELBASE.dll
Report Id: 305c75f4-8c83-484a-b673-565abfc2b7d6
Faulting package full name:
Faulting package-relative application ID
For more details I bring my Service Class Body below :
class service
{
HttpSelfHostConfiguration config;
HttpSelfHostServer server;
Timer _timer = new Timer();
protected override void OnStart(string[] args)
{
_timer.Interval = 2000;
_timer.Elapsed += _timer_Elapsed;
_timer.Enabled = true;
}
private void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
var listenToUrl = _getDestUrlFromDB();
var configChanged = false;
if (config != null && config.BaseAddress.AbsoluteUri != listenToUrl + "/")
{
configChanged = true;
config.Dispose();
}
config = new HttpSelfHostConfiguration(uploadApiUrl.Data);
config.Routes.MapHttpRoute("default",
"api/{controller}/{id}",
new { controller = "Home", id = RouteParameter.Optional });
config.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.Windows;
if (server == null)
{
server = new HttpSelfHostServer(config);
var task = server.OpenAsync();
task.Wait();
}
else if (configChanged)
{
try
{
Process.Start("cmd", $#"netsh http add urlacl url={listenToUrl} ");
Process.Start("cmd", $#"delete urlacl url={listenToUrl} ");
server.Dispose();
server = new HttpSelfHostServer(config);
var task = server.OpenAsync();
task.Wait();
}
catch (Exception ex)
{
}
}
}
}

Related

Cannot See Published Messages on RabbitMQ Dashboard After Publish Event

I run RabbitMQ through Docker Desktop with the following settings:
rabbitmq:
container_name: rabbitmq
restart: always
ports:
- "5672:5672"
- "15672:15672"
Second port number is for the RabbitMQ Dashboard. And, I have a basic REST API endpoint which is supposed to publish a RabbitMQ message as follows:
private readonly IMediator _mediator;
private readonly IPublishEndpoint _publish;
public FlightController(IMediator mediator, IPublishEndpoint publish)
{
_mediator = mediator;
_publish = publish;
}
[HttpPost(Name = "CheckoutCrew")]
[ProducesResponseType((int)HttpStatusCode.Accepted)]
public async Task<IActionResult> CheckoutCrew([FromBody] ScheduleFlightCommand command)
{
var crewIds = new List<string>() { command.SeniorCrewId, command.Crew1Id, command.Crew2Id, command.Crew3Id };
var hasSchedule = true;
var crewCheckoutEvent = new CrewCheckoutEvent() { EmployeeNumbers = crewIds, HasSchedule = hasSchedule };
await _publish.Publish(crewCheckoutEvent);
return Accepted();
}
And, below codes represent the configurations regarding RabbitMQ:
services.AddMassTransit(config => {
config.UsingRabbitMq((ctx, cfg) => {
cfg.Host(Configuration["EventBusSettings:HostAddress"]);
cfg.UseHealthCheck(ctx);
});
});
services.AddMassTransitHostedService();
This Configuration["EventBusSettings:HostAddress"] line points here on appsettings.json:
"EventBusSettings": {
"HostAddress": "amqp://guest:guest#localhost:5672"
}
After I have run my API (named Flight.API), I check RabbitMQ logs via DockerDesktop and see these:
2022-03-31 12:52:41.794701+00:00 [info] <0.1020.0> accepting AMQP connection <0.1020.0> (xxx.xx.x.x:45292 -> xxx.xx.x.x:5672)
2022-03-31 12:52:41.817563+00:00 [info] <0.1020.0> Connection <0.1020.0> (xxx.xx.x.x:45292 -> xxx.xx.x.x:5672) has a client-provided name: Flight.API
2022-03-31 12:52:41.820704+00:00 [info] <0.1020.0> connection <0.1020.0> (xxx.xx.x.x:45292 -> xxx.xx.x.x:5672 - Flight.API): user 'guest' authenticated and granted access to vhost '/'
Everything seems okay, do not they?
I have also wrap .Publish method with try...catch but it also doesn't throw any exceptions. When my endpoint returns Accepted without any issue, I go and check RabbitMQ dashboard but it shows Connections: 0, Channels: 0 etc. Message rates section is also staying on idle.
I cannot see what I am missing.
(Currently, I do not have any consumers, but I should still see some life signs, am I right? Those Connections and Channels counters shouldn't be staying at 0 after I have successfully published my payload)
Thank you in advance.
Edit after adding a consumer class
Still no changes on RabbitMQ Management screens. Everything is on their default values, empty, or idle. Below is my configuration on the consumer project:
services.AddMassTransit(config => {
config.AddConsumer<CrewChecoutConsumer>();
config.UsingRabbitMq((ctx, cfg) => {
cfg.Host(Configuration["EventBusSettings:HostAddress"]);
cfg.UseHealthCheck(ctx);
cfg.ReceiveEndpoint(EventBusConstants.CrewCheckoutQueue, config => {
config.ConfigureConsumer<CrewChecoutConsumer>(ctx);
});
});
});
services.AddMassTransitHostedService();
services.AddScoped<CrewChecoutConsumer>();
appsettings.json file on consumer project is changed accordingly:
"EventBusSettings": {
"HostAddress": "amqp://guest:guest#localhost:5672"
}
And, below is my complete consumer class:
public class CrewChecoutConsumer : IConsumer<CrewCheckoutEvent>
{
private readonly IMapper _mapper;
private readonly IMediator _mediator;
public CrewChecoutConsumer(IMapper mapper, IMediator mediator)
{
_mapper = mapper;
_mediator = mediator;
}
public async Task Consume(ConsumeContext<CrewCheckoutEvent> context)
{
foreach (var employeeNumber in context.Message.EmployeeNumbers)
{
var query = new GetSingleCrewQuery(employeeNumber);
var crew = await _mediator.Send(query);
crew.HasSchedule = context.Message.HasSchedule;
var updateCrewCommand = new UpdateCrewCommand();
_mapper.Map(crew, updateCrewCommand, typeof(CrewModel), typeof(UpdateCrewCommand));
var result = await _mediator.Send(updateCrewCommand);
}
}
}
If you do not have any consumers, the only thing you will see is a message rate on the published message exchange as messages are delivered to the exchange, but then discarded as there are no receive endpoints (queues) bound to that message type exchange.
Until you have a consumer, you won't see any messages in any queues.
Also, you should pass the controller's CancellationToken to the Publish call.

IIS session timeout occurs randomly - due to error in sending email

So let me explain the situation. Our asp.net mvc application is running on Windows server 2012 r2 and IIS 8.5.9600.16384. Now randomly user session is lost 4/5 times a day although timeout is set to 1000 minutes in process mode. Now checking the event viewer I found 4 errors occurs when when user session is lost (every time below errors repeat when session is lost). Below are the errors...
1.
An unhandled exception occurred and the process was terminated.
Application ID: /LM/W3SVC/7/ROOT
Process ID: 7680
Exception: System.Net.Mail.SmtpException
Message: The operation has timed out.
StackTrace: at System.Net.Mail.SmtpClient.Send(MailMessage message)
at PDSO.Models.MailClient.<>c__DisplayClass2_1.<SendGMail>b__0(Object o) in
D:\Development\Projects\YunuscoMRP\YunuscoMRP\Models\Repository\MailClient.cs:line 67
at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext,
ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback
callback, Object state, Boolean preserveSyncCtx)
at
System.Threading.QueueUserWorkItemCallback.System.Threading.
IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
`
Application: w3wp.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.Net.Mail.SmtpException
at System.Net.Mail.SmtpClient.Send(System.Net.Mail.MailMessage)
at PDSO.Models.MailClient+<>c__DisplayClass2_1.<SendGMail>b__0(System.Object)
at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(System.Object)
at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
`
3.
`
Faulting application name: w3wp.exe, version: 8.5.9600.16384, time stamp: 0x52157ba0
Faulting module name: KERNELBASE.dll, version: 6.3.9600.19724, time stamp: 0x5ec50c3e
Exception code: 0xe0434352
Fault offset: 0x000156e8
Faulting process id: 0x1e00
Faulting application start time: 0x01d8165b6e64aacc
Faulting application path: C:\Windows\SysWOW64\inetsrv\w3wp.exe
Faulting module path: C:\Windows\SYSTEM32\KERNELBASE.dll
Report Id: 38d3cbc4-824f-11ec-8116-000c293f4b2c
Faulting package full name:
Faulting package-relative application ID:
`
4.
An unhandled Microsoft .NET Framework exception occurred in w3wp.exe [7680].
Just-In-Time debugging this exception failed with the following error: Debugger could not be
started because no user is logged on.
Check the documentation index for 'Just-in-time debugging, errors' for more information.
I have one class to handle outgoing email. Code is provided below
public string SendGMail(string fromEmail, string toEmail, string mailSubject, string mailBody,
string senderName, string senderPass, string attacmmentLocationPath)
{
try
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress(fromEmail);
mail.To.Add(toEmail);
mail.Subject = mailSubject;
mail.Body = mailBody;
mail.IsBodyHtml = true;
//// mail.Attachments.Add(new Attachment(#attacmmentLocationPath));
//---------------- Enable the block before publish ----------
ThreadPool.QueueUserWorkItem(o =>
{
using (SmtpClient client = new SmtpClient("smtp.office365.com"))
{
client.Port = 587;
client.Credentials = new System.Net.NetworkCredential(senderName, senderPass);
client.EnableSsl = true;
client.Send(mail);
}
});
//-------------------------------------------------------------
return "Success";
}
catch (Exception ex)
{
bool error = new ErrorLogRepository().InsertErrorToDatabase("", "MailClient", "SendGmail", ex.ToString());
return "Error";
}
}
Can anyone suggest what is wrong with my sending email code or what is causing the session timeout/iis restart/application pool restart ?
You should add a try-catch block to your work item to handle the SMTP client exception and log the error gracefully. Because the work item executes outside of your SendMail function, the try-catch block in the SendMail function does not handle the exception.
ThreadPool.QueueUserWorkItem(o =>
{
try
{
using (SmtpClient client = new SmtpClient("smtp.office365.com"))
{
client.Port = 587;
client.Credentials = new System.Net.NetworkCredential(senderName, senderPass);
client.EnableSsl = true;
client.Send(mail);
}
}
catch (Exception ex)
{
bool error = new ErrorLogRepository().InsertErrorToDatabase("", "MailClient", "SendGmail", ex.ToString());
}
});

Cannot connect to Solace Cloud

I am following the solace tutorial for Publish/Subscribe (link: https://dev.solace.com/samples/solace-samples-java/publish-subscribe/). Therefore, there shouldn't be anything "wrong" with the code.
I am trying to get my TopicSubscriber to connect to the cloud. After building my jar I run the following command:
java -cp target/SOM_Enrichment-1.0-SNAPSHOT.jar TopicSubscriber <host:port> <client-username#message-vpn> <password>
(with the appropriate fields filled in)
I get the following error:
TopicSubscriber initializing...
Jul 12, 2018 2:27:56 PM com.solacesystems.jcsmp.protocol.impl.TcpClientChannel call
INFO: Connecting to host 'blocked out' (host 1 of 1, smfclient 2, attempt 1 of 1, this_host_attempt: 1 of 1)
Jul 12, 2018 2:28:17 PM com.solacesystems.jcsmp.protocol.impl.TcpClientChannel call
INFO: Connection attempt failed to host 'blocked out' ConnectException com.solacesystems.jcsmp.JCSMPTransportException: ('blocked out') - Error communicating with the router. cause: java.net.ConnectException: Connection timed out: no further information ((Client name: 'blocked out' Local port: -1 Remote addr: 'blocked out') - )
Jul 12, 2018 2:28:20 PM com.solacesystems.jcsmp.protocol.impl.TcpClientChannel close
INFO: Channel Closed (smfclient 2)
Exception in thread "main" com.solacesystems.jcsmp.JCSMPTransportException" (Client name: 'blocked out' Local port: -1 Remote addr: 'blocked out') - Error communicating with the router.
Below is the TopicSubscriber.java file:
import java.util.concurrent.CountDownLatch;
import com.solacesystems.jcsmp.BytesXMLMessage;
import com.solacesystems.jcsmp.JCSMPException;
import com.solacesystems.jcsmp.JCSMPFactory;
import com.solacesystems.jcsmp.JCSMPProperties;
import com.solacesystems.jcsmp.JCSMPSession;
import com.solacesystems.jcsmp.TextMessage;
import com.solacesystems.jcsmp.Topic;
import com.solacesystems.jcsmp.XMLMessageConsumer;
import com.solacesystems.jcsmp.XMLMessageListener;
public class TopicSubscriber {
public static void main(String... args) throws JCSMPException {
// Check command line arguments
if (args.length != 3 || args[1].split("#").length != 2) {
System.out.println("Usage: TopicSubscriber <host:port> <client-username#message-vpn> <client-password>");
System.out.println();
System.exit(-1);
}
if (args[1].split("#")[0].isEmpty()) {
System.out.println("No client-username entered");
System.out.println();
System.exit(-1);
}
if (args[1].split("#")[1].isEmpty()) {
System.out.println("No message-vpn entered");
System.out.println();
System.exit(-1);
}
System.out.println("TopicSubscriber initializing...");
final JCSMPProperties properties = new JCSMPProperties();
properties.setProperty(JCSMPProperties.HOST, args[0]); // host:port
properties.setProperty(JCSMPProperties.USERNAME, args[1].split("#")[0]); // client-username
properties.setProperty(JCSMPProperties.PASSWORD, args[2]); // client-password
properties.setProperty(JCSMPProperties.VPN_NAME, args[1].split("#")[1]); // message-vpn
final Topic topic = JCSMPFactory.onlyInstance().createTopic("tutorial/topic");
final JCSMPSession session = JCSMPFactory.onlyInstance().createSession(properties);
session.connect();
final CountDownLatch latch = new CountDownLatch(1); // used for
// synchronizing b/w threads
/** Anonymous inner-class for MessageListener
* This demonstrates the async threaded message callback */
final XMLMessageConsumer cons = session.getMessageConsumer(new XMLMessageListener() {
#Override
public void onReceive(BytesXMLMessage msg) {
if (msg instanceof TextMessage) {
System.out.printf("TextMessage received: '%s'%n",
((TextMessage) msg).getText());
} else {
System.out.println("Message received.");
}
System.out.printf("Message Dump:%n%s%n", msg.dump());
latch.countDown(); // unblock main thread
}
#Override
public void onException(JCSMPException e) {
System.out.printf("Consumer received exception: %s%n", e);
latch.countDown(); // unblock main thread
}
});
session.addSubscription(topic);
System.out.println("Connected. Awaiting message...");
cons.start();
// Consume-only session is now hooked up and running!
try {
latch.await(); // block here until message received, and latch will flip
} catch (InterruptedException e) {
System.out.println("I was awoken while waiting");
}
// Close consumer
cons.close();
System.out.println("Exiting.");
session.closeSession();
}
}
Any help would be greatly appreciated.
java.net.ConnectException: Connection timed out
The log entry indicates that network connectivity to the specified DNS name/IP address cannot be established.
Next step includes:
Verifying that you are able to resolve the DNS name to an IP
address.
Verifying that the correct DNS name/IP address/Port is in use - You need the "SMF Host" in the Solace Cloud Connection Details.
Verifying that the IP address/Port is not blocked by an intermediate network device.

How to better troubleshoot this 500 Error in MVC Web API

I have an MVC Web API project that I am working on. I created a controller with an action. I am able to hit the action properly using Postman, but when an external system tries to reach my controller, it gets a 500 error. The owner of the external service cannot give me any details beyond that, they can only retry the request.
Here is one of the log entries of their requests in IIS log
#Fields: date time s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs(User-Agent) cs(Referer) sc-status sc-substatus sc-win32-status time-taken
2017-02-15 20:38:58 192.168.2.34 POST /Route/to/actionName 8002 - 192.168.2.37 Apache-HttpClient/4.5.2+(Java/1.8.0_102) - 500 0 0 146
First I thought may be the action is being hit, so I added an exception handler and added logging.
[Route("actionName")]
[HttpPost]
public IHttpActionResult actionName(MessageModel message)
{
try
{
// code to handle the action
}
catch (Exception e)
{
// Code to log exception in the log file
}
}
Tried above and saw nothing in the log, I have run tests for failed requests to make sure the above exception handler logs and it does.
So the next thing I decided to do was to handle application level errors in Global.asax and log exception there.
protected void Application_Error(object sender, EventArgs e)
{
if (Request.HttpMethod == "POST")
{
var request = SomeMethodToReadRequestContentsInString();
var service = new SomeExceptionLoggingService();
var exception = Server.GetLastError();
if (exception == null)
{
exception = new ApplicationException("Unknown error occurred");
}
service.LogException(exception, Request.UserHostAddress, Request.UserAgent, request);
}
}
And to my surprise, nothing in the log file.
So then I decided to log ALL Post requests and see if I register ANYTHING in the log.
protected void Application_EndRequest(object sender, EventArgs e)
{
if (Request.HttpMethod == "POST")
{
var request = Helper.ReadStreamUnknownEncoding(Request.InputStream);
var service = new InterfaceTestingService();
var exception = Server.GetLastError();
if (exception == null)
{
exception = new ApplicationException("No Error in this request");
}
service.LogException(exception, Request.UserHostAddress, Request.UserAgent, request);
}
}
And again, nothing!
How do I catch this bug? My goal is to see the Content-Type, and contents.
I tried to add a Custom Field in IIS log settings to include `Content-Type', but the log files still don't have that.
I added a handler for Application_BeginRequest logging everything I did in Application_EndRequest. And it turns out, the content-length was zero, and there was no content. I also restarted IIS Web Server to get it to log custom fields too.
What's strange is that if I send empty content through Postman, I get the action code executed but for some reason when they do it, it doesn't.

Invoking Adapter from Java - Worklight 6.2

Below is the java sample code from worklight to invoke adapter.
public static void testAdapterCall(){
try{
DataAccessService service = WorklightBundles.getInstance().getDataAccessService();
String paramArray = "[5, 3,]";
ProcedureQName procedureQname = new ProcedureQName("CalculatorAdapter", "addTwoIntegers");
InvocationResult result = service.invokeProcedure(procedureQname, paramArray);
}
catch(Exception e)
{
e.printStackTrace();
}
}
I'm getting a Null Pointer exception, when it goes to line
DataAccessService service = WorklightBundles.getInstance().getDataAccessService();
Log is as below:
java.lang.NullPointerException
at com.worklight.customcode.Calculator1.testAdapterCall(Calculator1.java:38)
at com.worklight.customcode.Calculator1.main(Calculator1.java:53)
Versions:
Java 1.7
Worklight 6.2
The Adapter is deployed, and the server is also running locally.
I saw this question in other sites also, but it is not answered.
Any help is highly appreciated.
See the documentation in the following PDF document, starting page #13.
public void callProcedure() {
DataAccessService service = worklightBundles.getInstance().getDataAccessService();
String paramArray = "['param1', 'param2', 'param3']";
ProcedureQName procedureQName = new ProcedureQName("adapterName",
"procedureName");
InvocationResult result = service.invokeProcedure(ProcedureQName,
paramArray);
JSONObject jsonObject = result.toJSON();
String value = (String)jsonObject.get("key");
}
Be sure to add any missing includes once you enter the code into a Java IDE, such as Eclipse.

Resources