More details at ASP.Net site. At that site you also get some solutions, and I have read on the web that many people suggests changing web.config. That's a bad solution since it will affect all pages on your site.
Instead add a tag validateRequest="false" into the Page-directive on top of the page you want users to be able to input HTML and script tags.
Its very simple, free and SEO Friendly. Submit Now....
Tuesday, May 27, 2008
A potentially dangerous Request.Form value was detected from the client
Monday, May 19, 2008
ByRef vs ByVal
ByRef and ByVal
When getting the value of a variable from a procedure or function parameter you have two ways to request it. Either you can request for it to be passed ByRef (default), or ByVal.
Passing ByVal
Private Sub TestSub(ByVal strPath As String)
Passing ByRef
Private Sub TestSub(ByRef strPath As String) ' or just
Private Sub TestSub(strPath As String)
When you pass ByVal, Visual Basic passes a copy of the variable to the procedure. This way the procedure gets the value, but any changes it makes will not affect the original variable.
When you pass ByRef, Visual Basic passes a pointer to the procedure. This is a reference so that the procedure knows where to find the variable in the memory. Any changes the procedure makes to this variable will effect the original one, as they are the same thing, however the variable does not need to be declared as public if you were wanting the procedure to access the variabl any other way. The following example shows the differences:
Sub Form_Load()
Dim strTest As String
'// fill the variable
strTest = "Hello from Form_Load"
'// call the procedure
Call TestSub(strTest)
'// display a message box containing the value of strTest
Msgbox strTest
End Sub
'// TestSub procedure when passing ByVal
Sub TestSub(ByVal strString As String)
strString = "Hello from TestSub"
'// when control returns to Form_Load, no changes will have
'// been made to strTest
End Sub
'// TestSub procedure when passing ByRef
Sub TestSub(ByRef strString As String)
strString = "Hello from TestSub"
'// when control returns to Form_Load, the value of
'// strTest will have changed to Hello from TestSub
End Sub
Note that when you are passing a variable ByRef, it must be declared as a specific datatype (ie string). Otherwise, VB cannot pass a pointer to it. If you do not do this, you will get a compile error:
ByRef Argument Type Mismatch.
This does not occur when passing ByVal. For example, the code below will produce a compile error when you press Command1:
Private Function TestFunction(ByRef sString As String)
sString = sString & vbCrLf
End Function
Private Sub Command1_Click()
Dim sTestString
TestFunction sTestString
End Sub
while, the code below would not, as you have explicitly declared sTestString As String.
Private Function TestFunction(ByRef sString As String)
sString = sString & vbCrLf
End Function
Private Sub Command2_Click()
Dim sTestString As String
TestFunction sTestString
End Sub
Friday, May 16, 2008
Thursday, May 15, 2008
Bulk Insert Into SQL SERVER from CSV / text file
This is very common request recently - How to import CSV file into SQL Server? How to load CSV file into SQL Server Database Table? How to load comma delimited file into SQL Server? Let us see the solution in quick steps.
CSV stands for Comma Separated Values, sometimes also called Comma Delimited Values.
Create TestTable
USE TestData GO CREATE TABLE CSVTest
(ID INT,FirstName VARCHAR(40),LastName VARCHAR(40),BirthDate SMALLDATETIME) GO
Create CSV file in drive C: with name csvtest.txt with following content. The location of the file is C:\csvtest.txt
1,James,Smith,19750101 2,Meggie,Smith,19790122 3,Robert,Smith,20071101 4,Alex,Smith,20040202
Now run following script to load all the data from CSV to database table. If there is any error in any row it will be not inserted but other rows will be inserted.
BULK INSERT CSVTest FROM ‘c:\csvtest.txt’ WITH(FIELDTERMINATOR = ‘,’,ROWTERMINATOR = ‘\n’) GO
Check the content of the table.
SELECT * FROM CSVTest GO
Drop the table to clean up database.
SELECT * FROM CSVTest GO
ASP.NET 2.0 and "Validation of ViewState Mac failed" exception
If you get this Exception
[HttpException (0x80004005): Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that <machineKey> configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.]
and
- you know *for sure* that you aren't using a web farm
- it seems that it appears when using built-in databound controls such as GridView, DetailsView or FormView which utilize DataKeyNames.
- it appears if you have a large page which loads slowly for any reason
If following preconditions are true and you click a postbacking control/link while the Page hasn't loaded completely, you might get the "Validation of ViewState MAC failed" exception. In this case be sure to check following post on ASP.NET Forums where this has been discussed quite thoroughly : http://forums.asp.net/1173230/ShowPost.aspx
It appears because GridView using DataKeyNames requires ViewState to be encrypted. And when ViewState is encrypted, Page adds <input type="hidden" name="__VIEWSTATEENCRYPTED" id="__VIEWSTATEENCRYPTED" value="" /> field just before closing of the <form> tag. But this hidden field might not bet yet rendered to the browser with long-running pages, and if you make a postback before it "gets down", browser initiates postback without this field (in form post collection)
End result is that if this field is omitted on postback, Page doesn't "know" that viewstate is encrypted and causes the prementioned Exception. E.g Page expects to be fully-loaded before you can make a postback. And by the way similar problem is with event validation since __EVENTVALIDATION field is also rendered on the end of the form.
A way to overcome the problem is to set in web.config
-
<pages enableEventValidation="false" viewStateEncryptionMode ="Never" />
Just note the security implications of these!
Wednesday, May 14, 2008
Useful META TAGS Table of Contents
Note the keywords "HTTP-EQUIV", "Name" and "Content" are case-insensitive. Their values are also case-insensitive.
Tag Name | Example(s) | Description |
---|---|---|
Author | <META NAME="AUTHOR" CONTENT="Tex Texin"> | The author's name. |
cache-control | <META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE"> | HTTP 1.1. Allowed values = PUBLIC | PRIVATE | NO-CACHE | NO-STORE. Public - may be cached in public shared caches Private - may only be cached in private cache no-Cache - may not be cached no-Store - may be cached but not archived The directive CACHE-CONTROL:NO-CACHE indicates cached information should not be used and instead requests should be forwarded to the origin server. This directive has the same semantics as the PRAGMA:NO-CACHE. |
Content-Language | <META HTTP-EQUIV="CONTENT-LANGUAGE" CONTENT="en-US,fr"> | Declares the primary natural language(s) of the document. May be used by search engines to categorize by language. |
CONTENT-TYPE | <META HTTP-EQUIV="CONTENT-TYPE" CONTENT="text/html; charset=UTF-8"> | The HTTP content type may be extended to give the character set. It is recommended to always use this tag and to specify the charset. |
Copyright | <META NAME="COPYRIGHT" CONTENT="© 2004 Tex Texin"> | A copyright statement. |
DESCRIPTION | <META NAME="DESCRIPTION" CONTENT="...summary of web page..."> | The text can be used when printing a summary of the document. The text should not contain any formatting information. Used by some search engines to describe your document. Particularly important if your document has very little text, is a frameset, or has extensive scripts at the top. |
EXPIRES | <META HTTP-EQUIV="EXPIRES" CONTENT="Mon, 22 Jul 2002 11:12:01 GMT"> | The date and time after which the document should be considered expired. An illegal EXPIRES date, e.g. "0", is interpreted as "now". Setting EXPIRES to 0 may thus be used to force a modification check at each visit. Web robots may delete expired documents from a search engine, or schedule a revisit. HTTP 1.1 (RFC 2068) specifies that all HTTP date/time stamps MUST be generated in Greenwich Mean Time (GMT) and in RFC 1123 format. |
Keywords | <META NAME="KEYWORDS" CONTENT="sex, drugs, rock & roll"> | The keywords are used by some search engines to index your document in addition to words from the title and document body. Typically used for synonyms and alternates of title words. Consider adding frequent misspellings. e.g. heirarchy, hierarchy. |
PRAGMA NO-CACHE | <META HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE"> | This directive indicates cached information should not be used and instead requests should be forwarded to the origin server. This directive has the same semantics as the CACHE-CONTROL:NO-CACHE directive and is provided for backwards compatibility with HTTP/1.0. Clients SHOULD include both PRAGMA:NO-CACHE and CACHE-CONTROL:NO-CACHE when a no-cache request is sent to a server not known to be HTTP/1.1 compliant. HTTP/1.1 clients SHOULD NOT send the PRAGMA request-header. HTTP/1.1 caches SHOULD treat "PRAGMA:NO-CACHE" as if the client had sent "CACHE-CONTROL:NO-CACHE". Also see EXPIRES. |
Refresh | <META HTTP-EQUIV="REFRESH" CONTENT="15;URL=http://www.I18nGuy.com/index.html"> | Specifies a delay in seconds before the browser automatically reloads the document. Optionally, specifies an alternative URL to load, making this command useful for redirecting browsers to other pages. |
ROBOTS | <META NAME="ROBOTS" CONTENT="ALL"> <META NAME="ROBOTS" CONTENT="INDEX,NOFOLLOW"> <META NAME="ROBOTS" CONTENT="NOINDEX,FOLLOW"> <META NAME="ROBOTS" CONTENT="NONE"> | CONTENT="ALL | NONE | NOINDEX | INDEX| NOFOLLOW | FOLLOW | NOARCHIVE" default = empty = "ALL" "NONE" = "NOINDEX, NOFOLLOW" The CONTENT field is a comma separated list: |
GOOGLEBOT | <META NAME="GOOGLEBOT" CONTENT="NOARCHIVE"> | In addition to the ROBOTS META Command above, Google supports a GOOGLEBOT command. With it, you can tell Google that you do not want the page archived, but allow other search engines to do so. If you specify this command, Google will not save the page and the page will be unavailable via its cache. See Google's FAQ. |
Thursday, May 8, 2008
Loading Multiple Versions of same Assembly
In some cases where you have programmed against say a buggy assembly and have written some workaround logic for the bug in your code. With the newer version of that assembly that bug has been fixed, but due to some constraints, you can't remove your workaround code and hence can't use the new version. There is however new functionality provided by this new version which you do want to use. Hence you would need to be able to call new methods on new version and the buggy method on the old version.
With this preamble, lets get into how to get this done. There are various permutations and combinations and I will address them. At a high level the solution is in working with one version as already programmed (typically using early binding) and with another version using reflection. Do also note that the assembly loading follows probing rules as defined in .NET SDK documentation. To keep things simple, I will keep the folder path simple and not get into such diversions.
Consider this extremely critical business logic inside of a uniquely named assembly - ClassLibrary1.dll as below. Again to keep things simple, I am not showing the various "using" statements with the code. Additionally to identify which version the method is called on, I return the version# in the string itself. I can do a dynamic query for assembly version and remove this hard coding, but the recall.. our moto is simplicity at this time and focus on loading different versions and not any other aspect, hence the hard coding.
public class Class1{public static string Method1(){return "Method 1 called on version 1.0.0.0";}}
Then there is this Winform application that invokes this static Method1 and displays the returned string in message box. To help identify if this call has happened due to early binding or reflection, I prefix the string accordingly. I build the code with version 1.0.0.0 of ClassLibrary1.dll and run the application. On invoking the method, I see a message box displaying the appropriate version#. Before we get into multiple versions, a quick discussion of what happens with private as against strong named assemblies is in order.
Weakly named library assembly (privately deployed)
If you update the version of such an assembly and redeploy it with the application, the application is able to load it without any issues. The change in just minor version to 1.1.0.0 or major version also to 2.0.0.0 doens't impact and the application works fine. Note that this is in line with basics of versioning that aren't applicable to weakly named assemblies.
Strongly named library assembly (privately deployed)
If you update the version of such an assembly and redeploy it with the applicaton, the application will give a runtime error when it tries to invoke a method of the library assembly. Due to strong naming, the version policy comes into effect and the application tries to invoked method on version against which it was complied, in this case 1.0.0.0. When it doens't finds this at runtime, it will give an error. It won't automatically start using 1.1.0.0 version. For that you need to specify the
bindingRedirect in the application configuration file.
There are multiple ways to create this configuration file. One is to do this with Visual studio itself and when the application is compiled, the config file is also complied and deployed along wih it. However if you aren't sure of the exact syntax, you can use the Microsoft .NET Framework 2.0 Configuration MMC from Administrators group. Via this you can add the specific application for configuration, then configure the specific library assembly and specify the binding policy. The configuration file generated will look something like this
<?xml version="1.0"?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="ClassLibrary1" publicKeyToken="fbc28d9ca2fc8db5" />
<publisherPolicy apply="no" />
<bindingRedirect oldVersion="1.0.0.0" newVersion="1.1.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
To reiterate, this bindingRedirect is required only for strongly named assemblies. Once this configuration setting is in place, the application is able to load the 1.1.0.0 assembly and invoke methods on it. The same logic will work for assemblies deployed in GAC.
Let us now get on with loading of different versions of the same assembly. See the sample code below on how to achieve it.
private void btn_Click(object sender, EventArgs e)
{
string str = "early bind - ";
str += ClassLibrary1.Class1.Method1();
MessageBox.Show(str);
Assembly al = Assembly.LoadFile(@"E:\Temp\old\ClassLibrary1.dll");
Type t = al.GetType("ClassLibrary1.Class1");
MethodInfo m = t.GetMethod("Method1");
str = "reflection - " + (string)m.Invoke(null, null);
MessageBox.Show(str);
}
When we run the application, we expect the early binding call to go to the newer version and the call via reflection to go to the older version, that we have specifically deployed in another sub-folder. We are using Assembly.LoadFile method so that we can specify a path.
One important aspect to note here is that the application will have to be compiled with the newer version of the assembly if the assembly is strongly named. If that isn't done, as discussed earlier, we will have to use a bindingRedirect configuration setting. Such setting works for all assembly load calls and will even redirect the assembly load call that we are doing via reflection and hence we will not be able to invoke methods on older version. By explicitly building the application with newer version, we don't need to the bindingRedirect configuration setting and our reflection call to earlier version will then work.
Loading assemblies from GAC
There is slight difference in the way the assembly is loaded via reflection if working against GAC. To successfully load different versions from GAC it is best to use the AssemblyName class and specify the FullName of the assembly you want to load. As we all know, FullName includes name, version number, culture and public key token.
private void btn_Click(object sender, EventArgs e)
{
string str = "early bind - ";
str += ClassLibrary1.Class1.Method1();
MessageBox.Show(str);
AssemblyName asm = new AssemblyName("ClassLibrary1, Version=1.1.0.0, Culture=neutral,
PublicKeyToken=fbc28d9ca2fc8db5");
Assembly al = Assembly.Load(asm);
Type t = al.GetType("ClassLibrary1.Class1");
MethodInfo m = t.GetMethod("Method1");
str = "reflection - " + (string)m.Invoke(null, null);
MessageBox.Show(str);
}
While playing around with this, I also realized that one needs not worry about references added to the project. The compiler is intelligent enough to add them to the manifest only if a call is made to any method contained in the referenced assembly. If no call is made, the reference isn't included and hence the assembly won't be loaded at run time. You can easily verify this by viewing the manifest via ILDasm utility.
HTTP Status Codes that the Web Server can return
HTTP Status Codes that the Web Server can return - Definitions
- 200 OK
- 301 Moved Permanently
- 302 Found
- 304 Not Modified
- 307 Temporary Redirect
- 400 Bad Request
- 401 Unauthorized
- 403 Forbidden
- 404 Not Found
- 410 Gone
- 500 Internal Server Error
- 501 Not Implemented
HTTP Status Code - 200 OK
The request has succeeded. The information returned with the response is dependent on the method used in the request.
HTTP Status Code - 301 Moved Permanently
The requested resource has been assigned a new permanent URI and any future references to this resource SHOULD use one of the returned URIs.
Test URI: /w3c/status-codes/301.asp
HTTP Status Code - 302 Found
The requested resource resides temporarily under a different URI. Since the redirection might be altered on occasion, the client SHOULD continue to use the Request-URI for future requests.
Test URI: /w3c/status-codes/302.asp
Admin Note: 2005-03-14 - During the past several months, many discussions have been taking place in the search engine marketing communities concerning what many refer to as pagejacking. What you are about to read concerns everyone who has a website online, this is not an isolated incident. Those who are involved with the page jacking issues may not even know that they are causing harm to those they are linking to using a 302 Found redirect. Many of the 302s are generated from exit tracking scripts.
HTTP Status Code - 304 Not Modified
If the client has performed a conditional GET request and access is allowed, but the document has not been modified, the server SHOULD respond with this status code. The 304 response MUST NOT contain a message-body, and thus is always terminated by the first empty line after the header fields.
HTTP Status Code - 307 Temporary Redirect
The requested resource resides temporarily under a different URI. Since the redirection MAY be altered on occasion, the client SHOULD continue to use the Request-URI for future requests. This response is only cacheable if indicated by a Cache-Control or Expires header field.
Test URI: /w3c/status-codes/307.asp
HTTP Status Code - 400 Bad Request
The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.
HTTP Status Code - 401 Unauthorized
The request requires user authentication. The response MUST include a WWW-Authenticate header field containing a challenge applicable to the requested resource.
HTTP Status Code - 403 Forbidden
The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated.
HTTP Status Code - 404 Not Found
The server has not found anything matching the Request-URI. No indication is given of whether the condition is temporary or permanent.
Test URI: /w3c/status-codes/404.asp
HTTP Status Code - 410 Gone
The requested resource is no longer available at the server and no forwarding address is known. This condition is expected to be considered permanent. Clients with link editing capabilities SHOULD delete references to the Request-URI after user approval.
If the server does not know, or has no facility to determine, whether or not the condition is permanent, the status code 404 Not Found SHOULD be used instead. This response is cacheable unless indicated otherwise.
Test URI: /w3c/status-codes/410.asp
HTTP Status Code - 500 Internal Server Error
The server encountered an unexpected condition which prevented it from fulfilling the request.
HTTP Status Code - 501 Not Implemented
The server does not support the functionality required to fulfill the request. This is the appropriate response when the server does not recognize the request method and is not capable of supporting it for any resource.
W3C References
Wednesday, May 7, 2008
Data Types of SQL SERVER 2005
Exact numerics
Type | From | To |
bigint | -9,223,372,036,854,775,808 | 9,223,372,036,854,775,807 |
int | -2,147,483,648 | 2,147,483,647 |
smallint | -32,768 | 32,767 |
tinyint | 0 | 255 |
bit | 0 | 1 |
decimal | -10^38 +1 | 10^38 –1 |
numeric | -10^38 +1 | 10^38 –1 |
money | -922,337,203,685,477.5808 | +922,337,203,685,477.5807 |
smallmoney | -214,748.3648 | +214,748.3647 |
numeric and decimal are Fixed precision and scale data types and are functionally equivalent.
Approximate numerics
Type | From | To |
float | -1.79E + 308 | 1.79E + 308 |
real | -3.40E + 38 | 3.40E + 38 |
datetime and smalldatetime
Type | From | To |
datetime (3.33 milliseconds accuracy) | Jan 1, 1753 | Dec 31, 9999 |
smalldatetime (1 minute accuracy) | Jan 1, 1900 | Jun 6, 2079 |
Character Strings
Type | Description |
char | Fixed-length non-Unicode character data with a maximum length of 8,000 characters. |
varchar | Variable-length non-Unicode data with a maximum of 8,000 characters. |
varchar(max) | Variable-length non-Unicode data with a maximum length of 231 characters (SQL Server 2005 only). |
text | Variable-length non-Unicode data with a maximum length of 2,147,483,647 characters. |
Unicode Character Strings
Type | Description |
nchar | Fixed-length Unicode data with a maximum length of 4,000 characters. |
nvarchar | Variable-length Unicode data with a maximum length of 4,000 characters. |
nvarchar(max) | Variable-length Unicode data with a maximum length of 230 characters (SQL Server 2005 only). |
ntext | Variable-length Unicode data with a maximum length of 1,073,741,823 characters. |
Binary Strings
Type | Description |
binary | Fixed-length binary data with a maximum length of 8,000 bytes. |
varbinary | Variable-length binary data with a maximum length of 8,000 bytes. |
varbinary(max) | Variable-length binary data with a maximum length of 231 bytes (SQL Server 2005 only). |
image | Variable-length binary data with a maximum length of 2,147,483,647 bytes. |
Other Data Types
- sql_variant: Stores values of various SQL Server-supported data types, except text, ntext, and timestamp.
- timestamp: Stores a database-wide unique number that gets updated every time a row gets updated.
- uniqueidentifier: Stores a globally unique identifier (GUID).
- xml: Stores XML data. You can store xml instances in a column or a variable (SQL Server 2005 only).
- cursor: A reference to a cursor.
- table: Stores a result set for later processing.
Source: http://www.teratrax.com/sql_guide/data_types/sql_server_data_types.html
Tuesday, May 6, 2008
All types of format strings
Strings
There really isn’t any formatting within a strong, beyond it’s alignment. Alignment works for any argument being printed in a String.Format call.
Sample | Generates |
String.Format(”->{1,10}<-”, “Hello”); | -> Hello<- |
String.Format(”->{1,-10}<-”, “Hello”); | ->Hello <- |
Numbers
Basic number formatting specifiers:
Specifier | Type | Format | Output (Passed Double 1.42) | Output (Passed Int -12400) |
c | Currency | {0:c} | $1.42 | -$12,400 |
d | Decimal (Whole number) | {0:d} | System.FormatException | -12400 |
e | Scientific | {0:e} | 1.420000e+000 | -1.240000e+004 |
f | Fixed point | {0:f} | 1.42 | -12400.00 |
g | General | {0:g} | 1.42 | -12400 |
n | Number with commas for thousands | {0:n} | 1.42 | -12,400 |
r | Round trippable | {0:r} | 1.42 | System.FormatException |
x | Hexadecimal | {0:x4} | System.FormatException | cf90 |
Custom number formatting:
Specifier | Type | Example | Output (Passed Double 1500.42) | Note |
0 | Zero placeholder | {0:00.0000} | 1500.4200 | Pads with zeroes. |
# | Digit placeholder | {0:(#).##} | (1500).42 | |
. | Decimal point | {0:0.0} | 1500.4 | |
, | Thousand separator | {0:0,0} | 1,500 | Must be between two zeroes. |
,. | Number scaling | {0:0,.} | 2 | Comma adjacent to Period scales by 1000. |
% | Percent | {0:0%} | 150042% | Multiplies by 100, adds % sign. |
e | Exponent placeholder | {0:00e+0} | 15e+2 | Many exponent formats available. |
; | Group separator | see below |
The group separator is especially useful for formatting currency values which require that negative values be enclosed in parentheses. This currency formatting example at the bottom of this document makes it obvious:
Dates
Note that date formatting is especially dependant on the system’s regional settings; the example strings here are from my local locale.
Specifier | Type | Example (Passed System.DateTime.Now) |
d | Short date | 10/12/2002 |
D | Long date | December 10, 2002 |
t | Short time | 10:11 PM |
T | Long time | 10:11:29 PM |
f | Full date & time | December 10, 2002 10:11 PM |
F | Full date & time (long) | December 10, 2002 10:11:29 PM |
g | Default date & time | 10/12/2002 10:11 PM |
G | Default date & time (long) | 10/12/2002 10:11:29 PM |
M | Month day pattern | December 10 |
r | RFC1123 date string | Tue, 10 Dec 2002 22:11:29 GMT |
s | Sortable date string | 2002-12-10T22:11:29 |
u | Universal sortable, local time | 2002-12-10 22:13:50Z |
U | Universal sortable, GMT | December 11, 2002 3:13:50 AM |
Y | Year month pattern | December, 2002 |
The ‘U’ specifier seems broken; that string certainly isn’t sortable.
Custom date formatting:
Specifier | Type | Example | Example Output |
dd | Day | {0:dd} | 10 |
ddd | Day name | {0:ddd} | Tue |
dddd | Full day name | {0:dddd} | Tuesday |
f, ff, … | Second fractions | {0:fff} | 932 |
gg, … | Era | {0:gg} | A.D. |
hh | 2 digit hour | {0:hh} | 10 |
HH | 2 digit hour, 24hr format | {0:HH} | 22 |
mm | Minute 00-59 | {0:mm} | 38 |
MM | Month 01-12 | {0:MM} | 12 |
MMM | Month abbreviation | {0:MMM} | Dec |
MMMM | Full month name | {0:MMMM} | December |
ss | Seconds 00-59 | {0:ss} | 46 |
tt | AM or PM | {0:tt} | PM |
yy | Year, 2 digits | {0:yy} | 02 |
yyyy | Year | {0:yyyy} | 2002 |
zz | Timezone offset, 2 digits | {0:zz} | -05 |
zzz | Full timezone offset | {0:zzz} | -05:00 |
: | Separator | {0:hh:mm:ss} | 10:43:20 |
/ | Separator | {0:dd/MM/yyyy} | 10/12/2002 |
Enumerations
Specifier | Type |
g | Default (Flag names if available, otherwise decimal) |
f | Flags always |
d | Integer always |
x | Eight digit hex. |
Some Useful Examples
String.Format(”{0:$#,##0.00;($#,##0.00);Zero}”, value);
This will output “$1,240.00″ if passed 1243.50. It will output the same format but in parentheses if the number is negative, and will output the string “Zero” if the number is zero.
String.Format(”{0:(###) ###-####}”, 8005551212);
This will output “(800) 555-1212″.