Sunday, October 12, 2008

CRM 4.0 Creating Activities

When importing activities or creating them for a process, there are three important Steps.

  1. Create the Activity relating it to all appropriate entities.
  2. (Optional) Attach a file using an Annotation or ActivityMimeAttachment
  3. Set the State of the Activity

MS CRM has numerous Activities. They are all part of an ActivityPointer Entity, but we won't work with that directly.  We will directly create task, email, letter, appointment, and phonecall entities. I'll cover Campaign and Service Activities another day.

Activities need to be related with a number of entities before they are useful.

Activities need

  1. An owner, a systemuser who is responsible for carrying an activity out.
  2. A regardingobject, the entity the activity is related to, like a Contact, Opportunity or Account.
  3. Numerous activityparty arrays for holding the different types of related entities that this activity affects. For example an email could cc: a systemuser and a contact, and there is a cc activityparty array for an email.
  4. Any file attachments in the form of an annotation or activitymimeattachment
  5. Start and End dates Scheduled and Actual.
  6. A state/status combination
    1. Active will show up in the owners WorkPlace Activities and under the regardingobject entity and possible rollup to an entity above that.
    2. Inactive - will show up in history under the regardingobject and possible rollup to an entity above that.

Setting up each activity is very similar. Below is some example code that creates a phonecall, and completes that activity.

Notice the following in the code sample:

  • The activityparty arrays that allow any number of systemuser, contact, account and lead entities to be related to an activity.
  • The SetStatePhoneCallRequest to set the state of the phonecall to completed. The PhoneCallStatus of 2 for outgoing. You can refer to the following link for this and find other state enumerations required to set the state and status of all entities. Link to MSDN PhoneCallState Enumeration
  • I use the CRM SDK CrmTypes and other Enumeration helpers. They come in handy so why not?
var newphoneCall = new phonecall
  {
      ownerid = CrmTypes.CreateOwner(EntityName.systemuser.ToString(), activityOwnerId),
      from = new[]
          {
              new activityparty
                  {
                      participationtypemask = CrmTypes.CreatePicklist(ActivityPartyType.Sender),
                      partyid = CrmTypes.CreateLookup(EntityName.systemuser.ToString(), activityOwnerId)
                  }
          },
      subject = subject,
      description = description,
      regardingobjectid = (matchedContact) ? CrmTypes.CreateLookup(EntityName.contact.ToString(), relatedContactId) : null,
      to =  (!matchedContact)? null : new []
         {
            new activityparty
              {
                  participationtypemask = CrmTypes.CreatePicklist(ActivityPartyType.ToRecipient),
                  partyid = CrmTypes.CreateLookup(EntityName.contact.ToString(), relatedContactId)
              }
         },
      scheduledstart = CrmTypes.CreateCrmDateTime(Convert.ToDateTime(scheduledStart).ToShortDateString()),
      actualstart = CrmTypes.CreateCrmDateTime(Convert.ToDateTime(scheduledStart).ToShortDateString()),
      scheduledend = CrmTypes.CreateCrmDateTime(Convert.ToDateTime(scheduledEnd).ToShortDateString()),
      actualend = (isComplete) ? CrmTypes.CreateCrmDateTime(Convert.ToDateTime(scheduledEnd).ToShortDateString()) : null,
  };

try
  {
      Guid phonecallId = service.Create(newphoneCall);

      if (isComplete)
      {
          var request = new SetStatePhoneCallRequest
              {
                  EntityId = phonecallId,
                   PhoneCallState = PhoneCallState.Completed,
                   PhoneCallStatus = 2
              };

          try
          {
              service.Execute(request);
          }

          catch (SoapException ex)
          {
              string errormsg = String.Format("Update Error Setting PhoneCall State to Complete error {0}", ex.Detail.InnerText);
              WriteErrorFile(errormsg);
          }
      }

  }
catch (SoapException ex)
   {
       string errormsg = String.Format("Write Error for PhoneCall {0} error {1}", row[(int) tblCal.ACTVCODE], ex.Detail.InnerText);
       WriteErrorFile(errormsg);
   }

Next: My next post will cover importing files into CRM in the form of annotations and activitymimeattachments as well as mimeTypes, and CRM file size limitations and their configuration.

Monday, October 6, 2008

MS CRM Data Import (Cleaning up the Mess)

 

Before importing data into CRM it, I think it is important to know how to get it back out, how long it will take to get it back out, or how to get back to a clean state.

Why is that?

1. Time Estimation!  Creating a CRM record is FAST. Deleting a CRM record can be VERY slow!  There is a reason for this. When you create a new Account, there is a new record added to a Base and Extension base table. That's pretty simple! When you delete an Account, CRM checks for all of the dependencies and potentially deletes a number of child records in other tables, verifies that there are no records that restrict the deletion of a parent and finally deletes the Account.

To drive this home, using my import framework, I recently imported about 34,000 contacts from an Access database into a CRM system running on a VPC image on my laptop. It took 24 minutes to import these contacts, while updating associated accounts with primary contacts where applicable. However it took about 8 hours just to delete these Contacts! Granted, a VPC image running off of a single core of a laptop is going to be very slow in comparison to most production systems, but many imports are MUCH larger than 34,000 contacts.

2. Some data doesn't want to be deleted! Some CRM entities end up in a state where the CRM web service can not delete them.  Let's say that you import a company's Contracts with the expiration dates set. MS CRM being the smart system that it is will start changing the state of all contracts with a past expiration date to "Expired". This is a neat feature, but now you can not delete that entity. In fact you can not even set the state of that contract back to draft using web services so that you can delete it. There is a work around for this, but it is unsupported and requires using SQL.

3. Data must be removed in sequence! Because there are lots of relationships between entities in CRM, removing data typically means deleting data in the reverse order of your imports.  So that the last things that you can typically delete are the Contacts and then the Accounts. You must delete Quotes, Orders, and Invoices before the related Opportunities, etc. You must be aware of the data's hierarchy.

4. The Deletion Service. When you delete an entity using the CRM web service, the entity is being marked with a flag to be deleted after the Deletion Service runs. With MS CRM 4.0 that happens once a day by default, however you can use the CRM 4 Scale Group Job Editor to adjust that. With CRM 3.0 the default was every two hours and it could be adjusted with a registry setting. Knowing when this service runs is important if you want to back up a clean database.

Best Practices - Data Import Cleanup

Strong Suggestion! Use a Test system or VPC image for data import testing. Some of the methods I am going to cover for data cleanup are unsupported by MS. It is much better than you do all of your import testing on something other than the production CRM system.

The Quick Reset to Ground Zero

  1. When your base configuration and data are clean, and the Deletion service has finished running, back up the database pair MSCRM_CONFIG, and <BaseBUName>_MSCRM to a safe place.
  2. When you need to clean out your imported data, export your Customizations to a safe area then restore both databases and import and publish your customizations.

 

This is a great way to do things as long as you can keep track of any configuration changes between resets. However sometimes you may have hours invested in getting everything imported to a certain state and you just need to remove just the last thing that you imported and it would take more time to reset your system and import everything up to that point.

Proceed at your own risk! To reset your database bringup SQL Server Management Studio under Management-> activityMonitor to find the processes blocking your CRM database. Stop all of the CRM Services and IIS, then refresh the activityMonitor to see what is left. If there is anything left, then kill that process and when the activityMonitor is clear of references to your databases you can restore like below.

Alter Database MicrosoftCRM_MSCRM
  SET SINGLE_USER With ROLLBACK IMMEDIATE 

  RESTORE DATABASE MicrosoftCRM_MSCRM
  FROM DISK = 'C:\MicrosoftCRM_MSCRM.bak'

use Master 
Alter Database MicrosoftCRM_MSCRM 
  SET MULTI_USER WITH ROLLBACK IMMEDIATE;
Make sure to also do this for your CONFIG database. This will most likely require a reboot when you are finished.
Alter Database MSCRM_CONFIG
  SET SINGLE_USER With ROLLBACK IMMEDIATE 

  RESTORE DATABASE  MSCRM_CONFIG 
  FROM DISK = 'C:\MSCRM_CONFIG.bak'
  WITH REPLACE

use Master 
Alter Database MSCRM_CONFIG 
  SET MULTI_USER WITH ROLLBACK IMMEDIATE;
The Surgical Cleanup

This is when knowledge of the relationships between your entities and the requirements to put an entity into a state that allows deletion are important.

Example:  Cleaning up Contracts

Below you can see the BackgroundWorker DoWork method called from my CRM Import Winform Application. Every Import has a "Delete All" button, and a progress bar to allow an easy check the progress by glancing over at it.

        /// <summary>
        /// Delete Entity
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void deleteWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            var arg = (ImportArguments)e.Argument;

            var crmService = new webserviceHelper(arg.errorFile, arg.logFile);

            // Returns a collection with only the entity's id to use for deletion
            BusinessEntityCollection deleteCollection = crmService.GetEntitiesForDelete(EntityName.contract.ToString(), "contractid");

            float progressCount = 0;
            float progressTotal = (float) deleteCollection.BusinessEntities.Length;

            var directAccess = new crmdb();
            
            // Sets all Contracts into a Draft state and clear Originating Contract.
            directAccess.ClearContractsforDelete();

            foreach (contract deleteEntity in deleteCollection.BusinessEntities)
            {
                
                if (deleteWorker.CancellationPending)
                {
                    return;
                }

                // Update ProgressBar
                progressCount++;
                deleteWorker.ReportProgress((int)((progressCount / progressTotal) * 100));
               
                try
                {
                  crmService.service.Delete(entity, deleteEntity.contractid.Value);
                }

                catch(SoapException ex)
                {
                    MessageBox.Show(ex.Detail.InnerXml, string.Format("Delete {0}s Failed", entity), MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
Below is the SQL that is called to remove references to any Originating Contracts, and to put the Contract in a Draft state so that it can be deleted.
        /// <summary>
        /// PutsContract in a Draft state so it can not be deleted.
        /// NOTE: This is temporary as CRM will periodically start to mark contracts as expired!
        /// </summary>
        public void ClearContractsforDelete()
        {
            using (var connection = new SqlConnection(crmConnectionString))
            {
                connection.Open();

                string command = string.Format(
                    @"UPDATE dbo.ContractBase
                        SET 
                        StateCode = 0      
                        ,StatusCode = Null      
                        ,OriginatingContract = Null "
                );

                var cmd = new SqlCommand(command, connection);
                cmd.ExecuteNonQuery();
            }
        }

There is very similar logic for invoices, and quotes. Other entities like opportunities can be re-opened and then deleted.

Wednesday, October 1, 2008

Importing Data into MS CRM - Overview

MS CRM is a great place to permanently consolidate data silos, which could be in Excel, Access, external SQL databases or any other data source, but there are also many useful reasons for bringing data into CRM periodically or just having CRM accessing external data stores.

Integrating MS CRM with the rest of the world is a passion of mine and pulling data into CRM, driving CRM with external data and sharing data from CRM to drive external processes is key to powerful integration.

I put CRM data exchanges into a number categories.

  1. One Shot: Initial Imports from systems replaced by CRM.
  2. Scheduled Imports: Ongoing data pulled from another system.
  3. Synchronization: Synchronization with an external database.
  4. Business Process drivers: External data is consulted to start business processes within CRM.
  5. Integration: CRM and another application share data with each other.
  6. External Control: CRM drives external processes

What I would like to do is examine these topics and share some of the tools and parts of my import framework over the next few months.

I think that this is a good point to mention Scribe. I have used Scribe, but none of my tools or examples will be for Scribe.  Scribe has an excellent reputation and is a valuable tool for many. They also offer numerous connectors for moving data between CRM and other mainstream applications. I highly recommend Scribe if you are not a developer familiar with the CRM SDK.

Since I consider myself a .NET developer first, I have found that working with the SDK gives me a lot more low level control and flexibility, and none of my code or methods will require the purchase of a 3rd party tool.

Development side note: While developing my data import framework which uses CRM web services, I had to work with MS to find out why my application kept crashing.  It turned out that it was importing records so quickly that the web services were overloading the TCP/IP Sockets on the W2003 Server. The fix was to modify the registry settings to both drastically increase the number of Sockets available and to reduce the recycle time that that Sockets would sit idle before being reclaimed for reuse. This may not have been a big deal in the grand scheme of things, but that didn't stop me from having a brief Tim Allen moment when I found out that I completely blew by the default settings for W2003 :)

Saturday, September 20, 2008

Hint: Mapping Data Tables for CRM Imports

When importing data into a CRM database, there is an easy way to create current mapping tables.

First take the url for your CRM server and append /sdk/list.aspx to it.
example.  http://crmserver1:5555/sdk/list.aspx

That will give you a current listing of all of your entities with customizations.
Then click a particular appropriate entity to get a screen like the one below.

entityfieldbrowser

That's very informative, but we want to re-purpose this for use in a data import mapping table.

  1. Right click -> View Source
  2. Ctrl A  ( select all of the raw HTML )
  3. Ctrl C  ( copy it to your clipboard )
  4. Now open up excel. Excel is really accepting of a lot of data formats these days and most customers like to work in Excel Spreadsheets
  5. Paste that RAW HTML into a spreadsheet
  6. Do a little formatting and remove what you don't need.

Now you have CRM Entity import tables reflecting any customizations that you have made.

excel_entitymap

Monday, September 15, 2008

Hint: Developing for Multiple MS CRM 4.0 Servers

Ideally CRM custom application development is not being done on production CRM systems. It would be helpful if our custom applications would automatically switch between the appropriate web services of development, staging and production CRM environments.

The method below creates the appropriate CrmServiceUrl using the ServerUrl value in the registry of the CRM server running the custom application.

using Microsoft.Win32;  // For registry access
using crmWebService;    // Your crm webservice reference

// <snip>

    // Create a web service for your organization.     
    CrmService service = InitCRMWebService("MicrosoftCRM");    
        
    //Use service

// <snip>

    
    /// <summary>
    /// Get the crmservice for the organization specified
    /// </summary>
    /// <param name="organizationName"></param>
    /// <returns></returns>
    private CrmService InitCRMWebService(string organizationName)
    {
        // Create the CrmServiceUrl from the registry
        RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\MSCRM", false);
        string CrmServiceUrl = (string)key.GetValue("ServerUrl") + @"/2007/crmservice.asmx";
        
        service = new CrmService();
        service.Credentials = System.Net.CredentialCache.DefaultCredentials;
        service.Url = CrmServiceUrl;
        service.PreAuthenticate = false;
        
        CrmAuthenticationToken token = new CrmAuthenticationToken();
        token.AuthenticationType = 0;
        token.OrganizationName = organizationName;

        service.CrmAuthenticationTokenValue = token;
        
        return service;
    }
For debugging:
  1. Make sure that your local Active Directory account is a CRM user on all of environments that you will debug against.
  2. Export a copy of the MSCRM registry from your CRM server and apply it to your development computer's registry.
  3. Modify the ServerUrl value data to switch between the servers that you are debugging against.

 

Wednesday, September 10, 2008

Business Units, Opportunities and SQL Recursion

When generating reports in MS CRM you typically want to generate reports using the filtered Views so that all of the security rules are enforced. It is really powerful to be able to see everything you are allowed to see automatically. However in this example we are going to use the non-filtered views.

This started off as a simple question on the developer forums. "How do I total the Opportunity Value by business Unit totaling child business units?"

What it turned into was a SQL recursive CTE exercise. This basic framework could be used to total any entity by Business Unit hierarchy.

For this example we first need a function to total the EstimatedValue for each Opportunity in a Business Unit.

You probably want to look at the following function very closely and see what you need to customize. You may want to total something besides an Opportunity, or if you do want to accumulate Opportunities, you may want to filter on SalesStageCode, State or StatusCode. For example you may want all Opportunities with a Status Code of 1 and a StateCode of 0, which is what I have in the example below.  You may also want to look at OpportunityClose Entities to see which Opportunities closed in a certain time period. Here is where you use your imagination to create the cool information that you or your customer wants.

-- Function: OpportunitySum
--
-- Gets the Sum of Opportunity EstimatedValues by BUid
--
--
alter Function OpportunitySum(@buId uniqueidentifier)
returns float
as
begin
declare @sum float

select @sum = Sum(Opportunity.EstimatedValue) 
from Opportunity  
where OwningBusinessUnit = @buId
and StateCode = 0
and StatusCode = 1
and SalesStageCode = 1

return isnull(@sum, Cast(0 as float))
end

Then it would be nice to know the number of child Business Units to help order the hierarchy. So we will create our first recursive CTE. This one simply counts child business units.

-- Recursive counts Business units below a parent business unit
--
--
alter Function ChildBuCount(@buId uniqueidentifier)
returns float
as
begin
declare @count int;
with ChildBuCount ( Id )
as
(
select base.BusinessUnitId 
from BusinessUnit base Where base.ParentBusinessUnitId = @buid
union all
select  bb.BusinessUnitId 
from BusinessUnit bb 
join ChildBuCount cc on cc.Id = bb.ParentBusinessUnitId
)
select @count = count(*) from ChildBuCount
return @count
end

Next is something a little trickier. This function calls the OpportunitySum() function we created earlier as part of the recursion, so I broke it down by section.

--  Recursive sums Opportunity EstimatedValue for all child Business Units
--
--
alter Function OpportunityValue(@buId uniqueidentifier)
returns float
as
begin
declare @estimate float;
with OpportunityValue ( Id, estimate )
as
(
-- Anchor member definition
select initbb.BusinessUnitId, dbo.OpportunitySum( initbb.BusinessUnitId )
from BusinessUnit as initbb Where initbb.ParentBusinessUnitId = @buid
 
union all
 
-- Recursive member definition
select bb.BusinessUnitId,  dbo.OpportunitySum( bb.BusinessUnitId ) 
from BusinessUnit bb 
join OpportunityValue ov on ov.Id = bb.ParentBusinessUnitId
)
 
-- Statement that executes the CTE
select @estimate = Sum(estimate) from OpportunityValue
return @estimate
end

What is critical to this CTE is that the OpportunitySum function has to be included in the anchor for this to work. Now lets call all of this in a way that generates something useful.

-- Top level select that selects all Business Units
--
--
select             
        isnull( parent.Name, 'None') as 'Parent Business Unit',    
        bb.Name as 'Business Unit',
        dbo.OpportunitySum(bb.BusinessUnitId) + 
        isnull(dbo.OpportunityValue(bb.BusinessUnitId),0) as 'Total Opportunity Value',
        dbo.OpportunitySum(bb.BusinessUnitId) as 'My Opportunity Value', 
        isnull(dbo.OpportunityValue(bb.BusinessUnitId),0) as 'My Children Opportunity Value',
        dbo.ChildBuCount( bb.BusinessUnitId ) as Children            
from BusinessUnit bb
left outer join BusinessUnit parent on parent.BusinessUnitId = bb.ParentBusinessUnitId
order by Children desc

Finally we get the results. This shows 4 business units that are 3 levels deep, but it should work for any number or depth of BU's.

  Parent Business Unit Business Unit Total Opportunity Value My Opportunity Value My Children Opportunity Value Children
1 None MicrosoftCRM 45550 0 45550 3
2 MicrosoftCRM East Coast 25000 25000 0 0
3 MicrosoftCRM West Coast 20550 5550 15000 1
4 West Coast California 15000 15000 0 0

Thursday, August 28, 2008

Invoking MS CRM from other applications

The Active Directory security model of MS CRM is amazingly flexible and allows  powerful control inside of CRM, but when integrating with systems outside of CRM, AD security really shines.

One of the great things about AD security is that your users do not have to log into CRM after they are logged into a domain on their computers. This means that third party programs can just call into CRM with web services to get information as they need it. Reporting services written against the filtered views only show CRM users what they are allowed to see and CRM forms can be pulled up whenever it is convenient.

CRM from Links
Since CRM is a web application ANY entity form can be opened directly from Internet Explorer. Below is an example link to a specific contact.

http://crmserver1:5555/MicrosoftCRM/sfa/conts/edit.aspx?id={DE1F590A-37D0-DC11-AA32-0003FF33509E}#

Application: Directly accessing a CRM entity can be really handy for email messages generated from CRM, as you can send an email to the appropriate person with a link to an an entity requiring attention and even send instructions telling them what to do with it once they click on the link. In this way users require less training and have faster access to the information they need.

Implementation Details: Just create one mail group in exchange for each of the applicable types of mail they you need ( ie. CRMerrors, CRMmaint, CRMreports, etc... ). This way IT can administrate who gets the email without touching the CRM servers. Mail relaying from the CRM server to the Exchange Server will need to be set up first. Scheduled status emails with links for additional information could be routed to CRMreports, all your exceptions could be sent to CRMerrors, and anything that a business rule picks up on during the running of a plugin can email CRMmaint with a link to the entity in question with an explanation of what needs to be addressed. This can be useful with marginal data that is imported from another system and needs some massaging, or anything else that is flagged by internal business rules requiring decisions.

Hint: If you need a link for an specific entity, but that part of explorer is hidden, type <CTRL>N and a new fully functional browser will show up that you can cut a URL from or use other tools like the Web Accessibility Toolbar to examine the markup.

CRM from the command line
From the command line you can also open that page which could be useful for batch files.

C:\ @start "" /b "iexplore.exe"http://crmserver1:5555/MicrosoftCRM/sfa/conts/edit.aspx?id={DE1F590A-37D0-DC11-AA32-0003FF33509E}#

CRM from another application
Another application can automatically pop an entity up on the screen whenever some trigger occurs.

// Get contactID from information passed to auto dialer client
string contactId = "{DE1F590A-37D0-DC11-AA32-0003FF33509E}";

var proc = new System.Diagnostics.Process();
proc.EnableRaisingEvents=false;
proc.StartInfo.FileName="iexplore";
proc.StartInfo.Arguments = String.Format("http://crmserver1:5555/MicrosoftCRM/sfa/conts/edit.aspx?id={0}#", contactId);
proc.Start();
Application: Most auto dialers have a client that is customizable to do "screen pops" or to open a specific application when a call is connected to their phone. Ideally CRM has the marketing list stored and is generating the auto dialer lists that include some unique information like a Lead or Contact Guid, or at a bare minimum some unique information that can be queried against in CRM. Now your call center person can immediate do things related to that contact without having to look that contact up or even log into CRM, or by using CRM web services a related entity like an opportunity or a campaign could be popped instead.

Implementation details: If CRM is generating your auto dialer lists then make sure to include the appropriate guid of the entity that you want to pop with the data sent to the client. If your auto dialer is fed from another source, you might want to re-examine that. CRM imports leads from many sources very easily and creating auto dialer data from a Campaign associated with a given marketing list works very well. Then you want to make sure that your auto dialer client also tracks the results from a call so that you can use web services to create a Campaign Response record in CRM to track how successful your Campaign was.