Archive for the ‘ Internet Explorer ’ Category

Create and Read Cookies in ASP.NET


Cookies are small pieces of text which are created by websites and stored by the Internet browser in its cache for later use. Typically a cookie would contain information related to a surfer’s session in a particular website, such as the user name, items in a shopping cart, page layout preferences, etc.

When a surfer visits a website, a cookie would be created with his details, and when he returns to the site his details are loaded from the cookie and sent to the website. This can for example, allow the website to identify who the surfer is and load his last session back.

Cookies can be very useful but they are also easily accessible so it’s advisable to never store sensitive data, such as passwords or credit card numbers, in cookies.

In this short article I am going to show you how to create a cookie in ASP.NET, obviously using C#, and then I will also show you how to read your cookie’s value.

First you must create an ASP.NET Web Application, and once that’s done add two buttons and a label to your Default.aspx web form. The first button we will call“Save Cookie” and the second one “Load Cookie”. The label will be used to display the status on-screen.

In the event handler for the “Save Cookie” button we will create a cookie and add astring value to it. The code should look like this:

protected void btnSave_Click(object sender, EventArgs e)
{
    // Create a cookie object
    HttpCookie cookie = new HttpCookie("TestCookie");

    // Set the cookie's value
    cookie.Value = "Paul Mercieca";

    // Set the cookie's expiration date
    cookie.Expires = DateTime.Now.AddDays(7);

    // Add the cookie to the cookie collection
    Response.Cookies.Add(cookie);

    // Display the status
    lblStatus.Text = "Cookie has been created.";
}

The above code is quite simple. We are creating a cookie called “TestCookie” and assigning it my name as a value. Then we are setting an expiry date of 7 days for the cookie. This means that the cookie will remain valid for 7 days from creation. When that period expires the cookie will be deleted by the web browser. Finally we are adding our new cookie to the Response.Cookies collection which is actually an instance of HttpCookieCollection, and we are setting the status label’s text.

Now to read the cookie. To do this we need to access the HttpCookieCollection instance again by calling Request.Cookies as can be seen in the below code:

protected void btnLoad_Click(object sender, EventArgs e)
{
    // Retrieve the cookie from the cookie collection
    HttpCookie cookie = Request.Cookies["TestCookie"];

    // Verify the cookie exists
    if (cookie != null)
    {
        lblStatus.Text = string.Format("Hello {0}", cookie.Value.ToString());
    }
    else
    {
        lblStatus.Text = "Cookie not found.";
    }
}

Again, this code is very straight forward. All we are doing here is retrieving the “TestCookie” and verifying it exists. If it exists we are displaying the cookie’s value, which in this case is my name – “David Azzopardi”, and if it does not exist we are displaying “Cookie not found”.

And there you have it – creating and reading cookies with C# in ASP.NET.

Advertisements

Still Stuck With IE 6? Consider Just Jumping to IE 9


Odds are if you are viewing this Blog with IE 6 you are in a large, slow moving corporation. I really doubt normal folks reading this Blog would still have IE 6 installed on their home or small business computers. If so, Bad Geek, Bad Geek, now go think about what you are missing. Seriously there is no good reason for anyone to use IE 6, it is a 9 year old browser(warning clicking that link may display a disgusting image).

Internet ExplorerThe Internet moves fast, really fast and standards, trends and techniques change almost daily. Well maybe not really that fast, but at least the way we as developers and designers learn to leverage HTML, CSS2/3 and JavaScript. In the past 9 years we have learned to build some pretty amazing applications. Just think about it, back then AJAX was still just a household cleaner!

The real culprit behind the continued use of IE 6? Wellcorporations of courseChitcka did a survey of browser usage by the hour and determined the peak IE 6 usage hours were during the US work day. Why would the corporate world force their employees to use a less secure and less functional browser? Well they have built so many behind the firewall applications that are in a word, bad. Not bad in the fact they don’t work, but bad in the sense they were not written to have a forward life.

What is a ‘forward life’ you may ask, well its developing an application so that it cannot reasonably function in the near future as trends and standards progress. Think long Gevity.

Why Wait for IE 9?

With so much effort to get users to stop using IE 6 you may be wondering why I am espousing the idea of waiting for IE 9 as the natural upgrade path. The answer is two fold really, to avoid repeating yourself with IE 8 and to give you time to upgrade your applications.

Sadly the trend I am seeing in the corporate world right now is to upgrade to IE 7, again why? Well because most corporate IT directors have this long outdated mentality that you must wait 2-3 years for a release to be ‘stable’. This is modern day hog wash! These same IT decision makers probably drive a car built in the 70s I bet. Of course they don’t, they are probably already driving a 2011 model. Honestly there is no reason to not be using IE 8, or the latest FireFox or Chrome. So no, I am not going to advise IE 6 companies to plan a strategy to migrate to IE 8 specifically, but please do (like NOW). Just plan on moving to IE 9 next year as part of your plan. This really means upgrading your application to support the W3C standards, not a specific browser.

Time To Upgrade

IE 9 is set to release sometime next year, my guess is at MIX 11. Why, well Microsoft likes to use large events like MIX to make major releases. If you are not aware, MIX is Microsoft’s web technology conference, an ideal place to launch a new browser. This year at MIX 10 Microsoft unveiled a preview look at IE 9, with demonstrations of its new functionality and performance improvements.

So that gives you roughly 10 months to get ready, so get moving. This means you need to upgrade all of those poorly written applications from 2000-3, but seriously, isn’t an update long overdue for those applications anyway?

How Can You Test Your Applications Upgrades?

That’s pretty easy, just write your application to the standards. That means know HTML 4+ and CSS 3 and apply it to your applications. You can test in IE 8, FireFox and Chrome. And I well make a sizable wager that Microsoft will release previews of IE 9 later this year.Currently you can see use the IE 9 Developer Preview. If not I am sure you will see it before it is actually released so developers can really test their apps. But as usual, they are really wanting to see if IE 9 works in the real-world and fix any flaws unearthed by Beta testers.

The Moral of the Story

Companies still forcing their developers to create applications to support IE 6 are just hurting themselves. They are telling their employees they really do not care about their security and quality of life. For their developers they are saying this is a dead-end place to work, you can never advance your career.

Web standards are a great thing. They allow developers to code against a common target, not a browser. The browser is only responsible for rendering the application according to these standards. The browser competition is to perform this task the best. So far IE 9 looks to be doing a great job executing these standards. FireFox and Chrome are already implementing many of the newer standards. By creating applications to the standards you give your users the freedom of choice to use what browser they like best.

By avoiding IE 6 support corporations only stand to gain by freeing their developers to spend more resources on more modern applications. Applications that really take advantage of the standards that are driving great user experiences everyday. Each day these standards are exercised further by developers all over the world and the bar is constantly being raised to create great user experiences that make companies run efficiently and profitably. The choice to stick with a 9 year old, out dated and insecure browser is a choice that screams”This is a dead company, run far away.”

Working with the Internet Explorer Developer Tools


Internet Explorer has been out for a while now, and I am very pleased with it, especially from a developer’s perspective. First I am more and more appreciative of the IE team getting CSS compliant, this is making it so much easier to create a consistent design across browsers. If you want to appreciate the differences between the last three versions of Internet Explorer Smashing Magazine did a great article earlier this week. The thing that has truly changed my experience with client-side development (think JQuery and CSS) is the Internet Explorer Development Helper. In fact I can not imagine doing client-side development without it or FireBug in FireFox.

The Development Helper can either be invoked by selecting it from the Tools menu, or as I always do pressing F12. This launches a new window with all kinds of wonderful client-side development tools. The first thing that stands out are 4 tabs located below the menu (more on that later); HTML, CSS, Script and Profiler. The HTML table gives you manipulative access to the HTML. The CSS tab lets you access the CSS files loaded by the page. The Script tab lets you see and debug any JavaScript the page relies upon. The Profiler let you trace the page request and subsequent running of the scripts while the page is loaded.

HTML

HTML TabWhen I am working on CSS issues in my pages I spend a lot of time on this tab. The reason is the ability to see how style rules are applied to a specific DOM element and change that style applications real-time. There are 4 ways to view the CSS rules for an element; Style, Trace Styles, Layout and Attributes.

HTML TabThe HTML Style tab simple lists all the style rules in the order they are applied to the element. The rules are displayed in a tree hierarchy, with each selector having its rules displayed as child nodes. HTML TabIf a rule is overridden by another selector rule, then it is displayed with a strike through. Beside each rule is a checkbox, indicating if the rule is applied to the DOM element. Unchecking a rule will automatically cause the next matching rule to be applied to all elements that match that selector. You also have the freedom to select a rule, say background-color, and change it to another value. This will cause it to be applied to all elements that implement that rule. This is so valuable because now I can make minor tweaks to rules, selectors, etc to see how a change will affect the page without having to make the change in the stylesheet, save the file and reload the page.

HTML TabThe Trace Styles tab works almost the same as the Style tab, but instead of a treeview of CSS selectors and rules being displayed the CSS rules are listed for the DOM element with the ability to expand the selectors that apply to the element. You can again turn them on and off and adjust values as described before. I use this view more than the Style tab because it is much easier to see what I can adjust.

HTML TabThe Layout tab is much different than the two CSS tabs because it visualizes the box model of the element. This means you get to see the real height, width, margin, padding and offsets of the element. This is a very useful view when you are trying to work on layout and placement issues. I find it invaluable to understanding how a form using tables actually renders for example.

HTML TabFinally the Attribute tab lets you define element attributes at run-time. So you can add and set any attribute or style value at run-time. For the longest time I was very frustrated with the Developer Tools because I could not add style rules or change attributes (like table cell widths) without going back to the source, saving and reloading. So when I found I could do it here I was very happy. Working with FireBug in FireFox also allows this feature, so I was really happy learning how to do it in IE too.

Script

If you do any AJAX development you will spend a lot of time in the Script tab. In the past few years the debugging tools seem to have finally caught up to the need to adequately work with JavaScript. This has been the primary reason I stayed away from JavaScript development over the years, but now with JQuery and the IE Developer Tool I Love JavaScript Development.

The Script tab of the Developer Tool opens up a real debugging environment that you can set break points in your JavaScript and step through the code just like we are accustomed to doing in Visual Studio. It also has additional windows for watches (both local and developer defined), a Console and a Call Stack window.

Stepping through code works just like it does in Visual Studio. However if you have included a JavaScript file that has been minimized then you are going to have a very difficult time stepping through this code. If you are not familiar with minimizing JavaScript it basically means removing the unneeded whitespace characters that are ignored by the JavaScript interpreter, making it much more compact to send down the wire. If you are developing this can be problematic because stepping through the code now is very difficult. I relate it to trying to step into one of the .NET libraries you do not have source code access, it just gives you a class view in Visual Studio.

Setting a watch is pretty easy, you can right click on a variable a selector, $(‘#myelement’) for example, etc. and you can just add the watch from the context menu. HTML TabOne thing to note is once you close the Developer Tools you will loose not only the breakpoints you have set, but also the watches you have set.

The Console window is pretty nice because it allows you to execute a JavaScript statement based on the current point you have set your breakpoint. By this I mean you can execute a statement and see the result in the window based on the current state of the client-side state. So if a JS variable has a value that is set after your breakpoint it will not be available, but you can ‘set’ that value in the console and maybe play some what if scenarios like I described above in the CSS tabs.

Call Stack if a nice idea, but in my experience not quite as useful because I tend to only see ‘anonymous JavaScript function’ listed. But it does sometime actually list the functions called on the way to the point of the breakpoint execution.

Profiler

The profiler is another invaluable tool, but its not obvious at first glance. The profiler monitors all the JavaScript execution during a monitoring session. To start profiling just click the ‘Start Profiling’ button then go back to the browser and use your web site. When you are done executing things return to the Web Development tool and click ‘Stop Profiling’.

HTML TabYou will then be able to view the results of the profiler in one of two ways; by function call or in an execution tree. The usefulness of the profiler is allowing you to see where bottlenecks and other inefficient code is located in your JavaScript. It tells you how many times a function was called and how long those calls took. It also tells you what file the function is located and what line it is located.

The results can be exported to a CSV file by clicking the third button from the left on the Profiler toolbar. Now you can view and manipulate the data in another tool if you want. The E-Mail form I am using for this demonstration is rather boring because it does not do much outside the JQuery framework. But just glancing over it I can see some potential optimizations I can make by reducing the number of times I make JQuery use the selector syntax for example.

Menu Options

So far I have just been talking about the tabs in the Developer Tools and have not even started with the menu options!!! So wait, there’s more 😉 I am not going to cover them all, but want to write about the cooler features.

Disable

This menu option gives you the ability to turn off scripts the pop-up blocker and even CSS. This means the browser will not execute these items. This can be a good way to test your application for downlevel browsers (think Lynx) and to see how a search engine spider might see your site. I like to turn off the scripts so I make sure my page will work where JavaScript is turned off. Granted I do not do that very often, but it is a nice way to test it out.

View

The View menu option is another useful feature because it overlays information on the page for applicable elements such as the CSS class, Id, tab index and Access Keys. This is really nice because now you can just glance at your page and see what these values are from a user’s perspective. So its another way to see things without having to view the source and search through the markup to find these values and make sure you are on the right element.

Outline

HTML TabThe Outline menu lets you turn on ‘outlines’ to visualize where a table, div or any other DOM element’s box is actually located on the page. When working on a new layout this is very helpful in determining where containers begin and end. In the screen shot shown here (click for a larger view), the DIVs are indicated with a thin green line. Images are outlined by purple.

Images

HTML TabThis menu option lets you visualize information about images or just turn them off all together. Again overlaying this information on an image is very helpful in determining the dimensions and file sizes. One problem I have is on small images it overlays the information, but only within the boundary of the image itself, which means you just get a pink box covering the image with no useable information. I hope they fix this issue and allow you to roll your mouse over the image and have the information naturally expand to a viewable tooltip type metaphor.

In the image shown here you can see it is highlighted in pink and see it trying to write out the image dimensions. This needs to be corrected in the next version of IE.

Cache

The Cache menu can be a developer’s best friend at times because you can designate that all supporting files must be retrieved from the server each time the page is requested. You can also manually clear cookies and the browser cache related to the URL.

Tools

Under Tools you can Resize the browser window to different potential user dimensions. I have always targeted my sites for an 800×600 box, but that is quickly fading away with larger monitors quickly becoming the defacto standard. Uber Geeks tend to run at super high resolutions so you can set the browser dimensions to larger screens as well or a custom height and width.

HTML TabThe ruler is a very neat tool, but not quite obvious at first. But you can pick a point on the page and drag the mouse from it to another point. A ruler is drawn from point A to point B. The length is displayed in the Ruler window that is open above the page.

HTML TabThe color picker is very useful when you are trying to determine a color on a web page. This will launch a tool window over the browser with a eye dropper mouse cursor. As you pass over elements in the page the color is grabbed by the tool and displayed in tool window. Clicking over an element will lock the color for you. Now clicking the ‘Copy and Close’ button will place the color’s HEX value in the clipboard so you can easily use it in your CSS or Paint.Net, etc.

Validate

Using valid HTML code is critical to having a good web site, in my opinion. You can get by with bad markup and CSS, but you are actually hurting yourself in the long run. The Validate menu lets you send your markup or CSS to W3C for actual validation. Additionally you can check for accessibility compliance, which is really handy. Now this is not going to be the ultimate accessibility feedback you might get from a tool like JAWs. But I highly recommend using as much validation as you can. One drawback is the tool wants to send the URL to the W3C online validation tool instead of posting the markup to the tool. So you cannot send anything from your local development machine, it has to be a public facing web site. So I hope this gets improved in future version.

Browser Modes

IE 8 is a game changer when it comes to supporting CSS standards. Prior to IE 8 Internet Explorer was known for doing things its own way as far as how it implemented CSS standards. This causes many web developers and designers to pull out their hair every time they build a user interface. Now the real problem is there are so many web sites out there that only conform to IE 6 or 7 standards. Microsoft has even been offering bribes to get folks to upgrade from IE 6, and as a web developer let me say PLEASE STOP USING INTERNET EXPLORER 6!!!

Rather than allowing these poorly developed sites just not work in IE 8, they opted to let users click a button to the right of the address bar to have IE 8 use the IE 7 rendering engine to display the URL. The Web Developer takes this a step further because it allows you to select the browser and the browser mode you want the page rendered. It even offers Quirks Mode, which is used by browsers when it cannot determine what if any DOCTYPE the page uses.

Summary

The Internet Explorer 8 Developer Tools are an invaluable tool that every web developer should leverage in their day to day development tasks to make high value modern web sites. Understanding all the features available in the tool is very important because once you understand how to use the tools you will start seeing how to make your web sites’ user interface better. With the popularity of FireBug, this is a much needed tool for Internet Explorer that will help all of us develop better front-ends.