I am trying to take the github ServiceStack.UseCases/ImageResizer project, and make it self hosted. I thought this would be really easy, so I referenced this: https://github.com/ServiceStack/ServiceStack/wiki/Self-hosting but AppSelfHostBase is undefined in the project. I then tried AppHostHttpListenerBase and that got me to the point where I could at least hope to setup my self host:
public class AppHost : AppHostHttpListenerBase
{
public AppHost() : base("Image Resizer", typeof(AppHost).Assembly) {}
public override void Configure(Container container) {}
}
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
AppHost appHost = new AppHost();
appHost.Init();
appHost.Start("http://*:1301/");
}
}
I then transferred the project over to my CentOS box with mono. In monodevelop I was able to build and run, but it failed during runtime. It appears it still thinks it is an Mvc or Asp.Net project.
Aside from this attempt, I have a working self hosted ServiceStack project running there, but it is not this ImageResizer and all attempts to get my existing project to include the new project have also failed.
I also tried to include code that was part of the working self hosted project into the new one, but then symbols are undefined. Basic symbols like "ServiceStackHost". If I start trying to use Nuget and do more "Install-Package" I can solve this symbol problem, but then just cause other symbols that used to be resolved to no longer work. I don't really fully understand Nuget. Any ideas for a way forward would be appreciated.
ServiceStackHost and AppSelfHostBase are new classes added in ServiceStack v4.
You can use AppHostHttpListenerBase which is a Self-hosting class in ServiceStack v3. You're looking at the v4 docs, here are the docs for ServiceStack v3 which for Self-Hosting is at:
https://github.com/ServiceStackV3/ServiceStackV3/wiki/Self-hosting
Self-Hosting apps are normally created in a Console Application where-as your example is trying to run a self-hosting app inside an ASP.NET Web Application. If you want to run ServiceStack in an ASP.NET app you should inherit AppHostBase, otherwise if you want to run a self-hosting application, create a new Console Application and inherit from AppHostHttpListenerBase.
Related
I've configured Live Metrics for my ASP.NET MVC app with target framework 4.7.2 using the tutorial given in Microsoft Docs:
https://learn.microsoft.com/en-us/azure/azure-monitor/app/live-stream#enable-livemetrics-using-code-for-any-net-application
In this tutorial, they've given a sample client.TrackDependency() and client.TrackRequest() call in the end. They've also mentioned in comments that those are samples and we must replace it with actual application logic to work. I'm new to all these and I don't know what to replace. Since my application is huge and has a lot of methods, it is impractical to call the tracking methods in each method or controller. Since it is not ASP.NET Core, there are no middlewares and I have to enable Live Metrics by code too. I've added the code in the Application_Start() of Global.asax.cs of my application, so that it runs during startup.
This is what I've done so far,
// Create a TelemetryConfiguration instance.
Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration telemetryConfig = Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration.CreateDefault();
telemetryConfig.InstrumentationKey = System.Web.Configuration.WebConfigurationManager.AppSettings["AppInsightsInstrumentationKey"];
QuickPulseTelemetryProcessor quickPulseProcessor = null;
telemetryConfig.DefaultTelemetrySink.TelemetryProcessorChainBuilder
.Use((next) =>
{
quickPulseProcessor = new QuickPulseTelemetryProcessor(next);
return quickPulseProcessor;
})
.Build();
var quickPulseModule = new QuickPulseTelemetryModule();
// Secure the control channel.
// This is optional, but recommended.
//quickPulseModule.AuthenticationApiKey = "YOUR-API-KEY-HERE";
quickPulseModule.Initialize(telemetryConfig);
quickPulseModule.RegisterTelemetryProcessor(quickPulseProcessor);
// Create a TelemetryClient instance. It is important
// to use the same TelemetryConfiguration here as the one
// used to setup Live Metrics.
TelemetryClient client = new TelemetryClient(telemetryConfig);
// I need some method by which I can track all the requests, exceptions,
// dependencies etc. here.
I searched and searched a lot for a solution but couldn't get a concrete solution. As a last resort I'm requesting you guys to help me. What can I do to track all requests, dependencies, exceptions, etc. globally...?
If you're using the ASP .NET MVC with .Net Framework 4.7.2 Version, You need to configure the Application Insights code related to the .NET Specific SDK Type like Framework, Core, Console, etc.
From the given MS doc, you're following the console app related app insights code but as you're using the MVC Web App so you need to follow this code from this section of documentation.
Here is the workaround I tried to get the live metrics, logs in the Application Insights of Azure Portal.
In Visual Studio, Created the asp .net mvc web app (.NET Framework version 4.7.2)
Added the Application Insights Instrumentation Key in the ApplicationInsights.config
Follow the above documentation as it says to create a new folder in the root and add the ErrorHandler class and modify the FilterConfig class from the App_Start folder in order to match your ErrorHandler Class Functionality.
And then deploy the MVC Web App. While publishing configure the Application Insights in Visual Studio Publish Window like below:
After deploying the App, Open the Web App URL in the browser, then you can see the logs in overview tab and also in App Insights Resource Live Metrics Page as you can see the screenshots below:
I found a solution myself. I found out that I can use the Application_BeginRequest() event handler to catch all requests inside Global.asax itself. All I had to do is to store the TelemetryConfiguration into a global variable and access it from the Application_BeginRequest() handler. This is what I did:
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.QuickPulse;
protected void Application_Start()
{
RegisterLiveMetrics();
// Omitted the other code for brevity
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
var telemetryConfig = Application["TelemetryConfig"] as TelemetryConfiguration;
TelemetryClient client = new TelemetryClient(telemetryConfig);
var httpContextCurrent = HttpContext.Current;
client.TrackRequest(httpContextCurrent.Request.RawUrl, DateTimeOffset.Now,
TimeSpan.FromMilliseconds(230), httpContextCurrent.Response.StatusCode.ToString(),
true);
}
private void RegisterLiveMetrics()
{
// Create a TelemetryConfiguration instance.
Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration telemetryConfig = Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration.CreateDefault();
telemetryConfig.InstrumentationKey = System.Web.Configuration.WebConfigurationManager.AppSettings["AppInsightsInstrumentationKey"];
QuickPulseTelemetryProcessor quickPulseProcessor = null;
telemetryConfig.DefaultTelemetrySink.TelemetryProcessorChainBuilder
.Use((next) =>
{
quickPulseProcessor = new QuickPulseTelemetryProcessor(next);
return quickPulseProcessor;
})
.Build();
var quickPulseModule = new QuickPulseTelemetryModule();
quickPulseModule.Initialize(telemetryConfig);
quickPulseModule.RegisterTelemetryProcessor(quickPulseProcessor);
Application["TelemetryConfig"] = telemetryConfig;
}
Luckily this seems to work fine. Currently I'm only tracking requests.
Note: I'm not sure about the namespaces mentioned above.
As the title says,
How can I set up a middleware in a .NET Core 3.1 Azure Functions project? trying to dependency inject an external service that requires middleware.
First off, there are some problems here.
The Function app you create in Visual Studio 19, doesn't contain a Startup.cs class.
So we have to create this manually. Then there's a problem that it's not behaving like a real Startup class. It needs to inherit FunctionsStartup.
This is achieved by adding this line of code before the namespace first for some reason.
[assembly: FunctionsStartup(typeof(test_project.Startup))]
Then we need to inherit FunctionsStartup and then implement it.
public override void Configure(IFunctionsHostBuilder builder)
{
}
So after this, we are able to Add stuff like Singleton or external service like so,
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddSomeExternalService();
builder.Services.AddSingleton<SomeOtherStuff>(
new SomeOtherStuff(config, env_SomeOtherStuff));
}
But now my real problem starts. We need to add middleware for some functionality to work in the external service.
Usually, you can do this in a web applications (not function app) like so,
public void Configure(IApplicationBuilder app)
{
app.UseSomeExternalServiceMiddleware();
}
The problem is, I can't figure out how to do this in a function app with core 3.1
maybe it's not implemented the same way, I don't know why.
Is there a workaround for this sort of problem?
There is no direct way to do this but there is a proposed feature that you can refer to.
More References :
Dependency Injection in Azure Functions with C# (twilio.com)
c# - Azure Functions Runtime v3 Middleware - Stack Overflow
Be able to overwrite http response in IFunctionsWorkerMiddleware · Issue #530 · Azure/azure-functions-dotnet-worker · GitHub
I'm currently trying to integrate postsharp with my asmx web service for the purpose of logging exceptions.
Here's my code for the Aspect perspective:
[Serializable]
public class LogPerformance : OnMethodBoundaryAspect
{
public override void OnEntry(MethodExecutionArgs args)
{
string test = "test";
base.OnEntry(args);
}
public override void OnExit(MethodExecutionArgs args)
{
string test = "test";
base.OnExit(args);
}
public override void OnException(MethodExecutionArgs args)
{
string test = "test";
base.OnException(args);
}
}
while in my Service.cs class, i've the following web method:
[WebMethod(EnableSession = true)]
[SoapHeader("authentication")]
[LogPerformance]
public DataTable loginUser(string userName, string password)
{
doStuff();
}
Coming straight to the point:
Does postsharp support implementation with web methods? As in my case,
postSharp methods does not get called whenever the web method receives
a hit. (Yes i've added postsharp reference using Nuget and/or/plus manually added its dll as well) This does
suggest a step towards the mentioned subject but i could not make anything
out of it.
It is important to note that the same LogPerformance Class runs smoothly when integrated with:
Web API
ASP.Net Web Application (MVC)
Console Application
The problem is when i use it with .asmx web service. A little nudge towards the right direction would be appreciated.
The *.asmx web-services are supported by PostSharp. However, you need to pay attention whether your ASP.NET project is a Web Site or a Web Application (ASP.NET Web Site or ASP.NET Web Application?). Only Web Application projects are supported by PostSharp. For more information on compatibility you can also check Requirements and Compatibility.
You can convert your Web Site project to Web Application project by following the guidelines from the blog post Converting a Web Site Project to a Web Application Project. After the conversion you need to install PostSharp NuGet package into your project.
We are delivering an ASP.NET MVC application built with Sitecore to a client that deploys the application to a multi site/tenant Sitecore installation.
We make heavy use of ServiceStack as we do on most of our projects, but have run into an issue now. Another application in the Sitecore setup is also using ServiceStack. This causes the error:
[InvalidDataException: AppHostBase.Instance has already been set]
Which makes perfect sense really, because all files for all the applications in the Sitecore installation is in the same physical folder on disk. Meaning we share DLL's and everything.
So this other project initializes before ours and when we then try to register our services we get the above error.
Is there any way I can work around this? Can I somehow register my services on the already existing AppHostBase.Instance?
Two things that might be worth noting:
We do not have any influence on the setup of the Sitecore environment.
We can work together with the other team using ServiceStack if something has to be done in both projects.
Preferably you would tell ServiceStack all the assemblies with Services you want registered in your AppHost constructor, e.g:
public class AppHost : AppHostBase
{
//Tell ServiceStack the name of your app and which assemblies to scan for services
public AppHost() : base("Hello ServiceStack!",
typeof(ServicesFromDll1).Assembly,
typeof(ServicesFromDll2).Assembly
/*, etc */) {}
public override void Configure(Container container) {}
}
But you can dynamically Register Services outside of ServiceStack with:
HostContext.ServiceController.RegisterService(typeof(MyService));
Or register all Services in an Assembly with:
HostContext.ServiceController.
RegisterServicesInAssembly(typeof(MyService).Assembly);
I have constructed an API using webapi2.2.
When I deploy the API to Azure I get the Service Unhealthy Message...when I check the logs of my API the log gives the error message
"Boot strapping failed: executing 'WebApiConfig.Register' caused an
exception: 'Parameter count mismatch.'.
The Application Start function is below
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
And my WebApiConfig.cs has the following:
public static void Register(HttpConfiguration config)
{
config.EnableCors();
config.Formatters.JsonFormatter.
SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));.......
Another question here: The api implements its own Security mechanism (I used the following as a reference http://bitoftech.net/2014/12/15/secure-asp-net-web-api-using-api-key-authentication-hmac-authentication/). Would this implementation work in Azure or would you have to make use of the x-zumo header authorisation mechanism?
I found the resolution to this - I believe that the problem is caused by the fact that I have another mobile services app running in my Azure account. That app was built awhile ago - early 2015 and used the register procedure with no parameters
public static void Register(){.....}
I think that this may have confused the service operation (the fact that one app has a register without parameters and the other has a register with one parameter). To resolve the issue with my new app I removed the config parameter, and build the config settings in the register function see below
public static void Register()
{
ConfigOptions options = new ConfigOptions();
HttpConfiguration config = ServiceConfig.Initialize(new ConfigBuilder(options));
config.EnableCors();.....
Remember though you will need access to the using Microsoft.WindowsAzure.Mobile.Service namespace...this can be obtained by installing the nuget package WindowsAzure.MobileServices.Backend
Hope this helps someone who has similar problems