Exemple #1
0
        protected void Delete(IServiceProvider serviceProvider, string entityName)
        {
            try
            {
                IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
                if (context.MessageName != MessageName.Delete)
                {
                    //Invalid event attached
                    return;
                }

                IOrganizationServiceFactory          serviceFactory        = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService                 service               = serviceFactory.CreateOrganizationService(context.UserId);
                Configuration.IConfigurationProvider configurationProvider = Configuration.Factory.GetConfigurationProvider(service, entityName);
                if (configurationProvider.StorageProviderType == Providers.BinaryStorageProviderType.CrmDefault)
                {
                    //In this case, not doing anything.
                    return;
                }

                Providers.IBinaryStorageProvider storageProvider = Providers.Factory.GetStorageProvider(configurationProvider);
                storageProvider.Delete(context.PrimaryEntityId);
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(OperationStatus.Suspended, ex.ToString());
            }
        }
Exemple #2
0
        private void HandleEntity(IOrganizationService service, Guid userId, Providers.IBinaryStorageProvider storageProvider, Entity entity, string documentBodyAttributeKey, string fileNameAttributeKey)
        {
            try
            {
                if (!(entity.Attributes.ContainsKey(CrmConstants.FileSizeKey) || entity.Attributes.ContainsKey(documentBodyAttributeKey)))
                {
                    //If none of these columns are queried, we don't have to do anything, as it will just return whatever is in base tables.
                    return;
                }

                Entity attachementExtensionEntity = null;
                if (UserHasPrivilege(service, userId, string.Format(GenericConstants.AttachmentExtensionPrivilegeTemplate, "Read")))
                {
                    try
                    {
                        //If the file size is requested it's currently equal to the "empty body" length, need to redirect the value
                        //Retrieve the attachment extension record
                        var query = new QueryExpression(GenericConstants.AttachementExtensionEntityName);
                        query.ColumnSet = new ColumnSet(GenericConstants.AttachementExtensionFileSizeKey);
                        query.Criteria  = new FilterExpression(LogicalOperator.And);
                        query.Criteria.AddCondition(GenericConstants.AttachementExtensionEntityNameKey, ConditionOperator.Equal, entity.LogicalName);
                        query.Criteria.AddCondition(GenericConstants.AttachementExtensionEntityIdKey, ConditionOperator.Equal, entity.Id.ToString());
                        attachementExtensionEntity = service.RetrieveMultiple(query).Entities.SingleOrDefault();
                    }
                    catch
                    {
                    }
                }

                if (entity.Attributes.ContainsKey(CrmConstants.FileSizeKey) && ((int)entity.Attributes[CrmConstants.FileSizeKey] == GenericConstants.EmptyBodyContentDataLength))
                {
                    if (attachementExtensionEntity != null)
                    {
                        //Return the filesize from the attachments table, since crm automatically sets it to 3 when setting "empty" body contents
                        entity.Attributes[CrmConstants.FileSizeKey] = attachementExtensionEntity.Attributes[GenericConstants.AttachementExtensionFileSizeKey];
                    }
                    else
                    {
                        try
                        {
                            entity.Attributes[CrmConstants.FileSizeKey] = storageProvider.GetFileSize(entity.Id, (string)entity.Attributes[fileNameAttributeKey]);
                        }
                        catch { }
                    }
                }

                if (entity.Attributes.ContainsKey(documentBodyAttributeKey) &&
                    (string)entity.Attributes[documentBodyAttributeKey] == GenericConstants.EmptyBodyContent &&
                    entity.Attributes.ContainsKey(fileNameAttributeKey))
                {
                    //If the body is requested, go fetch it and populate it where CRM wants it
                    byte[] data = storageProvider.Read(entity.Id, (string)entity.Attributes[fileNameAttributeKey]);
                    entity.Attributes[documentBodyAttributeKey] = Convert.ToBase64String(data);
                }
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(OperationStatus.Failed, ex.ToString());
            }
        }
        private void HandleEntity(IOrganizationService service, Guid userId, Providers.IBinaryStorageProvider storageProvider, Entity entity, string documentBodyAttributeKey, string fileNameAttributeKey)
        {
            try
            {
                if (!(entity.Attributes.ContainsKey(documentBodyAttributeKey) || entity.Attributes.ContainsKey(CrmConstants.FileSizeKey)))
                {
                    //If none of these columns are queried, we don't have to do anything, as it will just return whatever is in base tables.
                    return;
                }

                if (entity.Attributes.ContainsKey(CrmConstants.FileSizeKey) &&
                    (int)entity.Attributes[CrmConstants.FileSizeKey] == GenericConstants.EmptyBodyContentDataLength &&
                    entity.Attributes.ContainsKey(fileNameAttributeKey))
                {
                    entity.Attributes[CrmConstants.FileSizeKey] = storageProvider.GetFileSize(entity.Id, (string)entity.Attributes[fileNameAttributeKey]);
                }

                if (entity.Attributes.ContainsKey(documentBodyAttributeKey) &&
                    (string)entity.Attributes[documentBodyAttributeKey] == GenericConstants.EmptyBodyContent &&
                    entity.Attributes.ContainsKey(fileNameAttributeKey))
                {
                    //If the body is requested, go fetch it and populate it where CRM wants it
                    byte[] data = storageProvider.Read(entity.Id, (string)entity.Attributes[fileNameAttributeKey]);
                    entity.Attributes[documentBodyAttributeKey] = Convert.ToBase64String(data);
                }
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(OperationStatus.Failed, ex.ToString());
            }
        }
        protected void Retrieve(IServiceProvider serviceProvider, string entityName, string documentBodyAttributeKey, string fileNameAttributeKey)
        {
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

            if (context.MessageName != MessageName.Retrieve && context.MessageName != MessageName.RetrieveMultiple)
            {
                //Invalid event attached
                return;
            }

            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

            Configuration.IConfigurationProvider configurationProvider = Configuration.Factory.GetConfigurationProvider(service, entityName);
            if (configurationProvider.StorageProviderType == Providers.BinaryStorageProviderType.CrmDefault)
            {
                //In this case, not doing anything.
                return;
            }

            Providers.IBinaryStorageProvider storageProvider = Providers.Factory.GetStorageProvider(configurationProvider);

            //This case handles where IOrganizationService is called with "LoadProperty".  For this, you need to attach this plugin to the "Retrieve" method of the parent Entity.
            if (context.OutputParameters.ContainsKey(CrmConstants.BusinessEntityKey) &&
                context.OutputParameters[CrmConstants.BusinessEntityKey] is Entity &&
                ((Entity)context.OutputParameters[CrmConstants.BusinessEntityKey]).RelatedEntities != null &&
                ((Entity)context.OutputParameters[CrmConstants.BusinessEntityKey]).RelatedEntities.Values is ICollection <EntityCollection> &&
                ((Entity)context.OutputParameters[CrmConstants.BusinessEntityKey]).RelatedEntities.Values.Count > 0)
            {
                foreach (EntityCollection entityCollection in ((Entity)context.OutputParameters[CrmConstants.BusinessEntityKey]).RelatedEntities.Values.Where(ec => ec.EntityName == entityName))
                {
                    entityCollection.Entities.ToList().ForEach(e => HandleEntity(storageProvider, e, documentBodyAttributeKey, fileNameAttributeKey));
                }
            }
            else if (context.MessageName == MessageName.Retrieve && context.OutputParameters.Contains(CrmConstants.BusinessEntityKey) && context.OutputParameters[CrmConstants.BusinessEntityKey] is Entity)
            {
                Entity entity = (Entity)context.OutputParameters[CrmConstants.BusinessEntityKey];
                if (entity.LogicalName != entityName)
                {
                    return;
                }
                HandleEntity(storageProvider, entity, documentBodyAttributeKey, fileNameAttributeKey);
            }
            else if (context.MessageName == MessageName.RetrieveMultiple && context.OutputParameters.Contains(CrmConstants.BusinessEntityCollectionKey) && context.OutputParameters[CrmConstants.BusinessEntityCollectionKey] is EntityCollection)
            {
                EntityCollection entityCollection = (EntityCollection)context.OutputParameters[CrmConstants.BusinessEntityCollectionKey];
                if (entityCollection.TotalRecordCount > 0 && entityCollection.Entities.First().LogicalName != entityName)
                {
                    return;
                }
                entityCollection.Entities.ToList().ForEach(e => HandleEntity(storageProvider, e, documentBodyAttributeKey, fileNameAttributeKey));
            }
        }
Exemple #5
0
        public void Delete(IServiceProvider serviceProvider)
        {
            try
            {
                IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
                if (context.MessageName != MessageName.Delete)
                {
                    //Invalid event attached
                    return;
                }

                if (!context.PreEntityImages.ContainsKey(PreDeleteImageKey) || context.PreEntityImages[PreDeleteImageKey] == null)
                {
                    throw new InvalidPluginExecutionException(OperationStatus.Failed, string.Format("PreEntityImage could not be found when deleting {0}", context.PrimaryEntityName));
                }
                Entity entity = context.PreEntityImages[PreDeleteImageKey];
                if (entity.LogicalName != CrmConstants.AnnotationEntityName && entity.LogicalName != CrmConstants.AttachmentEntityName)
                {
                    //only valid for attachments and annotations
                    return;
                }

                IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

                Configuration.IConfigurationProvider configurationProvider = Configuration.Factory.GetConfigurationProvider(service, entity.LogicalName, unsecurePluginStepConfiguration, securePluginStepConfiguration);
                if (configurationProvider.StorageProviderType == Providers.StorageProviderType.CrmDefault)
                {
                    //In this case, not doing anything for the external file.
                    return;
                }

                Providers.IBinaryStorageProvider storageProvider = Providers.Factory.GetStorageProvider(configurationProvider);

                if (entity.Attributes.ContainsKey(GenericConstants.Constants[entity.LogicalName][GenericConstants.FileNameAttributeKey]))
                {
                    storageProvider.Delete(entity.Id, (string)entity.Attributes[GenericConstants.Constants[entity.LogicalName][GenericConstants.FileNameAttributeKey]]);
                }
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(OperationStatus.Suspended, ex.ToString());
            }
        }
 private void HandleEntity(Providers.IBinaryStorageProvider storageProvider, Entity entity, string documentBodyAttributeKey, string fileNameAttributeKey)
 {
     try
     {
         if (entity.Attributes.Keys.Contains(fileNameAttributeKey) && ((string)entity.Attributes[fileNameAttributeKey]).StartsWith(Constants.ExternalFilePrefix))
         {
             byte[] data           = null;
             string actualFileName = ((string)entity.Attributes[fileNameAttributeKey]).Substring(Constants.ExternalFilePrefix.Length);
             entity.Attributes[fileNameAttributeKey] = actualFileName;
             if (entity.Attributes.Keys.Contains(documentBodyAttributeKey) && (string)entity.Attributes[documentBodyAttributeKey] == Constants.EmptyBodyContent)
             {
                 data = storageProvider.Read(entity.Id, actualFileName);
                 entity.Attributes[documentBodyAttributeKey] = Convert.ToBase64String(data);
             }
             if (entity.Attributes.Keys.Contains(CrmConstants.FileSizeKey))
             {
                 if (data != null)
                 {
                     entity.Attributes[CrmConstants.FileSizeKey] = data.Length;
                 }
                 else
                 {
                     entity.Attributes[CrmConstants.FileSizeKey] = storageProvider.GetFileSize(entity.Id, actualFileName);
                 }
             }
             if (entity.Attributes.Keys.Contains(CrmConstants.IsDocumentKey))
             {
                 if (entity.Attributes.Keys.Contains(CrmConstants.FileSizeKey))
                 {
                     entity.Attributes[CrmConstants.IsDocumentKey] = ((int?)entity.Attributes[CrmConstants.FileSizeKey]) > 0;
                 }
                 else
                 {
                     entity.Attributes[CrmConstants.IsDocumentKey] = false;
                 }
             }
         }
     }
     catch (Exception ex)
     {
         throw new InvalidPluginExecutionException(OperationStatus.Failed, ex.ToString());
     }
 }
Exemple #7
0
        public void Create(IServiceProvider serviceProvider)
        {
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

            if (context.MessageName != MessageName.Create)
            {
                //Invalid event attached
                return;
            }

            if (context.InputParameters.Contains(CrmConstants.TargetParameterKey) && context.InputParameters[CrmConstants.TargetParameterKey] is Entity)
            {
                try
                {
                    Entity entity = (Entity)context.InputParameters[CrmConstants.TargetParameterKey];
                    if (entity.LogicalName != CrmConstants.AnnotationEntityName && entity.LogicalName != CrmConstants.AttachmentEntityName)
                    {
                        return;
                    }

                    if (!entity.Attributes.Keys.Contains(GenericConstants.Constants[entity.LogicalName][GenericConstants.DocumentBodyAttributeKey]) || string.IsNullOrWhiteSpace((string)entity.Attributes[GenericConstants.Constants[entity.LogicalName][GenericConstants.DocumentBodyAttributeKey]]))
                    {
                        //No binary data
                        return;
                    }

                    IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                    IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

                    Configuration.IConfigurationProvider configurationProvider = Configuration.Factory.GetConfigurationProvider(service, entity.LogicalName, unsecurePluginStepConfiguration, securePluginStepConfiguration);
                    if (configurationProvider.StorageProviderType == Providers.BinaryStorageProviderType.CrmDefault)
                    {
                        //In this case, not doing anything with the binary data.
                        return;
                    }

                    //This check is actually a bit useless for sandboxed pluxings.  CRM is bugged and won't allow anything bigger than 5mb, the plugin sandbox will just crash.
                    if (entity.Attributes.Keys.Contains(CrmConstants.FileSizeKey) && (int)entity.Attributes[CrmConstants.FileSizeKey] > configurationProvider.MaxFileSize)
                    {
                        throw new InvalidPluginExecutionException(OperationStatus.Failed, string.Format("FileSize Limit of {0} bytes was exceeded.", configurationProvider.MaxFileSize));
                    }

                    Providers.IBinaryStorageProvider storageProvider = Providers.Factory.GetStorageProvider(configurationProvider);

                    byte[] data     = Convert.FromBase64String((string)entity.Attributes[GenericConstants.Constants[entity.LogicalName][GenericConstants.DocumentBodyAttributeKey]]);
                    string fileName = (string)entity.Attributes[GenericConstants.Constants[entity.LogicalName][GenericConstants.FileNameAttributeKey]];
                    if (storageProvider.Create(entity.Id, fileName, data))
                    {
                        if (UserHasPrivilege(service, context.UserId, string.Format(GenericConstants.AttachmentExtensionPrivilegeTemplate, "Create")))
                        {
                            try
                            {
                                //Create an additional record to basically store the filesize
                                Entity attachmentExtension = new Entity(GenericConstants.AttachementExtensionEntityName);
                                attachmentExtension.Attributes.Add(GenericConstants.AttachementExtensionEntityNameKey, entity.LogicalName);
                                attachmentExtension.Attributes.Add(GenericConstants.AttachementExtensionEntityIdKey, entity.Id.ToString());
                                attachmentExtension.Attributes.Add(GenericConstants.AttachementExtensionFileSizeKey, data.Length);
                                service.Create(attachmentExtension);
                            }
                            catch
                            {
                                //In case the user doesn't have access or something is changed, this is only usefull for filesize queries.
                            }
                        }

                        //FileSize (3) attributes are handled by CRM and is useless to set here.  Must have a body else we get funny requests in retrieve messages.
                        entity.Attributes[GenericConstants.Constants[entity.LogicalName][GenericConstants.DocumentBodyAttributeKey]] = GenericConstants.EmptyBodyContent;

                        //If the plugin is running in async mode, we have to make a call to save the attachment/annotation document body
                        if (context.Stage == CrmConstants.PostOperationStateNumber)
                        {
                            service.Update(entity);
                        }
                    }
                    else
                    {
                        throw new InvalidPluginExecutionException(OperationStatus.Suspended, string.Format("The storage provider '{0}' failed to when calling 'Create' method.", configurationProvider.StorageProviderType));
                    }
                }
                catch (Exception ex)
                {
                    throw new InvalidPluginExecutionException(OperationStatus.Suspended, ex.ToString());
                }
            }
        }
Exemple #8
0
        public void Retrieve(IServiceProvider serviceProvider)
        {
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

            if (context.MessageName != MessageName.Retrieve && context.MessageName != MessageName.RetrieveMultiple)
            {
                //Invalid event attached
                return;
            }

            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

            List <Entity> entities = new List <Entity>();

            //This case handles where IOrganizationService is called with "LoadProperty".  For this, you need to attach this plugin to the "Retrieve" method of the parent Entity.
            if (context.OutputParameters.ContainsKey(CrmConstants.BusinessEntityKey) &&
                context.OutputParameters[CrmConstants.BusinessEntityKey] is Entity &&
                ((Entity)context.OutputParameters[CrmConstants.BusinessEntityKey]).RelatedEntities != null &&
                ((Entity)context.OutputParameters[CrmConstants.BusinessEntityKey]).RelatedEntities.Values is ICollection <EntityCollection> &&
                ((Entity)context.OutputParameters[CrmConstants.BusinessEntityKey]).RelatedEntities.Values.Count > 0)
            {
                foreach (EntityCollection entityCollection in ((Entity)context.OutputParameters[CrmConstants.BusinessEntityKey]).RelatedEntities.Values.Where(ec => ec.EntityName == CrmConstants.AnnotationEntityName || ec.EntityName == CrmConstants.AttachmentEntityName))
                {
                    entities.AddRange(entityCollection.Entities);
                }
            }
            else if (context.MessageName == MessageName.Retrieve && context.OutputParameters.Contains(CrmConstants.BusinessEntityKey) && context.OutputParameters[CrmConstants.BusinessEntityKey] is Entity)
            {
                //Handles retrieve message
                Entity entity = (Entity)context.OutputParameters[CrmConstants.BusinessEntityKey];
                if (entity.LogicalName != CrmConstants.AnnotationEntityName && entity.LogicalName != CrmConstants.AttachmentEntityName)
                {
                    return;
                }
                entities.Add(entity);
            }
            else if (context.MessageName == MessageName.RetrieveMultiple && context.OutputParameters.Contains(CrmConstants.BusinessEntityCollectionKey) && context.OutputParameters[CrmConstants.BusinessEntityCollectionKey] is EntityCollection)
            {
                EntityCollection entityCollection = (EntityCollection)context.OutputParameters[CrmConstants.BusinessEntityCollectionKey];
                if (entityCollection.TotalRecordCount > 0 && entityCollection.EntityName != CrmConstants.AnnotationEntityName && entityCollection.EntityName != CrmConstants.AttachmentEntityName)
                {
                    return;
                }
                entities.AddRange(entityCollection.Entities);
            }

            if (entities.Count > 0)
            {
                Configuration.IConfigurationProvider configurationProvider = Configuration.Factory.GetConfigurationProvider(service, entities[0].LogicalName, unsecurePluginStepConfiguration, securePluginStepConfiguration);
                if (configurationProvider.StorageProviderType == Providers.BinaryStorageProviderType.CrmDefault)
                {
                    //In this case, not doing anything.
                    return;
                }

                Providers.IBinaryStorageProvider storageProvider = Providers.Factory.GetStorageProvider(configurationProvider);
                entities.ForEach(e =>
                                 HandleEntity(service, context.UserId, storageProvider, e, GenericConstants.Constants[e.LogicalName][GenericConstants.DocumentBodyAttributeKey], GenericConstants.Constants[e.LogicalName][GenericConstants.FileNameAttributeKey])
                                 );
            }
        }
Exemple #9
0
        public void Retrieve(IServiceProvider serviceProvider)
        {
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

            if (context.MessageName != MessageName.Retrieve && context.MessageName != MessageName.RetrieveMultiple)
            {
                //Invalid event attached
                return;
            }

            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

            List <Entity> entities = new List <Entity>();

            //This case handles where IOrganizationService is called with "LoadProperty".  For this, you need to attach this plugin to the "Retrieve" method of the parent Entity.
            if (context.OutputParameters.ContainsKey(CrmConstants.BusinessEntityKey) &&
                context.OutputParameters[CrmConstants.BusinessEntityKey] is Entity &&
                ((Entity)context.OutputParameters[CrmConstants.BusinessEntityKey]).RelatedEntities != null &&
                ((Entity)context.OutputParameters[CrmConstants.BusinessEntityKey]).RelatedEntities.Values is ICollection <EntityCollection> &&
                ((Entity)context.OutputParameters[CrmConstants.BusinessEntityKey]).RelatedEntities.Values.Count > 0)
            {
                foreach (EntityCollection entityCollection in ((Entity)context.OutputParameters[CrmConstants.BusinessEntityKey]).RelatedEntities.Values.Where(ec => ec.EntityName == CrmConstants.AnnotationEntityName || ec.EntityName == CrmConstants.AttachmentEntityName))
                {
                    entities.AddRange(entityCollection.Entities);
                }
            }
            //If this was a retrievemultiple query, we need to check whether the filesize was referenced and modify the results accordingly
            else if (context.InputParameters.ContainsKey(CrmConstants.Query) && context.OutputParameters.Contains(CrmConstants.BusinessEntityCollectionKey) && context.OutputParameters[CrmConstants.BusinessEntityCollectionKey] is EntityCollection)
            {
                EntityCollection entityCollection = (EntityCollection)context.OutputParameters[CrmConstants.BusinessEntityCollectionKey];
                if (entityCollection.EntityName != CrmConstants.AnnotationEntityName && entityCollection.EntityName != CrmConstants.AttachmentEntityName)
                {
                    return;
                }

                QueryExpression query = context.InputParameters[CrmConstants.Query] as QueryExpression;
                if (query != null)
                {
                    //For optimization purposes, only return these records after the last page of results and only if totalrecordcountlimit is not exceeded (crm doesn't allow that anyways)
                    if (!entityCollection.MoreRecords && !entityCollection.TotalRecordCountLimitExceeded)
                    {
                        entities.AddRange(entityCollection.Entities);
                        //Get a list of all the entity ids to modify and their new file sizes
                        var modifyNeeded = GetEntitiesToModifyFileSizes(service, context.UserId, query.Criteria, entityCollection.EntityName);
                        foreach (var mod in modifyNeeded)
                        {
                            var entity = entities.FirstOrDefault(e => e.Id == mod.Key);
                            if (entity == null)
                            {
                                //Need to load the entity with the same colums as any other entities
                                entity = service.Retrieve(entityCollection.EntityName, mod.Key, new ColumnSet(entities.First().Attributes.Keys.ToArray()));
                                entities.Add(entity);
                            }
                            if (entity != null)
                            {
                                if (entity.Attributes.ContainsKey(CrmConstants.FileSizeKey))
                                {
                                    entity.Attributes[CrmConstants.FileSizeKey] = mod.Value;
                                }
                            }
                        }
                        if (entities.Count > 0)
                        {
                            ((EntityCollection)context.OutputParameters[CrmConstants.BusinessEntityCollectionKey]).Entities.Clear();
                            ((EntityCollection)context.OutputParameters[CrmConstants.BusinessEntityCollectionKey]).Entities.AddRange(entities);
                            return;
                        }
                    }
                }
            }
            else if (context.MessageName == MessageName.Retrieve && context.OutputParameters.Contains(CrmConstants.BusinessEntityKey) && context.OutputParameters[CrmConstants.BusinessEntityKey] is Entity)
            {
                //Handles retrieve message
                Entity entity = (Entity)context.OutputParameters[CrmConstants.BusinessEntityKey];
                if (entity.LogicalName != CrmConstants.AnnotationEntityName && entity.LogicalName != CrmConstants.AttachmentEntityName)
                {
                    return;
                }
                entities.Add(entity);
            }
            else if (context.MessageName == MessageName.RetrieveMultiple && context.OutputParameters.Contains(CrmConstants.BusinessEntityCollectionKey) && context.OutputParameters[CrmConstants.BusinessEntityCollectionKey] is EntityCollection)
            {
                EntityCollection entityCollection = (EntityCollection)context.OutputParameters[CrmConstants.BusinessEntityCollectionKey];
                if (entityCollection.TotalRecordCount > 0 && entityCollection.EntityName != CrmConstants.AnnotationEntityName && entityCollection.EntityName != CrmConstants.AttachmentEntityName)
                {
                    return;
                }
                entities.AddRange(entityCollection.Entities);
            }

            if (entities.Count > 0)
            {
                Configuration.IConfigurationProvider configurationProvider = Configuration.Factory.GetConfigurationProvider(service, entities[0].LogicalName, unsecurePluginStepConfiguration, securePluginStepConfiguration);
                if (configurationProvider.StorageProviderType == Providers.BinaryStorageProviderType.CrmDefault)
                {
                    //In this case, not doing anything.
                    return;
                }

                Providers.IBinaryStorageProvider storageProvider = Providers.Factory.GetStorageProvider(configurationProvider);
                entities.ForEach(e =>
                                 HandleEntity(service, context.UserId, storageProvider, e, GenericConstants.Constants[e.LogicalName][GenericConstants.DocumentBodyAttributeKey], GenericConstants.Constants[e.LogicalName][GenericConstants.FileNameAttributeKey])
                                 );
            }
        }
        public void Update(IServiceProvider serviceProvider)
        {
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

            if (context.MessageName != MessageName.Update)
            {
                //Invalid event attached
                return;
            }

            if (context.InputParameters.Contains(CrmConstants.TargetParameterKey) && context.InputParameters[CrmConstants.TargetParameterKey] is Entity)
            {
                try
                {
                    Entity entity = (Entity)context.InputParameters[CrmConstants.TargetParameterKey];
                    if (entity.LogicalName != CrmConstants.AnnotationEntityName && entity.LogicalName != CrmConstants.AttachmentEntityName)
                    {
                        return;
                    }

                    if (!context.PreEntityImages.ContainsKey(PreUpdateKey) || context.PreEntityImages[PreUpdateKey] == null)
                    {
                        throw new InvalidPluginExecutionException(OperationStatus.Failed, string.Format("PreEntityImage could not be found when updating {0}", context.PrimaryEntityName));
                    }
                    Entity preUpdateEntity = context.PreEntityImages[PreUpdateKey];

                    if (!entity.Attributes.Keys.Contains(GenericConstants.Constants[entity.LogicalName][GenericConstants.DocumentBodyAttributeKey]))
                    {
                        //No change to binary data
                        return;
                    }

                    IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                    IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

                    Configuration.IConfigurationProvider configurationProvider = Configuration.Factory.GetConfigurationProvider(service, entity.LogicalName, unsecurePluginStepConfiguration, securePluginStepConfiguration);
                    if (configurationProvider.StorageProviderType == Providers.BinaryStorageProviderType.CrmDefault)
                    {
                        //In this case, not doing anything with the binary data.
                        return;
                    }

                    Providers.IBinaryStorageProvider storageProvider = Providers.Factory.GetStorageProvider(configurationProvider);

                    //If the document body is empty, delete the external binary (filename is in the preupdate image)
                    if (string.IsNullOrWhiteSpace((string)entity.Attributes[GenericConstants.Constants[entity.LogicalName][GenericConstants.DocumentBodyAttributeKey]]))
                    {
                        storageProvider.Delete(preUpdateEntity.Id, (string)preUpdateEntity.Attributes[GenericConstants.Constants[entity.LogicalName][GenericConstants.FileNameAttributeKey]]);
                        return;
                    }

                    byte[] data     = Convert.FromBase64String((string)entity.Attributes[GenericConstants.Constants[entity.LogicalName][GenericConstants.DocumentBodyAttributeKey]]);
                    string fileName = (string)entity.Attributes[GenericConstants.Constants[entity.LogicalName][GenericConstants.FileNameAttributeKey]];
                    if (storageProvider.Create(entity.Id, fileName, data))
                    {
                        entity.Attributes[GenericConstants.Constants[entity.LogicalName][GenericConstants.DocumentBodyAttributeKey]] = GenericConstants.EmptyBodyContent;
                        //If the plugin is running in async mode and is for attachment, we have to make a call to save the attachment.
                        if (context.Stage == CrmConstants.PostOperationStateNumber && entity.LogicalName == CrmConstants.AttachmentEntityName)
                        {
                            service.Update(entity);
                        }
                    }
                    else
                    {
                        throw new InvalidPluginExecutionException(OperationStatus.Suspended, string.Format("The storage provider '{0}' failed to when calling 'Create' method.", configurationProvider.StorageProviderType));
                    }
                }
                catch (Exception ex)
                {
                    throw new InvalidPluginExecutionException(OperationStatus.Suspended, ex.ToString());
                }
            }
        }
Exemple #11
0
        public void Create(IServiceProvider serviceProvider)
        {
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

            if (context.MessageName != MessageName.Create)
            {
                //Invalid event attached
                return;
            }

            if (context.InputParameters.Contains(CrmConstants.TargetParameterKey) && context.InputParameters[CrmConstants.TargetParameterKey] is Entity)
            {
                try
                {
                    Entity entity = (Entity)context.InputParameters[CrmConstants.TargetParameterKey];
                    if (entity.LogicalName != CrmConstants.AnnotationEntityName && entity.LogicalName != CrmConstants.AttachmentEntityName)
                    {
                        return;
                    }

                    if (!entity.Attributes.Keys.Contains(GenericConstants.Constants[entity.LogicalName][GenericConstants.DocumentBodyAttributeKey]) || string.IsNullOrWhiteSpace((string)entity.Attributes[GenericConstants.Constants[entity.LogicalName][GenericConstants.DocumentBodyAttributeKey]]))
                    {
                        //No binary data
                        return;
                    }

                    IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                    IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

                    Configuration.IConfigurationProvider configurationProvider = Configuration.Factory.GetConfigurationProvider(service, entity.LogicalName, unsecurePluginStepConfiguration, securePluginStepConfiguration);
                    if (configurationProvider.StorageProviderType == Providers.StorageProviderType.CrmDefault)
                    {
                        //In this case, not doing anything with the binary data.
                        return;
                    }

                    //This check is actually a bit useless for sandboxed pluxings.  CRM is bugged and won't allow anything bigger than 5mb, the plugin sandbox will just crash.
                    if (entity.Attributes.Keys.Contains(CrmConstants.FileSizeKey) && (int)entity.Attributes[CrmConstants.FileSizeKey] > configurationProvider.MaxFileSize)
                    {
                        throw new InvalidPluginExecutionException(OperationStatus.Failed, string.Format("FileSize Limit of {0} bytes was exceeded.", configurationProvider.MaxFileSize));
                    }

                    Providers.IBinaryStorageProvider storageProvider = Providers.Factory.GetStorageProvider(configurationProvider);

                    byte[] data     = Convert.FromBase64String((string)entity.Attributes[GenericConstants.Constants[entity.LogicalName][GenericConstants.DocumentBodyAttributeKey]]);
                    string fileName = (string)entity.Attributes[GenericConstants.Constants[entity.LogicalName][GenericConstants.FileNameAttributeKey]];
                    if (storageProvider.Create(entity.Id, fileName, data))
                    {
                        entity.Attributes[GenericConstants.Constants[entity.LogicalName][GenericConstants.DocumentBodyAttributeKey]] = GenericConstants.EmptyBodyContent;
                        //If the plugin is running in async mode and is for attachment, we have to make a call to save the attachment.
                        if (context.Stage == CrmConstants.PostOperationStateNumber && entity.LogicalName == CrmConstants.AttachmentEntityName)
                        {
                            service.Update(entity);
                        }
                    }
                    else
                    {
                        throw new InvalidPluginExecutionException(OperationStatus.Suspended, string.Format("The storage provider '{0}' failed to when calling 'Create' method.", configurationProvider.StorageProviderType));
                    }
                }
                catch (Exception ex)
                {
                    throw new InvalidPluginExecutionException(OperationStatus.Suspended, ex.ToString());
                }
            }
        }
        protected void Create(IServiceProvider serviceProvider, bool saveEntity, string entityName, string documentBodyAttributeKey, string fileNameAttributeKey)
        {
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

            if (context.MessageName != MessageName.Create)
            {
                //Invalid event attached
                return;
            }

            if (context.InputParameters.Contains(CrmConstants.TargetParameterKey) && context.InputParameters[CrmConstants.TargetParameterKey] is Entity)
            {
                try
                {
                    Entity entity = (Entity)context.InputParameters[CrmConstants.TargetParameterKey];
                    if (entity.LogicalName != entityName)
                    {
                        return;
                    }

                    if (!entity.Attributes.Keys.Contains(documentBodyAttributeKey) || string.IsNullOrWhiteSpace((string)entity.Attributes[documentBodyAttributeKey]))
                    {
                        //No binary data
                        return;
                    }

                    IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                    IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

                    Configuration.IConfigurationProvider configurationProvider = Configuration.Factory.GetConfigurationProvider(service, entityName);
                    if (configurationProvider.StorageProviderType == Providers.BinaryStorageProviderType.CrmDefault)
                    {
                        //In this case, not doing anything with the binary data.
                        return;
                    }

                    //This check is actually a bit useless for sandboxed pluxings.  CRM is bugged and won't allow anything bigger than 5mb, the plugin sandbox will just crash.
                    if (entity.Attributes.Keys.Contains(CrmConstants.FileSizeKey) && (int)entity.Attributes[CrmConstants.FileSizeKey] > configurationProvider.MaxFileSize)
                    {
                        throw new InvalidPluginExecutionException(OperationStatus.Failed, string.Format("FileSize Limit of {0} bytes was exceeded.", configurationProvider.MaxFileSize));
                    }

                    Providers.IBinaryStorageProvider storageProvider = Providers.Factory.GetStorageProvider(configurationProvider);

                    byte[] data        = Convert.FromBase64String((string)entity.Attributes[documentBodyAttributeKey]);
                    string fileName    = (string)entity.Attributes[fileNameAttributeKey];
                    string newFileName = string.Format("{0}{1}", Constants.ExternalFilePrefix, fileName);

                    if (storageProvider.Create(entity.Id, fileName, data))
                    {
                        entity.Attributes[fileNameAttributeKey]     = newFileName;
                        entity.Attributes[documentBodyAttributeKey] = Constants.EmptyBodyContent;
                        if (saveEntity)
                        {
                            service.Update(entity);
                        }
                    }
                    else
                    {
                        throw new InvalidPluginExecutionException(OperationStatus.Suspended, string.Format("The storage provider '{0}' failed to when calling 'Create' method.", configurationProvider.StorageProviderType));
                    }
                }
                catch (Exception ex)
                {
                    throw new InvalidPluginExecutionException(OperationStatus.Suspended, ex.ToString());
                }
            }
        }
Exemple #13
0
        public void Delete(IServiceProvider serviceProvider)
        {
            try
            {
                IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
                if (context.MessageName != MessageName.Delete)
                {
                    //Invalid event attached
                    return;
                }

                if (!context.PreEntityImages.ContainsKey(PreEntityImageKey) || context.PreEntityImages[PreEntityImageKey] == null)
                {
                    throw new InvalidPluginExecutionException(OperationStatus.Failed, string.Format("PreEntityImage could not be found when deleting {0}", context.PrimaryEntityName));
                }
                Entity entity = context.PreEntityImages[PreEntityImageKey];
                if (entity.LogicalName != CrmConstants.AnnotationEntityName && entity.LogicalName != CrmConstants.AttachmentEntityName)
                {
                    //only valid for attachments and annotations
                    return;
                }

                IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

                DataCollection <Entity> attachementExtensionEntities = null;
                if (UserHasPrivilege(service, context.UserId, string.Format(GenericConstants.AttachmentExtensionPrivilegeTemplate, "Delete")))
                {
                    try
                    {
                        //If an attachement extension record exists, need to delete that as well.
                        var query = new QueryExpression(GenericConstants.AttachementExtensionEntityName);
                        query.ColumnSet = new ColumnSet(false);
                        query.Criteria  = new FilterExpression(LogicalOperator.And);
                        query.Criteria.AddCondition(GenericConstants.AttachementExtensionEntityNameKey, ConditionOperator.Equal, entity.LogicalName);
                        query.Criteria.AddCondition(GenericConstants.AttachementExtensionEntityIdKey, ConditionOperator.Equal, entity.Id.ToString());
                        attachementExtensionEntities = service.RetrieveMultiple(query).Entities;
                    }
                    catch { }
                }
                if (attachementExtensionEntities != null)
                {
                    foreach (var attachementExtensionEntity in attachementExtensionEntities)
                    {
                        service.Delete(attachementExtensionEntity.LogicalName, attachementExtensionEntity.Id);
                    }
                }

                Configuration.IConfigurationProvider configurationProvider = Configuration.Factory.GetConfigurationProvider(service, entity.LogicalName, unsecurePluginStepConfiguration, securePluginStepConfiguration);
                if (configurationProvider.StorageProviderType == Providers.BinaryStorageProviderType.CrmDefault)
                {
                    //In this case, not doing anything for the external file.
                    return;
                }

                Providers.IBinaryStorageProvider storageProvider = Providers.Factory.GetStorageProvider(configurationProvider);

                if (entity.Attributes.ContainsKey(GenericConstants.Constants[entity.LogicalName][GenericConstants.FileNameAttributeKey]))
                {
                    storageProvider.Delete(entity.Id, (string)entity.Attributes[GenericConstants.Constants[entity.LogicalName][GenericConstants.FileNameAttributeKey]]);
                }
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(OperationStatus.Suspended, ex.ToString());
            }
        }