Developing a Module for IIS7 - c#

I've been working on a module for IIS7. I want to intercept requests from a specific browser. This is only in dev, but right now my code looks like this:
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
namespace MyNamespace
{
class MyModule : IHttpModule
{
#region IHttpModule Members
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.PreRequestHandlerExecute += new EventHandler(OnPreRequestHandlerExecute);
}
#endregion
public void OnPreRequestHandlerExecute(Object source, EventArgs e)
{
HttpApplication app = (HttpApplication)source;
HttpRequest request = app.Context.Request;
string useragent = "AGENT: " + request.Headers["User-Agent"];
throw new HttpException(403, useragent);
// stuff here
}
}
}
I want to test this, but despite reading NUMEROUS articles on adding it to IIS7, I can't seem to get it working.
Examples:
http://learn.iis.net/page.aspx/366/developing-iis-70-modules-and-handlers-with-the-net-framework/
http://learn.iis.net/page.aspx/269/how-to-create-a-simple-iis-manager-module/
I've got the module strongly named, signed, you name it. I can't seem to get it to show up under Managed Modules for IIS.
If someone who has experience in this area could point me in the right direction I would greatly appreciate it! The code is very incomplete and I don't expect it to be perfect, but just to get it working under IIS7 right now would be a huge step forward.
Thanks!

You can simply drop the MyNameSpace.dll file in the bin folder, and then reference it like this in the section of the web.config:
<add name="MyModuleName" type="MyNamespace.MyModule, MyNamespace" preCondition="managedHandler" />

Related

Restrict IP Address to access Web Application

I have publish my Web Application in IIS and I getting Error while running
Server Error in '/' Application.
Configuration Error
Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.
Parser Error Message: Could not load type 'SecurityHttpModule'.
My Web Config Like
<httpModules>
<add name="SecurityHttpModule type="SecurityHttpModule"/>
</httpModules>
My SecurityHttpModule Like
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
public interface IHttpModule
{ }
namespace BankSuite
{
public class SecurityHttpModule : IHttpModule
{
public SecurityHttpModule() { }
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(Application_BeginRequest);
}
private void Application_BeginRequest(object source, EventArgs e)
{
HttpContext context = ((HttpApplication)source).Context;
string ipAddress = context.Request.UserHostAddress;
if (!IsValidIpAddress(ipAddress))
{
context.Response.StatusCode = 403; // (Forbidden)
}
}
private bool IsValidIpAddress(string ipAddress)
{
return (ipAddress == "127.0.0.1");
}
public void Dispose() { /* clean up */ }
}
}
It seems like you are missing a closing quote on the name
make sure it is not like that in reall config
Try specify using Fully qualified name such as NamespaceQualifiedTypeName, AssemblyName
so something like BankSuite.SecurityHttpModule, AssemblyName - where AssemblyName correspond to your dll name
also if you are using iis 7+ with integrated mode, use
<configuration>
<system.webServer>
<modules>
<add name="SecurityHttpModule" type="BankSuite.SecurityHttpModule, AssemblyName"/>
</modules>
</system.webServer>
</configuration>
instead.

Cannot create an instance of the abstract class or interface on WCF Silverlight Service

I'm working through two tutorials to create a super simple WCF web service and Silverlight app.
Buiding a Service
Accessing a Service from Silverlight
Everything was going fine. I created my service:
using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
namespace TestOnline.Web.Data
{
[ServiceContract(Namespace = "")]
[SilverlightFaultBehavior]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class DataService
{
[OperationContract]
public String TestService()
{
return "Service Worked!";
}
}
}
I added it as a service reference, then tried to create an instance but I'm getting the error "Cannot create an instance of the abstract class or interface" on the line "proxy = new DataService();"
I pretty much followed the steps of the tutorial exactly, I'm unsure what I've missed. I've certainly not seen many Service examples with constructors, and the reference code is auto-generated - so I don't want to go adding them manually to that.
Does anyone know of a solution/what I've done wrong? Thanks
using System.ServiceModel;
using TestOnline.ServiceReference1;
namespace TestOnline
{
public partial class MainPage : UserControl
{
DataService proxy;
public MainPage()
{
InitializeComponent();
proxy = new DataService();
}
private void TestServiceButton_Click(object sender, RoutedEventArgs e)
{
//call service and get response
}
}
}
You should be creating an instance of the generated proxy client class.
It'll be named DataServiceClient() if it's been added correctly.

MVC global exceptions

I am coding an MVC 5 internet application, and I have a question in regards to handling exceptions globally.
I have my Application_Error setup in my global.asax file. This caters to errors such as 404 HttpExceptions.
How can I send all errors that occur in a controller to the Application_Error function? An example is the following exception:
System.Web.HttpRequestValidationException: A potentially dangerous
Request.Form value was detected from the client (name="").
I have written a OnException(ExceptionContext filterContext) for my controller, but am not sure on how to get the Application_Error function to handle these errors. Do I need to pass the exception from the OnException function, or is this the wrong approach?
Thanks in advance.
You can create a global filter by adding the following class to your App_Start folder:-
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
HandleErrorAttribute can be replaced with your own custom Exception Filter.
All you then need to do is make sure you add the following line of code to the App_Start method of your Gloabal.asax :-
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
//AreaRegistration.RegisterAllAreas();
//RouteConfig.RegisterRoutes(RouteTable.Routes);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
}
}
Hope this helps.
I'm using some kind of http-module which gives me exactly what you are asking for:
public class MyModule : IHttpModule {
public void Init(HttpApplication context) {
context.Error += OnRequestError;
}
private void OnRequestError(object sender, EventArgs e) {
var context = ((HttpApplication)sender).Context;
var error = context.Error;
if (error == null)
return;
var errorType = error.GetType();
if (errorType == typeof(HttpException))
// do something
// this is what you are looking for
if (errorType = typeof(HttpRequestValidationException))
// do something, whatever you want
// works for me, so should work to you too
}
}
To get the module to work, you can use web.config or DynamicModuleHelper:
Install Microsoft.Web.Infrastructure and WebActivatorEx via nuget
Add a Bootstrapper class to your project
Register module at PreApplicationStartMethod
Sample:
// File: Bootstrapper.cs (contains class Bootstrapper)
using Microsoft.Web.Infrastructure.DynamicModuleHelper;
using WebActivatorEx;
using WhatEver.It.Is;
[assembly: PreApplicationStartMethod(typeof(Bootstrapper), "Bootstrap")]
namespace WhatEver.It.Is {
public class Bootstrapper {
public static void Bootstrap() {
// Do what do you need just before the application get started
// like registering modules, etc...
DynamicModuleUtility.RegisterModule(typeof(MyModule));
}
}
}

Evaluating ASPX Pages from custom httpHandlers

I have search everywhere for help and its starting to annoy me.
I am creating an Internal Tooling Website which stores Tools and their related information.
My vision is to have a web address (Http://website.local/Tool/ID)
Where ID is the ID of the Tool we want displayed.
My reasoning is then I can extend the functionality of the URL to allow for various other functions.
Currently I use a custom httpHandler which intercepts any URL which is in the 'Tool' Folder.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Tooling_Website.Tool
{
public class ToolHandler : IHttpHandler
{
public bool IsReusable
{
get { return false; }
}
public void ProcessRequest(HttpContext context)
{
//The URL that would hit this handler is: http://{website}/Tool/{AN ID eg: http://{website}/Tool/PDINJ000500}
//The idea is that what would be the page name is now the ID of the tool.
//tool is an ASPX Page.
tool tl = new tool();
System.Web.UI.HtmlTextWriter htr = new System.Web.UI.HtmlTextWriter(context.Response.Output);
tl.RenderControl(htr);
htr.Close();
}
}
}
Basically I have a page inside the 'Tool' folder (Tool\tool.aspx) which I want my customer httpHandler to Render into the Response.
But this method doesn't work (It doesn't fail, just doesn't show anything) I can write the raw file to the response but obviously thats not my goal.
Thanks,
Oliver
If you still want to use your custom approach, you can try to do the following in your IHttpHandler derived class:
public void ProcessRequest(HttpContext context)
{
//NOTE: here you should implement your custom mapping
string yourAspxFile = "~/Default.aspx";
//Get compiled type by path
Type type = BuildManager.GetCompiledType(yourAspxFile);
//create instance of the page
Page page = (Page) Activator.CreateInstance(type);
//process request
page.ProcessRequest(context);
}

How does one use ManagementEventWatcher to keep track of suspend/resume?

I am trying to use ManagementEventWatcher in a service to keep track of when a computer goes in and out of sleep mode. I am new to .NET and C# so I am struggling quite a bit to come up with syntax to make this work.
I have found a blog post that details how he used ManagementEventWatcher to keep track of this status, but he did not post up his entire code. I am trying to go through and make a simple service that creates a .txt log file stating that the computer has been suspended/resumed but am running into problems with the namespaces and types.
Here is the code to the service.cs file:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Management;
namespace SleepNotifierService
{
public class WqlEventQuery : EventQuery { }
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
WqlEventQuery query = new WqlEventQuery("Win32_PowerManagementEvent");
_watcher = new ManagementEventWatcher(query);
_watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
_watcher.Start();
}
protected override void OnStop()
{
_watcher.Stop();
}
void watcher_EventArrived(object sender, EventArrivedEventArgs e)
{
try
{
int eventType = Convert.ToInt32(e.NewEvent.Properties["EventType"].Value);
switch (eventType)
{
case 4:
Sleep();
break;
case 7:
Resume();
break;
}
}
catch (Exception ex)
{
//Log(ex.Message);
}
}
public void Sleep()
{
}
public void Resume()
{
}
}
}
Again, this is the first time that I am programming with .NET and C# so I apologize for my ignorance.
I am getting namespace errors such as:
The type or namespace name
'ManagementEventWatcher' could not be
found (are you missing a using
directive or an assembly reference?)
Thanks,
Tomek
You need the System.Management namespace, which is included in the code sample provided by you. I believe you need to reference the System.Management library in your project settings. Follow the following steps to do this( I am assuming you are suing Visual Studio):
Go to the Solution Explorer, and expand your project, right click on the References folder/option and select Add References from the context menu. Now select the .Net tab and select the System.Management from the list and click OK.

Categories