SQL Server DateTime formatting

November 25, 2010

(0) Comments

When you working with database one of most often problem you face is date time data. In this post I’m going to post code snippets that do different things with datetime data and links to the original posts!

Snippet 1
Converting datetime value to a given format using built in SQL Sever functions

select convert(varchar, getdate(), 10) -- returns 12-30-06
select convert(varchar, getdate(), 1)  -- returns 12/30/06

--Convert and replacing the divider
select replace(convert(varchar, getdate(),101),'/','')  -- returns 12302006

The source for this snippet http://www.mssqltips.com/tip.asp?tip=1145
Link for MSDN : http://msdn.microsoft.com/en-us/library/ms187928.aspx

Snippet 2
Determine a value is valid datetime

update myTable
set part2=replace(convert(varchar, (CAST(custref1 AS datetime)),102),'.','')
where isdate(custref1)=1
and sourceorderidpart2='CUSTREF1'

Optional Parameters and Named Arguments in C# 4

November 17, 2010

(0) Comments

C# 4.0 now supports using optional parameters with methods, constructors, and indexers (note: VB has supported optional parameters for awhile).

This is how you declare your method to have optional parameter

public Boolean SendMail( string[] toAddresses, string subject, string body,string sender = "bala.singam@hotmail.com",bool isBodyHTML=false)
{
 
try
            {
                MailMessage mailMessage = new MailMessage();
                mailMessage.From =new MailAddress(sender);
                mailMessage.IsBodyHtml = isBodyHTML;

                foreach (string address in toAddresses)
                    mailMessage.To.Add(new MailAddress(address));

                mailMessage.Subject = subject;
                mailMessage.Body = body;

                SmtpClient smtpClient = new SmtpClient();
                smtpClient.Send(mailMessage);

                return true;
            }
            catch (SmtpException ex)
            {
               Console.WriteLine(ex);
                return false;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return false;
            }
}

And this is how you call your method with optional parameters/named arguments

//I did't passed sender parameter value
mailer.SendMail(toAddresses:new string[] { "bala.singam@hotmail.com" },subject: "File Received", body:Encoding.UTF8.GetString(msg),isBodyHTML:true);

Source : http://weblogs.asp.net/scottgu/archive/2010/04/02/optional-parameters-and-named-arguments-in-c-4-and-a-cool-scenario-w-asp-net-mvc-2.aspx

||