Using IHttpModule to overlay a website

I ran into the need to shut down an application for maintenance. What I needed is a plugin that I could drop on any website and it will create an overlay on top and disable all functionality. It had to also display a message notifying the users what's going on. Using an HttpModule seems to be the most logical way to go about that. First I create a class that inherits IHttpModule. In the implementation of the BeginRequest I inject a div overlay and the message into the body of the page. void context_BeginRequest(object sender, EventArgs e) { System.Web.HttpContext context = System.Web.HttpContext.Current; string message = System.Configuration.ConfigurationManager.AppSettings["WarningMessage"]; if (String.IsNullOrWhiteSpace(message)) message = "The web site is down for maintenance. Please check back again later."; context.Response.Filter = new OverlayInjector(context.Response.Filter, message); } I also created OverlayInjector : System.IO.Stream class to help with the injection overriding the Write method like that: public override void Write(byte[] buffer, int offset, int count) { var data = new byte[count]; Buffer.BlockCopy(buffer, offset, data, 0, count); string html = Encoding.Default.GetString(buffer); html = html.Replace("", "<div style='position: absolute; left: 100px; top: 250px; z-index: 999; color: red; font-weight: bold; font-size: 1.5em; width: 75%; background-color: #ffffcc; padding: 10px; text-align: center;'>" + _message + "</div> byte[] outdata = Encoding.Default.GetBytes(html); _stream.Write(outdata, 0, outdata.GetLength(0)); } Finally all I need to do is drop the dll into the bin of the website I want to implement this to and add two entries into the web.config file: <appSettings> <add key="WarningMessage" value="Down for maintanence check back on 1/1/2020"/> </appSettings> <httpModules> <add name="HttpModuleOverlay.Overlay" type="HttpModuleOverlay.Overlay"/> </httpModules> You can download the code here. HttpModuleOverlay.rar (16.64 kb)
.NET 4.0 // C# // EF

Entity Framework 4.0 - Running Ad hoc Queries or Commands

A nice addition to the latest version of ADO.NET Entity Framework is the ability to run ad hoc commands.  Two methods of the Entity Context have been introduced to accomplish that: ExecuteStoreQuery and ExecuteStoreCommand. The tricky part is passing the parameters. They are index based so the example below shows you how. string sql = "SELECT Col1, Col2 FROM MyUdf({0},{1});"; IEnumerable<MyComplexType> list = dbclient.ExecuteStoreQuery<MyComplexType>(sql, parameter1, parameter2);
.NET 4.0 // C# // WF

Running Workflows in .NET 4.0

Workflows can be run synchronously and asynchronously. Below is an example how you run a workflow instance synchronously: Dictionary<string, object> inputs = new Dictionary(); inputs.Add("InArgument", "SomeValue"); inputs.Add("InOutArgument", "SomeOtherValue"); WorkflowElement activity = workflow; IDictionary<string, object> outputs = WorkflowInvoker.Invoke(new MyWorkflow(), inputs); MyObject obj = (MyObject)outputs["OutArgument"]; MyOtherObject obj = (MyOtherObject)outputs["InOutArgument"]; Note that now workflows have arguments as well as parameters. Arguments are for passing data to and from the Workflow where parameters are for internal use. Remember: Workflow is an activity so the same goes for any custom activity you create. Any In or In/Out arguments have to be passed to the workflow for it to execute. Now here is a very simplified example of how to run a workflow instance asynchronously. The OnCompleted event is raised when the workflow has finished running and the IDictionary<string, object> outputs can be read off of the WorkflowCompletedEventArgs. ManualResetEvent resetEvent = new ManualResetEvent(false); WorkflowInstance instance = new WorkflowInstance(new MyWorkflow()); instance.OnCompleted = delegate(WorkflowCompletedEventArgs e) { Console.WriteLine("workflow instance completed, Id = " + instance.Id); resetEvent.Set(); }; instance.Run(); resetEvent.WaitOne(); I haven't done it yet but I presume running a workflow in IIS and interacting with it before it finishes would not be as staighforward as the examples above.

In .NET 4.0 SecurityManager.IsGranted is obsolete

In .NET 4.0 SecurityManager.IsGranted has been made obsolete.  This is what it was and if you compile in .NET 4.0 compatibility it will complain. bool isGranted = SecurityManager.IsGranted(new SecurityPermission(SecurityPermissionFlag.Infrastructure)) In order to fix this now you have to do this instead. var permissionSet = new PermissionSet(PermissionState.None); permissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode)); bool isGranted = permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet);

Enable Network Access for MS DTC

  Microsoft Distributed Transaction Coordinator (MS DTC) helps you control the coordination of transactions between applications and resource managers. Depending on the network topology of these components, a transaction can span multiple DTCs throughout your network. To allow transactions to be coordinated across the network, Network DTC Access must be enabled on all MS DTC instances that are participating in the transaction. For example, if a COM+ object attempts to update a Microsoft SQL Server® database on a remote computer by using an MS DTC transaction, the transaction fails if network transactions are disabled. Similarly, if the computer hosts a SQL database that has remote applications that try to access the database by using an MS DTC transaction, those transactions also fail if Network DTC Access is disabled. Configuring network transactions for MS DTC If your distributed transactions fail because of network connectivity problems, this failure might be related to the configuration of the DTCs that are participating in the transactions. Check each DTC and make sure that Network MS DTC Access is enabled. You can use the following procedure to accomplish this task. To enable Network DTC Access for MS DTC transactions Open the Component Services snap-in. To open Component Services, click Start. In the search box, type dcomcnfg, and then press ENTER. Expand the console tree to locate the DTC (for example, Local DTC) for which you want to enable Network MS DTC Access. On the Action menu, click Properties. Click the Security tab and make the following changes: In Security Settings, select the Network DTC Access check box. In Transaction Manager Communication, select the Allow Inbound and Allow Outbound check boxes. Click OK. If you want to change these settings programmatically, you can use the registry settings in the table in the following section to directly change the registry values that correspond to the setting that you want. After you change the registry settings, you must restart the Distributed Transaction Coordinator service (MSDTC). If you use Windows Firewall to protect the computers in your organization, you must enable the Distributed Transaction Coordinator exception in the exception list in the Windows Firewall settings. To accomplish this task, see Enable Firewall Exceptions for MS DTC. Accessing MS DTC security settings   To open the DTC security settings properties page Open the Component Services snap-in. To open Component Services, click Start. In the search box, type dcomcnfg, and then press ENTER. In the console tree, click Local DTC. On the Action menu, click Properties. Click the Security tab. Security settings for the MSDTC service The following table describes the fields on the DTC Security Settings properties page, along with the registry keys that are affected for the different settings. All the registry keys that are related to the MSDTC service are located in the following registry key: MyComputer\HKEY_LOCAL_MACHINE\Software\Microsoft\MSDTC   SettingDescriptionCorresponding registry value Network DTC Access Determines whether MS DTC on the local computer can access the network. This setting must be enabled in combination with one of the other settings to enable network MS DTC transactions. Default setting: Off Security\NetworkDtcAccess 0 = Off 1 = On Allow inbound Allows a distributed transaction that originates from a remote computer to run on this computer. Default setting: Off To enable this setting you must set the following registry key values to 1: Security\NetworkDtcAccess Security\NetworkDtcAccessTransactions Security\NetworkDtcAccessInbound To disable this setting, set the following registry key value to 0: Security\NetworkDtcAccessInbound Allow Outbound Allows the local computer to initiate a transaction and run it on a remote computer. To enable this setting, you must set the following registry key values to 1: Security\NetworkDtcAccess Security\ NetworkDtcAccessTransactions Security\ NetworkDtcAccessOutbound To disable this setting, you must set the following registry key value to 0: Security\NetworkDtcAccessOutbound Mutual Authentication Required This is the highest secured communication mode and the recommended transaction mode for clients running either Windows XP Service Pack 2 (SP2), Windows Server 2003, Windows Vista or Windows Server 2008. AllowOnlySecureRpcCalls = 1 FallbackToUnsecureRPCIfNecessary = 0 TurnOffRpcSecurity = 0 Incoming Caller Authentication Required Requires the local DTC to communicate with a remote DTC by using only encrypted messages and mutual authentication. We recommend that you use this setting for servers running either Windows Server 2003 or Windows Server 2008 that are operating in a failover cluster. Only computers running Windows XP SP2, Windows Server 2003, Windows Vista, or Windows Server 2008 support this feature. Therefore, use this setting only if you know that the DTC on the remote computer is running one of these versions of the Microsoft Windows operating system. AllowOnlySecureRpcCalls = 0 FallbackToUnsecureRPCIfNecessary = 1 TurnOffRpcSecurity = 0 No Authentication Required Provides system compatibility between earlier versions of the Windows operating system. When you enable this setting, communication on the network between DTCs can fall back to a nonauthentication or nonencrypted communication if a secure communication channel cannot be established. Use this setting if the DTC on the remote computer is running a version of Windows 2000 or Windows XP earlier than SP2. This setting is also useful when the DTCs that are involved are located on computers that are in domains that do not have an established trust relationship or if the computers are part of a Windows workgroup. AllowOnlySecureRpcCalls = 0 FallbackToUnsecureRPCIfNecessary = 0 TurnOffRpcSecurity = 1   Enabling Firewall Exceptions for MSDTC To enable firewall exceptions for MSDTC on computers running Windows XP or Windows Server 2003, do the following: Open the Windows Firewall dialog box. On a computer running Windows XP, click Start, click Control Panel, and then double-click Windows Firewall. On a computer running Windows Server 2003, click Start, click Control Panel, and then click Windows Firewall. In the Windows Firewall dialog box, click the Exceptions tab, and then click Add Program. In the Add a Program dialog box, click Browse. In the Browse dialog box, browse to the location of msdtc.exe. On a computer running Windows XP, browse to <system drive>:\WINDOWS\system32. On a computer running Windows Server 2003, browse to <system drive>:\WINNT\system32. In the Add a Program dialog box, click OK. In the Windows Firewall dialog box, click OK. To enable firewall exceptions for MSDTC on computers running Windows Vista or Windows Server 2008 Open Windows Firewall. To open Windows Firewall, on the Start menu, click Control Panel. In Control Panel, do one of the following: Under Security, click Allow a program through Windows Firewall. If Control Panel is in Classic view, click Windows Firewall.  On the Exceptions tab, select the Distributed Transaction Coordinator check box. Click OK.
.NET // C# // Microsoft

Efficient iterations using the yield keyword

Quick overview of the yield keyword in C#. [More]

Month List