Sunday, January 30, 2011

log4net Log Pattern String


< conversionPattern value="%date{HH:mm:ss,fff} [%property{InstanceID}][%property{log4net:HostName}][%thread] %-5level - %message%newline" />

< conversionPattern value="%date{HH:mm:ss,fff} [%property{InstanceID}][%property{log4net:HostName}] %-5level - %message%newline" />

Tuesday, January 25, 2011

Time Zones Pacific UTC

Convert from Pacific Time to UTC/GMT

private DateTime ToUtc(DateTime pacificDateTime)
{
TimeZoneInfo pacificZone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
// "Pacific Standard Time" it's the ID regardless of daylight saving time (i.e. no matters if right now is daylight saving time, the ID name remains the same)

DateTime utcTime = TimeZoneInfo.ConvertTimeToUtc(pacificDateTime, pacificZone);
// it automatically takes care of daylight saving time

return utcTime;
}

Convert from UTC/GMT to Mountain Time

private DateTime ToMountain(DateTime utcDate)
{
TimeZoneInfo mountainZone = TimeZoneInfo.FindSystemTimeZoneById("Mountain Standard Time");
// "Mountain Standard Time" it's the ID regardless of daylight saving time (i.e. no matters if right now is daylight saving time, the ID name remains the same)

DateTime mountainTime = TimeZoneInfo.ConvertTimeFromUtc(utcDate, mountainZone);
// it automatically takes care of daylight saving time

return mountainTime;
}

Time zone converter

private DateTime ToMountain(DateTime datetime, string originalTimeZoneID)
{
// The strings requested by the method are the ID regardless of daylight saving time (i.e. no matter if right now is daylight saving time, the ID name remains the same)
return TimeZoneInfo.ConvertTimeBySystemTimeZoneId(datetime, originalTimeZoneID, "Mountain Standard Time");
}

Monday, January 24, 2011

Register Cache Host in Cluster - Powershell

After executing Get-CacheHost and our host is not listed in the results:

1. Register the local host in the cluster using:
> Register-CacheHost
// Then provide System.Data.SqlClient and the connection string for the AppFabric cache cluster configuration DB
2. Execute Get-CacheHost and will see our host is now listed (as DOWN)
3. Execute Start-CacheHost (or start the AppFabric service in the service.msc console)
4. Execute Get-CacheHost again and will see our host as UP







Sunday, January 23, 2011

List< T> as XmlArray


[System.Xml.Serialization.XmlRoot(ElementName = "user")]
public class User
{
[System.Xml.Serialization.XmlElement(ElementName = "id")]
public string ID { get; set; }

[System.Xml.Serialization.XmlArray("logs")]
[System.Xml.Serialization.XmlArrayItem("log")]
public List< Log> Logs { get; set; }
}

public class Log
{
[System.Xml.Serialization.XmlElement(ElementName = "no")]
public int Number { get; set; }

[System.Xml.Serialization.XmlElement(ElementName = "level")]
public string LogLevel { get; set; }
}

We could then deserialize an xml like the following into a User object.


1344166


1
Info


2
Debug



Thursday, January 20, 2011

Regex


string number = "9813f";
string regexPattern = @"^\d{5}$";

if (!Regex.IsMatch(number, regexPattern))
{
errorMessage = "The number is invalid (not a 5-digit number).";
return false;
}

Wednesday, January 19, 2011

Random Number SQL

From http://goo.gl/vzyje

-- random integer BETWEEN 4 AND 6 - [4, 6]
SELECT 4 + CONVERT(INT, (6-4+1)*RAND())

Monday, January 17, 2011

Cache Algorithm

For an integer value:

private int GetInteger(int uniqueID)
{
int integerv;

string key = String.Format("{0}_{1}", "SOMETHING", uniqueID);

object value = Cache.Get(key); // could be HttpContext.Current.Cache.Get

if (value != null) {
integerv = (int)value;
}
else {
integerv = _db.GetValueFromDb(uniqueID);
Cache.Add(key, integerv); // could be HttpContext.Current.Cache.Add
}

return integerv;
}

Sunday, January 16, 2011

NOLOCK


SELECT *
FROM Users u (NOLOCK)
INNER JOIN Permissions p (NOLOCK) ON p.UserID = u.UserID
WHERE u.IsActive = 1
ORDER BY u.CreatedOn ASC

Thursday, January 6, 2011

MD5 Hash

To generate an MD5 like 9adff06850bedeace9d0c6ebfe7ce507

private byte[] GetData(string filePath, string fileName, out string md5)
{
string path = Path.Combine(filePath, fileName);

byte[] bytes = System.IO.File.ReadAllBytes(path);

md5 = GetHash(bytes);

return bytes;
}

private string GetHash(byte[] data)
{
byte[] bytes = System.Security.Cryptography.MD5.Create().ComputeHash(data);

return StringifyMD5(bytes); // This method will return something like 9adff06850bedeace9d0c6ebfe7ce507
}

private string StringifyMD5(IEnumerable< byte> bytes)
{
var result = new StringBuilder();

foreach (byte b in bytes)
{
result.AppendFormat("{0:x2}", b);
}

return result.ToString();
}

we can also use it to generate a hash based on a string, for example, a filename:

string fileName = "some_file_name.xml";
string hash = GetHash(System.Text.Encoding.UTF8.GetBytes(fileName));

Wednesday, January 5, 2011

Print HTTP Response Headers

Key code:

using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
foreach (string key in response.Headers.AllKeys)
{
Console.WriteLine(String.Format("{0}: {1}", key, response.Headers[key]));
}
}

Complete code:


HttpWebRequest request = WebRequest.Create(_url) as HttpWebRequest;

request.Method = "GET";
request.Headers.Add("AuthToken", _token);
request.ContentLength = 0;

using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
Console.WriteLine("{0} {1}", (int)response.StatusCode, response.StatusCode);

foreach (string key in response.Headers.AllKeys)
{
Console.WriteLine(String.Format("{0}: {1}", key, response.Headers[key]));
}
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
Console.WriteLine("\n{0} ", reader.ReadToEnd());
}
}

Monday, January 3, 2011

Query Tables Size

From http://goo.gl/dF6Cv
and http://goo.gl/jxTTa


CREATE TABLE #TempTable
(
tableName varchar(100),
numberofRows varchar(100),
reservedSize varchar(50),
dataSize varchar(50),
indexSize varchar(50),
unusedSize varchar(50)
)

INSERT INTO #TempTable
EXEC sp_MSforeachtable @command1="EXEC sp_spaceused '?'"

SELECT *, cast(cast(replace(reservedSize, ' KB', '') as int)/1024 as varchar) + ' MB' AS Size
FROM #TempTable
ORDER BY cast(replace(reservedSize, ' KB', '') as int) DESC

Result: