Thursday, 4 July 2013

ASP.NET Javascript Encode on server side

NET Framework Version 4.0 and above and has a method called

HttpUtility.JavaScriptStringEncode()

which can be used to encode string values for JavaScript. It is a handy method which will take care of all special characters in the string including new line characters. http://msdn.microsoft.com/en-us/library/dd991914.aspx

http://itmeze.com/2011/03/21/javascript-encode-on-server-side-medium-trust-environment/

Underscore or this - C# best practices

Background

C# and .NET have been around for a long time now and the standards and abilities of the language just keep getting better and better. However there is no getting away that some of the more core principles of this language originated from C and C++ created many many years ago. When C and C++ was first created tools were basic and the IDEs around were not very advanced and often programs were coded in notepad or similar tools. For speed and productivity common conventions came about that allowed developers identify code easier.

  • Prefixing the type on to a variable e.g. intAge
  • Adding underscores to internal class variables to indicate they are as such

These were perfectly fine back in the day when working with poor tools but now with Visual Studio and all of the features we have in modern IDEs a lot of this has changed

Underscore vs this keyword

Now comes my main gripe of standards that seem to be lingering on and one, mostly from C and C++ developers and incorrect information. C# has a keyword that has been in it a long time call the ‘this’ keyword which has the following benefits/features

  • Indicates that something you are accessing is from the instance of the class you are using
  • As soon as you type it Intellisense is narrowed down to only instance level code constructs

This feature has been built in to the language and Visual Studio to support having a keyword to replace the need to use anything artificial.

But Microsoft use underscore argument

I have the above argument as a reason why we should be using underscores but here is my responses/reasons why they are wrong

  • Their argument is based upon underscore in the source code. If you look at newer source code (.NET4)
  • There is far less use of underscores
  • Coding everywhere uses ‘this’ keyword
  • Looking on forums you can find Microsoft employees stating that they do not use underscores but still some of the developers that have been around a long time do
  • http://msdn.microsoft.com/en-us/library/ms229045(v=vs.100) which shows .NET 4 suggest conventions lists
  • Do not use underscores, hyphens, or any other nonalphanumeric characters. as one of the standards, so Microsoft are most definitely not suggesting the use of underscores
  • Why the hell would they add the ‘this’ keyword if it wasn’t to be used
  • Stylecop the internal tool created by Microsoft to check code for standards compliance doesn’t like underscores but likes the ‘this’ keyword

Summary

As you can tell I hate underscores and developers trying to tell me it’s clever when it clearly isn’t. We aren’t in the coding dark ages anymore so there isn’t any reason to name things non logically with random crap characters all over the place. The ‘this’ keyword was added in to the language for a reason so use it. Basically if I see code with underscore I will assume your old or ignorant.

Thanks to http://scottreed.eu/csharp/underscore/

Wednesday, 6 March 2013

Cross-browser mouse positioning

Understanding differences between the mouse position event properties, and how to normalize them between browsers.

Mouse Event Properties

clientX, clientY

Standard: W3C Recommendation
Mouse position relative to the browser's visible viewport.

screenX, screenY
Standard: W3C Recommendation
Mouse position relative to the user's physical screen.

offsetX, offsetY
Mouse position relative to the target element. This is implemented very inconsistently between browsers.

pageX, pageY
Mouse position relative to the html document (ie. layout viewport).

Normalization

Calculating pageX, pageY

The only major browser that does not support these properties is IE8. If you are doing event handling with jQuery, it will automatically normalize pageX and pageY for you. If you are not using jQuery's normalized events but still have access to the jQuery, you can use jQuery.event.fix to normalize the event object. Example:

document.body.onclick = function(e) {
    e = e || window.event;
    e = jQuery.event.fix(e);
    console.log([e.pageX, e.pageY]);
};

Without jQuery, the clientX and clientY properties can be added to the viewports scrollLeft and scrollTop to calculate the pageX and pageY values.

document.body.onclick = function(e) {
    e = e || window.event;

    var pageX = e.pageX;
    var pageY = e.pageY;
    if (pageX === undefined) {
        pageX = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
        pageY = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
    }

    console.log([pageX, pageY]);
};

Calculating offsetX, offsetY

According to the W3C Working Draft, offsetX and offsetY should be relative to the padding edge of the target element. The only browser using this convention is IE. Webkit uses the border edge, Opera uses the content edge, and FireFox does not support the properties.

Normalizing to the border edge is easiest to do, thanks to the nifty element.getBoundingClientRect:

document.body.onclick = function(e) {
    e = e || window.event;

    var target = e.target || e.srcElement,
        rect = target.getBoundingClientRect(),
        offsetX = e.clientX - rect.left,
        offsetY = e.clientY - rect.top;

    console.log([offsetX, offsetY]);
};

If you wanted to normalize to the W3C draft spec, then the border width needs to be subtracted from the previously calculated offsetX and offsetY:

document.body.onclick = function(e) {
    e = e || window.event;

    var target = e.target || e.srcElement,
        style = target.currentStyle || window.getComputedStyle(target, null),
        borderLeftWidth = parseInt(style['borderLeftWidth'], 10),
        borderTopWidth = parseInt(style['borderTopWidth'], 10),
        rect = target.getBoundingClientRect(),
        offsetX = e.clientX - borderLeftWidth - rect.left,
        offsetY = e.clientY - borderTopWidth - rect.top;

    console.log([offsetX, offsetY]);
};

Read more about "Mouse Event Properties" here

Read more about view ports here

Friday, 15 February 2013

The challenges of supporting mobile devices today

Even though mobile browsers now almost universally support HTML, you will still face many challenges when aiming to create great mobile browsing experiences:

  • Screen size - Mobile devices vary dramatically in form, and their screens are often much smaller than desktop monitors. So, you may need to design completely different page layouts for them.
  • Input methods – Some devices have keypads, some have styluses, others use touch. You may need to consider multiple navigation mechanisms and data input methods.
  • Standards compliance – Many mobile browsers do not support the latest HTML, CSS, or JavaScript standards.
  • Bandwidth – Cellular data network performance varies wildly, and some end users are on tariffs that charge by the megabyte.

There’s no one-size-fits-all solution; your application will have to look and behave differently according to the device accessing it. Depending on what level of mobile support you want, this can be a bigger challenge for web developers than the desktop “browser wars” ever was.

Developers approaching mobile browser support for the first time often initially think it’s only important to support the latest and most sophisticated smartphones (e.g., Windows Phone 7, iPhone, or Android), perhaps because developers often personally own such devices. However, cheaper phones are still extremely popular, and their owners do use them to browse the web – especially in countries where mobile phones are easier to get than a broadband connection. Your business will need to decide what range of devices to support by considering its likely customers. If you’re building an online brochure for a luxury health spa, you might make a business decision only to target advanced smartphones, whereas if you’re creating a ticket booking system for a cinema, you probably need to account for visitors with less powerful feature phones.

http://www.asp.net/whitepapers/add-mobile-pages-to-your-aspnet-web-forms-mvc-application

Friday, 18 January 2013

Using back-references in IIS rewrite rules

Parts of rules or conditions inputs can be captures in back-references. These can be then used to construct substitution URLs within rules actions or to construct input strings for rule conditions.

Back-references are generated in different ways, depending on which kind of pattern syntax is used for the rule. When an ECMAScript pattern syntax is used, a back-reference can be created by putting parenthesis around the part of the pattern that must capture the back-reference. For example, the pattern ([0-9]+)/([a-z]+)\.html will capture 07 and article in back-references from this requested URL: 07/article.html. When “Wildcard” pattern syntax is used, the back-references are always created when an asterisk symbol (*) is used in the pattern. No back-references are created when “?” is used in the pattern. For example the pattern */*.html will capture contoso and test in back-references from this requested URL: contoso/test.html.

Usage of back-references is the same regardless of which pattern syntax was used to capture them. Back-references can be used in the following locations within rewrite rules:

  • In condition input strings
  • In rule actions, specifically:
    • url attribute of Rewrite and Redirect action
    • statusLine and responseLine of a CustomResponse action
  • In a key parameter to the rewrite map

Back-references to condition patterns are identified by {C:N} where N is from 0 to 9. Back-references to rule patterns are identified by {R:N} where N is from 0 to 9. Note that for both types of back-references, {R:0} and {C:0}, will contain the matched string.

For example, in this pattern:

^(www\.)(.*)$

For the string: www.foo.com the back-references will be indexed as follows:

{C:0} - www.foo.com

{C:1} - www.

{C:2} - foo.com

Within a rule action, you can use the back-references to the rule pattern and to the last matched condition of that rule. Within a condition input string, you can use the back-references to the rule pattern and to the previously matched condition.

The following rule example demonstrates how back-references are created and referenced:

<rule name="Rewrite subdomain">
<match url=”^(.+)” > 
<conditions>
<add input="{HTTP_HOST}" type=”Pattern” pattern="^([^.]+)\.mysite\.com$"> 
</conditions>
<action type=”Rewrite” url="{C:1}/{R:1}" /> 
</rule>

Click here to read more about IIS rewrite rules

Monday, 31 December 2012

Using MS-SQL's NOLOCK for faster queries

NOLOCK (aka READUNCOMMITED) is a t-sql hint (directive) that allows MS SQL Server to ignore the normal locks that are placed and held for a transaction and allows the query to complete without having to wait for the first transaction to finish and therefore release the locks.

Using NOLOCK gives significant improvement on large tables, where insert / update commands cantake 3-15 seconds.

However you need to be very carefully with using NOLOCK. Remember you can get some records that were partially updated or inserted. It is safe to use NOLOCK on rows that you know are not changing right now.For example, records that belong to some user and he is running reports, but not updates, however some users can do updates / inserts at the same time.

Example:

SELECT * FROM ORDERS (NOLOCK) WHERE orderdate < GETDATE() - 1

Issues

You can get dirty reads using the NOLOCK hint. These are also other terms you may encounter for this hint.

  • Dirty Reads - this occurs when updates are done, so the data you select could be different.
  • Nonrepeatable Reads - this occurs when you need to read the data more than once and the data changes during that process
  • Phantom Reads - occurs where data is inserted or deleted and the transaction is rolled back. So for the insert you will get more records and for the delete you will get less records.

Understanding the SQL Server NOLOCK hint

MSDN >> Concurrency Effects

Mobile Site vs. Full Site

Good mobile user experience requires a different design than what's needed to satisfy desktop users. Two designs, two sites, and cross-linking to make it all work.

  • Build a separate mobile-optimized site (or mobile site ) if you can afford it. When people access sites using mobile devices, their measured usability is much higher for mobile sites than for full sites.
  • If mobile users arrive at your full site's URL, auto-redirect them to your mobile site. Sadly, many search engines still don't rank mobile sites high enough for mobile users, so people are often (mis)guided to full sites instead of the mobile ones, which offer a vastly superior user experience.
  • Offer a clear link from your full site to your mobile site for users who end up at the full site despite the redirect.
  • Offer a clear link from your mobile site to your full site for those (few) users who need special features that are found only on the full site.

The findings and guidelines regarding mobile and full sites are the same on all the currently popular platforms (including iPhone, Android, Windows Phone, and BlackBerry).

The guidelines are different for large tablets (10-inch form factor, as in Apple iPad, Lenovo IdeaPad, Samsung Galaxy, etc.), where full sites work reasonably well. For small tablets (7-inch form factor, as in Amazon Kindle Fire) the ideal would be to create yet a third design optimized for mid-sized devices, though most companies can get away with serving their mobile site to Kindle Fire users.

Mobile-optimized sites

The basic ideas are to:

  • cut features, to eliminate things that are not core to the mobile use case;
  • cut content, to reduce word count and defer secondary information to secondary pages; and
  • enlarge interface elements, to accommodate the "fat finger" problem.

The challenge is to eliminate features and word count without limiting the selection of products. A mobile site should have less information about each product and fewer things users can do with the products, but the range of items should remain the same as on the full site. If users can't find a product on a mobile site, they assume the company doesn't sell it and go elsewhere.

Why full-sites don't work for mobile use

It's common today to hear people argue the following: Mobile users have increasingly high expectations for what they should be able to accomplish on their phones, so eliminating content or features will inevitably disappoint some people. It's therefore better, the (flawed) argument goes, to serve the full site to everybody, including mobile users.

This analysis is flawed because it assumes that the only choice is between the full-featured desktop site and a less-featured mobile site. However, any mobile site that complies with the usability guidelines will provide links to the full site wherever features or content are missing, so users have access to everything when and if they need it.

The design challenge is to place the cut between mobile and full-site features in such a way that the mobile site satisfies almost all the mobile users' needs. If this goal is achieved, the extra interaction cost of following the link to the full site will be incurred fairly rarely.

The correct analysis goes as follows:

  • For the vast majority of tasks , mobile users will get a vastly better user experience from a well-designed mobile site than from the full site.
  • For a small minority of tasks , mobile users will be slightly delayed by the extra click to the full site.

A big gain that's experienced often will comfortably outweigh a small penalty that's suffered rarely.

A second argument against the mobile site option is that you could just optimize the entire website for mobile in the first place. Then, giving mobile users the "full" site wouldn't cause them any trouble. While true, this analysis neglects the penalty imposed on desktop users when you give them a design that's suboptimal for bigger screens and better input devices (see sidebar on mouse vs. fingers). If desktop users were a minute minority this might be acceptable, but almost all websites get substantially more traffic (and even more business) from desktop users than from mobile users. So, while we do want to serve mobile users, we can't neglect desktop users— who, after all, pay most of our salaries.

The basic point? The desktop user interface platform differs from the mobile user interface platform in many ways, including interaction techniques, how people read, context of use, and the plain number of things that can be grasped at a glance. This inequality is symmetric : mobile users need a different design than desktop users. But, just as much, desktop users need a different design than mobile users.

source: http://www.nngroup.com/articles/mobile-site-vs-full-site/