Exemplo n.º 1
0
        private async Task <List <KeyValuePair <string, string> > > PrepareAdverseEventForSpontaneousReportAsync(DatasetInstance datasetInstance, bool isSerious)
        {
            List <KeyValuePair <string, string> > rows = new();

            var reportInstance = await _reportInstanceRepository.GetAsync(ri => ri.ContextGuid == datasetInstance.DatasetInstanceGuid, new string[] { "TerminologyMedDra" });

            DateTime.TryParse(datasetInstance.GetInstanceValue("Reaction known start date"), out var onsetDateValue);
            DateTime.TryParse(datasetInstance.GetInstanceValue("Reaction date of recovery"), out var resolutionDateValue);

            rows.Add(new KeyValuePair <string, string>("Source Description", datasetInstance.GetInstanceValue("Description of reaction")));
            rows.Add(new KeyValuePair <string, string>("MedDRA Term", reportInstance.TerminologyMedDra?.MedDraTerm));
            rows.Add(new KeyValuePair <string, string>("Onset Date", onsetDateValue > DateTime.MinValue ? onsetDateValue.ToString("yyyy-MM-dd") : ""));
            rows.Add(new KeyValuePair <string, string>("Resolution Date", resolutionDateValue > DateTime.MinValue ? resolutionDateValue.ToString("yyyy-MM-dd") : ""));

            if (onsetDateValue > DateTime.MinValue && resolutionDateValue > DateTime.MinValue)
            {
                rows.Add(new KeyValuePair <string, string>("Duration", $"${(resolutionDateValue - onsetDateValue).Days} days"));
            }
            else
            {
                rows.Add(new KeyValuePair <string, string>("Duration", string.Empty));
            }

            rows.Add(new KeyValuePair <string, string>("Outcome", datasetInstance.GetInstanceValue("Outcome of reaction")));

            if (isSerious)
            {
                rows.Add(new KeyValuePair <string, string>("Seriousness", datasetInstance.GetInstanceValue("Reaction serious details")));
                rows.Add(new KeyValuePair <string, string>("Grading Scale", string.Empty));
                rows.Add(new KeyValuePair <string, string>("Severity Grade", string.Empty));
                rows.Add(new KeyValuePair <string, string>("SAE Number", string.Empty));
            }

            return(rows);
        }
Exemplo n.º 2
0
        private XmlNode CreateXmlNodeWithAttributes(DatasetXmlNode datasetXmlNode)
        {
            XmlNode xmlNode = _xmlDocument.CreateElement(datasetXmlNode.NodeName, "");

            if (datasetXmlNode.NodeAttributes.Count == 0)
            {
                return(xmlNode);
            }

            foreach (DatasetXmlAttribute datasetXmlAttribute in datasetXmlNode.NodeAttributes)
            {
                XmlAttribute xmlAttribute = _xmlDocument.CreateAttribute(datasetXmlAttribute.AttributeName);

                if (datasetXmlAttribute.DatasetElement != null)
                {
                    var value = _e2bInstance.GetInstanceValue(datasetXmlAttribute.DatasetElement.ElementName);
                    if (value.IndexOf("=") > -1)
                    {
                        value = value.Substring(0, value.IndexOf("="));
                    }
                    xmlAttribute.InnerText = value;
                }
                else
                {
                    xmlAttribute.InnerText = datasetXmlAttribute.AttributeValue;
                }
                xmlNode.Attributes.Append(xmlAttribute);
            }

            return(xmlNode);
        }
Exemplo n.º 3
0
        private List <KeyValuePair <string, string> > PrepareBasicInformationForSpontaneousReport(DatasetInstance datasetInstance)
        {
            List <KeyValuePair <string, string> > rows = new();

            rows.Add(new KeyValuePair <string, string>("Patient Name", datasetInstance.GetInstanceValue("Initials")));
            rows.Add(new KeyValuePair <string, string>("Date of Birth", DateTime.TryParse(datasetInstance.GetInstanceValue("Date of Birth"), out var dateOfBirthValue) ? dateOfBirthValue.ToString("yyyy-MM-dd") : ""));
            rows.Add(new KeyValuePair <string, string>("Age Group", string.Empty));
            rows.Add(new KeyValuePair <string, string>("Age at time of onset", $"{datasetInstance.GetInstanceValue("Age")} {datasetInstance.GetInstanceValue("Age Unit")}"));
            rows.Add(new KeyValuePair <string, string>("Gender", datasetInstance.GetInstanceValue("Sex")));
            rows.Add(new KeyValuePair <string, string>("Facility", string.Empty));
            rows.Add(new KeyValuePair <string, string>("Medical Record Number", string.Empty));
            rows.Add(new KeyValuePair <string, string>("Identity Number", datasetInstance.GetInstanceValue("Identification Number")));
            rows.Add(new KeyValuePair <string, string>("Weight (kg)", datasetInstance.GetInstanceValue("Weight (kg)")));
            rows.Add(new KeyValuePair <string, string>("Height (cm)", string.Empty));

            return(rows);
        }
        private void CustomMap(DatasetInstance datasetInstanceFromRepo, DatasetInstanceDetailDto mappedDatasetInstanceDto)
        {
            var groupedDatasetCategories = datasetInstanceFromRepo.Dataset.DatasetCategories
                                           .SelectMany(dc => dc.DatasetCategoryElements).OrderBy(dc => dc.FieldOrder)
                                           .GroupBy(dce => dce.DatasetCategory)
                                           .ToList();

            mappedDatasetInstanceDto.DatasetCategories = groupedDatasetCategories
                                                         .Select(dsc => new DatasetCategoryViewDto
            {
                DatasetCategoryId          = dsc.Key.Id,
                DatasetCategoryName        = dsc.Key.DatasetCategoryName,
                DatasetCategoryDisplayName = dsc.Key.FriendlyName ?? dsc.Key.DatasetCategoryName,
                DatasetCategoryHelp        = dsc.Key.Help,
                DatasetCategoryDisplayed   = true,
                DatasetElements            = dsc.Select(element => new DatasetElementViewDto
                {
                    DatasetElementId          = element.DatasetElement.Id,
                    DatasetElementName        = element.DatasetElement.ElementName,
                    DatasetElementDisplayName = element.FriendlyName ?? element.DatasetElement.ElementName,
                    DatasetElementHelp        = element.Help,
                    DatasetElementDisplayed   = true,
                    DatasetElementChronic     = false,
                    DatasetElementSystem      = element.DatasetElement.System,
                    DatasetElementType        = element.DatasetElement.Field.FieldType.Description,
                    DatasetElementValue       = datasetInstanceFromRepo.GetInstanceValue(element.DatasetElement.ElementName),
                    StringMaxLength           = element.DatasetElement.Field.MaxLength,
                    NumericMinValue           = element.DatasetElement.Field.MinSize,
                    NumericMaxValue           = element.DatasetElement.Field.MaxSize,
                    Required           = element.DatasetElement.Field.Mandatory,
                    SelectionDataItems = element.DatasetElement.Field.FieldValues.Select(fv => new SelectionDataItemDto()
                    {
                        SelectionKey = fv.Value, Value = fv.Value
                    }).ToList(),
                    DatasetElementSubs = element.DatasetElement.DatasetElementSubs.Select(elementSub => new DatasetElementSubViewDto
                    {
                        DatasetElementSubId          = elementSub.Id,
                        DatasetElementSubName        = elementSub.ElementName,
                        DatasetElementSubType        = elementSub.Field.FieldType.Description,
                        DatasetElementSubDisplayName = elementSub.FriendlyName ?? elementSub.ElementName,
                        DatasetElementSubHelp        = elementSub.Help,
                        DatasetElementSubSystem      = elementSub.System,
                        StringMaxLength    = elementSub.Field.MaxLength,
                        NumericMinValue    = elementSub.Field.MinSize,
                        NumericMaxValue    = elementSub.Field.MaxSize,
                        Required           = elementSub.Field.Mandatory,
                        SelectionDataItems = elementSub.Field.FieldValues.Select(fv => new SelectionDataItemDto()
                        {
                            SelectionKey = fv.Value, Value = fv.Value
                        }).ToList(),
                    }).ToArray()
                })
                                             .ToArray()
            })
                                                         .ToArray();
        }
Exemplo n.º 5
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                ddlSOC.Items.Add("---");
                foreach (var term in UnitOfWork.Repository <TerminologyMedDra>().Queryable().Where(u => u.MedDraTermType == "SOC").ToList())
                {
                    ddlSOC.Items.Add(new ListItem()
                    {
                        Text = term.MedDraTerm, Value = term.Id.ToString()
                    });
                }
                if (ddlSOC.Items.Count > 0)
                {
                    ddlSOC.SelectedIndex = 0;
                }

                if (_formMode == FormMode.ActiveMode)
                {
                    lblVerbatimLabel.InnerHtml = "<b> Facility Level Verbatim Description </b>";
                    lblVerbatim.InnerText      = _clinicalEvent.SourceDescription;
                    if (_clinicalEvent.SourceTerminologyMedDra != null)
                    {
                        lblSource.InnerText = _clinicalEvent.SourceTerminologyMedDra.DisplayName;
                    }
                    ;
                }
                else
                {
                    lblVerbatimLabel.InnerHtml = "<b> Reporter Verbatim Description </b>";
                    var source = _instance.GetInstanceValue(UnitOfWork.Repository <DatasetElement>().Queryable().SingleOrDefault(u => u.ElementName == "Description of reaction"));
                    if (source != string.Empty)
                    {
                        lblVerbatim.InnerText = source;
                    }
                    ;
                    divSource.Style["display"] = "none";
                }
            }
        }
Exemplo n.º 6
0
        private void HandleSpontaneousInit()
        {
            divSelection.Visible = false;

            DateTime tempdt;
            var      temp = _instance.GetInstanceValue(_instance.Dataset.DatasetCategories.Single(dc => dc.DatasetCategoryName == "Reaction and Treatment").DatasetCategoryElements.Single(dce => dce.DatasetElement.ElementName == "Reaction start date").DatasetElement);

            if (temp != string.Empty)
            {
                temp = DateTime.TryParse(temp, out tempdt) ? Convert.ToDateTime(temp).ToString("yyyy-MM-dd") : "";
            }
            ;
            lblOnsetDate.InnerText = temp;

            if (_reportInstance.TerminologyMedDra != null)
            {
                lblSelection.InnerText = _reportInstance.TerminologyMedDra.DisplayName;

                RenderSpontaneousMeds();

                divDesc.Style["display"] = "block";
            }
            else
            {
                divSetTerm.Visible = true;

                // Give user option of setting terminology
                HyperLink hyp = new HyperLink()
                {
                    Text        = "Set Terminology",
                    NavigateUrl = "TerminologyMedDRA.aspx?rid=" + _reportInstance.Id.ToString()
                };
                lblSource.Controls.Add(hyp);

                divMedications.Style["display"] = "none";
            }
        }
Exemplo n.º 7
0
        public ActionResult EditSpontaneous(DatasetInstanceModel model)
        {
            ViewBag.MenuItem = CurrentMenuItem;

            var returnUrl = (TempData["returnUrl"] ?? string.Empty).ToString();

            ViewBag.ReturnUrl = returnUrl;

            DatasetInstance datasetInstance = null;

            var datasetInstanceRepository = _unitOfWork.Repository <DatasetInstance>();

            datasetInstance = datasetInstanceRepository
                              .Queryable()
                              .Include(di => di.Dataset)
                              .Include("DatasetInstanceValues.DatasetInstanceSubValues.DatasetElementSub")
                              .Include("DatasetInstanceValues.DatasetElement")
                              .SingleOrDefault(di => di.Id == model.DatasetInstanceId);

            if (datasetInstance == null)
            {
                ViewBag.Entity = "DatasetInstance";
                return(View("NotFound"));
            }

            if (ModelState.IsValid)
            {
                var datasetElementIds = model.DatasetCategories.SelectMany(dc => dc.DatasetElements.Select(dse => dse.DatasetElementId)).ToArray();

                var datasetElements = _unitOfWork.Repository <DatasetElement>()
                                      .Queryable()
                                      .Where(de => datasetElementIds.Contains(de.Id))
                                      .ToDictionary(e => e.Id);

                var datasetElementSubs = datasetElements
                                         .SelectMany(de => de.Value.DatasetElementSubs)
                                         .ToDictionary(des => des.Id);

                try
                {
                    for (int i = 0; i < model.DatasetCategories.Length; i++)
                    {
                        for (int j = 0; j < model.DatasetCategories[i].DatasetElements.Length; j++)
                        {
                            try
                            {
                                if (!model.DatasetCategories[i].DatasetElements[j].DatasetElementSystem)
                                {
                                    var eleVal = model.DatasetCategories[i].DatasetElements[j].DatasetElementValue != null ? model.DatasetCategories[i].DatasetElements[j].DatasetElementValue : string.Empty;
                                    if (eleVal != string.Empty)
                                    {
                                        datasetInstance.SetInstanceValue(datasetElements[model.DatasetCategories[i].DatasetElements[j].DatasetElementId], eleVal);
                                    }
                                }
                            }
                            catch (DatasetFieldSetException ex)
                            {
                                // Need to rename the key in order for the message to be bound to the correct control.
                                throw new DatasetFieldSetException(string.Format("DatasetCategories[{0}].DatasetElements[{1}].DatasetElementValue", i, j), ex.Message);
                            }
                        }
                    }

                    datasetInstanceRepository.Update(datasetInstance);

                    _unitOfWork.Complete();

                    HttpCookie cookie = new HttpCookie("PopUpMessage");
                    cookie.Value = "Spontaneous record updated successfully";
                    Response.Cookies.Add(cookie);

                    return(Redirect("/Home/Index"));
                }
                catch (DatasetFieldSetException dse)
                {
                    ModelState.AddModelError(dse.Key, dse.Message);
                }
            }

            var groupedDatasetCategoryElements = datasetInstance.Dataset.DatasetCategories
                                                 .SelectMany(dc => dc.DatasetCategoryElements)
                                                 .GroupBy(dce => dce.DatasetCategory)
                                                 .ToList();

            model.DatasetCategories = groupedDatasetCategoryElements
                                      .Select(dsc => new DatasetCategoryEditModel
            {
                DatasetCategoryId          = dsc.Key.Id,
                DatasetCategoryDisplayName = String.IsNullOrWhiteSpace(dsc.Key.FriendlyName) ? dsc.Key.DatasetCategoryName : dsc.Key.FriendlyName,
                DatasetCategoryHelp        = dsc.Key.Help,
                DatasetElements            = dsc.Select(e => new DatasetElementEditModel
                {
                    DatasetElementId          = e.DatasetElement.Id,
                    DatasetElementName        = e.DatasetElement.ElementName,
                    DatasetElementDisplayName = String.IsNullOrWhiteSpace(e.FriendlyName) ? e.DatasetElement.ElementName : e.FriendlyName,
                    DatasetElementHelp        = e.Help,
                    DatasetElementSystem      = e.DatasetElement.System,
                    DatasetElementRequired    = e.DatasetElement.Field.Mandatory,
                    DatasetElementDisplayed   = true,
                    DatasetElementChronic     = false,
                    DatasetElementType        = e.DatasetElement.Field.FieldType.Description,
                    DatasetElementValue       = datasetInstance.GetInstanceValue(e.DatasetElement),
                    DatasetElementSubs        = e.DatasetElement.DatasetElementSubs.Select(es => new DatasetElementSubEditModel
                    {
                        DatasetElementSubId       = es.Id,
                        DatasetElementSubName     = es.ElementName,
                        DatasetElementSubRequired = es.Field.Mandatory,
                        DatasetElementSubType     = es.Field.FieldType.Description //,
                                                                                   //DatasetElementSubValue = datasetInstance.GetInstanceSubValue(es)
                    }).ToArray()
                })
                                             .ToArray()
            })
                                      .ToArray();

            var selectTypeDatasetElements = model.DatasetCategories
                                            .SelectMany(dc => dc.DatasetElements)
                                            .Where(de => de.DatasetElementType == FieldTypes.Listbox.ToString() ||
                                                   de.DatasetElementType == FieldTypes.DropDownList.ToString())
                                            .ToArray();

            var yesNoDatasetElements = model.DatasetCategories
                                       .SelectMany(dc => dc.DatasetElements)
                                       .Where(de => de.DatasetElementType == FieldTypes.YesNo.ToString())
                                       .ToArray();

            var datasetElementRepository    = _unitOfWork.Repository <DatasetElement>();
            var datasetElementSubRepository = _unitOfWork.Repository <DatasetElementSub>();

            foreach (var element in selectTypeDatasetElements)
            {
                var elementFieldValues = datasetElementRepository.Queryable()
                                         .SingleOrDefault(de => de.Id == element.DatasetElementId)
                                         .Field.FieldValues
                                         .ToList();

                var elementFieldValueList = new List <SelectListItem> {
                    { new SelectListItem {
                          Value = "", Text = ""
                      } }
                };
                elementFieldValueList.AddRange(elementFieldValues.Select(ev => new SelectListItem {
                    Value = ev.Value, Text = ev.Value, Selected = element.DatasetElementValue == ev.Value
                }));

                ViewData.Add(element.DatasetElementName, elementFieldValueList.ToArray());
            }

            foreach (var element in yesNoDatasetElements)
            {
                var yesNo = new[] { new SelectListItem {
                                        Value = "", Text = ""
                                    }, new SelectListItem {
                                        Value = "No", Text = "No"
                                    }, new SelectListItem {
                                        Value = "Yes", Text = "Yes"
                                    } };

                var selectedYesNo = yesNo.SingleOrDefault(yn => yn.Value == element.DatasetElementValue);
                if (selectedYesNo != null)
                {
                    selectedYesNo.Selected = true;
                }

                ViewData.Add(element.DatasetElementName, yesNo);
            }

            return(View(model));
        }
Exemplo n.º 8
0
        public ActionResult AddSpontaneous(DatasetInstanceModel model)
        {
            DatasetInstance datasetInstance = null;

            var datasetInstanceRepository = _unitOfWork.Repository <DatasetInstance>();

            datasetInstance = datasetInstanceRepository
                              .Queryable()
                              .Include(di => di.Dataset)
                              .Include("DatasetInstanceValues.DatasetInstanceSubValues.DatasetElementSub")
                              .Include("DatasetInstanceValues.DatasetElement")
                              .SingleOrDefault(di => di.Id == model.DatasetInstanceId);

            if (ModelState.IsValid)
            {
                if (datasetInstance == null)
                {
                    ViewBag.Entity = "DatasetInstance";
                    return(View("NotFound"));
                }

                datasetInstance.Status = DatasetInstanceStatus.COMPLETE;

                var datasetElementIds = model.DatasetCategories.SelectMany(dc => dc.DatasetElements.Select(dse => dse.DatasetElementId)).ToArray();

                var datasetElements = _unitOfWork.Repository <DatasetElement>()
                                      .Queryable()
                                      .Where(de => datasetElementIds.Contains(de.Id))
                                      .ToDictionary(e => e.Id);

                var datasetElementSubs = datasetElements
                                         .SelectMany(de => de.Value.DatasetElementSubs)
                                         .ToDictionary(des => des.Id);

                try
                {
                    for (int i = 0; i < model.DatasetCategories.Length; i++)
                    {
                        for (int j = 0; j < model.DatasetCategories[i].DatasetElements.Length; j++)
                        {
                            try
                            {
                                if (model.DatasetCategories[i].DatasetElements[j].DatasetElementType != "Table")
                                {
                                    datasetInstance.SetInstanceValue(datasetElements[model.DatasetCategories[i].DatasetElements[j].DatasetElementId], model.DatasetCategories[i].DatasetElements[j].DatasetElementValue);
                                }
                            }
                            catch (DatasetFieldSetException ex)
                            {
                                // Need to rename the key in order for the message to be bound to the correct control.
                                throw new DatasetFieldSetException(string.Format("DatasetCategories[{0}].DatasetElements[{1}].DatasetElementValue", i, j), ex.Message);
                            }
                        }
                    }

                    datasetInstanceRepository.Update(datasetInstance);

                    // Instantiate new instance of work flow
                    var patientIdentifier = datasetInstance.GetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().SingleOrDefault(u => u.ElementName == "Identification Number"));
                    if (String.IsNullOrWhiteSpace(patientIdentifier))
                    {
                        patientIdentifier = datasetInstance.GetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().SingleOrDefault(u => u.ElementName == "Initials"));
                    }
                    var sourceIdentifier = datasetInstance.GetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().SingleOrDefault(u => u.ElementName == "Description of reaction"));
                    _workflowService.CreateWorkFlowInstance("New Spontaneous Surveilliance Report", datasetInstance.DatasetInstanceGuid, patientIdentifier, sourceIdentifier);

                    // Prepare medications
                    List <ReportInstanceMedicationListItem> medications = new List <ReportInstanceMedicationListItem>();
                    var sourceProductElement      = _unitOfWork.Repository <DatasetElement>().Queryable().SingleOrDefault(u => u.ElementName == "Product Information");
                    var destinationProductElement = _unitOfWork.Repository <DatasetElement>().Queryable().SingleOrDefault(u => u.ElementName == "Medicinal Products");
                    var sourceContexts            = datasetInstance.GetInstanceSubValuesContext(sourceProductElement);
                    foreach (Guid sourceContext in sourceContexts)
                    {
                        var drugItemValues = datasetInstance.GetInstanceSubValues(sourceProductElement, sourceContext);
                        var drugName       = drugItemValues.SingleOrDefault(div => div.DatasetElementSub.ElementName == "Product").InstanceValue;

                        if (drugName != string.Empty)
                        {
                            var item = new ReportInstanceMedicationListItem()
                            {
                                MedicationIdentifier         = drugName,
                                ReportInstanceMedicationGuid = sourceContext
                            };
                            medications.Add(item);
                        }
                    }
                    _workflowService.AddOrUpdateMedicationsForWorkFlowInstance(datasetInstance.DatasetInstanceGuid, medications);

                    _unitOfWork.Complete();

                    return(RedirectToAction("FormAdded", "Public"));
                }
                catch (DatasetFieldSetException dse)
                {
                    ModelState.AddModelError(dse.Key, dse.Message);
                }
            }

            bool[] validCat;
            bool[] validMan;
            var    rule = datasetInstance.Dataset.GetRule(DatasetRuleType.MandatoryFieldsProminent);

            if (rule.RuleActive)
            {
                validCat = new[] { true, false };
                validMan = new[] { true, false };
            }
            else
            {
                validCat = new[] { false };
                validMan = new[] { true, false };
            }

            var groupedDatasetCategoryElements = datasetInstance.Dataset.DatasetCategories.Where(dc => validCat.Contains(dc.System)).OrderBy(dc => dc.CategoryOrder)
                                                 .SelectMany(dc => dc.DatasetCategoryElements).Where(dce => (rule.RuleActive && (dce.DatasetCategory.System == true && dce.DatasetElement.Field.Mandatory == true) || (dce.DatasetCategory.System == false && dce.DatasetElement.Field.Mandatory == false)) || (!rule.RuleActive && validMan.Contains(dce.DatasetElement.Field.Mandatory))).OrderBy(dce => dce.FieldOrder)
                                                 .GroupBy(dce => dce.DatasetCategory)
                                                 .ToList();

            model.DatasetCategories = groupedDatasetCategoryElements
                                      .Select(dsc => new DatasetCategoryEditModel
            {
                DatasetCategoryId          = dsc.Key.Id,
                DatasetCategoryDisplayName = String.IsNullOrWhiteSpace(dsc.Key.FriendlyName) ? dsc.Key.DatasetCategoryName : dsc.Key.FriendlyName,
                DatasetCategoryHelp        = dsc.Key.Help,
                DatasetElements            = dsc.Select(e => new DatasetElementEditModel
                {
                    DatasetElementId          = e.DatasetElement.Id,
                    DatasetElementName        = e.DatasetElement.ElementName,
                    DatasetElementDisplayName = String.IsNullOrWhiteSpace(e.FriendlyName) ? e.DatasetElement.ElementName : e.FriendlyName,
                    DatasetElementHelp        = e.Help,
                    DatasetElementRequired    = e.DatasetElement.Field.Mandatory,
                    DatasetElementDisplayed   = true,
                    DatasetElementChronic     = false,
                    DatasetElementType        = e.DatasetElement.Field.FieldType.Description,
                    DatasetElementValue       = datasetInstance.GetInstanceValue(e.DatasetElement),
                    DatasetElementSubs        = e.DatasetElement.DatasetElementSubs.Select(es => new DatasetElementSubEditModel
                    {
                        DatasetElementSubId       = es.Id,
                        DatasetElementSubName     = es.ElementName,
                        DatasetElementSubRequired = es.Field.Mandatory,
                        DatasetElementSubType     = es.Field.FieldType.Description //,
                                                                                   //DatasetElementSubValue = datasetInstance.GetInstanceSubValue(es)
                    }).ToArray()
                })
                                             .ToArray()
            })
                                      .ToArray();

            var selectTypeDatasetElements = model.DatasetCategories
                                            .SelectMany(dc => dc.DatasetElements)
                                            .Where(de => de.DatasetElementType == FieldTypes.Listbox.ToString() ||
                                                   de.DatasetElementType == FieldTypes.DropDownList.ToString())
                                            .ToArray();

            var yesNoDatasetElements = model.DatasetCategories
                                       .SelectMany(dc => dc.DatasetElements)
                                       .Where(de => de.DatasetElementType == FieldTypes.YesNo.ToString())
                                       .ToArray();

            var datasetElementRepository    = _unitOfWork.Repository <DatasetElement>();
            var datasetElementSubRepository = _unitOfWork.Repository <DatasetElementSub>();

            foreach (var element in selectTypeDatasetElements)
            {
                var elementFieldValues = datasetElementRepository.Queryable()
                                         .SingleOrDefault(de => de.Id == element.DatasetElementId)
                                         .Field.FieldValues
                                         .ToList();

                var elementFieldValueList = new List <SelectListItem> {
                    { new SelectListItem {
                          Value = "", Text = ""
                      } }
                };
                elementFieldValueList.AddRange(elementFieldValues.Select(ev => new SelectListItem {
                    Value = ev.Value, Text = ev.Value, Selected = element.DatasetElementValue == ev.Value
                }));

                ViewData.Add(element.DatasetElementName, elementFieldValueList.ToArray());
            }

            foreach (var element in yesNoDatasetElements)
            {
                var yesNo = new[] { new SelectListItem {
                                        Value = "", Text = ""
                                    }, new SelectListItem {
                                        Value = "No", Text = "No"
                                    }, new SelectListItem {
                                        Value = "Yes", Text = "Yes"
                                    } };

                var selectedYesNo = yesNo.SingleOrDefault(yn => yn.Value == element.DatasetElementValue);
                if (selectedYesNo != null)
                {
                    selectedYesNo.Selected = true;
                }

                ViewData.Add(element.DatasetElementName, yesNo);
            }

            return(View(model));
        }
        private void SetInstanceValuesForSpontaneousRelease3(DatasetInstance e2bInstance, DatasetInstance spontaneousReport, User currentUser)
        {
            e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "N.1.2 Batch Number"), "MSH.PViMS-B01000" + spontaneousReport.ToString());
            e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "N.1.5 Date of Batch Transmission"), DateTime.Now.ToString("yyyyMMddHHmmsss"));
            e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "N.2.r.1 Message Identifier"), "MSH.PViMS-B01000" + spontaneousReport.ToString() + "-" + DateTime.Now.ToString("mmsss"));
            e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "N.2.r.4 Date of Message Creation"), DateTime.Now.ToString("yyyyMMddHHmmsss"));
            e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "C.1.1 Sender’s (case) Safety Report Unique Identifier"), String.Format("US-MSH.PViMS-{0}-{1}", DateTime.Today.ToString("yyyy"), spontaneousReport.Id.ToString()));
            e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "C.1.2 Date of Creation"), DateTime.Now.ToString("yyyyMMddHHmmsss"));
            e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "C.1.8.1 Worldwide Unique Case Identification Number"), String.Format("US-MSH.PViMS-{0}-{1}", DateTime.Today.ToString("yyyy"), spontaneousReport.Id.ToString()));

            // Default remaining fields
            // C1 Identification
            e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "C.1.3 Type of Report"), "1=Spontaneous report");
            e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "C.1.4 Date Report Was First Received from Source"), spontaneousReport.Created.ToString("yyyy-MM-dd"));

            // C2 Primary Source
            var fullName = spontaneousReport.GetInstanceValue("Reporter Name");

            if (fullName != string.Empty)
            {
                if (fullName.Contains(" "))
                {
                    e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "C.2.r.1.2 Reporter’s Given Name"), fullName.Substring(0, fullName.IndexOf(" ")));
                    e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "C.2.r.1.4 Reporter’s Family Name"), fullName.Substring(fullName.IndexOf(" ") + 1, fullName.Length - (fullName.IndexOf(" ") + 1)));
                }
                else
                {
                    e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "C.2.r.1.2 Reporter’s Given Name"), fullName);
                }
            }
            var place = spontaneousReport.GetInstanceValue("Reporter Place of Practise");

            if (place != string.Empty)
            {
                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "C.2.r.2.1 Reporter’s Organisation"), place);
            }
            var address = spontaneousReport.GetInstanceValue("Reporter Address");

            if (address != string.Empty)
            {
                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "C.2.r.2.3 Reporter’s Street"), address.Substring(0, 99));
            }
            var telNo = spontaneousReport.GetInstanceValue("Reporter Telephone Number");

            if (telNo != string.Empty)
            {
                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "C.2.r.2.7 Reporter’s Telephone"), telNo);
            }

            // C3 Sender
            e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "C.3.3.3 Sender’s Given Name"), currentUser.FirstName);
            e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "C.3.3.5 Sender’s Family Name"), currentUser.LastName);
            e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "C.3.4.8 Sender’s E-mail Address"), currentUser.Email);

            // D Patient
            var dob   = spontaneousReport.GetInstanceValue("Date of Birth");
            var onset = spontaneousReport.GetInstanceValue("Date of Onset");

            if (dob != string.Empty)
            {
                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "D.2.1 Date of Birth"), dob);

                if (onset != string.Empty)
                {
                    var age = (Convert.ToDateTime(onset) - Convert.ToDateTime(dob)).Days;
                    e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "D.2.2a Age at Time of Onset of Reaction / Event"), age.ToString());
                    e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "D.2.2bAge at Time of Onset of Reaction / Event (unit)"), "Day");
                }
            }
            var weight = spontaneousReport.GetInstanceValue("Weight (kg)");

            if (weight != string.Empty)
            {
                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "D.3 Body Weight (kg)"), weight);
            }
            var sex = spontaneousReport.GetInstanceValue("Sex");

            if (sex != string.Empty)
            {
                if (sex == "Male")
                {
                    e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "D.5 Sex"), "1=Male");
                }
                if (sex == "Female")
                {
                    e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "D.5 Sex"), "2=Female");
                }
            }
            var death = spontaneousReport.GetInstanceValue("Reaction date of death");

            if (death != string.Empty)
            {
                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "D.9.1 Date of Death"), death);
                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "E.i.3.2a Results in Death"), "Yes");
            }

            // E Reaction
            var evnt = spontaneousReport.GetInstanceValue("Description of reaction");

            if (evnt != string.Empty)
            {
                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "E.i.1.1a Reaction / Event as Reported by the Primary Source in Native Language"), evnt);
            }

            var term    = spontaneousReport.GetInstanceValue("TerminologyMedDra");
            var termOut = "NOT SET";

            if (term != string.Empty)
            {
                var termid = Convert.ToInt32(term);
                termOut = _unitOfWork.Repository <TerminologyMedDra>().Queryable().Single(u => u.Id == termid).DisplayName;
            }
            ;
            e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "E.i.2.1b MedDRA Code for Reaction / Event"), termOut);

            if (onset != string.Empty)
            {
                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "E.i.4 Date of Start of Reaction / Event"), onset);
            }

            var outcome = spontaneousReport.GetInstanceValue("Outcome of reaction");

            if (outcome != string.Empty)
            {
                switch (outcome)
                {
                case "Died - Drug may be contributory":
                case "Died - Due to adverse reaction":
                case "Died - Unrelated to drug":
                    e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "E.i.7 Outcome of Reaction / Event at the Time of Last Observation"), "5=fatal");
                    break;

                case "Not yet recovered":
                    e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "E.i.7 Outcome of Reaction / Event at the Time of Last Observation"), "3=not recovered/not resolved/ongoing");
                    break;

                case "Recovered":
                    e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "E.i.7 Outcome of Reaction / Event at the Time of Last Observation"), "1=recovered/resolved");
                    break;

                case "Uncertain outcome":
                    e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "E.i.7 Outcome of Reaction / Event at the Time of Last Observation"), "0=unknown");
                    break;

                default:
                    break;
                }
            }

            for (int i = 1; i <= 6; i++)
            {
                var drugId      = 0;
                var elementName = "";
                var drugName    = "";
                var tempi       = 0;

                if (i < 4)
                {
                    drugId      = i;
                    elementName = string.Format("Suspected Drug {0}", drugId);
                    drugName    = spontaneousReport.GetInstanceValue(elementName);

                    if (drugName != string.Empty)
                    {
                        // Create a new context
                        var context = Guid.NewGuid();

                        e2bInstance.SetInstanceSubValue(_unitOfWork.Repository <DatasetElementSub>().Queryable().Single(dse => dse.ElementName == "G.k.1 Characterisation of Drug Role"), "1=Suspect", context);
                        e2bInstance.SetInstanceSubValue(_unitOfWork.Repository <DatasetElementSub>().Queryable().Single(dse => dse.ElementName == "G.k.2.2 Medicinal Product Name as Reported by the Primary Source"), drugName, context);

                        elementName = string.Format("Suspected Drug {0} Dosage", drugId);
                        var dosage = spontaneousReport.GetInstanceValue(elementName);
                        if (dosage != string.Empty)
                        {
                            if (Int32.TryParse(dosage, out tempi))
                            {
                                e2bInstance.SetInstanceSubValue(_unitOfWork.Repository <DatasetElementSub>().Queryable().Single(dse => dse.ElementName == "G.k.4.r.1a Dose (number)"), dosage, context);
                            }
                        }
                        elementName = string.Format("Suspected Drug {0} Dosage Unit", drugId);
                        var dosageUnit = spontaneousReport.GetInstanceValue(elementName);
                        if (dosageUnit != string.Empty)
                        {
                            e2bInstance.SetInstanceSubValue(_unitOfWork.Repository <DatasetElementSub>().Queryable().Single(dse => dse.ElementName == "G.k.4.r.1b Dose (unit)"), dosageUnit, context);
                        }
                        elementName = string.Format("Suspected Drug {0} Date Started", drugId);
                        var dateStarted = spontaneousReport.GetInstanceValue(elementName);
                        if (dateStarted != string.Empty)
                        {
                            e2bInstance.SetInstanceSubValue(_unitOfWork.Repository <DatasetElementSub>().Queryable().Single(dse => dse.ElementName == "G.k.4.r.4 Date of Start of Drug"), dateStarted, context);
                        }
                        elementName = string.Format("Suspected Drug {0} Date Stopped", drugId);
                        var dateStopped = spontaneousReport.GetInstanceValue(elementName);
                        if (dateStopped != string.Empty)
                        {
                            e2bInstance.SetInstanceSubValue(_unitOfWork.Repository <DatasetElementSub>().Queryable().Single(dse => dse.ElementName == "G.k.4.r.5 Date of Last Administration"), dateStopped, context);
                        }
                        elementName = string.Format("Suspected Drug {0} Batch Number", drugId);
                        var batch = spontaneousReport.GetInstanceValue(elementName);
                        if (batch != string.Empty)
                        {
                            e2bInstance.SetInstanceSubValue(_unitOfWork.Repository <DatasetElementSub>().Queryable().Single(dse => dse.ElementName == "G.k.4.r.7 Batch / Lot Number"), batch, context);
                        }
                        elementName = string.Format("Suspected Drug {0} Route", drugId);
                        var route = spontaneousReport.GetInstanceValue(elementName);
                        if (route != string.Empty)
                        {
                            e2bInstance.SetInstanceSubValue(_unitOfWork.Repository <DatasetElementSub>().Queryable().Single(dse => dse.ElementName == "G.k.4.r.10.1 Route of Administration"), route, context);
                        }
                    }
                }
                else
                {
                    drugId      = i - 3;
                    elementName = string.Format("Concomitant Drug {0}", drugId);
                    drugName    = spontaneousReport.GetInstanceValue(elementName);

                    if (drugName != string.Empty)
                    {
                        // Create a new context
                        var context = Guid.NewGuid();

                        e2bInstance.SetInstanceSubValue(_unitOfWork.Repository <DatasetElementSub>().Queryable().Single(dse => dse.ElementName == "G.k.1 Characterisation of Drug Role"), "1=Suspect", context);
                        e2bInstance.SetInstanceSubValue(_unitOfWork.Repository <DatasetElementSub>().Queryable().Single(dse => dse.ElementName == "G.k.2.2 Medicinal Product Name as Reported by the Primary Source"), drugName, context);

                        elementName = string.Format("Concomitant Drug {0} Dosage", drugId);
                        var dosage = spontaneousReport.GetInstanceValue(elementName);
                        if (dosage != string.Empty)
                        {
                            e2bInstance.SetInstanceSubValue(_unitOfWork.Repository <DatasetElementSub>().Queryable().Single(dse => dse.ElementName == "G.k.4.r.1a Dose (number)"), dosage, context);
                        }
                        elementName = string.Format("Concomitant Drug {0} Dosage Unit", drugId);
                        var dosageUnit = spontaneousReport.GetInstanceValue(elementName);
                        if (dosageUnit != string.Empty)
                        {
                            e2bInstance.SetInstanceSubValue(_unitOfWork.Repository <DatasetElementSub>().Queryable().Single(dse => dse.ElementName == "G.k.4.r.1b Dose (unit)"), dosageUnit, context);
                        }
                        elementName = string.Format("Concomitant Drug {0} Date Started", drugId);
                        var dateStarted = spontaneousReport.GetInstanceValue(elementName);
                        if (dateStarted != string.Empty)
                        {
                            e2bInstance.SetInstanceSubValue(_unitOfWork.Repository <DatasetElementSub>().Queryable().Single(dse => dse.ElementName == "G.k.4.r.4 Date of Start of Drug"), dateStarted, context);
                        }
                        elementName = string.Format("Concomitant Drug {0} Date Stopped", drugId);
                        var dateStopped = spontaneousReport.GetInstanceValue(elementName);
                        if (dateStopped != string.Empty)
                        {
                            e2bInstance.SetInstanceSubValue(_unitOfWork.Repository <DatasetElementSub>().Queryable().Single(dse => dse.ElementName == "G.k.4.r.5 Date of Last Administration"), dateStopped, context);
                        }
                        elementName = string.Format("Concomitant Drug {0} Batch Number", drugId);
                        var batch = spontaneousReport.GetInstanceValue(elementName);
                        if (batch != string.Empty)
                        {
                            e2bInstance.SetInstanceSubValue(_unitOfWork.Repository <DatasetElementSub>().Queryable().Single(dse => dse.ElementName == "G.k.4.r.7 Batch / Lot Number"), batch, context);
                        }
                        elementName = string.Format("Concomitant Drug {0} Route", drugId);
                        var route = spontaneousReport.GetInstanceValue(elementName);
                        if (route != string.Empty)
                        {
                            e2bInstance.SetInstanceSubValue(_unitOfWork.Repository <DatasetElementSub>().Queryable().Single(dse => dse.ElementName == "G.k.4.r.10.1 Route of Administration"), route, context);
                        }
                    }
                }
            }
        }
        private void SetInstanceValuesForSpontaneousRelease2(DatasetInstance e2bInstance, DatasetInstance spontaneousReport, User currentUser)
        {
            // ************************************* ichicsrmessageheader
            e2bInstance.SetInstanceValue(e2bInstance.Dataset.DatasetCategories.Single(dc => dc.DatasetCategoryName == "Message Header").DatasetCategoryElements.Single(dce => dce.DatasetElement.ElementName == "Message Number").DatasetElement, e2bInstance.Id.ToString("D8"));
            e2bInstance.SetInstanceValue(e2bInstance.Dataset.DatasetCategories.Single(dc => dc.DatasetCategoryName == "Message Header").DatasetCategoryElements.Single(dce => dce.DatasetElement.ElementName == "Message Date").DatasetElement, DateTime.Today.ToString("yyyyMMddhhmmss"));

            // ************************************* safetyreport
            e2bInstance.SetInstanceValue(e2bInstance.Dataset.DatasetCategories.Single(dc => dc.DatasetCategoryName == "Safety Report").DatasetCategoryElements.Single(dce => dce.DatasetElement.ElementName == "Safety Report ID").DatasetElement, string.Format("PH-FDA-{0}", spontaneousReport.Id.ToString("D5")));
            e2bInstance.SetInstanceValue(e2bInstance.Dataset.DatasetCategories.Single(dc => dc.DatasetCategoryName == "Safety Report").DatasetCategoryElements.Single(dce => dce.DatasetElement.ElementName == "Transmission Date").DatasetElement, DateTime.Today.ToString("yyyyMMdd"));
            e2bInstance.SetInstanceValue(e2bInstance.Dataset.DatasetCategories.Single(dc => dc.DatasetCategoryName == "Safety Report").DatasetCategoryElements.Single(dce => dce.DatasetElement.ElementName == "Report Type").DatasetElement, "1");

            var seriousReason = spontaneousReport.GetInstanceValue("Reaction serious details");

            if (!String.IsNullOrWhiteSpace(seriousReason))
            {
                var sd  = "2=No";
                var slt = "2=No";
                var sh  = "2=No";
                var sdi = "2=No";
                var sca = "2=No";
                var so  = "2=No";

                switch (seriousReason)
                {
                case "Resulted in death":
                    sd = "1=Yes";
                    break;

                case "Is life-threatening":
                    slt = "1=Yes";
                    break;

                case "Is a congenital anomaly/birth defect":
                    sca = "1=Yes";
                    break;

                case "Requires hospitalization or longer stay in hospital":
                    sh = "1=Yes";
                    break;

                case "Results in persistent or significant disability/incapacity (as per reporter's opinion)":
                    sdi = "1=Yes";
                    break;

                case "Other medically important condition":
                    so = "1=Yes";
                    break;

                default:
                    break;
                }

                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "B4EA6CBF-2D9C-482D-918A-36ABB0C96EFA"), sd);  //Seriousness Death
                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "26C6F08E-B80B-411E-BFDC-0506FE102253"), slt); //Seriousness Life Threatening
                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "837154A9-D088-41C6-A9E2-8A0231128496"), sh);  //Seriousness Hospitalization
                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "DDEBDEC0-2A90-49C7-970E-B7855CFDF19D"), sdi); //Seriousness Disabling
                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "DF89C98B-1D2A-4C8E-A753-02E265841F4F"), sca); //Seriousness Congenital Anomaly
                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "33A75547-EF1B-42FB-8768-CD6EC52B24F8"), so);  //Seriousness Other
                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "510EB752-2D75-4DC3-8502-A4FCDC8A621A"), "1"); //Serious
            }
            else
            {
                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "510EB752-2D75-4DC3-8502-A4FCDC8A621A"), "2"); //Serious
            }

            e2bInstance.SetInstanceValue(e2bInstance.Dataset.DatasetCategories.Single(dc => dc.DatasetCategoryName == "Safety Report").DatasetCategoryElements.Single(dce => dce.DatasetElement.ElementName == "Date report was first received").DatasetElement, spontaneousReport.Created.ToString("yyyyMMdd"));
            e2bInstance.SetInstanceValue(e2bInstance.Dataset.DatasetCategories.Single(dc => dc.DatasetCategoryName == "Safety Report").DatasetCategoryElements.Single(dce => dce.DatasetElement.ElementName == "Date of most recent info").DatasetElement, spontaneousReport.Created.ToString("yyyyMMdd"));

            // ************************************* primarysource
            var fullName = spontaneousReport.GetInstanceValue("Reporter Name");

            if (!String.IsNullOrWhiteSpace(fullName))
            {
                if (fullName.Contains(" "))
                {
                    e2bInstance.SetInstanceValue(e2bInstance.Dataset.DatasetCategories.Single(dc => dc.DatasetCategoryName == "Primary Source").DatasetCategoryElements.Single(dce => dce.DatasetElement.ElementName == "Reporter Given Name").DatasetElement, fullName.Substring(0, fullName.IndexOf(" ")));
                    e2bInstance.SetInstanceValue(e2bInstance.Dataset.DatasetCategories.Single(dc => dc.DatasetCategoryName == "Primary Source").DatasetCategoryElements.Single(dce => dce.DatasetElement.ElementName == "Reporter Family Name").DatasetElement, fullName.Substring(fullName.IndexOf(" ") + 1, fullName.Length - (fullName.IndexOf(" ") + 1)));
                }
                else
                {
                    e2bInstance.SetInstanceValue(e2bInstance.Dataset.DatasetCategories.Single(dc => dc.DatasetCategoryName == "Primary Source").DatasetCategoryElements.Single(dce => dce.DatasetElement.ElementName == "Reporter Given Name").DatasetElement, fullName);
                }
            }

            MapSenderAndReceivedRelatedFields(e2bInstance);

            // ************************************* patient
            var dob      = spontaneousReport.GetInstanceValue("Date of Birth");
            var onset    = spontaneousReport.GetInstanceValue("Reaction known start date");
            var recovery = spontaneousReport.GetInstanceValue("Reaction date of recovery");

            if (!String.IsNullOrWhiteSpace(dob))
            {
                e2bInstance.SetInstanceValue(e2bInstance.Dataset.DatasetCategories.Single(dc => dc.DatasetCategoryName == "Patient").DatasetCategoryElements.Single(dce => dce.DatasetElement.ElementName == "Patient Birthdate").DatasetElement, Convert.ToDateTime(dob).ToString("yyyyMMdd"));

                if (!String.IsNullOrWhiteSpace(onset))
                {
                    var age = (Convert.ToDateTime(onset) - Convert.ToDateTime(dob)).Days;
                    e2bInstance.SetInstanceValue(e2bInstance.Dataset.DatasetCategories.Single(dc => dc.DatasetCategoryName == "Patient").DatasetCategoryElements.Single(dce => dce.DatasetElement.ElementName == "Patient Onset Age").DatasetElement, age.ToString());
                    e2bInstance.SetInstanceValue(e2bInstance.Dataset.DatasetCategories.Single(dc => dc.DatasetCategoryName == "Patient").DatasetCategoryElements.Single(dce => dce.DatasetElement.ElementName == "Patient Onset Age Unit").DatasetElement, "804=Day");
                }
            }

            // ************************************* reaction
            var term    = spontaneousReport.GetInstanceValue("TerminologyMedDra");
            var termOut = "NOT SET";

            if (!String.IsNullOrWhiteSpace(term))
            {
                var termid = Convert.ToInt32(term);
                termOut = _unitOfWork.Repository <TerminologyMedDra>().Queryable().Single(u => u.Id == termid).DisplayName;
            }
            ;
            e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "Reaction MedDRA LLT"), termOut);
            if (!String.IsNullOrWhiteSpace(onset))
            {
                e2bInstance.SetInstanceValue(e2bInstance.Dataset.DatasetCategories.Single(dc => dc.DatasetCategoryName == "Reaction").DatasetCategoryElements.Single(dce => dce.DatasetElement.ElementName == "Reaction Start Date").DatasetElement, Convert.ToDateTime(onset).ToString("yyyyMMdd"));
            }
            ;
            if (!String.IsNullOrWhiteSpace(onset) && !String.IsNullOrWhiteSpace(recovery))
            {
                var rduration = (Convert.ToDateTime(recovery) - Convert.ToDateTime(onset)).Days;
                e2bInstance.SetInstanceValue(e2bInstance.Dataset.DatasetCategories.Single(dc => dc.DatasetCategoryName == "Reaction").DatasetCategoryElements.Single(dce => dce.DatasetElement.ElementName == "Reaction Duration").DatasetElement, rduration.ToString());
                e2bInstance.SetInstanceValue(e2bInstance.Dataset.DatasetCategories.Single(dc => dc.DatasetCategoryName == "Reaction").DatasetCategoryElements.Single(dce => dce.DatasetElement.ElementName == "Reaction Duration Unit").DatasetElement, "804=Day");
            }

            // ************************************* drug
            var destinationProductElement = _unitOfWork.Repository <DatasetElement>().Queryable().SingleOrDefault(u => u.ElementName == "Medicinal Products");
            var sourceContexts            = spontaneousReport.GetInstanceSubValuesContext("Product Information");

            foreach (Guid sourceContext in sourceContexts)
            {
                var drugItemValues = spontaneousReport.GetInstanceSubValues("Product Information", sourceContext);
                var drugName       = drugItemValues.SingleOrDefault(div => div.DatasetElementSub.ElementName == "Product").InstanceValue;

                if (drugName != string.Empty)
                {
                    Guid?newContext = e2bInstance.GetContextForInstanceSubValue(destinationProductElement, destinationProductElement.DatasetElementSubs.SingleOrDefault(des => des.ElementName == "Medicinal Product"), drugName);
                    if (newContext != null)
                    {
                        var reportInstanceMedication = _unitOfWork.Repository <ReportInstanceMedication>().Queryable().Single(x => x.ReportInstanceMedicationGuid == sourceContext);

                        // Causality
                        if (reportInstanceMedication.WhoCausality != null)
                        {
                            e2bInstance.SetInstanceSubValue(destinationProductElement.DatasetElementSubs.Single(des => des.ElementName == "Drug Reaction Assessment"), spontaneousReport.GetInstanceValue("Description of reaction"), (Guid)newContext);
                            e2bInstance.SetInstanceSubValue(destinationProductElement.DatasetElementSubs.Single(des => des.ElementName == "Method of Assessment"), "WHO Causality Scale", (Guid)newContext);
                            e2bInstance.SetInstanceSubValue(destinationProductElement.DatasetElementSubs.Single(des => des.ElementName == "Assessment Result"), reportInstanceMedication.WhoCausality.ToLowerInvariant() == "ignored" ? "" : reportInstanceMedication.WhoCausality, (Guid)newContext);
                        }
                        else
                        {
                            if (reportInstanceMedication.NaranjoCausality != null)
                            {
                                e2bInstance.SetInstanceSubValue(destinationProductElement.DatasetElementSubs.Single(des => des.ElementName == "Drug Reaction Assessment"), spontaneousReport.GetInstanceValue("Description of reaction"), (Guid)newContext);
                                e2bInstance.SetInstanceSubValue(destinationProductElement.DatasetElementSubs.Single(des => des.ElementName == "Method of Assessment"), "Naranjo Causality Scale", (Guid)newContext);
                                e2bInstance.SetInstanceSubValue(destinationProductElement.DatasetElementSubs.Single(des => des.ElementName == "Assessment Result"), reportInstanceMedication.NaranjoCausality.ToLowerInvariant() == "ignored" ? "" : reportInstanceMedication.NaranjoCausality, (Guid)newContext);
                            }
                        }

                        // Treatment Duration
                        var startValue = drugItemValues.SingleOrDefault(div => div.DatasetElementSub.ElementName == "Drug Start Date");
                        var endValue   = drugItemValues.SingleOrDefault(div => div.DatasetElementSub.ElementName == "Drug End Date");
                        if (startValue != null && endValue != null)
                        {
                            var rduration = (Convert.ToDateTime(endValue.InstanceValue) - Convert.ToDateTime(startValue.InstanceValue)).Days;
                            e2bInstance.SetInstanceSubValue(destinationProductElement.DatasetElementSubs.Single(des => des.ElementName == "Drug Treatment Duration"), rduration.ToString(), (Guid)newContext);
                            e2bInstance.SetInstanceSubValue(destinationProductElement.DatasetElementSubs.Single(des => des.ElementName == "Drug Treatment Duration Unit"), "804=Day", (Guid)newContext);
                        }

                        // Dosage
                        if (drugItemValues.SingleOrDefault(div => div.DatasetElementSub.ElementName == "Drug Strength") != null && drugItemValues.SingleOrDefault(div => div.DatasetElementSub.ElementName == "Dose Number") != null)
                        {
                            decimal strength = ConvertValueToDecimal(drugItemValues.SingleOrDefault(div => div.DatasetElementSub.ElementName == "Drug Strength").InstanceValue);
                            decimal dosage   = ConvertValueToDecimal(drugItemValues.SingleOrDefault(div => div.DatasetElementSub.ElementName == "Dose Number").InstanceValue);

                            decimal dosageCalc = strength * dosage;
                            e2bInstance.SetInstanceSubValue(destinationProductElement.DatasetElementSubs.Single(des => des.ElementName == "Structured Dosage"), dosageCalc.ToString(), (Guid)newContext);
                        }
                    }
                }
            }
        }