Plugin to set records' names automatically

On each projects there are entities we can't force user to set names for (because it is needless). However it is good approach if all you records has names, especially if you have to choose these records in lookups.

I use plugins to set names of such entities. To simplify development of such plugins I did a base class and want to share it with you.

Let me show you example of the plugin which is based on SetNamePluginBase (base plugin) I share below.

10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
using ExitoConsulting.Plugins.Base;
using Microsoft.Xrm.Sdk;
 
namespace ExitoConsulting.Plugins
{
    public class OwnerSetName : SetNamePluginBase
    {
        protected override string GetName(Entity entity, IPluginExecutionContext context, IOrganizationService service)
        {
            var fullName = entity.GetAttributeValue<string>("ec_fullname");
            var clientId = entity.GetAttributeValue<string>("ec_clientid");
 
            if(string.IsNullOrEmpty(fullName))
            {
                return null;
            }
 
            var name = fullName;
            if(!string.IsNullOrEmpty(clientId))
            {
                name = name + string.Format(" - {0}", clientId);
            }
 
            return name;
        }
    }
}</string></string>


Base class (SetNamePluginBase) I used in example above:
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
using System;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Xrm.Sdk.Messages;
 
namespace ExitoConsulting.Plugins.Base
{
    /// <summary>
    /// Base calass for plugins for setting names of records
    /// </summary>
    public abstract class SetNamePluginBase : IPlugin
    {
        /// <summary>
        /// Entry point. CRM is calling this method as soon as appropriate event take place.
        /// </summary>
        /// <param name="serviceProvider">
        public void Execute(IServiceProvider serviceProvider)
        {
            // Getting Plugin Execution Context
            var context = GetContext(serviceProvider);
 
            // Getting Organization Service
            var service = GetService(serviceProvider);
 
            // Retrieving current record from the server
            var entity = GetTargetEntity(context, service);
 
            // Getting primay attribute name (it could be name, subject, topic and so on.)
            var attributeName = GetEntityPrimaryNameAttribute(service, entity.LogicalName);
 
            if (attributeName == null)
            {
                return;
            }
 
            // Getting current name of the record
            var oldName = entity.GetAttributeValue<string>(attributeName);
 
            // Calculating new name for a record
            var name = GetName(entity, context, service);
 
            if (oldName != name)
            {
                try
                {
                    // Setting new name for a record
                    var toUpdate = GetEmptyEntity(entity);
                    toUpdate.Attributes.Add(attributeName, name);
                    service.Update(toUpdate);
                }
                catch
                {
 
                }
            }
        }
 
        /// <summary>
        /// This method have to be overridden in your plugin. The goal is to create a name for provided entity
        /// </summary>
        /// <param name="entity">Entity we have to create name for
        /// <param name="context">Plugin execution context
        /// <param name="service">Organization Service
        /// <returns></returns>
        protected abstract string GetName(Entity entity, IPluginExecutionContext context, IOrganizationService service);
 
        #region Private Methods
        /// <summary>
        /// Returns Organization Service
        /// </summary>
        /// <param name="serviceProvider">Service Provider
        /// <returns>Organization Service</returns>
        private IOrganizationService GetService(IServiceProvider serviceProvider)
        {
            var context = GetContext(serviceProvider);
            IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            return factory.CreateOrganizationService(context.UserId);
        }
 
        /// <summary>
        /// Returns Plugin Execution Context
        /// </summary>
        /// <param name="serviceProvider">Service Provider
        /// <returns>Plugin Execution Context</returns>
        private IPluginExecutionContext GetContext(IServiceProvider serviceProvider)
        {
            return (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
        }
 
        /// <summary>
        /// Returns Target Entity Reference
        /// </summary>
        /// <param name="context">Plugin Execution Context
        /// <returns>Target Entity Reference</returns>
        private EntityReference GetTargetReference(IPluginExecutionContext context)
        {
            object target = context.InputParameters["Target"];
            if (target is Entity) return ((Entity)target).ToEntityReference();
            if (target is EntityReference) return ((EntityReference)target);
 
            throw new InvalidPluginExecutionException("Plug-in failed while retrieving target entity reference.");
        }
 
        /// <summary>
        /// Returns Target Entity
        /// </summary>
        /// <param name="context">Plugin Execution Context
        /// <param name="service">Organization Service
        /// <returns>Target Entity</returns>
        private Entity GetTargetEntity(IPluginExecutionContext context, IOrganizationService service)
        {
            var targetReference = GetTargetReference(context);
            return service.Retrieve(targetReference.LogicalName, targetReference.Id, new ColumnSet(true));
        }
 
        /// <summary>
        /// Returns Entity Primary Attribute Name
        /// </summary>
        /// <param name="service">Organization Service
        /// <param name="entityName">Logical Name of the Entity
        /// <returns>Primary Attribute Name</returns>
        private string GetEntityPrimaryNameAttribute(IOrganizationService service, string entityName)
        {
            var metadata = GetEntityMetadata(service, entityName);
 
            if (metadata != null)
            {
                return metadata.PrimaryNameAttribute;
            }
 
            return null;
        }
 
        /// <summary>
        /// Returns Entity Metadata
        /// </summary>
        /// <param name="service">Organization Service
        /// <param name="entityName">Logical Name of the Entity
        /// <returns>Entity Metadata</returns>
        private EntityMetadata GetEntityMetadata(IOrganizationService service, string entityName)
        {
 
            var retrieveRequest = new RetrieveEntityRequest
            {
                EntityFilters = EntityFilters.Entity,
                LogicalName = entityName
            };
 
            // Execute the request.
            var response = (RetrieveEntityResponse)service.Execute(retrieveRequest);
 
            return response.EntityMetadata;
        }
 
        /// <summary>
        /// Returns empty entity for update request
        /// </summary>
        /// <param name="entity">Entity you want to update
        /// <returns>Empty entity created based on provided entity</returns>
        private Entity GetEmptyEntity(Entity entity)
        {
            var emptyEntity = new Entity()
            {
                Id = entity.Id,
                LogicalName = entity.LogicalName
            };
 
            return emptyEntity;
        }
 
        #endregion
    }
}</string>
You can download Visual Studio project here:

1 comments:

:)
:(
=(
^_^
:D
=D
|o|
@@,
;)
:-bd
:-d
:p