Monday, December 7, 2015

C# - How to send email without any plugins


Below code helps to send email without any third party email plugins, but it requires SMTPServer details to be specified in web.config AppSettings. That server needs to be configured as email server.

using System.Net.Mail;
public void SendEmail(string fromAddress, string[] toAddress, string subject, string bodyContent, string[] filenames)
        {
            MailMessage email = new MailMessage();

            email.From = new MailAddress(fromAddress);
            if (toAddress != null && toAddress.Length > 0)
            {
                foreach (var toAdd in toAddress)
                {
                    email.To.Add(new MailAddress(toAdd));
                }
            }

            email.Subject = subject;
            email.Body = bodyContent;

            if (filenames != null && filenames.Length > 0)
            {
                foreach (var file in filenames)
                {
                    Attachment attachment;
                    attachment = new Attachment(@file);
                    email.Attachments.Add(attachment);
                }
            }

            try
            {
                using (var client = new SmtpClient())
                {
                    client.Send(email);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                email.Dispose();
            };
        }

Friday, November 27, 2015

RavenDB Linq - How to use dynamic where clause

I faced scenario to add some specified where clause based some conditions, so that i have used following code. We can add any number of where conditions like below and execute query to RavenDB. 


public IEnumerable<Student> SearchStudents()
{
List<Expression<Func<Student, bool>>> whereConditionList = new List<Expression<Func<Student, bool>>>();

whereConditionList.Add(p => p.Name == "Balajiprasad");
whereConditionList.Add(p => p.Age > 16);
whereConditionList.Add(p => p.City == "Coimbatore");

var ravenQuery = ravenSession.Query<Student>();

foreach (var condition in whereConditionList)
  ravenQuery = ravenQuery.Where(condition);

return ravenQuery.ToList();
}