private void SaveToEBS(bool isCreate)
        {
            bool sr_saved;
            ServiceRequest sr = null;
            string logMessage, logNote;

            // Make sure we actually have an asset and a saved incident
            if (Contact != null)
            {
                //Compose Service Request
                sr = new ServiceRequest();

                // Set Service Request attributes - severity, status, request type, contact party id, etc. 
                KeyValuePair<String, String> severityKeyPair = sr.rnSeverityToServerSeverity(selected_rn_severity_id);
                selected_server_severity_id = severityKeyPair.Key;
                sr.SeverityID = Convert.ToDecimal(severityKeyPair.Key);
                sr.Severity = severityKeyPair.Value;

                KeyValuePair<String, String> statusKeyPair = sr.rnStatusToServerStatus(selected_rn_request_status_id);
                selected_server_request_status_id = statusKeyPair.Key;
                sr.StatusID = Convert.ToDecimal(statusKeyPair.Key);
                sr.Status = statusKeyPair.Value;

                KeyValuePair<String, String> requestTypeKeyPair = sr.rnRequestTypeToServerRequestType(selected_rn_request_type_id);
                selected_server_request_type_id = requestTypeKeyPair.Key;
                sr.RequestTypeID = Convert.ToDecimal(requestTypeKeyPair.Key);
                sr.RequestType = requestTypeKeyPair.Value;

                sr.EbsContactID = selectedContactPartyId;
                if (String.IsNullOrEmpty(selectedContactOrgId) || selectedContactOrgId == "0")
                {
                    sr.ContactOrgID = null;
                }
                else
                {
                    sr.ContactOrgID = selectedContactOrgId;
                }
                
                sr.Summary = Incident.Subject;
                sr.RequestDate = (Incident.Created.HasValue) ? Incident.Created.Value : DateTime.Now;
                sr.IncidentOccurredDate = (Incident.Created.HasValue) ? Incident.Created.Value : DateTime.Now;

                sr.IncidentRef = Incident.RefNo;
                sr.IncidentID = Incident.ID.ToString();
                sr.SerialNumber = current_serial_num;

                //String ebsProductId = (Incident.ProductID.HasValue)?Incident.ProductID.ToString():null;
                if(currentInstanceID != 0){
                    sr.ProductID = currentInstanceID;
                }
                else
                {
                    sr.ProductID = null;
                }

                if (_ebsServiceUserId >= 0)
                {
                    sr.CreatedByID = Convert.ToDecimal(_ebsServiceUserId);
                }
                if (_ebsDefaultSrOwnerId >= 0)
                {
                    sr.OwnerID = Convert.ToDecimal(_ebsDefaultSrOwnerId);
                }


                try
                {
                    if (isCreate)
                    {
                        //Create Service Request
                        sr.RnowHost = ConfigurationSetting.rnt_host;
                        logMessage = "Ready to create Service Request";
                        _log.DebugLog(incidentId: _logIncidentId, logMessage: logMessage);
                        sr_saved = sr.Create(_logIncidentId, 0);
                    }
                    else
                    {
                        //Update Service Request
                        //Set custom attribute fields for update
                        var sr_id = 0;
                        var sr_num = "";
                        var sr_obj_ver_num = 0;
                        var sr_owner_id = "";
                        IList<ICustomAttribute> incCustomAttributes = Incident.CustomAttributes;
                        string[] incCustomAttrs = { "Accelerator$ebs_sr_id", "Accelerator$ebs_sr_num", "Accelerator$ebs_sr_obj_ver_num", "Accelerator$ebs_sr_owner_id"};
                        Dictionary<String, Object> incCustomAttrsResults = CustomAttrHelper.fetchCustomAttrValue(incCustomAttributes, incCustomAttrs, this._logIncidentId, 0);
                        sr_id = incCustomAttrsResults["Accelerator$ebs_sr_id"] != null ? (int)incCustomAttrsResults["Accelerator$ebs_sr_id"] : 0;
                        sr_num = incCustomAttrsResults["Accelerator$ebs_sr_num"] != null ? incCustomAttrsResults["Accelerator$ebs_sr_num"].ToString() : "";
                        sr_obj_ver_num = incCustomAttrsResults["Accelerator$ebs_sr_obj_ver_num"] != null ? (int)incCustomAttrsResults["Accelerator$ebs_sr_obj_ver_num"] : 0;
                        sr_owner_id = incCustomAttrsResults["Accelerator$ebs_sr_owner_id"] != null ? incCustomAttrsResults["Accelerator$ebs_sr_owner_id"].ToString() : "";

                        sr.RequestID = Convert.ToDecimal(sr_id);
                        sr.RequestNumber = sr_num;
                        sr.SrObjVerNum = Convert.ToDecimal(sr_obj_ver_num);
                        if (sr_owner_id != "")
                        {
                            sr.OwnerID = Convert.ToDecimal(sr_owner_id);
                        }

                        logMessage = "Ready to update Service Request. SR ID = " + sr_id;
                        logNote = "";
                        _log.DebugLog(incidentId: _logIncidentId, logMessage: logMessage, logNote: logNote);

                        sr_saved = sr.Update(_logIncidentId, 0);
                    }
                }
                catch (Exception ex)
                {
                    logMessage = "Error in creating/updating Service Request.Error Message: " + ex.Message;
                    logNote = "";
                    _log.ErrorLog(incidentId: _logIncidentId, logMessage: logMessage, logNote: logNote);

                    string message = ex.Message;
                    //string message = "There has been an error communicating with EBS. Please check log for detail.";
                    MessageBox.Show(message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (!sr_saved)
                {
                    // If Service Request is not saved successfully, show error.
                    string message = "There has been an error communicating with EBS. Please check log for detail.";
                    MessageBox.Show(message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                    logMessage = "Error in creating/updating Service Request.";
                    logNote = "Response shows error code. Response's error message: " + sr.ErrorMessage;
                    _log.ErrorLog(incidentId: _logIncidentId, logMessage: logMessage, logNote: logNote);

                    return;
                }
                else
                {
                    logMessage = "Created/Updated Service Request successfully. SR ID = " + sr.RequestID;
                    logNote = "";
                    _log.DebugLog(incidentId: _logIncidentId, logMessage: logMessage, logNote: logNote);

                    if (isCreate)
                    {
                        //Check the interaction, we need created, after created a new service request
                        string sr_id = sr.RequestID.Value.ToString();
                        int currentThreadCount = Incident.Threads.Count == 0 ? 0 : Incident.Threads[0].ID;
                        int storedThreadsCount = 0;
                        IList<ICustomAttribute> incCustomAttributes = Incident.CustomAttributes;
                        string[] incCustomAttrThread = { "Accelerator$ebs_max_thread_id" };
                        Dictionary<String, Object> incCustomAttrResultThread = CustomAttrHelper.fetchCustomAttrValue(incCustomAttributes, incCustomAttrThread, this._logIncidentId, 0);
                        storedThreadsCount = incCustomAttrResultThread["Accelerator$ebs_max_thread_id"] != null ? (int)incCustomAttrResultThread["Accelerator$ebs_max_thread_id"] : 0;
                        

                        // If have new thread, then call function SaveInteractionToEBS to create interaction
                        if (currentThreadCount != storedThreadsCount && !String.IsNullOrWhiteSpace(sr_id))
                        {
                            logMessage = "After created new SR, need to store new threads to EBS System. Stored Thread Count = " + storedThreadsCount + "; Current Thread Count = " + currentThreadCount;
                            logNote = "";
                            _log.DebugLog(incidentId: _logIncidentId, logMessage: logMessage, logNote: logNote);

                            SaveInteractionToEBS(sr_id, currentThreadCount, storedThreadsCount, true);
                        }

                        // Iterate through the incident custom attributes and set values
                        try
                        {
                            bool sr_id_found = false;
                            bool sr_num_found = false;
                            bool sr_owner_id_found = false;
                            foreach (ICustomAttribute cusAttr in incCustomAttributes)
                            {
                                if (cusAttr.PackageName == "Accelerator" && cusAttr.GenericField.Name == "Accelerator$ebs_sr_id")
                                {
                                    sr_id_found = true;
                                    cusAttr.GenericField.DataValue.Value = Convert.ToInt32(sr.RequestID);
                                    UpdateIncCustomAttr(Incident.ID, "ebs_sr_id", Convert.ToString(sr.RequestID));
                                }
                                if (cusAttr.PackageName == "Accelerator" && cusAttr.GenericField.Name == "Accelerator$ebs_sr_num")
                                {
                                    sr_num_found = true;
                                    cusAttr.GenericField.DataValue.Value = sr.RequestNumber;
                                    UpdateIncCustomAttr(Incident.ID, "ebs_sr_num", sr.RequestNumber);
                                }
                                if (cusAttr.PackageName == "Accelerator" && cusAttr.GenericField.Name == "Accelerator$ebs_sr_owner_id")
                                {
                                    sr_owner_id_found = true;
                                    cusAttr.GenericField.DataValue.Value = sr.RequestNumber;
                                    UpdateIncCustomAttr(Incident.ID, "ebs_sr_owner_id", Convert.ToString(sr.OwnerID));
                                }
                            }

                            if (sr_id_found == false)
                            {
                                logMessage = "Custom attribute is not defined. Cannot get Accelerator$ebs_sr_id.";
                                _log.ErrorLog(incidentId:_logIncidentId, logMessage: logMessage);
                            }

                            if (sr_num_found == false)
                            {
                                logMessage = "Custom attribute is not defined. Cannot get Accelerator$ebs_sr_num.";
                                _log.ErrorLog(incidentId: _logIncidentId, logMessage: logMessage);
                            }

                            if (sr_owner_id_found == false)
                            {
                                logMessage = "Custom attribute is not defined. Cannot get Accelerator$ebs_sr_owner_id.";
                                _log.ErrorLog(incidentId: _logIncidentId, logMessage: logMessage);
                            }

                            if (sr_id_found == false || sr_num_found == false || sr_owner_id_found == false)
                            {
                                MessageBox.Show("Custom Attribute configuration missing. Please check log for detail.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }

                            storedRequestTypeId = Convert.ToInt32(selected_server_request_type_id);
                            storedRequestStatusId = Convert.ToInt32(selected_server_request_status_id);
                            storedSeverityId = Convert.ToInt32(selected_server_severity_id);
                            ebsStoredSerialNum = current_serial_num;
                        }
                        catch (Exception ex)
                        {
                            logMessage = "Error in updating incident fields with Service Request information, after created new SR.Error Message: " + ex.Message;
                            _log.ErrorLog(incidentId: _logIncidentId, logMessage: logMessage);
                            return;
                        }

                        logMessage = " Updating incident fields with Service Request information, after created new SR successfully.ebs_sr_id = " + sr.RequestID.ToString() + "; ebs_sr_num = " + sr.RequestNumber + "; ebs_sr_owner_id = " + sr.OwnerID.ToString() + ".";
                        _log.DebugLog(incidentId: _logIncidentId, logMessage: logMessage);
                    }
                    else
                    {
                        // After update successfully, update the values which are stored information from EBS side
                        try
                        {
                            storedRequestTypeId = Convert.ToInt32(selected_server_request_type_id);
                            storedRequestStatusId = Convert.ToInt32(selected_server_request_status_id);
                            storedSeverityId = Convert.ToInt32(selected_server_severity_id);
                            ebsStoredSerialNum = current_serial_num;
                        }
                        catch (Exception ex)
                        {
                            logMessage = "Error in updating incident fields with Service Request information, after updated  SR. Error Message: " + ex.Message;
                            _log.ErrorLog(incidentId: _logIncidentId, logMessage: logMessage);
                            return;
                        }
                    }

                    //_recordContext.RefreshWorkspace();


                }
            }
        }
        void _recordContext_Saving(object sender, CancelEventArgs e)
        {
            string logMessage, logNote;
            storedContactPartyId = _serviceRequestControl.storedContactPartyId;
            storedSeverityId = _serviceRequestControl.storedSeverityId;
            storedRequestStatusId = _serviceRequestControl.storedRequestStatusId;
            storedRequestTypeId = _serviceRequestControl.storedRequestTypeId;
            storedSubject = _serviceRequestControl.storedSubject;
            ebsStoredSerialNum = _serviceRequestControl.ebsStoredSerialNum;
            ebsStoredInstanceID = _serviceRequestControl.ebsStoredInstanceID;

            this._serviceRequestControl.LeaveFocusWhenSaving();

            Contact = _recordContext.GetWorkspaceRecord(RightNow.AddIns.Common.WorkspaceRecordType.Contact) as IContact;
            if (Contact == null)
            {
                _serviceRequestControl.tbSerialNo.Enabled = true;
                DialogResult result = MessageBox.Show("Contact is empty. Cannot do the serial number validation. ", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                if (result == DialogResult.OK)
                {
                    logMessage = "Contact is empty. Cannot do the serial number validation. ";
                    logNote = "";
                    _log.DebugLog(incidentId: _logIncidentId, logMessage: logMessage, logNote: logNote);
                    e.Cancel = true;
                    return;
                }
            }

            // get custom attribute Accelerator$ebs_sr_id value
            var sr_id = "";

            IList<ICustomAttribute> incCustomAttributes = Incident.CustomAttributes;
            string[] incCustomAttrSrId = { "Accelerator$ebs_sr_id", "Accelerator$ebs_serial_number"};
            Dictionary<String, Object> incCustomAttrSrIdResult = CustomAttrHelper.fetchCustomAttrValue(incCustomAttributes, incCustomAttrSrId, this._logIncidentId, 0);
            sr_id = incCustomAttrSrIdResult["Accelerator$ebs_sr_id"] != null ? incCustomAttrSrIdResult["Accelerator$ebs_sr_id"].ToString() : "";
            rnStoredSerialNum = !String.IsNullOrWhiteSpace((string)incCustomAttrSrIdResult["Accelerator$ebs_serial_number"])? incCustomAttrSrIdResult["Accelerator$ebs_serial_number"].ToString() : "";

            // If Incident's Contact has associated to an EBS Contact, it does not support to edit it.
            if (!String.IsNullOrWhiteSpace(sr_id) && currentContactID != Contact.ID)
            {
                string message = "This incident has been associated to a EBS Contact, we cannot allow changing the contact via this addin. Please change the primary contact back.";
                MessageBoxButtons buttons = MessageBoxButtons.OK;
                DialogResult result;

                // Show message box to mention the assigned contact party id
                result = System.Windows.Forms.MessageBox.Show(this, message, "Message", buttons, MessageBoxIcon.Information);

                logMessage = "Cannot changing incident's primary contact. This incident has been associated to an EBS Contact, Contact ID = " + Contact.ID;
                logNote = "";
                _log.DebugLog(incidentId: _logIncidentId, logMessage: logMessage, logNote: logNote);

                if (result == DialogResult.OK)
                {
                    e.Cancel = true;
                    return;
                }
            }

            current_serial_num = _serviceRequestControl.tbSerialNo.Text;
            //Validate serial number
            bool isValidSerial;
            string ebsProduct = null;
            if (current_serial_num != "")
            {
                try
                {
                    isValidSerial = this.validateSerialNumber(current_serial_num);
                }
                catch (Exception ex)
                {
                    logMessage = "Incident saving is cancelled, because error: " + ex.Message;
                    _log.ErrorLog(incidentId: _logIncidentId, logMessage: logMessage);
                    e.Cancel = true;
                    return;
                }
                
                currentInstanceID = _serviceRequestControl.inputInstanceID;
                if (isValidSerial)
                {
                    ebsProduct = _serviceRequestControl.ebsInventoryItemName;
                }
                else
                {
                    //Invalid Error
                    logMessage = "The serial number (" + current_serial_num + ") is invalid. It does not belong to current contact's organization.";
                    logNote = "";
                    _log.NoticeLog(incidentId: _logIncidentId, logMessage: logMessage, logNote: logNote);
                    
                    string message = "The serial number is invalid. It does not belong to current contact's organization.";
                    MessageBoxButtons buttons = MessageBoxButtons.OK;
                    DialogResult result;

                    // Show message box to mention the assigned contact party id
                    result = MessageBox.Show(this, message, "Error", buttons, MessageBoxIcon.Error);
                    if (result == DialogResult.OK)
                    {
                        //current_serial_num = ebsStoredSerialNum;
                        //currentInstanceID = ebsStoredInstanceID;
                        e.Cancel = true;
                        return;
                    }
                }
            }
            else
            {
                currentInstanceID = 0;
            }
                
            //Update current incident's serial number
            if (current_serial_num != rnStoredSerialNum)
                this.setSerialNum(current_serial_num);

            //Get Oracle Service Clould product ID according to EBS product information
            string rnProductId = null;
            if (ebsProduct != null)
            {
                rnProductId = this.getProductId(ebsProduct);
            }

            //Set current incident's product
            if (!String.IsNullOrEmpty(rnProductId))
            {
                Incident.ProductID = Convert.ToInt32(rnProductId);
            }
            else
            {
                Incident.ProductID = null;
            }
                
            ServiceRequest sr = new ServiceRequest();
            current_subject = Incident.Subject;
            //get current incident status id and convert to EBS status id
            selected_rn_request_status_id = Incident.Status.StatusID;
            selected_server_request_status_id = sr.rnStatusToServerStatus(selected_rn_request_status_id).Key;

            //get current incident severity id and convert to EBS severity id
            if (!Incident.SeverityID.Equals(null))
            {
                selected_rn_severity_id = (int)Incident.SeverityID;
            }
            else
            {
                selected_rn_severity_id = 0;
            }
            selected_server_severity_id = sr.rnSeverityToServerSeverity(selected_rn_severity_id).Key;

            //get current incident type id and serial number
            selected_rn_request_type_id = 0;

            string[] incCustomAttrs = { "Accelerator$ebs_sr_request_type"};
            Dictionary<String, Object> incCustomAttrsResults = CustomAttrHelper.fetchCustomAttrValue(incCustomAttributes, incCustomAttrs, this._logIncidentId, 0);
            selected_rn_request_type_id = incCustomAttrsResults["Accelerator$ebs_sr_request_type"] != null ? (int)incCustomAttrsResults["Accelerator$ebs_sr_request_type"] : 0;   
            
            //convert to EBS type id 
            selected_server_request_type_id = sr.rnRequestTypeToServerRequestType(selected_rn_request_type_id).Key;

            logMessage = "In CheckIncidentUpdates, get all current value.";
            logNote = "incident status id = " + selected_rn_request_status_id + ", sr status id = " + selected_server_request_status_id +
                "incident severity id = " + selected_rn_request_type_id + ", sr severity id = " + selected_server_severity_id +
                "incident type id = " + selected_rn_request_type_id + ", sr type id = " + selected_server_request_type_id +
                "incident serial num = " + current_serial_num + ", incident subject = " + current_subject;
            _log.DebugLog(incidentId: _logIncidentId, logMessage: logMessage, logNote: logNote);

            
        }