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.
Related
Can someone explain me the difference between Web services & web API? I have gone through so many blogs but all of them seems to be using the same bookish knowledge. What's the actual difference between them in real terms?
As #Dai explained the zest and I completely agree with him. In addition, I would like to provide you some real-life difference besides.
Web Service:
As Web Service basically, used WSDL which used to communicate with SOAP or XML base service. However, the main challenge in Web Service was to handle cross-platform request. We used to add service reference as following way: While developped Web Services.
Web API:
Considering these drawbacks, Microsoft, latter on developed the Web API more specifically, Asp.net Web API which provide the robust functionality for cross platform development using REST pattern mostly used Json data. It doesn’t mean that web service cannot do that, but not robust as Web API now a days. Unlike, web service we don’t need to go through any integration hassle as above which we can directly develop using asp.net core project and can open the route to call from anywhere.For instance below example:
[ApiController]
[Route("api/VehicleFilter")]
public class VehicleFilterController : ControllerBase
{
private readonly ApplicationDbContext _context;
private readonly IWebHostEnvironment _environment;
public VehicleFilterController(IWebHostEnvironment environment, ApplicationDbContext context)
{
_environment = environment;
_context = context;
}
[HttpGet]
public async Task<IActionResult> GetAllFilter()
{
string VehicleName = "Hatchback";
var sqlCommand = $"EXEC GetVehicleByTile {VehicleName}";
var vehicleFilterValues = await _context.VehicleFilter.FromSqlRaw(sqlCommand).ToListAsync();
return Ok(vehicleFilterValues);
}
}
To summarize, Web API provides more flexibility and robustness and of course its lightweight while writing any new method. Where web service leads to some demerits to the developer.
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.
I am preparing to port an .NET 4.6.1 application to .NET Core and struggle to find how the code permissions should be handled.
Currently i use custom ClaimsAuthorizationManager
public class AuthorizationManager : ClaimsAuthorizationManager
{
public override bool CheckAccess(AuthorizationContext context)
{
var resource = context.Resource.First().Value;
var action = context.Action.First().Value;
return context.Principal.HasClaim(resource,action);
}
}
The ClaimsAuthorizationManager is configured to be used by application in app.config file.
Then each function that needs to have a code access permission has an ClaimsPrincipalPermission set with required permissions.
Now i would want to achieve same functionality in .NET Core and outside of MVC.
Anyone has any idea if and how is this achievable?
Thanks.
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 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.