Events not added when hosted on Azure App Service - azure

Creating an event using the create event API call in Microsoft Graph with the .NET SDK. This is my code:
private async Task addEvent(Event #event)
{
using(var task = Task.Run(async() => await client
.Me
.Calendars[calendarID]
.Events.Request()
.AddAsync(#event)))
{
while (!task.IsCompleted)
Thread.Sleep(200);
}
}
This is running and working as expected on my local machine and on IIS in a VM by another provider - has been for about 6 months now.
However, when this runs on an Azure App Service, it doesn't throw an exception but no events are actually created. Read-only calls to get events and calendars work, but this one just doesn't. Any ideas appreciated - maybe there's a setting in an app service?

Related

Adding hosted service seems to crash Azure WebApp

So I have a webservice running in an Azure WebApp, that is the backend for a Blazor frontend. It has api controllers and SignalR.
For easier local development, I added a hosted service using .AddHostedService to have a small shell in the console for querying or triggering things without having to go through swagger or the frontend. This shell is a BackgroundService with practically this:
protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
this.Looper = Task.Run(() => Loop(stoppingToken), stoppingToken);
return this.Looper;
}
private async void Loop(CancellationToken stoppingToken)
{
char chosenOption;
while (!stoppingToken.IsCancellationRequested && (chosenOption = GetChoice()) != 'Q')
{
await Commands[Commands.Keys.Single(key => key[0] == chosenOption)]();
}
}
private char GetChoice()
{
char chosenOption;
Console.WriteLine("Menu:");
do
{
foreach (var choice in Choices)
{
Console.WriteLine(choice);
}
chosenOption = char.ToUpper(Console.ReadKey().KeyChar);
Console.WriteLine();
} while (!IsValidChoice(chosenOption));
return chosenOption;
}
But for some reason, the Azure WebApp now crashes on startup.
Can an Azure WebApp just not handle a hosted service or shell? Because it works fine in the local self-hosted application.
So thanks to #mtkachenko I found the problem in the azure portal's diagnostic tools a few levels deep:
System.InvalidOperationException: Cannot read keys when either application does not have a console or when console input has been redirected
Turns out Console.ReadKey() interacts directly with the console, not just with the input stream. As there is no console connected to the Azure WebApp though (instead the streams are redirected), it crashes trying to interact with the non-existing console.
Console.Read or .ReadLine will work though, as the streams are there.

Error while running after publishing the asp.net core project into Azure free account

I have a free account in Azure. I created a simple project without database and published in Azure and it is running fine in Azure
But after that I created another project with database and I published the following way
select project->publish->appservice->create new.
select create profile. Then I give Appservice name
create sqldatabase - I given the database server name , Administrator user name and admin password , - click ok
finally I clicked create button to create Azure sqlDatabase, SQL server, App Service, then it has created Appservice successfully
after creating the Appservice,I given the database defaultconnection ticked to use this connection string at run time, then i clicked save button.
After that I clicked Publish button and then when it try run the published file the following error message is being showed.
HTTP Error 500.30 - ANCM In-Process Start Failure
Common solutions to this issue:
The application failed to start
The application started but then stopped
The application started but threw an exception during startup
Troubleshooting steps:
Check the system event log for error messages
Enable logging the application process' stdout messages
Attach a debugger to the application process and inspect
I was calling a function SeedData from program.cs file to create the master file before start the application. But after commenting out it is working fine.
public static void Main(string[] args)
{
var host = CreateHostBuilder(args).Build();
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
var context = services.GetRequiredService<MvcProj3_1Context>();
SeedData(context);
}
host.Run();
CreateHostBuilder(args).Build().Run();
}

How To migrate windows service in Azure service fabric

I want to migrate typical windows service which is written in .net to Azure using Service fabric.
To implement this , I am creating one service fabric application containing one micro service as guest executable which uses .exe of windows service and deploying application package to service fabric cluster.
After deploying service fabric application on cluster I want windows service should install & start automatically on all nodes however at any time application is running on any single node. I want windows service should run on only one node at a time.
Please kindly help to implement this.
You can certainly run your service as a guest executable. Making sure it only runs on one node can be done by setting the instance count to 1 in the manifest, like so:
<Parameters>
<Parameter Name="GuestService_InstanceCount" DefaultValue="-1" />
</Parameters>
...
<DefaultServices>
<Service Name="GuestService">
<StatelessService ServiceTypeName="GuestServiceType"
InstanceCount="[GuestService_InstanceCount]">
<SingletonPartition />
</StatelessService>
</Service>
</DefaultServices>
Or, you could actually migrate it, not just re-host it in the SF environment...
If your Windows Service is written in .NET and the you wan't to benefit from Service Fabric then the job of migrating the code from a Windows Service to a Reliable Service in Service Fabric should not be to big.
Example for a basic service:
If you start by creating a Stateless Service in a Service Fabric application you end up with a service implementation that looks like (comments removed):
internal sealed class MigratedService : StatelessService
{
public MigratedService(StatelessServiceContext context)
: base(context)
{ }
protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners()
{
return new ServiceInstanceListener[0];
}
protected override async Task RunAsync(CancellationToken cancellationToken)
{
// TODO: Replace the following sample code with your own logic
// or remove this RunAsync override if it's not needed in your service.
long iterations = 0;
while (true)
{
cancellationToken.ThrowIfCancellationRequested();
ServiceEventSource.Current.ServiceMessage(this.Context, "Working-{0}", ++iterations);
await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
}
}
The RunAsync method starts running as soon as the Service is up and running on a node in the cluster. It will continue to run until the cluster, for some reason, decides to stop the service, or move it to another node.
In your Windows Service code you should have a method that is run on start. This is usually where you set up a Timer or similar to start doing something on a continuous basis:
protected override void OnStart(string[] args)
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 60000; // 60 seconds
timer.Elapsed += new System.Timers.ElapsedEventHandler(this.OnTimer);
timer.Start();
}
public void OnTimer(object sender, System.Timers.ElapsedEventArgs args)
{
...
DoServiceStuff();
Console.WriteLine("Windows Service says hello");
}
Now grab that code in OnTimer and put it in your RunAsync method (and any other code you need):
protected override async Task RunAsync(CancellationToken cancellationToken)
{
while (true)
{
cancellationToken.ThrowIfCancellationRequested();
DoServiceStuff();
ServiceEventSource.Current.ServiceMessage(this.Context,
"Reliable Service says hello");
await Task.Delay(TimeSpan.FromSeconds(60), cancellationToken);
}
}
Note the Task.Delay(...), it should be set to the same interval as your Windows Service had for it's Timer.
Now, if you have logging in your Windows Service and you use ETW, then that should work out of the box for you. You simply need to set up some way of looking at those logs from Azure now, for instance using Log Analytics (https://learn.microsoft.com/en-us/azure/log-analytics/log-analytics-service-fabric).
Other things you might have to migrate is if you run specific code on shut down, on continue, and if you have any parameters sent to the service on startup (for instance connection strings to databases). Those need to be converted to configuration settings for the service, look at SO 33928204 for a starting point for that.
The idea behind service fabric is so that it manages your services, from deployment and running. Once you've deployed your service/application to the service fabric instance it will be just like running a windows service (kinda) so you wont need to install your windows service. If you're using something like TopShelf you can just run the exe and everything will run totally fine within service fabric.

Alerts for exceptions in an Azure worker role

Is there an easy way to send an alert or notification in the Azure Management portal if a worker role throws an exception or has an error?
I am using Azure 2.5
I have tracing and diagnostics all set up and can view the logs in the server explorer of Visual studio, but is there anyway to set an alert if for example and error message appears in the logs.
I know you can set up alerts for monitoring metrics in the Management portal is there an easy way to add metrics for errors and exceptions?
Or someway to get C# exception code to create notifications or alerts in the Azure Management portal?
I ended up using email alerts and Application insights to monitor my worker role in the Azure portal. I created an Application insight on the portal according to these instructions.
Using the Nuget package manager in Visual Studio I added the Application insights API, Application insights for website (even though my worker role is not a web app) and the Application insights trace listener.
I then created an Application insight instance by adding the following to the worker role.
private TelemetryClient tc = new TelemetryClient();
And then adding this to the onStart method.
tc.Context.InstrumentationKey = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXX";
You can find your insturmentation Key in the Azure Portal.
After running, or deploying my worker role I could then view all of my Trace.TraceInformation and TraceError statements in the Azure portal as well as add tc.TrackError and tc.TrackEvent statements to track errors and events.
TrackError worked perfectly for notifying me when an exception was thrown.
I use SendGrid for sending emails through Azure because it's free. Here is what I would do something like below:
try
{
//....
}
catch(Exception ex)
{
MailMessage mailMsg = new MailMessage() {
//Set your properties here
};
// Add the alternate body to the message.
mailMsg.AlternateViews.Add(
AlternateView.CreateAlternateViewFromString(Body
, new System.Net.Mime.ContentType("text/html")));
SmtpClient smtpClient = new SmtpClient(
ServerGlobalVariables.SmtpServerHost
, Convert.ToInt32(587));
System.Net.NetworkCredential credentials =
new System.Net.NetworkCredential(
ServerGlobalVariables.SmtpServerUserName
, ServerGlobalVariables.SmtpServerPassword);
smtpClient.Credentials = credentials;
smtpClient.Send(mailMsg);
}
Please note that I store my credits in a globalvariables class called ServerGlobalVariables. Also, I send my emails formatted as HTML, but you don't have to do that.

Azure Worker Role Control Start Stop and Status

I'm doing my first project but large one on developing Azure Application with Intergration Component.
Currently most of the integration are done using SSIS Packages and would like to transform them on to Worker Role in Azure.
Could someone please help me to understand the following queries regarding Worker Role please?
Is there way to start or stop the Worker role (just like SSIS or Windows Schedulers) via GUI? If not how to achieve this?
How do I know my worker role has been running or not running (including why it's not running ie. logs)
How do I spin multiple worker role based on time (i.e. (9:00AM to 11:00AM spin 4 roles and scale down on quiet period)
Does the following code creates any poison message or dead lock (if multiple there are 10,000 messages to process and every 5 seconds the new thread (Processsing.run) is started?
while(true)
{
var thread = new Thread(Run);
thread.start();
Thread.Sleep(5000);
Trace.WriteLine("Working", "Information");
}
public class PhotoProcessing
{
public static void Run()
{
// Read from queue
CloudQueueMessage msg =
Storage.Queue.GetNextMessage();
while(msg != null)
{
string[] message = msg.AsString.Split('$');
if(message.Length == 2)
{
AddWatermark(message[0], message[1]);
}
// Message has been read so remove it
Storage.Queue.DeleteMessage(msg);
// Get next message if any
msg = Storage.Queue.GetNextMessage();
}
}
Is there way to start or stop the Worker role (just like SSIS or Windows Schedulers) via GUI? If not how to achieve this?
There are actually many ways to achieve this. You can use Windows Azure Portal to do or you could use 3rd party tools (like our Cloud Storage Studio) or you could write your own application using Windows Azure Service Management API (http://msdn.microsoft.com/en-us/library/ee460799.aspx)
How do I know my worker role has been running or not running (including why it's not running ie. logs)
Again you could use one of the GUI based tools to see the status of your roles. As far as why the roles are not running, you would need to enable Windows Azure Diagnostics in your worker role (http://msdn.microsoft.com/en-us/library/gg433048.aspx)
How do I spin multiple worker role based on time (i.e. (9:00AM to 11:00AM spin 4 roles and scale down on quiet period)
You can write your own application using Windows Azure Service Management API to do so or you could make use of 3rd party tools like AzureWatch from Paraleap or Azure Management Cmdlets (both from Microsoft and our company). While the cmdlets will get the job done, I believe Azure Watch is much more sophisticated solution. We wrote a blog post for autoscaling some days back which you can find here: http://www.cerebrata.com/Blog/post/Scale-your-Windows-Azure-instances-with-Azure-Management-Cmdlets.aspx.

Resources