4 Ocak 2011 Salı

E-mail Uygulaması(Birthday Reminder)


Merhaba arkadaşlar bugün sizlere MS CRM  web servisini  ve   C# kodlarını kullanarak nasıl e-mail göndereceğinizi anlatacağım. Uygulama tamamlandığında doğum günü olan ilgili kişileri kontrol edebilecek , e-mail aktivitesi oluşturarak e*mail gönderebileceksiniz.  email’leri crm üzerinden göndermek için Email Router bu link’den indirebilirsiniz.  Email Router  kurup Exchange veya POP3 ayarlarını yapdıktan sonra kodlarımızı yazmaya başlayabiliriz. Öncellikle  visual studio uygulamamızı açıp yeni bir Console projesi açalım. Daha sonra  web servis nesnelerine ulaşmak için add web reference diyerek projenize http:// server adı>/mscrmservices/2007/CrmServiceWsdl.aspx  dahil edelim.



 Daha sonra kullanacağımız metotların geldiğini göreceksiniz.



using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using EmailApplication.CrmWs;
using EmailApplication.Properties;

namespace EmailApplication
{
    class Program
    {

        static void Main(string[] args)
        {
            //İlgili kişiler varlığından email adresi boş olmayan ve doğum günü bugün olan kişlerin listesini alalım.
            string Query = @"
                                        DECLARE @UTCDiff INT
                                        SET @UTCDiff = DATEDIFF(HOUR, GetUTCDate(), GETDATE())
                                        SELECT
                                               f.fullname AS fullname,
                                               f.contactid AS contactid,
                                            f.fullname AS contactname,
                                               f.birthdate AS birthdate,
                                               f.emailaddress1 AS email                                                                                                                                     
                                        FROM
                                               FilteredContact AS f WITH (NOLOCK)                                                                         
                                        WHERE
                                               f.birthdate IS NOT NULL
                                               AND (DAY(DATEADD(hh, @UTCDiff, f.birthdate)) = DAY(GETDATE()))
                                               AND (MONTH(DATEADD(hh, @UTCDiff, f.birthdate)) = MONTH(GETDATE()))    
                                               AND f.emailaddress1 IS NOT NULL
                                        ORDER BY f.fullname";
            try
            {
                DataTable dt = new DataTable();
                SqlConnection con = GetCrmSqlConnection();

                if (con != null)
                {
                    SqlDataAdapter adap = new SqlDataAdapter(Query, con);
                    adap.Fill(dt);
                    if (dt.Rows.Count != 0)
                    {
                        SendEmail(dt);
                    }
                }
            }
            catch (Exception ex)
            {
                //throw new Exception(ex.Message);
                throw ex;
            }

        }
        private static void SendEmail(DataTable dt)
        {
            try
            {
                email mail = new email(); // Email sınıfını oluşturalım.
                activityparty from = new activityparty();
                activityparty toSingle = null;
                from.partyid = new Lookup();
                from.partyid.type = EntityName.systemuser.ToString();
                from.partyid.Value = new Guid(Settings.Default.From.ToString()); // Gönderen Id'si
                mail.from = new activityparty[] { from };
                if (dt != null)
                {
                    CrmService servis = ConnectService(); //crm servisini çağıralım.
                    activityparty[] to;

                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        to = new activityparty[dt.Rows.Count];
                        toSingle = new activityparty();
                        toSingle.partyid = new Lookup();
                        toSingle.partyid.type = EntityName.contact.ToString();
                        toSingle.partyid.Value = new Guid(Convert.ToString(dt.Rows[i]["contactid"]));
                        to[i] = toSingle;
                        mail.to = to;
                        mail.subject = "Doğum Gününüz Kutlu Olsun.";                   
                        CrmBoolean direction = new CrmBoolean();
                        direction.Value = true;
                        mail.directioncode = direction;      
                        Guid mailId = servis.Create(mail);
                        GetTrackingTokenEmailRequest getRequest = new GetTrackingTokenEmailRequest();
                        getRequest.Subject = mail.subject;
                        GetTrackingTokenEmailResponse getResponse = (GetTrackingTokenEmailResponse)servis.Execute(getRequest);
                        SendEmailRequest request = new SendEmailRequest();
                        request.EmailId = mailId;
                        request.IssueSend = true;
                        request.TrackingToken = getResponse.TrackingToken;
                        SendEmailResponse response = (SendEmailResponse)servis.Execute(request);
                        //}
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        private static CrmService ConnectService()
        {          
            CrmService servis = null;
            try
            {
                servis = new CrmService();
                CrmWs.CrmAuthenticationToken token = new CrmWs.CrmAuthenticationToken();
                token.AuthenticationType = 0;
                token.OrganizationName = "crm";
                servis.CrmAuthenticationTokenValue = token;
                servis.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;

            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return servis;
        }

        private static SqlConnection GetCrmSqlConnection()
        {
            string connStr = null;
            SqlConnection conn = null;
            try
            {
                connStr = String.Format("Data Source=.;Initial Catalog=ORG_MSCRM;Integrated Security=True");
                conn = new SqlConnection(connStr);
            }
            catch (SqlException ex)
            {
                throw new Exception(ex.Message);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return conn;
        }

    }

}

Bir sonraki yazımda görüşmek üzere, Herkese başarılar dilerim.


Hiç yorum yok:

Yorum Gönder