Tuesday, 4 March 2014

c# Winforms coding standards



Threading Design Guidelines
.NET Framework 1.1
5 out of 14 rated this helpful - Rate this topic
The following rules outline the design guidelines for implementing threading:
  • Avoid providing static methods that alter static state. In common server scenarios, static state is shared across requests, which means multiple threads can execute that code at the same time. This opens up the possibility for threading bugs. Consider using a design pattern that encapsulates data into instances that are not shared across requests.
  • Static state must be thread safe.
  • Instance state does not need to be thread safe. By default, class libraries should not be thread safe. Adding locks to create thread-safe code decreases performance, increases lock contention, and creates the possibility for deadlock bugs to occur. In common application models, only one thread at a time executes user code, which minimizes the need for thread safety. For this reason, the .NET Framework class libraries are not thread safe by default. In cases where you want to provide a thread-safe version, provide a static Synchronized method that returns a thread-safe instance of a type. For an example, see the System.Collections.ArrayList.Synchronized Method and the System.Collections.ArrayList.IsSynchronized Method.
  • Design your library with consideration for the stress of running in a server scenario. Avoid taking locks whenever possible.
  • Be aware of method calls in locked sections. Deadlocks can result when a static method in class A calls static methods in class B and vice versa. If A and B both synchronize their static methods, this will cause a deadlock. You might discover this deadlock only under heavy threading stress.
  • Performance issues can result when a static method in class A calls a static method in class A. If these methods are not factored correctly, performance will suffer because there will be a large amount of redundant synchronization. Excessive use of fine-grained synchronization might negatively impact performance. In addition, it might have a significant negative impact on scalability.
  • Be aware of issues with the lock statement (SyncLock in Visual Basic). It is tempting to use the lock statement to solve all threading problems. However, the System.Threading.Interlocked Class is superior for updates that must be atomic. It executes a single lock prefix if there is no contention. In a code review, you should watch out for instances like the one shown in the following example.
VB
SyncLock Me
   myField += 1
End SyncLock
[C#]
lock(this)
{
   myField++;
}
If you replace the previous example with the following one, you will improve performance.
VB
System.Threading.Interlocked.Increment(myField)
[C#]
System.Threading.Interlocked.Increment(myField);
Another example is to update an object type variable only if it is null (Nothing in Visual Basic). You can use the following code to update the variable and make the code thread safe.
VB
If x Is Nothing Then
   SyncLock Me
      If x Is Nothing Then
         x = y
      End If
   End SyncLock
End If
[C#]
if (x == null)
{
   lock (this)
   {
      if (x == null)
      {
         x = y;
      }
   }
}
You can improve the performance of the previous sample by replacing it with the following code.
VB
System.Threading.Interlocked.CompareExchange(x, y, Nothing)
[C#]
System.Threading.Interlocked.CompareExchange(ref x, y, null);
  • Avoid the need for synchronization if possible. For high traffic pathways, it is best to avoid synchronization. Sometimes the algorithm can be adjusted to tolerate race conditions rather than eliminate them.

Array Usage Guidelines

.NET Framework 1.1
Description: http://i3.msdn.microsoft.com/Areas/Epx/Content/Images/ImageSprite.png
7 out of 12 rated this helpful - Rate this topic
For a general description of arrays and array usage see Arrays, and System.Array Class.

Arrays vs. Collections

Class library designers might need to make difficult decisions about when to use an array and when to return a collection. Although these types have similar usage models, they have different performance characteristics. In general, you should use a collection when Add, Remove, or other methods for manipulating the collection are supported.
For more information on using collections, see Grouping Data in Collections.

Array Usage

Do not return an internal instance of an array. This allows calling code to change the array. The following example demonstrates how the array badChars can be changed by any code that accesses the Path property even though the property does not implement the set accessor.
VB
Imports System
Imports System.Collections
Imports Microsoft.VisualBasic
 
Public Class ExampleClass
   NotInheritable Public Class Path      
      Private Sub New()
      End Sub
 
      Private Property Path
         Get
         End Get
         Set
         End Set
      End Property
 
      Private Shared badChars() As Char = {Chr(34),"<"c,">"c}
      
      Public Shared Function GetInvalidPathChars() As Char()
         Return badChars
      End Function
 
   End Class
   
   Public Shared Sub Main()
      ' The following code displays the elements of the 
      ' array as expected.
      Dim c As Char
      For Each c In  Path.GetInvalidPathChars()
         Console.Write(c)
      Next c
      Console.WriteLine()
      
      ' The following code sets all the values to A.
      Path.GetInvalidPathChars()(0) = "A"c
      Path.GetInvalidPathChars()(1) = "A"c
      Path.GetInvalidPathChars()(2) = "A"c
      
      ' The following code displays the elements of the array to the
      ' console. Note that the values have changed.
      For Each c In  Path.GetInvalidPathChars()
         Console.Write(c)
      Next c
 
   End Sub
End Class
[C#]
using System;
using System.Collections;
 
public class ExampleClass
{
   public sealed class Path
   {
      private Path(){}
      private static char[] badChars = {'\"', '<', '>'};
      public static char[] GetInvalidPathChars()
      {
         return badChars;
      }
   }
   public static void Main()
   {
      // The following code displays the elements of the 
      // array as expected.
      foreach(char c in Path.GetInvalidPathChars())
      {
         Console.Write(c);
      }
      Console.WriteLine();
 
      // The following code sets all the values to A.
      Path.GetInvalidPathChars()[0] = 'A';
      Path.GetInvalidPathChars()[1] = 'A';
      Path.GetInvalidPathChars()[2] = 'A';
 
      // The following code displays the elements of the array to the
      // console. Note that the values have changed.
      foreach(char c in Path.GetInvalidPathChars())
      {
         Console.Write(c);
      }
   }
}
You can correct the problem in the preceding example by making the badChars collection readonly (ReadOnly in Visual Basic). Alternately, you can clone the badChars collection before returning. The following example demonstrates how to modify the GetInvalidPathChars method to return a clone of the badChars collection.
VB
Public Shared Function GetInvalidPathChars() As Char()
   Return CType(badChars.Clone(), Char())
End Function
[C#]
public static char[] GetInvalidPathChars()
{
   return (char[])badChars.Clone();
}
Do not use readonly (ReadOnly in Visual Basic) fields of arrays. If you do, the array is readonly and cannot be changed, but the elements in the array can be changed. The following example demonstrates how the elements of the readonly array InvalidPathChars can be changed.
Operator Overloading Usage Guidelines
.NET Framework 1.1
5 out of 7 rated this helpful - Rate this topic
The following rules outline the guidelines for operator overloading:
  • Define operators on value types that are logical built-in language types, such as the System.Decimal Structure.
  • Provide operator-overloading methods only in the class in which the methods are defined. The C# compiler enforces this guideline.
  • Use the names and signature conventions described in the Common Language Specification (CLS). The C# compiler does this for you automatically.
  • Use operator overloading in cases where it is immediately obvious what the result of the operation will be. For example, it makes sense to be able to subtract one Time value from another Time value and get a TimeSpan. However, it is not appropriate to use the or operator to create the union of two database queries, or to use shift to write to a stream.
  • Overload operators in a symmetric manner. For example, if you overload the equality operator (==), you should also overload the not equal operator(!=).
  • Provide alternate signatures. Most languages do not support operator overloading. For this reason, it is a CLS requirement for all types that overload operators to include a secondary method with an appropriate domain-specific name that provides the equivalent functionality. It is a Common Language Specification (CLS) requirement to provide this secondary method. The following example is CLS-compliant.
C#
public struct DateTime
{
   public static TimeSpan operator -(DateTime t1, DateTime t2) { }
   public static TimeSpan Subtract(DateTime t1, DateTime t2) { }
}
The following table contains a list of operator symbols and the corresponding alternative methods and operator names.
C++ operator symbol
Name of alternative method
Name of operator
Not defined
ToXxx or FromXxx
op_Implicit
Not defined
ToXxx or FromXxx
op_Explicit
+ (binary)
Add
op_Addition
- (binary)
Subtract
op_Subtraction
* (binary)
Multiply
op_Multiply
/
Divide
op_Division
%
Mod
op_Modulus
^
Xor
op_ExclusiveOr
& (binary)
BitwiseAnd
op_BitwiseAnd
|
BitwiseOr
op_BitwiseOr
&&
And
op_LogicalAnd
||
Or
op_LogicalOr
=
Assign
op_Assign
<< 
LeftShift
op_LeftShift
>> 
RightShift
op_RightShift
Not defined
LeftShift
op_SignedRightShift
Not defined
RightShift
op_UnsignedRightShift
==
Equals
op_Equality
> 
Compare
op_GreaterThan
< 
Compare
op_LessThan
!=
Compare
op_Inequality
>=
Compare
op_GreaterThanOrEqual
<=
Compare
op_LessThanOrEqual
*=
Multiply
op_MultiplicationAssignment
-=
Subtract
op_SubtractionAssignment
^=
Xor
op_ExclusiveOrAssignment
<<=
LeftShift
op_LeftShiftAssignment
%=
Mod
op_ModulusAssignment
+=
Add
op_AdditionAssignment
&=
BitwiseAnd
op_BitwiseAndAssignment
|=
BitwiseOr
op_BitwiseOrAssignment
,
None assigned
op_Comma
/=
Divide
op_DivisionAssignment
--
Decrement
op_Decrement
++
Increment
op_Increment
- (unary)
Negate
op_UnaryNegation
+ (unary)
Plus
op_UnaryPlus
~
OnesComplement
op_OnesCo

Security in Class Libraries

.NET Framework 1.1
1 out of 15 rated this helpful - Rate this topic
Class library designers must understand code access security in order to write secure class libraries. When writing a class library, be aware of two security principles: use permissions to help protect objects, and write fully trusted code. The degree to which these principles apply will depend upon the class you are writing. Some classes, such as the System.IO.FileStream Class, represent objects that need protection with permissions. The implementation of these classes is responsible for checking the permissions of callers and allowing only authorized callers to perform operations for which they have permission. The System.Security Namespace contains classes that can help you perform these checks in the class libraries that you write. Class library code often is fully trusted or at least highly trusted code. Because class library code often accesses protected resources and unmanaged code, any flaws in the code represent a serious threat to the integrity of the entire security system. To help minimize security threats, follow the guidelines described in this topic when writing class library code. For more information, see Writing Secure Class Libraries.

Protecting Objects with Permissions

Permissions are defined to help protect specific resources. A class library that performs operations on protected resources must be responsible for enforcing this protection. Before acting on any request on a protected resource, such as deleting a file, class library code first must check that the caller (and usually all callers, by means of a stack walk) has the appropriate delete permission for the resource. If the caller has the permission, the action should be allowed to complete. If the caller does not have the permission, the action should not be allowed to complete and a security exception should be raised. Protection is typically implemented in code with either a declarative or an imperative check of the appropriate permissions.
It is important that classes protect resources, not only from direct access, but from all possible kinds of exposure. For example, a cached file object is responsible for checking for file read permissions, even if the actual data is retrieved from a cache in memory and no actual file operation occurs. This is because the effect of handing the data to the caller is the same as if the caller had performed an actual read operation.

Fully Trusted Class Library Code

Many class libraries are implemented as fully trusted code that encapsulates platform-specific functionality as managed objects, such as COM or system APIs. Fully trusted code can expose a weakness to the security of the entire system. However, if class libraries are written correctly with respect to security, placing a heavy security burden on a relatively small set of class libraries and the core runtime security allows the larger body of managed code to acquire the security benefits of these core class libraries.
In a common class library security scenario, a fully trusted class exposes a resource that is protected by a permission; the resource is accessed by a native code API. A typical example of this type of resource is a file. The File class uses a native API to perform file operations, such as a deletion. The following steps are taken to protect the resource.
  1. A caller requests the deletion of file c:\test.txt by calling the File.Delete Method.
  2. The Delete method creates a permission object representing the delete c:\test.txt permission.
  3. The File class's code checks all callers on the stack to see if they have been granted the demanded permission; if not, a security exception is raised.
  4. The File class asserts FullTrust in order to call native code, because its callers might not have this permission.
  5. The File class uses a native API to perform the file delete operation.
  6. The File class returns to its caller, and the file delete request is completed successfully.

Precautions for Highly Trusted Code

Code in a trusted class library is granted permissions that are not available to most application code. In addition, an assembly might contain classes that do not need special permissions but are granted these permissions because the assembly contains other classes that do require them. These situations can expose a security weakness to the system. Therefore, you must be take special care when writing highly or fully trusted code.
Design trusted code so that it can be called by any semi-trusted code on the system without exposing security holes. Resources are normally protected by a stack walk of all callers. If a caller has insufficient permissions, attempted access is blocked. However, any time trusted code asserts a permission, the code takes responsibility for checking for required permissions. Normally, an assert should follow a permission check of the caller as described earlier in this topic. In addition, the number of higher permission asserts should be minimized to reduce the risk of unintended exposure.
Fully trusted code is implicitly granted all other permissions. In addition, it is allowed to violate rules of type safety and object usage. Independent of the protection of resources, any aspect of the programmatic interface that might break type safety or allow access to data not normally available to the caller can lead to a security problem.

Performance

Security checks involve checking the stack for the permissions of all callers. Depending upon the depth of the stack, these operations have the potential to be very expensive. If one operation actually consists of a number of actions at a lower level that require security checks, it might greatly improve performance to check caller permissions once and then assert the necessary permission before performing the actions. The assert will stop the stack walk from propagating further up the stack so that the check will stop there and succeed. This technique typically results in a performance improvement if three or more permission checks can be covered at once.

Summary of Class Library Security Issues

  • Any class library that uses protected resources must ensure that it does so only within the permissions of its callers.
  • Assertion of permissions should be done only when necessary, and should be preceded by the necessary permission checks.
  • To improve performance, aggregate operations that will involve security checks and consider the use of assert to limit stack walks without compromising security.
  • Be aware of how a semi-trusted malicious caller might potentially use a class to bypass security.
  • Do not assume that code will be called only by callers with certain permissions.
  • Do not define non-type-safe interfaces that might be used to bypass security elsewhere.
  • Do not expose functionality in a class that allows a semi-trusted caller to take advantage of the higher trust of the class.

See Also

Design Guidelines for Class Library Developers | Writing Secure Class Libraries | Code Access Security | Security and Culture-Aware String Operations
Asynchronous programming is a feature supported by many areas of the common language runtime, such as Remoting, ASP.NET, and Windows Forms. Asynchronous programming is a core concept in the .NET Framework. This topic introduces the design pattern for asynchronous programming.
The philosophy behind these guidelines is as follows:
  • The client should decide whether a particular call should be asynchronous.
  • It is not necessary for a server to do additional programming in order to support its clients' asynchronous behavior. The runtime should be able to manage the difference between the client and server views. As a result, the situation where the server has to implement IDispatch and do a large amount of work to support dynamic invocation by clients is avoided.
  • The server can choose to explicitly support asynchronous behavior either because it can implement asynchronous behavior more efficiently than a general architecture, or because it wants to support only asynchronous behavior by its clients. It is recommended that such servers follow the design pattern outlined in this document for exposing asynchronous operations.
  • Type safety must be enforced.
  • The runtime provides the necessary services to support the asynchronous programming model. These services include the following:
    • Synchronization primitives, such as critical sections and ReaderWriterLock instances.
    • Synchronization constructs such as containers that support the WaitForMultipleObjects method.
    • Thread pools.
    • Exposure to the underlying infrastructure, such as Message and ThreadPool objects.

Tuesday, 7 January 2014

CSS Hacks & Issues







CSS Hacks & Issues









Author: Chris Thomas
Monday, 12 March 2007









 

Company Number: 4510864 1st Floor, 77 Leonard Street, London, EC2A 4QS
Table of Contents
1. Introduction......................................................................................................3
2. Browser-Specific selectors..................................................................................3
3. Transparent PNG’s in IE6...................................................................................3
4. Removing dotted links .......................................................................................4
5. Applying a width to inline elements.....................................................................4
6. Centering a fixed width website..........................................................................4
7. Image replacement technique ............................................................................5
8. Min-width.........................................................................................................5
9. Hide horizontal scrolling.....................................................................................6


















 

Company Number: 4510864 1st Floor, 77 Leonard Street, London, EC2A 4QS


1. Introduction
This article includes 8 helpful solutions which we find essential when designing with CSS
2. Browser-Specific selectors
These selectors are very useful when you want to change a style in one browser but not
the others.

IE 6 and below
* html {}
IE 7 and below
*:first-child+html {} * html {}
IE 7 only
*:first-child+html {}
IE 7 and modern browsers only
html>body {}
Modern browsers only (not IE 7)
html>/**/body {}
Recent Opera versions 9 and below
html:first-child {}
Safari
 html[xmlns*=""] body:last-child {}



To use these selectors, place the code in front of the style. E.g.:

 #content-box {
 width: 300px;
 height: 150px;
 }

 * html #content-box {
 width: 250px;
 } /* overrides the above style and changes the width to 250px
in IE 6 and below */

Source
3. Transparent PNG’s in IE6
An IE6 bug which causes a great deal of hassle is that it doesn’t support transparent
PNG images.

Company Number: 4510864 1st Floor, 77 Leonard Street, London, EC2A 4QS
You will need to use a filter which overrides the CSS.

*html #image-style {
background-image: none;
filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src="fil
ename.png", sizingMethod="scale");
}
4. Removing dotted links
Firefox produces a dotted outline that appears around links when you click on them.



This is simple to stop. Just add outline:none to the a tag
 a {
 outline: none;
 },
5. Applying a width to inline elements
If you apply a width to an inline element it will only work in IE6.
All HTML elements are either a block or an inline element. Inline elements include
<span>, <a>, <strong> and <em>. Block elements include <div>, <p>, <h1>, <form> and
<li>
You can’t change the width of an inline element. A way around this is to change the
element from inline to block.
span {
 width: 150px;
 display: block
 }
Applying display: block will turn the span into a block element, allowing you to change
the width.
6. Centering a fixed width website
To centre your website within the browser, add relative positioning to the outer div, then
set the margin to auto.

Company Number: 4510864 1st Floor, 77 Leonard Street, London, EC2A 4QS

 #wrapper {
 margin: auto;
 position: relative;
}

7. Image replacement technique
It is always best to use text rather than an image for headings. On the odd occasion
when you must have an image it is best to use a background image with hidden text
within a div. This is extremely useful for screen readers and SEO as it is still using
regular text, with all the benefits associated with this.
HTML:
<h1><span>Main heading one</span></h1>
CSS:
h1 {
 background: url(heading-image.gif) no-repeat;
}

h1 span {
 position:absolute;
 text-indent: -5000px;
 }

As you can see we are using regular HTML code for the h1 tag and using CSS to
replace the text with an image. Text-indent pushes the text 5000px’s to the left, making it
invisible to the user.
Try turning off your CSS style on your website and see how the heading looks.
8. Min-width
Another bug in IE is that it doesn’t support min-width. Min-width is extremely useful,
especially for flexible templates that have a width of 100%, as it tells the browser to stop
contracting.

For all browsers apart from IE6 all you need is min-width:Xpx;. e.g.:

Company Number: 4510864 1st Floor, 77 Leonard Street, London, EC2A 4QS

 .container {
 min-width:300px;
 }

Getting this to work in IE6 takes some extra effort! To start you will need to create 2 divs,
one embedded in the other.

<div class=”container”>
 <div class=”holder”>Content</div>
</div>

Then you will need the min-width which goes on the outer div.

 .container {
 min-width:300px;
 }

Now this is where the IE hack comes into play. You will need to include the following
code.

 * html .container {
 border-right: 300px solid #FFF;
 }

 * html .holder {
 display: inline-block;
 position: relative;
 margin-right: -300px;
 }

As the browser window is resized the outer div width reduces to suit until it shrinks to the
border width, at which point it will not shrink any further. The holder div follows suit and
also stops shrinking. The outer div border width becomes the minimum width of the inner
div.
Source
9. Hide horizontal scrolling
To remove the horizontal scrolling bar, insert overflow-x: hidden; into the body
body {
overflow-x: hidden;
}
This is useful if you decide to have an image or flash file which has a larger width than
the browser.
 

Company Number: 4510864 1st Floor, 77 Leonard Street, London, EC2A 4QS
About Solid State Group
Solid State Group is a content management, web applications and services consultancy,
who focus on making your online presence dynamic and easy to manage, at a
reasonable price. Our primary goal is to complete innovative and robust websites for our
clients whilst maintaining a service second to none.

WebDeck content management system
Solid State Group’s products allow you to completely control your company’s brand on
the internet. WebDeck is a complete accessible content management system but it’s
easier to think of it as the remote control for your website.

It is accessible - WebDeck produces WACG level A, Double-A, and Triple-A websites.
It is flexible - WebDeck can work with any kind of website design.
It is multi-user - WebDeck enables teams to work securely and seamlessly on a site.
It is secure - WebDeck has been tested by Deloitte consulting for FSA accreditation.
It is sticky - WebDeck comes with interactive tools such as forums, polls, quizzes, etc.
It has management tools - WebDeck has real-time integrated web statistics.
It has marketing tools - OutReach is an email marketing plug-in for WebDeck.
It uses open standards - WebDeck uses open standards like XML, RSS, CSV and
SOAP.
It is platform independent - WebDeck runs on Java with a web front end.

Bespoke build services
Solid State Group also offer bespoke systems design and development. Some websites
need a little extra functionality that simply won’t be available out of the box from any
product. We specialise in capturing the exact requirements and translating them into a
working site with stylish design.

Our special offer
Solid State Group offer a free consultancy meeting to capture requirements and give a
‘no strings attached’ estimate for systems design and construction. If nothing else, you
will at least gain a well documented specification of your requirements, so if you are
interested in our services, please do get in touch.
Contact us
Call us on +44 (0)845 838 2163
Email us at info@solidstategroup.com
Visit our website at http://www.solidstategroup.com 

Tuesday, 24 December 2013

Interesting jQuery Mobile Tutorials

Friday, 20 December 2013

http://corporate.tuenti.com/en/dev/blog/top-13-javascript-mistakes

1. Usage of for..in to iterate Arrays

Example:

var myArray = [ “a”, “b”, “c” ];
var totalElements = myArray.length;
for (var i = 0; i < totalElements; i++) {
   console.log(myArray[i]);
}
The main problem here is that the for..in statement does not guarantee the order. Effectively this means that you could obtain different results at different executions. Moreover, if someone augmented Array.prototype with some other custom functions, your loop will iterate over those functions as well as the original array items.
Solution: always use regular for loops to iterate arrays.

var myArray = [ “a”, “b”, “c” ];
for (var i=0; i<myArray.length; i++) {
    console.log(myArray[i]);
}

2. Array dimensions

Example:

var myArray = new Array(10);
There are two different problems here. First, the developer is trying to create an array already containing 10 items, and it will create an array with 10 empty slots. However, if you try to get an array item, you will get ‘undefined’ as result. In other words, the effect is the same as if you did not reserved that memory space. There is no really good reason to predefine the array length.
The second problem is that the developer is creating an array using Array constructor. This is technically correct. However it’s slower than the literal notation.
Solution: Use literal notation to initialize arrays. Do not predefine array length.

var myArray = [];

3. Undefined properties

Example:

var myObject = {
    someProperty: “value”,
    someOtherProperty: undefined
}
Undefined properties (such as someOtherProperty in the above example) will create an element in the object with key 'someOtherProperty' and value 'undefined'. If you loop through your array checking the existence of an element the following 2 statements will both return 'undefined':
typeof myObject['someOtherProperty'] // undefined typeof myObject['unknownProperty'] // undefined
Solution: if you want to explicitly declare a uninitialized properties inside an object, mark them as null

var myObject = {
    someProperty: “value”,
    someOtherProperty: null
}

4. Misuse of Closures

Example:

function(a, b, c) {
    var d = 10;
    var element = document.getElementById(‘myID’);
    element.onclick = (function(a, b, c, d) {
        return function() {
            alert (a + b + c + d);
        }
    })(a, b, c, d);
}
Here the developer is using two functions to pass the arguments a, b and c to the onclick handler. The double function is not needed only adding complexity to the code.
The variables a, b and c are already defined in the inner function because they are already declared as parameters in the main function. Any function inside the inner function will create a closure with all variables defined by main function. This includes ‘regular’ variables (like d) and arguments (like a, b and c). Thus It is not necessary to pass them again as parameters using a auto-executable function.
See JavaScript Closures FAQ for an awesome explanation about closures and contexts.
Solution: use closures to simplify your code

function (a, b, c) {
    var d = 10;
    var element = document.getElementById(‘myID’);
    element.onclick = function() {
        //a, b, and c come from the outer function arguments.
        //d come from the outer function variable declarations.
        //and all of them are in my closure
        alert (a + b + c + d);
}; }

5. Closures in loops

Example:

var elements = document.getElementByTagName(‘div’);
for (var i = 0; i<elements.length; i++) {
    elements[i].onclick = function() {
        alert(“Div number “ + i);
    }
}
In this example, we want to trigger an action (display “Div number 1”, “Div number 2”... etc) when the user clicks on the different divs on the page. However, if we have 10 divs in the page, all of them will display “Div number 10”.
The problem is that we are creating a closure with the inner function, so the code inside the function has access to variable i. The point is that i inside the function and i outside the function refers to the same variable (i.e.: the same position in memory). When our loop ends, i points to the value 10. So the value of i inside the inner function will be 10.
See JavaScript Closures FAQ for an awesome explanation about closures and contexts.
Solution: use a second function to pass the correct value.

var elements = document.getElementsByTagName(‘div’);
for (var i = 0; i<elements.length; i++) {
    elements[i].onclick = (function(idx) { //Outer function
        return function() { //Inner function
            alert(“Div number “ + idx);
        }
    })(i);
}
The outer function is a function that executes inmediatly, receiving i as a parameter. That parameter is called idx inside the outer function, thus inner function creates a closure with idx (instead of i). Therefore idx is completly different from across iterations (i.e. they point to different memory address). This example is very important to understand how closures work. Be sure to read it and play with the code in your browser until you fully understand what’s going on there.

6. Memory leaks with DOM objects

Example:

function attachEvents() {
    var element = document.getElementById(‘myID’);
    element.onclick = function() {
        alert(“Element clicked”);
    }
};
attachEvents();
This code creates a reference loop. The variable element contains a reference to the function (it is assigned to onclick properties). Also, function is keeping a reference to the DOM element (note that inside the function you have access to element because of the closure). So JavaScript garbage collector cannot clean neither element nor the function, because both are referenced by each other. Most JavaScript engines aren’t clever enough to clean circular references.
Solution: avoid those closures or undo the circular reference inside the function

function attachEvents() {
    var element = document.getElementById(‘myID’);
    element.onclick = function() {
        //Remove element, so function can be collected by GC
        delete element;
        alert(“Element clicked”);
    }
};
attachEvents();

7. Differentiate float numbers from integer numbers

Example:

var myNumber = 3.5;
var myResult = 3.5 + 1.0; //We use .0 to keep the result as float
In JavaScript, there is no difference between float and integers. Actually, every number in JavaScript is represented using double-precision 64-bits format IEEE 754. In plain words, all numbers are floats.
Solution: don’t use decimals to “convert” numbers to floats.

var myNumber = 3.5;
var myResult = 3.5 + 1; //Result is 4.5, as expected

8. Usage of with() as a shortcut

Example:

team.attackers.myWarrior = { attack: 1, speed: 3, magic: 5};
with (team.attackers.myWarrior){
    console.log ( “Your warrior power is ” + (attack * speed));
}
Before talking about with(), let’s see how JavaScript contexts works. Each function has an execution context that, put in simple words, holds all the variables that the function can access. Thus the context contain arguments and defined variables. Also a context points to a “parent” context (the context that our caller function has). For example, if functionA() calls functionB(), functionB’s context points to functionA’s context as its parent context. When accessing any variable inside a function, the engine first search in his own context. If not found, it switches to the parent context and so on until it finds the variable or it reaches the end of the context chain. Execution contexts are what makes closures work.
What with() actually does, is to insert an object into our context chain. It injects between my current context and my parent’s context. In this way, the engine first searches in the current context for the requested variable, and then it searches for it in the recently injected object, and finally in the “real” parent context. As you can see, the shortcut used in the example code above is a side effect of using context injection. However usage of with() is very slow, and thus using it for shortcuts is just insane.
Just a side note. Every book recommends not to use with(). Nevertheless all of them are focused on its usage as a shortcut. Context injection is really useful and you may find that you need to use it in advanced JavaScript. In those cases, it’s acceptable to use with() with its real meaning. Although be aware that it’s it’s still very slow from a performance perspective.
See JavaScript Closures FAQ for an awesome explanation about closures and contexts.
Solution: don’t use with() for shortcuts. Only for context injection when you really need it.

team.attackers.myWarrior = { attack: 1, speed: 3, magic: 5};
var sc = team.attackers.myWarrior;
console.log(“Your warrior power is ” + (sc.attack * sc.speed));

9. Usage of strings with setTimeout/setInterval

Example:

function log1() { console.log(document.location); }
function log2(arg) { console.log(arg); }
var myValue = “test”;
setTimeout(“log1()”, 100);
setTimeout(“log2(” + myValue + “)”, 200);
Both setTimeout() and setInterval() can accept either a function or a string as the first parameter. If you pass a string, the engine will create a new function using Function constructor. This is very slow in some browsers. Instead pass the function itself as the first argument; it’s faster, more powerful and clearer.
Solution: never use strings for setTimeout()or setInterval()

function log1() { console.log(document.location); }
function log2(arg) { console.log(arg); }
var myValue = “test”;
setTimeout(log1, 100); //Reference to a function
setTimeout(function(){ //Get arg value using closures
    log2(arg);
}, 200);

10. Usage of setInterval() for heavy functions

Example:

function domOperations() {
    //Heavy DOM operations, takes about 300ms
}
setInterval(domOperations, 200);
We can have a problem when using intervals where operation time is bigger than the interval step time. In the example we are doing a complex (i.e.: long) operation with DOM objects every 200ms. If the domOperations() function takes more than 200ms to complete, each step will overlap with the previous step and eventually some steps may get discarded. This can become a problem.
setInterval() schedules a function to be executed only if there isn’t another execution already waiting in the main execution queue. The JavaScript engine only adds the next execution to the queue if there is no another execution already in the queue. This may yield to skip executions or run two different executions without waiting 200ms between them. To make it clear, setInterval() doesn’t take in account how long it takes domOperations() to complete its job.
Solution: avoid setInterval(), use setTimeout()

function domOperations() {
    //Heavy DOM operations, takes about 300ms
//After all the job is done, set another timeout for 200 ms setTimeout(domOperations, 200); } setTimeout(domOperations, 200);
11. Misuse of ‘this’ There is no example for this common mistake as it is very difficult to build one to illustrate it. The value of this in JavaScript is very different from other languages, where the this behaviour is usually clearer. However, in JavaScript this is a bit different.
First of all, the value of this inside a function is defined when the function is called, not when it is declared. Its very important to understand this, because the value of this depends on how the function is called. In the following cases, this has a different meaning inside myFunction
* Regular function: myFunction(‘arg1’);
this points to the global object, wich is window for all browers.
* Method: someObject.myFunction(‘arg1’);
this points to object before the dot, someObject in this case.
* Constructor: var something = new myFunction(‘arg1’);
this points to an empty Object.
* Using call()/apply(): myFunction.call(someObject, ‘arg1’);
this points to the object passed as first argument.
In this way you can have the same function (myFunction in the example above), that internally use this. However, the value of this is not related to the function declaration itself, only to the way that function is called.

12. Usage of eval() to access dynamic properties

Example:

var myObject = { p1: 1, p2: 2, p3: 3};
var i = 2;
var myResult = eval(‘myObject.p’+i);
The main problem lies in that starting a new execution context with eval() is extremely slow. The same can be achieved using square bracket notation instead of dot notation.
Solution: use square bracket notation instead of eval()

var myObject = { p1: 1, p2: 2, p3: 3};
var i = 2;
var myResult = myObject[“p”+i];

13. Usage of undefined as a variable

Example:

if ( myVar === undefined ) {
    //Do something
}
This check usually works, but it does by pure chance. In the code above undefined is effectively a variable. All JavaScript engines will create the variable window.undefined initialized to undefined as its value. However note that variables isn’t read-only, and any other code can change its value. It’s very weird to find a scenario where window.undefined has a value different from undefined. (nobody will never actually do undefined = 10;). But why take the risk? It is better to use typeof checks.
Solution: use typeof when checking for undefined.

if ( typeof myVar === “undefined” ) {
    //Do something

Tuesday, 19 November 2013

Avoiding timezone nightmares in PHP and MySQL

Avoiding timezone nightmares in PHP and MySQL »

FERDY CHRISTANT - APR 19, 2010 (07:08:48 PM)

I am a developer that finds things like date handling, character encodings and such to be a pain. Like many developers, I pretend the problem does not exist and just hope that things turn out well. This is an attitude that I can no longer afford in this global village, which is why I'm getting to the bottom of things like this. An example is one of my earlier articles, where I had to take a deep dive into Unicode:
Although time zones and daylight savings time are entirely unrelated, they are similar, undesirable problems that you cannot hide from. In this little article I will tell you how I deal with timezones and DST in a PHP/MySQL context. The key of this article is in avoiding timezone issues in your date handling.
Introduction
There are three aspects to date/time handling where timezones can be relevant:
  • Storing date/times
  • Calculating with date/times
  • Displaying date/times
Storing date times
The key to storing date times is to explicitly set the timezone or to set it to a neutral timezone. You should never just take any date and insert it into a database without explicitly converting it to a specific timezone. In most cases, you are best of storing it in a neutral format, meaning the GMT timezone. The GMT timezone is also used by the UTC standard. This little PHP snippet converts the current date/time into GMT:
 $timestamp = gmdate("Y-m-d H:i:s", time()); 
Next, one can insert this into MySQL without change if your table column is of type "timestamp". Note that in the example above, time() will give back the time using the timezone configured at the host. In my case it is on GMT+2. This means that if you actually look in the MySQL table, all dates will be 2 hours off. This is correct behavior, since we are storing the timestamp in the GMT timezone. The great thing here is that it does not matter in which timezone your host is.
(note: It is recommended though to set both your web host and MySQL to the same timezone explicitly)
Calculating with date times
Once we have stored timestamps in a neutral timezone, doing calculations on them is fairly easy. The thing to remember here is that if you are doing timestamp comparisons, your input timestamp first has to be converted to GMT too. This is best illustrated with an example:
SELECT COUNT(id) FROM c WHERE date_created > DATE_SUB(UTC_TIMESTAMP(), INTERVAL 1 HOUR)
The line of SQL above returns the amount of comments that were made in the last hour. The date_created column contains the timezone neutral timestamp. Since we are calculating a date offset, our input parameter (the current timestamp) first has to be converted to GMT/UTC. That's all we need to do, because date offsets are not time zone dependent in any other way. What happens one hour ago in one part of the world happened one hour ago in any other part of the world.
Displaying date times
When it comes to displaying date/times that are sensitive to a user's timezone, it takes a conversion from the neutral timestamp to a timestamp that is optimized to the user's timezone. You can do this straight from MySQL using theConvert_TZ function.
That's only part of the story though. You will need a reliable way to detect the current user's timezone or let them set it theirselves. Next, you need a way to convert the user-friendly list of timezones to the one used in MySQL or PHP. Finally, you can then display a date/time for the user's timezone.
Luckily, in some projects you may be able to escape this mess. If your customer accepts a date format like this:
"3 days ago"
Instead of
"April 16, 2010"
...then the whole problem of displaying timezone specific dates goes away. In that case, you can use the technique used in this article.
Closing
This mini article was just me thinking out loud and structuring my thoughts around this topic. Still, I hope it helps someone else. Please do rate and comment below

Sunday, 17 November 2013

timezone issues

Summary of answers and other data: (please add yours)

Do:
  • Whenever you are referring to a particular moment in time, persist the time according to a unified standard that is not affected by daylight savings. GMT and UTC have been mentioned by different people, though UTC seems to be mentioned most often.
  • ?? Include the local time offset as is (including DST offset) when storing timestamps. ?? Store timestamps as UTC or epochs(number of seconds since 1970) without time zone or offset.
  • Include the original time zone name, so you can reconstruct the original time at a later point and display correct offsets if needed.
  • Remember that DST offsets are not always an integer number of hours (for example, Indian Standard Time is UTC+05:30).
  • If using Java, use Joda Time.
  • If using .NET, consider using Noda Time.
  • If using Perl, use DateTime.
  • If using Python, use pytz
  • If using PHP > 5.2, use the native time zones conversions provided by DateTime, and DateTimeZone classes. To keep PHP with up to date Olson data install periodically this PECL package. See answer
  • Create a table TZOffsets with three columns: RegionClassId, StartDateTime, and OffsetMinutes (int, in minutes). See answer
  • Business rules should always work on civil time (UTC/GMT).
  • Internally, keep timestamps in something like civil-time-seconds-from-epoch. See answer.
  • Only convert to local times at the last possible moment.
  • Remember that time zones and offsets are not fixed and may change. For instance, historically US and UK used the same dates to 'spring forward' and 'fall back'. However, in the mid 2000s the US changed the dates that the clocks get changed on. This now means that for 48 weeks of the year the difference between London time and New York time is 5 hours and for 4 weeks (3 in the spring, 1 in the autumn) it is 4 hours. Be aware of items like this in any calculations that involve multiple zones.
  • Consider the type of time (actual event time, broadcast time, relative time, historical time, recurring time) what elements (timestamp, time zone offset and time zone name) you need to store for correct retrieval - see "Types of Time" in answer.
  • Check if your DBMS needs to be shutdown during transition.
  • Keep your OS, database and application tzdata files in sync, between themselves and the rest of the world.
  • On Servers, set hardware clocks and OS clocks to UTC.
  • Use NTP services on all servers.
  • If doing historical auditing store both UTC and local time (this allows exact pinpointing of time, as conversion tables will change).
  • If using FAT32, remember that timestamps are stored in local time, not UTC.
  • When dealing with recurring events (weekly TV show, for example), remember that the time changes with DST and will be different across time zones.
Don't:
  • Do not use JavaScript date and time calculations in web applications unless you ABSOLUTELY have to.
  • Never trust client datetime. It may very well be incorrect.
  • Do not compare client datetimes with server datetimes.
Testing:
  • When testing make sure you test countries in the Western and Eastern hemispheres, with both DST in progress and not and a country that does not use DST (6 in total).
  • Test all third-party libraries and applications and make sure they handle time zone data correctly.
Reference:
Other:
  • Lobby your representative to end the abomination that is DST. We can always hope...
  • Lobby for EST

Angular Tutorial (Update to Angular 7)

As Angular 7 has just been released a few days ago. This tutorial is updated to show you how to create an Angular 7 project and the new fe...