Monday, March 10, 2008

C# and Calendars

C# provides abstract class Calendar, which implements basic calendar operations, and different calendar implementations:

GregorianCalendar, HebrewCalendar, HijriCalendar, JapaneseCalendar, JulianCalendar, KoreanCalendar, TaiwanCalendar, and ThaiBuddhistCalendar.

Sample of calendars usage:

using System;
using System.Globalization;

namespace CalendarSamples
{
class Program
{
static void Main()
{
DateTime now = DateTime.Now;

HebrewCalendar hebrewCalendar = new HebrewCalendar();
String hebrewDate = String.Format("{0} {1} {2}",
hebrewCalendar.GetDayOfMonth(now),
hebrewCalendar.GetMonth(now),
hebrewCalendar.GetYear(now));

GregorianCalendar gregorianCalendar = new GregorianCalendar();
String gregorianDate = String.Format("{0} {1} {2}",
gregorianCalendar.GetDayOfMonth(now),
gregorianCalendar.GetMonth(now),
gregorianCalendar.GetYear(now));

JulianCalendar julianCalendar = new JulianCalendar();
String julianCDate = String.Format("{0} {1} {2}",
julianCalendar.GetDayOfMonth(now),
julianCalendar.GetMonth(now),
julianCalendar.GetYear(now));

Console.WriteLine("date: " + now);
Console.WriteLine("hebrew date: " + hebrewDate);
Console.WriteLine("gregorianCalendar date: " + gregorianDate);
Console.WriteLine("julianCalendar date: " + julianCDate);
}
}
}





Additional Links:

Sunday, March 9, 2008

C# basic compression and decompression services.

To compress and decompress a data it is suggested to use class DefalteStream or GZipStream

using System.IO;
using System.IO.Compression;

namespace zip_usage
{
class Program
{
static Stream CreateCompressStream(Stream inputStream, CompressionMode compressionMode)
{
//return new GZipStream(inputStream, compressionMode, true);
return new DeflateStream(inputStream, compressionMode, true);
}
static void Main()
{
string inputFileName = @"..\..\Data\inputData.bin";
string compressedFileName = @"..\..\Data\compressedData.zip";
string resultFileName = @"..\..\Data\outputData.bin";

byte[] inputBuffer = File.ReadAllBytes(inputFileName);
using (FileStream outputStream = File.OpenWrite(compressedFileName))
{
using (Stream compress = CreateCompressStream(outputStream, CompressionMode.Compress))
{
compress.Write(inputBuffer, 0, inputBuffer.Length);
}
}

byte[] resultBuffer = new byte[inputBuffer.Length];
using (FileStream compressedStream = File.OpenRead(compressedFileName))
{
using (Stream decompress = CreateCompressStream(compressedStream, CompressionMode.Decompress))
{
decompress.Read(resultBuffer, 0, resultBuffer.Length);
}
}

File.WriteAllBytes(resultFileName, resultBuffer);
}
}
}



Additional Links: System.IO.Compression Namespace

Thursday, March 6, 2008

How to send email and check without real SMTP server.

To send email via SMTP server see next sample code

using System.Net.Mail;
using System.Text;
 
namespace email_functions
{
    class Program
    {
        static void Main(string[] args)
        {
            string host = "test.com";
            SmtpClient smtpClient;
            MailAddress sender;
            MailAddress recipient;
 
            smtpClient = new SmtpClient(host);
            smtpClient.Timeout = 3000;
 
            sender = new MailAddress("sender@test.com", "Sender");
            recipient = new MailAddress("recipient@test.com", "Recipient");
 
            MailMessage message = new MailMessage(sender, recipient);
            message.SubjectEncoding = Encoding.UTF8;
            message.Subject = "test Smtp";
 
            smtpClient.Send(message);
        }
    }
}

But if real SMTP server (in sample, "test.com") is not accessible, then next error will be shown:






To test sending email without real SMTP server it is suggested to add section to .config file:


Notes:

  • Folder "c:\testEmailsFolder" should be created before email sending.
  • After .config file changes a program should be restarted.

Now, when the sample will finished, then text file .eml will be creared in folder "c:\testEmailsFolder". The file can be opened in Windows Live Mail.

X-Sender: Sender 
X-Receiver: Recipient
MIME-Version: 1.0
From: Sender
To: Recipient
Date: 6 Mar 2008 13:16:24 +0200
Subject: =?utf-8?B?dGVzdCBTbXRw?=

Additional Links:

SmtpClient..::.DeliveryMethod Property

Wednesday, March 5, 2008

Correct usage of IDisposable.

Original source code (write a text to text file):
--------------------------------------------------------------------
StreamWriter writer = new StreamWriter(filePath);
for (int i = 0; i < result.Length; i++)
{
writer.WriteLine(result[i].name + ": " + result[i].value);
}
writer.Flush();
--------------------------------------------------------------------

Class StreamWriter implements interface IDisposable, then we should call method Dispose(), which closes all unmanaged resources (and executes another 'destructor' actions).

Picture (Device Independent Bitmap)

Original code should be rewritten in another ways (when we call Dispose(), we may not close Flush()) :

--------------------------------------------------------------------

StreamWriter writer = new StreamWriter(filePath);
for (int i = 0; i < result.Length; i++)
{
writer.WriteLine(result[i].name + ": " + result[i].value);
}
writer.Flush();
writer.Dispose();

--------------------------------------------------------------------

or, more correctly,

--------------------------------------------------------------------

StreamWriter writer = new StreamWriter(filePath);
try
{
for (int i = 0; i < result.Length; i++)
{
writer.WriteLine(result[i].name + ": " + result[i].value);
}
}
finally
{
writer.Dispose();
}

--------------------------------------------------------------------

C# suggest statement "using" to call Dispose() method

--------------------------------------------------------------------

using (StreamWriter writer = new StreamWriter(filePath))
{
for (int i = 0; i < result.Length; i++)
{
writer.WriteLine(result[i].name + ": " + result[i].value);
}
}

--------------------------------------------------------------------

using Statement (C# Reference) http://msdn2.microsoft.com/en-us/library/yh598w02.aspx
As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement. The using statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and cannot be modified or reassigned.

Monday, March 3, 2008

Method File.AppendAllText

     To add any text to test file, can be used method

File.AppendAllText(String path, String contents)

   1: string fileName = Path.GetTempFileName();


   2: string fileContent = "sample of method File.WriteAllText";


   3: File.WriteAllText(fileName, fileContent);




Additional Links:



File..::.AppendAllText Method (String, String)



File..::.AppendAllText Method (String, String, Encoding)

Method Path.Combine()

To Combine 2 path strings (for example, file path and file name) it is suggested method

Path.Combine(string path1, string path2).

Samples:

Path1 Path2 Path.Combine()
"C:\\Temp" "file.txt" "C:\\Temp\\file.txt"
"C:\\Temp" "C:\\Temp\\file.txt" "C:\\Temp\\file.txt"

Additional Links:

Path..::.Combine Method

Sunday, March 2, 2008

C# function String.IsNullOrEmpty()

If it is necessary to check string variable on null and "" (empty), then

function String.IsNullOrEmpty can be used:


c0de with operator 'if'

string getName(string name)

{
if (name == null || name == "")
return "default";
else
return name;
}


code with function Sgtring.IsNullOrEmpty()


string getName_with_function_IsNullOrEmpty(string name)
{
if (String.IsNullOrEmpty(name))
return "default";
else
return name;
}


Sample can be download:

http://code.google.com/p/csharp-tips/source/browse/trunk/string_functions/Program.cs

Additional Links:
String..::.IsNullOrEmpty Method