Configurable Application Insights Instrumentation Key - asp.net-mvc

How can I best make the Application Inisghts' Instrumentation Key configurable in a way that allows an Azure Administrator to manage the settings for an App Services deployment of an MVC5 web application? Is there a certain event in an MVC application initialization where this should be done or is it okay to do it at pretty much any point? I am using the Trace Listener integration as well.
By default, the Instrumentation Key (iKey) is set in the ApplicationInsights.config file. Additionally, if you include the JavaScript portions, the iKey is again set in the _Layout.cshtml file. This is two different places with an iKey that you need to manage.
I want to be able to manage this key via the App Services -> Application settings tab of the Azure Portal. The reasons are:
I want to deploy multiple instances of this applications, each with its own unique iKey
I want to change this iKey periodically (because reasons)
I don't want this iKey stored in our code repository (it's okay for a "dev" iKey to be in code repo) nor do I want it to be managed by our build automation (again, because reasons)

Here is the implementation that I am currently using, and it seems to work. However, I had other implementations that seemed to set the iKey either too early or too late as it seemed it would use the iKey in the physical web.config file deployed to Azure instead of pulling from the Application settings tab from the Portal. Are there better options to do this in a best practice sort of way?
ApplicationInsights.config
<!-- Find the following node and *remove* it. It will have a GUID in it.
If you leave this, you may receive some errors even with all of the
other changes. -->
<InstrumentationKey>{GUID HERE}</InstrumentationKey>
Global.asax.cs
protected void Application_Start()
{
// Add this first line below
Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration.Active.InstrumentationKey =
ConfigurationManager.AppSettings["ai:InstrumentationKey"];
// Showing the rest of this so you can see the order of operations
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
AutomapperConfig.Init();
}
web.config
<!-- Add the following to <appSettings> and put your iKey value in here. -->
<add key="ai:InstrumentationKey" value="*****" />
_Layout.cshtml (in the <head> section of the HTML. NOTE TO FUTURE READERS: I recommend you don't use this entire snippet but instead just use the line that begins instrumentationKey: and integrate that line into whatever the modern version is for the rest of this JS snippet!):
<script type = 'text/javascript' >
var appInsights=window.appInsights||function(config)
{
function r(config){ t[config] = function(){ var i = arguments; t.queue.push(function(){ t[config].apply(t, i)})} }
var t = { config:config},u=document,e=window,o='script',s=u.createElement(o),i,f;for(s.src=config.url||'//az416426.vo.msecnd.net/scripts/a/ai.0.js',u.getElementsByTagName(o)[0].parentNode.appendChild(s),t.cookie=u.cookie,t.queue=[],i=['Event','Exception','Metric','PageView','Trace','Ajax'];i.length;)r('track'+i.pop());return r('setAuthenticatedUserContext'),r('clearAuthenticatedUserContext'),config.disableExceptionTracking||(i='onerror',r('_'+i),f=e[i],e[i]=function(config, r, u, e, o) { var s = f && f(config, r, u, e, o); return s !== !0 && t['_' + i](config, r, u, e, o),s}),t
}({
instrumentationKey:'#(Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration.Active.InstrumentationKey)'
});
window.appInsights=appInsights;
appInsights.trackPageView();
</script>

All of the methods you specified are great. Our recommendation is to use a web.config app setting and using this in the global.asax.cs for standard initialization. No telemetry will be sent before the initlization as we hook into OnBeginRequest().
https://learn.microsoft.com/en-us/azure/application-insights/app-insights-api-custom-events-metrics#a-namedynamic-ikeya-dynamic-instrumentation-key
Another method that might work well is to set the APPINSIGHTS_INSTRUMENTATIONKEY environment variable as it's picked up by the SDK. Of course that depends on if you have multiple apps on the same machine.
https://github.com/Microsoft/ApplicationInsights-dotnet/blob/v2.2.0/src/Core/Managed/Net40/Extensibility/Implementation/TelemetryConfigurationFactory.cs#L22

Related

Genexus Extensions SDK - Where can I find the avaliable Menu Context strings?

Im trying to use the Genexus Extensions SDK to place buttons on the IDE, in this case, i want to place it in the "context" menu, avaliable only in objects of type "Webpanel/Webcomponent" and "Transaction", Just like WorkWithPlus does here:
So far, digging up into the avaliable documentation, i've noticed that you need tu put the context type string into the xml tag and the GUID of the package that you're aiming to add the menu item, such as below in GeneXusPackage.package:
The Context ID above will add the item into the "Folder View" Context.
My questions:
Where can I find a list with all the possible ID Context strings?
What is that package attribute for, where can i get it's possible values?
I am using the SDK for Genexus 16 U11
I'm sorry to say that there is no extensive list of all the menus available. I'd never thought of it until now, and I see how it could be useful, so we'll definitely consider making it part of the SDK so that any package implementor may use it for reference.
In the meantime, in order to add a new command in the context menu you mentioned, you have to add it to the command group that is listed as part of that menu. That group is KBObjectGrp which is provided by the core shell package whose id is 98121D96-A7D8-468b-9310-B1F468F812AE.
First define your command in your .package file inside a Commands section:
<Commands>
<CommandDefinition id='MyCommand' context='selection'/>
</Commands>
Then add it to the KBObjectGrp mentioned earlier.
<Groups>
<Group refid='KBObjectGrp' package='98121D96-A7D8-468b-9310-B1F468F812AE'>
<Command refid='MyCommand' />
</Group>
</Groups>
Then in order to make your command available only to the objects you said before, you have to code a query handler for the command, that will rule when the command is enabled, disabled, or not visible at all. You can do that in the Initialize method of your package class.
public override void Initialize(IGxServiceProvider services)
{
base.Initialize(services);
CommandKey myCmdKey = new CommandKey(Id, "MyCommand");
AddCommand(myCmdKey, ExecMyCommand, QueryMyCommand);
}
private bool QueryMyCommand(CommandData data, ref CommandStatus status)
{
var selection = KBObjectSelectionHelper.TryGetKBObjectsFrom(data.Context).ToList();
status.Visible(selection.Count > 0 && selection.All(obj => obj.Type == ObjClass.Transaction || obj.Type == ObjClass.WebPanel));
return true;
}
private bool ExecMyCommand(CommandData data)
{
// Your command here
return true;
}
I'm using some helper classes here in order to get the objects from the selection, and then a class named ObjClass which exposes the guid of the most common object types. If you feel something isn't clear enough, don't hesitate to reach out.
Decompiling the Genexus dll and looking for the resource called package, you can infer what the names are.
It's cumbersome but it works

Hangfire job on Console/Web App solution?

I'm new to Hangfire and I'm trying to understand how this works.
So I have a MVC 5 application and a Console application in the same solution. The console application is a simple one that just updates some data on the database (originally planned to use Windows Task Scheduler).
Where exactly do I install Hangfire? In the Web app or the console? Or should I convert the console into a class on the Web app?
If I understand it correctly, the console in your solution is acting like an "pseudo" HangFire, since like you said it does some database operations overtime and you plan to execute it using the Task Scheduler.
HangFire Overview
HangFire was design to do exactly what you want with your console app, but with a lot more of power and functionalities, so you avoid all the overhead of creating all that by yourself.
HangFire Instalation
HangFire is installed commonly alongside with ASP.NET Applications, but if you carefully read the docs, you will surprisingly find this:
Hangfire project consists of a couple of NuGet packages available on
NuGet Gallery site. Here is the list of basic packages you should know
about:
Hangfire – bootstrapper package that is intended to be installed only
for ASP.NET applications that uses SQL Server as a job storage. It
simply references to Hangfire.Core, Hangfire.SqlServer and
Microsoft.Owin.Host.SystemWeb packages.
Hangfire.Core – basic package
that contains all core components of Hangfire. It can be used in any
project type, including ASP.NET application, Windows Service, Console,
any OWIN-compatible web application, Azure Worker Role, etc.
As you can see, HangFire can be used in any type of project including console applications but you will need to manage and add all the libraries depending on what kind of job storage you will use. See more here:
Once HangFire is Installed you can configure it to use the dashboard, which is an interface where you can find all the information about your background jobs. In the company I work, we used HangFire several times with recurring jobs mostly to import users, synchronize information across applications and perform operations that would be costly to run during business hours, and the Dashboard proved to be very useful when we wanted to know if a certain job was running or not. It also uses CRON to schedule the operations.
A sample of we are using right now is:
Startup.cs
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
//Get the connection string of the HangFire database
GlobalConfiguration.Configuration.UseSqlServerStorage(connection);
//Start HangFire Server and enable the Dashboard
app.UseHangfireDashboard();
app.UseHangfireServer();
//Start HangFire Recurring Jobs
HangfireServices.Instance.StartSendDetails();
HangfireServices.Instance.StartDeleteDetails();
}
}
HangfireServices.cs
public class HangfireServices
{
//.. dependency injection and other definitions
//ID of the Recurring JOBS
public static string SEND_SERVICE = "Send";
public static string DELETE_SERVICE = "Delete";
public void StartSend()
{
RecurringJob.AddOrUpdate(SEND_SERVICE, () =>
Business.Send(), //this is my class that does the actual process
HangFireConfiguration.Instance.SendCron.Record); //this is a simple class that reads an configuration CRON file
}
public void StartDeleteDetails()
{
RecurringJob.AddOrUpdate(DELETE_SERVICE, () =>
Business.SendDelete(), //this is my class that does the actual process
HangFireConfiguration.Instance.DeleteCron.Record); //this is a simple class that reads an configuration CRON file
}
}
HangFireConfiguration.cs
public sealed class HangFireConfiguration : ConfigurationSection
{
private static HangFireConfiguration _instance;
public static HangFireConfiguration Instance
{
get { return _instance ?? (_instance = (HangFireConfiguration)WebConfigurationManager.GetSection("hangfire")); }
}
[ConfigurationProperty("send_cron", IsRequired = true)]
public CronElements SendCron
{
get { return (CronElements)base["send_cron"]; }
set { base["send_cron"] = value; }
}
[ConfigurationProperty("delete_cron", IsRequired = true)]
public CronElements DeleteCron
{
get { return (CronElements)base["delete_cron"]; }
set { base["delete_cron"] = value; }
}
}
hangfire.config
<hangfire>
<send_cron record="0,15,30,45 * * * *"></send_cron>
<delete_cron record="0,15,30,45 * * * *"></delete_cron>
</hangfire>
The CRON expression above will run at 0,15,30,45 minutes every hour every day.
Web.config
<configSections>
<!-- Points to the HangFireConfiguration class -->
<section name="hangfire" type="MyProject.Configuration.HangFireConfiguration" />
</configSections>
<!-- Points to the .config file -->
<hangfire configSource="Configs\hangfire.config" />
Conclusion
Given the scenario you described, I would probably install HangFire in your ASP.NET MVC application and remove the console application, simple because it is one project less to worry about. Even though you can install it on a console application I would rather not follow that path because if you hit a brick wall (and you'll hit, trust me), chances are you'll find help mostly for cases where it was installed in ASP.NET applications.
No need of any more console application to update the database. You can use hangfire in your MVC application itself.
http://docs.hangfire.io/en/latest/configuration/index.html
After adding the hangfire configuration, you can make use of normal MVC method to do the console operations like updating the DB.
Based on your requirement you can use
BackgroundJob.Enqueue --> Immediate update to DB
BackgroundJob.Schedule --> Delayed update to DB
RecurringJob.AddOrUpdate --> Recurring update to DB like windows service.
Below is an example,
public class MyController : Controller
{
public void MyMVCMethod(int Id)
{
BackgroundJob.Enqueue(() => UpdateDB(Id));
}
public void UpdateDB(Id)
{
// Code to update the Database.
}
}

Inject bridge-code in JavaFX WebView before page-load?

I want to load some content or page in a JavaFX WebView and offer a Bridge object to Java so the content of the page can do calls into java.
The basic concept of how to do this is described here: https://blogs.oracle.com/javafx/entry/communicating_between_javascript_and_javafx
Now my question is: When is a good time inject the bridge-object into the WebView so it is available as soon as possible.
One option would be after page load as described here: https://stackoverflow.com/a/17612361/1520422
But is there a way to inject this sooner (before the page content itself is initialized), so the bridge-object is available DURING page-load (and not only after page-load)?
Since no one has answered, I'll tell you how I'm doing it, although it is ugly. This provides the ability for the page to function normally in non-Java environments but receive a Java object in Java environments.
I start by providing an onStatusChanged handler to the WebEngine. It listens for a magic value for window.status. If the magic value is received, the handler installs the Java object. (In my case, it's more complex, because I have some more complex orchestration: I'm executing a script that provides a client-side API for the page and then sets another magic value on window.status to cause the Java object to be sent to an initialization method of the client-side API).
Then in my target page, I have the following code in the first script in the page:
window.status = "MY-MAGIC-VALUE";
window.status = "";
This code is essentially a no-op in a "normal" browser but triggers the initialization when running in the custom JavaFX embedding.
In Java 8, you can trigger event changing from SCHEDULED to RUNNING to inject objects at this time. The objects will present in WebEngine before JavaScript running. Java 7, I see the state machine quite differs in operating, no solution given for Java 7.
webEngine.getLoadWorker().stateProperty().addListener(
new ChangeListener<State>(){
public void changed(ObservableValue<? extends State> ov,
State oldState,
State newState)
{
// System.out.println("old: "+oldState+", new: "+newState);
if(newState == State.RUNNING &&
oldState == State.SCHEDULED){
JSObject window = (JSObject)webEngine.executeScript("window");
window.setMember("foutput", foutput);
}
}
});

Enabling bundling and minification on 3rd party libraries

I am including a big javascript application into our MVC-based solution. However, the application includes a lot of files due to which I would like to enable bundling and minification on it. In fact, I would like to enable bundling on all 3rd party javascript and CSS files while keeping the files we develop ourselves unminified and unbundled. Until release, of course.
There is way to enable optimizations globally:
public static void RegisterBundles(BundleCollection bundles)
{
Bundle ckScripts = new ScriptBundle("~/scripts/ckeditor")
.IncludeDirectory("~/Areas/CMS/Editor", "*.js", true);
bundles.Add(ckScripts);
BundleTable.EnableOptimizations = true;
}
However, this happens in the top BundleTable level enabling optimizations on all the bundles within the bundle table.
I would need to have something like this:
public static void RegisterBundles(BundleCollection bundles)
{
Bundle ckScripts = new ScriptBundle("~/scripts/ckeditor")
.IncludeDirectory("~/Areas/CMS/Editor", "*.js", true)
.EnableOptimizations();
bundles.Add(ckScripts);
}
Which would effectively enable optimizations only for that particular bundle.
I know, there is currently no Bundle.EnableOptimizations() method and creating such given the fact that the optimization happens in the BundleTable level, which is inherently global by design, creating such method, would prove very difficult.
So, here I in loss of ideas where to look into.
Questions:
Is there an alternative framework somewhere that would support this
Is there a contrib project somewhere that would provide this
Have you encountered such need, possibly have a solution
Provided that there's no existing solution, please post an idea how to start unfolding this challenge.
From what I know, BundleTable is a singleton. Which means there can be only one instance. I had an idea of creating another bundle table but got lost when I started figuring out how to make MVC use it.
Another starting point would be to code a custom renderer. One that mimics the behavior of System.Web.Optimization.Scripts.Render(), but again, I'm getting lost with it trying to figure out in which state the BundleTable comes into picture.
UPDATE
Seems like I can create a new BundleContext and BundleResponse by using a HtmlHelper.
public static IHtmlString RenderBundled<TSource>(this HtmlHelper<TSource> helper, string bundlePath)
{
// Find the bundle in question
var bundle = BundleTable.Bundles.FirstOrDefault(b => b.Path == bundlePath);
// No bundle found, return
if (bundle == null) return MvcHtmlString.Create(String.Empty);
// Add the bundle found into a new collection
BundleCollection coll = new BundleCollection {bundle};
// Create a new BundleContext
BundleContext ctx = new BundleContext(helper.ViewContext.HttpContext, coll, "~/bundles");
// Enable optimizations
ctx.EnableOptimizations = true;
// Create the response (this contains bundled & minified script/styles from bundle)
BundleResponse response = bundle.GenerateBundleResponse(ctx);
// Render the content based on ContentType
if (response.ContentType == "text/css")
return RenderStyle(response.Content);// returns <style>bundled content</style>
if (response.ContentType == "text/javascript")
return RenderScript(response.Content); // returns <script>bundled content</script>
// In any other case return "nothing"
return MvcHtmlString.Create(String.Empty);
}
This probably is not the best approach. Overhead from creating BundleContext on every page request and adding the script/styles payload into the page output without the caching abilities. But it's a start. One thing I noticed was that the bundled content will actually be cached in HttpContext.Cache. So, theoretically I could just put the bundle path into script src or style href and somehow then handle the request from server side.

Is there any way to specify a service name in the app.config file?

I want to specify my service name in the app.config without needing to recomple and install/uninstall my service repeatedly.
But just retrieving service name from app.config, the service seems ignoring it. Are there any special tricks how to obtain this?
Thanks in advance.
I mean classic windows service. I don't think any code is needed here. I just want to retrieve the service name from app.config dynamically.
After searching a while on the internet and reading articles, it became clearer to me that A service name can't be specified in the app.config in so dynamic way, instead sc command can be used to perform a similar solution. You can specify other configuration variables in the app.config and use sc to rename it
sc.exe create "servicename" binPath="myservicepath.exe"
I am not sure what scenario you have in mind. You would like the name of your Windows service to change. Fair enough. When would it change?
Imagine you have found the solution and created such a Windows service. I presume in your scenario you would install it at least the first time. Then you do not want to uninstall/install it. But presumably you would like to start/stop and do other things with it. Will one of those actions cause the name of the service to change?
If so, I imagine you could launch a process that uninstalls and installs it with a different name for you transparently, based on some kind of naming logic.
I don't see how else you could do it.
Or just come up with a really generic name to cover all possibilities (which might be incredibly simple or incredibly difficult).
http://www.codeproject.com/Articles/21320/Multiple-Instance-NET-Windows-Service
<add key="ServiceName" value="I"/>
[RunInstaller(true)]
public class ServiceInstaller1 : Installer
{
internal static string ServiceNameDefault = "My Service";
internal static string ServiceName = GetConfigurationValue("ServiceName");
/// <summary>
/// Public Constructor for WindowsServiceInstaller.
/// - Put all of your Initialization code here.
/// </summary>
public ServiceInstaller1()
{
var serviceProcessInstaller = new ServiceProcessInstaller();
var serviceInstaller = new ServiceInstaller();
//# Service Account Information
serviceProcessInstaller.Account = ServiceAccount.LocalSystem;
//serviceProcessInstaller.Username = null;
//serviceProcessInstaller.Password = null;
//# Service Information
serviceInstaller.DisplayName = ServiceName;
serviceInstaller.StartType = ServiceStartMode.Manual;
//# This must be identical to the WindowsService.ServiceBase name
//# set in the constructor of WindowsService.cs
serviceInstaller.ServiceName = ServiceName;
Installers.Add(serviceProcessInstaller);
Installers.Add(serviceInstaller);
}
private static string GetConfigurationValue(string key)
{
Assembly service = Assembly.GetAssembly(typeof(Service));
Configuration config = ConfigurationManager.OpenExeConfiguration(service.Location);
if (config.AppSettings.Settings[key] != null)
return ServiceNameDefault + " " + config.AppSettings.Settings[key].Value;
else
return ServiceNameDefault;
}
}
Assuming you mean Windows Service, the answer is no. The service has to be installed in the registry, and the name is one of the registry keys.
I'm afraid that what you are trying to do its not possible. It actually seems to go against the nature of a Windows Service purpose and current behavior.
After a windows service is installed the name can't be changed without re-installing it again. What actually names the service is an element called service installer. Which by now, I assume you know what it is and where its located.
However there are ways of manipulating an installed service by using Windows Management Instrumentation (WMI). Maybe this combined with Izabela's recommendation become the right path to your solution.
I would recommend you to read the following tutorial, you might find an alternate way of achieving what you're trying to do.
http://www.serverwatch.com/tutorials/article.php/1576131/Windows-Services-Management-With-WMI-Part-1.htm

Resources