Exiting Kestrel in self-hosted .NET5 console app - .net-5

I'm trying to exit a console app from the startup.cs file.
Every piece of information about this is trying to use IApplicationLifetime but this does not exist in .NET5
This is the Configure signature:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
If I just call Environment.Exit(1); I get the following error:
Waiting for the host to be disposed. Ensure all 'IHost' instances are wrapped in 'using' blocks.

Related

How can I create a WCF Service Application in Visual Studio that does NOT use a Web Server

I have a simple task: A program (executable) is supposed to call a function of another program (also executable) with some parameters. Program A is supposed to be started, call the function and then terminate. Program B is legacy program that has a GUI and runs continuously. Both programs run on the same Windows PC and use the .NET Framework. I have no experience in web development and Program B is not supposed to run as a web service! Named pipes seem like a good option.
I researched what the best method would be and wanted to try WCF. The documentation claims that "A service endpoint can be part of a continuously available service hosted by IIS, or it can be a service hosted in an application". From that I understand that I can run Program B as a service without hosting a web server.
However everything I see in Visual Studio seems to presume I want to run a server. Wenn I want to create a new WCF project in Visual Studio the only options are a library or "A project for creating WCF service application that is hosted in IIS/WAS". Once I've created said project the debugger wants me to choose a browser for hosting the service.
In another StackOverflow topic a popular suggestion was using this website as a guide and simply removing the http references since the guide is for both named pipes and http. Another indication that it should be possible.
So can someone point me in the right direction? What am I missing? How can I use WCF with nothing related to Web Development involved?
You have already been on the way, it is enough to host the web service in Program B, without specifying a web server. this is called a self-hosted WCF. As the link you provided mentioned, the Service host class is used to host the WCF service, which means that we can host the service in the Console/Winform, and so on.
Here is an example of hosting the service in a Winform application.
public partial class Form1 : Form
{
ServiceHost serviceHost = null;
public Form1()
{
InitializeComponent();
Uri uri = new Uri("http://localhost:9009");
BasicHttpBinding binding = new BasicHttpBinding();
serviceHost = new ServiceHost(typeof(MyService), uri);
serviceHost.AddServiceEndpoint(typeof(IService), binding, "");
ServiceMetadataBehavior smb = new ServiceMetadataBehavior()
{
HttpGetEnabled = true
};
serviceHost.Description.Behaviors.Add(smb);
System.ServiceModel.Channels.Binding mexbinding = MetadataExchangeBindings.CreateMexHttpBinding();
serviceHost.AddServiceEndpoint(typeof(IMetadataExchange), mexbinding, "mex");
serviceHost.Open();
}
private void Form1_Load(object sender, EventArgs e)
{
if (serviceHost.State==CommunicationState.Opened)
{
this.label1.Text = "Service is running";
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (serviceHost.State==CommunicationState.Opened&&serviceHost.State!=CommunicationState.Closed)
{
serviceHost.Close();
}
}
}
[ServiceContract]
public interface IService
{
[OperationContract]
string Test();
}
public class MyService:IService
{
public string Test()
{
return DateTime.Now.ToLongTimeString();
}
}
After that, we could consume it by using a client proxy.
https://learn.microsoft.com/en-us/dotnet/framework/wcf/accessing-services-using-a-wcf-client
Feel free to let me know if there is anything I can help with.

Trace in Azure Bot Service

I'm following this step to enable tracing in Azure Bot App Service https://microsoft.github.io/AzureTipsAndTricks/blog/tip30.html
However, my trace does not appear in the log stream.
I can see a bunch of other logs here.
I also tried "#define TRACE" at the class with the code
System.Diagnostics.Trace.WriteLine("Entering the About View");
Am I missing anything?
My Azure Web App setting: https://pictr.com/images/2019/06/25/5BHthA.png
My Log stream: https://pictr.com/images/2019/06/25/5BHszI.png
Thanks.
Thanks. Can use below to log to App Service's Logstream as well if using Starter Bot at https://github.com/martinkearn/Bot-Starter-Template/:
ILogger<BotFrameworkHttpAdapter> logger,
logger.LogError($"Exception caught on attempting to Delete ConversationState : {e.Message}");
Apart from the changes in the portal to enable it; you'll want to use the Microsoft.Exensions.Logging namespace. Add the Microsoft.Extensions.Logging.AzureAppServices package (version appropriate for your project).
Then add logging for azure (AddAzureWebAppDiagnostics) where you setup your host:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureLogging((logging) =>
{
logging.AddAzureWebAppDiagnostics();
});
Then make sure your class implements ILogger. You can see an example of that in the Core bot sample here.
Then just do your logging in the method you wish:
Logger.LogInformation("This is my test.");
Here's some more info:
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-2.2

Web API works locally but doesn’t work on azure

I have created a web API connected to azure sql server in .net core using visual studio for Mac đź’». Then I created a web app in azure and then published by project directly in visual studio for Mac to azure.
After I published I try to access the api using postman and chrome (URL/api/menu) but I got 500 server error which is generic and doesn’t tell me anything.
In visual studio for Mac I got the green light it said published and directly took me to the new url.
So, what do you guys thing is the problem.
This is my first time using azure so I didn’t change any setting or anything
Since many different problems can cause this error page, I can strongly recommend the following in order to determine the root cause quickly and easily, without struggling with Azure (or any server/platform for that matter) to get logs.
You can enable extremely helpful error messages at startup by setting the .UseSetting("detailedErrors", "true") and .CaptureStartupErrors(true) actions in your Program.cs file.
For ASP.NET CORE 2.1
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.CaptureStartupErrors(true)
.UseSetting("detailedErrors", "true")
.UseStartup<Startup>()
.Build();
}
Add these commands in your startup.cs class:
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseBrowserLink();
also enable stdoutLog in your web.config file
stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout"
Error code 500 in web api,usually, means problems with a configuration in Startup.cs - the most common problems include an issue with DB itself, an issue with migrations (if you are using Code First approach), problems with appsettings.js.
Please refer to the log file in .\logs\stdout.
Hope it helps.

Deploy ASP.net core 2.1 WEB API to IIS using Visual Studio Code

Working on an ASP.net core 2.1 web API project. I need to enable the API so that it can be accesed by client applications that we also have under developement.
So far, the only way I've found to publish to IIS is by doing a manual process:
Run dotnet publish -c Release
Copy the files in bin\Release\netcoreapp2.1\publish\ to my IIS Web App folder
I wonder if there is a more straight forward way of doing this.
Also It takes quite sometime to build this release, so for a development environment it's quite a slow process. The problem is that we cannot allow external access to the WEB api when running with F5 on the Integrated test server. How can we enable an more agile testing environment?
Another issue is that when calling for example fetch('MyAPIServer/api/MyItems') from a javascript application, I get a CORS error:
Failed to load http://localhost:86/api/shit: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8082' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled
Is enabling CORS absolutely necesary when developing this type of apps?
If I fetch like this:
fetch(
`http://localhost:86/api/shit`,{mode: 'no-cors'}
)
I get:
Uncaught (in promise) SyntaxError: Unexpected end of input
at eval (Pos.vue?7f37:68)
As far as the CORs issue goes you can add the following to your startup:
public void ConfigureServices(IServiceCollection services)
{
// Rest of config stuff ...
services.AddCors();
}
Then in you will also need to add the following.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors(builder =>
{
builder.WithOrigins("http://localhost:8080",
"http://localhost:8081",
"http://localhost:8082")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
app.UseMvc();
}

Change Parse Application when App is running

I have an Android Application that works with locals instalations and I want use it with diferents Parse applications. Each instalation administrator will contract with Parse directly. When app start it will look for the keys for parse.
I wonder how to change the Parse App linkeded in the Android App once this is running
I have tried to call Parse.initialize (context, apllicationId, clientKey) twice but it doesn't work. I have tried the app register in diferent Parse App every time you start the App link with a different Parse App
It´s always linked only with the first application
public void onCreate(final Bundle icicle){
super.onCreate(icicle);
final Context context = this;
setContentView(R.layout.ssa);
getActionBar().hide();
// Getting the global variables
fmGlobalsBean = Utilities.getGlobals(this);
if(!"".equals(fmGlobalsBean.getUrl_server())){
Parse.initialize(contexto, "p4IWkTRc0WTdKkMH6r60hjYzwX1TIXChy8VcDvPb", "KhkcX4G3dqVpRawHyIYfnHAWqj1H2vyhwD3wINlQ");
ParseInstallation.getCurrentInstallation().saveInBackground();
ParsePush.subscribeInBackground(fmGlobalsBean.getUrl_server());
}
else
{
Parse.initialize(this, "Y3xgZ58u4Qcn9TrovFqCOe4PBzhURjXooZ3vDKgB", "ealo3nm4wa4lbJ7KrSR2OSf60DZiUjEUjdUJTQzs");
ParseInstallation.getCurrentInstallation().saveInBackground();
ParsePush.subscribeInBackground("INITIAL");
}
}

Resources