Category : AP
Time: 3:16 PM
2) Backup existing database
3) Restore fresh database over existing, which may require processes to be deleted using SQL Server - Activity Monitor from the bottom up.
4) Run cmd as Admin and run .bat file from SQL Patches, ensuring no other scripts are in the folder especially SELECT
5) Do a local publish of website to C:\setups\date
Remove files that should not be overwritten such as Web.config
Remove Logging folder etc
6) Deploy to staging area on dev server C:\inetpub\dev
7) As always DO NOT OVERWRITE CONFIGS if not necessary
8) Make sure Logging folder still has full permissions for IIS_IUSRS
9) Sending emails from server, dont set the config EmailSMTPServerName setting to an IP. I copied the value from the service config which was set to "spamfilter.ap.ie". The IP is the only thing works from my own dev machine which is why it's like that in the config by default. IT guys sometimes change firewall rules which makes the email server name/IP a little iffy sometimes
Category : mac
Time: 10:54 PM
Intro
In addition to being responsible for drawing and handling user events, a view instance can act as a container, enclosing other view instances. Those views are linked together creating a view hierarchy. Unlike a class hierarchy, which defines the lineage of a class, the view hierarchy defines the layout of views relative to other views.The window instance maintains a reference to a single top-level view instance, call the content view. The content view acts as the root of the visible view hierarchy in a window. The view instances enclosed within a view are called subviews. The parent view that encloses a view is referred to as its superview. While a view instance can have multiple subviews, it can have only one superview. In order for a view and its subviews to be visible to the user, the view must be inserted into a window's view hierarchy.
- The window is represented by an NSWindow(aWindow) instance.
- The content view serves as the root of the window's view hierarchy.
- The content View contains a single subview, an instance of a custom class.
- The custom view instance that, in turn has two subviews, an NSButton(viewB) instance, and an NSTextField(viewC) instance.
- The superview for both the button and text field is the NSBox(viewA) object. The custom view container actually encloses the button and text field views.
This window's view hierarchy has these parts.
Relationships among objects in a hierarchy
my thanks to:
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CocoaViewsGuide/WorkingWithAViewHierarchy/WorkingWithAViewHierarchy.html
Category : mac
Time: 3:01 PM
1) This tutorial assumes you have some basic C knowledge, including C data types, what a function is, what a return value is, knowledge of pointers and basic memory management in C. If you haven't gotten this far, I highly suggest you pick up K and R's book, The C Programming Language. This is the book on C written by the writers of C.
2) Objective-C, being a C derivative, inherits all of C's features. There are a few exceptions but they don't really deviate from what C offers as a language.
3) nil: In C/C++ you're probably used to NULL. In Objective-C it is nil. The difference is you can pass messages to nil (such as [nil message];) and this is perfectly legal. You cannot however do this with NULL.
4) BOOL: C doesn't have an official boolean type, and in reality neither does Objective-C. It's however built into the Foundation classes (Namely from importing NSObject.h). nil is also included in this header file. BOOL in Objective-C has two modes, YES and NO rather than TRUE and FALSE.
5) #import vs #include: As you will notice in the hello world example, #import was used. #import is supported by the gcc compiler, however it is deprecated in favor of #include. #import is basically the same thing as #ifndef #define #endif at the top and bottom of every .h file you make. I find this to be retarded, as many other programmers will most likely agree. For all purposes, just use #import. It's less hassle, and if gcc ever does remove it chances are enough Objective-C developers exist to either keep it from getting removed or getting added back in. As an aside, Apple officially uses #import in all their code so if this ever did happen, you can be certain that Apple would conviently ship a forked version of gcc to add this back in.
6) The word method and message are used interchangably in Objective-C, although messages have special properties. A message can be dynamically forwarded to another object. Calling a message on an object in Objective-C doesn't mean that the object implements that message, just that it knows how to respond to it somehow via directly implementing it or forwarding the message to an object that does know how to.
Creating classes
Fraction.h
1) Instance variables go between @interface Class: Parent { .... }
2) No access is set (protected, public, private). Default is protected. Setting the access will be shown later
3) Instance methods follow after the member variables. The format is: scope (returnType) methodName: (parameter1Type) parameter1Name; ie. -(IBAction) _uiLoginBtnTouch: (id)sender
4) scope refers to class or instance. instance methods begin with - class level methods begin with +
Instance variables go between @interface Class: Parent { .... }
No access is set (protected, public, private). Default is protected. Setting the access will be shown later
Piecing it together
main.m
1) Fraction *frac = [[Fraction alloc] init];
There are several important things in this one line.
The way methods in Objective-C are called is [object method], which is similar to object->method() in C++
Objective-C doesn't have value types, so there is nothing similar to C++'s: Fraction frac; frac.print();. You always deal with objects as pointers in Objective-C.
What this line is really doing is two things: [Fraction alloc] is calling the alloc method on the Fraction class. This is similar to mallocing memory, because that is all that is done in this operation.
[object init] is the constructor call, which initializes any variables in the object. This method is called on the instance returned from [Fraction alloc]. This operation is so common it's usually just done in one line as Object *var = [[Object alloc] init];
2) [frac setNumerator: 1] is quite simple. It's calling the setNumerator method on frac, and passing it the parameter 1.
3) Like every c variant, there's a construct for freeing memory. This is done via release, which is inherited from NSObject. This method will be explainted in greater detail later.
Interface Builder
Actions: things user do/events like push a button
Outlets: things program gonna do like display text
-- Memory Leaks
-----------------------
Try Apple's Instruments utility, found in /Developer/Applications/.
http://developer.apple.com/library/mac/#documentation/DeveloperTools/Conceptual/InstrumentsUserGuide/Introduction/Introduction.html
my thanks to:
http://www.otierney.net/objective-c.html#creatingclasses
Category :
Time: 12:12 PM
C#
check out asp.net "Skins" attaching CSS to controlsThemes - referenced images may be needed in multiple locations in project
ControlUtilities.GetDropDownValue(control);
validate user input on BOTH client and server
Log errors first and display after.
Try Catch Log and ShowError no need to throw
Parse csv of ints to pass to/from functions etc
---> Dev/CommonSQL/GeneralScripts
Web Service object: if 3 or more use a collection and not (Tutor1, Tutor2, Tutor3)
SQL
Check if columns exist when trying to Add new columnsTry Catch around ALL statements except stor procs
TRANS around ALL statements except stor procs
"Development\CommonSQL" for examples of code templates
Remove ALL square brackets [] from SQL scripts
No commentig out code just delete and let SVN handle
Add comments to SQL scripts
If updating a single stor proc use name in filename
Use stor procs to update date or retrieve multiple datasets
Use functions for rest usually just querying data
Try to ensure SQL patches run every evening!
Always Update database from scripts to ensure diagram and db stay in sync
SQL Server
When restoring database of dev server, activity monitor may need to be used to kill processes (from bottom up) related to database your trying to restore.SQL Script naming convention
--------------------------------000) structure updates
050) data updates
100) stor procs or function updates
500) reporting updates
Category :
Time: 3:04 PM
-------------------------------------------------------------
a) Ctrl + drag Trunk to branches folder.
b) Rename new folder to name of branch.
2) SVN - Switching Branches
-------------------------------------------------------------
Right click on correct LEVEL/directory
- SVN -> Switch (branch)
On this dialog the URL can be updated to the new location, so the following change would switch from trunk to UAT changes branch
replacing "trunk" with "branches/Coaching/Coaching v3.1.30 UAT Changes"
replacing "trunk" with "branches/Coaching/Coaching v3.2.00 UAT Changes"
This procedure will need to be repeated for all locations referenced in the visual studio project/solution
C:\Development\Coaching Ireland
C:\inetpub\dev\Coaching
C:\Development\CommonDotNet2
3) Commits prevented because of popup on top right of commit screen
-------------------------------------------------------------
a) right click repository and select properties
b) click first button "Import" and choose file "JiraSVNProperties.svnprops" located here C:\Development\ActionPoint
Ignore files in directory
Ignore all csv files:browse into folder and run command: "svn propset svn:ignore *.csv ."
Category :
Time: 9:20 PM
Or if I turn this sentence a little bit around
"...it should not be the database (-schema) that determines the design of an application but rather should the database schema be a natural outcome of the domain model..."
my thanks to:
http://nhibernate.hibernatingrhinos.com/14/create-and-update-database-schema
What are Design Patterns?
Design patterns provide solutions to common software design problems. In the case of object-oriented programming, design patterns are generally aimed at solving the problems of object generation and interaction, rather than the larger scale problems of overall software architecture. They give generalised solutions in the form of templates that may be applied to real-world problems.Design patterns are a powerful tool for software developers. However, they should not be seen as prescriptive specifications for software. It is more important to understand the concepts that design patterns describe, rather than memorising their exact classes, methods and properties. It is also important to apply patterns appropriately. Using the incorrect pattern for a situation or applying a design pattern to a trivial solution can overcomplicate your code and lead to maintainability issues.
Creational Patterns
The first type of design pattern is the creational pattern. Creational patterns provide ways to instantiate single objects or groups of related objects. There are five such patterns:Abstract Factory. The abstract factory pattern is used to provide a client with a set of related or dependant objects. The "family" of objects created by the factory are determined at run-time.
Builder. The builder pattern is used to create complex objects with constituent parts that must be created in the same order or using a specific algorithm. An external class controls the construction algorithm.
Factory Method. The factory pattern is used to replace class constructors, abstracting the process of object generation so that the type of the object instantiated can be determined at run-time.
Prototype. The prototype pattern is used to instantiate a new object by copying all of the properties of an existing object, creating an independent clone. This practise is particularly useful when the construction of a new object is inefficient.
Singleton. The singleton pattern ensures that only one object of a particular class is ever created. All further references to objects of the singleton class refer to the same underlying instance.
Structural Patterns
The second type of design pattern is the structural pattern. Structural patterns provide a manner to define relationships between classes or objects.Adapter. The adapter pattern is used to provide a link between two otherwise incompatible types by wrapping the "adaptee" with a class that supports the interface required by the client.
Bridge. The bridge pattern is used to separate the abstract elements of a class from the implementation details, providing the means to replace the implementation details without modifying the abstraction.
Composite. The composite pattern is used to create hierarchical, recursive tree structures of related objects where any element of the structure may be accessed and utilised in a standard manner.
Decorator. The decorator pattern is used to extend or alter the functionality of objects at run-time by wrapping them in an object of a decorator class. This provides a flexible alternative to using inheritance to modify behaviour.
Facade. The facade pattern is used to define a simplified interface to a more complex subsystem.
Flyweight. The flyweight pattern is used to reduce the memory and resource usage for complex models containing many hundreds, thousands or hundreds of thousands of similar objects.
Proxy. The proxy pattern is used to provide a surrogate or placeholder object, which references an underlying object. The proxy provides the same public interface as the underlying subject class, adding a level of indirection by accepting requests from a client object and passing these to the real subject object as necessary.
Behavioural Patterns
The final type of design pattern is the behavioural pattern. Behavioural patterns define manners of communication between classes and objects.Chain of Responsibility. The chain of responsibility pattern is used to process varied requests, each of which may be dealt with by a different handler.
Command. The command pattern is used to express a request, including the call to be made and all of its required parameters, in a command object. The command may then be executed immediately or held for later use.
Interpreter. The interpreter pattern is used to define the grammar for instructions that form part of a language or notation, whilst allowing the grammar to be easily extended.
Iterator. The iterator pattern is used to provide a standard interface for traversing a collection of items in an aggregate object without the need to understand its underlying structure.
Mediator. The mediator pattern is used to reduce coupling between classes that communicate with each other. Instead of classes communicating directly, and thus requiring knowledge of their implementation, the classes send messages via a mediator object.
Memento. The memento pattern is used to capture the current state of an object and store it in such a manner that it can be restored at a later time without breaking the rules of encapsulation.
Observer. The observer pattern is used to allow an object to publish changes to its state. Other objects subscribe to be immediately notified of any changes.
State. The state pattern is used to alter the behaviour of an object as its internal state changes. The pattern allows the class for an object to apparently change at run-time.
Strategy. The strategy pattern is used to create an interchangeable family of algorithms from which the required process is chosen at run-time.
Template Method.
The template method pattern is used to define the basic steps of an algorithm and allow the implementation of the individual steps to be changed.
Visitor. The visitor pattern is used to separate a relatively complex set of structured data classes from the functionality that may be performed upon the data that they hold.
my thanks to:
http://www.blackwasp.co.uk/GofPatterns.aspx
Category :
Time: 8:57 PM
Contents
- Introduction
- Plan for the worst
- Code Safely
- Don't throw new Exception()
- Don't put important exception information on the Message field
- Put a single catch (Exception ex) per thread
- Generic Exceptions caught should be published
- Log Exception.ToString(); never log only Exception.Message!
- Don't catch (Exception) more than once per thread
- Don't ever swallow exceptions
- Cleanup code should be put in finally blocks
- Use "using" everywhere
- Don't return special values on error conditions
- Don't use exceptions to indicate absence of a resource
- Don't use exception handling as means of returning information from a method
- Use exceptions for errors that should not be ignored
- Don't clear the stack trace when re-throwing an exception
- Avoid changing exceptions without adding semantic value
- Exceptions should be marked [Serializable]
- When in doubt, don't Assert, throw an Exception
- Each exception class should have at least the three original constructors
- Be careful when using the AppDomain.UnhandledException event
- Don't throw new Exception()
- Don't reinvent the wheel
- VB.NET
- Conclusion
- History
Introduction
Having a bug in your software is forgivable, and even expected. What's unforgivable is having a recurring bug you can't fix because you don't have enough information.
Plan for the worst
Check it early
Strong type checking and validation are powerful tools to prevent unexpected exceptions and to document and test code. The earlier in execution you detect a problem, the easier is to fix.Don't trust external data
External data is not reliable. It must be extensively checked. It doesn't matter if the data is coming from the registry, database, from a disk, from a socket, from a file you just wrote or from the keyboard. All external data should be checked and only then you can rely on it.The only reliable devices are: the video, the mouse and keyboard.
Anytime you need external data, you can have the following situations:- Not enough security privileges
- The information is not there
- The information is incomplete
- The information is complete, but invalid
Writes can fail, too
Unreliable data sources are also unreliable data repositories. When you're saving data, similar situations can happen:- Not enough security privileges
- The device isn't there
- There's not enough space
- The device has a physical fault
Code Safely
A friend of mine often says: "A good programmer is someone who never introduce bad code in his projects". I don't believe that this is all that it's needed to be a good programmer, but surely it will put you almost there. Below, I compiled a list of the most common "bad code" that you can introduce in your projects, when it comes to exception handling.Don't throw new Exception()
Please, don't do it.Exception
is a too broad class, and it's hard to catch without side-effects. Derive your own exception class, but derive it from ApplicationException
. This way you could set a specialized exception handler for exceptions thrown by the framework and another for exceptions thrown by yourself.Revision note: David Levitt wrote me, in the comments section below, that although Microsoft still touts using
System.ApplicationException
as a base class in MSDN docs, this is no longer considered a good practice, as noted by Brad Adams, as you can see in his blog. The idea is creating exception class hierarchies that are as shallow and wide as possible, as you often do with class hierarchies. The reason I didn't change the article immediately was because I needed to do more research before I introduced it here. After all this research, I could not decide yet whether shallow class hierarchies are a good idea in Exception handling or not, so I decided to leave both opinions here. But, no matter what you do, don't throw new Exception()
and derive your own Exception
class when needed.Don't put important exception information on the Message field
Exceptions are classes. When you return the exception information, create fields to store data. If you fail on doing it, people will need to parse the Message field to get the information they need. Now, think what will happen to the calling code if you need to localize or even just correct a spelling error in error messages. You may never know how much code you'll break by doing it.Put a single catch (Exception ex) per thread
Generic exception handling should be done in a central point in your application. Each thread needs a separate try/catch block, or you'll lose exceptions and you'll have problems hard to understand. When an application starts several threads to do some background processing, often you create a class for storing processing results. Don't forget to add a field for storing an exception that could happen or you won't be able to communicate it to the main thread. In "fire and forget" situations, you probably will need to duplicate the main application exception handler on the thread handler.Generic Exceptions caught should be published
It really doesn't matter what you use for logging - log4net, EIF, Event Log, TraceListeners, text files, etc. What's really important is: if you caught a generic Exception, log it somewhere. But log it only once - often code is ridden with catch blocks that log exceptions and you end up with a huge log, with too much repeated information to be useful.Log Exception.ToString(); never log only Exception.Message!
As we're talking about logging, don't forget that you should always logException.ToString()
, and never Exception.Message
. Exception.ToString()
will give you a stack trace, the inner exception and the message. Often, this information is priceless and if you only log Exception.Message
, you'll only have something like "Object reference not set to an instance of an object". Don't catch (Exception) more than once per thread
There are rare exceptions (no pun intended) to this rule. If you need to catch an exception, always use the most specific exception for the code you're writing.I always see beginners thinking that good code is code that doesn't throw exceptions. This is not true. Good code throws exceptions as needed, and handles only the exceptions it knows how to handle.
As a sample of this rule, look at the following code. I bet that the guy who wrote it will kill me when he read this, but it was taken from a real-world example. Actually, the real-world code was a bit more complicated - I simplified it a lot for didactic reasons.
The first class (
MyClass
) is on an assembly, and the second class (GenericLibrary
) is on another assembly, a library full of generic code. On the development machine the code ran right, but on the QA machines, the code always returned "Invalid number", even if the entered number was valid.Can you say why this was happening?
public class MyClass { public static string ValidateNumber(string userInput) { try { int val = GenericLibrary.ConvertToInt(userInput); return "Valid number"; } catch (Exception) { return "Invalid number"; } } } public class GenericLibrary { public static int ConvertToInt(string userInput) { return Convert.ToInt32(userInput); } }The problem was the too generic exception handler. According to the MSDN documentation,
Convert.ToInt32
only throws ArgumentException
, FormatException
and OverflowException
. So, those are the only exceptions that should be handled.The problem was on our setup, which didn't include the second assembly (
GenericLibrary
). Now, we had a FileNotFoundException
when the ConvertToInt
was called, and the code assumed that it was because the number was invalid.The next time you write "
catch (Exception ex)
", try to describe how your code would behave when an OutOfMemoryException
is thrown.Don't ever swallow exceptions
The worst thing you can do is catch (Exception) and put an empty code block on it. Never do this.Cleanup code should be put in finally blocks
Ideally, since you're not handling a lot of generic exceptions and have a central exception handler, your code should have a lot more finally blocks than catch blocks. Never do cleanup code, e.g., closing streams, restoring state (as the mouse cursor), outside of a finally block. Make it a habit.One thing that people often overlook is how a try/finally block can make your code both more readable and more robust. It's a great tool for cleanup code.
As a sample, suppose you need to read some temporary information from a file and return it as a string. No matter what happens, you need to delete this file, because it's temporary. This kind of return & cleanup begs for a try/finally block.
Let's see the simplest possible code without using try/finally:
string ReadTempFile(string FileName) { string fileContents; using (StreamReader sr = new StreamReader(FileName)) { fileContents = sr.ReadToEnd(); } File.Delete(FileName); return fileContents; }This code also has a problem when an exception is thrown on, e.g., the
ReadToEnd
method: it leaves a temporary file on the disk. So, I've actually saw some people trying to solve it coding as this: string ReadTempFile(string FileName) { try { string fileContents; using (StreamReader sr = new StreamReader(FileName)) { fileContents = sr.ReadToEnd(); } File.Delete(FileName); return fileContents; } catch (Exception) { File.Delete(FileName); throw; } }The code is becoming complex and it's starting to duplicate code.
Now, see how much cleaner and robust is the try/finally solution:
string ReadTempFile(string FileName)
{
try
{
using (StreamReader sr = new StreamReader(FileName))
{
return sr.ReadToEnd();
}
}
finally
{
File.Delete(FileName);
}
}
Where did the fileContents variable go? It's not necessary anymore, because we can return the contents and the cleanup code executes after the return point. This is one of the advantages of having code that can run after the function returns: you can clean resources that may be needed for the return statement. Use "using" everywhere
Simply callingDispose()
on an object is not enough. The using
keyword will prevent resource leaks even on the presence of an exception. Don't return special values on error conditions
There are lots of problems with special values:- Exceptions makes the common case faster, because when you return special values from methods, each method return needs to be checked and this consumes at least one processor register more, leading to slower code
- Special values can, and will be ignored
- Special values don't carry stack traces, and rich error details
- All too often there's no suitable value to return from a function that can represent an error condition. What value would you return from the following function to represent a "division by zero" error?
public int divide(int x, int y)
{
return x / y;
}
Don't use exceptions to indicate absence of a resource
Microsoft recommends that you should use return special values on extremely common situations. I know I just wrote the opposite and I also don't like it, but life is easier when most APIs are consistent, so I recommend you to adhere to this style with caution.I looked at the .NET framework, and I noticed that the almost only APIs that use this style are the APIs that return some resource (e.g.,
Assembly.GetManifestStream
method). All those APIs return null in case of the absence of some resource.Don't use exception handling as means of returning information from a method
This is a bad design. Not only exceptions are slow (as the name implies, they're meant only to be used on exceptional cases), but a lot of try/catch blocks in your code makes the code harder to follow. Proper class design can accommodate common return values. If you're really in need to return data as an exception, probably your method is doing too much and needs to be split.Use exceptions for errors that should not be ignored
I'll use a real world example for this. When developing an API so people could access Crivo (my product), the first thing that you should do is calling theLogin
method. If Login
fails, or is not called, every other method call will fail. I chose to throw an exception from the Login method if it fails, instead of simply returning false, so the calling program cannot ignore it. Don't clear the stack trace when re-throwing an exception
The stack trace is one of the most useful information that an exception carries. Often, we need to put some exception handling on catch blocks (e.g., to rollback a transaction) and re-throw the exception. See the right (and the wrong) way of doing it: The wrong way:try { // Some code that throws an exception } catch (Exception ex) { // some code that handles the exception throw ex; }
Why is this wrong? Because, when you examine the stack trace, the point of the exception will be the line of the "throw ex;", hiding the real error location. Try it.
try { // Some code that throws an exception } catch (Exception ex) { // some code that handles the exception throw; }
What has changed? Instead of "
throw ex;
", which will throw a new exception and clear the stack trace, we have simply "throw;
". If you don't specify the exception, the throw statement will simply rethrow the very same exception the catch statement caught. This will keep your stack trace intact, but still allows you to put code in your catch blocks. Avoid changing exceptions without adding semantic value
Only change an exception if you need to add some semantic value to it - e.g., you're doing a DBMS connection driver, so the user doesn't care about the specific socket error and wants only to know that the connection failed.If you ever need to do it, please, keep the original exception on the InnerException member. Don't forget that your exception handling code may have a bug too, and if you have InnerException, you may be able to find it easier.
Exceptions should be marked [Serializable]
A lot of scenarios needs that exceptions are serializable. When deriving from another exception class, don't forget to add that attribute. You'll never know when your method will be called from Remoting components or Web Services.When in doubt, don't Assert, throw an Exception
Don't forget thatDebug.Assert
is removed from release code. When checking and doing validation, it's often better to throw an Exception than to put an assertion in your code.Save assertions for unit tests, for internal loop invariants, and for checks that should never fail due to runtime conditions (a very rare situation, if you think about it).
Each exception class should have at least the three original constructors
Doing it is easy (just copy & paste the definitions from other exception classes) and failing to do that won't allow users of your classes to follow some of these guidelines.Which constructors I am referring to? The last three constructors described on this page.
Be careful when using the AppDomain.UnhandledException event
Revision note: I was pointed by Phillip Haack in my blog of this important omission. Other common source of mistakes is theApplication.ThreadException
event. There are lots of caveats when using them:- The exception notification occurs too late: when you receive the notification your application will not be able to respond to the exception anymore.
- The application will finish if the exception occurred on the main thread (actually, any thread that started from unmanaged code).
- It's hard to create generic code that works consistently. Quoting MSDN: "This event occurs only for the application domain that is created by the system when an application is started. If an application creates additional application domains, specifying a delegate for this event in those applications domains has no effect."
- When the code is running those events, you won't have access to any useful information other than the exception itself. You won't be able to close database connections, rollback transactions, nor anything useful. For beginners, the temptation of using global variables will be huge.
Indeed, you should never base your whole exception handling strategy on those events. Think of them as "safety nets", and log the exception for further examination. Later, be sure to correct the code that is not handling properly the exception.
Don't reinvent the wheel
There are lots of good frameworks and libraries to deal with exceptions. Two of them are provided by Microsoft and I mention here:Notice, though, that if you don't follow strict design guidelines, like those I showed here, those libraries will be nearly useless.
Conclusion
I hope that this article helps someone to code better. More than a closed list of practices, I hope that this article be a starting point for a discussion of how to deal with exceptions in our code, and how to make our programs more robust.I can't believe that I wrote all of this without any mistake or controversial opinion. I'd love to hear your opinion and suggestions about this topic.
History
- 9 Feb 2005 - Initial version
- 21 Feb 2005 - Added information about
ApplicationException
,AppDomain.UnhandledException
andApplication.ThreadException
my thanks to:
http://www.codeproject.com/KB/architecture/exceptionbestpractices.aspx
Category :
Time: 12:01 PM
Responsive Web Design: What It Is and How To Use It
In the field of Web design and development, we’re quickly getting to the point of being unable to keep up with the endless new resolutions and devices.
Responsive Web design is the approach that suggests that design and development should respond to the user’s behavior and environment based on screen size, platform and orientation. The practice consists of a mix of flexible grids and layouts, images and an intelligent use of CSS media queries. As the user switches from their laptop to iPad, the website should automatically switch to accommodate for resolution, image size and scripting abilities. In other words, the website should have the technology to automatically respond to the user’s preferences. This would eliminate the need for a different design and development phase for each new gadget on the market.
The Concept Of Responsive Web Design
some ideas are already being practiced: fluid layouts, media queries and scripts that can reformat Web pages and mark-up effortlessly (or automatically).But responsive Web design is not only about adjustable screen resolutions and automatically resizable images, but rather about a whole new way of thinking about design.
Adjusting Screen Resolution
With more devices come varying screen resolutions, definitions and orientations. Many new devices(being developed every day) are able to switch from portrait to landscape at the user’s whim. How is one to design for these situations?Part of the Solution: Flexible Everything
Now we can make things more flexible. Images can be automatically adjusted, and we have workarounds so that layouts never break (although they may become squished and illegible in the process). While it’s not a complete fix, the solution gives us far more options. It’s perfect for devices that switch from portrait orientation to landscape in an instant or for when users switch from a large computer screen to an iPad.Ethan Marcotte wrote an introductory article about the approach
http://www.alistapart.com/articles/responsive-web-design/
Flexible Images
One major problem that needs to be solved with responsive Web design is working with images. There are a number of techniques to resize images proportionately, and many are easily done. The most popular option, noted in Ethan Marcotte’s article on fluid images but first experimented with by Richard Rutter, is to use CSS’s max-width for an easy fix.Note that max-width is not supported in IE, but a good use of width: 100% would solve the problem neatly in an IE-specific style sheet.
img { max-width: 100%; }
While resizing an image for mobile devices can be very simple, if the original image size is meant for large devices, it could significantly slow download times and take up space unnecessarily.
Filament Group’s Responsive Images
This technique, presented by the Filament Group, takes this issue into consideration and not only resizes images proportionately, but shrinks image resolution on smaller devices, so very large images don’t waste space unnecessarily on small screens.http://filamentgroup.com/examples/responsive-images/
For any screen that is wider than 480 pixels, the larger-resolution image (largeRes.jpg) will load; smaller screens wouldn’t need to load the bigger image, and so the smaller image (smallRes.jpg) will load.
This technique is fully supported in modern browsers, such as IE8+, Safari, Chrome and Opera, as well as mobile devices that use these same browsers (iPad, iPhone, etc.). Older browsers and Firefox degrade nicely
Stop iPhone Simulator Image Resizing
One nice thing about the iPhone and iPod Touch is that Web designs automatically rescale to fit the tiny screen. A full-sized design, unless specified otherwise, would just shrink proportionally for the tiny browser, however many noticed that images were still changing proportionally with the page even if they were specifically made for (or could otherwise fit) the tiny screenBecause this works only with Apple’s simulator, we can use an Apple-specific meta tag to fix the problem
meta name="viewport" content="width=device-width; initial-scale=1.0"
Custom Layout Structure
For extreme size changes, we may want to change the layout altogether, either through a separate style sheet or, more efficiently, through a CSS media query. This does not have to be troublesome; most of the styles can remain the same, while specific style sheets can inherit these styles and move elements around with floats, widths, heights and so on.For example, we could have one main style sheet (which would also be the default) that would define all of the main structural elements, such as #wrapper, #content, #sidebar, #nav, along with colors, backgrounds and typography. Default flexible widths and floats could also be defined.
If a style sheet made the layout too narrow, short, wide or tall, we could then detect that and switch to a new style sheet. This new child style sheet would adopt everything from the default style sheet and then just redefine the layout’s structure.
Media Queries
CSS3 supports all of the same media types as CSS 2.1, such as screen, print and handheld, but has added dozens of new media features, including max-width, device-width, orientation and color, they will be ignored if accessed by an older computer browser that does not support CSS3.This media query is fairly self-explanatory: if the browser displays this page on a screen (rather than print, etc.), and if the width of the screen (not necessarily the viewport) is 480 pixels or less, then load shetland.css.
Multiple media queries can also be dropped right into a single style sheet, which is the most efficient option when used:
/* Smartphones (portrait and landscape) ----------- */ @media only screen and (min-device-width : 320px) and (max-device-width : 480px) { /* Styles */ } /* Smartphones (landscape) ----------- */ @media only screen and (min-width : 321px) { /* Styles */ } /* Smartphones (portrait) ----------- */ @media only screen and (max-width : 320px) { /* Styles */ }
CSS3 Media Queries
@media screen and (min-width: 600px) { .hereIsMyClass { width: 30%; float: right; } }this media query will run only if the minimum width is 600 pixels (therefore, 600 pixels or wider).
@media screen and (max-width: 600px) { .aClassforSmallScreens { clear: both; font-size: 1.3em; } }this media query will apply only to browser or screen widths with a maximum width of 600 pixels or narrower.
@media screen and (max-device-width: 480px) { .classForiPhoneDisplay { font-size: 1.2em; } } @media screen and (min-device-width: 768px) { .minimumiPadWidth { clear: both; margin-bottom: 2px solid #ccc; } }The min-device-width and max-device-width media query properties are great for targeting certain devices with set dimensions, without applying the same styles to other screen sizes in a browser that mimics the device’s size.
Media queries can also be defined in a standard HTML link tag:
JavaScript
Another method that can be used is JavaScript, especially as a back-up to devices that don’t support all of the CSS3 media query options.Fortunately, there is already a pre-made JavaScript library that makes older browsers (IE 5+, Firefox 1+, Safari 2) support CSS3 media queries. If you’re already using these queries, just grab a copy of the library, and include it in the mark-up: http://code.google.com/p/css3-mediaqueries-js/sample jQuery snippet that detects browser width and changes the style sheet accordingly — if one prefers a more hands-on approach:
There are many solutions for pairing up JavaScript with CSS media queries. Remember that media queries are not an absolute answer, but rather are fantastic options for responsive Web design when it comes to pure CSS-based solutions.
Designing for Touchscreen
http://www.whatcreative.co.uk/blog/tips/designing-for-touch-screen/Conclusion
We are indeed entering a new age of Web design and development. Far too many options are available now, and there will be far too many in the future to continue adjusting and creating custom solutions for each screen size, device and advancement in technology. We should rather start a new era today: creating websites that are future-ready right now. Understanding how to make a design responsive to the user doesn’t require too much learning, and it can definitely be a lot less stressful and more productive than learning how to design and code properly for every single device available.my thanks to:
http://www.smashingmagazine.com/2011/01/12/guidelines-for-responsive-web-design/
http://blogs.sitepoint.com/responsive-web-design-with-html5-and-the-less-framework-3/
Category : javascript
Time: 4:47 PM
Functions
A function is a piece of code that is called by name. It can be passed data to operate on (ie. the parameters) and can optionally return data (the return value).All data that is passed to a function is explicitly passed.
Let's say a function is a block of code (usually with its own scope, and sometimes with its own closure) that may receive some arguments and may also return a result.
Methods
A method is a piece of code that is called by name that is associated with an object. In most respects it is identical to a function except for two key differences.1. It is implicitly passed the object for which it was called
2. It is able to operate on data that is contained within the class (remembering that an object is an instance of a class - the class is the definition, the object is an instance of that data)
A method is a function that is owned by an object (in some object oriented systems, it is more correct to say it is owned by a class). Being "owned" by a object/class means that you refer to the method through the object/class; for example, in Java if you want to invoke a method "open()" owned by an object "door" you need to write "door.open()".
The way objects have to expose their behavior are called methods. Methods thus are the artifact object have to "do" something.
In many object oriented languages, all "functions" belong to some object (or class) and so in these languages there are no functions that are not methods.
Category : javascript
Time: 11:08 AM
Natively, the JavaScript language allows you to treat functions in just the same fashion as values. You can assign a function to a variable and also pass it around to other functions. Abstractly speaking, we can say that a JavaScript function is a value of a very special type: the value is the behavior provided and the type is something we can just call “function.”
Natively, the JavaScript language also offers objects. In JavaScript, objects are seen as plain bags of properties and methods. They look more like simple dictionaries of data and behavior than fully-fledged objects as you will find in a qualified OOP language such as C#, Java, or C++. In classic OOP, a class represents the layout of what will actually become an object once an instance of that class is created through the new operator. In JavaScript, you have no classes that provide the blueprints for objects to create. In JavaScript, the “blueprint” for an object is an implicit concept and it looks a lot like a dictionary. So in JavaScript, you just create objects and store data into them. JavaScript objects, however, offer some degree of object-oriented capabilities such as encapsulation and inheritance.
For once, the quick answer to the question that this article addresses is not the classic “It depends.” It is, instead, a less compromising “whatever you ultimately like most”. But let’s elaborate a bit on it.
Functional Programming in Brief
In functional programming the building block of code is the “function”, as opposed to the class in object-oriented programming and the subroutine in procedural programming. A function is a unit of code that only describes the operations to be performed on the input. A function gets some input and returns some output; everything else is hidden from view.As a functional programmer, you build your applications by pipelining function calls to create a super function that just gets the program’s input and returns the program’s output. There’s typically no layer where you process the input, store state, arrange a sequence of statements, update the state, and decide about the next step. A function is a like a value and can be used as an argument and be passed to other functions as well as used in any other context where values can be used.
Note, though, that real-world functional languages such as F# also mix concepts like functions and pipelining with variables and some simple notion of state. F#, for example, lets you store intermediate results in some local variable and use it as the input for successive function calls. The scope of such variables though is fairly limited and there’s anything like global or static members.
JavaScript and Functional Programming
JavaScript is not a truly functional language such as F#. JavaScript, however, does support some constructs that are typical of a functional language. By using these constructs extensively, you can do good functional programming in JavaScript. At the end of the day, this is largely what you do when you use the jQuery library.In JavaScript, anonymous functions are the pillar of functional programming. An anonymous function is a direct offshoot of lambda calculus or, if you like it most, a language adaptation of old-fashioned function pointers.
The only difference between a regular function and an anonymous function is in the name. In a functional context, you don’t strictly need to name a function especially if you’re using it as a value that you pass around. Here’s an example that shows how to combine together various functions.
// Function to calculate a total var CalcTotal = function(x, y) { return x + y; }; // Function to add taxes var AddTaxes = function(x) { return x * 1.2; }; // Function that pipelines the other two var CalcTotalPlusTaxes = function (fnCalcTotal, fnAddTaxes, x, y) { return fnAddTaxes(fnCalcTotal(x, y)); }; // Execution var result = CalcTotalPlusTaxes(CalcTotal, AddTaxes, 40, 60); alert(result);
Treating anonymous functions as plain values allows you to mix data and behavior in a quite effective way. This gives you a chance to apply some design principles to JavaScript code such as Dependency Inversion. When a higher level module (whether an object or a function) depends on capabilities provided by lower level modules, you can just inject the expected behavior as an argument. In many cases, this approach augments the readability and elegance of the code; for sure, it gives you more power to deal with complexity.
jQuery and the Consecration of Functional Programming
The jQuery library called more than ever the people’s attention on functional programming. The jQuery library is based on the jquery object or $. The $ is essentially a wrapper around DOM elements and DOM elements can be passed into the object through the type constructor—the popular $(…) expression. Furthermore, jQuery allows call chaining meaning that the $ object can pass its own wrapped values into other functions that return the same $ object.These three facts about jQuery qualify the root object of the library as a monad; and monads are a fundamental concept in the theory of functional languages. jQuery takes you to reason in terms of chunks of behavior that you concatenate and pass around. This is extremely effective as long as the values you ultimately work with are just those that library manipulates natively. The jQuery library is effective because it allows you to enjoy the power (and to some extent the cleanness) of functional programming for the Web environment where all you do is manipulation of wrapped DOM elements.
You may be a huge fan of the jQuery library and appreciate the functional lifestyle it pushes. However, that has to be put into perspective and should not become a reason to push the functional programming paradigm over everything else. Let’s have a look at the following snippet from the source code of jQuery.
jQuery.fn = jQuery.prototype = { init: function( selector, context ) { ... }, size: function() { return this.length; }, each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { ... } : }
As you can see, the jQuery object has its own prototype featuring capabilities such as size and each. More interestingly, when you write a jQuery plugin you just extend the basic prototype adding a new function. At the end of the day, effective JavaScript programming is always a mix of functional and object-oriented style. With jQuery, though, you are mostly exposed to the functional part of it.
Objects in JavaScript
There’s a significant difference between objects in a qualified OOP language and JavaScript. In OOP languages, the class is a blueprint for actual objects you use. In JavaScript, you just have objects whose blueprint is that of a dictionary of data and functions. When you create a new object in JavaScript, you have an empty dictionary you can fill with anything you like.Having said that, with a bit of work you can create (and reuse) custom objects and manage for them to inherit from existing objects and also behave polymorphically. This work is just what JavaScript object-oriented libraries do.
When it comes to adding layers to JavaScript to make it closer to a qualified OOP language and gain some more programming power and code reusability, you have to choose from two main approaches for extending the capabilities of the native JavaScript objects: closures and prototypes.
Before we get to that, however, a few words about the native Object type in JavaScript and it usage.
You can use the new keyword to create a new dictionary-like object in JavaScript. Next, you stuff data into it and you can add methods by wiring functions to property names. Here’s an example:
var person = new Object(); person.Name = "Dino"; person.LastName = "Esposito"; person.BirthDate = new Date(1979,10,17) person.getAge = function() { var today = new Date(); var thisDay = today.getDate(); var thisMonth = today.getMonth(); var thisYear = today.getFullYear(); var age = thisYear-this.BirthDate.getFullYear()-1; if (thisMonth > this.BirthDate.getMonth()) age = age +1; else if (thisMonth == this.BirthDate.getMonth() && thisDay >= this.BirthDate.getDate()) age = age +1; return age; }
What we have is an object modeled after a person; we don’t have a Person object. A possible way to define the layout of a type is creating a new, all-encompassing function that exposes just the members we like. In addition, in JavaScript all intrinsic objects have a read-only property named prototype. You can use the prototype property to provide a base set of functionality shared by any new instance of an object of that type. These two are the mechanisms to leverage for OOP in JavaScript.
Object-orientation through Closures
A closure is a general concept of programming languages. Applied to JavaScript, a closure is a function that can have variables and methods defined together within the same context. In this way, the outermost (anonymous or named) function “closes” the expression. Here’s an example of the closure model for a function that represents a Person type:var Person = function(name, lastname, birthdate) { this.Name = name; this.LastName = lastname; this.BirthDate = birthdate; this.getAge = function() { var today = new Date(); var thisDay = today.getDate(); var thisMonth = today.getMonth(); var thisYear = today.getFullYear(); var age = thisYear-this.BirthDate.getFullYear()-1; if (thisMonth > this.BirthDate.getMonth()) age = age +1; else if (thisMonth == this.BirthDate.getMonth() && thisDay >= this.BirthDate.getDate()) age = age +1; return age; } }
As you can see, the closure is nothing more than the constructor of the pseudo-class. In a closure model, the constructor contains the member declarations and members are truly encapsulated and private to the class. In addition, members are instance based, which increases the memory used by the class. Here’s how you use the object:
var p = new Person("Dino", "Esposito", new Date( ... ); alert(p.Name + " is " + p.getAge());
The closure model gives full encapsulation, but nothing more. To compose objects, you can only resort to aggregation.
Object-orientation through Prototypes
The prototype model entails that you define the public structure of the class through the JavaScript prototype object. The following code sample shows how to rewrite the preceding Person class to avoid a closure.// Pseudo constructor var Person = function(name, lastname, birthdate) { if(name && lastname && birthdate) { this.initialize(name, lastname, birthdate); } } // Members Person.prototype.initialize = function(name, lastname, birthdate) { this.Name = name; this.LastName = lastname; this.BirthDate = birthdate; } Person.prototype.getAge = function() { var today = new Date(); var thisDay = today.getDate(); var thisMonth = today.getMonth(); var thisYear = today.getFullYear(); var age = thisYear-this.BirthDate.getFullYear()-1; if (thisMonth > this.BirthDate.getMonth()) age = age +1; else if (thisMonth == this.BirthDate.getMonth() && thisDay >= this.BirthDate.getDate()) age = age +1; return age; }
In the prototype model, the constructor and members are clearly separated and a constructor is always required. As for private members, you just don’t have them. The var keyword which would keep them local in a closure doesn’t apply in the prototype model. So you can define getter/setter for what you intend to be properties, but the backing field will anyway remain accessible from the outside. You can resort to some internal (and documented) convention such as prefixing with an underscore the name of members you intend as private. It’s just a convention, however.
By using the prototype feature you can achieve inheritance by simply setting the prototype of a derived object to an instance of the “parent” object.
Developer = function Developer(name, lastname, birthdate) { this.initialize(name, lastname, birthdate); } Developer.prototype = new Person();
Note that you always need to use this to refer to members of the prototype from within any related member function.
Closure vs. Prototype
In the prototype model, members are shared by all instances as they are invoked on the shared prototype object. In this way, the amount of memory used by each instance is reduced which would also provide for faster object instantiation. Aside from syntax peculiarities, the prototype model makes defining classes much more similar to the classic OOP model than the closure model.The choice between closure and prototype should also be guided by performance considerations and browser capabilities. Prototypes have a good load time in all browsers; and indeed, they have excellent performance in Firefox. (In contrast, closures have a better load time than prototypes in Internet Explorer.) Prototypes provide better support for IntelliSense, and allow for tool-based statement completion when used in tools that support this feature, such as Visual Studio. Prototypes can also help you obtain type information by simply using reflection. You won’t have to create an instance of the type in order to query for type information, which is unavoidable if closures are used. Finally, prototypes allow you to easily view private class members when debugging. Debugging objects derived using the closure model requires a number of additional steps.
As an example, consider that the Microsoft AJAX library is built using the prototype model (and the closure model was discarded along the way).
Conclusion
JavaScript is neither 100% functional or object-oriented. However, it lends itself to support to a good extent both paradigms, because in a way it borrows concepts from both qualified functional and object-oriented languages. This inevitably creates some noise around the programming techniques you can employ. As a developer, you must be ready to accept compromises that may not be acceptable in a fully-qualified functional or object-oriented scenario.JavaScript is a must today for writing client-side code for Web and mobile applications. And the client-side code we are called to write is no longer plain scripting of the document object model as it was when the language was introduced. Today, we often use JavaScript for some client-side logic and input validation. To make the whole development process more sustainable, we resort to JavaScript libraries that abstract through functions or classes some of the most common tasks. The jQuery library is just the most illustrious example.
Because of the success of the jQuery library, functional programming is probably gaining momentum and overcoming object-oriented programming in JavaScript. But in the end, the final decision is left to you and attitude, skills, and ease are the key parameters for a decision. You don’t have to take it as a matter of religion and pick up option and stick to that forever. To use JavaScript at its best, you probably have to mix functional features with OO features.
Having said that, if I have to write client code for a Web front-end, I’d probably go with jQuery, use a lot of anonymous functions and don’t even bother about custom objects. Instead, if I have to write my own framework to support some server-side infrastructure, well, I’d probably opt for an object-oriented approach and consider closures or prototypes.
my thanks to:
http://msdn.microsoft.com/en-us/scriptjunkie/gg476048.aspx
Category :
Time: 9:51 PM
The HyperText Transfer Protocol (HTTP) is the life of the Web. It’s used every time you transfer a document, or make an AJAX request.
Why REST
REST is a simple way to organize interactions between independent systems with minimal overhead using clients as diverse as mobile phones and other websites. In theory, REST is not tied to the web, but REST is almost always implemented as such, and was inspired by HTTP. As a result, REST can be used wherever HTTP can.The alternative is building relatively complex conventions on top of HTTP. Often, this takes the shape of entire new XML-based languages. The most illustrious example is SOAP. Because REST has been inspired by HTTP and plays to its strengths, it is the best way to learn how HTTP works.
HTTP
HTTP is the protocol that allows for sending documents back and forth on the Web. A protocol is a set of rules that decide what messages can be exchanged and what messages are appropriate replies to others. Another common protocol is POP3, which you possibly use to fetch email on your hard disk.In HTTP, there are two different roles: server and client. In general, the client always initiates the conversation; the server replies. HTTP is text based; that is, messages are essentially bits of text, although the message body can also contain other media.
HTTP messages are made of a header and a body. The body can often remain empty; it contains data you want to transmit over the network in order to use it according to the instructions in the header. The header contains metadata, such as encoding information; but, in the case of a request, it also contains the important HTTP methods. In the REST style, you will find that header data is often more significant than the body.
URLs
URLs are how you identify the things that you want to operate on. We say that each URL identifies a resource. These are exactly the same URLs which are assigned to web pages. In fact, a web page is a type of resource.Resources are best thought of as nouns. For example, the following is not RESTful:
/clients/add
This is because it uses a URL to describe an action. This is a fairly fundamental point in distinguishing RESTful from non-RESTful systems.
Finally, URLs should be as precise as needed; everything needed to uniquely identify a resource should be in the URL. You should not need to include data identifying the resource in the request. This way, URLs act as a complete map of all the data your application handles.
But how do you specify an action? For example, how do you tell that you want a new client record created instead of retrieved? That is where HTTP verbs come into play.
URLs v Requests ???????????????????????????????????
Finally, URLs should be as precise as needed; everything needed to uniquely identify a resource should be in the URL. You should not need to include data identifying the resource in the request.HTTP Verbs
Each request specifies a certain HTTP verb, or method, in the request header. This is the first all caps word in the request header. For instance,GET / HTTP/1.1
HTTP verbs tell the server what to do with the data identified by the URL.
The request can optionally contain additional information in its body, which might be required to perform the operation – for instance, data you want to store with the resource.
If you have ever created HTML forms, you’ll be familiar with two of the most important HTTP verbs: GET and POST. But there are far more HTTP verbs available. The most important ones for building RESTful API are GET, POST, PUT and DELETE. Other methods are available, such as HEAD and OPTIONS, but they are more rare (if you want to know about all other HTTP methods, the official source is IETF).
GET
GET is the simplest type of HTTP request method the one browsers use all the time when you click a link or type a URL in the address bar. It instructs the server to transmit the data identified by the URL to the client. Data should never be modified on the server side as a result of a GET request. In this sense, a GET request is read-only, but of course, once the client receives the data, it is free to do any operation with it on its own side – for instance, format it for display.PUT
A PUT request is used when you want to create or update the resource identified by the URL. For example,PUT /clients/robin
might create a client called Robin on the server. You will notice that
REST
is completely backend agnostic; there is nothing in the request that informs the server how the data should be created – just that it should. PUT
requests contain the data to use in updating or creating the resource in the body.DELETE
DELETE
should perform the contrary of PUT
; it should be used when you want to delete the resource identified by the URL of the request.POST
POST is used when the processing you wish to happen on the server should be repeated, if the POST request is repeated (that is, they are not idempotent; more on that below). In addition, POST requests should cause processing of the request body as a subordinate of the URL you are posting to.POST /clients/
should not cause the resource at /clients/, itself, to be modified, but a resource whose URL starts with /clients/.
PUT
requests are used easily instead of POST
requests, and vice versa. Some systems use only one, some use POST
for create operations, and PUT
for update operations (since with a PUT
request you always supply the complete URL), some even use POST
for updates and PUT
for creates.Classifying HTTP Methods
Safe and unsafe methods:safe methods are those that never modify resources. The only safe methods, from the four listed above, is GET. The others are unsafe, because they may result in a modification of the resources.
Idempotent methods:
These methods achieve the same result, no matter how many times the request is repeated: they are GET, PUT, and DELETE. The only non idempotent method is POST. PUT and DELETE being considered idempotent might be surprising, though, it, in fact, is quite easy to explain: repeating a PUT method with exactly the same body should modify a resource in a way that it remains identical to the one described in the previous PUT request: nothing will change! Similarly, it makes no sense to delete a resource twice. It follows that no matter how many times a PUT or DELETE request is repeated, the result should be the same as if it had been done only once.
Remember: it’s you, the programmer, who ultimately decides what happens when a certain HTTP method is used. There is nothing inherent to HTTP implementations that will automatically cause resources to be created, listed, deleted, or updated. You must be careful to apply the HTTP protocol correctly and enforce these semantics yourself.
Representations
We can sum up what we have seen so far in the following way: the HTTP client and the HTTP server exchange information about resources identified by URLs.We say that the request and response contains a representation of the resource. By representation, we mean information, in a certain format, about the state of the resource or how that state should be in the future. Both the header and the body are part of the representation.
The HTTP headers, which contain metadata, are tightly defined by the HTTP spec; they can only contain plain text, and must be formatted in a certain manner.
The body can contain data in any format, and this is where the power of HTTP truly shines. You know that you can send plain text, pictures, HTML, and XML in any human language. Through request metadata or different URLs, you can choose between different representations for the same resource. For example, you might send a webpage to browsers and JSON to applications.
The HTTP response should specify the content type of the body. This is done in the header, in the Content-Type field; for instance:
Content/Type: application/json
HTTP Client Libraries
To experiment with the different request methods, you need a client which allows you to decide which method to use. Unfortunately, HTML forms do not fit the bill, as they only allow you to make GET and POST requests. In real life, APIs are accessed programatically, through a separate client application or through JavaScript in the browser.This is the reason why, in addition to the server, it is essential to have good HTTP client capabilities available in your progamming language of choice.
A very popular choice of HTTP client library is, again, cURL. You’re already been familiarized with the cURL command line over the course of this tutorial. cURL includes both a standalone command line program, and a library that can be used from many programming languages. In particular, cURL is very often the HTTP client solution of choice with PHP. Other languages, such as Python, offer more native HTTP client libraries.
Setting up the Example Application
TBC
Conclusion
It’s important to remember that HTTP was conceived to communicate between systems which share nothing but an understanding of the protocol. In general, the less assumptions beyond HTTP you make, the better: this allows the widest range of programs and devices to access your API.my thanks to:
http://net.tutsplus.com/tutorials/other/a-beginners-introduction-to-http-and-rest/
Category : javascript
Time: 6:38 PM
The Basics
We'll start out with a simple overview of the module patternAnonymous Closures
This is the fundamental construct that makes it all possible, and really is the single best feature of JavaScript. We'll simply create an anonymous function, and execute it immediately. All of the code that runs inside the function lives in a closure, which provides privacy and state throughout the lifetime of our application.(function () { // ... all vars and functions are in this scope only // still maintains access to all globals }());
Notice the () around the anonymous function. This is required by the language, since statements that begin with the token function are always considered to be function declarations. Including () creates a function expression instead.
Global Import
JavaScript has a feature known as implied globals. Whenever a name is used, the interpreter walks the scope chain backwards looking for a var statement for that name. If none is found, that variable is assumed to be global. If it's used in an assignment, the global is created if it doesn't already exist. This means that using or creating global variables in an anonymous closure is easy. Unfortunately, this leads to hard-to-manage code, as it's not obvious (to humans) which variables are global in a given file.Luckily, our anonymous function provides an easy alternative. By passing globals as parameters to our anonymous function, we import them into our code, which is both clearer and faster than implied globals.
(function ($, YAHOO) { // now have access to globals jQuery (as $) and YAHOO in this code }(jQuery, YAHOO));
Module Export
Sometimes you don't just want to use globals, but you want to declare them. We can easily do this by exporting them, using the anonymous function's return value. Doing so will complete the basic module pattern, so here's a complete example:var MODULE = (function () { var my = {}, privateVariable = 1; function privateMethod() { // ... } my.moduleProperty = 1; my.moduleMethod = function () { // ... }; return my; }());
Notice that we've declared a global module named MODULE, with two public properties: a method named MODULE.moduleMethod and a variable named MODULE.moduleProperty. In addition, it maintains private internal state using the closure of the anonymous function.
Advanced Patterns
While the above is enough for many uses, we can take this pattern farther and create some very powerful, extensible constructs. Lets work through them one-by-one, continuing with our module named MODULE.Augmentation
One limitation of the module pattern so far is that the entire module must be in one file. Anyone who has worked in a large code-base understands the value of splitting among multiple files. Luckily, we have a nice solution to augment modules. First, we import the module, then we add properties, then we export it. Here's an example, augmenting our MODULE from above:var MODULE = (function (my) { my.anotherMethod = function () { // added method... }; return my; }(MODULE));
After this code has run, our module will have gained a new public method named MODULE.anotherMethod. This augmentation file will also maintain its own private internal state and imports.
Loose Augmentation
While our example above requires our initial module creation to be first, and the augmentation to happen second, that isn't always necessary. One of the best things a JavaScript application can do for performance is to load scripts asynchronously. We can create flexible multi-part modules that can load themselves in any order with loose augmentation. Each file should have the following structure:var MODULE = (function (my) { // add capabilities... return my; }(MODULE || {}));
In this pattern, the var statement is always necessary. Note that the import will create the module if it does not already exist. This means you can use a tool like LABjs and load all of your module files in parallel, without needing to block.
Tight Augmentation
While loose augmentation is great, it does place some limitations on your module. Most importantly, you cannot override module properties safely. You also cannot use module properties from other files during initialization (but you can at run-time after intialization). Tight augmentation implies a set loading order, but allows overrides. Here is a simple example (augmenting our original MODULE):var MODULE = (function (my) { var old_moduleMethod = my.moduleMethod; my.moduleMethod = function () { // method override, has access to old through old_moduleMethod... }; return my; }(MODULE));
Here we've overridden MODULE.moduleMethod, but maintain a reference to the original method, if needed.
Cloning and Inheritance
var MODULE_TWO = (function (old) { var my = {}, key; for (key in old) { if (old.hasOwnProperty(key)) { my[key] = old[key]; } } var super_moduleMethod = old.moduleMethod; my.moduleMethod = function () { // override method on the clone, access to super through super_moduleMethod }; return my; }(MODULE));
This pattern is perhaps the least flexible option. It does allow some neat compositions, but that comes at the expense of flexibility. As I've written it, properties which are objects or functions will not be duplicated, they will exist as one object with two references. Changing one will change the other. This could be fixed for objects with a recursive cloning process, but probably cannot be fixed for functions, except perhaps with eval. Nevertheless, I've included it for completeness.
Cross-File Private State
One severe limitation of splitting a module across multiple files is that each file maintains its own private state, and does not get access to the private state of the other files. This can be fixed. Here is an example of a loosely augmented module that will maintain private state across all augmentations:var MODULE = (function (my) { var _private = my._private = my._private || {}, _seal = my._seal = my._seal || function () { delete my._private; delete my._seal; delete my._unseal; }, _unseal = my._unseal = my._unseal || function () { my._private = _private; my._seal = _seal; my._unseal = _unseal; }; // permanent access to _private, _seal, and _unseal return my; }(MODULE || {}));
Any file can set properties on their local variable _private, and it will be immediately available to the others. Once this module has loaded completely, the application should call MODULE._seal(), which will prevent external access to the internal _private. If this module were to be augmented again, further in the application's lifetime, one of the internal methods, in any file, can call _unseal() before loading the new file, and call _seal() again after it has been executed.
Sub-modules
Our final advanced pattern is actually the simplest. There are many good cases for creating sub-modules. It is just like creating regular modules:MODULE.sub = (function () { var my = {}; // ... return my; }());
Sub-modules have all the advanced capabilities of normal modules, including augmentation and private state.
Conclusions
Most of the advanced patterns can be combined with each other to create more useful patterns. If I had to advocate a route to take in designing a complex application, I'd combine loose augmentation, private state, and sub-modules.I haven't touched on performance here at all, but I'd like to put in one quick note: The module pattern is good for performance. It minifies really well, which makes downloading the code faster. Using loose augmentation allows easy non-blocking parallel downloads, which also speeds up download speeds. Initialization time is probably a bit slower than other methods, but worth the trade-off. Run-time performance should suffer no penalties so long as globals are imported correctly, and will probably gain speed in sub-modules by shortening the reference chain with local variables.
To close, here's an example of a sub-module that loads itself dynamically to its parent (creating it if it does not exist). I've left out private state for brevity, but including it would be simple. This code pattern allows an entire complex heirarchical code-base to be loaded completely in parallel with itself, sub-modules and all.
var UTIL = (function (parent, $) { var my = parent.ajax = parent.ajax || {}; my.get = function (url, params, callback) { // ok, so I'm cheating a bit :) return $.getJSON(url, params, callback); }; // etc... return parent; }(UTIL || {}, jQuery));
my thanks to:
http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth
Category : javascript
Time: 5:01 PM
Crockford shows a much nicer object creation strategy based on closures, which looks something like this:
var animalsApp = (function(){ var new_animal = function(name) { var animal = {}; animal.sayHello = function() { return "Hello, my name is " + name; } return animal; } var new_dog = function(name) { var dog = new_animal(name); dog.bark = function() { return "woof"; } return dog; } var new_cat = function(name) { var cat = new_animal(name); cat.meow = function() { return "eeooowww"; } return cat; } return { main: function(){ var dog = new_dog("rover"); console.log(dog.sayHello()); console.log(dog.bark()); var cat = new_cat("tom"); console.log(cat.sayHello()); console.log(cat.meow()); } }; }()); animalsApp.main();
Using this technique we can create properly encapsulated objects. In the example above, our animalsApp only exposes a single function, main, new_animal, new_dog and new_cat are all private. The class definitions are very clear, any variables or functions defined in the constructor body are private and we only expose members that we explicitly attach to the object (dog.bark = function(){}).
my thanks to:
http://mikehadlow.blogspot.com/2010/12/javascript-defining-classes-with.html
Category : javascript
Time: 4:27 PM
Function Declaration
standard function statement- must always have an Identifier(function name).
- parsed and evaluated before any other expressions are. Even if declaration is positioned last in a source, it will be evaluated before any other expressions contained in a scope.
function getarea(w,h){ //standard function return w * h; } getarea(3,5) //calls function
Function Literal or Expression
an anonymous function assigned to a variablevar getarea = function(w,h){ return w * h; } getarea(3,5) //calls function
Function Expression may omit Identifier.
Named Function Expressions may only access its Identifier in the scope of its newly-defined function
Named Function Expressions make for a much more pleasant debugging experience.
Function Constructor
creates a function on the fly, which is slower and generally discouraged//syntax: new Function(argument1, argument2, ..., argumentY, functionbody) //all parameters must be a string var getarea=new Function("w", "h", "var area=w*h; return area") getarea(3,5) //calls function
What's the difference between declaration and expression?
The 'identifier' is optional for function expression. And when you don't give an identifier, you create an anonymous function. It doesn't mean that you can't specify an identifier.This means following is valid.
var sum = function mySum(a, b) { return a + b; }Important point to note is that you can use 'mySum' only inside the mySum function body, not outside. See following example:
var test1 = function test2() { alert(typeof test2); } alert(typeof(test2)); //alerts 'undefined', surprise! test1(); //alerts 'function' because test2 is a function.
ECMAScript differentiates between two based on a context. If a function foo(){} is part of, say, assignment expression, it is considered a function expression. If, on the other hand, function foo(){} is contained in a function body or in a (top level of) program itself — it is parsed as a function declaration.
// declaration, since it's part of a Program function foo(){}; // expression, since it's part of an AssignmentExpression var bar = function foo(){}; // expression, since it's part of a NewExpression new function bar(){}; (function(){ function bar(){} // declaration, since it's part of a FunctionBody })();
A somewhat less obvious example of function expression is the one where function is wrapped with parenthesis — (function foo(){}). The reason it is an expression is again due to a context: "(" and ")" constitute a grouping operator and grouping operator can only contain an expression
function foo(){} // function declaration (function foo(){}); // function expression: due to grouping operator try { // grouping operator can only contain expression, //not a statement (which `var` is) (var x = 5); } catch(err) { // SyntaxError }
Immediately-Invoked Function Expression (IIFE)
The most widely accepted way to tell the parser to expect a function expression is just to wrap in in parens, because in JavaScript, parens can’t contain statements. At this point, when the parser encounters the function keyword, it knows to parse it as a function expression and not a function declaration.// Either of the following two patterns can be used to immediately invoke // a function expression, thus creating an anonymous closure with privacy. (function(){ /* code */ })(); // I've been using this one (function(){ /* code */ }()); // Crockford recommends this one // Because the point of the parens or coercing operators is to disambiguate // between function expressions and function declarations, they can be // omitted when the parser already expects an expression (but please see the // "important note" below).
In cases where the extra “disambiguation” parens surrounding the function expression are unnecessary (because the parser already expects an expression), it’s still a good idea to use them when making an assignment, as a matter of convention. Such parens typically indicate that the function expression will be immediately invoked, and the variable will contain the result of the function, not the function itself.
Properties
arguments
A local variable that points to the "arguments" object, which contains all of the arguments passed into the function. Use "arguments.length" to determine the number of arguments entered. You can use this property to define functions that accept varying number of parameters.caller
References the function in which the current function is called inside of. If the current function is called at the top level, caller returns null. You can use this property to check the context in which a function is being called.function myresidence(){ calltest() } // alerts function myresidence(), // the function in which calltest() was called inside myresidence()
prototype
Lets you add custom properties and methods to a function's prototype object, which instantly adds them to all instances of the function initialized using the new operator (also called a constructor function). In the below, I'm adding a getprice() method to the constructor function Car() that is reflected on all instances of new Car():function Car(baseprice, years_old){ this.baseprice=baseprice this.history=years_old } //add method getprice() to all instances of Car (called using new Car()) Car.prototype.getprice=function(){ this.price=this.baseprice - (this.history * 1000) alert(this.price) } var mytoyota=new Car(20000, 10) mytoyota.getprice() //alerts 10,000 var myford=new Car(18000, 5) myford.getprice() //alerts 13,000
You can also use the prototype object to extend prebuilt JavaScript objects that are initialized using the new operator with custom methods, such as with Date(), Array(), or String(). Lets extend the default String object with a backwards() method that takes a string and returns it backwards (ie: "george" becomes "egroeg"):
String.prototype.backwards=function(){ var strlen=this.length, reversestr='' //loop through each char within string backwards for (var i=strlen-1; i>-1; i--) reversestr+=this.charAt(i) return reversestr } document.write('george'.backwards()) //writes out "egroeg"
Methods
funcA.apply(funcB, [argument1, argument2, argumentN])
Lets you call a function (funcA) as if it's a method of another function (funcB). Specifically, the "this" keyword when used inside funcA now returns funcB. Identical to call() below, except any arguments passed into funcA should be wrapped in an array.funcA.call(funcB, argument1, argument2, argumentN)
Lets you call a function (funcA) as if it's a method of another function (funcB). Specifically, the "this" keyword when used inside funcA now returns funcB. The two methods apply() and call() are useful when you wish an object to "borrow" a method from another object and use it within its own context.The following illustrates this:
function borrowme(name){ this.bonus=(this.salary * 0.15) + (this.seniority * 500) alert(name + ", your bonus for this year is: " + this.bonus) } function employee(seniority, salary){ this.seniority=seniority this.salary=salary } var employee1=new employee(10, 30000) //returns "Sarah, your bonus for this year is: 9500" borrowme.call(employee1, "Sarah")
Here the custom object "employee" uses the function "borrowme()" to manipulate a few numbers stored within it. Normally the keyword "this" in borrowme() references just that- the function itself. However, when it''s invoked using call(), the context of "this" changes so it references the object passed into the first parameter of call(), or in this case, "employee1".
apply() and call() are important tools in implementing inheritance in JavaScript.
toString()
Returns a string that represents the source code (raw text) of the function. A useful method in debugging, by looking at the source code of a function.my thanks to:
http://www.javascriptkit.com/jsref/function.shtml
http://kangax.github.com/nfe/
http://benalman.com/news/2010/11/immediately-invoked-function-expression/