SendGrid – SMTP

What is SendGrid ?
SendGrid is for anyone that needs to send email, whether it’s transactional email or marketing emails and campaigns. SendGrid is a cloud-based SMTP provider that allows you to send email without having to maintain email servers. SendGrid manages all of the technical details, from scaling the infrastructure to ISP outreach and reputation monitoring to white list services and real time analytics. SendGrid also provide a robust marketing email API if you want to integrate any of these features into your own application.
SendGrid provides two ways to send email: through our SMTP relay or through our Web API. Please find samples for SMTP replay:

		public static void SmtpSendMessage()
        {
			try
			{
				var mailMsg = new MailMessage();

				// To
				//TODO: To Name should be Configured
				mailMsg.To.Add(new MailAddress("jijo.venginikkadan@gmail.com", "To Name"));
				mailMsg.To.Add(new MailAddress("jijo.venginikkadan@gmail.com", "To Name"));

				// From
				//TODO:From Name should be Configured
				mailMsg.From = new MailAddress("from@example.com", "From Name");

				// Subject and multipart/alternative Body
				//TODO:Subject should be configured
				mailMsg.Subject = "SendGrid Test email";
				//TODO:Body should be configured
				var text = "Hello,\n\nThis is a test message from SendGrid."; ;
				//TODO:Body should be configured
				//const string html = @"<p>html body</p>";

				mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(text, null, MediaTypeNames.Text.Plain));
				mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html));

				var smtpClient = new SmtpClient("smtp.sendgrid.net", Convert.ToInt32(587));
				//TODO:User ID and password should be configured
				//                var credentials = new System.Net.NetworkCredential("UserID", "password123");
				//                smtpClient.Credentials = credentials;

				smtpClient.Send(mailMsg);
			}
			catch (Exception ex)
			{
				Console.WriteLine(ex.Message);
			}
	  }
Advertisements

SendGrid – Web API

What is SendGrid ?
SendGrid is for anyone that needs to send email, whether it’s transactional email or marketing emails and campaigns. SendGrid is a cloud-based SMTP provider that allows you to send email without having to maintain email servers. SendGrid manages all of the technical details, from scaling the infrastructure to ISP outreach and reputation monitoring to white list services and real time analytics. SendGrid also provide a robust marketing email API if you want to integrate any of these features into your own application.
SendGrid provides two ways to send email: through our SMTP relay or through our Web API. Please find samples for Web API:

        private static void SendGridWebApi()
        {
            // Create the email object first, then add the properties.
            var myMessage = new SendGridMessageWebApi
            {
                To = new[]
                {
                    new MailAddress("jijo.venginikkadan@gmail.com", "Test To Address"),
                    new MailAddress("vgjijo@gmail.com", "Test To Address"),
                },
                From = new MailAddress("john@example.com", "John Smith"),
                Subject = "Testing the SendGrid Library",
                Text = "Hello World! %tag%",
                Html = "<html><p>Hello</p><p>World</p></html>"
            };
            //set the message recipients
            //set the message subject
            myMessage.Subject = "Hello World HTML Test";

            SendAsync(myMessage);

            Console.ReadLine();         
        }

        private static async void SendAsync(SendGridMessage message)
        {
            // Create credentials, specifying your user name and password.
            var credentials = new NetworkCredential("UserId", "Passoerd123");

            // Create a Web transport for sending email.
            var transportWeb = new Web(credentials);

            // Send the email.
            try
            {
                await transportWeb.DeliverAsync(message);
                Console.WriteLine("Sent!");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
		

Weak References

I never come across a situation where I’ve needed to use Weak Reference type in .Net, But while addressing a defect there was a scenario where UI is publishing an event and listen for the responses through event channel frame work built on hardware based java framework. Un fortunately the UI code for publishing the message was written on weak reference type (n later realised this was to address performance related issues)
Occasionally the frameworks that are subscribed to JIT events lose their subscription and stop receiving the events when it is published. The issue was due to the event aggregator that use for JIT publishing uses weak references for the subscribed events which can then be lost when Garbage Collection occurs.
The fix was simple, but to reach in to conclusion it was tough as this was not happening very often. The issue was fixed; basically remove all the weak reference from event aggregator subscription.
A Simple example to test weak reference is given below-

static WeakReference _weak;
public void TriggerWeakRefernce()
{
   // Assign the WeakReference.
   _weak = new WeakReference(new StringBuilder("eventtChannel"));
   // See if weak reference is alive.
   if (_weak.IsAlive)
   {
      var stringBuilder = _weak.Target as StringBuilder;
      if (stringBuilder != null)
        Console.WriteLine(stringBuilder.ToString());
    }
    // Invoke GC.Collect.
    // ... If this is commented out, the next condition will evaluate true.
    GC.Collect();

    // Check alive.
    if (_weak.IsAlive)
    {
       Console.WriteLine("Event Channel is Alive");
    }
    // Finish.
     Console.WriteLine("[Done]");
     Console.Read();
}

Weak References

I have not personally come across a situation where I’ve needed to use Weak Reference type in .Net, But while addressing a defect there was a scenario where UI is publishing an event and listen for the responses through event channel frame work built on hardware based java framework. Un fortunately the UI code for publishing the message was written on weak reference type (n later realised this was to address performance related issues)
Occasionally the frameworks that are subscribed to JIT events lose their subscription and stop receiving the events when it is published. The issue was due to the event aggregator that use for JIT publishing uses weak references for the subscribed events which can then be lost when Garbage Collection occurs.
The fix was simple, but to reach in to conclusion it was tough as this was not happening very often. The issue was fixed; basically remove all the weak reference from event aggregator subscription.
A Simple example to test weak reference is given below-

  static WeakReference _weak;
        public void TriggerWeakRefernce()
        {
            // Assign the WeakReference.
            _weak = new WeakReference(new StringBuilder("eventtChannel"));
            // See if weak reference is alive.
            if (_weak.IsAlive)
            {
                var stringBuilder = _weak.Target as StringBuilder;
                if (stringBuilder != null)
                    Console.WriteLine(stringBuilder.ToString());
            }
            // Invoke GC.Collect.
            // ... If this is commented out, the next condition will evaluate true.
            GC.Collect();

            // Check alive.
            if (_weak.IsAlive)
            {
                Console.WriteLine("Event Channel is Alive");
            }
            // Finish.
            Console.WriteLine("[Done]");
            Console.Read();
        }

Query Active directory using C#

Requirement definition
There was a requirement where we are dealing with a web based application and have to authenticate our logged in user against the LAN ID. The LAN ID information is maintained by Microsoft Active Directory.Active Directory is a technology by Microsoft that provides a variety of services. So here the issue is how we are going to communicate with ADI and get the information’s using our application.
Solution
This article describes how to use .NET framework to manage resources under Windows Active Directory Services. Microsoft provides ADSI (Active Directory Services Interface) which can interact with many providers including IIS (Internet Information Services), LDAP (Lightweight Directory Access Protocol), WinNT and NDS (Novell Netware Directory Service). Using the classes provided under .NET System.DirectoryServices namespace. To access these classes add System.DirectoryServices.dll to the references. The System.DirectoryServices namespaces provides two important classes DirectoryEntry and DirectorySearcher to work with the Active Directory. The DirectoryEntry class represents a resource in the Active Directory and the DirectorySearcher class is used to query the Active Directory. The DirectorySearcher class uses a search root which is a server where the search begins and a LDAP filter string (which is analogous to where clause in SQL) to query the Active Directory resources. A condition is enclosed by parenthesis and an operator precedes 2 conditions. Eg. (& (Condition1)(Condition2)) The statement is equivalent to saying A and B. Remember the parenthesis. Another example ((& (Condition1)(Condition2) ) (Condition3) ) should be interpreted as (Condition1 and Condition2) or (Condition3).
After a couple of days of Research I have successfully accomplished the tasks of querying for and updating users. I will share some basic functionality for those of you that are interested. It might be useful to read up on LDAP to get a good understanding of what it is and how it works with Active Directory.

public static DirectoryEntry GetDirectoryService()
{
      de.Path = ldap://OU=Domain,DC=YourDomain,DC=com/;
      de.AuthenticationType = AuthenticationTypes.Secure;     
      DirectoryEntry de = new DirectoryEntry();
      return de;
}
 public bool UserExists(string username)
{
     DirectoryEntry dr = GetDirectoryService();
    DirectorySearcher drSearch = new DirectorySearcher();"(&(objectClass=user) (cn=" + username + "))";
    SearchResultCollection results = drSearch.FindAll();
    return results;
}
Read the result :
foreach (SearchResult result in results)
{
    string userNmae = result.Properties["samaccountname"][0];
}
foreach (SearchResult result in results)
{
    string userNmae = result.Properties["samaccountname"][0];
}
Now if needed we can add more filter conditions here based on your requirement. Here by some examples are given.
adSearch.PropertiesToLoad.Add("cn");
adSearch.PropertiesToLoad.Add("givenname");
adSearch.PropertiesToLoad.Add("displayname");
adSearch.PropertiesToLoad.Add("employeenumber");
adSearch.PropertiesToLoad.Add("samaccountname");
adSearch.PropertiesToLoad.Add("countrycode");
adSearch.PropertiesToLoad.Add("memberof");

EF vs Linq to SQL

There is a battle between LINQ to SQL and the (EF)Entity Framework. Some say that it is already settled and that LINQ to SQL is DOA, destined to be replaced by Entity Framework. Microsoft will continue to support L2S but will put more effort into the EF and the Linq to Sql shall be retired.Not the complete retairment but the scope is going to be limited. The new term, I think, is LINQ to Entities (L2E). The entity framework is Microsoft’s implementation of a full grown Object/Relation Mapper such as NHibernate already is. Linq to SQL on the other hand may have some similarities, but is not recognized (and will never be) as a full o/r m tool. It is however a quick and easy way for accessing relational data in a much better way than the classic ado.net and can be very suitable in small projects or applications. MSDN has an article comparing the two. I am currently evaluating the latest release of Entity Framework.I am trying in to dig in to EF more deeply and keep posting my findings here.

AD access from C#

Requirement definition
There was a requirement where we are dealing with a web based application and have to authenticate our logged in user against the LAN ID. The LAN ID information is maintained by Microsoft Active Directory.Active Directory is a technology by Microsoft that provides a variety of services. So here the issue is how we are going to communicate with ADI and get the information’s using our application.
Solution
This article describes how to use .NET framework to manage resources under Windows Active Directory Services. Microsoft provides ADSI (Active Directory Services Interface) which can interact with many providers including IIS (Internet Information Services), LDAP (Lightweight Directory Access Protocol), WinNT and NDS (Novell Netware Directory Service). Using the classes provided under .NET System.DirectoryServices namespace. To access these classes add System.DirectoryServices.dll to the references. The System.DirectoryServices namespaces provides two important classes DirectoryEntry and DirectorySearcher to work with the Active Directory. The DirectoryEntry class represents a resource in the Active Directory and the DirectorySearcher class is used to query the Active Directory. The DirectorySearcher class uses a search root which is a server where the search begins and a LDAP filter string (which is analogous to where clause in SQL) to query the Active Directory resources. A condition is enclosed by parenthesis and an operator precedes 2 conditions. Eg. (& (Condition1)(Condition2)) The statement is equivalent to saying A and B. Remember the parenthesis. Another example ((& (Condition1)(Condition2) ) (Condition3) ) should be interpreted as (Condition1 and Condition2) or (Condition3).
After a couple of days of Research I have successfully accomplished the tasks of querying for and updating users. I will share some basic functionality for those of you that are interested. It might be useful to read up on LDAP to get a good understanding of what it is and how it works with Active Directory.

public static DirectoryEntry GetDirectoryService()
{
      de.Path = ldap://OU=Domain,DC=YourDomain,DC=com/;
      de.AuthenticationType = AuthenticationTypes.Secure;     
      DirectoryEntry de = new DirectoryEntry();
      return de;
}
 public bool UserExists(string username)
{
     DirectoryEntry dr = GetDirectoryService();
    DirectorySearcher drSearch = new DirectorySearcher();"(&(objectClass=user) (cn=" + username + "))";
    SearchResultCollection results = drSearch.FindAll();
    return results;
}
//Read the result :
foreach (SearchResult result in results)
{
    string userNmae = result.Properties["samaccountname"][0];
}

Now if needed we can add more filter conditions here based on your requirement. Here by some examples are given.

adSearch.PropertiesToLoad.Add("cn");
adSearch.PropertiesToLoad.Add("givenname");
adSearch.PropertiesToLoad.Add("displayname");
adSearch.PropertiesToLoad.Add("employeenumber");
adSearch.PropertiesToLoad.Add("samaccountname");
adSearch.PropertiesToLoad.Add("countrycode");
adSearch.PropertiesToLoad.Add("memberof");