Code to Send an Email in C#

dotnetlogo
Want to send an email from your .net application?
Just use the following code and don’t forget to put in the valid SMTP server id in the code and your email will be sent.

using System.Web.Mail;
private bool SendEmail(string sFrom, string sTo, string sCC,
string sBCC, string sSubject, string sMessage, int iMailType)
{
try
{
MailMessage Message = new MailMessage();

// If sFrom is blank, system mail id is assumed as the sender.
if(sFrom==””)
Message.From = “[email protected]”;
else
Message.From = sFrom;

// If sTo is blank, return false
if(sTo==””)
return false;
else
Message.To = sTo;

Message.Cc = sCC;
Message.Bcc = sBCC;
Message.Subject = sSubject;
Message.Body = sMessage;
Message.BodyFormat = MailFormat.Text;
SmtpMail.SmtpServer = “Put a valid smtp server IP”;
SmtpMail.Send(Message);

return true;
}
catch(System.Web.HttpException ehttp)
{
// Your exception handling code here…
return false;
}
catch(Exception e)
{
// Your exception handling code here…
return false;
}
catch
{
// Your exception handling code here…
return false;
}
}

Code to Write Log files in C#

dotnetlogo
Following method can be used to write errors into a log file through an application.

using System.IO;
public void WriteLogLine(string sCallerName, string sLogFolder,
long lCallerInstance, string sLogLine)
{
lock(this)
{
string sFileName;
sFileName = String.Format("{0}_{1:yyyy.MM.dd}_{2:00}.log",
sCallerName, DateTime.Now, lCallerInstance);
StreamWriter swServerLog =
new StreamWriter(sLogFolder + sFileName, true);
swServerLog.WriteLine(
String.Format("[{0:T}] {1}", DateTime.Now, sLogLine));
swServerLog.Close();
}
}

Salting the Password in C#

dotnetlogo
Hashed passwords provide much better security than storing passwords in the database as simple text. They are, however, potentially vulnerable to a dictionary attack. In a dictionary attack, the attacker attempts to guess passwords by using software to iteratively hash all words in a large dictionary and compare the generated hashes to the stored hash values.

You can help prevent dictionary attacks by requiring the end users to define passwords that are not common words and that contain some numbers or other nonalphanumeric characters.

In addition, you can add a random set of bytes at the beginning or end of the password before hashing it. This random set of bytes is called a salt. You then store this salt value in the table along with the password.

There are many ways to generate a salt value. One way is to generate a globally unique ID, or GUID, as follows.

public static String ComputeSalt()
{
System.Guid GuidValue = System.Guid.NewGuid();
return GuidValue.ToString();
}

This code can also be included in your utility component so it can be reused.

By using both the hash and the salt, you can minimize the possibility of an unauthorized user accessing your application.