How to show event message in Azure Service Fabric Explorer - azure

I'm new to Azure Service Fabric. I follow the tutorial to create hello demo service for Stateless.
It's simple service and I can find the Event Message in local VS IDE Diagnostic Events to show the message that I print
ServiceEventSource.Current.ServiceMessage(this.Context, "Working-{0}", ++iterations);
Like below picture:
But I can't see any log for cluster manager explorer.
Is it possible to show the event log in this explorer? How to do it?
There are my demo event source class code;
[NonEvent]
public void Message(string message, params object[] args)
{
if (this.IsEnabled())
{
string finalMessage = string.Format(message, args);
Message(finalMessage);
}
}
private const int MessageEventId = 1;
[Event(MessageEventId, Level = EventLevel.Informational, Message = "{0}")]
public void Message(string message)
{
if (this.IsEnabled())
{
WriteEvent(MessageEventId, message);
}
}

Pretty sure that currently the Service Fabric Explorer (SFX) only shows node level events and not application specific events.
According to the resent 7.0 release announcement (https://techcommunity.microsoft.com/t5/Azure-Service-Fabric/Service-Fabric-7-0-Release/ba-p/1015482) work is ongoing to display application specific events in SFX

Related

Xamarin IOS - Show local notification when application is closed

I have a Xamarin IOS application that get's the users location each 10 sec, even when the app is killed. I make us of this library: "https://jamesmontemagno.github.io/GeolocatorPlugin/".
What I want is: When the app is closed or open and the user is at a specific location, I want to show a local notification. Is that even possible when the app is closed? I can't find information on this because it's always about remote notifications.
Notification permission should be requested as soon as the app launches by adding the following code to the FinishedLaunching method of the AppDelegate and setting the desired notification type (UNAuthorizationOptions):
...
using UserNotifications;
...
public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
{
....
//after iOS 10
if(UIDevice.CurrentDevice.CheckSystemVersion(10,0))
{
UNUserNotificationCenter center = UNUserNotificationCenter.Current;
center.RequestAuthorization(UNAuthorizationOptions.Alert | UNAuthorizationOptions.Sound | UNAuthorizationOptions.UNAuthorizationOptions.Badge, (bool arg1, NSError arg2) =>
{
});
center.Delegate = new NotificationDelegate();
}
else if(UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
{
var settings = UIUserNotificationSettings.GetSettingsForTypes(UIUserNotificationType.Alert| UIUserNotificationType.Badge| UIUserNotificationType.Sound,new NSSet());
UIApplication.SharedApplication.RegisterUserNotificationSettings(settings);
}
return true;
}
New to iOS 10, an app can handle Notifications differently when it is in the foreground and a Notification is triggered. By providing a UNUserNotificationCenterDelegate and implementing the UserNotificationCentermethod, the app can take over responsibility for displaying the Notification. For example:
using System;
using ObjCRuntime;
using UserNotifications;
namespace workplat
{
public class NotificationDelegate:UNUserNotificationCenterDelegate
{
public NotificationDelegate()
{
}
public override void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification, Action<UNNotificationPresentationOptions> completionHandler)
{
// Do something with the notification
Console.WriteLine("Active Notification: {0}", notification);
// Tell system to display the notification anyway or use
// `None` to say we have handled the display locally.
completionHandler(UNNotificationPresentationOptions.Alert|UNNotificationPresentationOptions.Sound);
}
public override void DidReceiveNotificationResponse(UNUserNotificationCenter center, UNNotificationResponse response, Action completionHandler)
{
// Take action based on Action ID
switch (response.ActionIdentifier)
{
case "reply":
// Do something
break;
default:
// Take action based on identifier
if (response.IsDefaultAction)
{
// Handle default action...
}
else if (response.IsDismissAction)
{
// Handle dismiss action
}
break;
}
// Inform caller it has been handled
completionHandler();
}
}
}
To create and register a Custom Action with the system, use the following code:
public void RegisterNotification(long time)
{
UNUserNotificationCenter center = UNUserNotificationCenter.Current;
//creat a UNMutableNotificationContent which contains your notification content
UNMutableNotificationContent notificationContent = new UNMutableNotificationContent();
notificationContent.Title = "xxx";
notificationContent.Body= "xxxx";
notificationContent.Sound = UNNotificationSound.Default;
UNTimeIntervalNotificationTrigger trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(time, false);
UNNotificationRequest request = UNNotificationRequest.FromIdentifier("FiveSecond", notificationContent, trigger);
center.AddNotificationRequest(request,(NSError obj) =>
{
});
}
When you call this method ,for emample:
RegisterNotification(20);//set the time you want to push notification
The notification will been pushed after 20 seconds,enen if you close your app. You could put this line after uploading the location .
I have upload my demo to my github, you can download it for your reference: Demo Link .
And you can access the link for more information and details: MicroSoft Document

Webjob is causing performance issue with ASP.NET core

I created a .NET CORE console application and uploaded as a continuous mode webjob to an Azure application (ASP.NET Core). With webjob running, webapp is very slow responding to API request (Request time rise to few seconds).
WebJob code
static void Main(string[] args)
{
queueClient.RegisterMessageHandler(
async (message, token) =>
{
// Process the message
// Complete the message so that it is not received again.
// This can be done only if the queueClient is opened in ReceiveMode.PeekLock mode.
await queueClient.CompleteAsync(message.SystemProperties.LockToken);
},
new MessageHandlerOptions(exce => {
return Task.CompletedTask;
})
{ MaxConcurrentCalls = 1, AutoComplete = false });
//Console.ReadKey();
while (true) ;
}
And the processing the message operation takes few seconds.
from SCM console
Request time
The while(true) ; will pin the CPU so I suggest you don't do that.
Check the Queue message handling example for the proper way how to implement message handling: https://github.com/Azure/azure-webjobs-sdk/wiki/Queues
You will have to change your Main to:
static void Main(string[] args)
{
JobHost host = new JobHost();
host.RunAndBlock();
}
And then you can make a message handler in another file:
public static void ProcessQueueMessage([QueueTrigger("logqueue")] string logMessage, TextWriter logger)
{
logger.WriteLine(logMessage);
}
The 3.0.0 preview versions of the Microsoft.Azure.WebJobs library support .NET Standard 2.0, so it can be used with .NET Core 2.0 projects.
If you want to implement it yourself, you can check the Webjobs SDK source code for an example how they do it: https://github.com/Azure/azure-webjobs-sdk/blob/dev/src/Microsoft.Azure.WebJobs.Host/JobHost.cs

Internet Connectivity Listener in Xamarin.Forms

I am new in Xamarin.Forms and I want to check internet connectivity status in iOS and Android app. In fact using CrossConnectivity Plugins I am able to check internet connectivity successfully but It is not working as Listener. For example, When I open my app and internet connection is not there then it shows me message that "No internet connection" and now if I ON my mobile data then also it shows me same message. I am using below code for this:
string isConnected=CrossConnectivity.Current.IsConnected?"Connected":"No Connection";
My app is not able to listen the changing status of internet connectivity in middle something.
Using the plugin CrossConnectivity, you need to listen to changes via the event ConnectivityChanged, so in your page, or your App class, add this code to write an event handler:
CrossConnectivity.Current.ConnectivityChanged += (sender, args) =>
{
//your implementation
this.DisplayAlert("Connectivity Changed", "IsConnected: " + args.IsConnected.ToString(), "OK");
};
I have the solution for Android but i haven't started working on ios part
(better than nothing ;)
First Create a broadcastReceiver
public class Localize: BroadcastReceiver
{
public static Context context;
public Localize(Context ctx)
{
context = ctx;
}
public override void OnReceive (Context context, Intent intent)
{
isNetworkAvailable (context);
}
public void isNetworkAvailable(Context context)
{
Boolean state = false;
ConnectivityManager connectivity = (ConnectivityManager)
context.GetSystemService(Context.ConnectivityService);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.GetAllNetworkInfo();
foreach (NetworkInfo nwork in info)
{
if (nwork.GetState () == NetworkInfo.State.Connected) {
ConnectionDetected();//Execute your fonction here
break;
}
}
}
}
Then register your broadcastreceiver with intent in your activity (in MainActivity for example)
IntentFilter filter = new IntentFilter(ConnectivityManager.ConnectivityAction);
receiver = new Localize(this);
RegisterReceiver(receiver, filter);
This should work as long as your application is running.. If you want a service that runs even if your App is killed you should create a service and then register broadcastReceiver in your service..
CrossConnectivity.Current.IsReachable("localhost");
this also works if you download package. I haven't tested it thoroughly

Application Insights - Logging exceptions

I wrote a custom logger for Application Insights in my app. I don't see any exceptions or ANY events when viewing App Insights in Azure Portal. Here is the logger class code, when I debug the code I do see a key assigned to the InstrumentationKey property, any ideas what I am doing wrong here? Do I need to attach other info to the client or configuration?
public class AppInsightsLogger:ILogger
{
private TelemetryClient ai;
public AppInsightsLogger()
{
ai = new TelemetryClient();
if (string.IsNullOrEmpty(ai.InstrumentationKey))
{
// attempt to load instrumentation key from app settings
var appSettingsTiKey = AppSettings.InsightsKey;
if (!string.IsNullOrEmpty(appSettingsTiKey))
{
TelemetryConfiguration.Active.InstrumentationKey = appSettingsTiKey;
ai.InstrumentationKey = appSettingsTiKey;
}
else
{
throw new Exception("Could not find instrumentation key for Application Insights");
}
}
}
public void LogException(Exception ex)
{
ai.TrackException(ex);
}
}
I created a new Console Application, installed latest stable ApplicationInsights SDK and pretty much kept your example, with minor but important difference - I either let it wait before shutting down after calling TrackException or added TelemetryClient.Flush()
namespace logtest
{
class Program
{
static void Main(string[] args)
{
AppInsightsLogger logger = new AppInsightsLogger();
logger.LogException(new InvalidOperationException("Is data showing?"));
// either wait for a couple of minutes for the batch to be sent of add ai.Flush() after ai.TrackException() to send the batch immediately
Console.ReadLine();
}
}
public class AppInsightsLogger
{
private TelemetryClient ai;
public AppInsightsLogger()
{
ai = new TelemetryClient();
if (string.IsNullOrEmpty(ai.InstrumentationKey))
{
// attempt to load instrumentation key from app settings
var appSettingsTiKey = "<ikey>";
if (!string.IsNullOrEmpty(appSettingsTiKey))
{
TelemetryConfiguration.Active.InstrumentationKey = appSettingsTiKey;
ai.InstrumentationKey = appSettingsTiKey;
}
else
{
throw new Exception("Could not find instrumentation key for Application Insights");
}
}
}
public void LogException(Exception ex)
{
ai.TrackException(ex);
// ai.Flush();
}
}
}
First I could see telemetry item sent in Visual Studio debug output window:
Then I could see telemetry leaving my machine in Fiddler, I also could see it was successfully accepted by our data collection endpoint.
And finally I could see it in the portal:
Nowadays, the question and the accepted answer are outdated. The contemporary approach is to add Microsoft.ApplicationInsights.AspNet NuGet package, which has logging out-of-the-box.
Please refer to the official docs.
The gist from the docs:
ApplicationInsightsLoggerProvider is enabled by default.
Captured log types can be configured in appsettings.json (or programmatically if you really need it)
"Logging": {
"LogLevel": {
"Default": "Warning"
},
"ApplicationInsights": {
"LogLevel": {
"Default": "Error"
}
}
}
For a version 3 webjob, I tried instantiating a TelemetryClient and calling TrackException(), as well as calling Flush() and waiting up to 180 seconds, but none of that worked. What does work is using the ILogger logger object and passing the exception into LogError().

How can I set the type of azure service bus to notification hub programmatically

Using methods below, I previously (until last week) could create a service bus with a "mixed" type and then could add a notification hub. However, it suddenly stopped working. It creates a service bus with "Messaging" type and when it tries to create the notification hub, I get the error below:
Enity xxxxxx, create notification hub failed with error forbidden
public ServiceBusNamespaceResponse CreateServiceBus(SubscriptionCloudCredentials credentials, string regoin)
{
var serviceBushubClient = CloudContext.Clients.CreateServiceBusManagementClient(credentials);
var checkserviceBusResponse = serviceBushubClient.Namespaces.CheckAvailability(_deploymentName);
if (checkserviceBusResponse.IsAvailable)
{
try
{
var serviceBusClientResponse = serviceBushubClient.Namespaces.Create(_deploymentName, regoin);
_serviceBusEndpoint = serviceBusClientResponse.Namespace.ServiceBusEndpoint.ToString();
return serviceBusClientResponse;
}
catch (CloudException ex)
{
Console.WriteLine(ex.ErrorMessage);
return null;
}
}
return null;
}
and
public bool CreateNotificationHub(SubscriptionCloudCredentials credentials)
{
SBNotificationHubManager notificationHub;
EntityDescription servesBus = new EntityDescription();
servesBus.Name =_deploymentID;
var des = new MyNotificationHubDescription("push-hub-" + TenantID, servesBus);
notificationHub =
ResourceFactory.Get( _subscriptionID,
new X509Certificate2(Convert.FromBase64String(RowData._base64EncodedCert)),
SBRestResourceType.NHub, des) as SBNotificationHubManager;
if (notificationHub != null)
{
// Console.WriteLine("Created Notification Hub: {0}{1}", Environment.NewLine, notificationHub.LookUp().ToString());
if (notificationHub.Create())
{
Console.WriteLine("Created Notification Hub: {0}{1}", Environment.NewLine, notificationHub.LookUp().ToString());
notificationHub.WaitUntillActive();
return true;
}
}
return false;
}
I was wondering if something recently changed in azure? Can anyone please advise how to define the type of service bus (messaging/notification hub) when creating it in c#. The default with the above method is messaging. I need mixed, but notification hub type also works fine in my case.
Thank you
Now you must explicitly select Messaging (for topics/queues/event hubs) or NotificationHub (for notification hubs). That is idea.
About implementation. Observing source codes I can see overload which accepts ServiceBusNamespaceCreateParameters argument:
Task<ServiceBusNamespaceResponse> CreateNamespaceAsync(string namespaceName, ServiceBusNamespaceCreateParameters namespaceEntity, CancellationToken cancellationToken);
That class has public property of NamespaceType
public NamespaceType NamespaceType{...
So you probably could set it to NamespaceType.NotificationHub and then go ahead to create namespace.

Resources