HttpWebRequest Authentication error 400

November 3rd, 2011 5 comments

Using .Net webrequest and webclient class with the default implementation of authentication may lead to error 400.
When the request URL contain querystring parameters .Net default implementing of authentication exclude the querystring parameters on authentication what should give error 400 by authentication definition

The solution is to implement by your self the authentication :

/// 
/// The function athenticate given WebRequest with given credentials
/// 
/// authenticating credentials
/// authenticated request
/// return response from first attempt to authenticate(relevant when no authentication was required or other error occur
/// true on success otherwise false
public bool AuthenticateRequest(ICredentials credentials, ref WebRequest webRequest, out WebResponse webResponse)
{
    webResponse = null;
    if (credentials == null)
    {
        return true;
    }
    if (webRequest == null)
    {
        throw new ArgumentNullException(@"webRequest");
    }
    try
    {
        webResponse = webRequest.GetResponse();
    }
    catch (WebException ex)
    {
        if ((ex.Status != WebExceptionStatus.ProtocolError) || (ex.Response == null) || (((HttpWebResponse)ex.Response).StatusCode != HttpStatusCode.Unauthorized))
        {
            throw;
        }

        string authenticateHeader = ex.Response.Headers[@"WWW-Authenticate"];
        if (string.IsNullOrEmpty(authenticateHeader))
        {
            throw new ApplicationException(@"No Authenticate Header");
        }

        IAuthenticateParams authenticateParams;
        if (!ExtractAuthenticateHeaderParametes(authenticateHeader, webRequest.RequestUri, out authenticateParams))
        {
            throw new ApplicationException(@"Failed to extract WWW-Authenticate header");
        }

        NetworkCredential credential = credentials.GetCredential(webRequest.RequestUri, authenticateParams.AthenticateType);
        if (credential == null)
        {
            throw new ApplicationException(@"Credential mismatch error");
        }

        IAuthenticationHandler authenicationHandler;
        if (!GetAuthenticationHandler(authenticateParams, out authenicationHandler))
        {
            throw new ApplicationException(@"Failed to get authentication handler");
        }

        string authorizationHeader;
        if (!authenicationHandler.GetAuthorizationHeader(credential, out authorizationHeader))
        {
            throw new ApplicationException(@"Failed to get authentication header"HttpWebRequest tmpRequest = (HttpWebRequest)webRequest;
        webRequest = (HttpWebRequest)WebRequest.Create(webRequest.RequestUri);
        webRequest.Headers[@"Authorization"] = authorizationHeader;
        ((HttpWebRequest)webRequest).UserAgent = tmpRequest.UserAgent;
        webRequest.ContentType = tmpRequest.ContentType;
    }

    return true;
}

Authentication Sample Code Download
Further explanation :
Http web request use several authentication types:
Basic
Digest
Ntlm

When web request is made to protected website an authentication request is made
The parameters are past in “WWW-Autherization” header, the parameters past in name equal value coma separated except authentication method which past as first string with no name value pattern
The client respond with the same request adding “authentication” header

When perform Digest authentication,
one of the parameters past is URL.
The URL parameter is past in both authentication header and mast be the same (rfc2617).
The URL parameter is the URL of the request without the host info,
for example, if the request is for www.abc.com/1.htm the parameter value will be /1.htm .
The problem with .Net default implementation is it removes query parameters so instead of passing /1.aspx?a=b it passes /1.aspx on the Authorization header.
That’s why the authentication fails.

SynchronizationContext simply InvokeRequired

October 12th, 2011 No comments

Windows application usually have to split GUI functionality in one thread and logic functionality in another thread in order to achieve better performance
One of the common problems is when you trying to update windows controls is they enforce main thread identity, Which means you can’t update them directly. The common solution look like

private delegate void SetControlEnabledDlgt(Control control, bool, enabled);
private void SetControlEnabled(Control control, bool enabled)
{
 if(!control.InvokeRequired)
 {
   control.Enabled = enabled;
   return;
 }
 SetControlEnabledDlgt dlgt = new SetControlEnabledDlgt(SetControlEnabled);
 this.Invoke(dlgt, control, enabled);
}
public void SetTextEnabled()
{
   SetControlEnabled(m_displayTextBox, true);
}

Using the InvokeRequired Method on the form class

Now using SynchronizationContext you could easily do

SynchronizationContext m_GUISyncContext;
public Form() //form constructor or other function runs on gui thread
{
   InitializeComponent();
   m_GUISyncContext = SynchronizationContext.Current;
}

public void SetTextEnabled()
{
   m_GUISyncContext.Send(new SendOrPostCallback((o) =>
                     {
                        m_displayTextBox.Enabled =true;
                     }),null);
}

you must call SynchronizationContext.Current from the gui main thread(the thread creating the forms is okay or onload event of the form

Categories: Development, Threading Tags:

Multi-threading (c#) Part 1

September 9th, 2011 4 comments

This Post will cover the following topics:

  • What is a Process?, What is a Thread ?
  • Thread Actions
  • Locking , sync threads, (special sync threads)
  • Delegates

the following posts will cover :

  • Handle Threads (non-managed thread pool)
  • Managed Thread pool
  • Async Methods
  • Async Execute Sample(.net class)
  • Tasking

Process is a single unit of execution managed by the operating system, A thread is in process unit, a tinier unit of execution.
Operating system runs process in parallel on computer and thread run in parallel within the process
Threads share process data and their creation is less expensive than a process but they are more depended on another one. Thread may cause termination of the entire process (unhandled exception)
usually application runs on single process.

So What are we able to do with threads ?

UI application use one thread to handle UI and other threads to preform the actions in order to achieve better UI without preventing UI thread receiving user actions

Application may achieve better CPU by pausing waiting threads

Isolating different calculation and let each of them run in his own pass(easier to change the phase of single calculation\s thread\s)

C# and .net framework support these actions on thread:

  • ThreadState : return flagged enum of thread state
  • Sleep : cause the current to stop at least for given amount of milliseconds and suspend his work, other threads get his execution time
  • Start: start execution of thread with or without additional parameters, the thread will start when the first thing will happen : the execution of current thread will end, when the current thread will pass control (Sleep(0)), end of current function, current thread entered to waiting state(could by by IO, Network, database operations)
  • Stop: Stop the execution of given thread regardless to it’s current execution path
  • Join: join the current thread with the execution of given thread, the current thread will be blocked till the given thread will be terminated
  • Interrupt: ThreadInterruptException will be thrown on the given thread when its on non running state(block, wait, join), if the it’s already on the non running state exception will be thrown right away, if it never enters to that state the interrupt will be lost
  • Abort:ThreadAbortException will be thrown on the given thread unless it’s suspended otherwise the exception will be thrown and will be re-thrown after each catch block on the given thread unless ResetAbort is called
  • SpinWait:The thread will wait given amount of iterations more info is available on Microsoft documentation but this method should be used rarely by your code
  • Yield: the calling thread yields his execution to another ready thread
  • MemoryBarrier : synchronize memory access by disable instruction reorder prior the call with after the call

As mentioned earlier thread may share process data, since most of exist data object aren’t thread safe and there most of the time we will have a critical part of code which need to be run only once on the same, we will use synchronization methods in order to achieve this goal.
We have 2 kinds of synchronization (there is 3rd kind of synchronization access without locking but require complicated solution will be covered in additional post):

  • Locking: limiting access to critical sections (such as shared data)
  • Signaling: pausing, resume threads or waiting thread to end

We may have a lock to eliminate access to critical section of code in processes scope with Mutex or in threads scope with Monitor, Monitor lock is done by Monitor.Enter/TryEnter and Monitor.Exit, the lock keyword is the syntactic sugar for Monitor class and equivalent to

Monitor.Enter(lockObject);
try
{
}
finally
{
   Monitor.Exit(lockObject);
}

till framework 4.0
or

bool lockTaken=false;
try
{
   Monitor.Enter(lockObject, ref lockTaken);
}
finally
{
  if (locktaken)
  {
    Monitor.Exit(lockObject);
  }
}

since framework 4 which resolves the lock leak when thread had exception between the Monitor.Enter and the try at previous frameworks. Monitor is also used for signaling by Monitor.Wait and Monitor.Pulse.PulseAll be aware that Pulse is lost when no there is no current Wait

Keep in mind that although any object may be used for lock you should choose an object which wouldn’t change and will be as small as possible (double). A good design will be to create a dedicated lock object most of the times. In addition it is recommended to use TryEnter instead of Enter, so you will limit the time waiting for the thread to acquire the look(this way you never have lock leak or deadlock)

Mutex as described has a larger scope but also costs much more and leaving a Mutex locked by mistake would cost a windows reset. Using WaitOne and ReleaseMutex in order to achieve a lock. It is very recommended to use the WaitOne method with a time limit parameter to avoid infinite wait. In addition, this object is disposable so make sure you call Dispose method

A third locking option is done by using Semaphore or SemaphoreSlim, which runs on thread scope and eliminates access to an amount of threads given in creation time. That is opposed a to Mutex and to Monitor, the thread identity is not enforced so one thread may call Wait while another calls Release. When the the Semaphore is full and released, one of the waiting threads will enter, regardless of the order they start wait for an available slot.

Another common locking class is ReadWriterLock or ReadWriterLockSlim which answers a common locking problem (so common Microsoft develop this solution twice and integrated it in the .Net framework) of multiple readers and writers locks.

Delegates are methods signature type. This special type is used on events when its instance is a handler to function which can be used in other ways than events, one of them is making exists function asynchronous (which uses .net default thread pool).

delegate void FooDlgt();
FooDlgt m_dlgt = new FooDlgt(Foo);
protected void Foo()
{
}

public IAsynResult BeginFoo()
{
 return m_dlgt.BeginInvoke();
}

public void EndFoo(IAsyncResult ar)
{
   m_dlgt.endInvoke(ar);
}

This Pattern is called APM, we have many classes with this pattern, such as IO class with functions: BeginExcuteReader, BeginGetResponse and others.

.Net framework offers additional special sync threads through the SynchronizationContext class.
This special options are implemented by a GUI main thread (most other build-in threads don’t support it), which allows us to send method (a delegate) from another thread to be executed in another thread context which is very important when dealing with GUI thread and updating user controls which are allowed to be modified only through this thread.