Welcome!

Microsoft Cloud Authors: Janakiram MSV, Yeshim Deniz, David H Deans, Andreas Grabner, Stackify Blog

Related Topics: Microsoft Cloud, Mobile IoT

Microsoft Cloud: Blog Feed Post

What Do You Call One Search Result From StackOverflow?

Windows Phone 7 301 Redirect Bug

Microsoft Session at Cloud Expo

I checked with the Windows Phone 7 team before putting this post out, and got the OK to write about it.  I hit this bug when building out my FriendLinks Windows Phone 7 application, and was surprised to find it was a bona fide bug and not a problem with my coding skills.  If there was a default value in the constructor for any new project I start, it would look something like:

codingErrorResponsibilty == this.programmerName;

In any event, here’s the cruxt of the bug.  If you are using HttpWebRequest developing on Windows Phone 7, and you get a 301 redirect returned from the web server, and that web server sets a cookie, the current build (as of 03/16/10 at Mix10) of Windows Phone 7 will throw an exception.

In the case of my applications, I was trying to determine the title of the page as defined by the “<title></title>” tags for a given URL.  The function I wrote for this was:

try
{
    WebResponse response = ((HttpWebRequest)result.AsyncState)
                            .EndGetResponse(result);
    StreamReader reader = new StreamReader(response.GetResponseStream());
    string responseString = reader.ReadToEnd();
    string regex = @"(?<=<title.*>)([\s\S]*)(?=</title>)";

    if (new List<string>(response.Headers.AllKeys).Contains("Content-Type"))
    {
        if (response.Headers["Content-Type"].StartsWith("text/html"))
        {
            Regex ex = new Regex(regex, RegexOptions.IgnoreCase);

            selectedUrlTitle = ex.Match(responseString).Value.Trim();

            if (String.IsNullOrEmpty(selectedUrlTitle))
            {
                selectedUrlTitle = "No title for page";
            }
        }

    }
    
    UrlTitleRequestCompleted(this, EventArgs.Empty);
}

For some URLs this was throwing the most elusive of all exceptions: CookieException.  Behold, I present to you a StackOverflowWhack! [note: a nod to GoogleWhacks]  There should really be a better name for that.

image

There is only one response for this search query at StackOverflow.  Interestingly enough, when I first hit this bug, there were no questions – this one was asked in the last week.

The debug information from Visual Studio was even less useful.  It was telling me that the cookie was too big.  A little searching revealed that this exception is thrown when you try to set a cookie larger than MaxCookieSize for a CookieContainer.  That value cannot be changed in Silverlight, and since I don’t control the remote web servers, I can’t control the cookie coming back.  Worse, whether or not the cookie was being set on the 301 redirects varied from domain to domain.  Some set it, some didn’t.

In using Fiddler2 to debug this problem, here is what a redirect looks like that won’t throw the CookieException:

HTTP/1.1 301 Moved Permanently
Proxy-Connection: Keep-Alive
Connection: Keep-Alive
Transfer-Encoding: chunked
Via: 1.1 RED-PRXY-21
Date: Wed, 03 Mar 2010 02:55:15 GMT
Location: http://blogs.bnet.com/career-advice/?p=101
Content-Type: text/html; charset=UTF-8
Server: Apache
Set-Cookie: supr=supr301; path=/; domain=.su.pr
Vary: Accept-Encoding

In this case, su.pr didn’t try to set the cookie.  And here is a 301 redirect that tries to set a cookie:

HTTP/1.1 301 Moved
Proxy-Connection: Keep-Alive
Connection: Keep-Alive
Content-Length: 381
Via: 1.1 RED-PRXY-21
Date: Wed, 03 Mar 2010 02:57:15 GMT
Location: http://www.allfacebook.com/2010/03/facebook-developers-see-
               dramatic-drop-in-traffic-following-removal-of-notifications/
Content-Type: text/html; charset=utf-8
Server: nginx/0.7.42
Set-Cookie: _bit=4b8dd00b-0013c-01992-b5a08fa8;domain=.bit.ly;
                expires=Sun Aug 29 22:57:15 2010;path=/; HttpOnly
MIME-Version: 1.0

In this case, bit.ly is in fact trying to set a cookie.  What helped lead me down the path of figuring this out was a short.to link that forwarded to a bit.ly link.  Here’s the chain of raw headers:

HTTP/1.1 301 Moved Permanently
Proxy-Connection: Keep-Alive
Connection: Keep-Alive
Content-Length: 0
Via: 1.1 RED-PRXY-21
Expires: Fri, 01 Jan 1990 00:00:00 GMT
Date: Wed, 03 Mar 2010 02:58:43 GMT
Location: http://bit.ly/8ZyVoz
Content-Type: text/html; charset=utf-8
Server: Google Frontend
Cache-Control: no-cache
X-XSS-Protection: 0

HTTP/1.1 301 Moved
Proxy-Connection: Keep-Alive
Connection: Keep-Alive
Content-Length: 312
Via: 1.1 RED-PRXY-21
Date: Wed, 03 Mar 2010 02:58:44 GMT
Location: http://news.cnet.com/8301-13578_3-10462563-38.html
Content-Type: text/html; charset=utf-8
Server: nginx/0.7.42
Set-Cookie: _bit=4b8dd064-000f6-0198d-b5a08fa8;domain=.bit.ly;
                expires=Sun Aug 29 22:58:44 2010;path=/; HttpOnly
MIME-Version: 1.0

As you can see here, the first header revealed a 301 to a bit.ly URL, which then tried to redirect to a news.com article.  Some other offenders of this cookie setting on 301 redirects are FourSquare and TechCrunch.  Mind you, this isn’t a bug in their 301 redirect, it’s a bug in how Windows Phone 7 handles the redirect.

I ultimately had to abandon this path to get the page title because once that CookieException is thrown, there is no data in the exception that allows you to get access to the header.  The exception is thrown when the WebResponse object is being set to the result of reading to the end of the asynch response.  The CookieException itself doesn’t reveal any of the 301 redirect information, so recovering from this exception is next to impossible, except to abandon trying to get the URL title.

For my specific app, I needed to get that title information, and since the vast majority of links coming through Twitter were bit.ly, I needed another way.  Mercifully, TechMeme reveals this information through their API.

So there you go – if you are getting a 301 redirect in a HttpWebRequest, and your code is throwing a CookieException, now you know why.  This is a filed bug and should be fixed, but given the amount of excitement around Windows Phone 7 development right now, I wanted to try and save people pain and suffering.  It’s better that only one of us lose hair.

Read the original blog entry...

More Stories By Brandon Watson

Brandon Watson is Director for Windows Phone 7. He specifically focuses on developers and the developer platform. He rejoined Microsoft in 2008 after nearly a decade on Wall Street and running successful start-ups. He has both an engineering degree and an economics degree from the University of Pennsylvania, as well as an MBA from The Wharton School of Business, and blogs at www.manyniches.com.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


@ThingsExpo Stories
In this strange new world where more and more power is drawn from business technology, companies are effectively straddling two paths on the road to innovation and transformation into digital enterprises. The first path is the heritage trail – with “legacy” technology forming the background. Here, extant technologies are transformed by core IT teams to provide more API-driven approaches. Legacy systems can restrict companies that are transitioning into digital enterprises. To truly become a lead...
SYS-CON Events announced today that Daiya Industry will exhibit at the Japanese Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Ruby Development Inc. builds new services in short period of time and provides a continuous support of those services based on Ruby on Rails. For more information, please visit https://github.com/RubyDevInc.
SYS-CON Events announced today that CAST Software will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. CAST was founded more than 25 years ago to make the invisible visible. Built around the idea that even the best analytics on the market still leave blind spots for technical teams looking to deliver better software and prevent outages, CAST provides the software intelligence that matter ...
As businesses evolve, they need technology that is simple to help them succeed today and flexible enough to help them build for tomorrow. Chrome is fit for the workplace of the future — providing a secure, consistent user experience across a range of devices that can be used anywhere. In her session at 21st Cloud Expo, Vidya Nagarajan, a Senior Product Manager at Google, will take a look at various options as to how ChromeOS can be leveraged to interact with people on the devices, and formats th...
SYS-CON Events announced today that Yuasa System will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Yuasa System is introducing a multi-purpose endurance testing system for flexible displays, OLED devices, flexible substrates, flat cables, and films in smartphones, wearables, automobiles, and healthcare.
SYS-CON Events announced today that Dasher Technologies will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Dasher Technologies, Inc. ® is a premier IT solution provider that delivers expert technical resources along with trusted account executives to architect and deliver complete IT solutions and services to help our clients execute their goals, plans and objectives. Since 1999, we'v...
Enterprises have taken advantage of IoT to achieve important revenue and cost advantages. What is less apparent is how incumbent enterprises operating at scale have, following success with IoT, built analytic, operations management and software development capabilities – ranging from autonomous vehicles to manageable robotics installations. They have embraced these capabilities as if they were Silicon Valley startups. As a result, many firms employ new business models that place enormous impor...
SYS-CON Events announced today that Massive Networks, that helps your business operate seamlessly with fast, reliable, and secure internet and network solutions, has been named "Exhibitor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. As a premier telecommunications provider, Massive Networks is headquartered out of Louisville, Colorado. With years of experience under their belt, their team of...
SYS-CON Events announced today that Taica will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Taica manufacturers Alpha-GEL brand silicone components and materials, which maintain outstanding performance over a wide temperature range -40C to +200C. For more information, visit http://www.taica.co.jp/english/.
SYS-CON Events announced today that TidalScale, a leading provider of systems and services, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. TidalScale has been involved in shaping the computing landscape. They've designed, developed and deployed some of the most important and successful systems and services in the history of the computing industry - internet, Ethernet, operating s...
SYS-CON Events announced today that MIRAI Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. MIRAI Inc. are IT consultants from the public sector whose mission is to solve social issues by technology and innovation and to create a meaningful future for people.
SYS-CON Events announced today that IBM has been named “Diamond Sponsor” of SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California.
SYS-CON Events announced today that TidalScale will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. TidalScale is the leading provider of Software-Defined Servers that bring flexibility to modern data centers by right-sizing servers on the fly to fit any data set or workload. TidalScale’s award-winning inverse hypervisor technology combines multiple commodity servers (including their ass...
Join IBM November 1 at 21st Cloud Expo at the Santa Clara Convention Center in Santa Clara, CA, and learn how IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Cognitive analysis impacts today’s systems with unparalleled ability that were previously available only to manned, back-end operations. Thanks to cloud processing, IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Imagine a robot vacuum that becomes your personal assistant tha...
Widespread fragmentation is stalling the growth of the IIoT and making it difficult for partners to work together. The number of software platforms, apps, hardware and connectivity standards is creating paralysis among businesses that are afraid of being locked into a solution. EdgeX Foundry is unifying the community around a common IoT edge framework and an ecosystem of interoperable components.
As popularity of the smart home is growing and continues to go mainstream, technological factors play a greater role. The IoT protocol houses the interoperability battery consumption, security, and configuration of a smart home device, and it can be difficult for companies to choose the right kind for their product. For both DIY and professionally installed smart homes, developers need to consider each of these elements for their product to be successful in the market and current smart homes.
Infoblox delivers Actionable Network Intelligence to enterprise, government, and service provider customers around the world. They are the industry leader in DNS, DHCP, and IP address management, the category known as DDI. We empower thousands of organizations to control and secure their networks from the core-enabling them to increase efficiency and visibility, improve customer service, and meet compliance requirements.
With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend 21st Cloud Expo October 31 - November 2, 2017, at the Santa Clara Convention Center, CA, and June 12-14, 2018, at the Javits Center in New York City, NY, and learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation.
SYS-CON Events announced today that mruby Forum will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. mruby is the lightweight implementation of the Ruby language. We introduce mruby and the mruby IoT framework that enhances development productivity. For more information, visit http://forum.mruby.org/.
Digital transformation is changing the face of business. The IDC predicts that enterprises will commit to a massive new scale of digital transformation, to stake out leadership positions in the "digital transformation economy." Accordingly, attendees at the upcoming Cloud Expo | @ThingsExpo at the Santa Clara Convention Center in Santa Clara, CA, Oct 31-Nov 2, will find fresh new content in a new track called Enterprise Cloud & Digital Transformation.