public StagingTicket invoke(Outlook.MailItem mail)
        {
            StagingTicket ticket = new StagingTicket();

            //Calling CreateSOAPWebRequest method
            HttpWebRequest request = CreateSOAPWebRequest();
            XmlDocument SOAPReqBody = new XmlDocument();

            //declare SOAP message builder
            StringBuilder soap = new StringBuilder();
            //create envelope
            soap.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
            "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:urn=\"urn:Outlook2Remedy\">\n");
            //create auth header
            soap.Append("\t<soapenv:Header>\n" +
            "\t\t<urn:AuthenticationInfo>\n" +
            "\t\t\t<urn:userName>" + Properties.Settings.Default.RemedyUsername + "</urn:userName>\n" +
            "\t\t\t<urn:password>" + Properties.Settings.Default.RemedyPassword + "</urn:password>\n" +
            "\t\t</urn:AuthenticationInfo>\n" +
            "\t</soapenv:Header>\n");
            //open Body and start creating event
            soap.Append("\t<soapenv:Body>\n" +
            "\t\t<urn:Create>\n");
            //add workflow variables
            soap.Append("\t\t\t<urn:Submitter>" + Environment.UserName.ToLower() + "</urn:Submitter>\n" +
            "\t\t\t<urn:EventCode>" + Properties.Settings.Default.EventCode + "</urn:EventCode>\n");
            //add email content (subject and body)
            soap.Append("\t\t\t<urn:EmailSubject>" + (mail.Subject != null ? WebUtility.HtmlEncode(mail.Subject) : "(no subject)") + "</urn:EmailSubject>\n" +
            "\t\t\t<urn:EmailBody>" + WebUtility.HtmlEncode(mail.Body) + "</urn:EmailBody>\n");
            //add attachment details
            if(Properties.Settings.Default.EmailAttachment)
            {
                string path = AppDomain.CurrentDomain.BaseDirectory + @"\temp";
                if (!Directory.Exists(path)) Directory.CreateDirectory(path);
                if (mail.Subject.Length > 50) path += @"\"+ HandleSpecialChars(mail.Subject.Substring(0, 49), "_") + ".msg";
                    else path += @"\" + HandleSpecialChars(mail.Subject, "_") + ".msg";
                mail.SaveAs(path, Outlook.OlSaveAsType.olMSG);
                soap.Append("<urn:EML_attachmentName>" + path + "</urn:EML_attachmentName>");
                soap.Append("<urn:EML_attachmentData>" + Convert.ToBase64String(GetEmailContent(path)) + "</urn:EML_attachmentData>");
                soap.Append("<urn:EML_attachmentOrigSize>" + GetEmailLength(path) + "</urn:EML_attachmentOrigSize>");
                File.Delete(path);
            }
            //add releated ticket - if is found
            soap.Append("\t\t\t<urn:RelatedTicketID>" + GetTicketReference(mail.Subject) + "</urn:RelatedTicketID>\n");
            //add recepients
            soap.Append("\t\t\t<urn:EmailFrom>" + WebUtility.HtmlEncode(mail.SenderEmailAddress) + "</urn:EmailFrom>\n" +
            "\t\t\t<urn:EmailTO>" + WebUtility.HtmlEncode(mail.To) + "</urn:EmailTO>\n" +
            "\t\t\t<urn:EmailCC>" + WebUtility.HtmlEncode(mail.CC) + "</urn:EmailCC>\n");
            //closing event, Body and envelope
            soap.Append("\t\t</urn:Create>\n" +
            "\t</soapenv:Body>\n" +
            "</soapenv:Envelope>");

            //prepare XML SOAP request
            SOAPReqBody.LoadXml(soap.ToString());

            //send XML SOAP request to server
            using (Stream stream = request.GetRequestStream())
            {
                SOAPReqBody.Save(stream);
            }

            //Geting response from request
            using (WebResponse Serviceres = request.GetResponse())
            {
                using (StreamReader rd = new StreamReader(Serviceres.GetResponseStream()))
                {
                    //reading stream
                    var strResponse = rd.ReadToEnd();

                    XmlDocument xmldoc = new XmlDocument();
                    xmldoc.LoadXml(strResponse);
                    XmlNamespaceManager nsm = new XmlNamespaceManager(xmldoc.NameTable);
                    nsm.AddNamespace("soapenv", "http://schemas.xmlsoap.org/soap/envelope/");
                    nsm.AddNamespace("ns0", "urn:Outlook2Remedy");

                    XmlNode node1 = xmldoc.SelectSingleNode("//soapenv:Envelope/soapenv:Body/ns0:CreateResponse/ns0:RID", nsm);
                    if (node1 != null && node1.InnerText != null) ticket.rid = node1.InnerText;
                        else ticket.rid = null;

                    XmlNode node2 = xmldoc.SelectSingleNode("//soapenv:Envelope/soapenv:Body/ns0:CreateResponse/ns0:WID", nsm);
                    if (node2 != null && node2.InnerText != null) ticket.wid = node2.InnerText;
                        else ticket.wid = null;

                    XmlNode node3 = xmldoc.SelectSingleNode("//soapenv:Envelope/soapenv:Body/ns0:CreateResponse/ns0:STS", nsm);
                    if (node3 != null && node3.InnerText != null) ticket.sts = node3.InnerText;
                        else ticket.sts = "open";

                    XmlNode node4 = xmldoc.SelectSingleNode("//soapenv:Envelope/soapenv:Body/ns0:CreateResponse/ns0:LOG", nsm);
                    if (node4 != null && node4.InnerText != null) ticket.log = node4.InnerText;
                        else ticket.log = null;
                }
            }

            return ticket;
        }
        public void OnConvertButton(Office.IRibbonControl control)
        {
            StagingTicket ticket = new StagingTicket();

            Outlook.Application application = new Outlook.Application();
            Outlook.NameSpace   ns          = application.GetNamespace("MAPI");

            //get selected outlook object / mail item
            Object selectedObject = application.ActiveExplorer().Selection[1];

            Outlook.MailItem selectedMail = (Outlook.MailItem)selectedObject;

            //in case a email object si selected run the workflow
            if (selectedObject != null)
            {
                //1. invoke web service
                try
                {
                    //instanciate service and invoke it create the ticket and to receive the ticket reference (ID)
                    Remedy2OutlookService service = new Remedy2OutlookService();
                    ticket = service.invoke(selectedMail);
                }
                catch (Exception ex)
                {
                    string path = AppDomain.CurrentDomain.BaseDirectory + @"\temp";
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }

                    using (System.IO.StreamWriter file = new System.IO.StreamWriter(path + @"\errors.log", true))
                    {
                        file.WriteLine(DateTime.Now.ToString() + " - " + ex.Message + "\n" + ex.ToString());
                    }

                    // display an error message
                    MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }


                //2. open submitted ticket in browser or display info/warn/error messages
                if (Properties.Settings.Default.OpenInBrowser && ticket.wid != null)
                {
                    dynamic ie  = Activator.CreateInstance(Type.GetTypeFromProgID("InternetExplorer.Application"));
                    string  url = Properties.Settings.Default.AppConsoleURL;

                    if (url.EndsWith("/"))
                    {
                        url.Remove(url.Length - 1);
                    }
                    if (url.IndexOf("?", 0) > 0)
                    {
                        url += "&eid=" + ticket.wid;
                    }
                    else
                    {
                        url += "?eid=" + ticket.wid;
                    }

                    ie.AddressBar = false;
                    ie.MenuBar    = false;
                    ie.ToolBar    = false;
                    ie.Visible    = true;
                    ie.Navigate2(url);
                }
                else
                {
                    if (ticket.wid != null && String.Equals(ticket.sts, "done"))
                    {
                        MessageBox.Show("Remedy workflow ticket has been created: " + ticket.wid, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else if (ticket.rid != null && String.Equals(ticket.sts, "open"))
                    {
                        MessageBox.Show("Selected email is transferred to Remedy into the staging record [" + ticket.rid + "] but the fulfillment ticket was not created due to an error or misconfiguration.\n\nContact your Administrator!", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    else if (String.Equals(ticket.sts, "error") && ticket.log != null)
                    {
                        MessageBox.Show("Remedy workflow error: " + ticket.log + ".\n\nContact your Administrator!", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }


                //3. mark selected email as read
                if (Properties.Settings.Default.ReadMail && ticket.wid != null)
                {
                    selectedMail.UnRead = false;
                    selectedMail.Save();
                }


                //4. insert reference ticket number in the
                if (Properties.Settings.Default.InsertInSubject && ticket.wid != null)
                {
                    selectedMail.Subject = ticket.wid + ": " + selectedMail.Subject;
                    selectedMail.Save();
                }

                //5. copy selected email item into Backup MAPI folder (if not exist will be created)
                if (Properties.Settings.Default.BackupMail && ticket.wid != null)
                {
                    Outlook.Folder     inbox  = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox) as Outlook.Folder;
                    Outlook.MAPIFolder backup = null;

                    foreach (Outlook.MAPIFolder subfolder in inbox.Folders)
                    {
                        if (String.Equals(subfolder.Name, "Backup"))
                        {
                            backup = subfolder;
                            break;
                        }
                    }

                    if (backup == null)
                    {
                        try
                        {
                            backup = inbox.Folders.Add("Backup", Outlook.OlDefaultFolders.olFolderInbox);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Error trying to create Backup MAPI folder: " + ex.Message + ".\n\nContact your Administrator or create it manually!", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }

                    if (backup != null)
                    {
                        Outlook.MailItem copyMail = selectedMail.Copy();
                        copyMail.Move(backup);
                    }

                    if (inbox != null)
                    {
                        Marshal.ReleaseComObject(inbox);
                    }
                    if (backup != null)
                    {
                        Marshal.ReleaseComObject(backup);
                    }
                }

                //6. delete selected email item
                if (Properties.Settings.Default.RemoveMail && ticket.wid != null)
                {
                    selectedMail.Delete();
                }
            }
        }