/// <summary>
        /// Builds the data entry interface based on table
        /// </summary>
        protected void BuildUnplannedEvent()
        {
            // Build UI: build column layout based on default metadata
            var inputs   = CICHelper.GetCaisisInputControlsByTableName(QueryTableName, null);
            int colCount = new Caisis.Controller.PatientDataEntryController(null).GetNumDisplayColumns(QueryTableName);

            DataEntryLayout.BuildLayout(inputs, colCount, new string[] { });

            // Populate: populate exising record
            if (!string.IsNullOrEmpty(PriKeyField.Value))
            {
                int priKey = int.Parse(PriKeyField.Value);
                // load record and populate form
                var biz = BusinessObjectFactory.BuildBusinessObject(QueryTableName);
                biz.Get(priKey);
                // populate section with biz
                base.PopulateForm(DataEntryLayout, biz);

                // set related record if exists
                if (!string.IsNullOrEmpty(PatientItemId.Value))
                {
                    int           patientItemId = int.Parse(base.DecrypyValue(PatientItemId.Value));
                    RelatedRecord relatedRecord = Caisis.Controller.RelatedRecordController.GetRelatedRecords("ProtocolMgr_PatientItems", patientItemId, QueryTableName, priKey).FirstOrDefault();
                    if (relatedRecord != null)
                    {
                        RelatedRecordId.Value = relatedRecord[RelatedRecord.RelatedRecordId].ToString();
                    }
                }
            }
        }
Example #2
0
        /// <summary>
        /// Writes the inserted date value to the client.
        /// </summary>
        private void UpdateStopDateAndReturn()
        {
            string newDate = string.Empty;

            // validate required mappings
            if (TABLE_MAPPINGS.ContainsKey(Table) && BusinessObjectFactory.CanBuildBusinessObject(Table) && PriKey.HasValue)
            {
                int patientId = int.Parse(Session[SessionKey.PatientId].ToString());

                // create instance
                IBusinessObject biz = BusinessObjectFactory.BuildBusinessObject(Table);
                // load record and validate
                biz.Get(PriKey.Value);
                if (!biz.IsEmpty)
                {
                    // turn on validation of patient
                    biz.EnableSaveValidation(patientId);

                    // the date field representing the stop date
                    string dateField = TABLE_MAPPINGS[Table];
                    // check for date text field
                    string dateTextField = dateField + "Text";
                    if (biz.HasField(dateField))
                    {
                        // determine if updating stop date of nullifying
                        bool doStop = Checked;
                        if (doStop)
                        {
                            // set date fields
                            DateTime date = QueryDate.HasValue ? QueryDate.Value : DateTime.Today; // ?? use DateTime.Today for normalization
                            biz[dateField] = date;
                            if (biz.HasField(dateTextField))
                            {
                                biz[dateTextField] = date.ToShortDateString();
                            }
                            // set short date
                            newDate = date.ToShortDateString();
                        }
                        // nullify stop date fields
                        else
                        {
                            biz[dateField] = null;
                            if (biz.HasField(dateTextField))
                            {
                                biz[dateTextField] = null;
                            }
                            newDate = string.Empty;
                        }
                    }
                    // update
                    biz.Save();
                }
            }
            else
            {
                newDate = string.Empty;
            }
            // write the new short stop date
            Response.Write(newDate);
        }
Example #3
0
        /// <summary>
        /// Adds a grid using the current configuration proerpties
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="totalBlankRows"></param>
        /// <param name="totalVisibleBlankRows"></param>
        /// <param name="tableFieldsMetadata"></param>
        public virtual void BuildLayout(string tableName, int totalBlankRows, int totalVisibleBlankRows, Dictionary <string, Dictionary <string, string> > tableFieldsMetadata)
        {
            IEnumerable <IBusinessObject> dataSource = from i in Enumerable.Range(0, totalBlankRows)
                                                       select BusinessObjectFactory.BuildBusinessObject(tableName) as IBusinessObject;

            BuildLayout(tableName, dataSource, totalBlankRows, totalVisibleBlankRows, tableFieldsMetadata);
        }
Example #4
0
        protected string RecordDetails(string tableName, string primaryKey)
        {
            string recordDetails = "";

            if (BOL.BusinessObjectFactory.CanBuildBusinessObject(tableName))
            {
                IBusinessObject biz = BusinessObjectFactory.BuildBusinessObject(tableName);
                biz.Get(int.Parse(primaryKey));

                string tableDisplayName = (biz.TableLabel.Length > 0) ? biz.TableLabel : tableName;

                Dictionary <string, string> HPIRecordDataEntryFields = new Dictionary <string, string>();
                HPIRecordDataEntryFields = CICHelper.GetCaisisInputControlsByTableName(tableName).ToDictionary(i => i.Field, i => pdec.GetFieldLabel(i.Table, i.Field));

                if (HPIRecordDataEntryFields.Keys.Count > 0)
                {
                    recordDetails = "<span id=\"HPIRecordDetailsBubbleContent_" + tableName + "_" + primaryKey + "\" class=\"HPIRecordDetailsBubbleContent\"><table><tr><td colspan=\"2\" class=\"HPIRecordDetailsBubbleTitle\" >" + tableDisplayName + "</td>";
                    foreach (string fieldName in HPIRecordDataEntryFields.Keys)
                    {
                        string fieldLabel = HPIRecordDataEntryFields[fieldName];
                        string fieldValue = biz[fieldName].ToString();

                        if (fieldValue.Length > 0)
                        {
                            recordDetails += "<tr><td>" + fieldLabel + "</td><td>" + fieldValue + "</td></tr>";
                        }
                    }
                    recordDetails += "</table></span>";
                }
            }

            return(recordDetails);
        }
Example #5
0
        protected void ShowDxBiopsy(int DxBiopsyId)
        {
            BusinessObject biz = BusinessObjectFactory.BuildBusinessObject("Procedures");

            biz.Get(DxBiopsyId);

            DiagnosisDateText.Text = biz[BOL.Procedure.ProcDateText].ToString();
        }
Example #6
0
        protected void addGFRParams()
        {
            bool AgeOK    = false;
            bool GenderOK = false;
            bool RaceOK   = false;

            IBusinessObject biz = BusinessObjectFactory.BuildBusinessObject("Patients");

            biz.Get(this._patientId);
            string ptGender = biz[BOL.Patient.PtGender].ToString();
            string ptRace   = biz[BOL.Patient.PtRace].ToString();
            int    ptAge    = 0;

            DateTime ptBirthDate;

            if (DateTime.TryParse(biz[BOL.Patient.PtBirthDate].ToString(), out ptBirthDate))
            {
                ptAge = Convert.ToInt32(Math.Floor(((DateTime.Now - ptBirthDate).TotalDays) / (365.242222)));
                AgeOK = true;
            }

            double k = 0;
            double a = 0;


            if (ptGender.ToUpper() == "MALE")
            {
                k = 0.9; a = -0.411; GenderOK = true;
            }
            else if (ptGender.ToUpper() == "FEMALE")
            {
                k = 0.7; a = -0.329; GenderOK = true;
            }

            if (ptRace.Length > 0)
            {
                RaceOK = true;
            }

            if (GenderOK && RaceOK && AgeOK)
            {
                gfr_calcOK.Text    = "true";
                gfr_k.Text         = k.ToString();
                gfr_a.Text         = a.ToString();
                gfr_age.Text       = ptAge.ToString();
                gfr_genderMod.Text = ptGender.ToUpper() == "FEMALE" ? "1.018" : "1";
                gfr_raceMod.Text   = ptRace.ToUpper().Contains("BLACK") ? "1.159" : "1";
            }
            else
            {
                gfr_calcOK.Text    = "false";
                gfr_k.Text         = "0";
                gfr_a.Text         = "0";
                gfr_age.Text       = "0";
                gfr_genderMod.Text = "0";
                gfr_raceMod.Text   = "0";
            }
        }
        /// <summary>
        /// Save the data entry form and close
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void SaveClick(object sender, EventArgs e)
        {
            var biz = BusinessObjectFactory.BuildBusinessObject(QueryTableName);

            if (!string.IsNullOrEmpty(PriKeyField.Value))
            {
                biz.Get(int.Parse(PriKeyField.Value));
            }
            int patientId = (int)Session[Patient.PatientId];//int.Parse(BaseDecryptedPatientId)
            int parentKey = biz.HasField(Patient.PatientId) ? patientId : -1;

            CICHelper.SetBOValues(DataEntryLayout.Controls, biz, parentKey);
            biz.Save();
            // update hidden field
            int priKey = (int)biz[biz.PrimaryKeyName];

            PriKeyField.Value = priKey.ToString();

            // create patient item if needed
            PatientItem item = new PatientItem();
            int         patientItemId;

            if (!string.IsNullOrEmpty(PatientItemId.Value))
            {
                item.Get(int.Parse(base.DecrypyValue(PatientItemId.Value)));
            }
            else
            {
                item[PatientItem.PatientSchemaId] = PatientSchemaId;
                item[PatientItem.Status]          = "Unplanned";
            }
            // determine schedule date
            var dateFields = from field in biz.FieldNames
                             where field.EndsWith("Date")
                             select field;

            if (dateFields.Count() > 0)
            {
                item[PatientItem.ScheduledDate] = biz[dateFields.First()].ToString();
            }
            item.Save();
            patientItemId       = (int)item[item.PrimaryKeyName];
            PatientItemId.Value = base.EncryptValue(patientItemId.ToString());

            // now create association via related records
            if (string.IsNullOrEmpty(RelatedRecordId.Value))
            {
                int relatedRecordId = PatientProtocolController.CreateUnplannedVisitRelatedRecord(patientItemId, biz.TableName, priKey);
                RelatedRecordId.Value = relatedRecordId.ToString();
            }

            RegisterUpdateScript(false);

            // re populate
            BuildUnplannedEvent();
        }
Example #8
0
        /// <summary>
        /// Helper function used to create child records for projects based on lookup codes
        /// </summary>
        /// <param name="parentBizo"></param>
        /// <param name="childBizo"></param>
        /// <param name="parentBizoNameField"></param>
        /// <param name="childBizoNameField"></param>
        /// <param name="PARENT_LKP_FIELD_TYPE"></param>
        /// <param name="CHILD_LKP_FIELD_TYPE"></param>
        /// <param name="validate">Whether to check if parent has child records before inserting</param>
        /// <param name="doSave">true if to save populated biz objects before returning </param>
        /// <returns></returns>
        private static List <BusinessObject> CreateChildRecordByBizLkpCodes(BusinessObject parentBizo, BusinessObject childBizo, string parentBizoNameField, string childBizoNameField, string PARENT_LKP_FIELD_TYPE, string CHILD_LKP_FIELD_TYPE, bool validate, bool doSave)
        {
            List <BusinessObject> childBizList = new List <BusinessObject>();
            int    bizPriKey    = int.Parse(parentBizo[parentBizo.PrimaryKeyName].ToString());
            string bizNameField = parentBizo[parentBizoNameField].ToString();

            // Check child Bizo to ensure no records have been created

            //BusinessObject checker = BusinessObjectFactory.BuildBusinessObject(childBizo.TableName);
            //checker.GetByParent(bizPriKey);
            //if (checker.RecordCount > 0 && validate)
            //{
            //    return childBizList;
            //}

            if (validate)
            {
                string tablename     = childBizo.TableName;
                string parentKeyName = BusinessObject.GetParentKeyName(tablename);
                var    criteria      = new Dictionary <string, object>()
                {
                    { parentKeyName, bizPriKey }
                };

                if (BusinessObject.Exists(tablename, criteria))
                {
                    return(childBizList);
                }
            }

            LookupCodeDa da = new LookupCodeDa();

            DataRow[] lkpRecords = da.GetLookupsByFieldName(PARENT_LKP_FIELD_TYPE).Tables[0].Select("", LKP_SORT_ORDER);

            foreach (DataRow lkpRecord in lkpRecords)
            {
                string lkpCode = lkpRecord[LookupCode.LkpCode].ToString();
                if (lkpCode == bizNameField)
                {
                    int       lkpCodeId       = int.Parse(lkpRecord[LookupCode.LookupCodeId].ToString());
                    DataRow[] childLkpRecords = da.GetChildCodesByLookupIdAndChildLookupName(lkpCodeId, CHILD_LKP_FIELD_TYPE).Select("", LKP_SORT_ORDER);
                    foreach (DataRow childLkpRecord in childLkpRecords)
                    {
                        string         childLkpCode = childLkpRecord[LookupCode.LkpCode].ToString();
                        BusinessObject childBiz     = BusinessObjectFactory.BuildBusinessObject(childBizo.TableName);
                        childBiz[childBiz.ParentKeyName] = bizPriKey;
                        childBiz[childBizoNameField]     = childLkpCode;
                        childBiz.Save();

                        childBizList.Add(childBiz);
                    }
                }
            }
            return(childBizList);
        }
Example #9
0
            /// <summary>
            ///
            /// </summary>
            /// <param name="table"></param>
            /// <returns></returns>
            private Dictionary <string, string> Create(string table)
            {
                // create static dictionary reference instead of building instace on every call of table type
                if (!TableBaseDictionary.ContainsKey(table))
                {
                    Dictionary <string, string> entry = BusinessObjectFactory.BuildBusinessObject(table).FieldNames.ToDictionary(k => k, v => string.Empty);
                    TableBaseDictionary.Add(table, entry);
                }

                return(new Dictionary <string, string>(TableBaseDictionary[table]));
            }
Example #10
0
/*
 *              protected void AddTables(ArrayList selectedTables, BusinessObject [] tableList)
 *              {
 *                      foreach (BusinessObject biz in tableList)
 *                      {
 *                              selectedTables.Add(biz);
 *                      }
 *
 *              }
 */
        protected ArrayList ConvertNamesToTables(ArrayList selectedTableNames)
        {
            ArrayList tables = new ArrayList();

            //BusinessObjectFactory fact = new BusinessObjectFactory();
            //BusinessObjectFactory fact = new BusinessObjectFactory();
            foreach (string tableName in selectedTableNames)
            {
                tables.Add(BusinessObjectFactory.BuildBusinessObject(tableName));
            }
            return(tables);
        }
Example #11
0
        private void WriteChildRecordResponse()
        {
            string response = "";

            if (TABLE_MAPPINGS.ContainsKey(Table) && BusinessObjectFactory.CanBuildBusinessObject(Table) && PriKey.HasValue)
            {
                string childTable = TABLE_MAPPINGS[Table];
                if (BusinessObjectFactory.CanBuildBusinessObject(childTable))
                {
                    int patientId = int.Parse(Session[SessionKey.PatientId].ToString());

                    // load parent
                    BusinessObject parent = BusinessObjectFactory.BuildBusinessObject(Table);
                    parent.Get(PriKey.Value);
                    if (!parent.IsEmpty)
                    {
                        // get prefix (i.e. "MedTx", "RadTx")
                        string prefix = childTable.Substring(0, childTable.IndexOf("Tx") + 2);
                        // turn on validation of patient
                        parent.EnableSaveValidation(patientId);

                        // create child instance
                        BusinessObject child = BusinessObjectFactory.BuildBusinessObject(childTable);
                        child.EnableSaveValidation(patientId);

                        // set foreign key
                        child[child.ParentKeyName] = parent[parent.PrimaryKeyName];

                        // set fields
                        foreach (string field in COPY_FIELDS)
                        {
                            string parentField = prefix + field;
                            string childField  = prefix + "Admin" + field;
                            if (parent.FieldNames.Contains(parentField) && child.FieldNames.Contains(childField))
                            {
                                child[childField] = parent[parentField];
                            }
                        }
                        // sepcial date fields
                        DateTime date = QueryDate.HasValue ? QueryDate.Value : DateTime.Today;
                        child[prefix + "AdminStartDateText"] = date.ToShortDateString();
                        child[prefix + "AdminStartDate"]     = date;

                        // insert
                        child.Save();

                        response = "- Administered " + (DateTime.Today.Date == date.Date ? "Today" : date.ToShortDateString()) + " -";
                    }
                }
            }
            Response.Write(response);
        }
Example #12
0
        public AdminBaseMetadataPage(string metadataItemTableName, string attributeTableName, string attributeFieldName, string attributeValueTableName, string attributeValueFieldName)
            : base()
        {
            // set required fields for populating/updates
            this.metadataItemTableName   = metadataItemTableName;
            this.attributeTableName      = attributeTableName;
            this.attributeFieldName      = attributeFieldName;
            this.attributeValueTableName = attributeValueTableName;
            this.attributeValueFieldName = attributeValueFieldName;

            this.BIZ_METADATA_TABLE        = BusinessObjectFactory.BuildBusinessObject(this.metadataItemTableName);
            this.BIZ_ATTRIBUTE_TABLE       = BusinessObjectFactory.BuildBusinessObject(this.attributeTableName);
            this.BIZ_ATTRIBUTE_VALUE_TABLE = BusinessObjectFactory.BuildBusinessObject(this.attributeValueTableName);
        }
Example #13
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="table"></param>
        private void SetTable(MetadataTable table)
        {
            tableId   = (int)table[MetadataTable.TableId];
            TableName = table[MetadataTable.TableName_Field].ToString();

            biz = BusinessObjectFactory.BuildBusinessObject(TableName);
            if (tableId.HasValue)
            {
                CurrentTableId.Value = tableId.Value.ToString();
            }
            else
            {
                CurrentTableId.Value = string.Empty;
            }
        }
Example #14
0
    /// <summary>
    /// Sets the Audit Grid for the clicked row in the CurrentRecord Grid.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void SetAuditGridViewOnViewClick(object sender, EventArgs e)
    {
        LinkButton  viewRecordButton = sender as LinkButton;
        GridViewRow row = viewRecordButton.NamingContainer as GridViewRow;

        row.CssClass = "CurrentGridRow";
        //string tableName = currentRecordBiz.Tablename;
        int priKey = int.Parse(viewRecordButton.CommandArgument);
        //BizObject biz = BOFactory.GetBO(tableName);
        //biz.Get(priKey);
        IBusinessObject biz = BusinessObjectFactory.BuildBusinessObject(bizObjects_tablename);

        biz.Get(priKey);
        SetAuditGrid(biz);
    }
Example #15
0
        /// <summary>
        /// Adds the child table's data entry input fields for the child table
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void BuildRptrChildDataEntry(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                // get child table and data
                string childTableName = childTableName = e.Item.DataItem.ToString();
                IEnumerable <IBusinessObject> childRecords = _children[childTableName];
                // locate data entry control
                var childDataEntry = GetChildDataEntry(e.Item);
                // get child input fields
                var childInputFields = GetInputControls(childTableName);
                // build interface
                bool childIsGrid = pdec.IsGridView(childTableName);
                // grid interface
                if (childIsGrid)
                {
                    // add data entry fields interface
                    // important, at least 1 child bizo
                    var childGridRecords = childRecords;
                    // shouldn't ever hit here, blank data populated ??? - ac
                    if (childRecords.Count() == 0)
                    {
                        childRecords = new List <IBusinessObject>()
                        {
                            BusinessObjectFactory.BuildBusinessObject(childTableName)
                        };
                    }
                    CaisisGridView grid = CICHelper.AddGridViewByTableName(childDataEntry, childRecords, childTableName);
                    bool           childRecordsExist = childRecords.Where(c => c.PrimaryKeyHasValue).Count() > 0;
                    grid.VisibleBlankRows = childRecordsExist ? 0 : 1;
                }
                // standard data entry interface
                else
                {
                    var childDataEntryControl = BuildChildDataEntryInterface(childInputFields);
                    // add data entry fields interface
                    childDataEntry.Controls.Add(childDataEntryControl);

                    // set values on inital load
                    if (childRecords.Count() > 0 && !Page.IsPostBack)
                    {
                        IEnumerable <ICaisisInputControl> inputFields = PageUtil.GetControls <ICaisisInputControl>(e.Item);
                        SetFieldValues(childRecords.First(), inputFields);
                    }
                }
            }
        }
Example #16
0
        // set literal that displays the record note is associated with
        private void SetReferencedRecord(string tableName, int tableRecordId, bool showReferencesCheckbox)
        {
            // display information about the reference record if exists
            if (tableRecordId != null && tableRecordId > 0)
            {
                string recordInfo = "";
                string date       = "";

                // get Table Label from Meta Data
                // TODO: THIS LOGIC SHOULD BE BUILT INTO THE MIDDLE TIER, i.e. BusinessObject.GetTableMetaLabel()
                MetadataDa da = new MetadataDa();
                DataTable  dt = new DataTable();
                dt = da.GetTableMetaDataByTableName(tableName);
                if (dt.Rows.Count == 1)
                {
                    recordInfo = "This note references " + dt.Rows[0][MetadataTable.TableLabel_Field].ToString();
                }

                // instiantiate an biz object by table name and if there is a date text value, show it
                BusinessObject bo = BusinessObjectFactory.BuildBusinessObject(tableName);
                bo.Get(tableRecordId);
                IEnumerable <string> columnNames = bo.FieldNames;
                foreach (string column in columnNames)
                {
                    if (column.ToLower().Contains("datetext") && !column.ToLower().Contains("stop"))
                    {
                        date = bo[column].ToString();
                        // check for date length and make sure "stop" is not part of column name
                        if (date.Length > 0)
                        {
                            recordInfo += " dated " + date + ".";
                        }
                    }
                }

                RecordReferencedTitle.Text = recordInfo;

                if (showReferencesCheckbox)
                {
                    RecordReferenced.Visible = true;
                    RecordReferenced.Checked = true;
//                    RecordReferencedRow.Visible = true;
                }
            }
        }
Example #17
0
        /// <summary>
        /// Manually update "dirty" attributes
        /// </summary>
        private void Update()
        {
            // update table and field attributes (generic update)
            foreach (var grid in new ExtendedGridView[] { TableAttributesGrid, FieldAttributesGrid })
            {
                string table      = grid.TableName;
                string priKeyName = BusinessObject.GetPrimaryKeyName(table);
                foreach (GridViewRow row in grid.Rows)
                {
                    object rowPriKey      = grid.DataKeys[row.RowIndex][priKeyName];
                    int?   rowPriKeyValue = null;
                    if (rowPriKey != null && !string.IsNullOrEmpty(rowPriKey.ToString()))
                    {
                        rowPriKeyValue = int.Parse(rowPriKey.ToString());
                    }
                    // update/insert dirty rows
                    if (grid.DirtyGridRows.Contains(row))
                    {
                        BusinessObject biz = BusinessObjectFactory.BuildBusinessObject(table);
                        // update
                        if (rowPriKeyValue.HasValue)
                        {
                            biz.Get(rowPriKeyValue.Value);
                        }
                        // set values
                        CICHelper.SetBOValues(row.Controls, biz, -1);
                        // save/udpate
                        biz.Save();
                        // udpate key
                        rowPriKeyValue = (int)biz[priKeyName];
                    }

                    // update child options only if parent updated/inserted
                    if (grid == FieldAttributesGrid && rowPriKeyValue.HasValue)
                    {
                        int fieldAttributeId = rowPriKeyValue.Value;

                        // update attribute options
                        var attributeOptionsGrid = row.FindControl("FieldAttributeOptionsGrid") as ExtendedGridView;
                        attributeOptionsGrid.Save(fieldAttributeId);
                    }
                }
            }
        }
Example #18
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="aTableName"></param>
        /// <param name="aFieldName"></param>
        /// <param name="attributeLookup"></param>
        protected static void PopulateAttributes(string aTableName, string aFieldName, IDictionary <string, ICaisisInputControl> attributeLookup)
        {
            // get a list of all attributes (i.e., MetadataFieldAttributes)
            IBusinessObject attributeBiz             = BusinessObjectFactory.BuildBusinessObject(aTableName);
            string          tableName                = attributeBiz.TableName;
            string          priKeyName               = attributeBiz.PrimaryKeyName;
            IEnumerable <IBusinessObject> attributes = BusinessObject.GetAll(aTableName);
            var dbAttributes = (from biz in attributes
                                let attributeId = (int)biz[priKeyName]
                                                  let attributeName = biz[aFieldName].ToString()
                                                                      select new
            {
                Id = attributeId,
                Name = attributeName
            }).ToDictionary(a => a.Name, a => a.Id, StringComparer.OrdinalIgnoreCase);

            // for each attribute set pri key for assocaited hidden field
            foreach (var entry in attributeLookup)
            {
                string attributeName = entry.Key;
                ICaisisInputControl attributeIdField = entry.Value;
                // set attribute id
                if (dbAttributes.ContainsKey(attributeName))
                {
                    int attributeId = dbAttributes[attributeName];
                    attributeIdField.Value = attributeId.ToString();
                }
                // create attribute id
                else
                {
                    var biz = BusinessObjectFactory.BuildBusinessObject(aTableName);
                    biz[aFieldName] = attributeName;
                    biz.Save();
                    string priKey = biz[biz.PrimaryKeyName].ToString();
                    attributeIdField.Value = priKey;
                }
            }
        }
        /// <summary>
        /// Delete the data entry form and close
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void DeleteClick(object sender, EventArgs e)
        {
            var biz = BusinessObjectFactory.BuildBusinessObject(QueryTableName);

            if (!string.IsNullOrEmpty(PriKeyField.Value))
            {
                biz.Delete(int.Parse(PriKeyField.Value));
                // update hidden field
                PriKeyField.Value = string.Empty;

                // delete associated record
                if (!string.IsNullOrEmpty(RelatedRecordId.Value))
                {
                    RelatedRecord relatedRecord = new RelatedRecord();
                    relatedRecord.Delete(int.Parse(RelatedRecordId.Value));

                    RelatedRecordId.Value = string.Empty;

                    // register update script
                    RegisterUpdateScript(true);
                }
            }
            BuildUnplannedEvent();
        }
        /// <summary>
        /// Updates the Patient assoication for the specificed Repeater, i.e., list of patient institutions
        /// </summary>
        /// <param name="patientId"></param>
        /// <param name="rptr"></param>
        private void UpdatePatientRptr(int patientId, Repeater rptr)
        {
            foreach (RepeaterItem item in rptr.Items)
            {
                ICaisisInputControl foreignKeyField = item.FindControl("ForeignKeyField") as ICaisisInputControl;
                ICaisisInputControl primaryKeyField = item.FindControl("PrimaryKeyField") as ICaisisInputControl;
                CheckBox            isAssociated    = item.FindControl("AssociateCheckBox") as CheckBox;
                if (isAssociated.Checked)
                {
                    // only add association if none exists
                    if (string.IsNullOrEmpty(primaryKeyField.Value))
                    {
                        IBusinessObject biz = BusinessObjectFactory.BuildBusinessObject(primaryKeyField.Table);
                        // set keys (i.e, InstitutionId + PatientId)
                        biz[foreignKeyField.Field] = int.Parse(foreignKeyField.Value);
                        biz[Patient.PatientId]     = patientId;
                        biz.Save();

                        primaryKeyField.Value = biz[biz.PrimaryKeyName].ToString();
                    }
                }
                else
                {
                    // remove if assocaition exists
                    if (!string.IsNullOrEmpty(primaryKeyField.Value))
                    {
                        IBusinessObject biz = BusinessObjectFactory.BuildBusinessObject(primaryKeyField.Table);
                        // delete by pri key (i.e., PatientInstitutionId)
                        int priKey = int.Parse(primaryKeyField.Value);
                        biz.Delete(priKey);

                        primaryKeyField.Value = biz[biz.PrimaryKeyName].ToString();
                    }
                }
            }
        }
Example #21
0
        /// <summary>
        /// Updates the metadta attibutes and attribute values
        /// </summary>
        protected virtual void Update()
        {
            GridView grid = GetMetadataGrid();

            if (grid == null)
            {
                return;
            }
            foreach (var dirtyRow in dirtyRows)
            {
                // the "dirty" grid row
                GridViewRow row      = dirtyRow.Key;
                int         rowIndex = row.RowIndex;
                // lookup of key fields in row
                var rowDataKeys = grid.DataKeys[rowIndex].Values;
                // a list of controls which are "dirty" in row
                var dirtyControls = dirtyRow.Value;
                // a list of "dirty" controls which represent an attribute value
                var dirtyAttributes = dirtyControls.Where(c => c.Table == attributeValueTableName);
                // a list of "dirty" contorls which represents a dirty metdata item
                var dirtyMetadataItemFields = dirtyControls.Where(c => c.Table == metadataItemTableName);

                IBusinessObject metadataItemBiz = BusinessObjectFactory.BuildBusinessObject(metadataItemTableName);
                int             metadataItemKey = (int)rowDataKeys[metadataItemBiz.PrimaryKeyName];

                // for each row, only updates values(attribuet values) which have changed, not all attribute values
                foreach (ICaisisInputControl dirtyAttributeValue in dirtyAttributes)
                {
                    string attributeName = dirtyAttributeValue.Field;
                    // only update if there is an attribute by this name
                    if (AttributeToHiddenField.ContainsKey(attributeName))
                    {
                        IBusinessObject attributeBiz     = BusinessObjectFactory.BuildBusinessObject(BIZ_ATTRIBUTE_TABLE.TableName);
                        int?            attributeId      = null;
                        int?            attributeValueId = null;

                        // get the table attribute id
                        ICaisisInputControl attributeIdField = AttributeToHiddenField[attributeName];

                        // CREATE/LOAD: Attribute (i.e., "FieldLabel" -> MetadataFieldAttribute)

                        // if attribute exists, set value
                        if (!string.IsNullOrEmpty(attributeIdField.Value))
                        {
                            attributeId = int.Parse(attributeIdField.Value);
                        }
                        // otherwise insert attribute
                        else
                        {
                            // set required attribute name
                            attributeBiz[attributeFieldName] = attributeName;
                            attributeBiz.Save();

                            // update hidden attribute id field
                            attributeId            = (int)attributeBiz[attributeBiz.PrimaryKeyName];
                            attributeIdField.Value = attributeId.Value.ToString();
                        }

                        // INSERT/UPDATE: Attribute Value (i.e., "FieldLabel" + "My Field" -> MetadataFieldAttributeValue)

                        // the field representing the AttributeValueId
                        ICaisisInputControl attributeValueIdField = GetTableAttributeValueIdControl(row, attributeName);
                        // the field representing the input control containing the AttributeValue
                        ICaisisInputControl attributeValueControl = GetTableAttributeValueControl(row, attributeName);
                        // the disease mapping to the attribute value
                        ICaisisInputControl diseaseAttributeValueId = GetDiseaseAttributeValueId(row, attributeName);

                        // validate fields exists
                        if (attributeValueIdField != null && attributeValueControl != null)
                        {
                            IBusinessObject attributeValueBiz = BusinessObjectFactory.BuildBusinessObject(attributeValueTableName);
                            bool            isDiseaseSpecific = QueryDiseaseId.HasValue && diseaseAttributeValueId != null;
                            // load attribute value, if isn't disease specific or disease specific has a value
                            if (!string.IsNullOrEmpty(attributeValueIdField.Value) && (!isDiseaseSpecific || !string.IsNullOrEmpty(diseaseAttributeValueId.Value)))
                            {
                                attributeValueId = int.Parse(attributeValueIdField.Value);
                                attributeValueBiz.Get(attributeValueId.Value);
                            }
                            // set required foreign keys for insert
                            else
                            {
                                // set required attribute id key (i.e., AttributeId)
                                attributeValueBiz[attributeBiz.PrimaryKeyName] = attributeId;
                                // set required metadata id (i.e., FieldId)
                                attributeValueBiz[metadataItemBiz.PrimaryKeyName] = metadataItemKey;
                            }

                            // get attribute value (i.e., "ControlType" = "CaisisTextBox")
                            string attributeValue = GetInputControlValue(attributeValueControl);

                            // update table attribute value

                            // validate (no empty values allowed)
                            if (string.IsNullOrEmpty(attributeValue))
                            {
                                // delete empty values
                                if (attributeValueId.HasValue)
                                {
                                    // delete atttibute value
                                    attributeValueBiz.Delete(attributeValueId.Value);
                                    attributeValueId            = null;
                                    attributeValueIdField.Value = string.Empty;
                                    // delete disease specific mapping
                                    if (isDiseaseSpecific && !string.IsNullOrEmpty(diseaseAttributeValueId.Value))
                                    {
                                        DiseaseAttributeValue dav = new DiseaseAttributeValue();
                                        dav.Delete(int.Parse(diseaseAttributeValueId.Value));
                                        diseaseAttributeValueId.Value = string.Empty;
                                    }
                                }
                                continue;
                            }
                            else
                            {
                                attributeValueBiz[attributeValueFieldName] = attributeValue;
                                attributeValueBiz.Save();
                                // update hidden field
                                attributeValueId            = (int)attributeValueBiz[attributeValueBiz.PrimaryKeyName];
                                attributeValueIdField.Value = attributeValueId.ToString();

                                // handle disease specific mapping
                                if (isDiseaseSpecific)
                                {
                                    var diseaseAttributeValue = new DiseaseAttributeValue();
                                    var diseaseAttributeId    = GetMetadataDiseaseAttributeId();
                                    // load existing mapping
                                    if (!string.IsNullOrEmpty(diseaseAttributeValueId.Value))
                                    {
                                        diseaseAttributeValue.Get(int.Parse(diseaseAttributeValueId.Value));
                                    }
                                    // new
                                    else
                                    {
                                        diseaseAttributeValue[DiseaseAttributeValue.DiseaseId]          = QueryDiseaseId.Value;
                                        diseaseAttributeValue[DiseaseAttributeValue.DiseaseAttributeId] = diseaseAttributeId.Value;
                                    }
                                    diseaseAttributeValue[DiseaseAttributeValue.DiseaseAttributeValue_Field] = attributeValueIdField.Value;

                                    diseaseAttributeValue.Save();
                                    diseaseAttributeValueId.Value = diseaseAttributeValue[diseaseAttributeValue.PrimaryKeyName].ToString();
                                }
                            }
                        }
                    }
                }
                // update metadata item (i.e., MetadataField)
                if (dirtyMetadataItemFields.Count() > 0)
                {
                    // load by pri key (i.e., FieldId)
                    metadataItemBiz.Get(metadataItemKey);
                    // update fields which have changed (i.e., FieldOrder, FieldSupress)
                    foreach (ICaisisInputControl input in dirtyMetadataItemFields)
                    {
                        metadataItemBiz[input.Field] = GetInputControlValue(input);
                    }
                    // save record
                    metadataItemBiz.Save();
                }
            }
            // after update rebuilds lists
            PopulateAttributeValues();
        }
Example #22
0
        protected DataView LabsWithGFR(int PatientID, DataView labDv)
        {
            DataTable labDt = labDv.ToTable();

            labDt.Columns.Add("GFR");
            labDt.Columns.Add("GFRError");

            // Calculate GFR
            // eGFR = 141 * min(SCr/k,1)^a * max(SCr/k,1)^-1.209 * 0.993^Age x [1.018 if female] * [1.159 if black]

            bool AgeOK    = false;
            bool GenderOK = false;
            bool RaceOK   = false;
            //           bool CreatOK = false;

            IBusinessObject biz = BusinessObjectFactory.BuildBusinessObject("Patients");

            biz.Get(PatientID);
            string ptGender = biz[BOL.Patient.PtGender].ToString();
            string ptRace   = biz[BOL.Patient.PtRace].ToString();
            int    ptAge    = 0;

            DateTime ptBirthDate;

            if (DateTime.TryParse(biz[BOL.Patient.PtBirthDate].ToString(), out ptBirthDate))
            {
                ptAge = Convert.ToInt32(Math.Floor(((DateTime.Now - ptBirthDate).TotalDays) / (365.242222)));
                AgeOK = true;
            }

            double k = 0;
            double a = 0;


            if (ptGender.ToUpper() == "MALE")
            {
                k = 0.9; a = -0.411; GenderOK = true;
            }
            else if (ptGender.ToUpper() == "FEMALE")
            {
                k = 0.7; a = -0.329; GenderOK = true;
            }

            if (ptRace.Length > 0)
            {
                RaceOK = true;
            }

            if (GenderOK && RaceOK && AgeOK)
            {
                foreach (DataRow dr in labDt.Rows)
                {
                    if (dr[BOL.LabTest.LabTest_Field].ToString().ToUpper().Equals("CREAT"))
                    {
                        double creatResult;
                        if (dr[BOL.LabTest.LabResult].ToString().Length > 0 && double.TryParse(dr[BOL.LabTest.LabResult].ToString(), out creatResult))
                        {
                            double gfrCalc = (141) * (Math.Pow((Math.Min((creatResult / k), 1)), a)) * (Math.Pow((Math.Max((creatResult / k), 1)), -1.209)) * (Math.Pow(0.993, ptAge));
                            if (ptGender.ToUpper() == "FEMALE")
                            {
                                gfrCalc = gfrCalc * 1.018;
                            }
                            if (ptRace.ToUpper().Contains("BLACK"))
                            {
                                gfrCalc = gfrCalc * 1.159;
                            }
                            dr["GFR"] = Math.Round(gfrCalc, 3);
                        }
                        else
                        {
                            dr["GFRError"] = "Invalid Creatinine Value";
                        }
                    }
                }
            }
            else
            {
                string errorMsg = "GFR cannot be calculated.<br/>(";
                if (!GenderOK)
                {
                    errorMsg += "No Gender. ";
                }
                if (!RaceOK)
                {
                    errorMsg += "No Race. ";
                }
                if (!AgeOK)
                {
                    errorMsg += "No Age.";
                }
                errorMsg += ")";
                foreach (DataRow dr in labDt.Rows)
                {
                    if (dr[BOL.LabTest.LabTest_Field].ToString().ToUpper().Equals("CREAT"))
                    {
                        dr["GFRError"] = errorMsg;
                    }
                }
            }


            return(labDt.DefaultView);
        }
Example #23
0
        protected void ShowDxBiopsy(int DxBiopsyId)
        {
            populatedDiagnosisTable.Visible = true;
            NewDiagnosisTable.Visible       = false;



            BusinessObject biz = BusinessObjectFactory.BuildBusinessObject("Procedures");

            biz.Get(DxBiopsyId);

            DxDateLabel.Text = biz[BOL.Procedure.ProcDateText].ToString();

            // PreTx PSA ---------------------------
            if (biz[BOL.Procedure.ProcDate].ToString().Length > 0)
            {
                LabTestDa da = new LabTestDa();

                string[] l  = { "PSA" };
                DataSet  ds = da.GetLabTestsbyList(this._patientId, l);

                if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    DataView preTxPSAs = new DataView(ds.Tables[0]);

                    preTxPSAs.RowFilter = BOL.LabTest.LabDate + " <= #" + (DateTime)biz[BOL.Procedure.ProcDate] + "#";

                    if (preTxPSAs.Count > 0)
                    {
                        preTxPSAs.Sort  = BOL.LabTest.LabDate + " DESC";
                        PreBxTxPSA.Text = preTxPSAs[0][BOL.LabTest.LabResult].ToString() + preTxPSAs[0][BOL.LabTest.LabUnits].ToString() + " (" + (preTxPSAs[0][BOL.LabTest.LabDateText].ToString() + ")");
                    }
                }
            }


            // Path data for Biopsy ---------------------------
            DataView dv = BOL.BusinessObject.GetByFieldsAsDataView <BOL.Pathology>(new Dictionary <string, object> {
                { BOL.Pathology.ProcedureId, DxBiopsyId }
            });

            dv.Sort = BOL.Pathology.PathDate + " DESC";

            if (dv.Count > 0)
            {
                //   DxDateLabel.Text = dv[0][BOL.Pathology.PathDateText].ToString();

                int pathId = (int)dv[0][BOL.Pathology.PathologyId];


                populatedDiagnosisTable.Attributes.Add("onclick", "LoadDataEntryForm('Pathology', '" + pathId.ToString() + "', '', '','ProstateBiopsyPath,PathologyStageGrade')");


                // Prostate Biopsy Path
                DataView dv2 = BOL.BusinessObject.GetByParentAsDataView <BOL.BiopsyProstatePathology>(pathId);
                if (dv2.Count > 0)
                {
                    PathGG1Label.Text = dv2[0][BOL.BiopsyProstatePathology.PathGG1].ToString();
                    PathGG2Label.Text = dv2[0][BOL.BiopsyProstatePathology.PathGG2].ToString();
                    PathGGSLabel.Text = dv2[0][BOL.BiopsyProstatePathology.PathGGS].ToString();

                    DiagnosisPositiveCoresLabel.Text = dv2[0][BOL.BiopsyProstatePathology.PathPosCores].ToString();

                    int posCores;
                    int totCores;

                    if (int.TryParse(dv2[0][BOL.BiopsyProstatePathology.PathPosCores].ToString(), out posCores) && int.TryParse(dv2[0][BOL.BiopsyProstatePathology.PathNumCores].ToString(), out totCores))
                    {
                        int negCores = totCores - posCores;
                        DiagnosisNegativeCoresLabel.Text = negCores.ToString();
                    }
                }

                // Prostate Biopsy Path
                DataView dv3 = BOL.BusinessObject.GetByParentAsDataView <BOL.PathologyStageGrade>(pathId);
                if (dv3.Count > 0)
                {
                    DiagnosisUICC2002TStageLabel.Text = dv3[0][BOL.PathologyStageGrade.PathStageT].ToString();
                    DiagnosisUICC2002NStageLabel.Text = dv3[0][BOL.PathologyStageGrade.PathStageN].ToString();
                    DiagnosisUICC2002MStageLabel.Text = dv3[0][BOL.PathologyStageGrade.PathStageM].ToString();
                }
            }
        }
Example #24
0
        virtual protected void Save(object sender, System.EventArgs e)
        {
            // validation hooks?

            // TODO: we could refactor w/ custom iterators

            // set bizo fields from main fields
            IEnumerable <ICaisisInputControl> controls = CICHelper.GetCaisisInputControls(this);

            SetBizoValues(bizo, controls);

            // set parent fields (if applicable)
            if (parent != null)
            {
                SetBizoValues(parent, controls);
            }

            //foreach (ICaisisInputControl c in controls)
            //{
            //    // validate table and field
            //    if (bizo.TableName == c.Table && bizo.HasField(c.Field))
            //    {
            //        bizo[c.Field] = c.Value;
            //    }
            //}

            string squery = Request.Url.Query;

            squery = this.RemoveParameterFromUrlQueryString(squery, "error");
            squery = this.RemoveParameterFromUrlQueryString(squery, "save");

            string redirectURL = "DynamicForm.aspx" + squery;

            try
            {
                //if (primaryKey > -1)
                //{
                //    model.UpdateRecord();
                //}
                //else
                //{
                //    primaryKey = model.InsertRecord();
                //    redirectURL += "&pkey=" + primaryKey;
                //}

                // save parent (optional)
                if (parent != null)
                {
                    parent.Save();
                    //  update foreign key
                    bizo[bizo.ParentKeyName] = parent[parent.PrimaryKeyName];
                }

                // save main biz
                bizo.Save();

                // save children (optional)
                if (ChildTableNames.Count() > 0)
                {
                    // get child tables rptr
                    Repeater childTablesRptr = Page.FindControl("ChildTablesRptr") as Repeater;

                    // get required parent key
                    string parentTableName = bizo.TableName;
                    string parentKeyName   = bizo.PrimaryKeyName;
                    int    parentPriKey    = (int)bizo[bizo.PrimaryKeyName];

                    // save each child table
                    foreach (RepeaterItem rptrItem in childTablesRptr.Items)
                    {
                        HiddenField tableNameField = rptrItem.FindControl("TableNameField") as HiddenField;
                        if (tableNameField != null && !string.IsNullOrEmpty(tableNameField.Value))
                        {
                            string childTableName = tableNameField.Value;
                            bool   isGrid         = pdec.IsGridView(childTableName);
                            // validate: child table and "dirty" (!important: grid has own tracking)
                            if (ChildTableNames.Contains(childTableName) && (isGrid || isTableDirty.ContainsKey(childTableName)))
                            {
                                // grid tables
                                if (isGrid)
                                {
                                    // locate child grid
                                    var childTableGrid = PageUtil.GetControls <CaisisGridView>(rptrItem).FirstOrDefault();
                                    // should only by 1 grid per child table
                                    if (childTableGrid != null)
                                    {
                                        childTableGrid.Save();
                                    }
                                }
                                // standard data entry tables
                                else
                                {
                                    var             inputFields = PageUtil.GetControls <ICaisisInputControl>(rptrItem);
                                    IBusinessObject childBizo;
                                    // update
                                    if (_children.ContainsKey(childTableName) && _children[childTableName].Count() > 0)
                                    {
                                        childBizo = _children[childTableName].First();
                                    }
                                    // insert
                                    else
                                    {
                                        childBizo = BusinessObjectFactory.BuildBusinessObject(childTableName);
                                        // set parent key
                                        childBizo[parentKeyName] = parentPriKey;
                                    }
                                    // set field values
                                    SetBizoValues(childBizo, inputFields);
                                    // update/save
                                    childBizo.Save();
                                }
                            }
                        }
                    }
                }

                if (!redirectURL.Contains("pkey="))
                {
                    redirectURL += "&pkey=" + bizo[bizo.PrimaryKeyName].ToString();
                }

                redirectURL += "&saved=true";
            }
            catch (Exception ex)
            {
                // TODO: we can parse exception for more detail ...

                //if (ex is ClientException)
                //{
                //    string field = ex.Message;
                //    DataRow row = model.GetHelpFieldInfo(field);

                //    // we need to map this field to metadata
                //    redirectURL += "&error=" + row["FieldLabel"].ToString();
                //}
                //else
                //{
                redirectURL += "&error=_default";

                // let everyone know
                ExceptionHandler.Publish(ex);
                //}
            }

            Response.Redirect(redirectURL);
            // added saved=true, should prob move that portion at later date - jf
        }
Example #25
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string tableList    = Request["tableNames"].ToString();
        string encryptedKey = Request["tablePriKey"].ToString();
        string decryptedKey = "";

        // End Response if key can't be decrypted or bogus key entered
        try
        {
            decryptedKey = Caisis.Security.CustomCryptoHelper.Decrypt(encryptedKey);
        }
        catch (Exception ex)
        {
            Response.End();
        }
        if (string.IsNullOrEmpty(decryptedKey))
        {
            Response.End();
        }
        int priKey = int.Parse(decryptedKey);

        string[] listOfTables = tableList.Split(',');
        string   parentTable  = listOfTables[0];
        string   showTable    = Request["showTable"] != null ? Request["showTable"].ToString() : "";

        DataTable linkTable = new DataTable();

        linkTable.Columns.Add("TableName");
        linkTable.Columns.Add("TableURL");
        foreach (string table in listOfTables)
        {
            string url = "?tableNames=" + tableList + "&tablePriKey=" + Caisis.Security.CustomCryptoHelper.Encrypt(priKey.ToString()) + "&showTable=" + table;
            if (table == parentTable)
            {
                ParentTableLink.Text        = table;
                ParentTableLink.NavigateUrl = url;
            }
            else
            {
                DataRow row = linkTable.NewRow();
                row["TableName"] = table;
                row["TableURL"]  = url;
                linkTable.Rows.Add(row);
            }
        }
        string boTable = string.IsNullOrEmpty(showTable) ? parentTable : showTable;

        //currentRecordBiz = BOFactory.GetBO(boTable);
        //if (boTable == parentTable)
        //{
        //    currentRecordBiz.Get(priKey);
        //}
        //else
        //{
        //    currentRecordBiz.GetByParent(priKey);
        //}
        //SetCurrentRecordGrid(currentRecordBiz, parentTable);
        //if (currentRecordBiz.RecordCount == 1)
        //{
        //    SetAuditGrid(currentRecordBiz);
        //}

        if (boTable == parentTable)
        {
            IBusinessObject b = BusinessObjectFactory.BuildBusinessObject(boTable);
            b.Get(priKey);
            bizObjects = new IBusinessObject[] { b };
        }
        else
        {
            bizObjects = BusinessObject.GetByParent(boTable, priKey);
        }

        bizObjects_tablename = boTable;

        DataTable dt = bizObjects.AsDataView(boTable).Table;

        SetCurrentRecordGrid(dt, boTable, parentTable);
        if (bizObjects.Count() == 1)
        {
            SetAuditGrid(bizObjects.First());
        }

        rptTableList.DataSource = linkTable;
        rptTableList.DataBind();
    }
Example #26
0
        /// <summary>
        /// Sets the input control values for the input controls
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void SetAttributeValueFields(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                // bizo representing attribute (i.e., MetadataFieldAttribute)
                IBusinessObject attributeBiz = BusinessObjectFactory.BuildBusinessObject(BIZ_ATTRIBUTE_TABLE.TableName);
                // bizo representing metadata attribute  value(i.e., MetadataFieldAttributeValue)
                IBusinessObject attributeValueBiz = BusinessObjectFactory.BuildBusinessObject(BIZ_ATTRIBUTE_VALUE_TABLE.TableName);
                // only corcerned about populating input controls which map to metadata attributes
                foreach (var nameToField in AttributeToHiddenField)
                {
                    string attributeName = nameToField.Key;
                    // field: pri key of attribute
                    ICaisisInputControl attributeIdField = nameToField.Value;
                    // field: pri key to attribute value
                    ICaisisInputControl attributeValueIdField = GetTableAttributeValueIdControl(e.Row, attributeName);
                    // field: attribute value
                    ICaisisInputControl attributeValueField = GetTableAttributeValueControl(e.Row, attributeName);
                    // field: disease attribute value id (i.e., Prostate PageTitle)
                    ICaisisInputControl diseaseAttributeValueId = GetDiseaseAttributeValueId(e.Row, attributeName);
                    // validate fields
                    if (attributeIdField != null && attributeValueIdField != null && attributeValueField != null)
                    {
                        int?attributeId      = null;
                        int?attributeValueId = null;
                        if (!string.IsNullOrEmpty(attributeIdField.Value))
                        {
                            attributeId = int.Parse(attributeIdField.Value);
                        }
                        else
                        {
                            return;// no need to process items without attribute??
                        }

                        IEnumerable <DataRow> diseaseDataSource = DataBinder.Eval(e.Row.DataItem, "DiseaseAttributes") as IEnumerable <DataRow>;
                        // for list of item's attribute value pairs, find by current attribute

                        if (diseaseAttributeValueId != null)
                        {
                            if (diseaseDataSource.Count() > 0)
                            {
                                var diseaseSpecificAttributeValue = from row in diseaseDataSource
                                                                    let rowAttributeName = row[attributeFieldName].ToString()
                                                                                           where rowAttributeName.Equals(attributeName, StringComparison.CurrentCultureIgnoreCase)
                                                                                           select row;
                                if (diseaseSpecificAttributeValue.Count() > 0)
                                {
                                    string priKeyField = BIZ_ATTRIBUTE_VALUE_TABLE.PrimaryKeyName;

                                    // set attribute value id
                                    attributeValueIdField.Value = diseaseSpecificAttributeValue.First()[priKeyField].ToString();
                                    // set attribute value
                                    attributeValueField.Value = diseaseSpecificAttributeValue.First()[attributeValueFieldName].ToString();
                                    // set disease value id field
                                    diseaseAttributeValueId.Value = diseaseSpecificAttributeValue.First()["DiseaseAttributeValueId"].ToString();;

                                    // call setter for attribute value
                                    SetInputControlValue(attributeValueField, attributeValueField.Value, diseaseSpecificAttributeValue.First());

                                    continue;
                                }
                            }
                        }
                        // data already filtered out to only include attributes for this metadata item
                        IEnumerable <DataRow> dataSource = DataBinder.Eval(e.Row.DataItem, "Data") as IEnumerable <DataRow>;

                        var found = from row in dataSource
                                    where !row.IsNull(attributeBiz.PrimaryKeyName)
                                    let rowAttributeId = (int)row[attributeBiz.PrimaryKeyName]
                                                         where rowAttributeId == attributeId.Value
                                                         select row;
                        DataRow attributeKeyAndValue = found.FirstOrDefault();
                        string  attributeValue       = string.Empty;
                        // if data row found, set fields
                        if (attributeKeyAndValue != null)
                        {
                            attributeValueId = (int)attributeKeyAndValue[attributeValueBiz.PrimaryKeyName];
                            attributeValue   = attributeKeyAndValue[attributeValueFieldName].ToString();
                            // update hidden pri key
                            attributeValueIdField.Value = attributeValueId.Value.ToString();
                        }
                        // call setter for attribute value
                        SetInputControlValue(attributeValueField, attributeValue, attributeKeyAndValue);
                    }
                }
                // for other non-attribute fields, run setter
                var nonAttributeControls = from cic in CICHelper.GetCaisisInputControls(e.Row)
                                           where cic.Table != BIZ_ATTRIBUTE_VALUE_TABLE.TableName && cic.Table != BIZ_DISEASE_ATTRIBUTE_VALUE_TABLE.TableName
                                           select cic;
                foreach (ICaisisInputControl cic in nonAttributeControls)
                {
                    object value = DataBinder.GetPropertyValue(e.Row.DataItem, cic.Field);
                    if (value != null)
                    {
                        cic.Value = value.ToString();
                        SetInputControlValue(cic, value.ToString(), null);
                    }
                }
            }
        }
Example #27
0
        private void AddGrid(GridView grid, ImageButton addNewRowButton, string tableName)
        {
            Panel panel = new Panel();

            panel.CssClass         = "PDSectionHolder";
            panel.Style["padding"] = "5px";
            panel.Style["width"]   = "auto";

            grid.Style["margin-left"] = "15px";
            grid.Style["margin-top"]  = "0px";

            // add clear items columns
            GridRowClearImage clearBtnColumn = new GridRowClearImage();

            grid.Columns.Add(clearBtnColumn);
            string[] keyNames = grid.DataKeyNames;

            // validate: LockedBy
            bool validateAuditField = lockableTables.Contains(tableName);

            // add delete button in special cases
            if (ALLOW_TABLE_DELETES.Contains(tableName))
            {
                string             priKeyName   = BOL.BusinessObject.GetPrimaryKeyName(tableName);
                GridRowDeleteImage deleteButton = new GridRowDeleteImage();
                grid.Columns.Add(deleteButton);
                grid.RowDeleting += (o, e) =>
                {
                    GridViewRow gridRow     = grid.Rows[e.RowIndex];
                    HiddenField priKeyField = gridRow.FindControl(priKeyName) as HiddenField;
                    if (priKeyField != null && !string.IsNullOrEmpty(priKeyField.Value))
                    {
                        // delete record
                        int            priKey = int.Parse(priKeyField.Value);
                        BusinessObject bo     = BusinessObjectFactory.BuildBusinessObject(tableName);
                        bo.Delete(priKey);
                        // reset patient item fields
                        Dictionary <string, IEnumerable <int> > destTableToKeys = new Dictionary <string, IEnumerable <int> >();
                        destTableToKeys.Add(tableName, new int[] { priKey });
                        string username = new Security.SecurityController().GetUserName();
                        ProtocolMgmtDa.ClearProtocolMgrPatientFieldsWithPKey(PatientItemId, destTableToKeys, username);

                        // TODO: proper redirect
                        Response.Redirect(Request.Url.PathAndQuery, true);
                    }
                };
            }

            // add hidden keys as input fields (used for UI)
            var hiddenKeyNames = keyNames.Except(new string[] { Patient.PatientId });

            grid.RowCreated += (sender, e) =>
            {
                int lastCellIndex = e.Row.Cells.Count - 1;
                if (lastCellIndex > -1)
                {
                    TableCell lastCell = e.Row.Cells[lastCellIndex];
                    foreach (string key in hiddenKeyNames)
                    {
                        HiddenField hidden = new HiddenField();
                        hidden.ID = key;
                        // add field to cell
                        lastCell.Controls.Add(hidden);
                    }
                }
            };

            // suppress clear button for existing records
            grid.RowDataBound += (sender, e) =>
            {
                // data retriever
                DataRowView           dataRow     = e.Row.DataItem as DataRowView;
                Func <string, object> getRowValue = (fieldName) =>
                {
                    return(dataRow != null && dataRow.Row.Table.Columns[fieldName] != null ? dataRow[fieldName] : null);
                };
                if (e.Row.RowType == DataControlRowType.DataRow && e.Row.DataItem != null)
                {
                    bool hasEmptyKeys = false;
                    // for each key field, set associated hidden field
                    foreach (string key in keyNames)
                    {
                        string      keyValue = getRowValue(key) + "";
                        HiddenField hidden   = e.Row.FindControl(key) as HiddenField;
                        if (hidden != null)
                        {
                            hidden.Value = keyValue;
                        }
                        hasEmptyKeys = hasEmptyKeys || string.IsNullOrEmpty(keyValue);
                    }
                    // suppress clear on "real" rows
                    IEnumerable <HyperLink> clearBtn = Caisis.UI.Core.Classes.PageUtil.GetControls <HyperLink>(e.Row).Where(btn => btn.CssClass.Contains("ClearGridRowLink"));
                    if (!hasEmptyKeys)
                    {
                        clearBtn.ForEach(b => b.Style["display"] = "none");
                    }
                    // suppress delete button on "fake" rows
                    IEnumerable <ImageButton> deleteBtn = Caisis.UI.Core.Classes.PageUtil.GetControls <ImageButton>(e.Row).Where(btn => btn.CommandName == "Delete");
                    if (hasEmptyKeys)
                    {
                        deleteBtn.ForEach(b => b.Style["display"] = "none");
                    }

                    // validate: LockedBy
                    if (validateAuditField)
                    {
                        object lockedBy    = getRowValue(BusinessObject.LockedBy);
                        bool   rowIsLocked = lockedBy != null && lockedBy + "" != "";
                        if (rowIsLocked)
                        {
                            // special case
                            var fields = CICHelper.GetCaisisInputControlDictionary(e.Row);
                            if (fields.ContainsKey(LabTest.LabClinicalSignificance))
                            {
                                var input = fields[LabTest.LabClinicalSignificance];
                                input.PreRender += (a, b) => input.Enabled = true;
                            }
                        }
                    }

                    // c13-124
                    if (MatchProtocol("c13-124") && tableName == "Medications" && includeAnalgesicMedications.HasValue)
                    {
                        string medType = getRowValue(Medication.MedType) + "";
                        bool   showRow = string.IsNullOrEmpty(medType) || (includeAnalgesicMedications.Value ? medType == "Analgesic" : medType != "Analgesic");
                        e.Row.Visible = showRow;
                    }
                }
            };

            gridsToValidate.Add(tableName, grid);

            grid.DataBind();
            grid.DataKeyNames = null; // workaround for ControlState bogosity

            panel.Controls.Add(grid);
            panel.Controls.Add(addNewRowButton);

            container.Controls.Add(panel);
        }
Example #28
0
        virtual protected void Page_Load(object sender, System.EventArgs e)
        {
            bool   retrieveValues = false;
            string pks            = Request["pkey"];

            if (pks != null && pks.Length > 0)
            {
                primaryKey = int.Parse(pks);
                //v4.0 model = new DynamicModel(tableName, primaryKey, patientID, new ValidateNullsDelegate(NullsValidatorWrapper.ValidateNullsHaveData));
                // model = new DynamicModel();

                bizo = BusinessObjectFactory.BuildBusinessObject(tableName);
                bizo.Get(primaryKey);

                retrieveValues = true;

                // peek at the lockedby
                if (bizo.HasField(BusinessObject.LockedBy))
                {
                    if (bizo[BusinessObject.LockedBy] != null && !string.IsNullOrEmpty(bizo[BusinessObject.LockedBy].ToString()))
                    {
                        recordIsLocked = true;
                    }
                }
            }
            else
            {
                //v4.0 model = new DynamicModel(tableName, patientID, new ValidateNullsDelegate(NullsValidatorWrapper.ValidateNullsHaveData));
                // model = new DynamicModel();

                bizo = BusinessObjectFactory.BuildBusinessObject(tableName);

                // is this necessary?
                if (bizo.HasField("PatientId"))
                {
                    bizo["PatientId"] = patientID;
                }
            }

            // set parent biz
            if (bizo != null)
            {
                // LOAD OPTIONAL PARENT TABLE

                // verify has parent which isn't Patient
                if (!string.IsNullOrEmpty(bizo.ParentTableName) && bizo.ParentTableName != "Patients")
                {
                    // validate no multiple foreign keys
                    if (bizo.ForeignKeyNames.Count() == 1 && !bizo.ForeignKeyNames.Contains(Patient.PatientId))
                    {
                        var pBiz = BusinessObjectFactory.BuildBusinessObject(bizo.ParentTableName);
                        // one last verification
                        if (!(pBiz is Patient))
                        {
                            parent = pBiz;
                            // load parent biz if applicable
                            if (bizo.PrimaryKeyHasValue)
                            {
                                int parPriKey = (int)bizo[bizo.ParentKeyName];
                                parent.Get(parPriKey);
                            }
                        }
                    }
                }
                // LOAD CHILD TABLES
                if (ChildTableNames.Length > 0)
                {
                    // rebuild child table lookup
                    _children = new Dictionary <string, IEnumerable <IBusinessObject> >();

                    int parentKey = (int)bizo[bizo.PrimaryKeyName];
                    // build lookup: child table -> child records
                    var childTableNames     = ChildTableNames.Where(t => BusinessObject.GetParentTablename(t) == bizo.TableName);
                    var childTableToRecords = childTableNames.ToDictionary(t => t, t => BusinessObject.GetByParent(t, parentKey));

                    // validation: validate children
                    foreach (var child in childTableToRecords)
                    {
                        string childTable = child.Key;
                        IEnumerable <IBusinessObject> childBizos = child.Value;

                        // if child is grid with no record, create blank data
                        bool isGrid = pdec.IsGridView(childTable);
                        if (isGrid && childBizos.Count() == 0)
                        {
                            // init blank rows
                            childBizos = new IBusinessObject[] { BusinessObjectFactory.BuildBusinessObject(childTable) };
                            // set parent key
                            foreach (var b in childBizos)
                            {
                                b[b.ParentKeyName] = parentKey;
                            }
                        }
                        // add entry
                        _children.Add(childTable, childBizos);
                    }
                }
            }

            if (Page.IsPostBack)
            {
                BuildControls(bizo, false);
            }
            else
            {
                BuildControls(bizo, retrieveValues);
            }
            // init field-tracking: note late bound binding
            foreach (var input in PageUtil.GetControls <ICaisisInputControl>(Page))
            {
                input.ValueChanged += MarkTableFieldsDirty;
            }
        }