/// <summary>
        /// This method creates any entity records that this sample requires.
        /// </summary>
        public void CreateRequiredRecords()
        {
            //Define the email template to create.
            Template emailTemplate = new Template
            {
                Title = "An example email template",
                Subject = "This is an example email.",
                IsPersonal = false,
                TemplateTypeCode = "lead",

                //1033 is the code for US English - you may need to change this value
                //depending on your locale.
                LanguageCode = 1033
               
            };

            _emailTemplateId = _serviceProxy.Create(emailTemplate);

            for (int i = 0; i < 3; i++ )
            {
                ActivityMimeAttachment attachment = new ActivityMimeAttachment
                {
                    Subject = String.Format("Attachment {0}",i),
                    FileName = String.Format("ExampleAttachment{0}.txt", i),
                    Body = "Some Text",
                    ObjectId = new EntityReference(Template.EntityLogicalName, _emailTemplateId),
                    ObjectTypeCode = Template.EntityLogicalName
                };

                _templateAttachmentIds.Add(_serviceProxy.Create(attachment));
            }

            Console.WriteLine("An email template and {0} attachments were created.", _templateAttachmentIds.Count);

            return;
        }
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// </summary>
        public static void CreateRequiredRecords(CrmServiceClient service)
        {
            //Define the email template to create.
            Template emailTemplate = new Template
            {
                Title            = "An example email template",
                Subject          = "This is an example email.",
                IsPersonal       = false,
                TemplateTypeCode = "lead",

                //1033 is the code for US English - you may need to change this value
                //depending on your locale.
                LanguageCode = 1033
            };

            _emailTemplateId = service.Create(emailTemplate);

            for (int i = 0; i < 3; i++)
            {
                ActivityMimeAttachment attachment = new ActivityMimeAttachment
                {
                    Subject        = String.Format("Attachment {0}", i),
                    FileName       = String.Format("ExampleAttachment{0}.txt", i),
                    Body           = "Some Text",
                    ObjectId       = new EntityReference(Template.EntityLogicalName, _emailTemplateId),
                    ObjectTypeCode = Template.EntityLogicalName
                };

                _templateAttachmentIds.Add(service.Create(attachment));
            }

            Console.WriteLine("An email template and {0} attachments were created.", _templateAttachmentIds.Count);

            return;
        }
Example #3
0
        private void CoppyContactAttachmentsToEmail(Guid contactId, Guid emailId)
        {
            List <Entity> attachments      = new List <Entity>();
            var           queryByAttribute = new QueryByAttribute(Annotation.EntityLogicalName)
            {
                ColumnSet  = new ColumnSet(true),
                Attributes = { "objectid" },
                Values     = { contactId }
            };
            var response = _service.RetrieveMultiple(queryByAttribute);

            if (response != null && response.Entities.Count > 0)
            {
                attachments = response.Entities.ToList <Entity>();
                foreach (var attachment in attachments)
                {
                    ActivityMimeAttachment attachmentNew = new ActivityMimeAttachment()
                    {
                        Subject          = attachment.Contains("subject") ? attachment.GetAttributeValue <string>("subject") : string.Empty,
                        FileName         = attachment.Contains("filename") ? attachment.GetAttributeValue <string>("filename") : string.Empty,
                        Body             = attachment.Contains("documentbody") ? attachment.GetAttributeValue <string>("documentbody") : string.Empty,
                        MimeType         = attachment.GetAttributeValue <string>("mimetype"),
                        AttachmentNumber = 1,
                        ObjectId         = new EntityReference(Email.EntityLogicalName, emailId),
                        ObjectTypeCode   = Email.EntityLogicalName
                    };
                    _service.Create(attachmentNew);
                }
            }
        }
        /**
         * <summary>
         * Creates a CSV file attachment and adds it to the email that is to be sent to SIS.
         * </summary>
         * <param name="emailID">the ID of the email that is going to be sent to SIS.</param>
         * <param name="filename">the file name of the attachment</param>
         * <param name="fileBody">the file content of the attachment</param>
         * <param name="subject">the subject of the attachment </param>
         * */
        public void AddAttachmentToEmail(EntityReference entityRef, string filename, string fileBody, string subject)
        {
            ActivityMimeAttachment attachment = new ActivityMimeAttachment()
            {
                ObjectId       = entityRef,
                ObjectTypeCode = Email.EntityLogicalName,
                Subject        = subject,
                Body           = fileBody,
                FileName       = filename,
            };

            ElevatedService.Create(attachment.ToEntity <Entity>());
        }
        /// <summary>
        /// This metohd called once uesr picks up attachment. Create ActivityMimeAttachment and
        /// add to lvList.
        /// </summary>
        /// <param name="args"></param>
        public async void ContinueFileOpenPicker(FileOpenPickerContinuationEventArgs args)
        {
            // If attachment selected
            if ((args.ContinuationData["AttachmentFile"] as string) == "AttachmentFile" && args.Files != null && args.Files.Count > 0)
            {
                // Read attachemnt into Stream
                Stream fs         = await args.Files[0].OpenStreamForReadAsync();
                byte[] binaryData = new byte[fs.Length];
                long   bytesRead  = fs.Read(binaryData, 0, (int)fs.Length);

                ActivityMimeAttachment attach = new ActivityMimeAttachment()
                {
                    ObjectId       = new EntityReference("email", Guid.Empty),
                    ObjectTypeCode = "email",
                    Subject        = "email attachment",
                    Body           = Convert.ToBase64String(binaryData),
                    FileName       = args.Files[0].Name
                };
                CRMEmail.lvList.Items.Add(attach);
            }
        }
Example #6
0
        [STAThread] // Added to support UX
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    #region Sample Code
                    //////////////////////////////////////////////
                    #region Set up
                    SetUpSample(service);
                    #endregion Set up
                    #region Demonstrate

                    // Create three e-mail attachments
                    for (int i = 0; i < 3; i++)
                    {
                        ActivityMimeAttachment _sampleAttachment = new ActivityMimeAttachment
                        {
                            ObjectId       = new EntityReference(Email.EntityLogicalName, emailId),
                            ObjectTypeCode = Email.EntityLogicalName,
                            Subject        = String.Format("Sample Attachment {0}", i),
                            Body           = System.Convert.ToBase64String(
                                new ASCIIEncoding().GetBytes("Example Attachment")),
                            FileName = String.Format("ExampleAttachment{0}.txt", i)
                        };

                        emailAttachmentId[i] = service.Create(_sampleAttachment);
                    }

                    Console.WriteLine("Created three e-mail attachments for the e-mail activity.");

                    // Retrieve an attachment including its id, subject, filename and body.
                    ActivityMimeAttachment _singleAttachment =
                        (ActivityMimeAttachment)service.Retrieve(
                            ActivityMimeAttachment.EntityLogicalName,
                            emailAttachmentId[0],
                            new ColumnSet("activitymimeattachmentid",
                                          "subject",
                                          "filename",
                                          "body"));

                    Console.WriteLine("Retrieved an email attachment, {0}.", _singleAttachment.FileName);

                    // Update attachment
                    _singleAttachment.FileName = "ExampleAttachmentUpdated.txt";
                    service.Update(_singleAttachment);

                    Console.WriteLine("Updated the retrieved e-mail attachment to {0}.", _singleAttachment.FileName);

                    // Retrieve all attachments associated with the email activity.
                    QueryExpression _attachmentQuery = new QueryExpression
                    {
                        EntityName = ActivityMimeAttachment.EntityLogicalName,
                        ColumnSet  = new ColumnSet("activitymimeattachmentid"),
                        Criteria   = new FilterExpression
                        {
                            Conditions =
                            {
                                new ConditionExpression
                                {
                                    AttributeName = "objectid",
                                    Operator      = ConditionOperator.Equal,
                                    Values        = { emailId }
                                },
                                new ConditionExpression
                                {
                                    AttributeName = "objecttypecode",
                                    Operator      = ConditionOperator.Equal,
                                    Values        = { Email.EntityLogicalName }
                                }
                            }
                        }
                    };

                    EntityCollection results = service.RetrieveMultiple(
                        _attachmentQuery);

                    Console.WriteLine("Retrieved all the e-mail attachments.");

                    #region Clean up
                    CleanUpSample(service);
                    #endregion Clean up
                }
                #endregion Demonstrate
                #endregion Sample Code
                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Dynamics CRM";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }
            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
        protected override void ExecuteActivity(CodeActivityContext executionContext)
        {
            if (this.AttachmentsFilename == null)
            {
                throw new ArgumentNullException("AttachmentsFilename", "'AttachmentsFilename' input argument cannot be null");
            }

            string attachments = this.AttachmentsFilename.Get(executionContext);

            if (string.IsNullOrEmpty(attachments))
            {
                this.AllAttachmentsFound.Set(executionContext, false);
                this.AttachmentsNotFound.Set(executionContext, "Attachments Filename is null or empty");
                return;
            }

            string[] attachmentsArray = attachments.Split(',');

            EntityCollection activityMimeAttachments = ActivityMimeAttachment.RetrieveTemplatesActivityMimeAttachmentsByName(attachmentsArray, this.OrganizationService);

            if (activityMimeAttachments == null || activityMimeAttachments.TotalRecordCount == 0)
            {
                this.AllAttachmentsFound.Set(executionContext, false);
                this.AttachmentsNotFound.Set(executionContext, attachments);
                return;
            }

            DataCollection <Entity> activityMimeAttachmentEntities = activityMimeAttachments.Entities;
            StringBuilder           attachmentsNotFound            = new StringBuilder();
            bool found = false;

            foreach (string attachment in attachmentsArray)
            {
                foreach (Entity activityMimeAttachment in activityMimeAttachmentEntities)
                {
                    if (activityMimeAttachment.Contains("filename") &&
                        activityMimeAttachment["filename"].ToString().ToLowerInvariant() == attachment.ToLowerInvariant())
                    {
                        found = true;
                        break;
                    }
                }

                if (found == false)
                {
                    if (attachmentsNotFound.Length == 0)
                    {
                        attachmentsNotFound.Append(attachment);
                    }
                    else
                    {
                        attachmentsNotFound.Append(string.Format(",{0}", attachment));
                    }
                }
                found = false;
            }

            if (attachmentsNotFound.Length > 0)
            {
                this.AllAttachmentsFound.Set(executionContext, false);
                this.AttachmentsNotFound.Set(executionContext, attachmentsNotFound.ToString());
            }
            else
            {
                this.AllAttachmentsFound.Set(executionContext, true);
            }
        }
Example #8
0
        /// <summary>
        /// Create, Retrieve, Update and Delete an e-mail attachment.
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        /// </summary>
        public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {
                // Connect to the Organization service. 
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();

                    //<snippetCRUDEmailAttachments1>

                    // Create three e-mail attachments
                    for (int i = 0; i < 3; i++)
                    {
                        ActivityMimeAttachment _sampleAttachment = new ActivityMimeAttachment
                        {
                            ObjectId = new EntityReference(Email.EntityLogicalName, _emailId),
                            ObjectTypeCode = Email.EntityLogicalName,
                            Subject = String.Format("Sample Attachment {0}", i),
                            Body = System.Convert.ToBase64String(
                                    new ASCIIEncoding().GetBytes("Example Attachment")),
                            FileName = String.Format("ExampleAttachment{0}.txt", i)
                        };

                        _emailAttachmentId[i] = _serviceProxy.Create(_sampleAttachment);
                    }

                    Console.WriteLine("Created three e-mail attachments for the e-mail activity.");

                    // Retrieve an attachment including its id, subject, filename and body.
                    ActivityMimeAttachment _singleAttachment =
                        (ActivityMimeAttachment)_serviceProxy.Retrieve(
                                                    ActivityMimeAttachment.EntityLogicalName,
                                                    _emailAttachmentId[0],
                                                    new ColumnSet("activitymimeattachmentid",
                                                        "subject",
                                                        "filename",
                                                        "body"));

                    Console.WriteLine("Retrieved an email attachment, {0}.", _singleAttachment.FileName);

                    // Update attachment
                    _singleAttachment.FileName = "ExampleAttachmentUpdated.txt";
                    _serviceProxy.Update(_singleAttachment);

                    Console.WriteLine("Updated the retrieved e-mail attachment to {0}.", _singleAttachment.FileName);

                    // Retrieve all attachments associated with the email activity.
                    QueryExpression _attachmentQuery = new QueryExpression
                    {
                        EntityName = ActivityMimeAttachment.EntityLogicalName,
                        ColumnSet = new ColumnSet("activitymimeattachmentid"),
                        Criteria = new FilterExpression
                        {
                            Conditions =
                        {
                            new ConditionExpression
                            {
                                AttributeName = "objectid",
                                Operator = ConditionOperator.Equal,
                                Values = {_emailId}
                            },
                            new ConditionExpression
                            {
                                AttributeName = "objecttypecode",
                                Operator = ConditionOperator.Equal,
                                Values = {Email.EntityLogicalName}
                            }
                        }
                        }
                    };

                    EntityCollection results = _serviceProxy.RetrieveMultiple(
                        _attachmentQuery);

                    Console.WriteLine("Retrieved all the e-mail attachments.");

                    //</snippetCRUDEmailAttachments1>

                    DeleteRequiredRecords(promptForDelete);
                }
            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
Example #9
0
        /// <summary>
        /// Create, Retrieve, Update and Delete an e-mail attachment.
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        /// </summary>
        public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();


                    // Create three e-mail attachments
                    for (int i = 0; i < 3; i++)
                    {
                        ActivityMimeAttachment _sampleAttachment = new ActivityMimeAttachment
                        {
                            ObjectId       = new EntityReference(Email.EntityLogicalName, _emailId),
                            ObjectTypeCode = Email.EntityLogicalName,
                            Subject        = String.Format("Sample Attachment {0}", i),
                            Body           = System.Convert.ToBase64String(
                                new ASCIIEncoding().GetBytes("Example Attachment")),
                            FileName = String.Format("ExampleAttachment{0}.txt", i)
                        };

                        _emailAttachmentId[i] = _serviceProxy.Create(_sampleAttachment);
                    }

                    Console.WriteLine("Created three e-mail attachments for the e-mail activity.");

                    // Retrieve an attachment including its id, subject, filename and body.
                    ActivityMimeAttachment _singleAttachment =
                        (ActivityMimeAttachment)_serviceProxy.Retrieve(
                            ActivityMimeAttachment.EntityLogicalName,
                            _emailAttachmentId[0],
                            new ColumnSet("activitymimeattachmentid",
                                          "subject",
                                          "filename",
                                          "body"));

                    Console.WriteLine("Retrieved an email attachment, {0}.", _singleAttachment.FileName);

                    // Update attachment
                    _singleAttachment.FileName = "ExampleAttachmentUpdated.txt";
                    _serviceProxy.Update(_singleAttachment);

                    Console.WriteLine("Updated the retrieved e-mail attachment to {0}.", _singleAttachment.FileName);

                    // Retrieve all attachments associated with the email activity.
                    QueryExpression _attachmentQuery = new QueryExpression
                    {
                        EntityName = ActivityMimeAttachment.EntityLogicalName,
                        ColumnSet  = new ColumnSet("activitymimeattachmentid"),
                        Criteria   = new FilterExpression
                        {
                            Conditions =
                            {
                                new ConditionExpression
                                {
                                    AttributeName = "objectid",
                                    Operator      = ConditionOperator.Equal,
                                    Values        = { _emailId }
                                },
                                new ConditionExpression
                                {
                                    AttributeName = "objecttypecode",
                                    Operator      = ConditionOperator.Equal,
                                    Values        = { Email.EntityLogicalName }
                                }
                            }
                        }
                    };

                    EntityCollection results = _serviceProxy.RetrieveMultiple(
                        _attachmentQuery);

                    Console.WriteLine("Retrieved all the e-mail attachments.");


                    DeleteRequiredRecords(promptForDelete);
                }
            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }