AXForum  
Вернуться   AXForum > Microsoft Dynamics CRM > Dynamics CRM: Blogs
All
Забыли пароль?
Зарегистрироваться Правила Справка Пользователи Сообщения за день Поиск Все разделы прочитаны

 
 
Опции темы Поиск в этой теме Опции просмотра
Старый 13.06.2011, 12:11   #1  
Blog bot is offline
Blog bot
Участник
 
25,643 / 848 (80) +++++++
Регистрация: 28.10.2006
furnemont: How-to series: Send SMS messages from CRM 2011 (part 3)
Источник: http://www.furnemont.eu/2011/06/how-...m-2011-part-3/
==============

Finally! This is the final part of my how-to series on how to send and track SMS messages in Microsoft CRM 2011.

The first post explained how to prepare the solution.

The second post talked about the Web front-end customization.

This last post will explain how to communicate with Clickatell’s gateway to send your SMS messages.



First step: sign-up for a Clickatell account

  1. First of all, you need to sign-up on Clickatell’s web site using their sign-up form which can be found here: http://www.clickatell.com/register/account_signup.php
  2. Make sure you select the ‘clickatell central (api)’ and ‘International’ option for either Small Business or Enterprise
  3. During the registration process, you have to provide a cellphone number in order to receive a unique and personal code, which will be needed to create a ‘Sender ID’. The definition of the ‘Sender ID’ is this:
    A Sender ID is the name or number that the message appears to come from. By default you can send a message from the mobile number you registered your account with. If you wish to send messages from other numbers or names you will be required to register them. Approval of your submitted Sender ID is not guaranteed and generally only numbers, company and product names that we are able to verify will be approved. Any MO numbers linked to your account do not need to be registered.

  4. Once you have filled all the required information, you will receive an email to activate your account and you will be able to put the activation code you received by SMS
  5. Once the account is validated, you should receive 3 important information:
    • Your username
    • Your password
    • Your ‘Client ID
Which API do you need?

OK, this can be a bit confusing since Clickatell offers several types of API to developers: COM, HTTP, SOAP, SMTP, etc.

In my example, I used the SOAP API which is easier to integrate in a Microsoft CRM plugin but needs a permanent connection to the Web Service.

These are the steps to register a new API connection:

  • Log on to your Clickatell account (http://www.clickatell.com/register/account_login.php) using the correct product (in our case ‘Central API’) and fill in the username, client ID and password to access the ‘Central Home’ management console
  • The management console allows you to:
      • Verify how many SMS has been sent
      • How many SMS failed to be sent
      • Create a new API connection
      • Verify your credit balance
      • etc.
  • To create a new API connection, simply click on the ‘Create a new Connection’ hyperlink and select the type of connection you want to create, then request your ‘API ID’ (this parameter is really important for the rest of this article)
  • Once you close the confirmation screen, you will see a message stating that the 10 first test credits will always display the same SMS text (it’s OK, it’s just for testing purposes )
  • You are all set!
FYI, if you need to retrieve the API ID, just click on the ‘Manage my Products’ link in the management console:



Create the CRM plugin

OK, now it’s time to create our Microsoft CRM plugin using Visual Studio 2010; I’m using Pogo69’s CRM 2011 – Visual Studio Plugin Templates to easy my plugin developments so you might as well use it, it’s free

  1. Create a new VS project using the CRM 2011 plugin template and give it a easy name, such as ‘SMSMessaging’
    • In this new project, everything is already there for you to start developing your plugin, so I’m not going to explain all the steps
  2. Start by modifying the ‘plugin.cs’ file and change the name of the public class to ‘SendSMS’ for example
  3. Next step is to register the Clickatell’s Web Service by using the Internet address provided during the API connection creation: http://api.clickatell.com/soap/webservice.php?WSDL and by giving it an easy name (example: ‘Clickatell’)
  4. Add a new CS file (it will contain the SOAP API return codes) called ‘ClickatellRC.cs’ with the following C# code:
    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Text;

     

    namespace SMSMessaging.ReturnCodes

    {

    public sealed class StatusCodes

    {

    public const string m001 = "Status unknown";

    public const string m002 = "Message queued";

    public const string m003 = "Delivered to client gateway";

    public const string m004 = "Received by recipient";

    public const string m005 = "Error with message";

    public const string m006 = "User cancelled message delivery";

    public const string m007 = "Error delivering message";

    public const string m008 = "Message received by gateway";

    public const string m009 = "Routing error";

    public const string m010 = "Message expired";

    public const string m011 = "Message queued for later delivery";

    public const string m012 = "Out of credit";

    }

    }


  5. In your ‘plugin.cs’ file, add a reference to your return codes file:
    using SMSMessaging.ReturnCodes;


  6. When all of this is done, you can paste the following code in your file and then modify it to include the correct parameter according to your CRM customization (see previous post) :
    1: public class SendSMS : IPlugin

    2: {

    3: public void Execute(IServiceProvider serviceProvider)

    4: {

    5: IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

    6: 

    7: // TODO - If you require tracing, uncomment the following line

    8: ITracingService trace = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

    9: 

    10: Entity entity = null;

    11: 

    12: // Check if the InputParameters property bag contains a target

    13: // of the current operation and that target is of type Entity.

    14: if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)

    15: {

    16: // Obtain the target business entity from the input parmameters.

    17: entity = (Entity)context.InputParameters["Target"];

    18: 

    19: // TODO Test for an entity type and message supported by your plug-in.

    20: if (entity.LogicalName != "xxx_smsmessage") { return; }

    21: }

    22: else

    23: {

    24: return;

    25: }

    26: 

    27: try

    28: {

    29: if ((bool)entity.Attributes["xxx_readytosend"] == true)

    30: {

    31: // Obtain the organization service reference.

    32: IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

    33: IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

    34: 

    35: // Need to specify 'by hand' the binding and endpoint address

    36: BasicHttpBinding binding = new BasicHttpBinding();

    37: EndpointAddress ws = new EndpointAddress("http://api.clickatell.com/soap/webservice.php");

    38: // Instanciation of the Web Service client

    39: Clickatell.PushServerWSPortTypeClient client = new Clickatell.PushServerWSPortTypeClient(binding, ws);

    40: // Preparing the message

    41: string[] to = new string[1];

    42: to[0] = entity.Attributes["xxx_phonenumber"].ToString().Replace("+", "");

    43: string smsText = entity.Attributes["subject"].ToString();

    44: // Sending the message to Clickatell server

    45: string[] retCode = client.sendmsg("",

    46: API_ID,

    47: "USERNAME",

    48: "PASSWORD",

    49: to,

    50: "SENDER_ID",

    51: smsText,

    52: 0,

    53: 1,

    54: 0,

    55: 0,

    56: 3,

    57: 0,

    58: 1,

    59: 0,

    60: 0,

    61: null,

    62: 0,

    63: "SMS_TEXT",

    64: null,

    65: null,

    66: 1440);

    67: // Retrieving the message status to know if sent or not

    68: string msgId = retCode[0].ToString();

    69: retCode = client.querymsg("",

    70: API_ID,

    71: "USERNAME",

    72: "PASSWORD",

    73: msgId,

    74: null);

    75: // Looking for the status code in the return code

    76: int index = retCode[0].IndexOf("Status:");

    77: string statusCode = retCode[0].Substring(index, 11);

    78: statusCode = statusCode.Substring(statusCode.IndexOf("0"), 3);

    79: // Updating the SMS activity status and delivery info

    80: SetStateRequest smsStatus = new SetStateRequest();

    81: smsStatus.EntityMoniker = entity.ToEntityReference();

    82: switch (statusCode)

    83: {

    84: case "001":

    85: smsStatus.State = new OptionSetValue(1);

    86: smsStatus.Status = new OptionSetValue(100000002);

    87: break;

    88: case "002":

    89: case "003":

    90: case "008":

    91: case "011":

    92: smsStatus.State = new OptionSetValue(0);

    93: smsStatus.Status = new OptionSetValue(100000003);

    94: break;

    95: case "004":

    96: smsStatus.State = new OptionSetValue(1);

    97: smsStatus.Status = new OptionSetValue(2);

    98: break;

    99: case "005":

    100: case "007":

    101: case "009":

    102: case "010":

    103: smsStatus.State = new OptionSetValue(1);

    104: smsStatus.Status = new OptionSetValue(100000001);

    105: break;

    106: case "006":

    107: case "012":

    108: smsStatus.State = new OptionSetValue(2);

    109: smsStatus.Status = new OptionSetValue(3);

    110: break;

    111: default:

    112: break;

    113: }

    114: SetStateResponse resp = (SetStateResponse)service.Execute(smsStatus);

    115: }

    116: }

    117: catch (FaultException ex)

    118: {

    119: throw new InvalidPluginExecutionException("An error occurred in the plug-in.", ex);

    120: }

    121: }

    122: }


    • You have to modify the following line #: 20, 29, 42, 46 to 50, 70 to 72
  7. Your complete solution should look like this:
Now, I’m aware this code is not the best looking or the best bullet-proof C# code but it is only meant for educational purposes, so feel free to add all the error catching you want, etc. I don’t mind

Also, note that the part where I update the SMS message after getting the return code back from the Web Service does not work! The code is correct but the return message is always the same, which means that it is always kind of ‘OK’ even when it’s not

This might be due to the fact that the process is run synchronously or something like that, I don’t know and I haven’t investigated much…

Deploy your plugin

Now for the easy and last part of this post: deploying the new plugin!

  • Start the ‘Plugin Registration Tool’ found in the Microsoft CRM 2011 SDK package
  • Connect to your CRM server and to the appropriate organization
  • Register a new assembly and select your plugin’s compiled assembly
  • Once the assembly has been registered, you have to create a new step for it; in my case, I wanted to call the plugin in a new SMS message ‘Create’ event
  • Click on register new step, you’re all set!
Test your plugin

If you followed all the steps here above and modified what needed to be modified in the plugin code, you should be able to test your new plugin successfully:

  • Connect to your CRM server and go to your ‘Activities’ list
  • Create a new SMS message from the ribbon
  • Select a contact and type in its phone number (in a final customization, this field must be populated automatically according to a relationship mapping in CRM)
        • The phone number’s country code is required and must be typed without 0s or + sign
  • Click on the ‘Send SMS’ button in the ribbon… if everything goes well, you should receive a cool SMS message on your phone!


That’s it for this how-to series, I hope you enjoyed it! Feel free to put comments on this blog and remember…..you can always redirect your friends or colleagues to my posts also

Stay tuned for more how-to series in a near future.






Источник: http://www.furnemont.eu/2011/06/how-...m-2011-part-3/
__________________
Расскажите о новых и интересных блогах по Microsoft Dynamics, напишите личное сообщение администратору.
 

Похожие темы
Тема Автор Раздел Ответов Посл. сообщение
Microsoft Dynamics CRM Team Blog: Demystifying the Recurring Appointment series expansion in Microsoft Dynamics CRM 2011 Blog bot Dynamics CRM: Blogs 0 09.12.2010 02:13
Все о Microsoft Dynamics CRM: Как установить Microsoft Dynamics CRM 2011 Beta Blog bot Dynamics CRM: Blogs 0 31.10.2010 15:08
CRM DE LA CREME! Configuring Microsoft Dynamics CRM 4.0 for Internet-facing deployment Blog bot Dynamics CRM: Blogs 0 18.08.2009 11:05
Microsoft Dynamics CRM Team Blog: List Web Part for Microsoft Dynamics CRM 4.0 Deployment Scenarios Blog bot Dynamics CRM: Blogs 0 30.01.2009 22:05
Microsoft Dynamics CRM Team Blog: List Web Part for Microsoft Dynamics CRM 4.0: Understanding Connections Blog bot Dynamics CRM: Blogs 0 20.01.2009 02:07
Опции темы Поиск в этой теме
Поиск в этой теме:

Расширенный поиск
Опции просмотра

Ваши права в разделе
Вы не можете создавать новые темы
Вы не можете отвечать в темах
Вы не можете прикреплять вложения
Вы не можете редактировать свои сообщения

BB коды Вкл.
Смайлы Вкл.
[IMG] код Вкл.
HTML код Выкл.
Быстрый переход

Рейтинг@Mail.ru
Часовой пояс GMT +3, время: 00:39.