.NET Formatting Strings

formatting strings

Example Output
String.Format(“–{0,10}–“, “test”); —      test–
String.Format(“–{0,-10}–“, “test”); –test      —

formatting numbers

Specifier Type Format Output

(double 1.2345)

Output

(int -12345)

c Currency {0:c} $1.23 -$12,345.00
d Decimal (whole number) {0:d} System.FormatException -12345
e Exponent/scientific {0:e} 1.234500e+000 -1.234500e+004
f Fixed point {0:f} 1.23 -12345.00
g General {0:g} 1.2345 -12345
n Number {0:n} 1.23 -12,345.00
r Round trippable {0:r} 1.23 System.FormatException
x Hexadecimal {0:x4} System.FormatException ffffcfc7

custom number formatting

Specifier Type Format Output

(double 1234.56)

0 Zero placeholder {0:00.000} 1234.560
# Digit placeholder {0:#.##} 1234.56
. Decimal point placeholder {0:0.0} 1234.6
, Thousand separator {0:0,0} 1,235
% Percentage {0:0%} 123456%

Group separator

String.Format(“{0:$#,##0.00;($#,##0.00);Nothing}”, value);

This will output “$1,240.00” if passed 1243.56.  It will output the same format bracketed if the value is negative “($1,240.00)”, and will output the string “Nothing” if the number is zero.

date formatting

Specifier Type Output

(June 8, 1970 12:30:59)

d Short date 08/06/1970
D Long date 08 June 1970
t Short time 12:30
T Long time 12:30:59
f Full date and time 08 June 1970 12:30
F Full date and time (long) 08 June 1970 12:30:59
g Default date and time 08/06/1970 12:30
G Default date and time (long) 08/06/1970 12:30:59
M Day/Month 8 June
r RFC1123 date string Mon, 08 June 1970 12:30:59 GMT
s Sortable date/time 1970-06-08T12:30:59
u Universal time, local timezone 1970-06-08 12:30:59Z
Y Month/Year June 1970

custom date formatting

Specifier Type Output

(June 8, 1970 12:30:59)

dd Day 08
ddd Short day name Mon
dddd Full day name Monday
hh 2 digit hour 12
HH 2 digit hour (24 hour) 12
mm 2 digit minute 30
MM Month 06
MMM Short month name Jun
MMMM Month name June
ss Seconds 59
tt AM/PM PM
yy 2 digit year 70
yyyy 4 digit year 1970
: Separator, e.g. {0:hh:mm:ss} 12:30:59
/ Separator, e.g. {0:dd/MM/yyyy} 08/06/1970
Advertisements

DateTime to simple recognized string (Facebook time format)

// DateAndTime Helper
public static string GetDateAndTimeFormNow(this HtmlHelper helper, string datetime)
{
    string value = string.Empty;

    if (!string.IsNullOrEmpty(datetime))
    {
        DateTime d1 = DateTime.Now;
        DateTime d2 = Convert.ToDateTime(datetime);

        TimeSpan t = d1 - d2;

        if (t.TotalDays >= 2)
            value = Math.Round(t.TotalDays, 0).ToString() + " days ago.";
        else if (t.TotalDays >= 1)
            value = "a day ago.";
        else if (t.TotalHours >= 2)
            value = Math.Round(t.TotalHours, 0).ToString() + " hours ago.";
        else if (t.TotalHours >= 1)
            value = "an hour ago.";
        else if (t.TotalMinutes >= 2)
            value = Math.Round(t.TotalMinutes, 0).ToString() + " minutes ago.";
        else
            value = "a minute ago.";
    }

    return value;
}

ASP.NET MVC – File sharing and downloading from another server

Conditions:
We have 2 servers, Server A and B. Admin site is loaded on Server A and we need to share files which are uploaded from the admin site.
Classic ASP does not get a file from other or network drive. So, I decided to write files to Server A and B seperate.
Then classic ASP can load the file.

Preperation:
1. Create folders on both servers
2. Create local users on both servers and the users’ name and password must be same. Windows systems only check user name and password without server or domain name. In other words, there are users which are same id and password on different computers, and all users can access to other computers without credential. It is automatically passed through.
3. Grant read/write permissions to the users.

Implementation:
1. Configuration
a. add below to web.config

<identity impersonate=”true” userName=”USERID” password=”PASSWORD” />

<httpRuntime executionTimeout=”240″ maxRequestLength=”20480″ />
2. Write
3. Read

Issue: I’m on the admin site and trying to download a file which are placed on the other server. (local files are working fine.)


Event Type: Error
Event Source: ASP.NET 2.0.50727.0
Event Category: None
Event ID: 1194
Date: 8/24/2011
Time: 4:48:00 PM
User: N/A
Computer: _servername
Description:
TransmitFile failed. File Name: \\_path\_filename.pdf, Impersonation Enabled: 0, Token Valid: 1, HRESULT: 0x8007052e

My code looks like below


public ActionResult Download(string category, int id)
{
    DataRepository _repository = new DataRepository();
    Item item = _repository.getItem(id);

    string _filename = item.fileName;
    string _filepath;
    if (category.Equals("A"))
        _filepath = ConfigurationSettings.AppSettings["ServerA"];
    else
        _filepath = ConfigurationSettings.AppSettings["ServerB"];
    string _fullpath = Path.Combine(_filepath, _filename);

    FileInfo file = new FileInfo(_fullpath);

    Response.Clear();
    if (file.Exists)
    {
        return File(_filepath, "octet/stream", HttpUtility.UrlEncode(_filename, System.Text.Encoding.UTF8));
    }
    else
    {
        Response.Write("File not found.");
        Response.End();
        return null;
    }
}

Solution:
It needs to have Response.End();.
So, I decided to add more codes as I’ve done before. Then, it’s resolved.


public ActionResult Download(string category, int id)
{
    DataRepository _repository = new DataRepository();
    Item item = _repository.getItem(id);

    string _filename = item.fileName;
    string _filepath;
    if (category.Equals("A"))
        _filepath = ConfigurationSettings.AppSettings["ServerA"];
    else
        _filepath = ConfigurationSettings.AppSettings["ServerB"];
    string _fullpath = Path.Combine(_filepath, _filename);

    FileInfo file = new FileInfo(_fullpath);

    Response.Clear();
    if (file.Exists)
    {
        //return File(_filepath, "octet/stream", HttpUtility.UrlEncode(_filename, System.Text.Encoding.UTF8));
        fileDownload(_filename, _filepath);
    }
    else
        Response.Write("File not found.");
    Response.End();
    return null;
}

private void fileDownload(string _filename, string _filepath)
{
    bool success = ResponseFile(_filename, _filepath, 1024000);
    if (!success)
        Response.Write("Downloading error.");
}

private void ResponseFile(string _filename, string _filepath, long _speed)
{
    try
    {
        FileStream fs = new FileStream(_filepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
        BinaryReader br = new BinaryReader(fs);
        
        try
        {
            Response.AddHeader("Accept-Ranges", "bytes");
            Response.Buffer = false;
            long fileLength = fs.Length;
            long startBytes = 0;
            
            int pack = 10240;       // 10K bytes
            int sleep = (int)Math.Floor((double)(1000 * pack / _speed)) + 1;
            if (Request.Headers["Range"] != null)
            {
                Response.StatusCode = 206;
                string[] range = Request.Headers["Range"].Split(new char[] {'=', '-'});
                startBytes = Convert.ToInt64(range[1]);
            }
            Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
            if (startBytes != 0)
                Response.AddHeader("Content-Range", string.Format(" byte {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
                
            Response.AddHeader("Connection", "Keep-Alive"); 
            Response.ContentType = "application/octet-stream"; 
            Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_filename, System.Text.Encoding.UTF8)); 

            br.BaseStream.Seek(startBytes, SeekOrigin.Begin); 
            int maxCount = (int)Math.Floor((double)((fileLength - startBytes) / pack)) + 1; 

            for (int i = 0; i < maxCount; i++) 
            { 
                if (Response.IsClientConnected) 
                { 
                    Response.BinaryWrite(br.ReadBytes(pack)); 
                    Thread.Sleep(sleep); 
                } 
                else 
                { 
                    i = maxCount; 
                } 
            } 
        } 
        catch 
        { 
            return false; 
        } 
        finally 
        { 
            br.Close(); 
            fs.Close(); 
        }
    }
    catch
    {
        return false;
    }
    
    return true;
}

Regular Expression to Enforce Password Complexity in ASP.NET Applications

Regular expression to enforce password complexity in your applications:

^.*(?=.{10,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$

The regular expression enforces the following rules:

•Must be at least 10 characters
•Must contain at least one one lower case letter, one upper case letter, one digit and one special character
•Valid special characters (which are configurable) are – @#$%^&+=

Originally from Anil John’s post
http://cyberforge.com/weblog/aniltj/archive/2004/09/23/670.aspx

Download a file from page via HTTPS(SSL)

string _path = Server.MapPath(ConfigurationSettings.AppSettings["path"]);

if (File.Exists(_path))
{
    string data = File.ReadAllText(_path);

    byte[] byteArr = Encoding.UTF8.GetBytes(data);
    MemoryStream stream = new MemoryStream(byteArr);

    // downloading file via HTTPS(SSL) will not work w/o clearing resposne.
    Response.ClearHeaders();
    Response.ClearContent();
    Response.Clear();
    Response.AddHeader("Content-Disposition",
                       "attachment; filename=" + Path.GetFileName(_path) + "\"");
    Response.AddHeader("Content-Length", byteArr.Length.ToString());
    Response.ContentType = "application/octet-stream";
    Response.BinaryWrite(byteArr);
    Response.End();
}