protected override void Execute(CodeActivityContext executionContext)
        {
            Boolean         Logging     = EnableLogging.Get(executionContext);
            string          LogFilePath = LogFile.Get(executionContext);
            EntityReference Attachment  = AttachmentId.Get(executionContext);

            try
            {
                if (Logging)
                {
                    Log("Workflow Execution Start", LogFilePath);
                }

                // Create a CRM Service in Workflow.
                IWorkflowContext            context        = executionContext.GetExtension <IWorkflowContext>();
                IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
                IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

                if (Logging)
                {
                    Log("Removing Attachment", LogFilePath);
                }

                service.Delete(Attachment.LogicalName, Attachment.Id);

                if (Logging)
                {
                    Log("Workflow Executed Successfully", LogFilePath);
                }
            }
            catch (Exception ex)
            {
                Log(ex.Message, LogFilePath);
            }
        }
Exemplo n.º 2
0
        public void Save(XmlWriter writer)
        {
            writer.WriteStartDocument(true);

            writer.WriteStartElement("kei-gui");
            writer.WriteAttributeString("config-version", "1.1");

            writer.WriteElementString("EnableLogging", EnableLogging.ToString());
            writer.WriteElementString("LocalIntranetAddress", LocalIntranetAddress);
            writer.WriteElementString("LocalKClientPort", LocalKClientPort.ToString());
            writer.WriteElementString("LocalTrackerServerPort", LocalTrackerServerPort.ToString());
            writer.WriteElementString("ForceBroadcastTime", ForceBroadcastTime.ToString());
            writer.WriteElementString("AutoStartAndConnect", AutoStartAndConnect.ToString());
            writer.WriteElementString("IsPointInsertion", IsPointInsertion.ToString());
            writer.WriteElementString("UseUPnP", UsePortMapping.ToString());

            writer.WriteStartElement("TargetEndPoints");
            foreach (var item in TargetEndPoints)
            {
                writer.WriteElementString("EndPoint", item);
            }
            writer.WriteEndElement();

            writer.WriteEndElement();

            writer.WriteEndDocument();
        }
Exemplo n.º 3
0
        protected override string GenerateResponseFileCommands()
        {
            var args = new Dictionary <string, string>
            {
                ["KernelPkg"]   = KernelPkg,
                ["EnableDebug"] = DebugEnabled.ToString(),
                ["EnableStackCorruptionDetection"] = StackCorruptionDetectionEnabled.ToString(),
                ["StackCorruptionDetectionLevel"]  = StackCorruptionDetectionLevel,
                ["DebugMode"]                = DebugMode,
                ["TraceAssemblies"]          = TraceAssemblies,
                ["DebugCom"]                 = DebugCom.ToString(),
                ["TargetAssembly"]           = Path.GetFullPath(TargetAssembly),
                ["OutputFilename"]           = Path.GetFullPath(OutputFilename),
                ["EnableLogging"]            = EnableLogging.ToString(),
                ["EmitDebugSymbols"]         = EmitDebugSymbols.ToString(),
                ["IgnoreDebugStubAttribute"] = IgnoreDebugStubAttribute.ToString(),
            }.ToList();

            foreach (var reference in References)
            {
                args.Add(new KeyValuePair <string, string>("References", reference.ItemSpec));
            }

            foreach (var plugsReference in PlugsReferences)
            {
                args.Add(new KeyValuePair <string, string>("PlugsReferences", plugsReference.ItemSpec));
            }

            return(String.Join(Environment.NewLine, args.Select(a => $"{a.Key}:{a.Value}")));
        }
Exemplo n.º 4
0
        protected override void Execute(CodeActivityContext executionContext)
        {
            Boolean         Logging     = EnableLogging.Get(executionContext);
            string          LogFilePath = LogFile.Get(executionContext);
            EntityReference Email       = EmailId.Get(executionContext);

            try
            {
                if (Logging)
                {
                    Log("Workflow Execution Start", LogFilePath);
                }
                IWorkflowContext            context        = executionContext.GetExtension <IWorkflowContext>();
                IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
                IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);
                if (Logging)
                {
                    Log("Sending Email", LogFilePath);
                }
                SendEmailRequest sendEmailreq = new SendEmailRequest();
                sendEmailreq.EmailId       = Email.Id;
                sendEmailreq.TrackingToken = "";
                sendEmailreq.IssueSend     = true;
                SendEmailResponse sendEmailresp = (SendEmailResponse)service.Execute(sendEmailreq);
                if (Logging)
                {
                    Log("Workflow Executed Successfully", LogFilePath);
                }
            }
            catch (Exception ex)
            {
                Log(ex.Message, LogFilePath);
            }
        }
        protected override void Execute(CodeActivityContext executionContext)
        {
            Boolean         EnableLoggingValue = EnableLogging.Get(executionContext);
            string          ProductUriValue    = ProductUri.Get(executionContext);
            string          AppSIDValue        = AppSID.Get(executionContext);
            string          AppKeyValue        = AppKey.Get(executionContext);
            string          LogFilePath        = LogFile.Get(executionContext);
            EntityReference Attachment         = AttachmentId.Get(executionContext);
            CloudAppConfig  config             = new CloudAppConfig();

            config.ProductUri = ProductUriValue;
            config.AppSID     = AppSIDValue;
            config.AppKey     = AppKeyValue;
            IWorkflowContext            context        = executionContext.GetExtension <IWorkflowContext>();
            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

            try
            {
                if (EnableLoggingValue)
                {
                    Log("WorkFlow Started", LogFilePath);
                }
                if (EnableLoggingValue)
                {
                    Log("Retrieving Attachment From CRM", LogFilePath);
                }
                Entity ThisAttachment = service.Retrieve("annotation", Attachment.Id, new ColumnSet(new string[] { "filename", "documentbody", "mimetype" }));
                if (ThisAttachment != null)
                {
                    if (EnableLoggingValue)
                    {
                        Log("Attachment Retrieved Successfully", LogFilePath);
                    }
                    if (ThisAttachment.Contains("mimetype") && ThisAttachment.Contains("documentbody"))
                    {
                        string FileName = "Aspose .NET AutoMerge Attachment (" + DateTime.Now.ToString() + ").docx";
                        if (ThisAttachment.Contains("filename"))
                        {
                            FileName = ThisAttachment["filename"].ToString();
                        }
                        config.FileName = FileName;
                        byte[]       DocumentBody = Convert.FromBase64String(ThisAttachment["documentbody"].ToString());
                        MemoryStream fileStream   = new MemoryStream(DocumentBody);

                        if (EnableLoggingValue)
                        {
                            Log("Upload Attachment on Storage", LogFilePath);
                        }
                        UploadFileOnStorage(config, fileStream);
                    }
                }
            }
            catch (Exception ex)
            {
                Log(ex.Message, LogFilePath);
                throw ex;
            }
        }
Exemplo n.º 6
0
        private bool ValidateParameters(CodeActivityContext executionContext)
        {
            Boolean         Logging     = EnableLogging.Get(executionContext);
            string          LogFilePath = LogFile.Get(executionContext);
            EntityReference Attachment  = AttachmentId.Get(executionContext);
            string          entityName  = EntityName.Get(executionContext);
            string          recordId    = RecordId.Get(executionContext);

            return(true);
        }
Exemplo n.º 7
0
        protected override void Execute(CodeActivityContext executionContext)
        {
            Boolean         Logging     = EnableLogging.Get(executionContext);
            string          LogFilePath = LogFile.Get(executionContext);
            EntityReference Attachment  = AttachmentId.Get(executionContext);
            string          entityName  = EntityName.Get(executionContext);
            string          recordId    = RecordId.Get(executionContext);

            try
            {
                if (Logging)
                {
                    Log("Workflow Execution Start", LogFilePath);
                }
                if (ValidateParameters(executionContext))
                {
                    // Create a CRM Service in Workflow.
                    IWorkflowContext            context        = executionContext.GetExtension <IWorkflowContext>();
                    IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
                    IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

                    if (Logging)
                    {
                        Log("Attaching Attachment", LogFilePath);
                    }

                    // Create an attachment.
                    Entity UpdatedAttachment = new Entity("annotation");
                    UpdatedAttachment.Id = Attachment.Id;
                    UpdatedAttachment.Attributes.Add("objectid", new EntityReference(entityName, new Guid(recordId)));
                    service.Update(UpdatedAttachment);

                    if (Logging)
                    {
                        Log("Attachment linked successfully", LogFilePath);
                    }

                    if (Logging)
                    {
                        Log("Workflow Executed Successfully", LogFilePath);
                    }
                }
            }
            catch (Exception ex)
            {
                Log(ex.Message, LogFilePath);
            }
        }
Exemplo n.º 8
0
        protected override string GenerateCommandLineCommands()
        {
            Dictionary <string, string> args = new Dictionary <string, string>
            {
                { "KernelPkg", KernelPkg },
                { "EnableDebug", DebugEnabled.ToString() },
                { "EnableStackCorruptionDetection", StackCorruptionDetectionEnabled.ToString() },
                { "StackCorruptionDetectionLevel", StackCorruptionDetectionLevel },
                { "DebugMode", DebugMode },
                { "TraceAssemblies", TraceAssemblies },
                { "DebugCom", DebugCom.ToString() },
                { "OutputFilename", Path.GetFullPath(OutputFilename) },
                { "EnableLogging", EnableLogging.ToString() },
                { "EmitDebugSymbols", EmitDebugSymbols.ToString() },
                { "IgnoreDebugStubAttribute", IgnoreDebugStubAttribute.ToString() }
            };

            List <string> refs =
                (from reference in References
                 where reference.MetadataNames.OfType <string>().Contains("FullPath")
                 select reference.GetMetadata("FullPath")
                 into xFile
                 select Convert.ToString(xFile)).ToList();

            string Arguments = args.Aggregate("", (current, arg) => current + "\"" + arg.Key + ":" + arg.Value + "\" ");

            Arguments = refs.Aggregate(Arguments, (current, Ref) => current + "\"References:" + Ref + "\" ");
            Arguments = AssemblySearchDirs.Split(';').Aggregate(Arguments, (current, Dir) => current + "\"AssemblySearchDirs:" + Dir + "\" ");

            // replace \" by \\"
            Arguments = Arguments.Replace("\\\"", "\\\\\"");

            Log.LogMessage(MessageImportance.High, $"Invoking IL2CPU.exe {Arguments}");

            return(Arguments);
        }
Exemplo n.º 9
0
        protected override void Execute(CodeActivityContext executionContext)
        {
            try
            {
                EntityReference Template        = DocumentTemplateId.Get(executionContext);
                EntityReference Contact         = ContactId.Get(executionContext);
                Boolean         Logging         = EnableLogging.Get(executionContext);
                string          LicenseFilePath = LicenseFile.Get(executionContext);
                if (Logging)
                {
                    Log("Workflow Executed");
                }
                IWorkflowContext            context           = executionContext.GetExtension <IWorkflowContext>();
                IOrganizationServiceFactory serviceFactory    = executionContext.GetExtension <IOrganizationServiceFactory>();
                IOrganizationService        service           = serviceFactory.CreateOrganizationService(context.UserId);
                QueryExpression             RetrieveNoteQuery = new QueryExpression("annotation");
                RetrieveNoteQuery.ColumnSet = new ColumnSet(new string[] { "subject", "documentbody" });
                RetrieveNoteQuery.Criteria.AddCondition(new ConditionExpression("objectid", ConditionOperator.Equal, Template.Id));
                if (Logging)
                {
                    Log("Executing Query to retrieve Template Attachment");
                }
                EntityCollection Notes = service.RetrieveMultiple(RetrieveNoteQuery);
                if (Logging)
                {
                    Log("Attachment Retrieved Successfully");
                }
                if (Notes.Entities.Count > 0)
                {
                    Entity Note     = Notes[0];
                    string FileName = "";
                    if (Note.Contains("subject"))
                    {
                        FileName = Note["subject"].ToString();
                    }
                    if (Note.Contains("documentbody"))
                    {
                        if (Logging)
                        {
                            Log("Attachment Read Successfully");
                        }
                        byte[]       DocumentBody = Convert.FromBase64String(Note["documentbody"].ToString());
                        MemoryStream fileStream   = new MemoryStream(DocumentBody);
                        try
                        {
                            if (Logging)
                            {
                                Log("Enable Licensing");
                            }
                            if (LicenseFilePath != "" && File.Exists(LicenseFilePath))
                            {
                                Aspose.Words.License Lic = new License();
                                Lic.SetLicense(LicenseFilePath);
                                if (Logging)
                                {
                                    Log("License Set");
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Log("Error while applying license: " + ex.Message);
                        }
                        if (Logging)
                        {
                            Log("Reading Document in Aspose.Words");
                        }
                        Document doc    = new Document(fileStream);
                        string[] fields = doc.MailMerge.GetFieldNames();
                        if (Logging)
                        {
                            Log("Getting list of fields");
                        }
                        Entity contact = service.Retrieve("contact", Contact.Id, new ColumnSet(fields));
                        if (Logging)
                        {
                            Log("Retrieved Contact entity");
                        }
                        if (contact != null)
                        {
                            string[] values = new string[fields.Length];
                            for (int i = 0; i < fields.Length; i++)
                            {
                                if (contact.Contains(fields[i]))
                                {
                                    if (contact[fields[i]].GetType() == typeof(OptionSetValue))
                                    {
                                        values[i] = contact.FormattedValues[fields[i]].ToString();
                                    }
                                    else if (contact[fields[i]].GetType() == typeof(EntityReference))
                                    {
                                        values[i] = ((EntityReference)contact[fields[i]]).Name;
                                    }
                                    else
                                    {
                                        values[i] = contact[fields[i]].ToString();
                                    }
                                }
                                else
                                {
                                    values[i] = "";
                                }
                            }
                            if (Logging)
                            {
                                Log("Executing Mail Merge");
                            }
                            doc.MailMerge.Execute(fields, values);
                            MemoryStream UpdateDoc = new MemoryStream();
                            if (Logging)
                            {
                                Log("Saving Document");
                            }
                            doc.Save(UpdateDoc, SaveFormat.Docx);
                            byte[] byteData = UpdateDoc.ToArray();

                            // Encode the data using base64.
                            string encodedData = System.Convert.ToBase64String(byteData);

                            if (Logging)
                            {
                                Log("Creating Attachment");
                            }
                            Entity NewNote = new Entity("annotation");
                            // Im going to add Note to entity
                            NewNote.Attributes.Add("objectid", new EntityReference("contact", Contact.Id));
                            NewNote.Attributes.Add("subject", FileName);

                            // Set EncodedData to Document Body
                            NewNote.Attributes.Add("documentbody", encodedData);

                            // Set the type of attachment
                            NewNote.Attributes.Add("mimetype", @"application\ms-word");
                            NewNote.Attributes.Add("notetext", "Document Created using template");

                            // Set the File Name
                            NewNote.Attributes.Add("filename", FileName);
                            service.Create(NewNote);
                            if (Logging)
                            {
                                Log("Successfull");
                            }
                        }
                    }
                }
                if (Logging)
                {
                    Log("Workflow Executed Successfully");
                }
            }
            catch (Exception ex)
            {
                Log(ex.Message);
            }
        }
Exemplo n.º 10
0
        protected override void Execute(CodeActivityContext executionContext)
        {
            Boolean         Logging     = EnableLogging.Get(executionContext);
            string          LogFilePath = LogFile.Get(executionContext);
            EntityReference Email       = EmailId.Get(executionContext);
            EntityReference Attachment  = AttachmentId.Get(executionContext);

            try
            {
                if (Logging)
                {
                    Log("Workflow Execution Start", LogFilePath);
                }
                // Create CRM Service in Workflow
                IWorkflowContext            context        = executionContext.GetExtension <IWorkflowContext>();
                IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
                IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);
                if (Logging)
                {
                    Log("Retrieving Attahment", LogFilePath);
                }
                // Retrieve the Attachment from the given template
                Entity TempAttachment = service.Retrieve("annotation", Attachment.Id, new ColumnSet(true));
                if (TempAttachment != null)
                {
                    if (Logging)
                    {
                        Log("Creating New Attachment", LogFilePath);
                    }
                    // Create new Attachment under Email Activity
                    Entity NewAttachment = new Entity("activitymimeattachment");
                    if (TempAttachment.Contains("subject"))
                    {
                        NewAttachment.Attributes.Add("subject", TempAttachment["subject"]);
                    }
                    if (TempAttachment.Contains("filename"))
                    {
                        NewAttachment.Attributes.Add("filename", TempAttachment["filename"]);
                    }
                    if (TempAttachment.Contains("mimetype"))
                    {
                        NewAttachment.Attributes.Add("mimetype", TempAttachment["mimetype"]);
                    }
                    if (TempAttachment.Contains("documentbody"))
                    {
                        NewAttachment.Attributes.Add("body", TempAttachment["documentbody"]);
                    }
                    NewAttachment.Attributes.Add("objectid", new EntityReference(Email.LogicalName, Email.Id));
                    NewAttachment.Attributes.Add("objecttypecode", "email");
                    NewAttachment.Attributes.Add("attachmentnumber", 1);
                    service.Create(NewAttachment);
                    if (Logging)
                    {
                        Log("New Attachment Added To Email", LogFilePath);
                    }
                }
                else
                {
                    if (Logging)
                    {
                        Log("Temp Attachment doesnot exist", LogFilePath);
                    }
                }
                if (Logging)
                {
                    Log("Workflow Executed Successfully", LogFilePath);
                }
            }
            catch (Exception ex)
            {
                Log(ex.Message, LogFilePath);
            }
        }
Exemplo n.º 11
0
        protected override void Execute(CodeActivityContext executionContext)
        {
            EntityReference Template        = DocumentTemplateId.Get(executionContext);
            Boolean         Logging         = EnableLogging.Get(executionContext);
            string          LicenseFilePath = LicenseFile.Get(executionContext);
            string          LogFilePath     = LogFile.Get(executionContext);
            bool            savePrimary     = SavePrimary.Get(executionContext);
            string          saveAs          = SaveAs.Get(executionContext);

            OutputAttachmentId.Set(executionContext, new EntityReference("annotation", Guid.Empty));
            try
            {
                if (Logging)
                {
                    Log("Workflow Executed", LogFilePath);
                }
                IWorkflowContext            context        = executionContext.GetExtension <IWorkflowContext>();
                IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
                IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);
                string PrimaryEntityName = context.PrimaryEntityName;
                Guid   PrimaryEntityId   = context.PrimaryEntityId;
                try
                {
                    if (Logging)
                    {
                        Log("Enable Licensing", LogFilePath);
                    }
                    if (LicenseFilePath != "" && File.Exists(LicenseFilePath))
                    {
                        License Lic = new License();
                        Lic.SetLicense(LicenseFilePath);
                        if (Logging)
                        {
                            Log("License Set", LogFilePath);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log("Error while applying license: " + ex.Message, LogFilePath);
                }
                QueryExpression RetrieveNoteQuery = new QueryExpression("annotation");
                RetrieveNoteQuery.ColumnSet = new ColumnSet(new string[] { "subject", "documentbody" });
                RetrieveNoteQuery.Criteria.AddCondition(new ConditionExpression("objectid", ConditionOperator.Equal, Template.Id));
                if (Logging)
                {
                    Log("Executing Query to retrieve Template Attachment", LogFilePath);
                }
                EntityCollection Notes = service.RetrieveMultiple(RetrieveNoteQuery);
                if (Logging)
                {
                    Log("Attachment Retrieved Successfully", LogFilePath);
                }
                if (Notes.Entities.Count > 0)
                {
                    Entity Note     = Notes[0];
                    string FileName = "";
                    if (Note.Contains("filename"))
                    {
                        FileName = Note["filename"].ToString();
                    }
                    if (Note.Contains("documentbody"))
                    {
                        if (Logging)
                        {
                            Log("Attachment Read Successfully", LogFilePath);
                        }
                        byte[]       DocumentBody = Convert.FromBase64String(Note["documentbody"].ToString());
                        MemoryStream fileStream   = new MemoryStream(DocumentBody);
                        if (Logging)
                        {
                            Log("Reading Document in Aspose.Words", LogFilePath);
                        }
                        Document doc = new Document(fileStream);
                        if (Logging)
                        {
                            Log("Getting Fields list", LogFilePath);
                        }

                        string[] fields = doc.MailMerge.GetFieldNames();
                        if (Logging)
                        {
                            Log("Getting list of fields for entity", LogFilePath);
                        }
                        Entity PrimaryEntity = service.Retrieve(PrimaryEntityName, PrimaryEntityId, new ColumnSet(fields));
                        if (Logging)
                        {
                            Log("Retrieved Contact entity", LogFilePath);
                        }
                        if (PrimaryEntity != null)
                        {
                            string[] values = new string[fields.Length];
                            for (int i = 0; i < fields.Length; i++)
                            {
                                if (PrimaryEntity.Contains(fields[i]))
                                {
                                    if (PrimaryEntity[fields[i]].GetType() == typeof(OptionSetValue))
                                    {
                                        values[i] = PrimaryEntity.FormattedValues[fields[i]].ToString();
                                    }
                                    else if (PrimaryEntity[fields[i]].GetType() == typeof(EntityReference))
                                    {
                                        values[i] = ((EntityReference)PrimaryEntity[fields[i]]).Name;
                                    }
                                    else
                                    {
                                        values[i] = PrimaryEntity[fields[i]].ToString();
                                    }
                                }
                                else
                                {
                                    values[i] = "";
                                }
                            }
                            if (Logging)
                            {
                                Log("Executing Mail Merge", LogFilePath);
                            }
                            doc.MailMerge.Execute(fields, values);
                            MemoryStream UpdateDoc = new MemoryStream();
                            if (Logging)
                            {
                                Log("Saving Document", LogFilePath);
                            }
                            switch (saveAs.ToLower())
                            {
                            case "bmp":
                                doc.Save(UpdateDoc, SaveFormat.Bmp);
                                break;

                            case "doc":
                                doc.Save(UpdateDoc, SaveFormat.Doc);
                                break;

                            case "html":
                                doc.Save(UpdateDoc, SaveFormat.Html);
                                break;

                            case "jpeg":
                                doc.Save(UpdateDoc, SaveFormat.Jpeg);
                                break;

                            case "pdf":
                                doc.Save(UpdateDoc, SaveFormat.Pdf);
                                break;

                            case "png":
                                doc.Save(UpdateDoc, SaveFormat.Png);
                                break;

                            case "rtf":
                                doc.Save(UpdateDoc, SaveFormat.Rtf);
                                break;

                            case "text":
                            case "txt":
                                doc.Save(UpdateDoc, SaveFormat.Text);
                                break;

                            default:
                                doc.Save(UpdateDoc, SaveFormat.Docx);
                                break;
                            }
                            byte[] byteData = UpdateDoc.ToArray();
                            // Encode the data using base64.
                            string encodedData = System.Convert.ToBase64String(byteData);

                            if (Logging)
                            {
                                Log("Creating Attachment", LogFilePath);
                            }
                            Entity NewNote = new Entity("annotation");
                            // Im going to add Note to entity
                            if (savePrimary)
                            {
                                NewNote.Attributes.Add("objectid", new EntityReference(PrimaryEntityName, PrimaryEntityId));
                            }
                            NewNote.Attributes.Add("subject", FileName != "" ? FileName : "Aspose .NET AutoMerge Created Document." + saveAs);

                            // Set EncodedData to Document Body
                            NewNote.Attributes.Add("documentbody", encodedData);

                            // Set the type of attachment
                            NewNote.Attributes.Add("mimetype", @"application/vnd.openxmlformats-officedocument.wordprocessingml.document");
                            NewNote.Attributes.Add("notetext", "Document Created using template");

                            // Set the File Name
                            NewNote.Attributes.Add("filename", FileName != "" ? FileName : "Aspose .NET AutoMerge Created Document." + saveAs);
                            Guid NewNoteId = service.Create(NewNote);
                            OutputAttachmentId.Set(executionContext, new EntityReference("annotation", NewNoteId));
                            if (Logging)
                            {
                                Log("Successfull", LogFilePath);
                            }
                        }
                    }
                }

                if (Logging)
                {
                    Log("Workflow Executed Successfully", LogFilePath);
                }
            }
            catch (Exception ex)
            {
                Log(ex.Message, LogFilePath);
                if (ex.InnerException != null)
                {
                    Log(ex.InnerException.Message, LogFilePath);
                }
            }
        }
        protected override void Execute(CodeActivityContext executionContext)
        {
            try
            {
                EntityReference FirstAttachment  = FirstAttachmentId.Get(executionContext);
                EntityReference SecondAttachment = SecondAttachmentId.Get(executionContext);
                EntityReference Contact          = ContactId.Get(executionContext);
                string          Option           = OutputOption.Get(executionContext);
                Boolean         Logging          = EnableLogging.Get(executionContext);
                string          LicenseFilePath  = LicenseFile.Get(executionContext);

                if (Logging)
                {
                    Log("Workflow Executed");
                }

                // Create a CRM Service in Workflow.
                IWorkflowContext            context        = executionContext.GetExtension <IWorkflowContext>();
                IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
                IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

                if (Logging)
                {
                    Log("Executing Query to retrieve First Attachment");
                }

                Entity FirstNote = service.Retrieve("annotation", FirstAttachment.Id, new ColumnSet(new string[] { "subject", "documentbody" }));

                if (Logging)
                {
                    Log("First Attachment Retrieved Successfully");
                }
                if (Logging)
                {
                    Log("Executing Query to retrieve Second Attachment");
                }

                Entity SecondNote = service.Retrieve("annotation", SecondAttachment.Id, new ColumnSet(new string[] { "subject", "documentbody" }));

                if (Logging)
                {
                    Log("Second Attachment Retrieved Successfully");
                }

                MemoryStream fileStream1 = null, fileStream2 = null;
                string       FileName1 = "";
                string       FileName2 = "";
                if (FirstNote != null && FirstNote.Contains("documentbody"))
                {
                    byte[] DocumentBody = Convert.FromBase64String(FirstNote["documentbody"].ToString());
                    fileStream1 = new MemoryStream(DocumentBody);
                    if (FirstNote.Contains("filename"))
                    {
                        FileName1 = FirstNote["filename"].ToString();
                    }
                }
                if (SecondNote != null && SecondNote.Contains("documentbody"))
                {
                    byte[] DocumentBody = Convert.FromBase64String(SecondNote["documentbody"].ToString());
                    fileStream2 = new MemoryStream(DocumentBody);
                    if (SecondNote.Contains("filename"))
                    {
                        FileName2 = SecondNote["filename"].ToString();
                    }
                }
                try
                {
                    if (Logging)
                    {
                        Log("Enable Licensing");
                    }

                    if (LicenseFilePath != "" && File.Exists(LicenseFilePath))
                    {
                        Aspose.Words.License Lic = new License();
                        Lic.SetLicense(LicenseFilePath);
                        if (Logging)
                        {
                            Log("License Set");
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log("Error while applying license: " + ex.Message);
                }

                if (Logging)
                {
                    Log("Merging Documents");
                }

                Document doc1 = new Document(fileStream1);
                Document doc2 = new Document(fileStream2);
                doc1.AppendDocument(doc2, ImportFormatMode.KeepSourceFormatting);

                if (Logging)
                {
                    Log("Merging Complete");
                }

                MemoryStream UpdateDoc = new MemoryStream();

                if (Logging)
                {
                    Log("Saving Document");
                }

                doc1.Save(UpdateDoc, SaveFormat.Docx);
                byte[] byteData = UpdateDoc.ToArray();

                // Encode the data using base64.
                string encodedData = System.Convert.ToBase64String(byteData);

                if (Logging)
                {
                    Log("Creating Attachment");
                }

                Entity NewNote = new Entity("annotation");

                // Add a note to the entity.
                NewNote.Attributes.Add("objectid", new EntityReference("contact", Contact.Id));

                // Set EncodedData to Document Body.
                NewNote.Attributes.Add("documentbody", encodedData);

                // Set the type of attachment.
                NewNote.Attributes.Add("mimetype", @"application\ms-word");
                NewNote.Attributes.Add("notetext", "Document Created using template");

                if (Option == "0")
                {
                    NewNote.Id = FirstNote.Id;
                    NewNote.Attributes.Add("subject", FileName1);
                    NewNote.Attributes.Add("filename", FileName1);
                    service.Update(NewNote);
                }
                else if (Option == "1")
                {
                    NewNote.Id = SecondNote.Id;
                    NewNote.Attributes.Add("subject", FileName2);
                    NewNote.Attributes.Add("filename", FileName2);
                    service.Update(NewNote);
                }
                else
                {
                    NewNote.Attributes.Add("subject", "Aspose .Net Document Merger");
                    NewNote.Attributes.Add("filename", "Aspose .Net Document Merger.docx");
                    service.Create(NewNote);
                }
                if (Logging)
                {
                    Log("Successfull");
                }
            }
            catch (Exception ex)
            {
                Log(ex.Message);
            }
        }
Exemplo n.º 13
0
        protected override void Execute(CodeActivityContext executionContext)
        {
            bool   Logging         = EnableLogging.Get(executionContext);
            string LicenseFilePath = LicenseFile.Get(executionContext);
            string LogFilePath     = LogFile.Get(executionContext);
            int    detectIn        = DetectIn.Get(executionContext);

            OutputAttachmentId.Set(executionContext, new EntityReference("annotation", Guid.Empty));

            if (Logging)
            {
                Log("Execution Started", LogFilePath);
            }

            // Create a CRM Service in Workflow.
            IWorkflowContext            context        = executionContext.GetExtension <IWorkflowContext>();
            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

            try
            {
                if (Logging)
                {
                    Log("Enable Licensing", LogFilePath);
                }

                if (LicenseFilePath != "" && File.Exists(LicenseFilePath))
                {
                    License Lic = new License();
                    Lic.SetLicense(LicenseFilePath);

                    if (Logging)
                    {
                        Log("License Set", LogFilePath);
                    }
                }
            }
            catch (Exception ex)
            {
                Log("Error while applying license: " + ex.Message, LogFilePath);
            }

            if (detectIn == 0) // Under this record.
            {
                Guid            ThisRecordId = context.PrimaryEntityId;
                string          RecordType   = context.PrimaryEntityName;
                Document        Result       = new Document();
                DocumentBuilder ResultWriter = new DocumentBuilder(Result);

                if (Logging)
                {
                    Log("Working under all attachments under this record", LogFilePath);
                }

                QueryExpression RetrieveNoteQuery = new QueryExpression("annotation");
                RetrieveNoteQuery.ColumnSet = new ColumnSet(new string[] { "filename", "subject", "documentbody" });
                RetrieveNoteQuery.Criteria.AddCondition(new ConditionExpression("objectid", ConditionOperator.Equal, ThisRecordId));

                if (Logging)
                {
                    Log("Executing Query to retrieve All Notes within this record", LogFilePath);
                }

                EntityCollection Notes = service.RetrieveMultiple(RetrieveNoteQuery);

                foreach (Entity Note in Notes.Entities)
                {
                    try
                    {
                        if (Note.Contains("documentbody"))
                        {
                            string FileName = "";
                            if (Note.Contains("filename"))
                            {
                                FileName = Note["filename"].ToString();
                            }

                            byte[]       DocumentBody = Convert.FromBase64String(Note["documentbody"].ToString());
                            MemoryStream fileStream   = new MemoryStream(DocumentBody);
                            Document     doc          = new Document(fileStream);

                            ResultWriter.Writeln("Comparing Document: " + FileName);
                            ResultWriter.StartTable();

                            foreach (Entity OtherNote in Notes.Entities)
                            {
                                if (OtherNote.Id != Note.Id)
                                {
                                    if (OtherNote.Contains("documentbody"))
                                    {
                                        string OtherFileName = "";
                                        if (OtherNote.Contains("filename"))
                                        {
                                            OtherFileName = OtherNote["filename"].ToString();
                                        }
                                        byte[]       OtherDocumentBody = Convert.FromBase64String(OtherNote["documentbody"].ToString());
                                        MemoryStream fileStream2       = new MemoryStream(OtherDocumentBody);
                                        Document     doc2 = new Document(fileStream);

                                        ResultWriter.InsertCell();
                                        ResultWriter.Write(OtherFileName);

                                        doc.Compare(doc2, "a", DateTime.Now);
                                        if (doc.Revisions.Count == 0)
                                        {
                                            ResultWriter.InsertCell();
                                            ResultWriter.Write("Duplicate Documents");
                                        }
                                        ResultWriter.EndRow();
                                    }
                                }
                            }
                            ResultWriter.EndTable();
                        }
                    }
                    catch (Exception ex)
                    {
                        Log("Error while applying license: " + ex.Message, LogFilePath);
                    }
                }

                MemoryStream UpdateDoc = new MemoryStream();
                if (Logging)
                {
                    Log("Saving Document", LogFilePath);
                }

                Result.Save(UpdateDoc, SaveFormat.Docx);
                byte[] byteData = UpdateDoc.ToArray();

                // Encode the data using base64.
                string encodedData = System.Convert.ToBase64String(byteData);

                if (Logging)
                {
                    Log("Creating Attachment for result", LogFilePath);
                }

                // Add a Node to the entity.
                Entity NewNote = new Entity("annotation");
                NewNote.Attributes.Add("objectid", new EntityReference(RecordType, ThisRecordId));
                NewNote.Attributes.Add("subject", "Duplicate detection report");

                // Set EncodedData to Document Body.
                NewNote.Attributes.Add("documentbody", encodedData);

                // Set the type of attachment.
                NewNote.Attributes.Add("mimetype", @"application\ms-word");
                NewNote.Attributes.Add("notetext", "Duplicate detection report");

                // Set the filename.
                NewNote.Attributes.Add("filename", "Duplicate detection report");

                Guid NewNoteId = service.Create(NewNote);
                OutputAttachmentId.Set(executionContext, new EntityReference("annotation", NewNoteId));

                if (Logging)
                {
                    Log("Attachment Created Successfully", LogFilePath);
                }
            }
            else if (detectIn == 1) // Under this entity.
            {
                Guid            ThisRecordId = context.PrimaryEntityId;
                string          RecordType   = context.PrimaryEntityName;
                Document        Result       = new Document();
                DocumentBuilder ResultWriter = new DocumentBuilder(Result);

                if (Logging)
                {
                    Log("Working under all attachments under this Entity", LogFilePath);
                }

                QueryExpression RetrieveNoteQuery = new QueryExpression("annotation");
                RetrieveNoteQuery.ColumnSet = new ColumnSet(new string[] { "filename", "subject", "documentbody", "objectid" });

                if (Logging)
                {
                    Log("Executing Query to retrieve All Notes within this Entity", LogFilePath);
                }

                EntityCollection Notes = service.RetrieveMultiple(RetrieveNoteQuery);

                foreach (Entity Note in Notes.Entities)
                {
                    if (Note.Contains("objectid") && ((EntityReference)Note["objectid"]).LogicalName == RecordType)
                    {
                        try
                        {
                            if (Note.Contains("documentbody"))
                            {
                                string FileName = "";
                                if (Note.Contains("filename"))
                                {
                                    FileName = Note["filename"].ToString();
                                }

                                byte[]       DocumentBody = Convert.FromBase64String(Note["documentbody"].ToString());
                                MemoryStream fileStream   = new MemoryStream(DocumentBody);
                                Document     doc          = new Document(fileStream);

                                ResultWriter.Writeln("Comparing Document: " + FileName);
                                ResultWriter.StartTable();

                                foreach (Entity OtherNote in Notes.Entities)
                                {
                                    if (OtherNote.Id != Note.Id)
                                    {
                                        if (OtherNote.Contains("documentbody"))
                                        {
                                            string OtherFileName = "";
                                            if (OtherNote.Contains("filename"))
                                            {
                                                OtherFileName = OtherNote["filename"].ToString();
                                            }
                                            byte[]       OtherDocumentBody = Convert.FromBase64String(OtherNote["documentbody"].ToString());
                                            MemoryStream fileStream2       = new MemoryStream(OtherDocumentBody);
                                            Document     doc2 = new Document(fileStream);

                                            ResultWriter.InsertCell();
                                            ResultWriter.Write(OtherFileName);

                                            doc.Compare(doc2, "a", DateTime.Now);
                                            if (doc.Revisions.Count == 0)
                                            {
                                                ResultWriter.InsertCell();
                                                ResultWriter.Write("Duplicate Documents");
                                            }
                                            ResultWriter.EndRow();
                                        }
                                    }
                                }
                                ResultWriter.EndTable();
                            }
                        }
                        catch (Exception ex)
                        {
                            Log("Error while applying license: " + ex.Message, LogFilePath);
                        }
                    }
                }
                MemoryStream UpdateDoc = new MemoryStream();
                if (Logging)
                {
                    Log("Saving Document", LogFilePath);
                }

                Result.Save(UpdateDoc, SaveFormat.Docx);
                byte[] byteData = UpdateDoc.ToArray();

                // Encode the data using base64.
                string encodedData = System.Convert.ToBase64String(byteData);

                if (Logging)
                {
                    Log("Creating Attachment for result", LogFilePath);
                }

                // Add a Note do the endity.
                Entity NewNote = new Entity("annotation");
                NewNote.Attributes.Add("objectid", new EntityReference(RecordType, ThisRecordId));
                NewNote.Attributes.Add("subject", "Duplicate detection report");

                // Set EncodedData to Document Body.
                NewNote.Attributes.Add("documentbody", encodedData);

                // Set the type of attachment.
                NewNote.Attributes.Add("mimetype", @"application\ms-word");
                NewNote.Attributes.Add("notetext", "Duplicate detection report");

                // Set the filename.
                NewNote.Attributes.Add("filename", "Duplicate detection report");

                Guid NewNoteId = service.Create(NewNote);
                OutputAttachmentId.Set(executionContext, new EntityReference("annotation", NewNoteId));

                if (Logging)
                {
                    Log("Attachment Created Successfully", LogFilePath);
                }
            }
            else if (detectIn == 2) // Under whole organization.
            {
                Guid            ThisRecordId = context.PrimaryEntityId;
                string          RecordType   = context.PrimaryEntityName;
                Document        Result       = new Document();
                DocumentBuilder ResultWriter = new DocumentBuilder(Result);

                if (Logging)
                {
                    Log("Working under all attachments under this Entity", LogFilePath);
                }

                QueryExpression RetrieveNoteQuery = new QueryExpression("annotation");

                if (Logging)
                {
                    Log("Executing Query to retrieve All Notes within this Entity", LogFilePath);
                }

                EntityCollection Notes = service.RetrieveMultiple(RetrieveNoteQuery);

                foreach (Entity Note in Notes.Entities)
                {
                    try
                    {
                        if (Note.Contains("documentbody"))
                        {
                            string FileName = "";
                            if (Note.Contains("filename"))
                            {
                                FileName = Note["filename"].ToString();
                            }

                            byte[]       DocumentBody = Convert.FromBase64String(Note["documentbody"].ToString());
                            MemoryStream fileStream   = new MemoryStream(DocumentBody);
                            Document     doc          = new Document(fileStream);

                            ResultWriter.Writeln("Comparing Document: " + FileName);
                            ResultWriter.StartTable();

                            foreach (Entity OtherNote in Notes.Entities)
                            {
                                if (OtherNote.Id != Note.Id)
                                {
                                    if (OtherNote.Contains("documentbody"))
                                    {
                                        string OtherFileName = "";
                                        if (OtherNote.Contains("filename"))
                                        {
                                            OtherFileName = OtherNote["filename"].ToString();
                                        }
                                        byte[]       OtherDocumentBody = Convert.FromBase64String(OtherNote["documentbody"].ToString());
                                        MemoryStream fileStream2       = new MemoryStream(OtherDocumentBody);
                                        Document     doc2 = new Document(fileStream);

                                        ResultWriter.InsertCell();
                                        ResultWriter.Write(OtherFileName);

                                        doc.Compare(doc2, "a", DateTime.Now);
                                        if (doc.Revisions.Count == 0)
                                        {
                                            ResultWriter.InsertCell();
                                            ResultWriter.Write("Duplicate Documents");
                                        }
                                        ResultWriter.EndRow();
                                    }
                                }
                            }
                            ResultWriter.EndTable();
                        }
                    }
                    catch (Exception ex)
                    {
                        Log("Error while applying license: " + ex.Message, LogFilePath);
                    }
                }
                MemoryStream UpdateDoc = new MemoryStream();
                if (Logging)
                {
                    Log("Saving Document", LogFilePath);
                }

                Result.Save(UpdateDoc, SaveFormat.Docx);
                byte[] byteData = UpdateDoc.ToArray();

                // Encode the data using base64.
                string encodedData = System.Convert.ToBase64String(byteData);

                if (Logging)
                {
                    Log("Creating Attachment for result", LogFilePath);
                }

                // Add a Node to the entity.
                Entity NewNote = new Entity("annotation");
                NewNote.Attributes.Add("objectid", new EntityReference(RecordType, ThisRecordId));
                NewNote.Attributes.Add("subject", "Duplicate detection report");

                // Set EncodedData to Document Body.
                NewNote.Attributes.Add("documentbody", encodedData);

                // Set the type of attachment.
                NewNote.Attributes.Add("mimetype", @"application\ms-word");
                NewNote.Attributes.Add("notetext", "Duplicate detection report");

                // Set the filename.
                NewNote.Attributes.Add("filename", "Duplicate detection report");

                Guid NewNoteId = service.Create(NewNote);
                OutputAttachmentId.Set(executionContext, new EntityReference("annotation", NewNoteId));

                if (Logging)
                {
                    Log("Attachment Created Successfully", LogFilePath);
                }
            }
        }
Exemplo n.º 14
0
        protected override void Execute(CodeActivityContext executionContext)
        {
            Boolean                     Logging        = EnableLogging.Get(executionContext);
            EntityReference             Letter         = LetterId.Get(executionContext);
            EntityReference             Attachment     = AttachmentId.Get(executionContext);
            IWorkflowContext            context        = executionContext.GetExtension <IWorkflowContext>();
            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

            try
            {
                if (Logging)
                {
                    Log("Workflow Execution Start", service);
                }
                if (Logging)
                {
                    Log("Retrieving Attahment", service);
                }
                Entity TempAttachment = service.Retrieve("annotation", Attachment.Id, new ColumnSet(true));
                if (TempAttachment != null)
                {
                    if (Logging)
                    {
                        Log("Creating New Attachment", service);
                    }
                    Entity NewAttachment = new Entity("annotation");
                    if (TempAttachment.Contains("subject"))
                    {
                        NewAttachment.Attributes.Add("subject", TempAttachment["subject"]);
                    }
                    if (TempAttachment.Contains("filename"))
                    {
                        NewAttachment.Attributes.Add("filename", TempAttachment["filename"]);
                    }
                    if (TempAttachment.Contains("notetext"))
                    {
                        NewAttachment.Attributes.Add("notetext", TempAttachment["notetext"]);
                    }
                    if (TempAttachment.Contains("mimetype"))
                    {
                        NewAttachment.Attributes.Add("mimetype", TempAttachment["mimetype"]);
                    }
                    if (TempAttachment.Contains("documentbody"))
                    {
                        NewAttachment.Attributes.Add("documentbody", TempAttachment["documentbody"]);
                    }
                    NewAttachment.Attributes.Add("objectid", new EntityReference(Letter.LogicalName, Letter.Id));
                    service.Create(NewAttachment);
                    if (Logging)
                    {
                        Log("New Attachment Added To Letter", service);
                    }
                }
                else
                {
                    if (Logging)
                    {
                        Log("Temp Attachment doesnot exist", service);
                    }
                }
                if (Logging)
                {
                    Log("Workflow Executed Successfully", service);
                }
            }
            catch (Exception ex)
            {
                Log(ex.Message, service);
                throw ex;
            }
        }
Exemplo n.º 15
0
        protected override void Execute(CodeActivityContext executionContext)
        {
            Boolean         Logging     = EnableLogging.Get(executionContext);
            string          LogFilePath = LogFile.Get(executionContext);
            EntityReference Attachment  = AttachmentId.Get(executionContext);

            OutputAttachmentId.Set(executionContext, new EntityReference("annotation", Guid.Empty));
            try
            {
                if (Logging)
                {
                    Log("Workflow Execution Start", LogFilePath);
                }
                IWorkflowContext            context        = executionContext.GetExtension <IWorkflowContext>();
                IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
                IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);
                if (Logging)
                {
                    Log("Reading Attachment", LogFilePath);
                }
                Entity ExistingAttachment = service.Retrieve(Attachment.LogicalName, Attachment.Id, new ColumnSet(true));
                if (ExistingAttachment != null)
                {
                    if (Logging)
                    {
                        Log("Creating New Attachment", LogFilePath);
                    }

                    // Create new Attachment under Email Activity.
                    Entity NewAttachment = new Entity("annotation");
                    if (ExistingAttachment.Contains("subject"))
                    {
                        NewAttachment.Attributes.Add("subject", ExistingAttachment["subject"]);
                    }
                    if (ExistingAttachment.Contains("filename"))
                    {
                        NewAttachment.Attributes.Add("filename", ExistingAttachment["filename"]);
                    }
                    if (ExistingAttachment.Contains("mimetype"))
                    {
                        NewAttachment.Attributes.Add("mimetype", ExistingAttachment["mimetype"]);
                    }
                    if (ExistingAttachment.Contains("documentbody"))
                    {
                        NewAttachment.Attributes.Add("documentbody", ExistingAttachment["documentbody"]);
                    }
                    Guid NewAttachmentId = service.Create(NewAttachment);
                    OutputAttachmentId.Set(executionContext, new EntityReference("annotation", NewAttachmentId));
                    if (Logging)
                    {
                        Log("New Attachment Created", LogFilePath);
                    }
                }
                else
                {
                    if (Logging)
                    {
                        Log("Provided Attachment doesnot exist", LogFilePath);
                    }
                }
                if (Logging)
                {
                    Log("Workflow Executed Successfully", LogFilePath);
                }
            }
            catch (Exception ex)
            {
                Log(ex.Message, LogFilePath);
            }
        }
        protected override void Execute(CodeActivityContext executionContext)
        {
            EntityReference DocumentTemplateIdValue = DocumentTemplateId.Get(executionContext);
            Boolean         EnableLoggingValue      = EnableLogging.Get(executionContext);
            string          ProductUriValue         = ProductUri.Get(executionContext);
            string          AppSIDValue             = AppSID.Get(executionContext);
            string          AppKeyValue             = AppKey.Get(executionContext);
            Boolean         DeleteTemplateValue     = DeleteTemplate.Get(executionContext);
            Boolean         DeleteDocumentValue     = DeleteDocument.Get(executionContext);

            OutputAttachmentId.Set(executionContext, new EntityReference("annotation", Guid.Empty));
            CloudAppConfig config = new CloudAppConfig();

            config.ProductUri = ProductUriValue;
            config.AppSID     = AppSIDValue;
            config.AppKey     = AppKeyValue;
            IWorkflowContext            context        = executionContext.GetExtension <IWorkflowContext>();
            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

            try
            {
                if (EnableLoggingValue)
                {
                    Log("WorkFlow Started", service);
                }

                string PrimaryEntityName = context.PrimaryEntityName;
                Guid   PrimaryEntityId   = context.PrimaryEntityId;
                if (EnableLoggingValue)
                {
                    Log("Retrieving Attachment From Template", service);
                }
                QueryExpression RetrieveNoteQuery = new QueryExpression("annotation");
                RetrieveNoteQuery.ColumnSet = new ColumnSet(new string[] { "filename", "documentbody", "mimetype" });
                RetrieveNoteQuery.Criteria.AddCondition(new ConditionExpression("objectid", ConditionOperator.Equal, DocumentTemplateIdValue.Id));
                EntityCollection TemplateAttachments = service.RetrieveMultiple(RetrieveNoteQuery);
                if (EnableLoggingValue)
                {
                    Log("Attachment Retrieved Successfully", service);
                }

                if (TemplateAttachments != null && TemplateAttachments.Entities.Count > 0)
                {
                    Entity AttachmentTemplate = TemplateAttachments.Entities[0];
                    if (AttachmentTemplate.Contains("mimetype") && AttachmentTemplate.Contains("documentbody"))
                    {
                        string FileName = "";
                        if (AttachmentTemplate.Contains("filename"))
                        {
                            FileName = AttachmentTemplate["filename"].ToString();
                        }
                        config.FileName = FileName;
                        byte[]       DocumentBody = Convert.FromBase64String(AttachmentTemplate["documentbody"].ToString());
                        MemoryStream fileStream   = new MemoryStream(DocumentBody);

                        if (EnableLoggingValue)
                        {
                            Log("Upload Template on Storage", service);
                        }
                        UploadFileOnStorage(config, fileStream);

                        if (EnableLoggingValue)
                        {
                            Log("Get Fields List", service);
                        }
                        string[] Fields = GetFieldsName(config).ToArray();

                        if (EnableLoggingValue)
                        {
                            Log("Retrieving Fields Values From CRM", service);
                        }
                        Entity   PrimaryEntity = service.Retrieve(PrimaryEntityName, PrimaryEntityId, new ColumnSet(Fields));
                        string[] Values        = new string[Fields.Length];
                        if (PrimaryEntity != null)
                        {
                            for (int i = 0; i < Fields.Length; i++)
                            {
                                if (PrimaryEntity.Contains(Fields[i]))
                                {
                                    if (PrimaryEntity[Fields[i]].GetType() == typeof(OptionSetValue))
                                    {
                                        Values[i] = PrimaryEntity.FormattedValues[Fields[i]].ToString();
                                    }
                                    else if (PrimaryEntity[Fields[i]].GetType() == typeof(EntityReference))
                                    {
                                        Values[i] = ((EntityReference)PrimaryEntity[Fields[i]]).Name;
                                    }
                                    else
                                    {
                                        Values[i] = PrimaryEntity[Fields[i]].ToString();
                                    }
                                }
                                else
                                {
                                    Values[i] = "";
                                }
                            }
                        }

                        if (EnableLoggingValue)
                        {
                            Log("Generating Xml", service);
                        }
                        string Xml = GenerateXML(Fields, Values);

                        if (EnableLoggingValue)
                        {
                            Log("Executing MailMerge", service);
                        }
                        string OutputFileName = ExecuteMailMerge(config, Xml);

                        if (EnableLoggingValue)
                        {
                            Log("Downloading File From Cloud", service);
                        }
                        MemoryStream OutputFile = DownloadFile(config, OutputFileName);

                        if (EnableLoggingValue)
                        {
                            Log("Generating CRM Attachment", service);
                        }
                        byte[] byteData    = OutputFile.ToArray();
                        string encodedData = System.Convert.ToBase64String(byteData);
                        Entity NewNote     = new Entity("annotation");
                        NewNote.Attributes.Add("objectid", new EntityReference(PrimaryEntityName, PrimaryEntityId));
                        NewNote.Attributes.Add("subject", FileName);
                        NewNote.Attributes.Add("documentbody", encodedData);
                        NewNote.Attributes.Add("mimetype", @"application/vnd.openxmlformats-officedocument.wordprocessingml.document");
                        NewNote.Attributes.Add("notetext", "Document Created using Aspose Cloud");
                        NewNote.Attributes.Add("filename", FileName);
                        Guid NewNoteId = service.Create(NewNote);

                        if (EnableLoggingValue)
                        {
                            Log("Removing Documents from Storage", service);
                        }
                        if (DeleteTemplateValue)
                        {
                            DeleteDocumentFromStorage(config, FileName);
                        }
                        if (DeleteDocumentValue)
                        {
                            DeleteDocumentFromStorage(config, OutputFileName);
                        }

                        OutputAttachmentId.Set(executionContext, new EntityReference("annotation", NewNoteId));
                    }
                    else
                    {
                        if (EnableLoggingValue)
                        {
                            Log("Attachment Doesnot contain any document", service);
                        }
                    }
                }
                else
                {
                    if (EnableLoggingValue)
                    {
                        Log("No Attachments in the Template Provided", service);
                    }
                }

                if (EnableLoggingValue)
                {
                    Log("Workflow Executed Successfully", service);
                }
            }
            catch (Exception ex)
            {
                Log(ex.Message, service);
                throw ex;
            }
        }