Text editor options
Monday, November 28, 2011
Tuesday, September 27, 2011
Convert IEnumerable of String to Int
Code
// ids is an IEnumerable of String
var integers = ids.Select(x => int.Parse(x));
// to convert and sort at the same time:
var sortedIds = ids.Select(x => int.Parse(x)).OrderBy(x => x));
Sunday, August 21, 2011
Create XSD based on XML file
Sunday, July 31, 2011
Default Field Value at Table Creation Time
Syntax:
Example:
And for an already created table:
[FieldName] type CONSTRAINT [constraint_name] DEFAULT default_value
Example:
CREATE TABLE [Clients]
(
ClientID bigint NOT NULL IDENTITY(1,1) CONSTRAINT [PK_Clients] PRIMARY KEY,
CreatedOn datetime NOT NULL CONSTRAINT [DF_Clients_CreatedOnUtc] DEFAULT GETDATE()
...
)
And for an already created table:
ALTER TABLE Clients
ADD CONSTRAINT [DF_Clients_CreatedOn] DEFAULT GETDATE() FOR CreatedOn
Saturday, July 23, 2011
Unique Fields at Table Creation Time
Sintax:
Example:
Example 2:
[FieldName] type CONSTRAINT [constraint_name] UNIQUE
Example:
CREATE TABLE [Clients]
(
ClientID int NOT NULL IDENTITY(1,1) CONSTRAINT [PK_Clients] PRIMARY KEY,
ServiceCode varchar(50) NOT NULL CONSTRAINT [UQ_Clients_ServiceCode] UNIQUE
...
)
Example 2:
CREATE TABLE [Clients]
(
ClientID int NOT NULL IDENTITY(1,1) CONSTRAINT [PK_Clients] PRIMARY KEY,
ServiceCode varchar(50) NOT NULL,
CONSTRAINT [UN_Clients_Unique] UNIQUE (ClientID, ServiceCode)
...
)
Sunday, July 3, 2011
jQuery ajax function template
Example
Another example
$.ajax({
url: "/Home/Index",
data: { email: email, username: username, etc: etc },
success: function (data) {
debugger; // remove debugger before check-in.
$("#somelabel").text(data.SomeText);
},
type: "POST",
dataType: 'json'
});
Another example
$.ajax(
{
url: "/Account/LogOn",
type: "POST",
dataType: 'json',
data: {
username: $("txtUserName").val(),
password: $("txtPassword").val(),
rememberMe: $("#chkRememberMe").is(':checked')
},
success: function (mydata) {
if(mydata.Success) {
alert(mydata.WelcomeMessage);
}
else{
alert(mydata.Error);
}
}
});
Sunday, June 19, 2011
Get Url - Protocol/Schema, Domain and (if applicable) Port
From goo.gl/WfuVV and goo.gl/AYp9v
It will return a string like the following
Requesr.Url properties and sample values:
Request.Url.GetLeftPart(UriPartial.Authority)
It will return a string like the following
"http://localhost:51528"
Requesr.Url properties and sample values:
Request.Url
{http://localhost:51528/Account/SendForgotPasswordEmail?email=jon@connor.com}
AbsolutePath: "/Account/SendForgotPasswordEmail"
AbsoluteUri: "http://localhost:51528/Account/SendForgotPasswordEmail?email=jon@connor.com"
Authority: "localhost:51528"
DnsSafeHost: "localhost"
Fragment: ""
Host: "localhost"
HostNameType: Dns
IsAbsoluteUri: true
IsDefaultPort: false
IsFile: false
IsLoopback: true
IsUnc: false
LocalPath: "/Account/SendForgotPasswordEmail"
OriginalString: "http://localhost:51528/Account/SendForgotPasswordEmail?email=jon@connor.com"
PathAndQuery: "/Account/SendForgotPasswordEmail?email=jon@connor.com"
Port: 51528
Query: "?email=jon@connor.com"
Scheme: "http"
Segments: {string[3]}
UserEscaped: false
UserInfo: ""
Friday, June 3, 2011
Javascript Function Objects
Having:
the following
is similar to this:
and, to this as well:
So you could say that
is essentially the same as
i.e. validateFields is not a function/method but an object. Therefore I conclude "Javascript is a different language in disguise."
function validateFields() {
// a lot of cool and interesting code goes here.
var a = 1;
var b = 2;
var c = a + b;
}
the following
$('#submit').bind('click', function() {
validateFields();
});
is similar to this:
$('#submit').bind('click', validateFields);
and, to this as well:
$('#submit').bind('click', function() {
var a = 1;
var b = 2;
var c = a + b;
});
So you could say that
function validateFields() {
// a lot of cool and interesting code goes here.
var a = 1;
var b = 2;
var c = a + b;
}
is essentially the same as
var validateFields = function() {
// a lot of cool and interesting code goes here.
var a = 1;
var b = 2;
var c = a + b;
}
i.e. validateFields is not a function/method but an object. Therefore I conclude "Javascript is a different language in disguise."
Sunday, May 22, 2011
Enable DTC
1. Enable DTC in Component Services
Configure network access for the Distributed Transaction Coordinator
2. Setup Firewall Rules/Exceptions for DTC
Enable the Distributed Transaction Coordinator rules (inbound and outbound) in the Windows Firewall
3. Configure Port Range 5000-5100
From http://goo.gl/z0Ye7
4. Name resolution
Configure network access for the Distributed Transaction Coordinator
- Open Component Services.
- Expand Component Services > Computers > My Computer > Distributed Transaction Coordinator.
- Right click on “Local DTC” and select “Properties”.
- In the “Security” tab, enable the checkboxes for “Network DTC Access”, “Allow Remote Clients”, “Allow Remote Administration”, “Allow Inbound”, “Allow Outbound”, “Enable XA Transactions” and “Enable SNA LU 6.2 Transactions”. Change the radio button to “No Authentication Required”, and make sure that the DTC Logon Account is “NT AUTHORITY\NETWORK SERVICE”.
2. Setup Firewall Rules/Exceptions for DTC
Enable the Distributed Transaction Coordinator rules (inbound and outbound) in the Windows Firewall
- Open Window Firewall with Advanced Security
- In Inbound Rules enable the 3 rules for DTC
- In Outbound Rules enable the 1 rule for DTC
3. Configure Port Range 5000-5100
From http://goo.gl/z0Ye7
- Open Component Services.
- Expand the Component Services node.
- Expand the Computers node.
- Right-click My Computer and press Properties.
- Select the Default Protocols tab.
- Select Connection-oriented TCP/IP and press the Properties button.
- Press the Add button.
- Type the port range 5000-5100 into the Port range box, and press OK.
- Ensure that the Port range assignment and Default dynamic port allocation options are set to Internet range.
- Press OK, and OK again.
- Shutdown and restart your computer.
4. Name resolution
- Add an entry in the Hosts file in the MachineA with the ip address and name of MachineB
- Add an entry in the Hosts file in the MachineB with the ip address and name of MachineA
Wednesday, April 13, 2011
Regex Email
This is the one that jquery.validate.js uses:
string emailRegex = @"^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$";
Sunday, April 3, 2011
Monday, March 28, 2011
Friday, March 25, 2011
Tuesday, March 22, 2011
Friday, March 18, 2011
Powershell Cannot Execute Files
Thursday, March 17, 2011
ASPNET State Database
You will need to run the following commands using a db login that has Create Database permission.
(command prompt)
where
-S server name
-U user (database server login)
-P user's password
-d database name
(command prompt)
cd C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727
aspnet_regsql -S serverName -U myUser -P p4zz#w0rd -ssadd -sstype c -d MyASPState
where
-S server name
-U user (database server login)
-P user's password
-d database name
Sunday, March 13, 2011
SQL Loop with Temp Table
declare @id int
while exists(select 1 from #ids)
begin
select top 1 @id = id from #ids
--
-- do stuff
--
delete from #ids where id = @id
end
Tuesday, March 8, 2011
Substring and Character Position
String fucntions
Result:
declare @name varchar(10) = 'SMITH,JON'
SELECT SUBSTRING(@name, CHARINDEX(',', @name)+1, LEN(@name)) AS Name
Result:
Name
----------
JON
Sunday, February 27, 2011
RESEED Table
SQL Command:
DBCC CHECKIDENT(Employees, reseed, 1073741824)
Result/Message:
Checking identity information: current identity value '44', current column value '1073741824'.
DBCC execution completed. If DBCC printed error messages, contact your system administrator.
Sunday, February 20, 2011
Retry Logic (Recursively)
Uploading a file to a webserver.
private string UploadFile(string name, string token, bool retry = true)
{
string publicUrl = null;
try
{
bool success = _service.Save(name, token, out publicUrl);
}
catch (WebException ex)
{
// Server will return a 401 (Unauthorized) response when the authorization token has expired.
// So will create a new token and retry this operation.
if (ex.Response != null && (ex.Response as HttpWebResponse).StatusCode == HttpStatusCode.Unauthorized)
{
if (retry)
{
_logger.WarnFormat("Server returned 401 (Unauthorized), requesting new token and retrying operation...");
token = UpdateToken();
publicUrl = UploadFile(name, token retry: false); // try only one more time.
}
else
_logger.ErrorFormat("Server returned 401 (Unauthorized) again. File {0} could not be uploaded, please process it manually.", name);
}
else
throw ex;
}
return publicUrl;
}
Thursday, February 17, 2011
XML SQL Input Parameter
XML:
SQL:
Result:
50
Jon
Doe
A
99
Jon
Connor
A
1235
James
Bond
B
SQL:
declare @Clients xml
set @Clients =
''
50
Jon
Doe
A
99
Jon
Connor
A
1235
James
Bond
B
declare @clientsTable as table
(
ID int,
Name varchar(20),
LastName varchar(20),
Class char(1)
)
-- IMPORTANT:
-- value in col.value MUST be lowercase, otherwise this INSERT will fail.
INSERT INTO @clientsTable (ID
,Name
,LastName
,Class)
SELECT col.value('id[1]', 'int') AS ID
,col.value('name[1]', 'varchar(20)') AS Name
,col.value('lastname[1]', 'varchar(20)') AS LastName
,col.value('class[1]', 'char(1)') AS Class
FROM @Clients.nodes('//Client') tab(col)
select * from @clientsTable
Result:
ID Name LastName Class
----------- -------------------- -------------------- -----
50 Jon Doe A
99 Jon Connor A
1235 James Bond B
Sunday, February 13, 2011
Wednesday, February 9, 2011
Singleton C#
Non thread-safe
public class MyStorage
{
private static MyStorage instance;
public static MyStorage Instance
{
get {
if (instance == null)
instance = new MyStorage();
return instance;
}
}
private MyStorage()
{
// do stuff
InitStuff();
bool result;
_overwrite = bool.TryParse( ConfigurationManager.AppSettings["Overwrite"], out result) ? result : false;
}
...
}
Friday, February 4, 2011
FileInfo Get File Bytes
1. approach
2. approach
FileStream fs = myfileInfo.OpenRead();
int bytesCount =(int)fs.Length;
byte[] bytes = new byte[bytesCount];
int bytesRead = fs.Read(bytes, 0, bytesCount);
fs.Close();
2. approach
byte[] bytes = System.IO.File.ReadAllBytes(myfileInfo.FullName);
Wednesday, February 2, 2011
CSS Hacks IE7 IE8 and Chrome
Firefox: Padding Top = 2 pixels
IE7 and IE8: Padding Top = 1 pixels
Chrome: Padding Top = 1 pixels
IE7 and IE8: Padding Top = 1 pixels
Chrome: Padding Top = 1 pixels
table.main td#infobox div#container > div#legend {
float: right;
padding-top: 2px;
padding-right: 3px;
*padding-top: 1px; /* IE7 hack*/
padding-top: 1px\0/; /* IE8 hack, this hack must go after the rules for all another browser */
}
/* Chrome hack for the preceding style */
@media screen and (-webkit-min-device-pixel-ratio:0) {
table.main td#infobox div#container > div#legend {
padding-top: 1px;
}
}
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
Convert from UTC/GMT to Mountain Time
Time zone converter
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
we can also use it to generate a hash based on a string, for example, a filename:
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:
Complete 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
Result:
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:
Subscribe to:
Posts (Atom)