jump to navigation

SoapExtensions: A Bad Day with HTTP 400 Bad Requests December 5, 2012

Posted by codinglifestyle in ASP.NET, CodeProject, IIS.
Tags: , , , , , , ,
1 comment so far

You may have found this post if you were searching for:

  • HTTP 400 Bad Request web service
  • Response is not well-formed XML web service
  • System.Xml.XmlException: Root element is missing web service
  • SoapExtension impacting all web services

Yesterday I was debugging an inconsistent issue in production. Thankfully we could track trending recurring errors and began to piece together all incoming and outgoing webservices were being negatively impacted for unknown reasons. This was creating a lot of pressure as backlogs of incoming calls were returning HTTP 400 Bad Request errors. Outgoing calls were silently failing without a facility to retrigger the calls later creating manual work.

We suspected SSO or SSL leading us to change settings in IIS. Being IIS 7.5 this touched the web.config which recycles the app pool. Every time a setting in IIS was changed or an iisreset was issued it seemed to rectify the situation. But after an indeterminate amount of time the problems would resurface.

The culprit ended up being a SoapExtension. The SoapExtension modifies the soap header for authentication when making outgoing calls to a java webservice.

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<SOAP-ENV:Header>
<h:BasicAuth xmlns:h="http://soap-authentication.org/basic/2001/10/"
SOAP-ENV:mustUnderstand="1">
<Name>admin</Name>
<Password>broccoli</Password>
</h:BasicAuth>
</SOAP-ENV:Header>
<SOAP-ENV:Body>
<m:echoString xmlns:m="http://soapinterop.org/">
<inputString>This is a test.</inputString>
</m:echoString>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

It does this with a dynamically loaded (that bit was my fault and made it a complete bitch to debug) SoapExtension taken from a legacy command line util which did this every 5 minutes:

Vendavo Sequence Diagram

This existed simply because nobody could figure out how to call the webservice directly within the web application.  Once incorporated when the web service was called, perhaps hours from an iisreset, the SoapExtension is dynamically loaded.  The bug was, even though it was coded to not affect anything but Vendavo, the checks performed were performed too late and therefore all web services, incoming and outgoing, were impacted.

SoapExtension Lifecycle

Previously the check was in the After Serialize message handler.  The fix was to return the original stream in the ChainStream.  The hard part was knowing what webservice was making the call before ChainStream was called. The check was moved to:

public overrides void Initialize(Object initializer)

The initializer object was tested setting a flag used in ChainStream to determine which stream was returned.

So lesson learned, beware SoapExtensions may impact all soap calls.  While you can specify a custom attribute to limit the extension to web methods you publish you cannot use this filtering mechanism on webservices you consume.  This  means you must self-filter or risk affecting all incoming and outgoing web services unintentionally.

Also, dynamically loading a setting which belongs in the web.config was a dumb idea which delayed identification of the problem. Now we use this:

<system.web>
   <webServices>
      <soapExtensionTypes>
         <add type="SBA.Data.PMMSoapExtension, SBA.Data" priority="1" group="High" />
      </soapExtensionTypes>
   </webServices>
</system.web>

Ref:
http://www.hanselman.com/blog/ASMXSoapExtensionToStripOutWhitespaceAndNewLines.aspx

http://msdn.microsoft.com/en-ie/magazine/cc164007(en-us).aspx

Advertisement

Set IE7 Compatibility Flag for IE8 in IIS May 11, 2009

Posted by codinglifestyle in IIS.
1 comment so far

Now that IE8 has officially been pushed out via Windows Update it’s time to get serious about testing your web site compatibility.  As you probably know, one of the big changes in IE8 is complying to standards for increased interoperability.  In other words, Microsoft won’t be going it’s own way with standards anymore.  Out of the box, IE8 complies with standards that many pages developed with IE6 or IE7 in mind won’t adhere to.  This means customers may have serious layout and style issues when their customers start browsing with IE8.

There is a meta flag that can be set set to tell IE8 to automatically switch to compatiblity view, which will render the page the same as IE7.  This is fine if you have a masterpage, but in an older app with many pages this is not ideal.  Luckily, there is a dead easy way of setting a custom HTTP header which will tell IE8 the same thing.

IE7Compat

 

  1. Open iismgr
  2. Open website properties
  3. Click HTTP Headers tab
  4. Click Add
  5. For customer header name enter X-UA-Compatible
  6. For custom header value enter IE=EmulateIE7
  7. Click OK

Done!  From now on IE8 browsers will default to compatibility mode and won’t even offer the user the option of viewing the side with compatibility mode off.

Tech-ed 2008 November 17, 2008

Posted by codinglifestyle in ASP.NET, C#, IIS, jQuery, Parallelism, Security, SharePoint, Visual Studio 2010.
Tags: , , , , , , , , , , , , , , , , ,
3 comments

Last week I had the opportunity to attend TechEd 2008.  I have compiled a set of notes from the keynote and sessions I attended below.  Most of the information presented at these conferences is not really instructive for addressing today’s problems but talks about future problems and the technologies we will use to address them.  There are some interesting technologies coming down the pipe in the not so distant future and these notes may provide you with enough information to google more information about the topics which interest you.

 

I skipped a lot of older information about the VS2008 release, C# v3.0, and Linq which can all be found here.

 

Keynote

·         Testing Activity Center application

o   Pillar: No more no-repro

o   Generate test cases that tester can click off

o   Bug recording including video, call stack, system information

o   Generate a bug integrated in to Team System

§  Can start up debugger and reproduce tester’s scenario

§  Captures line of code, call stack, everything

·         Code buffering

o   Method shows history of changes (graphically too)

o   Integrates SCC versions in to IDE

·         MVC design pattern

o   Model                   =              data

o   View                     =              web page / UI

o   Controller             =              logic

·         SharePoint Integration

o   Server explorer includes lists, ect

o   Webpart template automatically contains ascx control for design support

o   SharePoint LINQ

o   List Event wizard

§  Auto-generate XML for site def??

·         Performance Profiler

o   Pillar: Leverage multi-core systems

o   See which method is taking time and core utilization

§  Graphically shows core usage including drill down

·         Will help with concurrency, deadlock debugging, ect

VS2008 Service Pack 1 Overview

·         ADO.NET Entity Framework release

o   Very similar to Linq To SQL

o   Generate data model

§  conceptual model static (actual db) model

o   Data Services

§  Data centric abstraction over web services (WFC)

§  Exposes and takes IQueryable so datasets very easy to work with in a LINQ like way

§  Routing lets URI act like a Linq query

·         http://Root/my.svc/Customers/35/FirstName

o   Dynamic Data

§  Given a data model will create aspx accessibility to defined objects

·         Security: all objects off by default but can dynamically access entire data model

·         Allow CRUD access via ASPX templates applied to all objects

o   CRUD = create, read, update, delete

o   Can create individual page for certain object

o   Can customize template to affect all objects

·         Ajax / other enhancements

o   Ajax

§  History Points

·         Addresses problem that users lose ability to hit back button

§  Script combining

·         To improve performance allows to dynamically combine js libraries

o   Improves javascript intellisense

o   Improves web designer performance (bugs/regressions addressed)

C# v4.0

·         History

o   V1 – Managed Code big emphasis

o   V2 – Generics; finished the language

o   V3 – LINQ

·         Pillars

o   Declarative programming: we are moving from “what?” to “how?”

§  LINQ is an example of this

o   Concurrency: Some of the parallelism extensions we will be getting

o   Co-Evolution: VB and C# will more closely evolve together vs. Features hitting languages at different times

o   Static vs. Dynamic Languages: aren’t necessarily a dichotomy

§  Static: C++, C#, VB – anything compiles

§  Dynamic: IronRuby, IronPython, Javascript

·         New keyword: dynamic

o   Call any method of a dynamic object and the compiler won’t complain

§  No intellisense possible

§  Will call during runtime

§  i.e.

·         dynamic calc = GetCalculator();

·         calc.Add(10,20);   //We know nothing about calc object

§  Lots of power to  be explored here

o   Optional Parameters

§  Like in C++ (and apparently VB)

§  Named parameters

·         Can also skip optional parameters

·         Public StreamReader OpenTextFile(string sFile, bool bReadOnly = true, int nBufferSize = 1024);

·         sr = OpenTextFile(“foo.txt”, buffersize:4096);

o   COM Interoperability

§  No more “ref dummy”!

·         Will get: doc.SaveAs(“Test.docx”);  //Winword saveas

·         Versus:   doc.SaveAs(“Test.docx”, ref dummy, ref dummy, ref dummy, ref dummy, ref dummy, ref dummy, ref dummy, ref dummy, ref dummy, ref dummy, ref dummy, ref dummy, ref dummy, ref dummy);

§  Automatic dynamic mapping so less unnecessary casting

§  Interop type embedding

·         No more bringing in PIA

o   Safe Co and Contra-variance

o   Compiler as a service

§  Compiler black box opened up to be used and extended

§  In example created a command window with C#> prompt

·         Was able to define variables, functions, ect like in IronPython

Ajax v4.0

·         Introduction

o   Web app definition

§  Web site is a static collection of pages (such a BBC news)

§  Web application is something which replaces a traditional windows app

o    Traditional Server-Side ASP.NET vs. AJAX

§  Pros

·         Safe: Guaranteed browser compatibility

·         Powerful: All the power of a .NET language in code-behind

§  Cons

·         Response: User must wait for postback

·         Performance: All page content rendered for each interaction

·         Update Panels: Use Wisely

o   An update panel uses sneaky postbacks so while it looks better it is still as bad as traditional server side asp.net

o   Don’t wrap an entire page in an update panel

§  Wrap the smallest region required

§  Use triggers to set what controls will fire a sneaky postback

o   Turn ViewState OFF

§  Down the line this will not be on by default

§  We often send a lot of unnecessary information over the wire in ViewState

·         Ajax Calls (Services)

o   Consider using an Ajax control to update data as needed

o   Calling a web service from javascript is not considered dangerous or bad practice

o   Example

§  Have a datagrid with postback bound to a dropdown list.  Instead of a postback on ddlist use Ajax call

·         Instead of a datagrid use a straight html table

·         Via script we make a call to the web service

·         Use stringbuilder to format return to build up new rows

§  Kinda horrible!  Too much mixing of mark-up and script

·         Client Side Controls

o   Clean way of separating Ajax related script from the web page

o   Allows you to bind to Ajax calls in a template way

o   Example

§  From above we now separate js in to a client side control which is now cleanly referenced on our web page

·         Declarative Client Side Controls

o   “X” in XML stands for extensible; but not often extended!

o   Use XML to bring in namespaces like System and DataView

o   Can define a datagrid purely in html by adding attributes to the

tag in a table

·         Fail over

o   Problem with Ajax is not it is not always supported for reasons of accessibility, search engines, or disabled javascript (mobile devices)

o   Does require double implementation of Ajax and traditional solution but it is an option when needed

·         New features in SP1

o   Back button support!

§  As of VS2008 SP1 Ajax now has back button support

§  ScriptManager property EnableHistory=true and onNavigate event

§  AddHistoryPoint(key,value);

§  AddHistoryPoint(key,value,“Text seen in back button history instead of url”)

§  Process

·         Enable history and add event

·         When page event fires store value (index, ect) with AddHistoryPoint() in provided history cache

·         Use history event to set page back up with value retrieved from HistoryEventArgs

o   Example: set a form to display an item from the last selected index

o   Script Combining

§  Combine scripts for better performance

·         Example showed initial 15sec down to 3

§  Must tell ScriptManager all libraries and it will combine/compress them in to one server call

§  Must explicitly tell which scripts to use – even separate AJAX libraries

·         ScriptReferenceProfiler

o   Free webcontrols which will tell you all the libraries a page uses to make the above less painful

·         Factoids

o   Ajax initiative started to address Outlook Web Access (OWA); a good example of a web application

o   Script Manager is just a way to make sure the page includes the Ajax javascript libraries

§  Ajax script commands prefixed with $

·         $get(“my id”) looks to be handy

§  Can dynamically add event handlers in javascript using Ajax js library

·         $addHandler($get(“dropdownlist1”), “change”, myFunc);

·         Cool “must have” tools

o   Fiddler (www.fiddler2.com)

§  Shows response time, requests/responses, statistics

§  Tip: must place a dot in uri for Fiddler to capture localhost

·         http://localhost./default.aspx

o   Firebug – Firefox extension

 

Visual Studio Tips & Tricks

·         Ppt slides: http://code.msdn.microsoft.com/karenliuteched08

·         A lot more keyboard shortcuts: http://blogs.msdn.com/karenliu/

·         MS and partnered with DevExpress which is offering CodeRush Express for free

o   Required for a lot of the shortcuts and refactoring shown

·         Editing

o   Tools>Options>Editors>C#>Formatting>Set Other Spacing Options>Ignore Spaces

o   Keyboard tricks

§  Ctrl M,O               Toggle collapse all

§  Ctrl M,M              Expand region

§  F12                         Go to definition

§  Shift F12              Final all references

§  Ctrl Shift F8        Jump up Go to definition stack

§  Ctrl [ or ]              Jump between brackets

§  Ctrl Alt = or –      Smart Select

§  Ctrl .                      See smart tag (Implement a missing function, add using statements)

§   

o   Snippets

§  Lots of boilerplate goodies are there.  Really need to start using them

·         Ctor

§  Lots more smart HTML snippets coming

·         Debugging

o   Step OVER properties (r-click at breakpoint to check option)

o   Step into Specific – list of all functions down the chain you can jump to step in to

o   Tools

§  Tinyget – mini stress test

§  Adphang – get memory dump of w3wp

§  Windbg – open dump

·         Loadby SOS mscorwks

o   Need sos.dll for windbg to interpret stack

·         Deployment

o   Web.config transform for release, uat, ect

o   Powerful web deployment publishing options

§  Http, ftp, fpse

§  Msdeploypublish

·         New MS protocol for host supporting includes database, iis settings, access control lists (ACL), ect

·         Free test account at http://labs.discountasp.net/msdeploy

·         Other

o   www.VisualStudioGallery.com  – IDE extensions gallery

§  PowerCommands for VS08

o   VS2008 SDK application

§  Samples tab

·         Click to open sample straight in VS ready to go

Silverlight v2 101

·         XAML

o   A subset of WPF

o   Read-only designer view

§  Must edit  XAML by hand

§  Proper designer on the way

o   Can at least drag XAML text templates for many controls

·         Silverlight Controls

o   Greatly extended in Silverlight v2

§  Visit: www.silverlight.net for a demo

§  Most of what you’d expect in ASP.NET is available in Silverlight

o   Of Note

§  StackPanel

·         Previously on Canvas available requiring static x,y position designation

·         Operates like a panel with z-order

·         Security

o   Lives in a sandbox which can’t be extended for security reasons

o   There are ways to safe access local (isolated) storage, have a file dialog, sockets, cross domain access

·         Nifty

o   Can easily stream media content with one line of XAML

o   Can easily spin any element

Parallelism

·         Introduction

o   Sequential performance has plateaued

o   When we have 30 cores this may lead to dumber cores where we have a situation that today’s software runs slower on tomorrow’s hardware

o   Need  to start thinking about parallelism

§  Understand goals vs. usage

§  Measure existing performance.  VS2010 has tools to do this

§  Tuning Performance

·         Typically we start with sequential programming and add parallelism later

·         VS2010 has Profiler tool for tuning performance

§  Identify opportunities for parallelism

§  Use realistic datasets from the outset; not only on site with the customer

§  Parallelize only when necessary, but PLAN for it as it does introduce race conditions, non-determinism, timing issues, and a slew of other potential bugs

§  Once code is written for parallelism it can scale to any size automatically without any code changes

·         New technologies to help

o   Parallel API

§  Task

·         Like a thread but more optimal with a richer API

o   Has a value for threads which must return a value

§  Accessing the value automatically the same as Thread.Join or Task.Wait

§  ThreadPool

·         Just pass a delegate and let Microsoft worry about the hardware and how to best allocate and spawn threads

·         The ideal number of threads = number of cores

§  TimingBlock class makes it easy to test performance

·         No more: (end time – start time) / 1000

§  Decorate code w/ measurement blocks which appear in Profiler

o   Parallel Extensions

§  First class citizen in VS2010 (SDK today?)

§  Parallel.For and Parallel.ForEach

·         Still need to use critical sections around shared resources inside loop

·         Tip: Best practice is to parallelize the outer for loop only

·         Automatically adds measurement blocks to profiler to see results

§  Parallel.Invoke

§  Parallel extended IEnumerable to perform queries much faster

·         var q = from n in arr.AsParallel() where IsPrime(n) select n;

§  Task group

·         i.e.  For a quick sort instead of using a recursive algorithm use task groups to leverage parallelism with little change to code

o   Debugging – Parallel Stacks

§  Richer API to display tasks or threads and view a holistic mapping of their execution

o   Tools

§  Performance Wizard

·         CPU sampling, timing, ect

§  Profiler

·         Thread Blocking Analysis

o   Shows each thread’s parallel execution revealing race conditions affecting performance

§  Displays information about critical sections in tooltip

§  Can show dependencies for resources/locks across threads

jQuery

·         Ships in future VS but available now

·         Will not be changed by Microsoft but will be supported so we can use it with customers requiring support

·         VS intellisense available from jquery.com

·         Selectors

1.       $(“:text”)             tag          Select all text boxes

2.       $(.required)       class      Select any element with this class tag

3.       $(“#name”)        id            Select with this ID

·         Animations

1.       $(…).Show()

2.       $(…).Hide()

3.       $(…).slideDown()

4.       $(…).slideUp()

5.       $(…).fadeIn()

6.       $(…).fadeOut

7.       Massive open source libraries with hundreds more

§  Plugins.jquery.com

MVC 101

·         MVC

o   Controller (input) pushes to model and view

o   View (UI)

o   Model (logic)

·         An alternative, not replacement, to traditional web forms

·         Easier to test

o   No dependencies on request/response or viewstate as this everything is explicit and therefore testable

·         No server side controls (or designer support), postbacks, or events.

o   Think back to classic ASP

o   What is all this by-hand crap?  XAML (WPF and Silverlight) is only notepad as well

·         Action, instead of event, fires not in View but in the Controller. 

o   The View, aka aspx page, has no code behind.

·         In Controller can define a action and use wizard to create it’s view (web page)

·         ViewUserControl is a collection of html and inline asp which is reusable

IIS v7

·         Modules

o   ASP.NET managed HttpModules can be plugged in directly to IIS v7

§  No more unmanaged ISAPI filters

o   Modules can be managed within IIS v7 Manager

o   Configuration for modules can be exposed through manager

§  Customer WinForm configuration can also be exposed

·         Config

o   No more meta-base

§  All settings exists in central applicationHost.config – similar to a web.config

·         C:\windows\system32\inetsrv\config\schema

§  Can share IIS config for farm scenario

o   www.iis.net contains a configuration pack which allows you to show the config file within the IIS manager

Security

·         Concept of Security Development Lifecycle (SDL)

·         Threat Modelling – package available for formalized  security reviews

o   Talks about prioritizing risks

·         Multi-Pass Review Model

o   1 – Run fuzz and code analysis tools

o   2 – Look for ‘patterns’ in riskier code

o   3 – Deep review of riskiest code

·         Golden rule: What does the bad guy control?

o   What if he controls x & j (resources obtained from user, port, pipeline, compromised file system or database)

§  Char [] f = new char[3];

§  f[3] = 0;                                 bug

§  f[x] = 0;                                 can write a null to anywhere in memory

§  f[x] = y;                                 can write anything anywhere in memory

·         Accepted encryption

o   AES and SHAXXX only

o   Everything else is banned!  So long TripleDES

·         Do not use:  try { } catch (Exception ex) { }

o   Hides bugs and security flaws

o   Catch only exceptions we can handle

IE v8

·         Debug tools included out of the box

o   Hit F12

§  Debug javascript

§  Solve style issues

·         Compatibility – new rendering engine following widely-accepted standard

o   Get prepared for our apps look and feel to break

o   www.msdn.com/iecompat

o   Set meta-tag to tell IE8 to continue to render using v7 engine

·         Accelerators

o   Can develop own accelerators which can highlight a name and pass to a website as a parameter.  Employee staff directory, for example.

Cool Stuff

·         Ctrl-,

o   Quick search feature in 2010

·         Ctrl-.

o   Refactoring: infers using statement.  Generate a new method as your developing

·         Web.config

o   Release version compiles debug/standard web.config and turns off debug, hardens security, replaces config and connection strings

o   Part of the installer

Other Stuff

·         Ribbon support in VS2008 Feature Pack

·         Vista Bridge

o   Wrapper to get access to Vista controls and features

o   TaskDialog and CommandLinks

§  Standard now so will be seen in Win v7

§  Backwards compatible, just extra messages to standard native button

o   Restart/Recovery API

§  Get notified of a reboot

§  Register delegate called in separate thread when app crashes/reboots

§  OS will run app with a command line argument you catch to load saved info

o   Power Management

§  Get notified about all power related info, low battery, ect

Biz Stuff

·         StepUp Program

o   Allows customers to upgrade current SKU

§  i.e. VS Pro to Team Foundation Server

§  30% discount until June 2009

Multi-threaded WebService: “Unable to connect to remote server” April 24, 2007

Posted by codinglifestyle in ASP.NET, IIS, Parallelism.
Tags: , , , , ,
2 comments

You know you’ve made it in to hackerdom when 4000 ports just isn’t enough.  I need more power!

 

I have a webservice which spawns, potentially thousands, of threads.  These in turn are calling a webservice in SharePoint to perform a real-time query (or else we could make a single call to the search service which relies on the index being up-to-date).  I did think to include a throttle which would restrict the total number of threads spawned across all calls to the webmethod.  However, even with this number safely at 100 threads I didn’t account for TCP/IP’s default settings keeping the port alive 4 minutes.  It didn’t take long to put around 4000 ports in a TIME_WAIT state.  When my webservice would make a call to the SharePoint webservice this would result in a System.Net.WebException:

 

“Unable to connect to remote server” with an inner exception of:

 

“Only one usage of each socket address (protocol/network address/port) is normally permitted”

 

The solution was simple enough and is common across a number of greedy applications.  TCP/IP allows us to up the ante by changing a few parameters in the registry.  This allows you to adjust the delay before a port is available again.  In addition you may increase the number of ports at your disposal by nearly 60,000.  If this isn’t enough, maybe a design change is in order!

 

Here’s how you do it:

 

The product handles heavy query volumes more efficiently if the following TCP/IP parameters are set in the Windows® registry:

1.       Start the registry editor:

a.       Click the Windows Start button.

b.       Click Run.

c.       Type regedit in field provided.

d.       Click OK

2.       Use the following directory path to navigate to the registry key:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters

3.       In the right pane of the registry editor, look for the TcpTimedWaitDelay value name. If it is not there, add it by selecting Edit > New > DWORD Value from the menu bar. Type the value name TcpTimedWaitDelay in the name box that appears with the flashing cursor.

Note: If you do not see the a flashing cursor and New Value # inside the box, right-click inside the right panel and select Rename from the menu, then type the value name TcpTimedWaitDelay in the name box.

4.       Double-click inside the right pane again to set the value of TcpTimedWaitDelay. Select Decimal as the Base, and enter 30 in the Value data field.

5.       In the right pane of the registry editor, look for the MaxUserPort value name. If it is not there, add it by selecting Edit > New > DWORD Value from the menu bar. Type the value name MaxUserPort in the name box that appears with the flashing cursor.

Note: If you do not see the a flashing cursor and New Value # inside the box, right-click inside the right panel and select Rename from the menu, then type the value name TcpTimedWaitDelay in the name box.

6.       Double-click inside the right pane again to set the value of MaxUserPort. Select Decimal as the Base, and enter 65534 in the Value data field.

7.       You must restart Windows for these settings to take effect

 

Reference: http://blogs.msdn.com/dgorti/archive/2005/09/18/470766.aspx

 

 

 

Update! 

 

After issuing the above changes were made and the customer finally rebooted the server I ran in to an new, exciting System.Net.WebException:

 

The underlying connection was closed: An unexpected error occurred on a send.” with a status of: SendFailure

 

Searching for this exception lead me to exactly the information I was looking for.  Let’s close down those ports as soon as we are done with them.  I have no desire to use up thousands of ports and wear the hacker crown.  We can do this by changing the keep alive state of our web request to false.  Funny that this isn’t by default false for a webservice nor is it a public member to set like the timeout.  We have two choices, the high road and the low road.  First the low road:

We will alter generated proxy class directly; meaning your fix may be lost if you update your web reference.  In the GetWebRequest function the KeepAlive property must be set to false. This can be accomplished by following these steps:

  • Add a Web Reference using the normal way (if you haven’t already added one ofcourse).
  • Make sure Show All Files menu item is enable in the Project menu.
  • In the Solution Explorer window, navigate to:
    • Web References
        • Reference.map
          • Reference.cs (or .vb)
  • Open the Reference.cs file and add following code in the webservice proxy class:
    • protected override System.Net.WebRequest GetWebRequest(Uri uri)

      {

      System.Net.HttpWebRequest webRequest =

                      (System.Net.HttpWebRequest)base.GetWebRequest(uri);

       

            webRequest.KeepAlive       = false;

            webRequest.ProtocolVersion = HttpVersion.Version10;

       

            return webRequest;

      }

       

       

The high road, or proper way of doing this, is to subclass our webservice such that we don’t touch the auto-generated proxy class.  Here is a sample: 

 

using System;
using System.Net;
using System.Reflection;

// Web service reference entered in wizard was “MyWebService.MyWebServiceWse”
using MyProject.MyWebService;

namespace MyProject
{
 public class MySubClassedWebService : MyWebServiceWse
 {
  private static PropertyInfo requestPropertyInfo = null;

  public MySubClassedWebService(){}

  protected override System.Net.WebRequest GetWebRequest(Uri uri)
  {
   WebRequest request = base.GetWebRequest(uri);

   // Retrieve property info and store it in a static member for optimizing future use
   if (requestPropertyInfo==null)
    requestPropertyInfo = request.GetType().GetProperty(“Request”);

   // Retrieve underlying web request
   HttpWebRequest webRequest = (HttpWebRequest)requestPropertyInfo.GetValue(request, null);

   // Setting KeepAlive
   webRequest.KeepAlive = false;
   // Setting protocol version
   webRequest.ProtocolVersion = HttpVersion.Version10;
   return request;
  }
 }
}

 

 

 

Reference: http://weblogs.asp.net/jan/archive/2004/01/28/63771.aspx

IIS Madness: 401, Application Pool identities, and IP addresses March 1, 2007

Posted by codinglifestyle in IIS, Security.
Tags: , , , , , , ,
add a comment
Okay, here’s the situation. Set up a new website using Windows authentication only on any port other than 80. Create a “hello world” default.htm.  So far, so good… you may access the site at http://machinename:port. Now set that site to use an application pool with a domain user as the identity. Ensure you run aspnet_regiis -ga MachineName\AccountName. Now you are challenged and receive a 401. 
 
You are now in an interesting scenario:
http://machine:100/default.htm – does not work
http://192.168.1.234:100/default.htm – does work (assumming machine’s IP is 192.168.1.234)
 
Why?
 
According to Microsoft, IIS’s Integrated Windows authentication uses Kerberos v5 authentication and NTLM authentication. If Active Directory is installed on a domain controller running Windows 2000 Server or Windows Server 2003, and the client browser supports the Kerberos v5 authentication protocol, Kerberos v5 authentication is used. To use Kerberos authentication, a service must register its service principal name (SPN) under the account in the Active Directory directory service that the service is running under.  By default, Active Directory registers the network basic input/output system (NetBIOS) computer name.  But what about the computer name under a different port?
 
In summary, the application pool’s identity is not authenticated correctly because of IIS will try to use Kerberos by default.
 
 
To work around this behavior if you have multiple application pools that run under different domain user accounts, you must force IIS to use NTLM as your authentication mechanism if you want to use Integrated Windows authentication only. To do this, follow these steps on the server that is running IIS:
1.
Start a command prompt.
2.
Locate and then change to the directory that contains the Adsutil.vbs file. By default, this directory is C:\Inetpub\Adminscripts.
3.
Type the following command, and then press ENTER:
cscript adsutil.vbs set w3svc/NTAuthenticationProviders “NTLM”
4.
To verify that the NtAuthenticationProviders metabase property is set to NTLM, type the following command, and then press ENTER:
cscript adsutil.vbs get w3svc/NTAuthenticationProviders
The following text should be returned:
NTAuthenticationProviders : (STRING) “NTLM”
Reference: http://support.microsoft.com/kb/871179

Caching woes in the garden November 6, 2006

Posted by codinglifestyle in ASP.NET, IIS.
Tags: , ,
add a comment

Over the past few weeks I have received numerous bugs on a SharePoint project I’ve been trying to close.  This project had a lot of custom webparts and added functionality.  These various reports all centered on inconsistent behavior resulting from the cache being lost.  The thing was everything worked fine in the development environment (of course).  What was causing the server to give up its cache so quickly?  I tried varying settings in the web.config, monitored application recycles, monitored if the virus scanner was touching web or machine.config.  I tried PartCache, Application State, Page.Cache, and tweaked every setting they had.  I was even reduced to using (shudder) hidden fields in a few cases.

Finally I wrote a webpart for testing the cache.  It allowed you to submit a value or simply refresh (postback).  The webpart stored and displayed the value in every available type of cache: View State, Cache, WP Shared, WP Personal, Session, AppState.

I quickly discovered an odd behavior.  The cache was cycling between values.  I’d submit “one”, “two”, “three” and then simply postback and see the cache cycle between these 3 values.  I shut down every other web site on the server and opened task manager.  Lo and behold I saw three, count em three, w3wp.exe processes running.

Finally the penny dropped and I opened the application pool properties.  On the performance tab there is an innocuous setting at the bottom called Web garden.  While I was away on holiday the customer had been complaining about performance so someone had set this to 3 and forgot to tell anyone.  This simple action, which does not flash any sirens, bells, or whistles, completely changes the environment in which the code runs.  A web garden has multiple processes; a server farm has multiple physical machines with a load balancer.  The effect on cache is the same.  In a garden/farm environment you must persist cache using a custom provider, namely a SQL database which persists a single copy of the cache so that multiple servers/processes all point to a single copy.

You can imagine the impact this had on a code which relied on various types of caching, either to cache data or to maintain state for an individual user.  By changing this single setting back to 1 process, everything was back in order.  If I had a swear jar, I would be destitute.  Here is what MSDN has to say for those who read about the ramifications of their changes before doing:

“Because Web gardens enable the use of multiple processes, each process will have its own copy of application state, in-process session state, caches, and static data. Web gardens should not be used for all applications, especially if they need to maintain state. Be sure to benchmark the performance of the application before deciding whether Web garden mode is appropriate.

When using a Web garden, it is important to understand how session state and round robin works. It is also important to consider of how other application pool settings affect the application.”

So, the lesson learned?  Next time you have a funky caching problem add this to your list of things to check.  Also, swear jars and programmers don’t mix.

Programatically recycle an IIS application pool October 20, 2006

Posted by codinglifestyle in ASP.NET, IIS.
Tags: , , ,
3 comments

One of the many banes in my life is waiting for IIS to reset.  When developing certain components, like a webpart or webcontrol, I often use a post-build event to gac the assembly and issue an iisreset.  This is necessary for IIS to pick up the latest assembly from the GAC.  Recycling the app pool also forces IIS to reload the assembly, but I never could find a command I could issue from my post-build batch file to automate this.  Well, now I don’t need to look because I just wrote my own utility to recycle the application pool:

using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices;

namespace AppPoolRecycler
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length != 2)
            {
                Console.WriteLine(“Usage:\tapppoolrecycler.exe machine apppool\n\tapppoolrecycler.exe localhost mypool”);
                return;
            }
            try
            {
                string sMachine = args[0];
                string sAppPool = args[1];

                string sPath = “IIS://” + sMachine + “/W3SVC/AppPools/” + sAppPool;
                Console.WriteLine(sPath);
                DirectoryEntry w3svc = new DirectoryEntry(sPath);
                w3svc.Invoke(“Recycle”, null);
                Console.WriteLine(“Application pool recycled”);
            }
            catch (Exception ex)
            {
                Console.WriteLine(“Error: ” + ex.Message);
            }
        }
    }
}

Now in my post build event I can gac my assembly and recycle the app pool which is much faster than a reset.

AppPoolRecycler.exe sanpaula mssharepointportalapppool

 

Take a look at this blog entry for more information: http://blogs.aspitalia.com/daniele/post555/Riciclare-Application-Pool-IIS-Codice-CSharp.aspx

 ———————–

Update!  I’ve recently come across a way to do this using a script which should be installed on W2003: 

c:\windows\system32\iisapp.vbs /a mssharepointportalapppool /r