Updating your Twitter Status from C#


Today I needed a way to update my Twitter Status via C#, and for that I found this library: Yedda Twitter C# Library.

After I added a reference to the Yedda.Twitter.dll, I tried working with the following code:

  1. using Yedda;
  2. namespace TestingAPIs
  3. {
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. var t = new Twitter();
  9. t.Update(
  10. “myUsername”,                          // Username
  11. “myPassword”,                          // Password
  12. “From Visual Studio”,                  // New Status
  13. Yedda.Twitter.OutputFormatType.JSON);  // Output Type
  14. }
  15. }
  16. }

Simple eh?

Well, much to my amazement, that threw an exception -_- …obviously, it wouldn’t as much fun if it worked on the first try eh!

So, after some googling, I found some posts that detailed the problem:

This error is seemingly because Twitter servers have started rejecting Expect HTTP header with value “100-Continue”.

So anyways, to fix this problem we need to modify a method from the Twitter.cs file of the Yedda library.

Open up the file and find the following method: ExecutePostCommand

At the start of the method, add the following line of code:

01. System.Net.ServicePointManager.Expect100Continue = false;

That will fix the above problem.

Here is the complete modified method:

  1. protected string ExecutePostCommand(string url, string userName, string password, string data) {
  2. System.Net.ServicePointManager.Expect100Continue = false;
  3. WebRequest request = WebRequest.Create(url);
  4. if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password)) {
  5. request.Credentials = new NetworkCredential(userName, password);
  6. request.ContentType = “application/x-www-form-urlencoded”;
  7. request.Method = “POST”;
  8. if (!string.IsNullOrEmpty(TwitterClient)) {
  9. request.Headers.Add(“X-Twitter-Client”, TwitterClient);
  10. }
  11. if (!string.IsNullOrEmpty(TwitterClientVersion)) {
  12. request.Headers.Add(“X-Twitter-Version”, TwitterClientVersion);
  13. }
  14. if (!string.IsNullOrEmpty(TwitterClientUrl)) {
  15. request.Headers.Add(“X-Twitter-URL”, TwitterClientUrl);
  16. }
  17. if (!string.IsNullOrEmpty(Source)) {
  18. data += “&source=” + HttpUtility.UrlEncode(Source);
  19. }
  20. byte[] bytes = Encoding.UTF8.GetBytes(data);
  21. request.ContentLength = bytes.Length;
  22. using (Stream requestStream = request.GetRequestStream()) {
  23. requestStream.Write(bytes, 0, bytes.Length);
  24. using (WebResponse response = request.GetResponse()) {
  25. using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
  26. return reader.ReadToEnd();
  27. }
  28. }
  29. }
  30. }
  31. return null;
  32. }

Unit Testing for Exceptions with Visual Studio 2008


The following are the two different ways I’ve unit tested for Exceptions with Visual Studio 2008.

Using Try / Catch

There first way of testing for Exceptions is by using the try-catch construct.

  1. [TestMethod]
  2. public void TestCard()
  3. {
  4. var c = new CreditCard();
  5. try
  6. {
  7. c.CardNo = “123”//Should throw an exception
  8. Assert.Fail(“InvalidCardNoException wasn’t thrown”);
  9. }
  10. catch (InvalidCardNoException)
  11. {
  12. Assert.IsTrue(true“InvalidCardNoException was properly thrown”);
  13. }
  14. }

As you can see from the above example, if the exception isn’t thrown, Assert.Fail is called which fails the test; and if it is thrown, we succeed the test with Assert.IsTrue.

But Visual Studio 2008 offers a better way on how to deal with exceptions, by using the ExpectedException Attribute.

Using the ExpectedExceptionAttribute Class

Here is the same example, but this time using the ExpectedException Attribute:

  1. [TestMethod, ExpectedException(typeof(InvalidCardNoException))]
  2. public void TestCard()
  3. {
  4. var c = new CreditCard();
  5. c.CardNo = “123”//Should throw an exception
  6. }

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.”

Dynamically Setting a Style at Run-Time in ASP.NET


Trolling the ASP.NET forums this week I came across a good question, “setting the background on a master page div at run-time?”. Even though the person posted he found an acceptable solution before I posted my response, I think the user has a complicated solution. Mostly because he is using themes, but nonetheless. I posted my answer and thought I would share it here.

A nice feature of CSS is the ability to assign multiple classes to can DOM element via the class attribute. This opens up the possibility to dynamically set a class assignment based on some logic as the page is being rendered. The example below demonstrates having a common style rule and a rule added at run-time. Of course you are not limited to this methodology, there are many ways to apply styles to an element.

<div class="contentBox bkg1">...</div>

I find the easiest way to set something like a dynamic style at run-time is to define a public method in the page class to return the desired rule. For my demonstration I will return a style rule name based on a QueryString parameter, but you can use all sorts of criteria. I also chose to apply the rule to the Body tag.

public string GetBackgroundClass()
{
    switch ( Request.QueryString["bkg"])
    {
        case "1":
            return "bkg1";
        case "2":
            return "bkg2";
        case "3":
            return "bkg3";
        default:
            return "bkg1";
    }
}

The style rules just set the color as follows, a nice egg shell (at least that is what I call it), red and blue.

.bkg1
{
    background-color: #FFFFCC;
}

.bkg2
{
    background-color: #C30000;
}

.bkg3
{
    background-color: #0000CC;
}

Finally I just inline the call to the method in the HTML markup:

<body class="<%=GetBackgroundClass() %>">

The result as I pass in different values to the page:

Egg Shell:

Red:

Blue:

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.

10 Ways to Debug JavaScript in IE 8


I know, I know use FireBug and FireFox. I hear it all the time. I say meh, everyone does that. As I wrote last year, in IE 8 press F12 and Bazinga!!! You get the IE Developer tools. Read more about using the IE developer tools in my old post. But I show this in my CodeCamp sessions and folks are just amazed the tools are there and they work quite nicely.

Now that I spend a majority of my web development in the JavaScript layer debugging my scripts is very important. If you are working in the corporate world chances are you are targeting IE (version 8 I pray). So lets look at 10 ways to debug your JavaScript in IE 8.

Set Breakpoints

Any good debugging experience has to allow you to set a breakpoint, or designate a place in your code to stop execution and allow you to examine variables and process flow. The IE Developer tools are no different. Just like Visual Studio you can view your JavaScripts in the Script Tab.

Across the top of the tab there is a toolbar, the ‘Start Debugging’ button and the dropdown to the right are the most important items. More about the button in a moment. The dropdown is a list of scripts and markup pages, i.e. resources that can contain JavaScript. Clicking the dropdown list reveals a list of possible scripts, selecting an item opens that script in the tab.

The script window is a viewer, not an editor, which I can understand. There are many instances where it would not have rights to edit anyway because the scripts are loaded through a web server, etc. The line number is displayed to the left, which is important to locate code to actually edit in Visual Studio later.

set breakpoints

Setting a breakpoint is very straight forward. Place your cursor on the line you want to set a breakpoint and press F9. In the right-hand pane there are several action buttons on the right, which are basically tabs they just don’t look like it. Selecting the Breakpoint option shows a list of breakpoints. There is a checkbox to the left of each breakpoint. Unchecking the correlating checkbox disables the breakpoint. You can also delete individual or all the breakpoints as well.

To enable debugging mode the ‘Start Debugging’ button needs to be pressed. This changes the button to a ‘Stop Debugging’ button, which make sense, right? Now when you load the page, or cause script to be executed the debugger watches the execution and if it hits a breakpoint it stops execution to allow you to evaluate the code.

Just like other IDE (i.e. Visual Studio) conventions convey for stepping through code. F10 goes to the next line in scope, F11 steps into a function, etc. F5 even starts the debugger and lets you continue execution from a breakpoint. You can even set breakpoint conditionals. That is where you designate a condition where the breakpoint actually executes.

View Local Variables

Now that you have hit a breakpoint there are two things you need to do, see what variable values are and of course step through the code. Back over to the right-hand pane there is another button called ‘Locals’. Pressing this button reveals, well nothing really, until you hit a breakpoint. Once you hit a breakpoint in a script you will see all the locally scoped variables on the left and their values on the right. If a variable is an object literal you can expand it to see the values of each property. You can expand properties too if they are objects.

view local variables

Add Watches Directly From Your Code

Additionally you can also add custom watches. These can be viewed by pressing the ‘Watch’ button on the toolbar. Custom watches can be added in two ways. First by selecting a variable or expression in the script, right-clicking and selecting ‘Add Watch’. The selected variable or expression is now added to the Watch window.

Add Custom Watches Directly in the Watch Tab

You can also add a watch by hand by clicking on the last row in the watch window. Here you can just start typing in the variable name or expression to watch. This is extremely useful when you are trying to see things like what a different selector references or a modification of an expression. You can also edit any watch by clicking it. Then you just start editing it as needed.

custom watch

Step Through Your Code

Stepping through code is a breeze as well. F10 to step to the next line. F11 steps into a function. Be careful stepping into functions, if you step into a minified script (like the jQuery framework) you will most likely feel lost and it may be somewhat difficult to get back up to your code because the flow goes through so much framework code.

set breakpoints

Change a Variable Value

Just like working in Visual Studio you can change the value of a variable in the watch window as you are stepping through code. You can do the same in either of the IE Developer Tools Watch windows. Simple double-click the current value and change it accordingly.

edit variable value

Drill Into an Object

I mentioned above you can expand an object in either of the watch windows. If a variable is an object literal you will see a + icon to its left. This indicates it can be expanded to view the child properties. One you do this you can manipulate their values and expand them as well.

view local variables

Use the Console To Test Code

The console is just like the Console window you never use in Visual Studio the IE Developer tools allow you to type expressions for evaluation. You can think of this is sort of a scratch pad to try ideas out. If your script hits an unhandled exception you will also see the error messages here.

Console

You can also use the console object in your script to echo information to the this window during the execution of your test.

Use the Console to Reveal Syntax Issues

I mentioned above if there is an unhandled exception in your script it will be logged to the console window. This is true if you have a syntax error. When the browser loads your script and there is a syntax error, think missing ; or closing } etc, you typically see a little warning icon in the bottom-left corner of the browser. Viewing the console window will tell you what the issue is. It also allows you to click a link on the message to take you to the line of code in the script window to the left. This feature has really helped me out a lot over the past few months.

Profile Your Code to Find Inefficiencies

Finally, Another tab on the main toolbar is Profile. This is very useful to track down bad code.

Profiler

To profile code press the Start Profiling button. Then run your script, interacting with is as necessary. Once you are done, press the same button to stop profiling.

Profiler

Now you can see how many times a function is called and how long it executes. You can now track down inefficiencies in your script and make it better.