Monday, October 4, 2010

DateTime and Number Format in C#

int intNum = 13; 
String.Format("{0:d4}", intNum);          // "0013"
intNum.ToString("D4");                    // "0013"

Decimal
// fixed two decimal part

String.Format("{0:0.00}", 123.4567);      // "123.46"
String.Format("{0:0.00}", 123.4);         // "123.40"

String.Format("{0:0.00}", 123.0);         // "123.00"
// maximum two decimal part
String.Format("{0:0.##}", 123.4567);      // "123.46"
String.Format("{0:0.##}", 123.4);         // "123.4"

String.Format("{0:0.##}", 123.0);         // "123"
// at least two digits at integer part
String.Format("{0:00.0}", 123.4567);      // "123.5"
String.Format("{0:00.0}", 1.4567);        // "01.5"

String.Format("{0:00.0}", -1.4456);       // "-03.4"
// Align numbers with spaces
// To align numbers to the left use negative number of spaces
String.Format("{0,10:0.0}", 123.4567);    // "     123.5"
String.Format("{0,-10:0.0}", 123.4567);   // "123.5     "
String.Format("{0,10:0.0}", -123.4567);   // "    -123.5"

String.Format("{0,-10:0.0}", -123.4567);  // "-123.5    "

Currency
123.456 ("C3", en-US) -> ($123.456)
-123.456 ("C3", fr-FR) -> -123,456 €
-123.456 ("C3", ja-JP) -> -¥123.456

Decimal

1234 ("D") -> 1234
-1234 ("D6") -> -001234

Fixed-point

1234 ("F1", en-US) -> 1234.0
1234 ("F1", en-US) -> 1234.0


General
-123.456 ("G", en-US) -> -123.456
-1.234567890e-25 ("G", sv-SE) -> -1,23456789E-25


Number
1234.567 ("N", en-US) -> 1,234.57
1234 ("N", en-US) -> 1,234.0


Percent
1 ("P", en-US) -> 100.00 %
-0.39678 ("P1", en-US) -> -39.7 %


Round-trip
123456789.12345678 ("R") -> 123456789.12345678
-1234567890.12345678 ("R") -> -1234567890.1234567


Hexadecimal
255 ("X") -> FF
-1 ("x") -> ff
255 ("x4") -> 00ff
-1 ("X4") -> 00FF


 
 
DateTime.ToString() Patterns
 
ddd, dd MMM yyyy HH':'mm':'ss 'GMT'      Tue, 22 Aug 2006 06:30:07 GM
dddd, dd MMMM yyyy HH:mm:ss              Tuesday, 22 August 2006 06:30:07

yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK   2006-08-22T06:30:07.7199222-04:00 


// create date time 2008-03-09 16:05:07.123
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);
String.Format("{0:y yy yyy yyyy}", dt);  // "8 08 008 2008"   year
String.Format("{0:M MM MMM MMMM}", dt);  // "3 03 Mar March"  month
String.Format("{0:d dd ddd dddd}", dt);  // "9 09 Sun Sunday" day
String.Format("{0:h hh H HH}",     dt);  // "4 04 16 16"      hour 12/24
String.Format("{0:m mm}",          dt);  // "5 05"            minute
String.Format("{0:s ss}",          dt);  // "7 07"            second
String.Format("{0:f ff fff ffff}", dt);  // "1 12 123 1230"   sec.fraction
String.Format("{0:F FF FFF FFFF}", dt);  // "1 12 123 123"    without zeroes
String.Format("{0:t tt}",          dt);  // "P PM"            A.M. or P.M.
String.Format("{0:z zz zzz}",      dt);  // "-6 -06 -06:00"   time zone
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9/3/2008 16:05:07" - english (en-US)
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9.3.2008 16:05:07" - german (de-DE)

// month/day numbers without/with leading zeroes
String.Format("{0:M/d/yyyy}", dt);            // "3/9/2008"
String.Format("{0:MM/dd/yyyy}", dt);          // "03/09/2008"

// day/month names
String.Format("{0:ddd, MMM d, yyyy}", dt);    // "Sun, Mar 9, 2008"
String.Format("{0:dddd, MMMM d, yyyy}", dt);  // "Sunday, March 9, 2008"

// two/four digit year
String.Format("{0:MM/dd/yy}", dt);            // "03/09/08"
String.Format("{0:MM/dd/yyyy}", dt);          // "03/09/2008" 
 
String.Format("{0:t}", dt);  // "4:05 PM"                         ShortTime
String.Format("{0:d}", dt);  // "3/9/2008"                        ShortDate
String.Format("{0:T}", dt);  // "4:05:07 PM"                      LongTime
String.Format("{0:D}", dt);  // "Sunday, March 09, 2008"          LongDate
String.Format("{0:f}", dt);  // "Sunday, March 09, 2008 4:05 PM"  LongDate+ShortTime
String.Format("{0:F}", dt);  // "Sunday, March 09, 2008 4:05:07 PM" FullDateTime
String.Format("{0:g}", dt);  // "3/9/2008 4:05 PM"                ShortDate+ShortTime
String.Format("{0:G}", dt);  // "3/9/2008 4:05:07 PM"             ShortDate+LongTime
String.Format("{0:m}", dt);  // "March 09"                        MonthDay
String.Format("{0:y}", dt);  // "March, 2008"                     YearMonth
String.Format("{0:r}", dt);  // "Sun, 09 Mar 2008 16:05:07 GMT"   RFC1123
String.Format("{0:s}", dt);  // "2008-03-09T16:05:07"             SortableDateTime
String.Format("{0:u}", dt);  // "2008-03-09 16:05:07Z"            UniversalSortableDateTime 


d Represents the day of the month as a number from 1 through 31. A single-digit day is formatted without a leading zero
dd Represents the day of the month as a number from 01 through 31. A single-digit day is formatted with a leading zero
ddd Represents the abbreviated name of the day of the week (Mon, Tues, Wed etc)
dddd Represents the full name of the day of the week (Monday, Tuesday etc)
h 12-hour clock hour (e.g. 7)
hh 12-hour clock, with a leading 0 (e.g. 07)
H 24-hour clock hour (e.g. 19)
HH 24-hour clock hour, with a leading 0 (e.g. 19)
m Minutes
mm Minutes with a leading zero
M Month number
MM Month number with leading zero
MMM Abbreviated Month Name (e.g. Dec)
MMMM Full month name (e.g. December)
s Seconds
ss Seconds with leading zero
t Abbreviated AM / PM (e.g. A or P)
tt AM / PM (e.g. AM or PM
y Year, no leading zero (e.g. 2001 would be 1)
yy Year, leadin zero (e.g. 2001 would be 01)
yyy Year, (e.g. 2001 would be 2001)
yyyy Year, (e.g. 2001 would be 2001)
K Represents the time zone information of a date and time value (e.g. +05:00)
z With DateTime values, represents the signed offset of the local operating system's time zone from Coordinated Universal Time (UTC), measured in hours. (e.g. +6)
zz As z but with leadin zero (e.g. +06)
zzz With DateTime values, represents the signed offset of the local operating system's time zone from UTC, measured in hours and minutes. (e.g. +06:00)
f Represents the most significant digit of the seconds fraction; that is, it represents the tenths of a second in a date and time value.
ff Represents the two most significant digits of the seconds fraction; that is, it represents the hundredths of a second in a date and time value.
fff Represents the three most significant digits of the seconds fraction; that is, it represents the milliseconds in a date and time value.
ffff Represents the four most significant digits of the seconds fraction; that is, it represents the ten thousandths of a second in a date and time value. While it is possible to display the ten thousandths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On Windows NT 3.5 and later, and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds.
fffff Represents the five most significant digits of the seconds fraction; that is, it represents the hundred thousandths of a second in a date and time value. While it is possible to display the hundred thousandths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On Windows NT 3.5 and later, and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds.
ffffff Represents the six most significant digits of the seconds fraction; that is, it represents the millionths of a second in a date and time value. While it is possible to display the millionths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On Windows NT 3.5 and later, and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds.
fffffff Represents the seven most significant digits of the seconds fraction; that is, it represents the ten millionths of a second in a date and time value. While it is possible to display the ten millionths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On Windows NT 3.5 and later, and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds.
F Represents the most significant digit of the seconds fraction; that is, it represents the tenths of a second in a date and time value. Nothing is displayed if the digit is zero.
: Represents the time separator defined in the current DateTimeFormatInfo..::.TimeSeparator property. This separator is used to differentiate hours, minutes, and seconds.
/ Represents the date separator defined in the current DateTimeFormatInfo..::.DateSeparator property. This separator is used to differentiate years, months, and days.
" Represents a quoted string (quotation mark). Displays the literal value of any string between two quotation marks ("). Your application should precede each quotation mark with an escape character (\).
' Represents a quoted string (apostrophe). Displays the literal value of any string between two apostrophe (') characters.
%c Represents the result associated with a c custom format specifier, when the custom date and time format string consists solely of that custom format specifier. That is, to use the d, f, F, h, m, s, t, y, z, H, or M custom format specifier by itself, the application should specify %d, %f, %F, %h, %m, %s, %t, %y, %z, %H, or %M. For more information about using a single format specifier, see Using Single Custom Format Specifiers.
 

Related Link
http://www.csharp-examples.net/string-format-double/

Tuesday, August 17, 2010

How to remove GRUB and restore the Windows bootloader

1. Boot computer from bootable Windows XP CD
2. when the first screen stop and prompt options, press R to repair an existing installation.
3. In the console type commands as below:
    C:\> FIXBOOT C:
    C:\> FIXMBR
    C:\> BOOTCFG /rebuild
         Enter Load Identifier: Windows Server 2003, Enterprise
         Enter OS Load Options:  /fastdetect
4. reboot done! 

Related
http://support.microsoft.com/kb/317521/en-us?fr=1

Monday, July 19, 2010

How to resotre MS SQL backup and fixed user incorect associate to login

When you restore a DB to a new create Database or Users has changed after backup the database,  you may notice that user name in the restored database not correctly associate to user in logins.
the SQL Command as below will restore database name call myDb and fix the User user1 associate to user name in Logins.


-- Full backup database , WITH FORMAT says overwrite the bak file if it is already existed.
BACKUP DATABASE myDb
    TO DISK = 'd:\backup\myDb.bak'
    WITH FORMAT;
GO

-- Restore Sample 1
USE master
RESTORE DATABASE myDb
FROM DISK = 'd:\myDb.bak'
WITH REPLACE
GO


-- Restore Sample 2
-- 1. List File Set position in backup file
RESTORE HEADERONLY
FROM DISK = 'd:\myDb.bak'
GO
-- 2. List Logical Name from particular file set position in backup file
RESTORE FILELISTONLY
FROM DISK = 'd:\myDb.bak'
WITH FILE = 2
GO
-- 3. Restore data from particular file set position and move backup data to specify location
-- 'MyDB' and 'MyDB_log' is Logical name from step 2.
--  MyDB.mdf is data store, MyDB_log.ldf is DB log file
RESTORE DATABASE myDb
FROM DISK = 'd:\myDb.bak'
WITH MOVE 'MyDB' TO 'd:\DB\MyDB.mdf'
,MOVE 'MyDB_log' TO 'D:\DB\MyDB_log.ldf'
,FILE = 2, REPLACE


--
USE myDb

-- the following statement say if login 'test_user' not exist just create it with password.
IF NOT EXISTS(SELECT name FROM master.dbo.syslogins WHERE name = 'test_user')
BEGIN
    CREATE LOGIN test_user WITH PASSWORD = 'Password123', CHECK_POLICY = OFF
END
GO

-- Create new user for login
-- for sql server 2005/2008
USE myDb
CREATE USER user1 FOR LOGIN test_user WITH DEFAULT_SCHEMA = dbo

-- for SQL Server 2000
EXEC sp_adduser 'login1', 'user1'

-----------------------------------------------------------------
-- the Syntax of sp_adduser
sp_adduser [ @loginame = ] 'login' 
    [ , [ @name_in_db = ] 'user' ] 
    [ , [ @grpname = ] 'group' ]

-- Set default schema to user
USE myDb
ALTER USER user1 WITH DEFAULT_SCHEMA = dbo;

-- Add db_owner role to the user
EXEC sp_addrolemember 'db_owner', 'user1'


-- the 'update_one' is the parameter value of @action in sp_change_users_login
-- the 'test_user' is user name in myDb
-- the 'user1' is login name
-- the third parameter password no require if you specific the first param @action='update_one'
EXEC sp_change_users_login 'update_one', 'test_user', 'user1';

------------------------------------------------------------------- the Syntax of sp_change_users_login
sp_change_users_login [ @Action= ] 'action' 
    [ , [ @UserNamePattern= ] 'user' ] 
    [ , [ @LoginName= ] 'login' ] 
    [ , [ @Password= ] 'password' ]
[;]
 
 



-- If you got a error while restore db: Exclusive access could not be obtained because the database is in use.
-- find out which user connecting the db and kill the spid
-- Show all the users connection include spid.
EXEC sp_who
-- Kill the users who is connecting the db, 52 is spid.
KILL 52



-- Change DB Logic Name
-- display current using DB logic name
select * from sysfiles
-- change logic name
ALTER DATABASE MyDB
MODIFY FILE (NAME =  'MyDB_log' , NEWNAME = 'MyDB2_log');




See MSDN
 
  

Sunday, July 11, 2010

How To call a Web service in javascript

By Using jQuery

    var params = "{'id':'123','name':'josh'}";

    $(document).ready(function()
    {
        $.ajax({
            type: "POST",
            url: "/WebService/aspnet_service.asmx/getUserInfoFunc",
            data: params,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg)
            {
                alert(msg.d);
            }
            ,
            error: function(result)
            {
                alert(result.status + ":" + result.statusText);
            }
        });
    });

Microsoft Ajax

<script type="text/javascript" src="/script/MicrosoftAjax.js"></script>





<script type="text/javascript">

    function onclickBtn1()
    {
        var wRequest = new Sys.Net.WebRequest();
        wRequest.set_url("/test.aspx?id=3");
        wRequest.add_completed(
            function(executor, eventArgs)
            {
                alert(executor.get_responseData());
             });
        wRequest.invoke();
    }
</script>

How to request URL with login credential in C#

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Credentials = new NetworkCredential(user, password);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

Saturday, July 10, 2010

How To Create XML Object in C#




XmlDocument xDoc = new XmlDocument();
XmlElement root = null;
XmlElement node = null;
XmlAttribute att = null;

// Create XML declaration
XmlNode declaration = xDoc.CreateNode(XmlNodeType.XmlDeclaration, null, null);
declaration.Value = "version=\"1.0\" encoding=\"utf-8\"";
xDoc.AppendChild(declaration);


// Create Child Element with two attributes id and name
node = xDoc.CreateElement("node");

att = xDoc.CreateAttribute("id");
att.Value = "100";
node.Attributes.Append(att);

att = xDoc.CreateAttribute("name");
att.Value = "data_100";
node.Attributes.Append(att);

// Create data content which encapesole in <![CDATA[[ ]]> section.
XmlCDataSection CData = xDoc.CreateCDataSection("This text contains some xml escape characters & < > ' \" which encapsolete in CDATA.");

node.AppendChild(CData);

// Create root Element
root = xDoc.CreateElement("root");


root.AppendChild(node);

xDoc.AppendChild(root);



// Get XML string from XmlDocument
string xmlStr = xDoc.outerXml;

the result of xmlStr will be like this:
<?xml version="1.0" encoding="utf-8"?>
<root>
    <node id="100" name="data_100" >
        <![CDATA [This text contains some xml escape characters & < > ' " which encapsolete in CDATA.]]>
    </node>
</root>