<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:blogger='http://schemas.google.com/blogger/2008' xmlns:georss='http://www.georss.org/georss' xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-4158593070832043065</id><updated>2024-09-22T20:41:08.703-07:00</updated><category term="c#"/><category term=".net"/><category term="asp.net"/><category term="asp.net-mvc"/><category term="c++"/><category term="mvc"/><category term=".NET 3.5"/><category term="async"/><category term="asynchronous"/><category term="authentication"/><category term="blocking queue"/><category term="blocking-queue"/><category term="c++ testing"/><category term="client"/><category term="concurrency"/><category term="derobins"/><category term="derobins-wmd"/><category term="dotnetopenauth"/><category term="google test"/><category term="gtest"/><category term="http"/><category term="markdown"/><category term="markdown-editor"/><category term="multi-threading"/><category term="openid"/><category term="partial-view"/><category term="qt"/><category term="socket programming"/><category term="sockets"/><category term="state machine"/><category term="testing framework"/><category term="threading"/><category term="unit testing"/><category term="user-control"/><category term="visual studio 2008"/><category term="visual studio 2010"/><category term="visual-studio-2010"/><category term="wmd"/><category term="wysiwyg"/><title type='text'>Code Sprout</title><subtitle type='html'>&lt;center&gt;Where sprouts of code meet the internet! &#xa;&lt;br&gt;&#xa;I post them as I code them.&lt;/center&gt;</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://codesprout.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4158593070832043065/posts/default?redirect=false'/><link rel='alternate' type='text/html' href='http://codesprout.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/00374520101046586303</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>5</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-4158593070832043065.post-3475011958084367631</id><published>2012-11-13T08:49:00.002-08:00</published><updated>2012-11-21T09:07:35.603-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="blocking queue"/><category scheme="http://www.blogger.com/atom/ns#" term="blocking-queue"/><category scheme="http://www.blogger.com/atom/ns#" term="c++"/><category scheme="http://www.blogger.com/atom/ns#" term="concurrency"/><category scheme="http://www.blogger.com/atom/ns#" term="multi-threading"/><category scheme="http://www.blogger.com/atom/ns#" term="qt"/><category scheme="http://www.blogger.com/atom/ns#" term="threading"/><category scheme="http://www.blogger.com/atom/ns#" term="visual studio 2010"/><category scheme="http://www.blogger.com/atom/ns#" term="visual-studio-2010"/><title type='text'></title><content type='html'>I recently had to build my own blocking queue for a Qt project which I&#39;m developing in Visual Studio 2010.&lt;br /&gt;
&lt;br /&gt;
The BlockingQueue is designed to take advantage of the Qt library. In particular I utilize the QWaitCondition and QMutex for signalling. The underlying queue uses QSharedPointer to store the items in queue, but some of you may want to use the QSharedDataPointer instead (the decision as to why is up to you).&lt;br /&gt;
&lt;br /&gt;
Anyway, I thought I&#39;d share it with all of you:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: cpp&quot;&gt;#ifndef BLOCKING_QUEUE_H
#define BLOCKING_QUEUE_H

#include &amp;lt;QObject&amp;gt;
#include &amp;lt;QSharedPointer&amp;gt;
#include &amp;lt;QWaitCondition&amp;gt;
#include &amp;lt;QMutex&amp;gt;
#include &amp;lt;queue&amp;gt;

namespace Concurrency
{
    template&amp;lt;typename Data&amp;gt;
    class BlockingQueue
    {
    private:
        QMutex _mutex;
        QWaitCondition _monitor;
        volatile bool _closed;
        std::queue&amp;lt;QSharedPointer&amp;lt;Data&amp;gt;&amp;gt; _queue;

    public:
        BlockingQueue()
        {
            _closed = false;
        }

        ~BlockingQueue()
        {
        }

        void Close()
        {
            QMutexLocker locker(&amp;amp;_mutex);
            if(!_closed)
            {
                _closed = true;
                _monitor.wakeAll();
            }
        }

        size_t Size()
        {
            QMutexLocker locker(&amp;amp;_mutex);
            return _queue.size();
        }

        bool IsClosed()
        {
            return _closed;
        }
    
        bool Enqueue(QSharedPointer&amp;lt;Data&amp;gt; data)
        {
            QMutexLocker locker(&amp;amp;_mutex);

            // Make sure that the queue is not closed
            if(_closed)
            {
                return false;
            }

            _queue.push(data);
            
            // Signal all the waiting threads
            if(queue.size()==1)
            {
                _monitor.wakeAll();
            }

            return true;
        }
    
        bool TryDequeue(QSharedPointer&amp;lt;Data&amp;gt;&amp;amp; value, unsigned long time = ULONG_MAX)
        {
            QMutexLocker locker(&amp;amp;_mutex);

            // Block until something goes into the queue
            // or until the queue is closed
            while(_queue.empty())
            {
                if(_closed || !_monitor.wait(&amp;amp;_mutex, time))
                {
                    return false;
                }
            }
            
            if(!_closed)
            {
                // Dequeue the next item from the queue
                value = _queue.front();
                _queue.pop();
                return true;
            }
            else
            {
                return false;
            }
        }
    };

#include &quot;BlockingQueue.cpp&quot;
}
#endif //BLOCKING_QUEUE_H
&lt;/pre&gt;

There are some issues with closing the queue at the moment. Working to fix it.
</content><link rel='replies' type='application/atom+xml' href='http://codesprout.blogspot.com/feeds/3475011958084367631/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://codesprout.blogspot.com/2012/11/i-recently-had-to-build-my-own-blocking.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4158593070832043065/posts/default/3475011958084367631'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4158593070832043065/posts/default/3475011958084367631'/><link rel='alternate' type='text/html' href='http://codesprout.blogspot.com/2012/11/i-recently-had-to-build-my-own-blocking.html' title=''/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/00374520101046586303</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4158593070832043065.post-2098534544635529002</id><published>2011-06-21T08:59:00.000-07:00</published><updated>2011-06-21T09:22:51.557-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="c++"/><category scheme="http://www.blogger.com/atom/ns#" term="c++ testing"/><category scheme="http://www.blogger.com/atom/ns#" term="google test"/><category scheme="http://www.blogger.com/atom/ns#" term="gtest"/><category scheme="http://www.blogger.com/atom/ns#" term="testing framework"/><category scheme="http://www.blogger.com/atom/ns#" term="unit testing"/><category scheme="http://www.blogger.com/atom/ns#" term="visual studio 2008"/><title type='text'>Using Google C++ Test Framework with Visual Studio 2008</title><content type='html'>I recently needed to add a testing framework to a Visual Studio 2008 C++ project and I stumbled on &lt;a href=&quot;http://code.google.com/p/googletest/&quot;&gt;Google&#39;s C+ Testing Framework&lt;/a&gt;. A lot of people seemed to be happy with it and I figured I&#39;d give it a try, if it&#39;s written by Google it can&#39;t be bad :) ^_^!&lt;br /&gt;&lt;br /&gt;It&#39;s been a couple of years since I&#39;ve done any C++ testing and as always: &lt;a href=&quot;http://stackoverflow.com/questions/531941/how-to-setup-google-c-testing-framework-gtest-on-visual-studio-2005&quot;&gt;StackOverflow had the answer for me&lt;/a&gt;. The guide is for Visual Studio 2005, but it works just as good with Visual Studio 2008. I was even able to get it all to build and run in 64 bit mode, so I was a pretty happy camper!&lt;br /&gt;&lt;br /&gt;Here are the instructions that worked for me with some minor modifications (verbatim from &lt;a href=&quot;http://stackoverflow.com/questions/531941/how-to-setup-google-c-testing-framework-gtest-on-visual-studio-2005/4222169#4222169&quot;&gt;nonsensical101&#39;s SO answer&lt;/a&gt;):&lt;br /&gt;&lt;br /&gt;&lt;blockquote&gt;(These instructions get the testing framework working for the Debug configuration. It should be pretty trivial to apply the same process to the Release configuration.)&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-weight:bold;&quot;&gt;Get Google C++ Testing Framework&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;    Download the latest gtest framework&lt;br /&gt;    Unzip to C:\gtest&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-weight:bold;&quot;&gt;Build the Framework Libraries&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;    Open C:\gtest\msvc\gtest.sln in Visual Studio&lt;br /&gt;    Set Configuration to &quot;Debug&quot;&lt;br /&gt;    Build Solution&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-weight:bold;&quot;&gt;Create and Configure Your Test Project&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;    Create a new solution and choose the template Visual C++ &gt; Win32 &gt; Win32 Console Application&lt;br /&gt;    &lt;span style=&quot;font-weight:bold;&quot;&gt;** If you choose to create an empty project, you will not have Stdafx.h (you may not actually need it anyway).&lt;/span&gt;&lt;br /&gt;    Right click the newly created project and choose Properties&lt;br /&gt;    Change Configuration to Debug.&lt;br /&gt;    Configuration Properties &gt; C/C++ &gt; General &gt; Additional Include Directories: Add C:\gtest\include&lt;br /&gt;    Configuration Properties &gt; C/C++ &gt; Code Generation &gt; Runtime Library: If your code links to a runtime DLL, choose Multi-threaded Debug DLL (/MDd). If not, choose Multi-threaded Debug (/MTd).&lt;br /&gt;    &lt;span style=&quot;font-weight:bold;&quot;&gt;** Note that both your project and gtest have to be build with the same Code Generation options: i.e. both have to be /MDd or /MTd&lt;/span&gt;&lt;br /&gt;    Configuration Properties &gt; Linker &gt; General &gt; Additional Library Directories: Add C:\gtest\msvc\gtest\Debug&lt;br /&gt;    Configuration Properties &gt; Linker &gt; Input &gt; Additional Dependencies: Add gtestd.lib&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-weight:bold;&quot;&gt;Verifying Everything Works&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;    Open the cpp in your Test Project containing the main() function.&lt;br /&gt;    Paste the following code:&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;brush: cpp&quot;&gt;&lt;br /&gt;// #include &quot;stdafx.h&quot; // &lt;-- I didn&#39;t need stdafx.h&lt;br /&gt;#include &lt;iostream&gt;&lt;br /&gt;&lt;br /&gt;#include &quot;gtest/gtest.h&quot;&lt;br /&gt;&lt;br /&gt;TEST(sample_test_case, sample_test)&lt;br /&gt;{&lt;br /&gt;    EXPECT_EQ(1, 1);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;int main(int argc, char** argv) &lt;br /&gt;{ &lt;br /&gt;    testing::InitGoogleTest(&amp;argc, argv); &lt;br /&gt;    RUN_ALL_TESTS(); &lt;br /&gt;    std::getchar(); // keep console window open until Return keystroke&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;    Debug &gt; Start Debugging&lt;br /&gt;&lt;br /&gt;If everything worked, you should see the console window appear and show you the unit test results.&lt;br /&gt;&lt;br /&gt;&lt;/blockquote&gt;&lt;br /&gt;&lt;br /&gt;Indeed, everything worked and I was able to see the test results. As I mentioned in my comments: make sure that you compile both the testing framework and the test project with the same output options and everything should go without a hitch. Now I&#39;m off to testing some C++ code, woohoo!</content><link rel='replies' type='application/atom+xml' href='http://codesprout.blogspot.com/feeds/2098534544635529002/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://codesprout.blogspot.com/2011/06/google-c-test-framework.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4158593070832043065/posts/default/2098534544635529002'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4158593070832043065/posts/default/2098534544635529002'/><link rel='alternate' type='text/html' href='http://codesprout.blogspot.com/2011/06/google-c-test-framework.html' title='Using Google C++ Test Framework with Visual Studio 2008'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/00374520101046586303</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4158593070832043065.post-9040633073617430207</id><published>2011-04-24T21:07:00.000-07:00</published><updated>2011-04-24T21:36:43.830-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term=".net"/><category scheme="http://www.blogger.com/atom/ns#" term=".NET 3.5"/><category scheme="http://www.blogger.com/atom/ns#" term="async"/><category scheme="http://www.blogger.com/atom/ns#" term="asynchronous"/><category scheme="http://www.blogger.com/atom/ns#" term="c#"/><category scheme="http://www.blogger.com/atom/ns#" term="client"/><category scheme="http://www.blogger.com/atom/ns#" term="http"/><category scheme="http://www.blogger.com/atom/ns#" term="socket programming"/><category scheme="http://www.blogger.com/atom/ns#" term="sockets"/><category scheme="http://www.blogger.com/atom/ns#" term="state machine"/><title type='text'>Asynchronous HTTP Client</title><content type='html'>I recently came across the need to create an asynchronous HTTP client and I went through some examples online but I found that asynchronous socket connections can be somewhat difficult to manage. Due to the &quot;unreliable&quot; nature of the internet, there can be multiple exceptions and errors that may leave your HTTP client hanging in an invalid state. So instead of writing numerous exception cases and verifications at each stage, I tried to simplify the design by making the client behave like a state machine. So let&#39;s look at some of the code...&lt;br /&gt;&lt;br /&gt;First, we&#39;ll start with the underlying data required for data required for each asynchronous request (which I called an AsyncTask):&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;brush: csharp&quot;&gt;&lt;br /&gt;    public class AsyncTask&lt;br /&gt;    {&lt;br /&gt;        public byte[] ReceiveBuffer { get; private set; }&lt;br /&gt;        public int TotalBytesReceived { get; set; }&lt;br /&gt;        public int BytesReceived { get; set; }&lt;br /&gt;        public string DocSource { get; set; }&lt;br /&gt;        public string Host { get; private set; }&lt;br /&gt;        public int Port { get; private set; }&lt;br /&gt;        public string Path { get; private set; }&lt;br /&gt;        public IPAddress[] Addresses { get; private set; }&lt;br /&gt;        public AsyncTask(string host, int port, string path)&lt;br /&gt;        {&lt;br /&gt;            ReceiveBuffer = new byte[256];&lt;br /&gt;            TotalBytesReceived = 0;&lt;br /&gt;            BytesReceived = -1; // can&#39;t be zero!&lt;br /&gt;            Host = host;&lt;br /&gt;            Port = port;&lt;br /&gt;            Path = path;&lt;br /&gt;            Addresses = Dns.GetHostEntry(Host).AddressList;&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;In addition to a data structure to hold the internals associated with each task, we also need enumeration of the possible client states. I&#39;ve come up with 11 states, but you can get by with 7 just fine. The reason I have the extra 4 states is just for getting a bit more information as to what the client is currently doing.&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;brush: csharp&quot;&gt;&lt;br /&gt;    public enum EClientState&lt;br /&gt;    {&lt;br /&gt;        Available = 0,&lt;br /&gt;        Connecting,&lt;br /&gt;        Connected,&lt;br /&gt;        Disconnecting,&lt;br /&gt;        Disconnected,&lt;br /&gt;        Sending,&lt;br /&gt;        SendDone,&lt;br /&gt;        Receiving,&lt;br /&gt;        ReceiveDone,&lt;br /&gt;        Failed,&lt;br /&gt;        CleanUp&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The core function of the client is the ChangeState method, which acts as the brain of the client: it manages the changes of states and enforces strict rules on how state changes can occur. If the client attempts to perform an invalid change state, then the method throws an exception. The idea is that if there is a failure at any stage, then the client can just change the state to Failed and the class will automatically clean up the state in order to resume &quot;normal&quot; operation.&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;brush: csharp&quot;&gt;&lt;br /&gt;private void ChangeState(EClientState state)&lt;br /&gt;{&lt;br /&gt;    lock (_sync) // re-entrant lock&lt;br /&gt;    {&lt;br /&gt;        try&lt;br /&gt;        {&lt;br /&gt;            switch (state)&lt;br /&gt;            {&lt;br /&gt;                case EClientState.Available:&lt;br /&gt;                    if (_clientState != EClientState.CleanUp)&lt;br /&gt;                    {&lt;br /&gt;                        ThrowInvalidStateException(_clientState, state);&lt;br /&gt;                    }&lt;br /&gt;                    else&lt;br /&gt;                    {&lt;br /&gt;                        _clientState = state;&lt;br /&gt;                        //Console.WriteLine(&quot;Client &quot; + _clientId + &quot;: &quot; + _clientState);&lt;br /&gt;                    }&lt;br /&gt;                    break;&lt;br /&gt;                case EClientState.Connecting:&lt;br /&gt;                    if (_clientState != EClientState.Available)&lt;br /&gt;                    {&lt;br /&gt;                        ThrowInvalidStateException(_clientState, state);&lt;br /&gt;                    }&lt;br /&gt;                    else&lt;br /&gt;                    {&lt;br /&gt;                        _clientState = state;&lt;br /&gt;                        //Console.WriteLine(&quot;Client &quot; + _clientId + &quot;: &quot; + _clientState);&lt;br /&gt;                        BeginConnect();&lt;br /&gt;                    }&lt;br /&gt;                    break;&lt;br /&gt;                case EClientState.Connected:&lt;br /&gt;                    if (_clientState != EClientState.Connecting)&lt;br /&gt;                    {&lt;br /&gt;                        ThrowInvalidStateException(_clientState, state);&lt;br /&gt;                    }&lt;br /&gt;                    else&lt;br /&gt;                    {&lt;br /&gt;                        _clientState = state;&lt;br /&gt;                        //Console.WriteLine(&quot;Client &quot; + _clientId + &quot;: &quot; + _clientState);&lt;br /&gt;                        ChangeState(EClientState.Sending);&lt;br /&gt;                    }&lt;br /&gt;                    break;&lt;br /&gt;                case EClientState.Disconnecting:&lt;br /&gt;                    if (_clientState == EClientState.Available || &lt;br /&gt;                        _clientState == EClientState.CleanUp)&lt;br /&gt;                    {&lt;br /&gt;                        ThrowInvalidStateException(_clientState, state);&lt;br /&gt;                    }&lt;br /&gt;                    else&lt;br /&gt;                    {&lt;br /&gt;                        _clientState = state;&lt;br /&gt;                        //Console.WriteLine(&quot;Client &quot; + _clientId + &quot;: &quot; + _clientState);&lt;br /&gt;                        BeginDisconnect();&lt;br /&gt;                    }&lt;br /&gt;                    break;&lt;br /&gt;                case EClientState.Disconnected:&lt;br /&gt;                    if (_clientState != EClientState.Disconnecting)&lt;br /&gt;                    {&lt;br /&gt;                        ThrowInvalidStateException(_clientState, state);&lt;br /&gt;                    }&lt;br /&gt;                    else&lt;br /&gt;                    {&lt;br /&gt;                        _clientState = state;&lt;br /&gt;                        //Console.WriteLine(&quot;Client &quot; + _clientId + &quot;: &quot; + _clientState);&lt;br /&gt;                        ChangeState(EClientState.CleanUp);&lt;br /&gt;                    }&lt;br /&gt;                    break;&lt;br /&gt;                case EClientState.Sending:&lt;br /&gt;                    if (_clientState != EClientState.Connected)&lt;br /&gt;                    {&lt;br /&gt;                        ThrowInvalidStateException(_clientState, state);&lt;br /&gt;                    }&lt;br /&gt;                    else&lt;br /&gt;                    {&lt;br /&gt;                        _clientState = state;&lt;br /&gt;                        //Console.WriteLine(&quot;Client &quot; + _clientId + &quot;: &quot; + _clientState);&lt;br /&gt;                        BeginSend();&lt;br /&gt;                    }&lt;br /&gt;                    break;&lt;br /&gt;                case EClientState.SendDone:&lt;br /&gt;                    if (_clientState != EClientState.Sending)&lt;br /&gt;                    {&lt;br /&gt;                        ThrowInvalidStateException(_clientState, state);&lt;br /&gt;                    }&lt;br /&gt;                    else&lt;br /&gt;                    {&lt;br /&gt;                        _clientState = state;&lt;br /&gt;                        //Console.WriteLine(&quot;Client &quot; + _clientId + &quot;: &quot; + _clientState);&lt;br /&gt;                        ChangeState(EClientState.Receiving);&lt;br /&gt;                    }&lt;br /&gt;                    break;&lt;br /&gt;                case EClientState.Receiving:&lt;br /&gt;                    if (_clientState != EClientState.SendDone &amp;&amp;&lt;br /&gt;                        _clientState != EClientState.Receiving)&lt;br /&gt;                    {&lt;br /&gt;                        ThrowInvalidStateException(_clientState, state);&lt;br /&gt;                    }&lt;br /&gt;                    else&lt;br /&gt;                    {&lt;br /&gt;                        _clientState = state;&lt;br /&gt;                        //Console.WriteLine(&quot;Client &quot; + _clientId + &quot;: &quot; + _clientState);&lt;br /&gt;                        BeginReceive();&lt;br /&gt;                    }&lt;br /&gt;                    break;&lt;br /&gt;                case EClientState.ReceiveDone:&lt;br /&gt;                    if (_clientState != EClientState.Receiving)&lt;br /&gt;                    {&lt;br /&gt;                        ThrowInvalidStateException(_clientState, state);&lt;br /&gt;                    }&lt;br /&gt;                    else&lt;br /&gt;                    {&lt;br /&gt;                        _clientState = state;&lt;br /&gt;                        //Console.WriteLine(&quot;Client &quot; + _clientId + &quot;: &quot; + _clientState);&lt;br /&gt;                        ChangeState(EClientState.Disconnecting);&lt;br /&gt;                    }&lt;br /&gt;                    break;&lt;br /&gt;                case EClientState.Failed:&lt;br /&gt;                    if (_clientState == EClientState.CleanUp)&lt;br /&gt;                    {&lt;br /&gt;                        ThrowInvalidStateException(_clientState, state);&lt;br /&gt;                    }&lt;br /&gt;                    else&lt;br /&gt;                    {&lt;br /&gt;                        _clientState = EClientState.Failed;&lt;br /&gt;                        //Console.WriteLine(&quot;Client &quot; + _clientId + &quot;: &quot; + _clientState);&lt;br /&gt;                        ChangeState(EClientState.CleanUp);&lt;br /&gt;                    }&lt;br /&gt;                    break;&lt;br /&gt;                case EClientState.CleanUp:&lt;br /&gt;                    if (_socket.Connected)&lt;br /&gt;                    {&lt;br /&gt;                        ChangeState(EClientState.Disconnecting);&lt;br /&gt;                    }&lt;br /&gt;                    else&lt;br /&gt;                    {&lt;br /&gt;                        _clientState = state;&lt;br /&gt;                        //Console.WriteLine(&quot;Client &quot; + _clientId + &quot;: &quot; + _clientState);&lt;br /&gt;                        CleanUp();&lt;br /&gt;                    }&lt;br /&gt;                    break;&lt;br /&gt;                default:&lt;br /&gt;                    ThrowInvalidStateException(_clientState, state);&lt;br /&gt;                    break;&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;        catch (InvalidOperationException e)&lt;br /&gt;        {&lt;br /&gt;            throw e;&lt;br /&gt;        }&lt;br /&gt;        catch (Exception e)&lt;br /&gt;        {&lt;br /&gt;            Console.WriteLine(&quot;ChangeState Exception:\n\t[Source]: &quot; + e.Source + &quot;\n\t[Message]: &quot; + e.Message);&lt;br /&gt;            ChangeState(EClientState.Failed);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Finally, here is the client itself:&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;brush: csharp&quot;&gt;&lt;br /&gt;public class AsyncHttpClient:IHttpClient&lt;br /&gt;{&lt;br /&gt;    private static readonly int KILOBYTES = 1024;&lt;br /&gt;    private static readonly int _maxPageSize = 128 * KILOBYTES; // limit the page size to 128 KB&lt;br /&gt;&lt;br /&gt;    private Socket _socket;&lt;br /&gt;    private readonly int _clientId;&lt;br /&gt;    private EClientState _clientState;&lt;br /&gt;    &lt;br /&gt;    private AsyncTask _asyncTask;&lt;br /&gt;    private readonly object _sync;&lt;br /&gt;&lt;br /&gt;    public AsyncHttpClient(int clientId)&lt;br /&gt;    {&lt;br /&gt;        _sync = new object();&lt;br /&gt;        &lt;br /&gt;        // Initialize the socket&lt;br /&gt;        _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);&lt;br /&gt;&lt;br /&gt;        // Set the socket to be non-blocking&lt;br /&gt;        _socket.Blocking = false;&lt;br /&gt;&lt;br /&gt;        // Set the send and receive timeouts to 10 seconds   &lt;br /&gt;        _socket.SetSocketOption(SocketOptionLevel.Socket,&lt;br /&gt;            SocketOptionName.SendTimeout,&lt;br /&gt;            10000);&lt;br /&gt;&lt;br /&gt;        _socket.SetSocketOption(SocketOptionLevel.Socket,&lt;br /&gt;            SocketOptionName.ReceiveTimeout,&lt;br /&gt;            10000);&lt;br /&gt;&lt;br /&gt;        // Initialize the fields&lt;br /&gt;        _asyncTask = new AsyncTask(string.Empty, 80, string.Empty);&lt;br /&gt;        _clientId = clientId;&lt;br /&gt;        _clientState = EClientState.Available;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    #region IHttpClient Members&lt;br /&gt;    public event OnGetCompleteCallback OnGetCompleted;&lt;br /&gt;   &lt;br /&gt;    public void Get(string host)&lt;br /&gt;    {&lt;br /&gt;        Get(host, 80);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public void Get(string host, int port)&lt;br /&gt;    {&lt;br /&gt;        lock (_sync)&lt;br /&gt;        {&lt;br /&gt;            if (_clientState != EClientState.Available)&lt;br /&gt;            {&lt;br /&gt;                // Do not invoke a client that&#39;s allready working!&lt;br /&gt;                throw new InvalidOperationException(&quot;The client is not available! Current state: &quot; + _clientState.ToString());&lt;br /&gt;            }&lt;br /&gt;            else&lt;br /&gt;            {&lt;br /&gt;                try&lt;br /&gt;                {&lt;br /&gt;                    // Initialize the socket&lt;br /&gt;                    _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);&lt;br /&gt;&lt;br /&gt;                    // Set the socket to be non-blocking&lt;br /&gt;                    _socket.Blocking = false;&lt;br /&gt;&lt;br /&gt;                    // Set the send and receive timeouts to 10 seconds   &lt;br /&gt;                    _socket.SetSocketOption(SocketOptionLevel.Socket,&lt;br /&gt;                        SocketOptionName.SendTimeout,&lt;br /&gt;                        10000);&lt;br /&gt;&lt;br /&gt;                    _socket.SetSocketOption(SocketOptionLevel.Socket,&lt;br /&gt;                        SocketOptionName.ReceiveTimeout,&lt;br /&gt;                        10000);&lt;br /&gt;&lt;br /&gt;                    _asyncTask = new AsyncTask(host, port, string.Empty);&lt;br /&gt;                    ChangeState(EClientState.Connecting);&lt;br /&gt;                }&lt;br /&gt;                catch (Exception e)&lt;br /&gt;                {&lt;br /&gt;                    Console.WriteLine(&quot;Exception: &quot; + e.Message);&lt;br /&gt;                    ChangeState(EClientState.Failed);&lt;br /&gt;                }&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;    #endregion&lt;br /&gt;&lt;br /&gt;    private void ChangeState(EClientState state)&lt;br /&gt;    {&lt;br /&gt;        lock (_sync) // re-entrant lock&lt;br /&gt;        {&lt;br /&gt;            try&lt;br /&gt;            {&lt;br /&gt;                switch (state)&lt;br /&gt;                {&lt;br /&gt;                    case EClientState.Available:&lt;br /&gt;                        if (_clientState != EClientState.CleanUp)&lt;br /&gt;                        {&lt;br /&gt;                            ThrowInvalidStateException(_clientState, state);&lt;br /&gt;                        }&lt;br /&gt;                        else&lt;br /&gt;                        {&lt;br /&gt;                            _clientState = state;&lt;br /&gt;                            //Console.WriteLine(&quot;Client &quot; + _clientId + &quot;: &quot; + _clientState);&lt;br /&gt;                        }&lt;br /&gt;                        break;&lt;br /&gt;                    case EClientState.Connecting:&lt;br /&gt;                        if (_clientState != EClientState.Available)&lt;br /&gt;                        {&lt;br /&gt;                            ThrowInvalidStateException(_clientState, state);&lt;br /&gt;                        }&lt;br /&gt;                        else&lt;br /&gt;                        {&lt;br /&gt;                            _clientState = state;&lt;br /&gt;                            //Console.WriteLine(&quot;Client &quot; + _clientId + &quot;: &quot; + _clientState);&lt;br /&gt;                            BeginConnect();&lt;br /&gt;                        }&lt;br /&gt;                        break;&lt;br /&gt;                    case EClientState.Connected:&lt;br /&gt;                        if (_clientState != EClientState.Connecting)&lt;br /&gt;                        {&lt;br /&gt;                            ThrowInvalidStateException(_clientState, state);&lt;br /&gt;                        }&lt;br /&gt;                        else&lt;br /&gt;                        {&lt;br /&gt;                            _clientState = state;&lt;br /&gt;                            //Console.WriteLine(&quot;Client &quot; + _clientId + &quot;: &quot; + _clientState);&lt;br /&gt;                            ChangeState(EClientState.Sending);&lt;br /&gt;                        }&lt;br /&gt;                        break;&lt;br /&gt;                    case EClientState.Disconnecting:&lt;br /&gt;                        if (_clientState == EClientState.Available || &lt;br /&gt;                            _clientState == EClientState.CleanUp)&lt;br /&gt;                        {&lt;br /&gt;                            ThrowInvalidStateException(_clientState, state);&lt;br /&gt;                        }&lt;br /&gt;                        else&lt;br /&gt;                        {&lt;br /&gt;                            _clientState = state;&lt;br /&gt;                            //Console.WriteLine(&quot;Client &quot; + _clientId + &quot;: &quot; + _clientState);&lt;br /&gt;                            BeginDisconnect();&lt;br /&gt;                        }&lt;br /&gt;                        break;&lt;br /&gt;                    case EClientState.Disconnected:&lt;br /&gt;                        if (_clientState != EClientState.Disconnecting)&lt;br /&gt;                        {&lt;br /&gt;                            ThrowInvalidStateException(_clientState, state);&lt;br /&gt;                        }&lt;br /&gt;                        else&lt;br /&gt;                        {&lt;br /&gt;                            _clientState = state;&lt;br /&gt;                            //Console.WriteLine(&quot;Client &quot; + _clientId + &quot;: &quot; + _clientState);&lt;br /&gt;                            ChangeState(EClientState.CleanUp);&lt;br /&gt;                        }&lt;br /&gt;                        break;&lt;br /&gt;                    case EClientState.Sending:&lt;br /&gt;                        if (_clientState != EClientState.Connected)&lt;br /&gt;                        {&lt;br /&gt;                            ThrowInvalidStateException(_clientState, state);&lt;br /&gt;                        }&lt;br /&gt;                        else&lt;br /&gt;                        {&lt;br /&gt;                            _clientState = state;&lt;br /&gt;                            //Console.WriteLine(&quot;Client &quot; + _clientId + &quot;: &quot; + _clientState);&lt;br /&gt;                            BeginSend();&lt;br /&gt;                        }&lt;br /&gt;                        break;&lt;br /&gt;                    case EClientState.SendDone:&lt;br /&gt;                        if (_clientState != EClientState.Sending)&lt;br /&gt;                        {&lt;br /&gt;                            ThrowInvalidStateException(_clientState, state);&lt;br /&gt;                        }&lt;br /&gt;                        else&lt;br /&gt;                        {&lt;br /&gt;                            _clientState = state;&lt;br /&gt;                            //Console.WriteLine(&quot;Client &quot; + _clientId + &quot;: &quot; + _clientState);&lt;br /&gt;                            ChangeState(EClientState.Receiving);&lt;br /&gt;                        }&lt;br /&gt;                        break;&lt;br /&gt;                    case EClientState.Receiving:&lt;br /&gt;                        if (_clientState != EClientState.SendDone &amp;&amp;&lt;br /&gt;                            _clientState != EClientState.Receiving)&lt;br /&gt;                        {&lt;br /&gt;                            ThrowInvalidStateException(_clientState, state);&lt;br /&gt;                        }&lt;br /&gt;                        else&lt;br /&gt;                        {&lt;br /&gt;                            _clientState = state;&lt;br /&gt;                            //Console.WriteLine(&quot;Client &quot; + _clientId + &quot;: &quot; + _clientState);&lt;br /&gt;                            BeginReceive();&lt;br /&gt;                        }&lt;br /&gt;                        break;&lt;br /&gt;                    case EClientState.ReceiveDone:&lt;br /&gt;                        if (_clientState != EClientState.Receiving)&lt;br /&gt;                        {&lt;br /&gt;                            ThrowInvalidStateException(_clientState, state);&lt;br /&gt;                        }&lt;br /&gt;                        else&lt;br /&gt;                        {&lt;br /&gt;                            _clientState = state;&lt;br /&gt;                            //Console.WriteLine(&quot;Client &quot; + _clientId + &quot;: &quot; + _clientState);&lt;br /&gt;                            ChangeState(EClientState.Disconnecting);&lt;br /&gt;                        }&lt;br /&gt;                        break;&lt;br /&gt;                    case EClientState.Failed:&lt;br /&gt;                        if (_clientState == EClientState.CleanUp)&lt;br /&gt;                        {&lt;br /&gt;                            ThrowInvalidStateException(_clientState, state);&lt;br /&gt;                        }&lt;br /&gt;                        else&lt;br /&gt;                        {&lt;br /&gt;                            _clientState = EClientState.Failed;&lt;br /&gt;                            //Console.WriteLine(&quot;Client &quot; + _clientId + &quot;: &quot; + _clientState);&lt;br /&gt;                            ChangeState(EClientState.CleanUp);&lt;br /&gt;                        }&lt;br /&gt;                        break;&lt;br /&gt;                    case EClientState.CleanUp:&lt;br /&gt;                        if (_socket.Connected)&lt;br /&gt;                        {&lt;br /&gt;                            ChangeState(EClientState.Disconnecting);&lt;br /&gt;                        }&lt;br /&gt;                        else&lt;br /&gt;                        {&lt;br /&gt;                            _clientState = state;&lt;br /&gt;                            //Console.WriteLine(&quot;Client &quot; + _clientId + &quot;: &quot; + _clientState);&lt;br /&gt;                            CleanUp();&lt;br /&gt;                        }&lt;br /&gt;                        break;&lt;br /&gt;                    default:&lt;br /&gt;                        ThrowInvalidStateException(_clientState, state);&lt;br /&gt;                        break;&lt;br /&gt;                }&lt;br /&gt;            }&lt;br /&gt;            catch (InvalidOperationException e)&lt;br /&gt;            {&lt;br /&gt;                throw e;&lt;br /&gt;            }&lt;br /&gt;            catch (Exception e)&lt;br /&gt;            {&lt;br /&gt;                Console.WriteLine(&quot;ChangeState Exception:\n\t[Source]: &quot; + e.Source + &quot;\n\t[Message]: &quot; + e.Message);&lt;br /&gt;                ChangeState(EClientState.Failed);&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private void CleanUp()&lt;br /&gt;    {&lt;br /&gt;        if (OnGetCompleted != null)&lt;br /&gt;        {&lt;br /&gt;            OnGetCompleted(_asyncTask.DocSource, _asyncTask.Host, _clientId);&lt;br /&gt;        }&lt;br /&gt;        ChangeState(EClientState.Available);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private void ThrowInvalidStateException(EClientState currentState, EClientState newState)&lt;br /&gt;    {&lt;br /&gt;        throw new InvalidOperationException(&lt;br /&gt;            String.Format(&quot;Cannot change the state from {0} to {1}&quot;, &lt;br /&gt;            currentState, newState));&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private void BeginConnect()&lt;br /&gt;    {&lt;br /&gt;        BeginConnect(0);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private void BeginConnect(int endPointIndex)&lt;br /&gt;    {&lt;br /&gt;        if (_asyncTask.Addresses.Length &amp;lt;= endPointIndex)&lt;br /&gt;        {&lt;br /&gt;            // We don&#39;t have anymore end points to connect to&lt;br /&gt;            ChangeState(EClientState.Disconnecting);&lt;br /&gt;        }&lt;br /&gt;        else&lt;br /&gt;        {&lt;br /&gt;            EndPoint ep = new IPEndPoint(_asyncTask.Addresses[endPointIndex], _asyncTask.Port);&lt;br /&gt;&lt;br /&gt;            // Setup the async event arguments&lt;br /&gt;            SocketAsyncEventArgs e = new SocketAsyncEventArgs();&lt;br /&gt;&lt;br /&gt;            e.DisconnectReuseSocket = true;&lt;br /&gt;            e.RemoteEndPoint = ep;&lt;br /&gt;            e.Completed += new EventHandler&amp;lt;SocketAsyncEventArgs&amp;gt;(ConnectCallback);&lt;br /&gt;            e.UserToken = endPointIndex + 1;&lt;br /&gt;&lt;br /&gt;            bool completedAsync = false;&lt;br /&gt;            try&lt;br /&gt;            {&lt;br /&gt;                // Connect to the first available end point&lt;br /&gt;                completedAsync = _socket.ConnectAsync(e);&lt;br /&gt;            }&lt;br /&gt;            catch (SocketException se)&lt;br /&gt;            {&lt;br /&gt;                Console.WriteLine(&quot;Socket Exception: &quot; + se.ErrorCode + &quot; Message: &quot; + se.Message);&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;            if (!completedAsync)&lt;br /&gt;            {&lt;br /&gt;                // The call completed synchronously so invoke the callback ourselves.&lt;br /&gt;                ConnectCallback(this, e);&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private void ConnectCallback(object sender, SocketAsyncEventArgs e)&lt;br /&gt;    {&lt;br /&gt;        lock (_sync) // re-entrant lock&lt;br /&gt;        {&lt;br /&gt;            if (e.SocketError == SocketError.Success)&lt;br /&gt;            {&lt;br /&gt;                ChangeState(EClientState.Connected);&lt;br /&gt;            }&lt;br /&gt;            else if (_asyncTask.Addresses.Length &amp;gt; (int)e.UserToken)&lt;br /&gt;            {&lt;br /&gt;                // Try and connect to the next available end point&lt;br /&gt;                BeginConnect((int)e.UserToken);&lt;br /&gt;            }&lt;br /&gt;            else&lt;br /&gt;            {&lt;br /&gt;                Console.WriteLine(&quot;Socket Error: {0} when connecting to {1}&quot;,&lt;br /&gt;                    e.SocketError,&lt;br /&gt;                    _asyncTask.Host);&lt;br /&gt;                ChangeState(EClientState.Failed);&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private void BeginDisconnect()&lt;br /&gt;    {&lt;br /&gt;        if (_socket.Connected)&lt;br /&gt;        {&lt;br /&gt;            _socket.Shutdown(SocketShutdown.Both);&lt;br /&gt;&lt;br /&gt;            SocketAsyncEventArgs e = new SocketAsyncEventArgs();&lt;br /&gt;            e.DisconnectReuseSocket = false; // do not reuse the socket&lt;br /&gt;            e.Completed += new EventHandler&amp;lt;SocketAsyncEventArgs&amp;gt;(DisconnectCallback);&lt;br /&gt;            &lt;br /&gt;            bool completedAsync = false;&lt;br /&gt;            try&lt;br /&gt;            {&lt;br /&gt;                // fake async since we&#39;re not reusing the socket&lt;br /&gt;                completedAsync = true; &lt;br /&gt;                _socket.Close(); // close the socket&lt;br /&gt;                ChangeState(EClientState.Disconnected);&lt;br /&gt;                //completedAsync = _socket.DisconnectAsync(e);&lt;br /&gt;            }&lt;br /&gt;            catch (SocketException se)&lt;br /&gt;            {&lt;br /&gt;                Console.WriteLine(&quot;Socket Exception: &quot; + se.ErrorCode + &quot; Message: &quot; + se.Message);&lt;br /&gt;                ChangeState(EClientState.Failed);&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;            if (!completedAsync)&lt;br /&gt;            {&lt;br /&gt;                // The call completed synchronously so invoke the callback ourselves&lt;br /&gt;                DisconnectCallback(this, e);&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private void DisconnectCallback(object sender, SocketAsyncEventArgs e)&lt;br /&gt;    {&lt;br /&gt;        if (e.SocketError == SocketError.Success)&lt;br /&gt;        {&lt;br /&gt;            ChangeState(EClientState.Disconnected);&lt;br /&gt;        }&lt;br /&gt;        else&lt;br /&gt;        {&lt;br /&gt;            Console.WriteLine(&quot;Socket Error: {0} when disconnecting from {1}&quot;,&lt;br /&gt;                   e.SocketError,&lt;br /&gt;                   _asyncTask.Host);&lt;br /&gt;            ChangeState(EClientState.Failed);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private void BeginSend()&lt;br /&gt;    {&lt;br /&gt;        _clientState = EClientState.Sending;&lt;br /&gt;        Encoding ASCII = Encoding.ASCII;&lt;br /&gt;        string Get = &quot;GET /&quot; + _asyncTask.Path + &quot; HTTP/1.1\r\nHost: &quot; + _asyncTask.Host + &quot;\r\nConnection: Close\r\n\r\n&quot;;&lt;br /&gt;        byte[] buffer = ASCII.GetBytes(Get);&lt;br /&gt;&lt;br /&gt;        SocketAsyncEventArgs e = new SocketAsyncEventArgs();&lt;br /&gt;        e.SetBuffer(buffer, 0, buffer.Length);&lt;br /&gt;        e.Completed += new EventHandler&amp;lt;SocketAsyncEventArgs&amp;gt;(SendCallback);&lt;br /&gt;&lt;br /&gt;        bool completedAsync = false;&lt;br /&gt;&lt;br /&gt;        try&lt;br /&gt;        {&lt;br /&gt;            completedAsync = _socket.SendAsync(e);&lt;br /&gt;        }&lt;br /&gt;        catch (SocketException se)&lt;br /&gt;        {&lt;br /&gt;            Console.WriteLine(&quot;Socket Exception: &quot; + se.ErrorCode + &quot; Message: &quot; + se.Message);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        if (!completedAsync)&lt;br /&gt;        {&lt;br /&gt;            // The call completed synchronously so invoke the callback ourselves&lt;br /&gt;            SendCallback(this, e);&lt;br /&gt;        }&lt;br /&gt;        &lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private void SendCallback(object sender, SocketAsyncEventArgs e)&lt;br /&gt;    {&lt;br /&gt;        if (e.SocketError == SocketError.Success)&lt;br /&gt;        {&lt;br /&gt;            ChangeState(EClientState.SendDone);&lt;br /&gt;        }&lt;br /&gt;        else&lt;br /&gt;        {&lt;br /&gt;            Console.WriteLine(&quot;Socket Error: {0} when sending to {1}&quot;,&lt;br /&gt;                   e.SocketError,&lt;br /&gt;                   _asyncTask.Host);&lt;br /&gt;            ChangeState(EClientState.Failed);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private void BeginReceive()&lt;br /&gt;    {&lt;br /&gt;        if ( _clientState == EClientState.Receiving)&lt;br /&gt;        {&lt;br /&gt;            if (_asyncTask.BytesReceived != 0 &amp;&amp; _asyncTask.TotalBytesReceived &amp;lt;= _maxPageSize)&lt;br /&gt;            {&lt;br /&gt;                SocketAsyncEventArgs e = new SocketAsyncEventArgs();&lt;br /&gt;                e.SetBuffer(_asyncTask.ReceiveBuffer, 0, _asyncTask.ReceiveBuffer.Length);&lt;br /&gt;                e.Completed += new EventHandler&amp;lt;SocketAsyncEventArgs&amp;gt;(ReceiveCallback);&lt;br /&gt;                e.UserToken = _asyncTask.Host;&lt;br /&gt;&lt;br /&gt;                bool comletedAsync = false;&lt;br /&gt;                try&lt;br /&gt;                {&lt;br /&gt;                    comletedAsync = _socket.ReceiveAsync(e);&lt;br /&gt;                }&lt;br /&gt;                catch (SocketException se)&lt;br /&gt;                {&lt;br /&gt;                    Console.WriteLine(&quot;Error receiving data from: &quot; + _asyncTask.Host);&lt;br /&gt;                    Console.WriteLine(&quot;SocketException: {0} Error Code: {1}&quot;, se.Message, se.NativeErrorCode);&lt;br /&gt;&lt;br /&gt;                    ChangeState(EClientState.Failed);&lt;br /&gt;                }&lt;br /&gt;&lt;br /&gt;                if (!comletedAsync)&lt;br /&gt;                {&lt;br /&gt;                    // The call completed synchronously so invoke the callback ourselves&lt;br /&gt;                    ReceiveCallback(this, e);&lt;br /&gt;                }&lt;br /&gt;            }&lt;br /&gt;            else&lt;br /&gt;            {&lt;br /&gt;                //Console.WriteLine(&quot;Num bytes received: &quot; + _asyncTask.TotalBytesReceived);&lt;br /&gt;                ChangeState(EClientState.ReceiveDone);&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private void ReceiveCallback(object sender, SocketAsyncEventArgs args)&lt;br /&gt;    {&lt;br /&gt;        lock (_sync) // re-entrant lock&lt;br /&gt;        {&lt;br /&gt;            // Fast fail: should not be receiving data if the client&lt;br /&gt;            // is not in a receiving state.&lt;br /&gt;            if (_clientState == EClientState.Receiving)&lt;br /&gt;            {&lt;br /&gt;                String host = (String)args.UserToken;&lt;br /&gt;                &lt;br /&gt;                if (_asyncTask.Host == host &amp;&amp; args.SocketError == SocketError.Success)&lt;br /&gt;                {&lt;br /&gt;                    try&lt;br /&gt;                    {&lt;br /&gt;                        Encoding encoding = Encoding.ASCII;&lt;br /&gt;                        _asyncTask.BytesReceived = args.BytesTransferred;&lt;br /&gt;                        _asyncTask.TotalBytesReceived += _asyncTask.BytesReceived;&lt;br /&gt;                        _asyncTask.DocSource += encoding.GetString(_asyncTask.ReceiveBuffer, 0, _asyncTask.BytesReceived);&lt;br /&gt;&lt;br /&gt;                        BeginReceive();&lt;br /&gt;                    }&lt;br /&gt;                    catch (SocketException e)&lt;br /&gt;                    {&lt;br /&gt;                        Console.WriteLine(&quot;Error receiving data from: &quot; + host);&lt;br /&gt;                        Console.WriteLine(&quot;SocketException: {0} Error Code: {1}&quot;, e.Message, e.NativeErrorCode);&lt;br /&gt;&lt;br /&gt;                        ChangeState(EClientState.Failed);&lt;br /&gt;                    }&lt;br /&gt;                }&lt;br /&gt;                else if (_asyncTask.Host != host)&lt;br /&gt;                {&lt;br /&gt;                    Console.WriteLine(&quot;Warning: received a callback for {0}, but the client is currently working on {1}.&quot;,&lt;br /&gt;                        host, _asyncTask.Host);&lt;br /&gt;                }&lt;br /&gt;                else&lt;br /&gt;                {&lt;br /&gt;                    Console.WriteLine(&quot;Socket Error: {0} when receiving from {1}&quot;,&lt;br /&gt;                       args.SocketError,&lt;br /&gt;                       _asyncTask.Host);&lt;br /&gt;                    ChangeState(EClientState.Failed);&lt;br /&gt;                }&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;</content><link rel='replies' type='application/atom+xml' href='http://codesprout.blogspot.com/feeds/9040633073617430207/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://codesprout.blogspot.com/2011/04/asynchronous-http-client.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4158593070832043065/posts/default/9040633073617430207'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4158593070832043065/posts/default/9040633073617430207'/><link rel='alternate' type='text/html' href='http://codesprout.blogspot.com/2011/04/asynchronous-http-client.html' title='Asynchronous HTTP Client'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/00374520101046586303</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4158593070832043065.post-1932327609326755096</id><published>2011-03-07T21:16:00.000-08:00</published><updated>2011-03-07T22:59:38.682-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="asp.net"/><category scheme="http://www.blogger.com/atom/ns#" term="asp.net-mvc"/><category scheme="http://www.blogger.com/atom/ns#" term="c#"/><category scheme="http://www.blogger.com/atom/ns#" term="derobins"/><category scheme="http://www.blogger.com/atom/ns#" term="derobins-wmd"/><category scheme="http://www.blogger.com/atom/ns#" term="markdown"/><category scheme="http://www.blogger.com/atom/ns#" term="markdown-editor"/><category scheme="http://www.blogger.com/atom/ns#" term="mvc"/><category scheme="http://www.blogger.com/atom/ns#" term="partial-view"/><category scheme="http://www.blogger.com/atom/ns#" term="user-control"/><category scheme="http://www.blogger.com/atom/ns#" term="wmd"/><category scheme="http://www.blogger.com/atom/ns#" term="wysiwyg"/><title type='text'>WYSIWYG: derobins wmd markdown editor in a partial view</title><content type='html'>Putting &lt;a href=&quot;https://github.com/derobins/wmd&quot;&gt;derobins wmd markdown editor&lt;/a&gt; in a partial view was very easy, so this should be a pretty straight forward post. The main benefit of placing your wysiwyg editor in a partial view is that you can treat it like a widget and display it anywhere on your web site with ease. However, I am yet to try and capture the content of the editor. I hope that capturing the input from the editor in the partial view will not be that difficult, but if it turns out to be something messy, then this idea might have to get scrapped.&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-weight:bold;&quot;&gt;Installation&lt;/span&gt;&lt;br /&gt;The &lt;a href=&quot;https://github.com/derobins/wmd/blob/master/readme.txt&quot;&gt;installation instructions&lt;/a&gt; were quite good, so the installation went without a hitch!&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-weight:bold;&quot;&gt;Usage&lt;/span&gt;&lt;br /&gt;I found it useful to muck with the &lt;a href=&quot;https://github.com/derobins/wmd/blob/master/wmd-test.html&quot;&gt;wmd test page&lt;/a&gt; a little, just to get a feel for the editor (which should be pretty familiar to people who are already familiar with StackOverflow).&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-weight:bold;&quot;&gt;Implementation&lt;/span&gt;&lt;br /&gt;Suppose you&#39;ve already added/merged the wmd style sheet to your web site&#39;s style sheet, now you just need to add the proper references in your master page, create a partial view with the wmd editor, and finally display the partial view on a page of your choice.&lt;br /&gt;&lt;br /&gt;Step 1: Follow the installation instructions for wmd.&lt;br /&gt;The installation are in the &lt;a href=&quot;https://github.com/derobins/wmd/blob/master/readme.txt&quot;&gt;readme file&lt;/a&gt; of the &lt;a href=&quot;https://github.com/derobins/wmd&quot;&gt;wmd download&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;Step 2: Create a partial view for the editor (I called mine MarkdownControl).&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;brush: csharp&quot;&gt;&lt;br /&gt;&amp;lt;%@ Control Language=&quot;C#&quot; Inherits=&quot;System.Web.Mvc.ViewUserControl&amp;lt;dynamic&amp;gt;&quot; %&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;div id=&quot;wmd-editor&quot; class=&quot;wmd-panel&quot;&amp;gt;&lt;br /&gt; &amp;lt;div id=&quot;wmd-button-bar&quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt; &amp;lt;textarea id=&quot;wmd-input&quot;&amp;gt;&amp;lt;/textarea&amp;gt;&lt;br /&gt;&amp;lt;/div&amp;gt;&lt;br /&gt;&amp;lt;div id=&quot;wmd-preview&quot; class=&quot;wmd-panel&quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Step 3: Display the control in a page of your choice:&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;brush: csharp&quot;&gt;&lt;% Html.RenderPartial(&quot;MarkdownControl&quot;); %&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;And there you have it: a WYSIWYG editor in a partial view which you can display anywhere on your web site! You can see my implementation in action here: &lt;a href=&quot;http://www.mydevarmy.com/Competition/Propose&quot;&gt;www.mydevarmy.com/Competition/Propose&lt;/a&gt;</content><link rel='replies' type='application/atom+xml' href='http://codesprout.blogspot.com/feeds/1932327609326755096/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://codesprout.blogspot.com/2011/03/wysiwyg-derobins-wmd-markdown-editor-in.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4158593070832043065/posts/default/1932327609326755096'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4158593070832043065/posts/default/1932327609326755096'/><link rel='alternate' type='text/html' href='http://codesprout.blogspot.com/2011/03/wysiwyg-derobins-wmd-markdown-editor-in.html' title='WYSIWYG: derobins wmd markdown editor in a partial view'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/00374520101046586303</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4158593070832043065.post-6669505213830404579</id><published>2011-03-05T19:43:00.000-08:00</published><updated>2011-03-06T12:44:26.308-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term=".net"/><category scheme="http://www.blogger.com/atom/ns#" term="asp.net"/><category scheme="http://www.blogger.com/atom/ns#" term="asp.net-mvc"/><category scheme="http://www.blogger.com/atom/ns#" term="authentication"/><category scheme="http://www.blogger.com/atom/ns#" term="c#"/><category scheme="http://www.blogger.com/atom/ns#" term="dotnetopenauth"/><category scheme="http://www.blogger.com/atom/ns#" term="mvc"/><category scheme="http://www.blogger.com/atom/ns#" term="openid"/><title type='text'>ASP.NET MVC: using DotNetOpenAuth to create a simple OpenID log in</title><content type='html'>I recently started dabbling in ASP.NET MVC in an effort to make my own &lt;a href=&quot;http://www.mydevarmy.com&quot;&gt;competative crowdsourcing web site&lt;/a&gt;. The nature of crowdsourcing is such that it requires multiple people to come together on the internet and work on the same project, but I wouldn&#39;t necessarily know who those people are, what are their intentions and much less have a reasonable way to ensure that they&#39;re all going to &quot;play good.&quot; Developing the web site requires that the contributors have access to some parts of the project which should not be publicly available: e.g. the Web.config file (which contains the connection string of the database) and subsequently access to the database, since both the Web.config and the database will have to be modified as the web site grows. Of course this poses a serious problem for the privacy of the users: their personal information, such as e-mail address and password, may be accessible to members of the community as long as those members are also contributing to the web site.&lt;br /&gt;&lt;br /&gt;There are probably some very good ways to prevent the personal information of the users from leaking out, perhaps by providing various credential levels for the contributors and less trusted users will have a restricted access to the database, and/or coming up with a complex scheme to protect private information. In any case, the security solutions only seem to mask the problem and the root of the problem is that I had to store the passwords and verify the user log in against the database. Naturally, the best way to secure such private information is not to store it at all, so I turned to &lt;a href=&quot;http://openid.net/&quot;&gt;OpenID&lt;/a&gt;! I only allow users to log in to the web site with an open ID and that model seems to work very well for other successful web sites, such as StackOverflow.&lt;br /&gt;&lt;br /&gt;I got the latest &lt;a href=&quot;http://www.dotnetopenauth.net/&quot;&gt;DotNetOpenAuth&lt;/a&gt; library and since I&#39;m as a total &quot;noob&quot; I cracked open the sample projects I opened up the ASP.NET MVC sample only to find out that the sample is missing the M from the MVC, which is a pretty important letter! A few days later I stumbled across a &lt;a href=&quot;http://stackoverflow.com/questions/5133921/what-openid-solution-is-really-used-by-stackoverflow/5133923#5133923&quot;&gt;question on StackOverflow&lt;/a&gt; that gave me an opportunity to share my newly gained knowledge with the world! The OP was very satisfied with my answer and suggested that I write it in my blog, alas here I am writing about it!&lt;br /&gt;&lt;br /&gt;So what would a very simple OpenID authentication in the MVC framework look like? Well, have a look for yourself:&lt;br /&gt;&lt;br /&gt;1. We need a &lt;span style=&quot;font-weight:bold;&quot;&gt;Model&lt;/span&gt;:&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;brush: csharp&quot;&gt;&lt;br /&gt;public class User&lt;br /&gt;{&lt;br /&gt;    [DisplayName(&quot;User ID&quot;)]&lt;br /&gt;    public int UserID{ get; set; }&lt;br /&gt;&lt;br /&gt;    [Required]&lt;br /&gt;    [DisplayName(&quot;OpenID&quot;)]&lt;br /&gt;    public string OpenID { get; set; }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public class FormsAuthenticationService : IFormsAuthenticationService&lt;br /&gt;{&lt;br /&gt;    public void SignIn(string openID, bool createPersistentCookie)&lt;br /&gt;    {&lt;br /&gt;        if (String.IsNullOrEmpty(openID)) throw new ArgumentException(&quot;OpenID cannot be null or empty.&quot;, &quot;OpenID&quot;);&lt;br /&gt;&lt;br /&gt;        FormsAuthentication.SetAuthCookie(openID, createPersistentCookie);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public void SignOut()&lt;br /&gt;    {&lt;br /&gt;        FormsAuthentication.SignOut();&lt;br /&gt;    }&lt;br /&gt;}  &lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;2. We need a &lt;span style=&quot;font-weight:bold;&quot;&gt;View&lt;/span&gt;:&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;brush: csharp&quot;&gt;&lt;br /&gt;&lt;%@ Page Language=&quot;C#&quot; MasterPageFile=&quot;~/Views/Shared/Site.Master&quot; Inherits=&quot;System.Web.Mvc.ViewPage&lt;YourProject.Models.User&gt;&quot; %&gt;&lt;br /&gt;&lt;br /&gt;&lt;asp:Content ID=&quot;loginTitle&quot; ContentPlaceHolderID=&quot;TitleContent&quot; runat=&quot;server&quot;&gt;&lt;br /&gt;    Log in - YourWebSiteName&lt;br /&gt;&lt;/asp:Content&gt;&lt;br /&gt;&lt;asp:Content ID=&quot;loginContent&quot; ContentPlaceHolderID=&quot;MainContent&quot; runat=&quot;server&quot;&gt;&lt;br /&gt;        &lt;p&gt;&lt;br /&gt;            &lt;%--- If you have a domain, then you should sign up for an affiliate id with MyOpenID or something like that ---%&gt;&lt;br /&gt;            Please log in with your OpenID or &lt;a href=&quot;https://www.myopenid.com/signup?affiliate_id=????&quot;&gt;create an&lt;br /&gt;                OpenID with myOpenID&lt;/a&gt; if you don&#39;t have one.&lt;br /&gt;        &lt;/p&gt;&lt;br /&gt;        &lt;% &lt;br /&gt;        string returnURL = HttpUtility.UrlEncode(Request.QueryString[&quot;ReturnUrl&quot;]);&lt;br /&gt;        if (returnURL == null)&lt;br /&gt;        {&lt;br /&gt;            returnURL = string.Empty;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        using (Html.BeginForm(&quot;LogIn&quot;, &quot;User&quot;, returnURL))&lt;br /&gt;        {%&gt;&lt;br /&gt;            &lt;%= Html.LabelFor(m =&gt; m.OpenID)%&gt;:&lt;br /&gt;            &lt;%= Html.TextBoxFor(m =&gt; m.OpenID)%&gt;&lt;br /&gt;            &lt;input type=&quot;submit&quot; value=&quot;Log in&quot; /&gt;&lt;br /&gt;        &lt;% &lt;br /&gt;        } %&gt;&lt;br /&gt;&lt;br /&gt;        &lt;%--- Display Errors ---%&gt;&lt;br /&gt;        &lt;%= Html.ValidationSummary()%&gt;&lt;br /&gt;&lt;/asp:Content&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;3. And finally, we need a &lt;span style=&quot;font-weight:bold;&quot;&gt;Controller&lt;/span&gt;:&lt;br /&gt;&lt;pre class=&quot;brush: csharp&quot;&gt;&lt;br /&gt;[HandleError]&lt;br /&gt;public class UserController : Controller&lt;br /&gt;{&lt;br /&gt;    private static OpenIdRelyingParty openid = new OpenIdRelyingParty();&lt;br /&gt;    public IFormsAuthenticationService FormsService { get; set; }&lt;br /&gt;&lt;br /&gt;    protected override void Initialize(RequestContext requestContext)&lt;br /&gt;    {&lt;br /&gt;        if (FormsService == null) &lt;br /&gt;        {&lt;br /&gt;            FormsService = new FormsAuthenticationService(); &lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        base.Initialize(requestContext);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // **************************************&lt;br /&gt;    // URL: /User/LogIn&lt;br /&gt;    // **************************************&lt;br /&gt;    public ActionResult LogIn()&lt;br /&gt;    {&lt;br /&gt;        if (User.Identity.IsAuthenticated)&lt;br /&gt;        {&lt;br /&gt;            return RedirectToAction(&quot;Profile&quot;, &quot;User&quot;);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        Identifier openID;&lt;br /&gt;        if (Identifier.TryParse(Request.QueryString[&quot;dnoa.userSuppliedIdentifier&quot;], out openID))&lt;br /&gt;        {&lt;br /&gt;            return LogIn(new User { OpenID = openID }, Request.QueryString[&quot;ReturnUrl&quot;]);&lt;br /&gt;        }&lt;br /&gt;        else&lt;br /&gt;        {&lt;br /&gt;            return View();&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    [HttpPost]&lt;br /&gt;    public ActionResult LogIn(User model, string returnUrl)&lt;br /&gt;    {&lt;br /&gt;        string openID = ModelState.IsValid?model.OpenID:Request.Form[&quot;openid_identifier&quot;];&lt;br /&gt;&lt;br /&gt;        if (User.Identity.IsAuthenticated)&lt;br /&gt;        {&lt;br /&gt;            return RedirectToAction(&quot;Profile&quot;, &quot;User&quot;);&lt;br /&gt;        }&lt;br /&gt;        else if (!string.IsNullOrEmpty(openID))&lt;br /&gt;        {&lt;br /&gt;            return Authenticate(openID, returnUrl);&lt;br /&gt;        }&lt;br /&gt;        else if(ModelState.IsValid)&lt;br /&gt;        {&lt;br /&gt;            ModelState.AddModelError(&quot;error&quot;, &quot;The OpenID field is required.&quot;);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        // If we got this far, something failed, redisplay form&lt;br /&gt;        return View(model);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // **************************************&lt;br /&gt;    // URL: /User/LogOut&lt;br /&gt;    // **************************************&lt;br /&gt;    public ActionResult LogOut()&lt;br /&gt;    {&lt;br /&gt;        if (User.Identity.IsAuthenticated)&lt;br /&gt;        {&lt;br /&gt;            FormsService.SignOut();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        return RedirectToAction(&quot;Index&quot;, &quot;Home&quot;);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // **************************************&lt;br /&gt;    // URL: /User/Profile&lt;br /&gt;    // **************************************&lt;br /&gt;    [Authorize]&lt;br /&gt;    public ActionResult Profile(User model)&lt;br /&gt;    {&lt;br /&gt;        if (User.Identity.IsAuthenticated)&lt;br /&gt;        {&lt;br /&gt;            // ------- YOU CAN SKIP THIS SECTION ----------------&lt;br /&gt;            model = /*some code to get the user from the repository*/;&lt;br /&gt;&lt;br /&gt;            // If the user wasn&#39;t located in the database&lt;br /&gt;            // then add the user to our database of users&lt;br /&gt;            if (model == null)&lt;br /&gt;            {&lt;br /&gt;                model = RegisterNewUser(User.Identity.Name);&lt;br /&gt;            }&lt;br /&gt;            // --------------------------------------------------&lt;br /&gt;&lt;br /&gt;            return View(model);&lt;br /&gt;        }&lt;br /&gt;        else&lt;br /&gt;        {&lt;br /&gt;            return RedirectToAction(&quot;LogIn&quot;);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private User RegisterNewUser(string openID)&lt;br /&gt;    {&lt;br /&gt;        User user = new User{OpenID = openID};&lt;br /&gt;&lt;br /&gt;        // Create a new user model&lt;br /&gt;&lt;br /&gt;        // Submit the user to the database repository&lt;br /&gt;&lt;br /&gt;        // Update the user model in order to get the UserID, &lt;br /&gt;        // which is automatically generated from the DB.&lt;br /&gt;        // (you can use LINQ-to-SQL to map your model to the DB)&lt;br /&gt;&lt;br /&gt;        return user;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    [ValidateInput(false)]&lt;br /&gt;    private ActionResult Authenticate(string openID, string returnUrl)&lt;br /&gt;    {&lt;br /&gt;        var response = openid.GetResponse();&lt;br /&gt;        if (response == null)&lt;br /&gt;        {&lt;br /&gt;            // Stage 2: user submitting Identifier&lt;br /&gt;            Identifier id;&lt;br /&gt;            if (Identifier.TryParse(openID, out id))&lt;br /&gt;            {&lt;br /&gt;                try&lt;br /&gt;                {&lt;br /&gt;                    return openid.CreateRequest(openID).RedirectingResponse.AsActionResult();&lt;br /&gt;                }&lt;br /&gt;                catch (ProtocolException ex)&lt;br /&gt;                {&lt;br /&gt;                    ModelState.AddModelError(&quot;error&quot;, &quot;Invalid OpenID.&quot;);&lt;br /&gt;&lt;br /&gt;                    ModelState.AddModelError(&quot;error&quot;, ex.Message);&lt;br /&gt;                    return View(&quot;LogIn&quot;);&lt;br /&gt;                }&lt;br /&gt;            }&lt;br /&gt;            else&lt;br /&gt;            {&lt;br /&gt;                ModelState.AddModelError(&quot;error&quot;, &quot;Invalid OpenID.&quot;);&lt;br /&gt;                return View(&quot;LogIn&quot;);&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;        else&lt;br /&gt;        {&lt;br /&gt;            // Stage 3: OpenID Provider sending assertion response&lt;br /&gt;            switch (response.Status)&lt;br /&gt;            {&lt;br /&gt;                case AuthenticationStatus.Authenticated:&lt;br /&gt;                    Session[&quot;FriendlyIdentifier&quot;] = response.FriendlyIdentifierForDisplay;&lt;br /&gt;                    FormsAuthentication.SetAuthCookie(response.FriendlyIdentifierForDisplay, true);&lt;br /&gt;                    if (!string.IsNullOrEmpty(returnUrl))&lt;br /&gt;                    {&lt;br /&gt;                        return Redirect(returnUrl);&lt;br /&gt;                    }&lt;br /&gt;                    else&lt;br /&gt;                    {&lt;br /&gt;                        return RedirectToAction(&quot;Profile&quot;, &quot;User&quot;);&lt;br /&gt;                    }&lt;br /&gt;                case AuthenticationStatus.Canceled:&lt;br /&gt;                    ModelState.AddModelError(&quot;error&quot;, &quot;Authentication canceled at provider.&quot;);&lt;br /&gt;                    return View(&quot;LogIn&quot;);&lt;br /&gt;                case AuthenticationStatus.Failed:&lt;br /&gt;                    ModelState.AddModelError(&quot;error&quot;, &quot;Authentication failed: &quot; + response.Exception.Message);&lt;br /&gt;                    return View(&quot;LogIn&quot;);&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;        return new EmptyResult();&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Wanna see it all in action? Go to my web site and log in with your OpenID: &lt;a href=&quot;http://www.mydevarmy.com/User/LogIn&quot;&gt;http://www.mydevarmy.com/User/LogIn&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Voila! You have a simple log in with OpenID!</content><link rel='replies' type='application/atom+xml' href='http://codesprout.blogspot.com/feeds/6669505213830404579/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://codesprout.blogspot.com/2011/03/using-dotnetopenauth-to-create-simple.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4158593070832043065/posts/default/6669505213830404579'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4158593070832043065/posts/default/6669505213830404579'/><link rel='alternate' type='text/html' href='http://codesprout.blogspot.com/2011/03/using-dotnetopenauth-to-create-simple.html' title='ASP.NET MVC: using DotNetOpenAuth to create a simple OpenID log in'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/00374520101046586303</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry></feed>