Tuesday 31 January 2012

MemCached vs Redis for ASP.NET and Entity framework

memcached and redis differ quite a bit.
Memcached is completely in memory and will lose all of its cache in case the server is restarted.
Redis is persistent, and on top of that has a lot more features (like set operations, lists, counters, etc).
Since you're only talking about a cache, memcache might be the better fit since it's dedicated for just that.
We use memcache for a lot of things and what it does it does good. If it turns out later that you need persistence, you can always switch for memcachedb which uses the same mecache protocol but has a berkelydb backend

Format numbers in javascript

Format numbers in javascript same in C#


Here's a simple JS function to add commas to an integer number in string format.
function addCommas(str) {
    var amount = new String(str);
    amount = amount.split("").reverse();

    var output = "";
    for ( var i = 0; i <= amount.length-1; i++ ){
        output = amount[i] + output;
        if ((i+1) % 3 == 0 && (amount.length-1) !== i)output = ',' + output;
    }
    return output;
}

example:
addCommas(12345);

output: 12,345

Formatting numbers for decimals and significant digits in JavaScript


       Formatting numbers so they confirm to a specific format can be deceivingly tricky. For example, one of the most common tasks is to format a number for currency display- an integer followed by two decimals. You may be tempted to use number rounding to first shift the number's decimal places (via multiplication), round it, then shift the decimal back (via division) to pound the number into your hard earned dollar, though that won't work in many cases. For example, consider the number 120. Number rounding certainly won't get you to 120.00.
To easily format numbers for a specific number of trailing decimals or total digits (aka padding), JavaScript 1.5 introduces the below two nifty methods:
Methods Description
Number.toFixed(x) Formats any number for "x" number of trailing decimals. The number is rounded up, and "0"s are used after the decimal point if needed to create the desired decimal length.
Number.toPrecision(x) Formats any number so it is of "x" length. Also called significant digits. A decimal point and "0"s are used if needed to create the desired length.

Number.toFixed()

The best way to see all the subtleties of toFixed() is to see it in action:
var profits=2489.8237
profits.toFixed(3) //returns 2489.824 (round up)
profits.toFixed(2) //returns 2489.82
profits.toFixed(7) //returns 2489.8237000 (padding)
Displaying any number in currency format can't get any easier!

Number.toPrecision()

To toPrecision() now:
var anumber=123.45
anumber.toPrecision(6) //returns 123.450 (padding)
anumber.toPrecision(4) //returns 123.5 (round up)
anumber.toPrecision(2) //returns 1.2e+2 (you figure it out!)
toPrecision() is useful if your number must be of a certain length.

Browser considerations

Now, as noted, our two heros above are JavaScript 1.5 methods. What this means is that they'll only work in IE5.5+ and NS6+. The issue of legacy browsers not performing the desired formatting operation not withstanding, how do you ensure that these two methods at least degrade well? Well, by using method detection in your code. For example:
var profits=2489.8237
if (profits.toFixed) //if browser supports toFixed() method
profits.toFixed(2)
For those of you who also need to ensure legacy browsers such as IE5 also perform the desired number formatting operation, well, then it's time to roll your own function. But be warned, it won't as pretty as what has taken place here!

MemcacheProvider For C#


using System;
using Enyim.Caching;
using Enyim.Caching.Memcached;

namespace CafeX.Core.Provider
{
    public class MemcacheProvider
    {
        private static MemcachedClient _instant;
        public static MemcachedClient Instant
        {
            get { return _instant ?? (_instant = new MemcachedClient()); }
        }

        public static object Get(string key)
        {
            return Instant.Get(key);
        }

        public static void Add(string key, object value)
        {
           Instant.Store(StoreMode.Add, key, value);
        }

        public static void AddWithTimeOut(string key, object value, int timeout)
        {
            Instant.Store(StoreMode.Add, key, value, DateTime.Now.AddMinutes(timeout));
        }

        public static void Update(string key, object value)
        {
            Instant.Store(StoreMode.Set, key, value);
        }

        public static void UpdateWithTimeOut(string key, object value, int timeout)
        {
            Instant.Store(StoreMode.Set, key, value, DateTime.Now.AddMinutes(timeout));
        }

        public static void Remove(string key)
        {
            Instant.Remove(key);
        }
    }
}

Provider for Memcache(VB.NET)


Imports Enyim.Caching
Imports Enyim.Caching.Memcached

Namespace CacheService
    Public Class MemcacheProvider
        Implements ICacheProvider

        Private Shared _instant As MemcachedClient
        Public Shared ReadOnly Property Instant() As MemcachedClient
            Get
                If _instant Is Nothing Then
                    _instant = New MemcachedClient()
                End If
                Return _instant
            End Get
        End Property

        Public Function [Get](ByVal key As String) As Object Implements ICacheProvider.[Get]
            Return Instant.[Get](key)
        End Function

        Public Sub Add(ByVal key As String, ByVal value As Object) Implements ICacheProvider.Add
            Instant.Store(StoreMode.Add, key, value)
        End Sub

        Public Sub Add(ByVal key As String, ByVal value As Object, ByVal timeout As Integer) Implements ICacheProvider.Add
            Instant.Store(StoreMode.Add, key, value, DateTime.Now.AddMinutes(timeout))
        End Sub

        Public Sub Update(ByVal key As String, ByVal value As Object) Implements ICacheProvider.Update
            Instant.Store(StoreMode.[Set], key, value)
        End Sub

        Public Sub UpdateWithTimeOut(ByVal key As String, ByVal value As Object, ByVal timeout As Integer) Implements ICacheProvider.Update
            Instant.Store(StoreMode.[Set], key, value, DateTime.Now.AddMinutes(timeout))
        End Sub

        Public Sub Remove(ByVal key As String) Implements ICacheProvider.Remove
            Instant.Remove(key)
        End Sub


    End Class
End Namespace

Monday 30 January 2012

memcached for Windows


memcached for Windows

This is a port of memcached to the win32 architecture by Kenneth Dalgleish, based on Kronuz's 1.2.1 port. This port is not supported by the official memcached team.

Install

The win32 version of memcached can be run both as a NT Service or from the command line. To install memcached as a service, follow the next steps:
  1. Unzip the binaries in your desired directory (eg. c:\memcached)
  2. Install the service using the command: 'c:\memcached\memcached.exe -d install' from the command line
  3. Start the server from the Microsoft Management Console or by running the following command: 'c:\memcached\memcached.exe -d start'
  4. Use the server, by default listening to port 11211

Building from source

To build from source, you will need Visual Studio 2005 (any edition with C++ should work), Windows SDK (eg.Windows SDK for Windows Server 2008 and .NET Framework 3.5) and libevent (win32 binary provided on this page).
  1. Install Visual Studio 2005
  2. Install Windows SDK
  3. Put libevent.lib in Win32-Prj/ folder
  4. Open solution file and it should build

Downloads

memcached 1.2.4 Win32 Beta

Libevent 1.3e Win32

(Needed if building from source)

Object reference not set to an instance of an object(call webservice)


Error:

Server Error in '/' Application.

Server was unable to process request. ---> Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> Object reference not set to an instance of an object.

Source Error:


Line 891:        Public Function AddComment(ByVal content As String As String
Line 892:            Dim results() As Object = 
Me.Invoke("AddComment", New Object() {content)
Line 893:            Return CType(results(0),String)
Line 894:        End Function

Source File: D:\Develope\SoHoa\Sohoa2012\Test\Web References\commentservice\Reference.vb    Line: 892

Stack Trace:



[SoapException: Server was unable to process request. 
---> Object reference not set to an instance of an object.]
   System.Web.Services.Protocols.SoapHttpClientProtocol.
ReadResponse(SoapClientMessage message, 
WebResponse response, Stream responseStream, Boolean asyncCall) +431702
   System.Web.Services.Protocols.SoapHttpClientProtocol.
Invoke(String methodName, Object[] parameters) +204
   Test.commentservice.Service.AddComment(String content
   ASP.default_aspx.Page_Load(Object sender, EventArgs e) +92
   System.Web.UI.Control.OnLoad(EventArgs e) +99
   System.Web.UI.Control.LoadRecursive() +50
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint,
 Boolean includeStagesAfterAsyncPoint) +627



Version Information: Microsoft .NET Framework Version:2.0.50727.5420; ASP.NET Version:2.0.50727.5420              



Resolve:

The error should occur at server side and I believe above code is taken from client side proxy class.
Try putting a debugger on the server side and see what is going on. This kind of error typically comes from code that assumes that an object exists
and users it when a null value is present. With the debugger you can figure out what line of code is failing, and then from that figure out what object reference is null. At the very least you will then know where you should be checking object references for null values.

Sunday 29 January 2012

HTML5 Form Attributes

This chapter covers some of the new attributes for <form> and <input>.
New form attributes:
  • autocomplete
  • novalidate
New input attributes:
  • autocomplete
  • autofocus
  • form
  • form overrides (formaction, formenctype, formmethod, formnovalidate, formtarget)
  • height and width
  • list
  • min, max and step
  • multiple
  • pattern (regexp)
  • placeholder
  • required

Browser Support

Attribute IE Firefox Opera Chrome Safari
autocomplete 8.0 3.5 9.5 3.0 4.0
autofocus No 4.0 10.0 3.0 4.0
form No 4.0 9.5 10.0 No
form overrides No 4.0 10.5 10.0 No
height and width 8.0 3.5  9.5 3.0 4.0
list No 4.0 9.5 No No
min, max and step No No 9.5 3.0 No
multiple No 3.5 11.0 3.0 4.0
novalidate No 4.0 11.0 10.0 No
pattern No 4.0 9.5 3.0 No
placeholder No 4.0 11.0 3.0 3.0
required No 4.0 9.5 3.0 No


autocomplete Attribute

The autocomplete attribute specifies that the form or input field should have an autocomplete function.
Note: The autocomplete attribute works with <form>, and the following <input> types: text, search, url, telephone, email, password, datepickers, range, and color.
When the user starts to type in an autocomplete field, the browser should display options to fill in the field:

Example

<form action="demo_form.asp" method="get" autocomplete="on">
First name: <input type="text" name="fname" /><br />
Last name: <input type="text" name="lname" /><br />
E-mail: <input type="email" name="email" autocomplete="off" /><br />
<input type="submit" />
</form>

Try it yourself »
Note: In some browsers you may need to activate the autocomplete function for this to work.

autofocus Attribute

The autofocus attribute specifies that a field should automatically get focus when a page is loaded.
Note: The autofocus attribute works with all <input> types.

Example

User name: <input type="text" name="user_name"  autofocus="autofocus" />

Try it yourself »


form Attribute

The form attribute specifies one or more forms the input field belongs to.
Note: The form attribute works with all <input> types.
The form attribute must refer to the id of the form it belongs to:

Example

<form action="demo_form.asp" method="get" id="user_form">
First name:<input type="text" name="fname" />
<input type="submit" />
</form>
Last name: <input type="text" name="lname" form="user_form" />

Try it yourself »
Note: To refer to more than one form, use a space-separated list.  


Form Override Attributes

The form override attributes allow you to override some of the attributes set for the form element.
The form override attributes are:
  • formaction - Overrides the form action attribute
  • formenctype - Overrides the form enctype attribute
  • formmethod - Overrides the form method attribute
  • formnovalidate - Overrides the form novalidate attribute
  • formtarget - Overrides the form target attribute
Note: The form override attributes works with the following <input> types: submit and image.

Example

<form action="demo_form.asp" method="get" id="user_form">
E-mail: <input type="email" name="userid" /><br />
<input type="submit" value="Submit" />
<br />
<input type="submit" formaction="demo_admin.asp" value="Submit as admin" />
<br />
<input type="submit" formnovalidate="true"
value="Submit without validation" />
<br />
</form>

Try it yourself »
Note: These attributes are helpful for creating different submit buttons.

height and width Attributes

The height and width attributes specifies the height and width of the image used for the input type image.
Note: The height and width attributes only works with <input> type: image.

Example

<input type="image" src="img_submit.gif" width="24" height="24" />

Try it yourself »


list Attribute

The list attribute specifies a datalist for an input field. A datalist is a list of options for an input field.
Note: The list attribute works with the following <input> types: text, search, url, telephone, email, date pickers, number, range, and color.

Example

Webpage: <input type="url" list="url_list" name="link" />
<datalist id="url_list">
<option label="W3Schools" value="http://www.w3schools.com" />
<option label="Google" value="http://www.google.com" />
<option label="Microsoft" value="http://www.microsoft.com" />
</datalist>

Try it yourself »


min, max and step Attributes

The min, max and step attributes are used to specify restrictions for input types containing numbers or dates.
The max attribute specifies the maximum value allowed for the input field.
The min attribute specifies the minimum value allowed for the input field.
The step attribute specifies the legal number intervals for the input field (if step="3", legal numbers could be -3,0,3,6, etc).
Note: The min, max, and step attributes works with the following <input> types: date pickers, number, and range.
The example below shows a numeric field that accepts values between 0 and 10, with a step of 3 (legal numbers are 0, 3, 6 and 9):

Example

Points: <input type="number" name="points" min="0" max="10" step="3" />

Try it yourself »


multiple Attribute

The multiple attribute specifies that multiple values can be selected for an input field.
Note: The multiple attribute works with the following <input> types: email, and file.

Example

Select images: <input type="file" name="img" multiple="multiple" />

Try it yourself »


novalidate Attribute

The novalidate attribute specifies that the form or input field should not be validated when submitted.
If this attribute is present the form will not validate form input.
Note: The novalidate attribute works with: <form> and the following <input> types: text, search, url, telephone, email, password, date pickers, range, and color.

Example

<form action="demo_form.asp" novalidate="novalidate">
E-mail: <input type="email" name="user_email" />
<input type="submit" />
</form>

Try it yourself »


pattern Attribute

The pattern attribute specifies a pattern used to validate an input field.
The pattern is a regular expression. You can read about this in our JavaScript tutorial.
Note: The pattern attribute works with the following <input> types: text, search, url, telephone, email, and password
The example below shows a text field that can only contain three letters (no numbers or special characters):

Example

Country code: <input type="text" name="country_code"
pattern="[A-z]{3}" title="Three letter country code" />

Try it yourself »


placeholder Attribute

The placeholder attribute provides a hint that describes the expected value of an input field.
Note: The placeholder attribute works with the following <input> types: text, search, url, telephone, email, and password
The hint is displayed in the input field when it is empty, and disappears when the field gets focus:

Example

<input type="search" name="user_search"  placeholder="Search W3Schools" />

Try it yourself »


required Attribute

The required attribute specifies that an input field must be filled out before submitting.
Note: The required attribute works with the following <input> types: text, search, url, telephone, email, password, date pickers, number, checkbox, radio, and file.

Example

Name: <input type="text" name="usr_name" required="required" />

Try it yourself »

HTML5 Form Elements

HTML5 New Form Elements

HTML5 has several new elements and attributes for forms.
This chapter covers the new form elements:
  • <datalist>
  • <keygen>
  • <output>

Browser Support

Tag IE Firefox Opera Chrome Safari
<datalist> No 4.0 9.5 No No
<keygen> No 4.0 10.5 3.0 No
<output> No 4.0 9.5 10.0 5.1


<datalist> Element

The <datalist> element specifies a list of options for an input field.
The list is created with <option> elements inside the <datalist>.
To bind a <datalist> to an input field, let the list attribute of the input field refer to the id of the datalist:

Example

Webpage: <input type="url" list="url_list" name="link" />
<datalist id="url_list">
<option label="W3Schools" value="http://www.w3schools.com" />
<option label="Google" value="http://www.google.com" />
<option label="Microsoft" value="http://www.microsoft.com" />
</datalist>

Try it yourself »
Tip: The <option> elements should always have a value attribute.

<keygen> Element

The purpose of the <keygen> element is to provide a secure way to authenticate users.
The <keygen> element is a key-pair generator. When a form is submitted, two keys are generated, one private and one public.
The private key is stored on the client, and the public key is sent to the server. The public key could be used to generate a client certificate to authenticate the user in the future.
Currently, the browser support for this element is not good enough to be a useful security standard.

Example

<form action="demo_form.asp" method="get">
Username: <input type="text" name="usr_name" />
Encryption: <keygen name="security" />
<input type="submit" />
</form>

Try it yourself »


<output> Element

The <output> element is used for different types of output, like calculations or script output:

Example

<form oninput="x.value=parseInt(a.value)+parseInt(b.value)">0
<input type="range" name="a" value="50" />100
+<input type="number" name="b" value="50" />
=<output name="x" for="a b"></output>
</form>

Try it yourself »


HTML5 New Form Elements

Tag Description
<datalist> Defines a list of options for an input field
<keygen> Defines a key-pair generator field
<output> Represents the result of a calculation

HTML5 Input Types

HTML5 has several new input types for forms. These new features allow better input control and validation.
This chapter covers the new input types:
  • color
  • date
  • datetime
  • datetime-local
  • email
  • month
  • number
  • range
  • search
  • tel
  • time
  • url
  • week
Note: Not all major browsers support all the new input types. However, you can already start using them; If they are not supported, they will behave as regular text fields.

Input Type: color

The color type is used for input fields that should contain a color.
Opera Safari Chrome Firefox Internet Explorer

Example

Select a color from a color picker:
Select your favorite color: <input type="color" name="favcolor" />

Try it yourself »


Input Type: date

The date type allows the user to select a date.
Opera Safari Chrome Firefox Internet Explorer

Example

Define a date control:
Birthday: <input type="date" name="bday" />

Try it yourself »


Input Type: datetime

The datetime type allows the user to select a date and time (with time zone).
Opera Safari Chrome Firefox Internet Explorer

Example

Define a date and time control (with time zone):
Birthday (date and time): <input type="datetime" name="bdaytime" />

Try it yourself »


Input Type: datetime-local

The datetime-local type allows the user to select a date and time (no time zone).
Opera Safari Chrome Firefox Internet Explorer

Example

Define a date and time control (no time zone):
Birthday (date and time): <input type="datetime-local" name="bdaytime" />

Try it yourself »


Input Type: email

The email type is used for input fields that should contain an e-mail address.
Opera Safari Chrome Firefox Internet Explorer

Example

Define a field for an e-mail address (will be automatically validated when submitted):
E-mail: <input type="email" name="usremail" />

Try it yourself »
Tip: Safari on iPhone recognizes the email type, and changes the on-screen keyboard to match it (adds @ and .com options).

Input Type: month

The month type allows the user to select a month and year.
Opera Safari Chrome Firefox Internet Explorer

Example

Define a month and year control (no time zone):
Birthday (month and year): <input type="month" name="bdaymonth" />

Try it yourself »


Input Type: number

The number type is used for input fields that should contain a numeric value.
You can also set restrictions on what numbers are accepted:
Opera Safari Chrome Firefox Internet Explorer

Example

Define a numeric field (with restrictions):
Quantity (between 1 and 5): <input type="number" name="quantity" min="1" max="5" />

Try it yourself »
Use the following attributes to specify restrictions:
  • max - specifies the maximum value allowed
  • min - specifies the minimum value allowed
  • step - specifies the legal number intervals
  • value - Specifies the default value
Try an example with all the restriction attributes: Try it yourself

Input Type: range

The range type is used for input fields that should contain a value from a range of numbers.
You can also set restrictions on what numbers are accepted.
Opera Safari Chrome Firefox Internet Explorer

Example

Define a control for entering a number whose exact value is not important (like a slider control):
<input type="range" name="points" min="1" max="10" />

Try it yourself »
Use the following attributes to specify restrictions:
  • max - specifies the maximum value allowed
  • min - specifies the minimum value allowed
  • step - specifies the legal number intervals
  • value - Specifies the default value

Input Type: search

The search type is used for search fields (a search field behaves like a regular text field).
Opera Safari Chrome Firefox Internet Explorer

Example

Define a search field (like a site search, or Google search):
Search Google: <input type="search" name="googlesearch" />

Try it yourself »


Input Type: tel

Opera Safari Chrome Firefox Internet Explorer

Example

Define a field for entering a telephone number:
Telephone: <input type="tel" name="usrtel" />

Try it yourself »


Input Type: time

The time type allows the user to select a time.
Opera Safari Chrome Firefox Internet Explorer

Example

Define a control for entering a time (no time zone):
Select a time: <input type="time" name="usr_time" />

Try it yourself »


Input Type: url

The url type is used for input fields that should contain a URL address.
The value of the url field is automatically validated when the form is submitted.
Opera Safari Chrome Firefox Internet Explorer

Example

Define a field for entering a URL:
Add your homepage: <input type="url" name="homepage" />

Try it yourself »
Tip: Safari on iPhone recognizes the url input type, and changes the on-screen keyboard to match it (adds .com option).

Input Type: week

The week type allows the user to select a week and year.
Opera Safari Chrome Firefox Internet Explorer

Example

Define a week and year control (no time zone):
Select a week: <input type="week" name="week_year" />

Try it yourself »


HTML5 <input> Tag

Tag Description
<input> Defines an input field