String Format for DateTime [C#]

 String Format for DateTime [C#]

This example shows how to format DateTime using String.Format method. All formatting can be done also using DateTime.ToString method.

Custom DateTime Formatting

There are following custom format specifiers y (year), M (month), d (day), h (hour 12), H (hour 24), m (minute), s (second), f (second fraction), F (second fraction, trailing zeroes are trimmed), t (P.M or A.M) and z (time zone).
Following examples demonstrate how are the format specifiers rewritten to the output.
[C#]
// create date time 2011-03-09 16:05:07.123
DateTime dt = new DateTime(2011, 3, 9, 16, 5, 7, 123);
 
String.Format("{0:y yy yyy yyyy}", dt);  // "8 08 008 2011"   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
 
You can use also date separator / (slash) and time sepatator : (colon). These characters will be rewritten to characters defined in the current DateTimeForma­tInfo.DateSepa­rator and DateTimeForma­tInfo.TimeSepa­rator.
[C#]
// date separator in german culture is "." (so "/" changes to ".")
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9/3/2011 16:05:07" - english (en-US)
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9.3.2011 16:05:07" - german (de-DE)
 
Here are some examples of custom date and time formatting:
[C#]
// month/day numbers without/with leading zeroes
String.Format("{0:M/d/yyyy}", dt);            // "3/9/2011"
String.Format("{0:MM/dd/yyyy}", dt);          // "03/09/2011"
 
// day/month names
String.Format("{0:ddd, MMM d, yyyy}", dt);    // "Sun, Mar 9, 2011"
String.Format("{0:dddd, MMMM d, yyyy}", dt);  // "Sunday, March 9, 2011"
 
// two/four digit year
String.Format("{0:MM/dd/yy}", dt);            // "03/09/08"
String.Format("{0:MM/dd/yyyy}", dt);          // "03/09/2011"
 

Standard DateTime Formatting

In DateTimeForma­tInfo there are defined standard patterns for the current culture. For example property ShortTimePattern is string that contains value h:mm tt for en-US culture and value HH:mm for de-DE culture.
Following table shows patterns defined in DateTimeForma­tInfo and their values for en-US culture. First column contains format specifiers for the String.Format method.
Specifier
DateTimeFormatInfo property
Pattern value (for en-US culture)
t
ShortTimePattern
h:mm tt
d
ShortDatePattern
M/d/yyyy
T
LongTimePattern
h:mm:ss tt
D
LongDatePattern
dddd, MMMM dd, yyyy
f
(combination of D and t)
dddd, MMMM dd, yyyy h:mm tt
F
FullDateTimePattern
dddd, MMMM dd, yyyy h:mm:ss tt
g
(combination of d and t)
M/d/yyyy h:mm tt
G
(combination of d and T)
M/d/yyyy h:mm:ss tt
m, M
MonthDayPattern
MMMM dd
y, Y
YearMonthPattern
MMMM, yyyy
r, R
RFC1123Pattern
ddd, dd MMM yyyy HH':'mm':'ss 'GMT' (*)
s
SortableDateTi­mePattern
yyyy'-'MM'-'dd'T'HH':'mm':'ss (*)
u
UniversalSorta­bleDateTimePat­tern
yyyy'-'MM'-'dd HH':'mm':'ss'Z' (*)


(*) = culture independent
Following examples show usage of standard format specifiers in String.Format method and the resulting output.
[C#]
String.Format("{0:t}", dt);  // "4:05 PM"                         ShortTime
String.Format("{0:d}", dt);  // "3/9/2011"                        ShortDate
String.Format("{0:T}", dt);  // "4:05:07 PM"                      LongTime
String.Format("{0:D}", dt);  // "Sunday, March 09, 2011"          LongDate
String.Format("{0:f}", dt);  // "Sunday, March 09, 2011 4:05 PM"  LongDate+ShortTime
String.Format("{0:F}", dt);  // "Sunday, March 09, 2011 4:05:07 PM" FullDateTime
String.Format("{0:g}", dt);  // "3/9/2011 4:05 PM"                ShortDate+ShortTime
String.Format("{0:G}", dt);  // "3/9/2011 4:05:07 PM"             ShortDate+LongTime
String.Format("{0:m}", dt);  // "March 09"                        MonthDay
String.Format("{0:y}", dt);  // "March, 2011"                     YearMonth
String.Format("{0:r}", dt);  // "Sun, 09 Mar 2011 16:05:07 GMT"   RFC1123
String.Format("{0:s}", dt);  // "2011-03-09T16:05:07"             SortableDateTime
String.Format("{0:u}", dt);  // "2011-03-09 16:05:07Z"            UniversalSortableDateTime
 
Special thanks for this blog to C# Examples  

0 comments:

.net framework 4.5 features

New Features for Web Development in Visual Studio 11 Beta

Here are a few web development tools features included in the Visual Studio 11 Beta compared to VS2010.  Many of them have already been mentioned in our Visual Studio 11 Developer Preview blogs.
  • Visual Studio 11 Express Beta for Web is now available.  It includes support for TFS and unit testing tools.   It’s downloadable via Web PI.
  • ASP.NET MVC 4 Beta and ASP.NET MVC 3 are included in the Visual Studio 11 Beta
  • New MVC 4 templates and Web Forms templates are provided with features such as HTML5 support and ASP.NET 4.5 bundling and minification.
  • Page Inspector allows you to see what elements in the source files (including server-side code) have produced the HTML markup that is rendered to the browser. Page Inspector also lets you modify CSS properties and DOM element attributes and see the changes reflected immediately in the browser.
  • The JavaScript editor is rewritten and is now based on IE10's JavaScript engine. Many new features are added to support JavaScript as a first class citizen programming language, such as Go to Definition, outlining, brace matching, etc.  In Beta, we enhanced reference settings, extensibility, performance and reliability.
  • New CSS editor functionalities include a new formatter, validator, snippets, color picker, comment support, hierarchical indentation, and vendor specific IntelliSense. In Beta, we enhanced the color picker and made CSS editor features friendlier.
  • New HTML editor functionalities include source view smart tasks, better auto indentation, live updating of matching open/close tags, server side event handler generation, Extract to User Control and more.
  • IIS Express is now the default website and web application host instead of ASP.NET Development Server (i.e. Cassini). With Visual Studio 11 Beta Ultimate, you can also use profiling with IIS Express.
  • SQL Server 2012 Express LocalDB is the default database for Visual Studio 11. LocalDB is created specifically for developers. It is very easy to install and requires no management, yet it offers the same T-SQL language, programming surface and client-side providers as the regular SQL Server Express. In effect the developers that target SQL Server no longer have to install and manage a full instance of SQL Server Express on their laptops and other development machines.
  • Publishing for Web Application Projects (WAP) has been updated. Publishing profiles are now designed for team scenarios and are stored into a separate folder, allowing proper version control and usage from MSBuild/Team Build. You can configure your WAP to be precompiled/merged before publishing on the Package/Publish Web tab under the Project Properties.
  • Project System enhancements include having a list of common and most recently used items in the Solution Explorer add menu, and the ability to set the browser for viewing and debugging via toolbar.
further details available @ http://blogs.msdn.com/

0 comments:

Delete All Files in C#


This examples shows how to delete all files (*.*) from a folder in C#.
First, you need to get the list of file names from the specified directory (using static method Directory.Get­Files. Then delete all files from the list.
Delete all files in C#

[C#]
using System.IO;

string[] filePaths = Directory.GetFiles(@"c:\MyDir\");
foreach (string filePath in filePaths)
  File.Delete(filePath);

Delete all files (one-row example)
To delete all files using one code line, you can use Array.ForEach with combination of anonymous method.
[C#]
Array.ForEach(Directory.GetFiles(@"c:\MyDir\"),
              delegate(string path) { File.Delete(path); });

Get Application Directory [C#]
Following examples show how to get application or assembly folder.
Directory of windows forms application (.exe) in C#

Class Application in System.Window­s.Forms namespace has static property ExecutablePath. It contains path of the .exe file (that started the application) including the executable file name. To get only the folder part of the path, use static method GetDirectoryName of Path class.
[C#]
using System.IO;
using System.Windows.Forms;

string appPath = Path.GetDirectoryName(Application.ExecutablePath);
 
Directory of any loaded assembly (.exe or .dll) in C#

First get reference to the assembly. You can use static methods of Assembly class. To get assembly of currently executing code use method Assembly.GetE­xecutingAssem­bly. To get assembly in which the specified class is defined use method Assembly.GetAs­sembly (with the specified class type as a paramater). The assembly must be loaded. Next get assembly file path using Assembly.CodeBase property.
[C#]
using System.IO;
using System.Reflection;

string path = Path.GetDirectoryName(
                     Assembly.GetAssembly(typeof(MyClass)).CodeBase);

File Attributes [C#]

This example shows how to get or set file attributes, how to add attributes and how to remove attributes from current ones.
Get file attributes in C#

To get file attributes use static method File.GetAttri­butes. The method returns FileAttributes which is a bitwise combination of file attribute flags.
[C#]
string filePath = @"c:\TEXT.txt";
 
// get file attributes
FileAttributes fileAttributes = File.GetAttributes(filePath);
 
Set file attributes in C#

To set file attributes use static method File.SetAttri­butes. Parameter of the method is a bitwise combination of FileAttributes enumeration.
[C#]
// clear all file attributes
File.SetAttributes(filePath, FileAttributes.Normal);

// set just only archive and read only attributes (no other attribute will set)
File.SetAttributes(filePath, FileAttributes.Archive |
                             FileAttributes.ReadOnly);

Check whether a file has any attribute in C#

To check whether a file has any attribute (readonly, hidden) get current file attributes first and use bitwise AND (&) operator with a mask of specific attributes.
[C#]
// check whether a file is read only
bool isReadOnly = ((File.GetAttributes(filePath) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly);
 
// check whether a file is hidden
bool isHidden = ((File.GetAttributes(filePath) & FileAttributes.Hidden) == FileAttributes.Hidden);

// check whether a file has archive attribute
bool isArchive = ((File.GetAttributes(filePath) & FileAttributes.Archive) == FileAttributes.Archive);

// check whether a file is system file
bool isSystem = ((File.GetAttributes(filePath) & FileAttributes.System) == FileAttributes.System);

Delete/clear file attributes from current ones in C#

To delete file attributes from the existing ones get the current file attributes first and use AND (&) operator with a mask (bitwise complement of desired attributes combination).
[C#]

// delete/clear hidden attribute
File.SetAttributes(filePath, File.GetAttributes(filePath) & ~FileAttributes.Hidden);

// delete/clear archive and read only attributes
File.SetAttributes(filePath, File.GetAttributes(filePath) & ~(FileAttributes.Archive |
                                                              FileAttributes.ReadOnly));

Get File Time [C#]

This example shows how to get file time informations, when any file was created, last modified or accessed. To get file datetime info you can use either static methods of File class or instance methods of FileInfo class.
Get file times using File class in C#
Use File class when you want to get just one specific time, for example if you are only interested in a file last modification time. To do this use static method File.GetLastWri­teTime with file path as a parameter. File class also provides static methods to get file creation time or file last access time. You can also get this times in UTC, e.g. to get file last write time in UTC use File.GetLastWri­teTimeUtc.
[C#]
// local times
DateTime creationTime = File.GetCreationTime(@"c:\TEXT.txt");
DateTime lastWriteTime = File.GetLastWriteTime(@"c:\ TEXT.txt");
DateTime lastAccessTime = File.GetLastAccessTime(@"c:\ TEXT.txt");

// UTC times
DateTime creationTimeUtc = File.GetCreationTimeUtc(@"c:\ TEXT.txt");
DateTime lastWriteTimeUtc = File.GetLastWriteTimeUtc(@"c:\ TEXT.txt");
DateTime lastAccessTimeUtc = File.GetLastAccessTimeUtc(@"c:\ TEXT.txt");

// write file last modification time (local / UTC)
Console.WriteLine(lastWriteTime);     // 9/30/2011 2:16:04 PM
Console.WriteLine(lastWriteTimeUtc);  // 9/30/2011 6:16:04 PM

Get file times using FileInfo class in C#

Use instance of FileInfo class when you want to get more than one file time or any other informations about the file (like file attributes). Advantage is that you will get all needed informations just in one disk access. See following example.
[C#]
FileInfo fileInfo = new FileInfo(@"c:\file.txt");

// local times
DateTime creationTime = fileInfo.CreationTime;
DateTime lastWriteTime = fileInfo.LastWriteTime;
DateTime lastAccessTime = fileInfo.LastAccessTime;

// UTC times
DateTime creationTimeUtc = fileInfo.CreationTimeUtc;
DateTime lastWriteTimeUtc = fileInfo.LastWriteTimeUtc;
DateTime lastAccessTimeUtc = fileInfo.LastAccessTimeUtc;
 
// write file last modification time (local / UTC)
Console.WriteLine(lastWriteTime);     // 9/30/2011 2:16:04 PM
Console.WriteLine(lastWriteTimeUtc);  // 9/30/2011 6:16:04 PM

Open File With Associated Application [C#]

This example demonstrates how to open file with an associated program. It shows, how to open text document in notepad, how to open image in a default viewer or how to open url address in a default web browser.
Applications are launched using Process.Start method. The file path or url is passed as a parameter.
[C#]
// open text file in notepad (or another default text editor)
System.Diagnostics.Process.Start(@"c:\textfile.txt");
[C#]
// open image in default viewer
System.Diagnostics.Process.Start(@"c:\image.jpg");
[C#]
// open url in default web browser
System.Diagnostics.Process.Start("http://www.csharp-examples.net");
[C#]
// open PDF file
System.Diagnostics.Process.Start(@"c:\document.pdf");

Similarly you can open Word document or any other file from your .NET application.



0 comments:

How to create dynamic datatable in asp.net or C#

 Hi Friends ,
Here i am going to show how to create dynamic datatable . we need to create datatable at run time for this we use System.Data namespace because DataTable is Derived from this name space.
DataTable is Derived from




//Create a object of Datatable
        DataTable dynamicDataTable = new DataTable();

        //DataRow
        DataRow dynamicRow;
        //DataColumn for Name and Address
        DataColumn NameColumn = new DataColumn("Name", typeof(string));
        DataColumn AddColumn = new DataColumn("Address", typeof(string));

        //add Column to Datatable
        dynamicDataTable.Columns.Add(NameColumn);
        dynamicDataTable.Columns.Add(AddColumn);
        //loop for 5 item in DataTable
        for (int i = 0; i < 5; i++)
        {
            dynamicRow = dynamicDataTable.NewRow();
            //Add Rows to dymanicTable
            dynamicDataTable.Rows.Add(dynamicRow);
            //Assign Column value
            dynamicDataTable.Rows[i][NameColumn] = Guid.NewGuid().ToString();
            dynamicDataTable.Rows[i][AddColumn] = = Guid.NewGuid().ToString();
        }

        //Bind DynamicDataTable into a GridView
        GridViewDataShow.DataSource = dynamicDataTable;
       GridViewDataShow.DataBind();

Hope this code will help you
Regards,
Rajesh C#

0 comments:

Closing Child Popup Windows When Parent Window is Closed

Hi friends .
  Few days ago , i faced a problem with my project , that i need to close all the child popups when parents window is closed . some time we missed this check but we have to follow this in our common practices.
Here I am placing a code regarding to my issue . hope this will help you .

for example ,
 
Here is the code to open a new window:
<script type="text/javascript">
        var arrPopups = new Array();// create an array of popup window object
//This is a java script function used for open a popup window in which we maintain a array with all the child window names .
     function openPopUp(pageUrl,pageName) {
var popUpObj = window.open(pageUrl, pageName,                                                            "width=600px,height=500px,resizable,toolbar=false, scrollbars");
              arrPopups .push(popUpObj );
        }
//Here is the function for closing all the child windows which is maintain by array .
  function closePopUps() {
            if (arrPopups.length == 0) return;

            for (i = 0; i < popups.length; i++) {
                arrPopups [i].close();
            }
        }
    </script>

finally call this function on body onunload
like this,
<body onunload="closePopUps()">

If you refresh the parent  window through the child window from server side use this code

 Page.ClientScript.RegisterStartupScript(this.GetType(), "close", "<script language=javascript>window.opener.document.forms[0].submit();self.close();</script>");

Hope this will helps you..

Regards ,
Rajesh 

0 comments:

disable double Click on Web Page

Hi Friend ,.
    Some time we face a problem like when we click on the server side button twice or more time ,it call a button event more then one time for single calling .some time it makes problem in our logic .so we need a solution code which hold the page till the server respond the single request .
Here i am placing a code which is useful in this case.

<script type="text/javascript">
        function pageLoad(sender, args) {
            var rm = Sys.WebForms.PageRequestManager.getInstance();
            rm.add_initializeRequest(initializeRequest);
            rm.add_endRequest(endRequest);
        }
        function initializeRequest(sender, args) {
            //Disable button to prevent double submit
            var btn = $get(args._postBackElement.id);
            if (btn) {
                btn.disabled = true;
                if (btn.className == 'button')
                    btn.className = 'buttonDisabled';
            }
        }
        function endRequest(sender, args) {
            //Re-enable button

            var btn = $get(sender._postBackSettings.sourceElement.id);
            if (btn) {
                btn.disabled = false;
                if (btn.className == 'buttonDisabled')
                    btn.className = 'button';
            }
        }
</script>
Hope this will help you

Rajesh

0 comments: