internal static WordCRMConfig GetCRMConfig(IOrganizationService crm)
        {
            try
            {
                var query = new QueryExpression("pp_signicatconfig");
                query.ColumnSet = new ColumnSet(true);
                var results = crm.RetrieveMultiple(query);

                if (results.Entities.Count == 1)
                {
                    var entity = results.Entities[0];

                    var config = new WordCRMConfig();
                    config.Worduser           = entity.GetAttributeValue <EntityReference>("pp_wordsignuser");
                    config.Entitylogicalnames = entity.GetAttributeValue <string>("pp_entitylogicalnames");
                    config.SPUser             = entity.GetAttributeValue <string>("pp_spuser");
                    config.SPpassword         = entity.GetAttributeValue <string>("pp_sppassord");
                    config.Webapiurl          = entity.GetAttributeValue <string>("pp_webapiurl");
                    config.Wordsaveinsp       = entity.GetAttributeValue <bool>("pp_wordsaveinsp");
                    config.Wordsigningmethod  = entity.GetAttributeValue <OptionSetValue>("pp_signing").Value;

                    var senderRef = crm.Retrieve("systemuser", config.Worduser.Id, new ColumnSet("fullname"));
                    config.Wordusername = senderRef.GetAttributeValue <string>("fullname");

                    config.AccountNrField  = entity.GetAttributeValue <string>("pp_accountnumberfield");
                    config.OrderNrField    = entity.GetAttributeValue <string>("pp_ordernumberfield");
                    config.IncidentNrField = entity.GetAttributeValue <string>("pp_incidentnumberfield");
                    config.QuoteNrField    = entity.GetAttributeValue <string>("pp_quotenumberfield");
                    config.ContractNrField = entity.GetAttributeValue <string>("pp_contractnumberfield");
                    config.EmailField      = entity.GetAttributeValue <string>("pp_emailfield");

                    return(config);
                }
                return(null);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot find value in Signicat config in CRM: " + ex.Message, "Document Signing", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(null);
            }
        }
        public async Task <HttpResponseMessage> SendRequest(WordSearchObject searchValues, Document doc, string pdfName,
                                                            string orgName, WordCRMConfig crmconfig, IOrganizationService crm)
        {
            try
            {
                using (var client = new HttpClient())
                {
                    using (var content = new MultipartFormDataContent())
                    {
                        var apiurl = crmconfig.Webapiurl;
                        client.BaseAddress = new Uri(apiurl);
                        client.DefaultRequestHeaders.Accept.Clear();
                        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/pdf"));

                        StreamReader sr          = new StreamReader(doc.Path + "\\" + pdfName);
                        var          fileContent = new ByteArrayContent(WordHelpers.ReadToEnd(sr.BaseStream));
                        var          orgname     = new NameValueHeaderValue("orgname", orgName);
                        var          language    = new NameValueHeaderValue("language", searchValues.language.ToString());
                        var          method      = new NameValueHeaderValue("method", crmconfig.Wordsigningmethod.ToString());
                        //pdfName = Convert.ToBase64String(Encoding.UTF8.GetBytes(pdfName));

                        fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                        {
                            FileName   = pdfName,
                            Parameters = { orgname, language, method }
                        };
                        fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
                        content.Add(fileContent);

                        var response = client.PostAsync("api/SignRequest/PostWord", content).Result;
                        sr.Close();
                        return(response);
                    }
                }
            }

            catch (Exception ex)
            {
                return(new HttpResponseMessage(HttpStatusCode.ExpectationFailed));
            }
        }
        internal static Guid CreatDocumentSigningInCRM(string sdsurl, string docPath, string docName, Entity entity,
                                                       WordSearchObject searchValues, WordCRMConfig crmconfig, IOrganizationService crm)
        {
            try
            {
                var parts     = sdsurl.Split('=');
                var taskid    = parts.Last();
                var requestid = GetRequestId(sdsurl);

                var saveinsp = crmconfig.Wordsaveinsp;


                //Create signing package
                var documentsigning = new Entity("pp_documentsigning");
                documentsigning["pp_name"]      = "Word dokument: " + docName;
                documentsigning["pp_requestid"] = requestid;
                documentsigning["pp_signing"]   = new OptionSetValue(crmconfig.Wordsigningmethod);

                if (saveinsp)
                {
                    documentsigning["pp_saveindocumentlocation"] = true;
                }

                if (entity != null)
                {
                    var regardingidfield = "pp_" + entity.LogicalName + "id";
                    documentsigning[regardingidfield] = new EntityReference(entity.LogicalName, entity.Id);
                }

                var documentsigningid = crm.Create(documentsigning);

                //Save doc as note in singing package
                SavePDFInCRM(searchValues, docName, docPath, documentsigningid, crm);

                //Create signing task
                var documenttask = new Entity("pp_signicatdocurl");
                documenttask["pp_name"]   = taskid;
                documenttask["pp_sdsurl"] = sdsurl;
                if (documentsigningid != Guid.Empty)
                {
                    documenttask["pp_documentsigningid"] = new EntityReference("pp_documentsigning", documentsigningid);
                }
                documenttask["statuscode"] = new OptionSetValue(1);
                var documenttaskid = crm.Create(documenttask);

                CreateOrAddContact(searchValues.recievermail, documenttaskid, documentsigningid, crm);

                return(documentsigningid);
            }
            catch (Exception ex)
            {
                if (searchValues.language == 1044)
                {
                    MessageBox.Show(Resources.ResourceWordNb.cannotcreateinsignicat + ex.Message, Resources.ResourceWordNb.documentsinging, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    MessageBox.Show(Resources.ResourceWordEn.cannotcreateinsignicat + ex.Message, Resources.ResourceWordEn.documentsinging, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                return(Guid.Empty);
            }
        }
        internal static void SendEmail(string sdsurl, string docName, Entity entity, Guid documentsigningid,
                                       WordSearchObject searchValues, WordCRMConfig crmconfig, IOrganizationService crm)
        {
            try
            {
                var linkBtnImg   = "https://ppsignicatresources.blob.core.windows.net/signicatlinkbutton/SignicatLinkButton.png";
                var emailLogoImg = "https://ppsignicatresources.blob.core.windows.net/signicatlinkbutton/SignicatMailLogo.png";

                var url = "";
                if (searchValues.language == 1044)
                {
                    url = "<br/><a href='" + sdsurl + "'><img alt='Click her' src='" + linkBtnImg + "'></a>";
                }
                else
                {
                    url = "<br/><a href='" + sdsurl + "'><img alt='Click here' src='" + linkBtnImg + "'></a>";
                }

                // Create an e-mail message.
                Entity email = new Entity("email");

                if (crmconfig.Worduser == null)
                {
                    if (searchValues.language == 1044)
                    {
                        MessageBox.Show(Resources.ResourceWordNb.cannotfindsender);
                    }
                    else
                    {
                        MessageBox.Show(Resources.ResourceWordEn.cannotfindsender);
                    }
                }

                if (crmconfig.Worduser != null)
                {
                    Entity fromParty = new Entity("activityparty");
                    fromParty["partyid"] = crmconfig.Worduser;
                    var listfrom = new List <Entity>()
                    {
                        fromParty
                    };
                    email["from"] = new EntityCollection(listfrom);
                }

                Entity toParty = new Entity("activityparty");
                //if (string.IsNullOrWhiteSpace(searchValues.recievermail) && entity != null)
                //    toParty["partyid"] = new EntityReference(entity.LogicalName, entity.Id);
                if (!string.IsNullOrWhiteSpace(searchValues.recievermail))
                {
                    var reciever = GetCustomerByEmail(searchValues.recievermail, crm);
                    if (reciever != null)
                    {
                        toParty["partyid"] = reciever;
                    }
                    else
                    {
                        toParty["addressused"] = searchValues.recievermail;
                    }
                    var listto = new List <Entity>()
                    {
                        toParty
                    };
                    email["to"] = new EntityCollection(listto);
                }


                var subject     = "";
                var description = "";
                if (searchValues.language == 1044)
                {
                    subject     = Resources.ResourceWordNb.documentsinging + ": " + docName;
                    description = Resources.ResourceWordNb.clicktosign;
                }
                else
                {
                    subject     = Resources.ResourceWordEn.documentsinging + ": " + docName;
                    description = Resources.ResourceWordEn.clicktosign;
                }

                email["subject"]           = subject;
                email["directioncode"]     = true;
                email["regardingobjectid"] = new EntityReference("pp_documentsigning", documentsigningid);

                if (description != null)
                {
                    var newText = "<img src='" + emailLogoImg + "'/><br/>";
                    //newText += description;
                    newText += url + "<br/><br/><br/>";
                    newText += "<br/> With Regards / Med vennlig Hilsen<br/>";
                    newText += crmconfig.Wordusername;

                    email["description"] = newText;
                }

                //SendEmailFromTemplate(email, documentsigningid, sdsurl, crm);
                //return;

                var _emailId = crm.Create(email);

                // Use the SendEmail message to send an e-mail message.
                SendEmailRequest sendEmailreq = new SendEmailRequest
                {
                    EmailId       = _emailId,
                    TrackingToken = "",
                    IssueSend     = true
                };

                SendEmailResponse sendEmailresp = (SendEmailResponse)crm.Execute(sendEmailreq);
            }
            catch (Exception ex)
            {
                if (searchValues.language == 1044)
                {
                    MessageBox.Show(Resources.ResourceWordNb.emailerror + ex.Message, "Email sending", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    MessageBox.Show(Resources.ResourceWordEn.emailerror + ex.Message, "Email sending", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
예제 #5
0
        private void buttonSign_Click(object sender, RibbonControlEventArgs e)
        {
            try
            {
                var crm = WordConnectToCrm.ConnectToMSCRM();
                if (crm == null)
                {
                    return;
                }

                WordSearchObject searchValues = new WordSearchObject();
                WordCRMConfig    crmconfig    = WordHandlerCRM.GetCRMConfig(crm);
                searchValues.language = WordHandlerCRM.RetrieveUserUiLanguageCode(crm, crmconfig.Worduser.Id);

                var accountfield  = (!string.IsNullOrWhiteSpace(crmconfig.AccountNrField)) ? crmconfig.AccountNrField.Split(',') : new[] { "accountnumber" };
                var orderfield    = (!string.IsNullOrWhiteSpace(crmconfig.OrderNrField)) ? crmconfig.OrderNrField.Split(',') : new[] { "ordernumber" };
                var quotefield    = (!string.IsNullOrWhiteSpace(crmconfig.QuoteNrField)) ? crmconfig.QuoteNrField.Split(',') : new[] { "quotenumber" };
                var incidentfield = (!string.IsNullOrWhiteSpace(crmconfig.IncidentNrField)) ? crmconfig.IncidentNrField.Split(',') : new[] { "ticketnumber" };
                var contractfield = (!string.IsNullOrWhiteSpace(crmconfig.ContractNrField)) ? crmconfig.ContractNrField.Split(',') : new[] { "contractnumber" };
                var emailfield    = (!string.IsNullOrWhiteSpace(crmconfig.EmailField)) ? crmconfig.EmailField.Split(',') : new[] { "recievermailaddress" };

                var account      = accountfield;  // new[] { "accountnumber", "kundenr" };
                var order        = orderfield;    //new[] { "ordernumber", "ordrenummer"};
                var quote        = quotefield;    //new[] { "quotenumber"};
                var incident     = incidentfield; //new[] { "ticketnumber"};
                var contract     = contractfield; //new[] { "contractnumber"};
                var recievermail = emailfield;    //new[] { "recievermailaddress", "e-post" };


                Document document = Globals.ThisAddIn.Application.ActiveDocument;
                //HeaderFooter objHeader = document.Sections[1].Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary];
                Object start = document.Content.Start;
                Object end   = document.Content.End;
                //document.Range(ref start, ref end).Select();

                var selectedText = Globals.ThisAddIn.Application.ActiveDocument.Range(start, end).Text;

                //var headerText = objHeader.Range.Text;
                //headerText = headerText.Replace("\r\a", "").Replace("\r", "").Replace("\a", "");
                //var headerTextSplit = headerText.Split(' ');

                selectedText = selectedText.Replace("\r\a", "").Replace("\r", "").Replace("\a", "");
                var    docText = selectedText.Split(' ');
                string searchnumber, searchentity, searchnumberfield, senderfrom, recieverto;
                searchnumber = searchentity = searchnumberfield = senderfrom = recieverto = "";

                for (int i = 0; i < docText.Length; i++)
                {
                    //if (docText[i].ToLower().Contains(recievermail))
                    if (recievermail.Any(docText[i].Contains))
                    {
                        recieverto = docText[i + 1];
                    }
                }

                for (int i = 0; i < docText.Length; i++)
                {
                    //if (docText[i].ToLower().Contains(account))
                    if (account.Any(docText[i].Contains))
                    {
                        searchnumber      = docText[i + 1];
                        searchentity      = "account";
                        searchnumberfield = "accountnumber";
                        break;
                    }
                    //if (docText[i].ToLower().Contains(order))
                    if (order.Any(docText[i].Contains))
                    {
                        searchnumber      = docText[i + 1];
                        searchentity      = "salesorder";
                        searchnumberfield = "ordernumber";
                        break;
                    }
                    //if (docText[i].ToLower().Contains(quote))
                    if (quote.Any(docText[i].Contains))
                    {
                        searchnumber      = docText[i + 1];
                        searchentity      = "quote";
                        searchnumberfield = "quotenumber";
                        break;
                    }
                    //if (docText[i].ToLower().Contains(incident))
                    if (incident.Any(docText[i].Contains))
                    {
                        searchnumber      = docText[i + 1];
                        searchentity      = "incident";
                        searchnumberfield = "ticketnumber";
                        break;
                    }
                    //if (docText[i].ToLower().Contains(contract))
                    if (contract.Any(docText[i].Contains))
                    {
                        searchnumber      = docText[i + 1];
                        searchentity      = "contract";
                        searchnumberfield = "contractnumber";
                        break;
                    }
                }

                for (int i = 0; i < docText.Length; i++)
                {
                    if (docText[i].ToLower().Contains("saveat"))
                    {
                        searchentity = docText[i + 1];
                        searchnumber = docText[i + 2];
                        if (searchentity == "account")
                        {
                            searchnumberfield = searchentity + "accountnumber";
                        }
                        if (searchentity == "salesorder")
                        {
                            searchnumberfield = "ordernumber";
                        }
                        if (searchentity == "quote")
                        {
                            searchnumberfield = "quotenumber";
                        }
                        if (searchentity == "incident")
                        {
                            searchnumberfield = "ticketnumber";
                        }
                        if (searchentity == "contract")
                        {
                            searchnumberfield = "contractnumber";
                        }
                        break;
                    }
                }

                searchValues.searchentity      = searchentity;
                searchValues.searchnumber      = searchnumber;
                searchValues.searchnumberfield = searchnumberfield;
                searchValues.recievermail      = recieverto;

                if (string.IsNullOrWhiteSpace(searchentity) || string.IsNullOrWhiteSpace(searchnumber) || string.IsNullOrWhiteSpace(searchnumberfield))
                {
                    if (searchValues.language == 1044)
                    {
                        MessageBox.Show(Resources.ResourceWordNb.wordtemplaterror, Resources.ResourceWordNb.documentsinging, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        MessageBox.Show(Resources.ResourceWordEn.wordtemplaterror, Resources.ResourceWordEn.documentsinging, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    return;
                }

                WordHandlerSigning.SendDocumentForSigning(searchValues, crmconfig, crm);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Signicat Sign", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        internal static async Task SendDocumentForSigning(WordSearchObject searchValues, WordCRMConfig crmconfig, IOrganizationService crm)
        {
            Document document = Globals.ThisAddIn.Application.ActiveDocument;

            try
            {
                var fullname = document.Name.Split('.');
                var pdfName  = fullname[0] + ".pdf";
                var fullPath = document.Path + "\\" + pdfName;

                if (File.Exists(fullPath))
                {
                    File.Delete(fullPath);
                }

                document.ExportAsFixedFormat(
                    Path.Combine(document.Path, pdfName),
                    WdExportFormat.wdExportFormatPDF,
                    OpenAfterExport: false);

                var orgName = ConfigurationManager.AppSettings["OrgName"];

                var signicatHandler = new WordHandlerSignicat();
                var responseMessage = await signicatHandler.SendRequest(searchValues, document, pdfName, orgName,
                                                                        crmconfig, crm);

                var stringResult = await responseMessage.Content.ReadAsStringAsync();

                var result = stringResult.Split('"');
                var sdsurl = result[1];

                var entity = WordHandlerCRM.FindRecordByNumber(searchValues, crm);
                if (entity == null)
                {
                    if (searchValues.language == 1044)
                    {
                        MessageBox.Show(Resources.ResourceWordNb.recordnotfound + searchValues.searchnumber + Resources.ResourceWordNb.unassociated, Resources.ResourceWordNb.documentsinging, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    else
                    {
                        MessageBox.Show(Resources.ResourceWordEn.recordnotfound + searchValues.searchnumber + Resources.ResourceWordEn.unassociated, Resources.ResourceWordEn.documentsinging, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }

                var documentsigningid = WordHandlerCRM.CreatDocumentSigningInCRM(sdsurl, fullPath, fullname[0], entity,
                                                                                 searchValues, crmconfig, crm);
                if (documentsigningid != Guid.Empty)
                {
                    WordHandlerCRM.SendEmail(sdsurl, fullname[0], entity, documentsigningid, searchValues, crmconfig, crm);
                    if (searchValues.language == 1044)
                    {
                        MessageBox.Show(Resources.ResourceWordNb.documentsent, Resources.ResourceWordNb.documentsinging, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show(Resources.ResourceWordEn.documentsent, Resources.ResourceWordEn.documentsinging, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }

                File.Delete(fullPath);
            }
            catch (Exception ex)
            {
                if (searchValues.language == 1044)
                {
                    MessageBox.Show(Resources.ResourceWordNb.cannotcreateinsignicat + ex.Message);
                }
                else
                {
                    MessageBox.Show(Resources.ResourceWordEn.cannotcreateinsignicat + ex.Message);
                }
            }
        }