Ejemplo n.º 1
0
        /// <summary>
        /// Returns contents of a table.
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="columnNames">List of column names to select. Column names should not be bracketed; this method will add brackets.</param>
        /// <returns>DataTable</returns>
        public virtual DataTable GetTableData(string tableName, List <string> columnNames)
        {
            WordBuilder wb = new WordBuilder(",");

            foreach (string s in columnNames)
            {
                wb.Add(this.InsertInEscape(s));
            }
            return(GetTableData(tableName, wb.ToString(), string.Empty));
        }
Ejemplo n.º 2
0
        /// <summary>
        /// AboutEpiInfo load event
        /// </summary>
        /// <param name="sender">Object that fired the event.</param>
        /// <param name="e">.NET supplied event args.</param>
        private void AboutEpiInfo_Load(object sender, System.EventArgs e)
        {
            try
            {
                ApplicationIdentity appId = new ApplicationIdentity(typeof(Configuration).Assembly);

                // App Name
                WordBuilder appNameBuilder = new WordBuilder();
                appNameBuilder.Add(appId.SuiteName);
                appNameBuilder.Add(appId.Version);
                lblAppName.Text = appNameBuilder.ToString();

                // Release date
                lblReleaseDate.Text = appId.VersionReleaseDate;

                // Description
                txtDescription.Text = Util.GetProductDescription();
            }
            catch (FileNotFoundException ex)
            {
                MsgBox.ShowException(ex);
            }
        }
        /// <summary>
        /// AboutEpiInfo load event
        /// </summary>
        /// <param name="sender">Object that fired the event.</param>
        /// <param name="e">.NET supplied event args.</param>
        private void AboutEpiInfo_Load(object sender, System.EventArgs e)
        {
            try
            {
                ApplicationIdentity appId = new ApplicationIdentity(typeof(Configuration).Assembly);

                // App Name
                WordBuilder appNameBuilder = new WordBuilder();
                appNameBuilder.Add("Epi Info\u2122");
                appNameBuilder.Add(appId.Version);
                lblAppName.Text = appNameBuilder.ToString();

                // Release date
                lblReleaseDate.Text = appId.VersionReleaseDate;

                // Description
                txtDescription.Text = Util.GetProductDescription();
            }
            catch (FileNotFoundException ex)
            {
                MsgBox.ShowException(ex);
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Initiates an export of the data to the specified file.
        /// </summary>
        public override void Export()
        {
            DataView     dv    = this.DataView;
            DataTable    table = new DataTable(); // dv.ToTable(false);
            WordBuilder  wb    = new WordBuilder(SEPARATOR);
            StreamWriter sw    = null;

            if (IncludeDeletedRecords == false)
            {
                if (table.Columns.Contains("RecStatus") || table.Columns.Contains("RECSTATUS"))
                {
                    dv.RowFilter = "[RecStatus] > 0";
                }
            }

            try
            {
                sw = File.CreateText(fileName);

                if (ColumnSortOrder != ImportExport.ColumnSortOrder.None || !exportAllFields)
                {
                    table = dv.ToTable(false);

                    if (view != null)
                    {
                        ImportExportHelper.OrderColumns(table, ColumnSortOrder, view);
                    }
                    else
                    {
                        ImportExportHelper.OrderColumns(table, ColumnSortOrder);
                    }

                    List <DataColumn> columnsToRemove = new List <DataColumn>();

                    foreach (DataColumn dc in table.Columns)
                    {
                        bool found = false;
                        foreach (Epi.Data.TableColumn tc in columnList)
                        {
                            if (tc.Name.Equals(dc.ColumnName))
                            {
                                found = true;
                                break;
                            }
                        }

                        if (!found)
                        {
                            columnsToRemove.Add(dc);
                        }
                    }

                    foreach (DataColumn dc in columnsToRemove)
                    {
                        table.Columns.Remove(dc);
                    }
                }

                foreach (DataColumn dc in table.Columns)
                {
                    wb.Add(dc.ColumnName);
                }

                sw.WriteLine(wb.ToString());
                rowsExported = 0;
                int totalRows = 0;

                //if (useTabOrder || !exportAllFields)
                //{
                totalRows = table.Rows.Count;
                foreach (DataRow row in table.Rows)
                {
                    wb = new WordBuilder(SEPARATOR);
                    for (int i = 0; i < table.Columns.Count; i++)
                    {
                        string rowValue = row[i].ToString().Replace("\r\n", " ");
                        if (rowValue.Contains(",") || rowValue.Contains("\""))
                        {
                            rowValue = rowValue.Replace("\"", "\"\"");
                            rowValue = Util.InsertIn(rowValue, "\"");
                        }
                        wb.Add(rowValue);
                    }
                    sw.WriteLine(wb);
                    rowsExported++;
                    if (rowsExported % 500 == 0)
                    {
                        //this.Dispatcher.BeginInvoke(new SetGadgetStatusHandler(RequestUpdateStatusMessage), string.Format(SharedStrings.DASHBOARD_EXPORT_PROGRESS, rowsExported.ToString(), totalRows.ToString()), (double)rowsExported);
                        //RequestUpdateStatusMessage(string.Format(SharedStrings.DASHBOARD_EXPORT_PROGRESS, rowsExported.ToString(), totalRows.ToString()), (double)rowsExported);
                        //SetProgressAndStatus(string.Format(SharedStrings.DASHBOARD_EXPORT_PROGRESS, rowsExported.ToString(), totalRows.ToString()), (double)rowsExported);
                        OnSetStatusMessageAndProgressCount(string.Format(SharedStrings.DASHBOARD_EXPORT_PROGRESS, rowsExported.ToString(), totalRows.ToString()), (double)rowsExported);
                    }
                }
                //}
                //else
                //{
                //    totalRows = dv.Count;
                //    foreach (DataRowView rowView in dv)
                //    {
                //        wb = new WordBuilder(SEPARATOR);
                //        for (int i = 0; i < table.Columns.Count; i++)
                //        {
                //            DataRow row = rowView.Row;
                //            string rowValue = row[i].ToString().Replace("\r\n", " ");
                //            if (rowValue.Contains(",") || rowValue.Contains("\""))
                //            {
                //                rowValue = rowValue.Replace("\"", "\"\"");
                //                rowValue = Util.InsertIn(rowValue, "\"");
                //            }
                //            wb.Add(rowValue);
                //        }
                //        sw.WriteLine(wb);
                //        rowsExported++;
                //        if (rowsExported % 500 == 0)
                //        {
                //            //this.Dispatcher.BeginInvoke(new SetGadgetStatusHandler(RequestUpdateStatusMessage), string.Format(SharedStrings.DASHBOARD_EXPORT_PROGRESS, rowsExported.ToString(), totalRows.ToString()), (double)rowsExported);
                //            //RequestUpdateStatusMessage(string.Format(SharedStrings.DASHBOARD_EXPORT_PROGRESS, rowsExported.ToString(), totalRows.ToString()), (double)rowsExported);
                //            SetProgressAndStatus(string.Format(SharedStrings.DASHBOARD_EXPORT_PROGRESS, rowsExported.ToString(), totalRows.ToString()), (double)rowsExported);
                //        }
                //    }
                //}

                //this.Dispatcher.BeginInvoke(new SetStatusDelegate(SetStatusMessage), string.Format(SharedStrings.DASHBOARD_EXPORT_SUCCESS, rowsExported.ToString()));
                OnSetStatusMessage(string.Format(SharedStrings.DASHBOARD_EXPORT_SUCCESS, rowsExported.ToString()));
            }

            catch (Exception ex)
            {
                OnSetStatusMessage(ex.Message);
                //this.Dispatcher.BeginInvoke(new SetStatusDelegate(SetErrorMessage), ex.Message);
            }
            finally
            {
                if (sw != null)
                {
                    sw.Close();
                    sw.Dispose();
                    sw = null;
                }

                //stopWatch.Stop();
                //System.Diagnostics.Debug.Print("File I/O Export thread finished in " + stopWatch.Elapsed.ToString());
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Initiates an export of the data to the specified file.
        /// </summary>
        public override void Export()
        {
            OnSetStatusMessage(ImportExportSharedStrings.WEB_CSV_EXPORT_CONNECTING);

            rowsExported = 0;
            WordBuilder wb = new WordBuilder(SEPARATOR);
            StreamWriter sw = null;

            Epi.Web.Common.Message.SurveyAnswerRequest Request = new Epi.Web.Common.Message.SurveyAnswerRequest();
            Request.Criteria.SurveyId = surveyKey.ToString();
            Request.Criteria.UserPublishKey = secToken;
            Request.Criteria.OrganizationKey = orgKey;
            Request.Criteria.ReturnSizeInfoOnly = true;
            Epi.Web.Common.Message.SurveyAnswerResponse Result = client.GetSurveyAnswer(Request);
            Pages = Result.NumberOfPages;
            PageSize = Result.PageSize;

            Request.Criteria.ReturnSizeInfoOnly = false;

            int count = 0;

            List<SurveyAnswerResponse> Results = new List<SurveyAnswerResponse>();

            OnSetStatusMessage(ImportExportSharedStrings.WEB_CSV_EXPORT_BUILDING_COLUMN_HEADINGS);

            for (int i = 1; i <= Pages; i++)
            {
                Request.Criteria.PageNumber = i;
                Request.Criteria.PageSize = PageSize;

                Result = client.GetSurveyAnswer(Request);
                Results.Add(Result);

                foreach (Epi.Web.Common.DTO.SurveyAnswerDTO surveyAnswer in Result.SurveyResponseList)
                {
                    if (surveyAnswer.Status == 3)
                    {
                        count++;
                    }
                }
            }

            if (SetMaxProgressBarValue != null)
            {
                SetMaxProgressBarValue((double)count);
            }

            List<string> columnHeaders = new List<string>();

            foreach (SurveyAnswerResponse R in Results)
            {
                wfList = ParseXML(R);

                foreach (WebFieldData wfData in wfList)
                {
                    if (!columnHeaders.Contains(wfData.FieldName))
                    {
                        columnHeaders.Add(wfData.FieldName);
                    }
                    else
                    {
                        break;
                    }
                }

                break;
            }

            try
            {
                OnSetStatusMessage(ImportExportSharedStrings.WEB_CSV_EXPORTING);

                sw = File.CreateText(fileName);

                foreach (string s in columnHeaders)
                {
                    wb.Add(s);
                }

                sw.WriteLine(wb.ToString());
                rowsExported = 0;

                foreach (SurveyAnswerResponse R in Results)
                {
                    string currentGUID = string.Empty;
                    string lastGUID = string.Empty;

                    wfList = ParseXML(R);

                    wb = new WordBuilder(SEPARATOR);

                    foreach (WebFieldData wfData in wfList)
                    {
                        currentGUID = wfData.RecordGUID;

                        if (!string.IsNullOrEmpty(currentGUID) && !string.IsNullOrEmpty(lastGUID) && currentGUID != lastGUID)
                        {
                            sw.WriteLine(wb.ToString());
                            wb = new WordBuilder(SEPARATOR);

                            OnSetStatusMessageAndProgressCount("", 1);
                        }

                        string rowValue = wfData.FieldValue.ToString().Replace("\r\n", " ");
                        if (rowValue.Contains(",") || rowValue.Contains("\""))
                        {
                            rowValue = rowValue.Replace("\"", "\"\"");
                            rowValue = Util.InsertIn(rowValue, "\"");
                        }
                        wb.Add(rowValue);

                        lastGUID = wfData.RecordGUID;
                    }

                    sw.WriteLine(wb.ToString());
                }

                OnSetStatusMessage(ImportExportSharedStrings.WEB_CSV_EXPORT_COMPLETE);

                if (FinishExport != null)
                {
                    FinishExport();
                }
            }

            catch (Exception ex)
            {
                OnSetStatusMessage(ex.Message);

                if (ExportFailed != null)
                {
                    ExportFailed(ex.Message);
                }
            }
            finally
            {
                // Clean up
                if (sw != null)
                {
                    sw.Close();
                    sw.Dispose();
                    sw = null;
                }
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Converts the gadget's output to Html
        /// </summary>
        /// <returns></returns>
        public override string ToHTML(string htmlFileName = "", int count = 0)
        {
            if (IsCollapsed) return string.Empty;

            StringBuilder htmlBuilder = new StringBuilder();

            CustomOutputHeading = headerPanel.Text;
            CustomOutputDescription = descriptionPanel.Text;

            if (CustomOutputHeading == null || (string.IsNullOrEmpty(CustomOutputHeading) && !CustomOutputHeading.Equals("(none)")))
            {
                htmlBuilder.AppendLine("<h2 class=\"gadgetHeading\">Crosstabulation</h2>");
            }
            else if (CustomOutputHeading != "(none)")
            {
                htmlBuilder.AppendLine("<h2 class=\"gadgetHeading\">" + CustomOutputHeading + "</h2>");
            }

            htmlBuilder.AppendLine("<p class=\"gadgetOptions\"><small>");
            htmlBuilder.AppendLine("<em>Main variable:</em> <strong>" + cbxExposureField.Text + "</strong>");
            htmlBuilder.AppendLine("<br />");

            htmlBuilder.AppendLine("<em>Crosstab variable:</em> <strong>" + cbxOutcomeField.Text + "</strong>");
            htmlBuilder.AppendLine("<br />");

            if (cbxFieldWeight.SelectedIndex >= 0)
            {
                htmlBuilder.AppendLine("<em>Weight variable:</em> <strong>" + cbxFieldWeight.Text + "</strong>");
                htmlBuilder.AppendLine("<br />");
            }
            //if (cbxFieldStrata.SelectedIndex >= 0)
            //{
            //    htmlBuilder.AppendLine("<em>Strata variable:</em> <strong>" + cbxFieldStrata.Text + "</strong>");
            //    htmlBuilder.AppendLine("<br />");
            //}
            if (lbxFieldStrata.SelectedItems.Count > 0)
            {
                WordBuilder wb = new WordBuilder(", ");
                foreach (string s in lbxFieldStrata.SelectedItems)
                {
                    wb.Add(s);
                }
                htmlBuilder.AppendLine("<em>Strata variable:</em> <strong>" + wb.ToString() + "</strong>");
                htmlBuilder.AppendLine("<br />");
            }

            htmlBuilder.AppendLine("<em>Include missing:</em> <strong>" + checkboxIncludeMissing.IsChecked.ToString() + "</strong>");
            htmlBuilder.AppendLine("<br />");
            htmlBuilder.AppendLine("</small></p>");

            if (!string.IsNullOrEmpty(CustomOutputDescription))
            {
                htmlBuilder.AppendLine("<p class=\"gadgetsummary\">" + CustomOutputDescription + "</p>");
            }

            if (!string.IsNullOrEmpty(messagePanel.Text) && messagePanel.Visibility == Visibility.Visible)
            {
                htmlBuilder.AppendLine("<p><small><strong>" + messagePanel.Text + "</strong></small></p>");
            }

            if (!string.IsNullOrEmpty(infoPanel.Text) && infoPanel.Visibility == Visibility.Visible)
            {
                htmlBuilder.AppendLine("<p><small><strong>" + infoPanel.Text + "</strong></small></p>");
            }

            foreach (Grid grid in this.StrataGridList)
            {
                string gridName = grid.Tag.ToString();

                htmlBuilder.AppendLine("<div style=\"height: 7px;\"></div>");
                htmlBuilder.AppendLine("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\">");
                htmlBuilder.AppendLine("<caption>" + cbxExposureField.Text + " * " + cbxOutcomeField.Text + "</caption>");

                foreach (UIElement control in grid.Children)
                {
                    string value = string.Empty;
                    int rowNumber = -1;
                    int columnNumber = -1;
                    if (control is TextBlock || control is StackPanel)
                    {
                        if (control is TextBlock)
                        {
                            rowNumber = Grid.GetRow(control);
                            columnNumber = Grid.GetColumn(control);
                            value = ((TextBlock)control).Text;
                        }
                        else if (control is StackPanel)
                        {
                            rowNumber = Grid.GetRow(control);
                            columnNumber = Grid.GetColumn(control);
                            value = (((control as StackPanel).Children[0]) as TextBlock).Text;
                        }

                        string tableDataTagOpen = "<td>";
                        string tableDataTagClose = "</td>";

                        if (rowNumber == 0)
                        {
                            tableDataTagOpen = "<th>";
                            tableDataTagClose = "</th>";
                        }

                        if (columnNumber == 0)
                        {
                            htmlBuilder.AppendLine("<tr>");
                        }
                        if (columnNumber == 0 && rowNumber > 0)
                        {
                            tableDataTagOpen = "<td class=\"value\">";
                        }

                        string formattedValue = value;

                        if ((rowNumber == grid.RowDefinitions.Count - 1) || (columnNumber == grid.ColumnDefinitions.Count - 1))
                        {
                            formattedValue = "<span class=\"total\">" + value + "</span>";
                        }

                        htmlBuilder.AppendLine(tableDataTagOpen + formattedValue + tableDataTagClose);

                        if (columnNumber >= grid.ColumnDefinitions.Count - 1)
                        {
                            htmlBuilder.AppendLine("</tr>");
                        }
                    }
                }

                htmlBuilder.AppendLine("</table>");

                // Chi Square

                Grid chiSquareGrid = GetStrataChiSquareGrid(grid.Tag.ToString());
                htmlBuilder.AppendLine("<p></p>");
                htmlBuilder.AppendLine("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\">");

                foreach (UIElement control in chiSquareGrid.Children)
                {
                    if (control is TextBlock)
                    {
                        int rowNumber = Grid.GetRow(control);
                        int columnNumber = Grid.GetColumn(control);

                        string tableDataTagOpen = "<td>";
                        string tableDataTagClose = "</td>";

                        if (rowNumber == 0)
                        {
                            tableDataTagOpen = "<th>";
                            tableDataTagClose = "</th>";
                        }

                        if (columnNumber == 0)
                        {
                            htmlBuilder.AppendLine("<tr>");
                        }

                        string value = ((TextBlock)control).Text;
                        string formattedValue = value;

                        htmlBuilder.AppendLine(tableDataTagOpen + formattedValue + tableDataTagClose);

                        if (columnNumber >= grid.ColumnDefinitions.Count - 1)
                        {
                            htmlBuilder.AppendLine("</tr>");
                        }
                    }
                }

                htmlBuilder.AppendLine("</table>");

                string disclaimer = GetStrataChiSquareDisclaimer(grid.Tag.ToString()).Text;
                if (!string.IsNullOrEmpty(disclaimer))
                {
                    htmlBuilder.AppendLine("<p></p>");
                    htmlBuilder.AppendLine("<p>" + disclaimer.Replace("<", "&lt;") + "</p>");
                }

                // End Chi Square
            }

            foreach (GadgetMatchedPairPanel grid2x2 in this.strata2x2GridList)
            {
                //string gridName = grid.Tag.ToString();
                string gridName = string.Empty;
                if (grid2x2.Tag != null)
                {
                    gridName = grid2x2.Tag.ToString();
                }
                if (!string.IsNullOrEmpty(gridName))
                {
                    htmlBuilder.AppendLine("<h3>" + gridName + "</h3>");
                }
                htmlBuilder.AppendLine("<div style=\"height: 7px;\"></div>");
                htmlBuilder.AppendLine(grid2x2.ToHTML());
                htmlBuilder.AppendLine("<p></p>");
            }

            foreach (UIElement element in panelMain.Children)
            {
                if (element is GadgetMatchedPairPanel)
                {
                    GadgetMatchedPairPanel stap = element as GadgetMatchedPairPanel;
                    htmlBuilder.AppendLine("<div style=\"height: 7px;\"></div>");
                    htmlBuilder.AppendLine(stap.ToHTML());
                    htmlBuilder.AppendLine("<p></p>");
                }
            }

            return htmlBuilder.ToString();
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Generates Xml representation of this gadget
        /// </summary>
        /// <param name="doc">The Xml docment</param>
        /// <returns>XmlNode</returns>
        public override XmlNode Serialize(XmlDocument doc)
        {
            CreateInputVariableList();

            Dictionary<string, string> inputVariableList = GadgetOptions.InputVariableList;

            string freqVar = string.Empty;
            string strataVar = string.Empty;
            string weightVar = string.Empty;
            string sort = string.Empty;
            bool allValues = false;
            bool showConfLimits = true;
            bool showCumulativePercent = true;
            bool includeMissing = false;

            WordBuilder wb = new WordBuilder(",");
            if (lbxColumns.SelectedItems.Contains("Frequency")) wb.Add("1");
            if (lbxColumns.SelectedItems.Contains("Percent")) wb.Add("2");
            if (lbxColumns.SelectedItems.Contains("Cumulative Percent")) wb.Add("3");
            if (lbxColumns.SelectedItems.Contains("95% CI Lower")) wb.Add("4");
            if (lbxColumns.SelectedItems.Contains("95% CI Upper")) wb.Add("5");
            if (lbxColumns.SelectedItems.Contains("Percent bars")) wb.Add("6");

            if (inputVariableList.ContainsKey("freqvar"))
            {
                freqVar = inputVariableList["freqvar"].Replace("<", "&lt;");
            }
            if (inputVariableList.ContainsKey("stratavar"))
            {
                strataVar = inputVariableList["stratavar"].Replace("<", "&lt;");
            }
            if (inputVariableList.ContainsKey("weightvar"))
            {
                weightVar = inputVariableList["weightvar"].Replace("<", "&lt;");
            }
            if (inputVariableList.ContainsKey("sort"))
            {
                sort = inputVariableList["sort"];
            }
            if (inputVariableList.ContainsKey("allvalues"))
            {
                allValues = bool.Parse(inputVariableList["allvalues"]);
            }
            if (inputVariableList.ContainsKey("showconflimits"))
            {
                showConfLimits = bool.Parse(inputVariableList["showconflimits"]);
            }
            if (inputVariableList.ContainsKey("showcumulativepercent"))
            {
                showCumulativePercent = bool.Parse(inputVariableList["showcumulativepercent"]);
            }
            if (inputVariableList.ContainsKey("includemissing"))
            {
                includeMissing = bool.Parse(inputVariableList["includemissing"]);
            }

            int precision = 4;
            if (cbxFieldPrecision.SelectedIndex >= 0)
            {
                precision = cbxFieldPrecision.SelectedIndex;
            }

            CustomOutputHeading = headerPanel.Text;
            CustomOutputDescription = descriptionPanel.Text;

            string xmlString =
            "<mainVariable>" + freqVar + "</mainVariable>";

            if(GadgetOptions.StrataVariableNames.Count == 1)
            {
                xmlString = xmlString + "<strataVariable>" + GadgetOptions.StrataVariableNames[0].Replace("<", "&lt;") + "</strataVariable>";
            }
            else if (GadgetOptions.StrataVariableNames.Count > 1)
            {
                xmlString = xmlString + "<strataVariables>";

                foreach (string strataVariable in this.GadgetOptions.StrataVariableNames)
                {
                    xmlString = xmlString + "<strataVariable>" + strataVariable.Replace("<", "&lt;") + "</strataVariable>";
                }

                xmlString = xmlString + "</strataVariables>";
            }

            xmlString = xmlString + "<weightVariable>" + weightVar + "</weightVariable>" +
            "<sort>" + sort + "</sort>" +
            "<allValues>" + allValues + "</allValues>" +
            "<precision>" + precision.ToString() + "</precision>" +
            "<showListLabels>" + checkboxCommentLegalLabels.IsChecked + "</showListLabels>" +
            "<useFieldPrompts>" + checkboxUsePrompts.IsChecked.ToString() + "</useFieldPrompts>" +
            "<columnsToShow>" + wb.ToString() + "</columnsToShow>" +
            "<includeMissing>" + includeMissing + "</includeMissing>" +
            "<customHeading>" + CustomOutputHeading.Replace("<", "&lt;") + "</customHeading>" +
            "<customDescription>" + CustomOutputDescription.Replace("<", "&lt;") + "</customDescription>" +
            "<customCaption>" + CustomOutputCaption + "</customCaption>";

            if (!string.IsNullOrEmpty(txtRows.Text))
            {
                xmlString += "<rowsToDisplay>" + txtRows.Text + "</rowsToDisplay>";
            }

            xmlString = xmlString + SerializeAnchors();

            System.Xml.XmlElement element = doc.CreateElement("frequencyGadget");
            element.InnerXml = xmlString;
            element.AppendChild(SerializeFilters(doc));

            System.Xml.XmlAttribute id = doc.CreateAttribute("id");
            System.Xml.XmlAttribute locationY = doc.CreateAttribute("top");
            System.Xml.XmlAttribute locationX = doc.CreateAttribute("left");
            System.Xml.XmlAttribute collapsed = doc.CreateAttribute("collapsed");
            System.Xml.XmlAttribute type = doc.CreateAttribute("gadgetType");

            id.Value = this.UniqueIdentifier.ToString();
            locationY.Value = Canvas.GetTop(this).ToString("F0");
            locationX.Value = Canvas.GetLeft(this).ToString("F0");
            collapsed.Value = IsCollapsed.ToString();
            type.Value = "EpiDashboard.FrequencyControl";

            element.Attributes.Append(locationY);
            element.Attributes.Append(locationX);
            element.Attributes.Append(collapsed);
            element.Attributes.Append(type);
            element.Attributes.Append(id);

            return element;
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Initiates an export of the data to the specified file.
        /// </summary>
        public override void Export()
        {
            DataView dv = this.DataView;
            DataTable table = new DataTable(); // dv.ToTable(false);
            WordBuilder wb = new WordBuilder(SEPARATOR);
            StreamWriter sw = null;

            if (IncludeDeletedRecords == false)
            {
                if (table.Columns.Contains("RecStatus") || table.Columns.Contains("RECSTATUS"))
                {
                    dv.RowFilter = "[RecStatus] > 0";
                }
            }

            try
            {
                sw = File.CreateText(fileName);

                if (ColumnSortOrder != ImportExport.ColumnSortOrder.None || !exportAllFields)
                {
                    table = dv.ToTable(false);

                    if (view != null)
                    {
                        ImportExportHelper.OrderColumns(table, ColumnSortOrder, view);
                    }
                    else
                    {
                        ImportExportHelper.OrderColumns(table, ColumnSortOrder);
                    }

                    List<DataColumn> columnsToRemove = new List<DataColumn>();

                    foreach (DataColumn dc in table.Columns)
                    {
                        bool found = false;
                        foreach (Epi.Data.TableColumn tc in columnList)
                        {
                            if (tc.Name.Equals(dc.ColumnName))
                            {
                                found = true;
                                break;
                            }
                        }

                        if (!found)
                        {
                            columnsToRemove.Add(dc);
                        }
                    }

                    foreach (DataColumn dc in columnsToRemove)
                    {
                        table.Columns.Remove(dc);
                    }
                }

                foreach (DataColumn dc in table.Columns)
                {
                    wb.Add(dc.ColumnName);
                }

                sw.WriteLine(wb.ToString());
                rowsExported = 0;
                int totalRows = 0;

                //if (useTabOrder || !exportAllFields)
                //{
                totalRows = table.Rows.Count;
                foreach (DataRow row in table.Rows)
                {
                    wb = new WordBuilder(SEPARATOR);
                    for (int i = 0; i < table.Columns.Count; i++)
                    {
                        string rowValue = row[i].ToString().Replace("\r\n", " ");
                        if (rowValue.Contains(",") || rowValue.Contains("\""))
                        {
                            rowValue = rowValue.Replace("\"", "\"\"");
                            rowValue = Util.InsertIn(rowValue, "\"");
                        }
                        wb.Add(rowValue);
                    }
                    sw.WriteLine(wb);
                    rowsExported++;
                    if (rowsExported % 500 == 0)
                    {
                        //this.Dispatcher.BeginInvoke(new SetGadgetStatusHandler(RequestUpdateStatusMessage), string.Format(SharedStrings.DASHBOARD_EXPORT_PROGRESS, rowsExported.ToString(), totalRows.ToString()), (double)rowsExported);
                        //RequestUpdateStatusMessage(string.Format(SharedStrings.DASHBOARD_EXPORT_PROGRESS, rowsExported.ToString(), totalRows.ToString()), (double)rowsExported);
                        //SetProgressAndStatus(string.Format(SharedStrings.DASHBOARD_EXPORT_PROGRESS, rowsExported.ToString(), totalRows.ToString()), (double)rowsExported);
                        OnSetStatusMessageAndProgressCount(string.Format(SharedStrings.DASHBOARD_EXPORT_PROGRESS, rowsExported.ToString(), totalRows.ToString()), (double)rowsExported);
                    }
                }
                //}
                //else
                //{
                //    totalRows = dv.Count;
                //    foreach (DataRowView rowView in dv)
                //    {
                //        wb = new WordBuilder(SEPARATOR);
                //        for (int i = 0; i < table.Columns.Count; i++)
                //        {
                //            DataRow row = rowView.Row;
                //            string rowValue = row[i].ToString().Replace("\r\n", " ");
                //            if (rowValue.Contains(",") || rowValue.Contains("\""))
                //            {
                //                rowValue = rowValue.Replace("\"", "\"\"");
                //                rowValue = Util.InsertIn(rowValue, "\"");
                //            }
                //            wb.Add(rowValue);
                //        }
                //        sw.WriteLine(wb);
                //        rowsExported++;
                //        if (rowsExported % 500 == 0)
                //        {
                //            //this.Dispatcher.BeginInvoke(new SetGadgetStatusHandler(RequestUpdateStatusMessage), string.Format(SharedStrings.DASHBOARD_EXPORT_PROGRESS, rowsExported.ToString(), totalRows.ToString()), (double)rowsExported);
                //            //RequestUpdateStatusMessage(string.Format(SharedStrings.DASHBOARD_EXPORT_PROGRESS, rowsExported.ToString(), totalRows.ToString()), (double)rowsExported);
                //            SetProgressAndStatus(string.Format(SharedStrings.DASHBOARD_EXPORT_PROGRESS, rowsExported.ToString(), totalRows.ToString()), (double)rowsExported);
                //        }
                //    }
                //}

                //this.Dispatcher.BeginInvoke(new SetStatusDelegate(SetStatusMessage), string.Format(SharedStrings.DASHBOARD_EXPORT_SUCCESS, rowsExported.ToString()));
                OnSetStatusMessage(string.Format(SharedStrings.DASHBOARD_EXPORT_SUCCESS, rowsExported.ToString()));
            }

            catch (Exception ex)
            {
                OnSetStatusMessage(ex.Message);
                //this.Dispatcher.BeginInvoke(new SetStatusDelegate(SetErrorMessage), ex.Message);
            }
            finally
            {
                if (sw != null)
                {
                    sw.Close();
                    sw.Dispose();
                    sw = null;
                }

                //stopWatch.Stop();
                //System.Diagnostics.Debug.Print("File I/O Export thread finished in " + stopWatch.Elapsed.ToString());
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Used to generate the list of variables and options for the GadgetParameters object
        /// </summary> 
        private void CreateInputVariableList()
        {
            Dictionary<string, string> inputVariableList = new Dictionary<string, string>();

            GadgetOptions.MainVariableName = string.Empty;
            GadgetOptions.WeightVariableName = string.Empty;
            GadgetOptions.StrataVariableNames = new List<string>();
            GadgetOptions.CrosstabVariableName = string.Empty;

            List<string> listFields = new List<string>();

            if (lbxFields.SelectedItems.Count > 0)
            {
                foreach (string item in lbxFields.SelectedItems)
                {
                    if (!string.IsNullOrEmpty(item))
                    {
                        listFields.Add(item);
                    }
                }
            }

            listFields.Sort();
            if (IsHostedByEnter)
            {
                //if (dashboardHelper.IsUsingEpiProject && checkboxAllowUpdates.IsChecked == true)
                //{
                    if (listFields.Contains("UniqueKey"))
                        listFields.Remove("UniqueKey");
                    listFields.Add("UniqueKey");
                //}
            }

            foreach (string field in listFields)
            {
                inputVariableList.Add(field, "listfield");
            }

            if (!inputVariableList.ContainsKey("sortcolumnsbytaborder"))
            {
                if (checkboxTabOrder.IsChecked == true)
                {
                    inputVariableList.Add("sortcolumnsbytaborder", "true");
                }
                else
                {
                    inputVariableList.Add("sortcolumnsbytaborder", "false");
                }
            }

            if (!inputVariableList.ContainsKey("usepromptsforcolumnnames"))
            {
                if (checkboxUsePrompts.IsChecked == true)
                {
                    inputVariableList.Add("usepromptsforcolumnnames", "true");
                }
                else
                {
                    inputVariableList.Add("usepromptsforcolumnnames", "false");
                }
            }

            if (!inputVariableList.ContainsKey("showcolumnheadings"))
            {
                if (checkboxColumnHeaders.IsChecked == true)
                {
                    inputVariableList.Add("showcolumnheadings", "true");
                }
                else
                {
                    inputVariableList.Add("showcolumnheadings", "false");
                }
            }

            if (!inputVariableList.ContainsKey("showlinecolumn"))
            {
                if (checkboxLineColumn.IsChecked == true)
                {
                    inputVariableList.Add("showlinecolumn", "true");
                }
                else
                {
                    inputVariableList.Add("showlinecolumn", "false");
                }
            }

            if (!inputVariableList.ContainsKey("shownulllabels"))
            {
                if (checkboxShowNulls.IsChecked == true)
                {
                    inputVariableList.Add("shownulllabels", "true");
                }
                else
                {
                    inputVariableList.Add("shownulllabels", "false");
                }
            }

            if (checkboxListLabels.IsChecked == true)
            {
                GadgetOptions.ShouldShowCommentLegalLabels = true;
            }
            else
            {
                GadgetOptions.ShouldShowCommentLegalLabels = false;
            }

            if (lbxSortFields.Items.Count > 0)
            {
                foreach (string item in lbxSortFields.Items)
                {
                    if (!string.IsNullOrEmpty(item))
                    {
                        string baseStr = item;

                        if (baseStr.EndsWith("(ascending)"))
                        {
                            baseStr = "[" + baseStr.Remove(baseStr.Length - 12) + "] ASC";
                        }
                        if (baseStr.EndsWith("(descending)"))
                        {
                            baseStr = "[" + baseStr.Remove(baseStr.Length - 13) + "] DESC";
                        }
                        inputVariableList.Add(baseStr, "sortfield");
                    }
                }
            }

            if (cbxGroupField.SelectedIndex >= 0)
            {
                if (!string.IsNullOrEmpty(cbxGroupField.SelectedItem.ToString()))
                {
                    GadgetOptions.StrataVariableNames.Add(cbxGroupField.SelectedItem.ToString());
                }
            }

            if (StrataGridList.Count >= 1)
            {
                Grid grid = StrataGridList[0];
                SortedDictionary<int, string> sortColumnDictionary = new SortedDictionary<int, string>();

                foreach (UIElement element in grid.Children)
                {
                    if (Grid.GetRow(element) == 0 && element is TextBlock)
                    {
                        TextBlock txtColumnName = element as TextBlock;
                        //columnOrder.Add(txtColumnName.Text);
                        sortColumnDictionary.Add(Grid.GetColumn(element), txtColumnName.Text);
                    }
                }

                columnOrder = new List<string>();
                foreach (KeyValuePair<int, string> kvp in sortColumnDictionary)
                {
                    columnOrder.Add(kvp.Value);
                }

                if (columnOrder.Count == listFields.Count || columnOrder.Count == (listFields.Count + 1))
                {
                    bool same = true;
                    foreach (string s in listFields)
                    {
                        if (!columnOrder.Contains(s))
                        {
                            same = false;
                        }
                    }

                    if (same)
                    {
                        WordBuilder wb = new WordBuilder("^");
                        foreach (string s in columnOrder)
                        {
                            wb.Add(s);
                        }

                        inputVariableList.Add("customusercolumnsort", wb.ToString());
                    }
                    else
                    {
                        columnOrder = new List<string>();
                    }
                }
                else
                {
                    columnOrder = new List<string>();
                }
            }

            inputVariableList.Add("maxcolumns", MaxColumns.ToString());
            inputVariableList.Add("maxrows", MaxRows.ToString());

            GadgetOptions.ShouldIncludeFullSummaryStatistics = false;
            GadgetOptions.InputVariableList = inputVariableList;
        }
        /// <summary>
        /// Converts the gadget's output to Html
        /// </summary>
        /// <returns></returns>
        public override string ToHTML(string htmlFileName = "", int count = 0)
        {
            if (IsCollapsed) return string.Empty;
            ComplexSampleMeansParameters csmeansParameters = (ComplexSampleMeansParameters)Parameters;
            StringBuilder htmlBuilder = new StringBuilder();

            CustomOutputHeading = headerPanel.Text;
            CustomOutputDescription = descriptionPanel.Text;

            if (CustomOutputHeading == null || (string.IsNullOrEmpty(CustomOutputHeading) && !CustomOutputHeading.Equals("(none)")))
            {
                htmlBuilder.AppendLine("<h2 class=\"gadgetHeading\">Complex Sample Means</h2>");
            }
            else if(CustomOutputHeading != "(none)")
            {
                htmlBuilder.AppendLine("<h2 class=\"gadgetHeading\">" + CustomOutputHeading + "</h2>");
            }

            htmlBuilder.AppendLine("<p class=\"gadgetOptions\"><small>");
            htmlBuilder.AppendLine("<em>Frequency variable:</em> <strong>" + csmeansParameters.ColumnNames[0] + "</strong>");
            htmlBuilder.AppendLine("<br />");
            htmlBuilder.AppendLine("<em>PSU variable:</em> <strong>" + csmeansParameters.PSUVariableName + "</strong>");
            htmlBuilder.AppendLine("<br />");

            if (!String.IsNullOrEmpty(csmeansParameters.CrosstabVariableName))
            {
                htmlBuilder.AppendLine("<em>Crosstab variable:</em> <strong>" + csmeansParameters.CrosstabVariableName + "</strong>");
                htmlBuilder.AppendLine("<br />");
            }
            if (!String.IsNullOrEmpty(csmeansParameters.WeightVariableName))
            {
                htmlBuilder.AppendLine("<em>Weight variable:</em> <strong>" + csmeansParameters.WeightVariableName + "</strong>");
                htmlBuilder.AppendLine("<br />");
            }
            if (csmeansParameters.StrataVariableNames.Count > 0)
            {
                WordBuilder wb = new WordBuilder(", ");
                foreach (string s in csmeansParameters.StrataVariableNames)
                {
                    wb.Add(s);
                }
                htmlBuilder.AppendLine("<em>Strata variable:</em> <strong>" + wb.ToString() + "</strong>");
                htmlBuilder.AppendLine("<br />");
            }
            //htmlBuilder.AppendLine("<em>Include missing:</em> <strong>" + checkboxIncludeMissing.IsChecked.ToString() + "</strong>");
            //htmlBuilder.AppendLine("<br />");
            htmlBuilder.AppendLine("</small></p>");

            if (!string.IsNullOrEmpty(CustomOutputDescription))
            {
                htmlBuilder.AppendLine("<p class=\"gadgetsummary\">" + CustomOutputDescription + "</p>");
            }

            if (!string.IsNullOrEmpty(messagePanel.Text) && messagePanel.Visibility == Visibility.Visible)
            {
                htmlBuilder.AppendLine("<p><small><strong>" + messagePanel.Text + "</strong></small></p>");
            }

            if (!string.IsNullOrEmpty(txtFilterString.Text) && txtFilterString.Visibility == Visibility.Visible)
            {
                htmlBuilder.AppendLine("<p><small><strong>" + txtFilterString.Text + "</strong></small></p>");
            }

            foreach (Grid grid in this.StrataGridList)
            {
                string gridName = grid.Tag.ToString();

                htmlBuilder.AppendLine("<div style=\"height: 7px;\"></div>");
                htmlBuilder.AppendLine("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\">");

                htmlBuilder.AppendLine("<tr>");
                htmlBuilder.AppendLine(" <th>&nbsp;</th>");
                htmlBuilder.AppendLine(" <th colspan=\"7\">" + csmeansParameters.ColumnNames[0] + "</th>");
                htmlBuilder.AppendLine("</tr>");

                htmlBuilder.AppendLine("<tr>");
                htmlBuilder.AppendLine(" <th rowspan=\"2\">" + csmeansParameters.CrosstabVariableName + "</th>");
                htmlBuilder.AppendLine(" <th rowspan=\"2\">Count</th>");
                htmlBuilder.AppendLine(" <th rowspan=\"2\">Mean</th>");
                htmlBuilder.AppendLine(" <th rowspan=\"2\">Std Error</th>");
                htmlBuilder.AppendLine(" <th rowspan=\"1\" colspan=\"2\">Confidence Limits</th>");
                htmlBuilder.AppendLine(" <th rowspan=\"2\">Minimum</th>");
                htmlBuilder.AppendLine(" <th rowspan=\"2\">Maximum</th>");
                htmlBuilder.AppendLine("</tr>");

                htmlBuilder.AppendLine("<tr>");
                htmlBuilder.AppendLine(" <th>Lower</th>");
                htmlBuilder.AppendLine(" <th>Upper</th>");
                htmlBuilder.AppendLine("</tr>");

                for (int i = 3; i < grid.RowDefinitions.Count; i++)
                {
                    for (int j = 0; j < grid.ColumnDefinitions.Count; j++)
                    {
                        string tableDataTagOpen = "<td>";
                        string tableDataTagClose = "</td>";

                        if (j == 0)
                        {
                            htmlBuilder.AppendLine("<tr>");
                        }
                        if (j == 0 && i > 0)
                        {
                            tableDataTagOpen = "<td class=\"value\">";
                        }

                        IEnumerable<UIElement> elements = grid.Children.Cast<UIElement>().Where(x => Grid.GetRow(x) == i && Grid.GetColumn(x) == j);
                        TextBlock txt = null;
                        foreach (UIElement element in elements)
                        {
                            if (element is TextBlock)
                            {
                                txt = element as TextBlock;
                            }
                        }

                        string value = "&nbsp;";

                        if (txt != null)
                        {
                            value = txt.Text;
                        }

                        htmlBuilder.AppendLine(tableDataTagOpen + value + tableDataTagClose);

                        if (j >= grid.ColumnDefinitions.Count - 1)
                        {
                            htmlBuilder.AppendLine("</tr>");
                        }
                    }
                }

                htmlBuilder.AppendLine("</table>");
            }
            return htmlBuilder.ToString();
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Generates Xml representation of this gadget
        /// </summary>
        /// <param name="doc">The Xml docment</param>
        /// <returns>XmlNode</returns>
        public override XmlNode Serialize(XmlDocument doc)
        {
            CreateInputVariableList();

            Dictionary<string, string> inputVariableList = GadgetOptions.InputVariableList;

            string meansVar = string.Empty;
            string strataVar = string.Empty;
            string weightVar = string.Empty;
            string crosstabVar = string.Empty;

            WordBuilder wb = new WordBuilder(",");
            if (lbxColumns.SelectedItems.Contains("Observations")) wb.Add("1");
            if (lbxColumns.SelectedItems.Contains("Total")) wb.Add("2");
            if (lbxColumns.SelectedItems.Contains("Mean")) wb.Add("3");
            if (lbxColumns.SelectedItems.Contains("Variance")) wb.Add("4");
            if (lbxColumns.SelectedItems.Contains("Std. Dev.")) wb.Add("5");
            if (lbxColumns.SelectedItems.Contains("Minimum")) wb.Add("6");
            if (lbxColumns.SelectedItems.Contains("25%")) wb.Add("7");
            if (lbxColumns.SelectedItems.Contains("Median")) wb.Add("8");
            if (lbxColumns.SelectedItems.Contains("75%")) wb.Add("9");
            if (lbxColumns.SelectedItems.Contains("Maximum")) wb.Add("10");
            if (lbxColumns.SelectedItems.Contains("Mode")) wb.Add("11");

            if (inputVariableList.ContainsKey("meansvar"))
            {
                meansVar = inputVariableList["meansvar"].Replace("<", "&lt;");
            }
            if (inputVariableList.ContainsKey("stratavar"))
            {
                strataVar = inputVariableList["stratavar"].Replace("<", "&lt;");
            }
            if (inputVariableList.ContainsKey("weightvar"))
            {
                weightVar = inputVariableList["weightvar"].Replace("<", "&lt;");
            }
            if (inputVariableList.ContainsKey("crosstabvar"))
            {
                crosstabVar = inputVariableList["crosstabvar"].Replace("<", "&lt;");
            }

            CustomOutputHeading = headerPanel.Text;
            CustomOutputDescription = descriptionPanel.Text;

            int precision = 4;
            if (cbxFieldPrecision.SelectedIndex >= 0)
            {
                precision = cbxFieldPrecision.SelectedIndex;
            }

            string xmlString =
            "<mainVariable>" + meansVar + "</mainVariable>";

            if(GadgetOptions.StrataVariableNames.Count == 1)
            {
                xmlString = xmlString + "<strataVariable>" + GadgetOptions.StrataVariableNames[0].Replace("<", "&lt;") + "</strataVariable>";
            }
            else if (GadgetOptions.StrataVariableNames.Count > 1)
            {
                xmlString = xmlString + "<strataVariables>";

                foreach (string strataVariable in this.GadgetOptions.StrataVariableNames)
                {
                    xmlString = xmlString + "<strataVariable>" + strataVariable.Replace("<", "&lt;") + "</strataVariable>";
                }

                xmlString = xmlString + "</strataVariables>";
            }

            xmlString = xmlString + "<weightVariable>" + weightVar + "</weightVariable>" +
            "<crosstabVariable>" + crosstabVar + "</crosstabVariable>" +
            "<columnsToShow>" + wb.ToString() + "</columnsToShow>" +
            "<precision>" + precision.ToString() + "</precision>" +
            "<showANOVA>" + (bool)checkboxShowANOVA.IsChecked + "</showANOVA>" +
            "<customHeading>" + CustomOutputHeading.Replace("<", "&lt;") + "</customHeading>" +
            "<customDescription>" + CustomOutputDescription.Replace("<", "&lt;") + "</customDescription>" +
            "<customCaption>" + CustomOutputCaption + "</customCaption>";

            xmlString = xmlString + SerializeAnchors();

            System.Xml.XmlElement element = doc.CreateElement("meansGadget");
            element.InnerXml = xmlString;
            element.AppendChild(SerializeFilters(doc));

            System.Xml.XmlAttribute id = doc.CreateAttribute("id");
            System.Xml.XmlAttribute locationY = doc.CreateAttribute("top");
            System.Xml.XmlAttribute locationX = doc.CreateAttribute("left");
            System.Xml.XmlAttribute collapsed = doc.CreateAttribute("collapsed");
            System.Xml.XmlAttribute type = doc.CreateAttribute("gadgetType");

            id.Value = this.UniqueIdentifier.ToString();
            locationY.Value = Canvas.GetTop(this).ToString("F0");
            locationX.Value = Canvas.GetLeft(this).ToString("F0");
            collapsed.Value = IsCollapsed.ToString(); //
            type.Value = "EpiDashboard.MeansControl";

            element.Attributes.Append(locationY);
            element.Attributes.Append(locationX);
            element.Attributes.Append(collapsed);
            element.Attributes.Append(type);
            element.Attributes.Append(id);

            return element;
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Used to generate the list of variables and options for the GadgetParameters object
        /// </summary>
        protected override void CreateInputVariableList()
        {
            this.DataFilters = RowFilterControl.DataFilters;

            Dictionary <string, string> inputVariableList = new Dictionary <string, string>();

            Parameters.ColumnNames = new List <string>();

            Parameters.SortVariables = new Dictionary <string, SortOrder>();

            Parameters.GadgetTitle       = txtTitle.Text;
            Parameters.GadgetDescription = txtDesc.Text;

            double height          = 5000;
            double width           = 0;
            int    maxrows         = 0;
            int    maxColumnLength = 0;

            bool success = double.TryParse(txtMaxWidth.Text, out width);

            if (success)
            {
                Parameters.Width = width;
            }

            success = int.TryParse(txtMaxRows.Text, out maxrows);
            if (success)
            {
                Parameters.MaxRows = maxrows;
            }

            List <string> listFields        = new List <string>();
            List <string> numerFilterFields = new List <string>();
            List <string> denomFilterFields = new List <string>();

            if (Parameters.NumerFilter != null)
            {
                foreach (System.Data.DataRow numerRow in Parameters.NumerFilter.ConditionTable.Rows)
                {
                    string[] fragments = (numerRow["filter"]).ToString().Split(new char[] { '[', ']' });
                    if (fragments.Length == 3)
                    {
                        numerFilterFields.Add(fragments[1]);
                    }
                }
            }

            if (Parameters.DenomFilter != null)
            {
                foreach (System.Data.DataRow denomRow in Parameters.DenomFilter.ConditionTable.Rows)
                {
                    string[] fragments = (denomRow["filter"]).ToString().Split(new char[] { '[', ']' });
                    if (fragments.Length == 3)
                    {
                        denomFilterFields.Add(fragments[1]);
                    }
                }
            }

            numerFilterFields.AddRange(denomFilterFields.ToList <string>());
            listFields = numerFilterFields;

            listFields.Sort();
            if ((Gadget as RatesControl).IsHostedByEnter)
            {
                if (listFields.Contains("UniqueKey"))
                {
                    listFields.Remove("UniqueKey");
                }

                listFields.Add("UniqueKey");
            }

            foreach (string field in listFields)
            {
                Parameters.ColumnNames.Add(field);
            }

            Parameters.NumerDistinct = checkBoxNumberatorDistinct.IsChecked.Value;
            Parameters.DenomDistinct = checkBoxDenominatorDistinct.IsChecked.Value;

            if (lbxSortOrder.Items.Count > 0)
            {
                foreach (string item in lbxSortOrder.Items)
                {
                    if (!string.IsNullOrEmpty(item))
                    {
                        string baseStr = item;

                        if (baseStr.EndsWith("(ascending)"))
                        {
                            baseStr = baseStr.Remove(baseStr.Length - 12);
                            Parameters.SortVariables.Add(baseStr, SortOrder.Ascending);
                        }
                        if (baseStr.EndsWith("(descending)"))
                        {
                            baseStr = baseStr.Remove(baseStr.Length - 13);
                            Parameters.SortVariables.Add(baseStr, SortOrder.Descending);
                        }
                    }
                }
            }

            if (string.IsNullOrWhiteSpace(cmbRateMultiplier.Text) == false)
            {
                Parameters.RateMultiplierString = cmbRateMultiplier.Text;
            }
            else
            {
                Parameters.RateMultiplierString = "100";
            }

            if (cmbNumeratorField.SelectedIndex >= 0)
            {
                if (cmbNumeratorField.SelectedItem is RatesProperties.FieldInfo)
                {
                    Parameters.NumeratorField = ((RatesProperties.FieldInfo)cmbNumeratorField.SelectedItem).Name;
                }
            }

            if (cmbDenominatorField.SelectedIndex >= 0)
            {
                if (cmbDenominatorField.SelectedItem is RatesProperties.FieldInfo)
                {
                    Parameters.DenominatorField = ((RatesProperties.FieldInfo)cmbDenominatorField.SelectedItem).Name;
                }
            }

            if (string.IsNullOrWhiteSpace(Parameters.DenominatorField) == false)
            {
                Parameters.ColumnNames.Add(Parameters.DenominatorField);
            }

            if (string.IsNullOrWhiteSpace(Parameters.DenominatorField) == false)
            {
                Parameters.ColumnNames.Add(Parameters.DenominatorField);
            }

            if (cmbSelectNumeratorAggregateFunction.SelectedIndex >= 0)
            {
                Parameters.NumeratorAggregator = (string)((AggFxInfo)(cmbSelectNumeratorAggregateFunction.SelectedItem)).Keyword;
            }

            if (cmbSelectDenominatorAggregateFunction.SelectedIndex >= 0)
            {
                Parameters.DenominatorAggregator = (string)((AggFxInfo)(cmbSelectDenominatorAggregateFunction.SelectedItem)).Keyword;
            }

            if (cmbGroupField.SelectedIndex >= 0)
            {
                Parameters.PrimaryGroupField = cmbGroupField.SelectedItem.ToString();
            }

            if (cmbSecondaryGroupField.SelectedIndex >= 0)
            {
                Parameters.SecondaryGroupField = cmbSecondaryGroupField.SelectedItem.ToString();
            }

            if (StrataGridList.Count >= 1)
            {
                Grid grid = StrataGridList[0];
                SortedDictionary <int, string> sortColumnDictionary = new SortedDictionary <int, string>();

                foreach (UIElement element in grid.Children)
                {
                    if (Grid.GetRow(element) == 0 && element is TextBlock)
                    {
                        TextBlock txtColumnName = element as TextBlock;
                        sortColumnDictionary.Add(Grid.GetColumn(element), txtColumnName.Text);
                    }
                }

                ColumnOrder = new List <string>();
                foreach (KeyValuePair <int, string> kvp in sortColumnDictionary)
                {
                    ColumnOrder.Add(kvp.Value);
                }

                if (ColumnOrder.Count == listFields.Count || ColumnOrder.Count == (listFields.Count + 1))
                {
                    bool same = true;
                    foreach (string s in listFields)
                    {
                        if (!ColumnOrder.Contains(s))
                        {
                            same = false;
                        }
                    }

                    if (same)
                    {
                        WordBuilder wb = new WordBuilder("^");
                        foreach (string s in ColumnOrder)
                        {
                            wb.Add(s);
                        }

                        inputVariableList.Add("customusercolumnsort", wb.ToString());
                    }
                    else
                    {
                        ColumnOrder = new List <string>();
                    }
                }
                else
                {
                    ColumnOrder = new List <string>();
                }
            }

            Parameters.InputVariableList = inputVariableList;

            Parameters.DefaultColor    = rctColorDefault.Fill.ToString();
            Parameters.UseDefaultColor = defaultColorOption.IsChecked == true;

            double doubleValue = -1;

            Parameters.Color_L1 = rctColor1.Fill.ToString();
            success             = double.TryParse(rampEnd01.Text, out doubleValue);
            if (success)
            {
                Parameters.HighValue_L1 = doubleValue;
            }

            Parameters.Color_L2 = rctColor2.Fill.ToString();
            success             = double.TryParse(rampStart02.Text, out doubleValue);
            if (success)
            {
                Parameters.LowValue_L2 = doubleValue;
            }
            success = double.TryParse(rampEnd02.Text, out doubleValue);
            if (success)
            {
                Parameters.HighValue_L2 = doubleValue;
            }

            Parameters.Color_L3 = rctColor3.Fill.ToString();
            success             = double.TryParse(rampStart03.Text, out doubleValue);
            if (success)
            {
                Parameters.LowValue_L3 = doubleValue;
            }
            success = double.TryParse(rampEnd03.Text, out doubleValue);
            if (success)
            {
                Parameters.HighValue_L3 = doubleValue;
            }

            Parameters.Color_L4 = rctColor4.Fill.ToString();
            success             = double.TryParse(rampStart04.Text, out doubleValue);
            if (success)
            {
                Parameters.LowValue_L4 = doubleValue;
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Begins the process of importing records from the data package into the destination form
        /// </summary>
        /// <param name="form">The form that will receive the data</param>
        /// <param name="formNode">The XmlNode representing the form</param>
        /// <param name="records">The data to be imported</param>
        protected virtual void ImportRecords(View form, XmlNode formNode, List<PackageFieldData> records)
        {
            ImportInfo.RecordsAppended.Add(form, 0);
            ImportInfo.RecordsUpdated.Add(form, 0);

            IDbDriver destinationDb = DestinationProject.CollectedData.GetDatabase();
            Dictionary<string, bool> destinationGuids = new Dictionary<string, bool>();
            Dictionary<string, int> destinationGuidsAndRecStatus = new Dictionary<string, int>();
            Dictionary<Dictionary<Field, object>, bool> destinationKeyValues = new Dictionary<Dictionary<Field, object>, bool>();

            using (IDataReader baseTableReader = destinationDb.GetTableDataReader(form.TableName))
            {
                while (baseTableReader.Read())
                {
                    string readerGuid = baseTableReader["GlobalRecordId"].ToString();
                    int readerRecStatus = 0;

                    bool success = Int32.TryParse(baseTableReader["RecStatus"].ToString(), out readerRecStatus);

                    destinationGuids.Add(readerGuid, true);
                    destinationGuidsAndRecStatus.Add(readerGuid, readerRecStatus);
                }
            }

            #region Custom Keys
            if (this.IsUsingCustomMatchkeys)
            {
                WordBuilder wb = new WordBuilder(",");
                foreach (Field field in KeyFields)
                {
                    wb.Add(field.Name);
                }

                Query selectQuery = destinationDb.CreateQuery("SELECT " + wb.ToString() + " " + form.FromViewSQL);
                using (IDataReader keyTableReader = destinationDb.ExecuteReader(selectQuery))
                {
                    while (keyTableReader.Read())
                    {
                        Dictionary<Field, object> keys = new Dictionary<Field, object>();

                        foreach (Field field in KeyFields)
                        {
                            keys.Add(field, keyTableReader[field.Name]);
                            //destinationKeyValues.Add(keyTableReader["GlobalRecordId"].ToString(), true);
                        }

                        destinationKeyValues.Add(keys, true);
                    }
                }
            }
            #endregion // Custom Keys

            foreach (XmlNode recordNode in formNode.SelectSingleNode("Data").ChildNodes)
            {
                if (recordNode.Name.Equals("record", StringComparison.OrdinalIgnoreCase))
                {
                    string guid = String.Empty;
                    string recStatus = String.Empty;
                    string fkey = String.Empty;
                    string firstSaveId = String.Empty;
                    string lastSaveId = String.Empty;
                    DateTime? firstSaveTime = null;
                    DateTime? lastSaveTime = null;

                    foreach (XmlAttribute attrib in recordNode.Attributes)
                    {
                        if (attrib.Name.Equals("id", StringComparison.OrdinalIgnoreCase)) guid = attrib.Value;
                        if (attrib.Name.Equals("recstatus", StringComparison.OrdinalIgnoreCase)) recStatus = attrib.Value;
                        if (attrib.Name.Equals("fkey", StringComparison.OrdinalIgnoreCase)) fkey = attrib.Value;
                        if (attrib.Name.Equals("firstsaveuserid", StringComparison.OrdinalIgnoreCase)) firstSaveId = attrib.Value;
                        if (attrib.Name.Equals("lastsaveuserid", StringComparison.OrdinalIgnoreCase)) lastSaveId = attrib.Value;
                        if (attrib.Name.Equals("firstsavetime", StringComparison.OrdinalIgnoreCase)) firstSaveTime = new DateTime(Convert.ToInt64(attrib.Value));
                        if (attrib.Name.Equals("lastsavetime", StringComparison.OrdinalIgnoreCase)) lastSaveTime = new DateTime(Convert.ToInt64(attrib.Value));
                    }

                    if (!destinationGuids.ContainsKey(guid))
                    {
                        if (Append)
                        {
                            destinationGuids.Add(guid, true);
                            CreateNewBlankRow(form, guid, fkey, recStatus, firstSaveId, lastSaveId, firstSaveTime, lastSaveTime);
                            ImportInfo.TotalRecordsAppended++;
                            ImportInfo.RecordsAppended[form]++;
                            ImportInfo.AddRecordIdAsAppended(form, guid);
                        }
                    }
                    else
                    {
                        if (!Update)
                        {
                            destinationGuids[guid] = false;
                        }
                        else
                        {
                            #region Record status update for deletions
                            // the destination recStatus doesn't match the one in the sync file. Now we need to do an update...
                            if (!String.IsNullOrEmpty(recStatus) && destinationGuidsAndRecStatus[guid].ToString() != recStatus)
                            {
                                // if the desired rec status is 0 (deleted) then try to change the target recstatus to this value
                                if (recStatus == "0")
                                {
                                    // but we only update rec status if the caller allowed it via the Delete property
                                    if (Delete)
                                    {
                                        // update RecStatus with DB query
                                        IDbDriver db = DestinationProject.CollectedData.GetDatabase();
                                        Query updateQuery = db.CreateQuery("UPDATE [" + form.TableName + "] SET [RecStatus] = @RecStatus WHERE [GlobalRecordId] = @GlobalRecordId");
                                        updateQuery.Parameters.Add(new QueryParameter("@RecStatus", DbType.Int32, Double.Parse(recStatus)));
                                        updateQuery.Parameters.Add(new QueryParameter("@GlobalRecordId", DbType.String, guid));
                                        db.ExecuteNonQuery(updateQuery);
                                    }

                                    // and regardless of the delete property's setting, we still add the record ID to the list of deleted records
                                    ImportInfo.AddRecordIdAsDeleted(form, guid);
                                }
                                else if (recStatus == "1")
                                {
                                    // now, the destination has a value of 0 and the sender has a value of 1, meaning the sender
                                    // is trying to UNDELETE the record for the receiver.

                                    // but only undelete if the caller said so via API
                                    if (Undelete)
                                    {
                                        IDbDriver db = DestinationProject.CollectedData.GetDatabase();
                                        Query updateQuery = db.CreateQuery("UPDATE [" + form.TableName + "] SET [RecStatus] = @RecStatus WHERE [GlobalRecordId] = @GlobalRecordId");
                                        updateQuery.Parameters.Add(new QueryParameter("@RecStatus", DbType.Int32, Double.Parse(recStatus)));
                                        updateQuery.Parameters.Add(new QueryParameter("@GlobalRecordId", DbType.String, guid));
                                        db.ExecuteNonQuery(updateQuery);
                                    }

                                    // regardless of whether we hit the DB, add the ID to the undelete list
                                    ImportInfo.AddRecordIdAsUndeleted(form, guid);
                                }
                            }
                            #endregion

                            ImportInfo.TotalRecordsUpdated++;
                            ImportInfo.RecordsUpdated[form]++;
                            ImportInfo.AddRecordIdAsUpdated(form, guid);
                        }
                    }
                }
            }

            ImportRecordsToPageTables(form, records, destinationGuids);
        }
Ejemplo n.º 14
0
        protected override bool CreateNewRow(IDbConnection conn, View form, XElement record, string guid, string fkey = "", string recStatus = "1", string firstSaveId = "", string lastSaveId = "", DateTime?firstSaveTime = null, DateTime?lastSaveTime = null)
        {
            SqlConnection connection = conn as SqlConnection;

            IDbDriver     db = Project.CollectedData.GetDatabase();
            StringBuilder sb = new StringBuilder();

            sb.Append(" insert into ");
            sb.Append(db.InsertInEscape(form.TableName));
            sb.Append(StringLiterals.SPACE);
            sb.Append(StringLiterals.SPACE);

            WordBuilder fields = new WordBuilder(",");

            fields.Append("[GlobalRecordId]");

            if (!String.IsNullOrEmpty(fkey))
            {
                fields.Append("[FKEY]");
            }
            if (!String.IsNullOrEmpty(recStatus))
            {
                fields.Append("[RecStatus]");
            }
            if (!String.IsNullOrEmpty(firstSaveId))
            {
                fields.Append("[FirstSaveLogonName]");
            }
            if (!String.IsNullOrEmpty(lastSaveId))
            {
                fields.Append("[LastSaveLogonName]");
            }
            if (firstSaveTime.HasValue)
            {
                firstSaveTime = new DateTime(firstSaveTime.Value.Year,
                                             firstSaveTime.Value.Month,
                                             firstSaveTime.Value.Day,
                                             firstSaveTime.Value.Hour,
                                             firstSaveTime.Value.Minute,
                                             firstSaveTime.Value.Second);
                fields.Append("[FirstSaveTime]");
            }
            if (lastSaveTime.HasValue)
            {
                lastSaveTime = new DateTime(lastSaveTime.Value.Year,
                                            lastSaveTime.Value.Month,
                                            lastSaveTime.Value.Day,
                                            lastSaveTime.Value.Hour,
                                            lastSaveTime.Value.Minute,
                                            lastSaveTime.Value.Second);
                fields.Append("[LastSaveTime]");
            }

            sb.Append("(" + fields.ToString() + ")");
            sb.Append(" values (");

            List <QueryParameter> parameters = new List <QueryParameter>();
            WordBuilder           values     = new WordBuilder(",");

            values.Append("'" + guid + "'");

            if (!String.IsNullOrEmpty(fkey))
            {
                values.Append("@FKEY");
                parameters.Add(new QueryParameter("@FKEY", DbType.String, fkey));
            }
            if (!String.IsNullOrEmpty(recStatus))
            {
                values.Append("@RecStatus");
                parameters.Add(new QueryParameter("@RecStatus", DbType.Int32, Convert.ToInt32(recStatus)));
            }
            if (!String.IsNullOrEmpty(firstSaveId))
            {
                values.Append("@FirstSaveLogonName");
                parameters.Add(new QueryParameter("@FirstSaveLogonName", DbType.String, firstSaveId));
            }
            if (!String.IsNullOrEmpty(lastSaveId))
            {
                values.Append("@LastSaveLogonName");
                parameters.Add(new QueryParameter("@LastSaveLogonName", DbType.String, lastSaveId));
            }
            if (firstSaveTime.HasValue)
            {
                values.Append("@FirstSaveTime");
                parameters.Add(new QueryParameter("@FirstSaveTime", DbType.DateTime, firstSaveTime));
            }
            if (lastSaveTime.HasValue)
            {
                values.Append("@LastSaveTime");
                parameters.Add(new QueryParameter("@LastSaveTime", DbType.DateTime, lastSaveTime));
            }

            sb.Append(values.ToString());
            sb.Append(") ");
            Epi.Data.Query insertQuery = db.CreateQuery(sb.ToString());
            insertQuery.Parameters = parameters;

            using (SqlTransaction transaction = connection.BeginTransaction("SampleTransaction"))
            {
                try
                {
                    using (IDbCommand baseTableCommand = GetCommand(insertQuery.SqlStatement, conn, insertQuery.Parameters))
                    {
                        baseTableCommand.Transaction = transaction;
                        object baseObj = baseTableCommand.ExecuteNonQuery();
                    }

                    //foreach (Page page in form.Pages)
                    //{
                    //    sb = new StringBuilder();
                    //    sb.Append(" insert into ");
                    //    sb.Append(db.InsertInEscape(page.TableName));
                    //    sb.Append(StringLiterals.SPACE);
                    //    sb.Append(StringLiterals.SPACE);
                    //    sb.Append("([GlobalRecordId])");
                    //    sb.Append(" values (");
                    //    sb.Append("'" + guid + "'");
                    //    sb.Append(") ");
                    //    insertQuery = db.CreateQuery(sb.ToString());

                    //    using (IDbCommand pageTableCommand = GetCommand(insertQuery.SqlStatement, conn, insertQuery.Parameters))
                    //    {
                    //        pageTableCommand.Transaction = transaction;
                    //        object pageObj = pageTableCommand.ExecuteNonQuery();
                    //    }
                    //}

                    foreach (Page page in form.Pages)
                    {
                        WordBuilder           wbFieldNames         = new WordBuilder(", ");
                        WordBuilder           wbParamNames         = new WordBuilder(", ");
                        List <QueryParameter> pageInsertParameters = new List <QueryParameter>();

                        foreach (RenderableField field in page.Fields)
                        {
                            if (field is IDataField && record.Element(field.Name) != null)
                            {
                                wbFieldNames.Add(field.Name);
                                wbParamNames.Add("@" + field.Name);

                                pageInsertParameters.Add(
                                    GetQueryParameterForField(field,
                                                              FormatFieldData(form, field.Name, record.Element(field.Name).Value),
                                                              form,
                                                              page));
                            }
                        }

                        wbFieldNames.Add("GlobalRecordId");
                        wbParamNames.Add("@GlobalRecordId");
                        pageInsertParameters.Add(new QueryParameter("@GlobalRecordId", DbType.String, guid));

                        Query inserteQuery = db.CreateQuery("INSERT INTO " + page.TableName + " (" + wbFieldNames.ToString() + ") VALUES (" + wbParamNames.ToString() + ")");

                        foreach (QueryParameter parameter in pageInsertParameters)
                        {
                            inserteQuery.Parameters.Add(parameter);
                        }

                        using (IDbCommand pageTableCommand = GetCommand(inserteQuery.SqlStatement, conn, inserteQuery.Parameters))
                        {
                            pageTableCommand.Transaction = transaction;
                            object obj = pageTableCommand.ExecuteNonQuery();
                        }
                    }

                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    Epi.Logger.Log(String.Format(DateTime.Now + ":  " + "Commit Exception Type: {0}", ex.GetType()));
                    Epi.Logger.Log(String.Format(DateTime.Now + ":  " + "Commit Exception Message: {0}", ex.Message));

                    try
                    {
                        transaction.Rollback();
                    }
                    catch (Exception ex2)
                    {
                        Epi.Logger.Log(String.Format(DateTime.Now + ":  " + "Rollback Exception Type: {0}", ex2.GetType()));
                        Epi.Logger.Log(String.Format(DateTime.Now + ":  " + "Rollback Exception Message: {0}", ex2.Message));
                    }

                    return(false);
                }
            }

            return(true);
        }
        /// <summary>
        /// Creates a new blank row for a given form's base table and all of its page tables.
        /// </summary>
        /// <param name="form">The form where the row should be added.</param>
        /// <param name="guid">The Guid value to use for the row.</param>
        /// <param name="keyValues">The key values to use for custom matching</param>
        /// <param name="fkey">The foreign key for the row.</param>
        /// <param name="firstSaveId">The user ID of the first person that saved this record.</param>
        /// <param name="firstSaveTime">The time when the record was first saved.</param>
        /// <param name="lastSaveId">The user ID of the last person that saved this record.</param>
        /// <param name="lastSaveTime">The time when the record was last saved.</param>
        protected virtual void CreateNewBlankRow(View form, string guid, Dictionary <Field, object> keyValues = null, string fkey = "", string firstSaveId = "", string lastSaveId = "", DateTime?firstSaveTime = null, DateTime?lastSaveTime = null)
        {
            #region Input Validation
            if (string.IsNullOrEmpty(guid))
            {
                throw new ArgumentNullException("guid");
            }
            if (form == null)
            {
                throw new ArgumentNullException("form");
            }
            #endregion // Input Validation

            if (Conn.State != ConnectionState.Open)
            {
                Conn.Open();
            }

            IDbDriver     db = DestinationProject.CollectedData.GetDatabase();
            StringBuilder sb = new StringBuilder();
            sb.Append(" insert into ");
            sb.Append(db.InsertInEscape(form.TableName));
            sb.Append(StringLiterals.SPACE);
            sb.Append(StringLiterals.SPACE);

            WordBuilder fields = new WordBuilder(",");
            fields.Append("[GlobalRecordId]");

            if (!string.IsNullOrEmpty(fkey))
            {
                fields.Append("[FKEY]");
            }
            if (!string.IsNullOrEmpty(firstSaveId))
            {
                fields.Append("[FirstSaveLogonName]");
            }
            if (!string.IsNullOrEmpty(lastSaveId))
            {
                fields.Append("[LastSaveLogonName]");
            }
            if (firstSaveTime.HasValue)
            {
                fields.Append("[FirstSaveTime]");
            }
            if (lastSaveTime.HasValue)
            {
                fields.Append("[LastSaveTime]");
            }

            sb.Append("(" + fields.ToString() + ")");
            sb.Append(" values (");

            List <QueryParameter> parameters = new List <QueryParameter>();
            WordBuilder           values     = new WordBuilder(",");
            values.Append("'" + guid + "'");

            if (!string.IsNullOrEmpty(fkey))
            {
                values.Append("@FKEY");
                parameters.Add(new QueryParameter("@FKEY", DbType.String, fkey));
            }
            if (!string.IsNullOrEmpty(firstSaveId))
            {
                values.Append("@FirstSaveLogonName");
                parameters.Add(new QueryParameter("@FirstSaveLogonName", DbType.String, firstSaveId));
            }
            if (!string.IsNullOrEmpty(lastSaveId))
            {
                values.Append("@LastSaveLogonName");
                parameters.Add(new QueryParameter("@LastSaveLogonName", DbType.String, lastSaveId));
            }
            if (firstSaveTime.HasValue)
            {
                values.Append("@FirstSaveTime");
                parameters.Add(new QueryParameter("@FirstSaveTime", DbType.DateTime, firstSaveTime));
            }
            if (lastSaveTime.HasValue)
            {
                values.Append("@LastSaveTime");
                parameters.Add(new QueryParameter("@LastSaveTime", DbType.DateTime, lastSaveTime));
            }

            sb.Append(values.ToString());
            sb.Append(") ");
            Epi.Data.Query insertQuery = db.CreateQuery(sb.ToString());
            insertQuery.Parameters = parameters;

            if (DestinationProject.CollectedDataDriver.ToLowerInvariant().Contains("epi.data.office"))
            {
                IDbCommand command = GetCommand(insertQuery.SqlStatement, Conn, insertQuery.Parameters);
                object     obj     = command.ExecuteNonQuery();
            }
            else
            {
                db.ExecuteNonQuery(insertQuery);
            }

            //Parallel.ForEach(form.Pages, page =>
            foreach (Page page in form.Pages)
            {
                WordBuilder           wbFields    = new WordBuilder(",");
                WordBuilder           wbParams    = new WordBuilder(",");
                List <QueryParameter> queryParams = new List <QueryParameter>();

                wbFields.Add("[GlobalRecordId]");
                wbParams.Add("@GlobalRecordId");
                queryParams.Add(new QueryParameter("@GlobalRecordId", DbType.String, guid));

                foreach (KeyValuePair <Field, object> kvp in keyValues)
                {
                    RenderableField field = kvp.Key as RenderableField;

                    PackageFieldData fieldData = new PackageFieldData();
                    fieldData.FieldValue = kvp.Value;
                    fieldData.FieldName  = field.Name;
                    fieldData.Page       = field.Page;

                    if (field.Page.TableName.Equals(page.TableName))
                    {
                        wbFields.Add(db.InsertInEscape(fieldData.FieldName));
                        wbParams.Add("@" + fieldData.FieldName);

                        QueryParameter parameter = GetQueryParameterForField(fieldData, form, field.Page);
                        queryParams.Add(parameter);
                    }
                }
                sb = new StringBuilder();
                sb.Append(" insert into ");
                sb.Append(db.InsertInEscape(page.TableName));
                sb.Append(StringLiterals.SPACE);
                sb.Append(StringLiterals.SPACE);
                sb.Append("(");
                sb.Append(wbFields.ToString());
                sb.Append(")");
                sb.Append(" values (");
                sb.Append(wbParams.ToString());
                sb.Append(") ");
                insertQuery = db.CreateQuery(sb.ToString());

                foreach (QueryParameter queryParam in queryParams)
                {
                    insertQuery.Parameters.Add(queryParam);
                }

                if (DestinationProject.CollectedDataDriver.ToLowerInvariant().Contains("epi.data.office"))
                {
                    IDbCommand command = GetCommand(insertQuery.SqlStatement, Conn, insertQuery.Parameters);
                    object     obj     = command.ExecuteNonQuery();
                }
                else
                {
                    db.ExecuteNonQuery(insertQuery);
                }
            }
            //);
        }
        /// <summary>
        /// Begins the process of importing records from the data package into the destination form
        /// </summary>
        /// <param name="form">The form that will receive the data</param>
        /// <param name="formNode">The XmlNode representing the form</param>
        /// <param name="records">The data to be imported</param>
        protected override void ImportRecords(View form, XmlNode formNode, List <PackageFieldData> records)
        {
            if (!IsUsingCustomMatchkeys) // Calling class should instantiate normal data packager if custom keys aren't used
            {
                throw new ApplicationException("This class should not be used without custom match keys.");
            }

            ImportInfo.RecordsAppended.Add(form, 0);
            ImportInfo.RecordsUpdated.Add(form, 0);

            IDbDriver destinationDb = DestinationProject.CollectedData.GetDatabase();

            DataTable destinationKeyTable = new DataTable();

            destinationKeyTable.Columns.Add(new DataColumn("GlobalRecordId", typeof(string)));
            destinationKeyTable.Columns.Add(new DataColumn("Update", typeof(bool)));
            destinationKeyTable.Columns.Add(new DataColumn("KeyDictionary", typeof(Dictionary <Field, object>)));

            DataColumn [] primaryKey = new DataColumn[1];
            primaryKey[0] = destinationKeyTable.Columns["GlobalRecordId"];
            destinationKeyTable.PrimaryKey = primaryKey;

            WordBuilder wb = new WordBuilder(",");

            wb.Add("t.GlobalRecordId");
            foreach (Field field in KeyFields)
            {
                wb.Add(field.Name);
            }

            Query selectQuery = destinationDb.CreateQuery("SELECT " + wb.ToString() + " " + form.FromViewSQL);

            using (IDataReader keyTableReader = destinationDb.ExecuteReader(selectQuery))
            {
                while (keyTableReader.Read())
                {
                    string guid = keyTableReader["GlobalRecordId"].ToString();
                    Dictionary <Field, object> keys = new Dictionary <Field, object>();

                    foreach (Field field in KeyFields)
                    {
                        keys.Add(field, keyTableReader[field.Name]);
                    }

                    destinationKeyTable.Rows.Add(guid, true, keys);
                }
            }

            var query = from record in records
                        group record by record.RecordGUID;

            IEnumerable <IEnumerable <PackageFieldData> > fieldDataLists = query as IEnumerable <IEnumerable <PackageFieldData> >;

            foreach (IEnumerable <PackageFieldData> fieldDataList in fieldDataLists)
            {
                PackageFieldData fieldData = fieldDataList.First();
                bool             found     = false;

                foreach (DataRow row in destinationKeyTable.Rows)
                {
                    Dictionary <Field, object> keyDictionary = row["KeyDictionary"] as Dictionary <Field, object>;

                    if (AreKeyFieldDictionariesEqual(keyDictionary, fieldData.KeyValues))
                    {
                        found = true;
                        if (!Update)
                        {
                            row["Update"] = false;
                        }
                        else
                        {
                            ImportInfo.TotalRecordsUpdated++;
                            ImportInfo.RecordsUpdated[form]++;
                        }
                    }
                }

                if (!found && Append) // no match, this is a new record that must be inserted
                {
                    CreateNewBlankRow(form, fieldData.RecordGUID, fieldData.KeyValues);
                    ImportInfo.TotalRecordsAppended++;
                    ImportInfo.RecordsAppended[form]++;
                }
            }

            System.Threading.Thread.Sleep(2000); // give time for DB to update

            destinationKeyTable.Clear();
            selectQuery = destinationDb.CreateQuery("SELECT " + wb.ToString() + " " + form.FromViewSQL);
            using (IDataReader keyTableReader = destinationDb.ExecuteReader(selectQuery))
            {
                while (keyTableReader.Read())
                {
                    string guid = keyTableReader["GlobalRecordId"].ToString();
                    Dictionary <Field, object> keys = new Dictionary <Field, object>();

                    foreach (Field field in KeyFields)
                    {
                        keys.Add(field, keyTableReader[field.Name]);
                    }

                    destinationKeyTable.Rows.Add(guid, true, keys);
                }
            }

            //Parallel.ForEach(records, rec =>

            // TODO: Make this faster (note that Parallel foreach seems to make it worse)
            foreach (PackageFieldData rec in records)
            {
                bool   found        = false;
                string targetGuid   = String.Empty;
                bool   shouldUpdate = true;

                foreach (DataRow row in destinationKeyTable.Rows)
                {
                    Dictionary <Field, object> keyDictionary = row["KeyDictionary"] as Dictionary <Field, object>;

                    if (AreKeyFieldDictionariesEqual(keyDictionary, rec.KeyValues))
                    {
                        found        = true;
                        targetGuid   = row["GlobalRecordId"].ToString();
                        shouldUpdate = (bool)row["Update"];
                        break;
                    }
                }

                if (shouldUpdate && found && !String.IsNullOrEmpty(targetGuid) && rec.FieldValue != null && !String.IsNullOrEmpty(rec.FieldValue.ToString()))
                {
                    Query updateQuery = destinationDb.CreateQuery("UPDATE " + rec.Page.TableName + " SET " +
                                                                  "[" + rec.FieldName + "] = @" + rec.FieldName + " WHERE [GlobalRecordId] = @GlobalRecordId");

                    QueryParameter fieldParam = GetQueryParameterForField(rec, form, rec.Page);

                    if (fieldParam != null)
                    {
                        updateQuery.Parameters.Add(fieldParam);
                        updateQuery.Parameters.Add(new QueryParameter("@GlobalRecordId", DbType.String, targetGuid));
                        int rowsAffected = destinationDb.ExecuteNonQuery(updateQuery);

                        if (rowsAffected == 0)
                        {
                            throw new ApplicationException("No records affected.");
                        }
                        else if (rowsAffected > 1)
                        {
                            throw new ApplicationException("Too many records affected.");
                        }
                    }
                }
            }
            //);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Used to generate the list of variables and options for the GadgetParameters object
        /// </summary>
        protected override void CreateInputVariableList()
        {
            // Set data filters!
            this.DataFilters = RowFilterControl.DataFilters;

            Dictionary <string, string> inputVariableList = new Dictionary <string, string>();

            Parameters.ColumnNames = new List <string>();

            Parameters.SortVariables = new Dictionary <string, SortOrder>();

            Parameters.GadgetTitle       = txtTitle.Text;
            Parameters.GadgetDescription = txtDesc.Text;

            double height          = 0;
            double width           = 0;
            int    maxrows         = 0;
            int    maxColumnLength = 0;

            bool success = double.TryParse(txtMaxHeight.Text, out height);

            if (success)
            {
                Parameters.Height = height;
            }

            success = double.TryParse(txtMaxWidth.Text, out width);
            if (success)
            {
                Parameters.Width = width;
            }

            success = int.TryParse(txtMaxVarNameLength.Text, out maxColumnLength);
            if (success)
            {
                if (maxColumnLength > 64)
                {
                    maxColumnLength = 64;
                }
                Parameters.MaxColumnLength = maxColumnLength;
            }

            success = int.TryParse(txtMaxRows.Text, out maxrows);
            if (success)
            {
                Parameters.MaxRows = maxrows;
            }

            List <string> listFields = new List <string>();

            if (lvVariables.SelectedItems.Count > 0)
            {
                foreach (FieldInfo fieldInfo in lvVariables.SelectedItems)
                {
                    if (!string.IsNullOrEmpty(fieldInfo.Name))
                    {
                        listFields.Add(fieldInfo.Name);
                    }
                }
            }

            listFields.Sort();
            if ((Gadget as LineListControl).IsHostedByEnter)
            {
                //if (dashboardHelper.IsUsingEpiProject && checkboxAllowUpdates.IsChecked == true)
                //{
                if (listFields.Contains("UniqueKey"))
                {
                    listFields.Remove("UniqueKey");
                }
                listFields.Add("UniqueKey");
                //}
            }

            foreach (string field in listFields)
            {
                Parameters.ColumnNames.Add(field);
            }

            Parameters.SortColumnsByTabOrder    = checkboxTabOrder.IsChecked.Value;
            Parameters.UsePromptsForColumnNames = checkboxUsePrompts.IsChecked.Value;
            Parameters.ShowColumnHeadings       = checkboxColumnHeaders.IsChecked.Value;
            Parameters.ShowLineColumn           = checkboxLineColumn.IsChecked.Value;
            Parameters.ShowNullLabels           = checkboxShowNulls.IsChecked.Value;
            Parameters.ShowCommentLegalLabels   = checkboxListLabels.IsChecked.Value;

            if (checkboxUsePrompts.IsChecked == true)
            {
                inputVariableList.Add("usepromptsforcolumnnames", "true");
            }
            else
            {
                inputVariableList.Add("usepromptsforcolumnnames", "false");
            }

            if (lbxSortOrder.Items.Count > 0)
            {
                foreach (string item in lbxSortOrder.Items)
                {
                    if (!string.IsNullOrEmpty(item))
                    {
                        //string baseStr = item;

                        //if (baseStr.EndsWith("(ascending)"))
                        //{
                        //    baseStr = "[" + baseStr.Remove(baseStr.Length - 12) + "] ASC";
                        //}
                        //if (baseStr.EndsWith("(descending)"))
                        //{
                        //    baseStr = "[" + baseStr.Remove(baseStr.Length - 13) + "] DESC";
                        //}
                        //inputVariableList.Add(baseStr, "sortfield");

                        string baseStr = item;

                        if (baseStr.EndsWith("(ascending)"))
                        {
                            baseStr = baseStr.Remove(baseStr.Length - 12);
                            Parameters.SortVariables.Add(baseStr, SortOrder.Ascending);
                        }
                        if (baseStr.EndsWith("(descending)"))
                        {
                            baseStr = baseStr.Remove(baseStr.Length - 13);
                            Parameters.SortVariables.Add(baseStr, SortOrder.Descending);
                        }
                    }
                }
            }

            if (cmbGroupField.SelectedIndex >= 0)
            {
                Parameters.PrimaryGroupField = cmbGroupField.SelectedItem.ToString();
            }

            if (cmbSecondaryGroupField.SelectedIndex >= 0)
            {
                Parameters.SecondaryGroupField = cmbSecondaryGroupField.SelectedItem.ToString();
            }

            if (StrataGridList.Count >= 1)
            {
                Grid grid = StrataGridList[0];
                SortedDictionary <int, string> sortColumnDictionary = new SortedDictionary <int, string>();

                foreach (UIElement element in grid.Children)
                {
                    if (Grid.GetRow(element) == 0 && element is TextBlock)
                    {
                        TextBlock txtColumnName = element as TextBlock;
                        //columnOrder.Add(txtColumnName.Text);
                        sortColumnDictionary.Add(Grid.GetColumn(element), txtColumnName.Text);
                    }
                }

                ColumnOrder = new List <string>();
                foreach (KeyValuePair <int, string> kvp in sortColumnDictionary)
                {
                    ColumnOrder.Add(kvp.Value);
                }

                if (ColumnOrder.Count == listFields.Count || ColumnOrder.Count == (listFields.Count + 1))
                {
                    bool same = true;
                    foreach (string s in listFields)
                    {
                        if (!ColumnOrder.Contains(s))
                        {
                            same = false;
                        }
                    }

                    if (same)
                    {
                        WordBuilder wb = new WordBuilder("^");
                        foreach (string s in ColumnOrder)
                        {
                            wb.Add(s);
                        }

                        inputVariableList.Add("customusercolumnsort", wb.ToString());
                    }
                    else
                    {
                        ColumnOrder = new List <string>();
                    }
                }
                else
                {
                    ColumnOrder = new List <string>();
                }
            }

            Parameters.InputVariableList = inputVariableList;
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Converts the gadget's output to Html
        /// </summary>
        /// <returns></returns>
        public override string ToHTML(string htmlFileName = "", int count = 0)
        {
            if (IsCollapsed) return string.Empty;

            StringBuilder htmlBuilder = new StringBuilder();
            CustomOutputHeading = headerPanel.Text;
            CustomOutputDescription = descriptionPanel.Text;

            if (CustomOutputHeading == null || (string.IsNullOrEmpty(CustomOutputHeading) && !CustomOutputHeading.Equals("(none)")))
            {
                htmlBuilder.AppendLine("<h2 class=\"gadgetHeading\">Means</h2>");
            }
            else if (CustomOutputHeading != "(none)")
            {
                htmlBuilder.AppendLine("<h2 class=\"gadgetHeading\">" + CustomOutputHeading + "</h2>");
            }

            htmlBuilder.AppendLine("<p class=\"gadgetOptions\"><small>");
            htmlBuilder.AppendLine("<em>Main variable:</em> <strong>" + cbxField.Text + "</strong>");
            htmlBuilder.AppendLine("<br />");

            if (cbxFieldCrosstab.SelectedIndex >= 0)
            {
                htmlBuilder.AppendLine("<em>Crosstab variable:</em> <strong>" + cbxFieldCrosstab.Text + "</strong>");
                htmlBuilder.AppendLine("<br />");
            }

            if (cbxFieldWeight.SelectedIndex >= 0)
            {
                htmlBuilder.AppendLine("<em>Weight variable:</em> <strong>" + cbxFieldWeight.Text + "</strong>");
                htmlBuilder.AppendLine("<br />");
            }
            //if (cbxFieldStrata.SelectedIndex >= 0)
            //{
            //    htmlBuilder.AppendLine("<em>Strata variable:</em> <strong>" + cbxFieldStrata.Text + "</strong>");
            //    htmlBuilder.AppendLine("<br />");
            //}
            if (lbxFieldStrata.SelectedItems.Count > 0)
            {
                WordBuilder wb = new WordBuilder(", ");
                foreach (string s in lbxFieldStrata.SelectedItems)
                {
                    wb.Add(s);
                }
                htmlBuilder.AppendLine("<em>Strata variable(s):</em> <strong>" + wb.ToString() + "</strong>");
                htmlBuilder.AppendLine("<br />");
            }

            htmlBuilder.AppendLine("</small></p>");

            if (!string.IsNullOrEmpty(CustomOutputDescription))
            {
                htmlBuilder.AppendLine("<p class=\"gadgetsummary\">" + CustomOutputDescription + "</p>");
            }

            if (!string.IsNullOrEmpty(messagePanel.Text) && messagePanel.Visibility == Visibility.Visible)
            {
                htmlBuilder.AppendLine("<p><small><strong>" + messagePanel.Text + "</strong></small></p>");
            }

            if (!string.IsNullOrEmpty(infoPanel.Text) && infoPanel.Visibility == Visibility.Visible)
            {
                htmlBuilder.AppendLine("<p><small><strong>" + infoPanel.Text + "</strong></small></p>");
            }

            // Each grid in the 'strataGridList' has a tag associated with it which tells us which strata
            // that grid is for. For example, if we stratify by 'Sex' in the Oswego table (in Sample.prj)
            // we will have two grids in strataGridList, one for males and one for females. The tags will
            // be 'Sex = Male' and 'Sex = Female', respectively.
            foreach (Grid grid in this.StrataGridList)
            {
                string gridName = grid.Tag.ToString();

                string summaryText = "This tables contains several descriptive statistics for the field " + cbxField.Text + ". ";
                if (!string.IsNullOrEmpty(cbxFieldWeight.Text)) { summaryText += "The field " + cbxFieldWeight.Text + " has been specified as a weight. "; }
                if (lbxFieldStrata.SelectedItems.Count > 0) { summaryText += "The data has been stratified. The data in this table is for the strata value " + grid.Tag.ToString() + ". "; }
                if (!string.IsNullOrEmpty(cbxFieldCrosstab.Text)) { summaryText += "The data has been cross-tabulated; there will be one data row for each value of " + cbxFieldCrosstab.Text + ". "; }
                summaryText += "The column headings are: The description of the data, the total number of observations, the sum of the observations, the mean, the variance, the standard deviation, the minimum observed value, the 25% value, the median value, the 75% value, the maximum, and the mode.";

                htmlBuilder.AppendLine("<div style=\"height: 7px;\"></div>");
                htmlBuilder.AppendLine("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" summary=\"" + summaryText + "\">");
                htmlBuilder.AppendLine("<caption>" + gridName + "</caption>");

                for (int i = 0; i < grid.RowDefinitions.Count; i++)
                {
                    for (int j = 0; j < grid.ColumnDefinitions.Count; j++)
                    {
                        string tableDataTagOpen = "<td>";
                        string tableDataTagClose = "</td>";

                        if (i == 0)
                        {
                            tableDataTagOpen = "<th>";
                            tableDataTagClose = "</th>";
                        }

                        if (j == 0)
                        {
                            htmlBuilder.AppendLine("<tr>");
                        }
                        if (j == 0 && i > 0)
                        {
                            tableDataTagOpen = "<td class=\"value\">";
                        }

                        ColumnDefinition colDef = grid.ColumnDefinitions[j];
                        if (colDef.Width.Value > 0)
                        {
                            IEnumerable<UIElement> elements = grid.Children.Cast<UIElement>().Where(x => Grid.GetRow(x) == i && Grid.GetColumn(x) == j);
                            TextBlock txt = null;
                            foreach (UIElement element in elements)
                            {
                                if (element is TextBlock)
                                {
                                    txt = element as TextBlock;
                                }
                            }
                            string value = "&nbsp;";

                            if (txt != null)
                            {
                                value = txt.Text;
                            }

                            htmlBuilder.AppendLine(tableDataTagOpen + value + tableDataTagClose);
                        }

                        if (j >= grid.ColumnDefinitions.Count - 1)
                        {
                            htmlBuilder.AppendLine("</tr>");
                        }
                    }
                }

                htmlBuilder.AppendLine("</table>");

                // We must find the specific stack panel that corresponds to this strata value from the list of
                // ANOVA panels in the gadget. The 'tag' property of the panel is a key value pair that contains
                // the strata value we need, plus the set of descriptive statistics that we must display in the
                // output.
                StackPanel anovaPanel = null;
                DescriptiveStatistics statistics = new DescriptiveStatistics();
                foreach (StackPanel panel in anovaBlocks)
                {
                    if(panel.Tag is KeyValuePair<string, DescriptiveStatistics>)
                    {
                        KeyValuePair<string, DescriptiveStatistics> kvp = ((KeyValuePair<string, DescriptiveStatistics>)panel.Tag);
                        if (kvp.Key.Equals(gridName))
                        {
                            anovaPanel = panel;
                            statistics = kvp.Value;
                            break; // no sense in continuning
                        }
                    }
                }

                // check to make sure we actually found one
                if (!(anovaPanel == null))
                {
                    string strssBetweenValue = SharedStrings.UNDEFINED;
                    string strdfBetweenValue = SharedStrings.UNDEFINED;
                    string strmsBetweenValue = SharedStrings.UNDEFINED;
                    string strssWithinValue = SharedStrings.UNDEFINED;
                    string strdfWithinValue = SharedStrings.UNDEFINED;
                    string strmsWithinValue = SharedStrings.UNDEFINED;
                    string strfStatisticValue = SharedStrings.UNDEFINED;
                    string stranovaPValueValue = SharedStrings.UNDEFINED;
                    string stranovaTValueValue = SharedStrings.UNDEFINED;
                    string strchiSquareValue = SharedStrings.UNDEFINED;
                    string strbartlettPValue = SharedStrings.UNDEFINED;
                    string strTotalSSValue = SharedStrings.UNDEFINED;
                    string strTotalDFValue = SharedStrings.UNDEFINED;
                    string strKruskalWallisH = SharedStrings.UNDEFINED;
                    string strKruskalPValue = SharedStrings.UNDEFINED;

                    if (statistics.ssBetween.HasValue) { strssBetweenValue = statistics.ssBetween.Value.ToString("F4"); }
                    if (statistics.dfBetween.HasValue) { strdfBetweenValue = statistics.dfBetween.Value.ToString("F0"); }
                    if (statistics.msBetween.HasValue) { strmsBetweenValue = statistics.msBetween.Value.ToString("F4"); }
                    if (statistics.ssWithin.HasValue) { strssWithinValue = statistics.ssWithin.Value.ToString("F4"); }
                    if (statistics.dfWithin.HasValue) { strdfWithinValue = statistics.dfWithin.Value.ToString("F0"); }
                    if (statistics.msWithin.HasValue) { strmsWithinValue = statistics.msWithin.Value.ToString("F4"); }
                    if (statistics.fStatistic.HasValue) { strfStatisticValue = statistics.fStatistic.Value.ToString("F4"); }
                    if (statistics.anovaPValue.HasValue) { stranovaPValueValue = statistics.anovaPValue.Value.ToString("F4"); }
                    if (statistics.chiSquare.HasValue) { strchiSquareValue = statistics.chiSquare.Value.ToString("F4"); }
                    if (statistics.bartlettPValue.HasValue) { strbartlettPValue = statistics.bartlettPValue.Value.ToString("F4"); }

                    if (statistics.ssBetween.HasValue && statistics.ssWithin.HasValue) { strTotalSSValue = (statistics.ssBetween.Value + statistics.ssWithin.Value).ToString("F4"); }
                    if (statistics.dfBetween.HasValue && statistics.dfWithin.HasValue) { strTotalDFValue = (statistics.dfBetween.Value + statistics.dfWithin.Value).ToString("F0"); }
                    if (statistics.kruskalWallisH.HasValue) { strKruskalWallisH = statistics.kruskalWallisH.Value.ToString("F4"); }
                    if (statistics.kruskalPValue.HasValue) { strKruskalPValue = statistics.kruskalPValue.Value.ToString("F4"); }

                    summaryText = "This table contains analysis of variance (ANOVA) statistics for the field " + cbxField.Text + ", cross-tabulated by " + cbxFieldCrosstab.Text + ". ";
                    summaryText += "The column headings for this table are: The variation, the SS value, the degrees of freedom, the MS value, and the F-statistic. There are three rows: The between, the within, and the total.";

                    // ANOVA
                    htmlBuilder.AppendLine("<div style=\"height: 7px;\"></div>");
                    htmlBuilder.AppendLine("<p><strong>" + SharedStrings.ANOVA_DESCRIPTION_FOR_MEANS + "</strong><br />");
                    htmlBuilder.AppendLine("<small>" + SharedStrings.ANOVA_DESCRIPTION_FOR_MEANS_SUBTITLE + "</small></p>");
                    htmlBuilder.AppendLine("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" summary=\"" + summaryText + "\">");
                    htmlBuilder.AppendLine(" <tr>");
                    htmlBuilder.AppendLine("   <th>Variation</th>");
                    htmlBuilder.AppendLine("   <th>SS</th>");
                    htmlBuilder.AppendLine("   <th>df</th>");
                    htmlBuilder.AppendLine("   <th>MS</th>");
                    htmlBuilder.AppendLine("   <th>F statistic</th>");
                    htmlBuilder.AppendLine(" </tr>");

                    htmlBuilder.AppendLine(" <tr>");
                    htmlBuilder.AppendLine("   <th>Between</th>");
                    htmlBuilder.AppendLine("   <td>" + strssBetweenValue + "</td>");
                    htmlBuilder.AppendLine("   <td>" + strdfBetweenValue + "</td>");
                    htmlBuilder.AppendLine("   <td>" + strmsBetweenValue + "</td>");
                    htmlBuilder.AppendLine("   <td>" + strfStatisticValue + "</td>");
                    htmlBuilder.AppendLine(" </tr>");

                    htmlBuilder.AppendLine(" <tr>");
                    htmlBuilder.AppendLine("   <th>Within</th>");
                    htmlBuilder.AppendLine("   <td>" + strssWithinValue + "</td>");
                    htmlBuilder.AppendLine("   <td>" + strdfWithinValue + "</td>");
                    htmlBuilder.AppendLine("   <td>" + strmsWithinValue + "</td>");
                    htmlBuilder.AppendLine("   <td>&nbsp;</td>");
                    htmlBuilder.AppendLine(" </tr>");

                    htmlBuilder.AppendLine(" <tr>");
                    htmlBuilder.AppendLine("   <th>Total</th>");
                    htmlBuilder.AppendLine("   <td>" + strTotalSSValue + "</td>");
                    htmlBuilder.AppendLine("   <td>" + strTotalDFValue + "</td>");
                    htmlBuilder.AppendLine("   <td>&nbsp;</td>");
                    htmlBuilder.AppendLine("   <td>&nbsp;</td>");
                    htmlBuilder.AppendLine(" </tr>");
                    htmlBuilder.AppendLine("</table>");

                    htmlBuilder.AppendLine("<div style=\"height: 7px;\"></div>");

                    htmlBuilder.AppendLine("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" summary=\"This table contains the ANOVA p-value.\">");
                    htmlBuilder.AppendLine(" <tr>");
                    htmlBuilder.AppendLine("   <th>P Value</th>");
                    htmlBuilder.AppendLine("   <td>" + stranovaPValueValue + "</td>");
                    htmlBuilder.AppendLine(" </tr>");
                    htmlBuilder.AppendLine("</table>");

                    // Bartlett
                    htmlBuilder.AppendLine("<div style=\"height: 7px;\"></div>");
                    htmlBuilder.AppendLine("<p><strong>Bartlett's Test for Inequality of Population Variances</strong></p>");
                    htmlBuilder.AppendLine("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\">");
                    htmlBuilder.AppendLine(" <tr>");
                    htmlBuilder.AppendLine("   <th>Chi Square</th>");
                    htmlBuilder.AppendLine("   <td>" + strchiSquareValue + "</td>");
                    htmlBuilder.AppendLine(" </tr>");

                    htmlBuilder.AppendLine(" <tr>");
                    htmlBuilder.AppendLine("   <th>Degrees of freedom</th>");
                    htmlBuilder.AppendLine("   <td>" + strdfBetweenValue + "</td>");
                    htmlBuilder.AppendLine(" </tr>");

                    htmlBuilder.AppendLine(" <tr>");
                    htmlBuilder.AppendLine("   <th>P Value</th>");
                    htmlBuilder.AppendLine("   <td>" + strbartlettPValue + "</td>");
                    htmlBuilder.AppendLine("</table>");

                    htmlBuilder.AppendLine("<p><small>A small p-value (e.g., less than 0.05) suggests that the variances are not homogeneous and that the ANOVA may not be appropriate.</small></p>");

                    // Kruskal-Wallis
                    htmlBuilder.AppendLine("<div style=\"height: 7px;\"></div>");
                    htmlBuilder.AppendLine("<p><strong>Mann-Whitney/Wilcoxon Two-Sample Test (Kruskal-Wallis test for two groups)</strong></p>");
                    htmlBuilder.AppendLine("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" >");
                    htmlBuilder.AppendLine(" <tr>");
                    htmlBuilder.AppendLine("   <th>Kruskal-Wallis H</th>");
                    htmlBuilder.AppendLine("   <td>" + strKruskalWallisH + "</td>");
                    htmlBuilder.AppendLine(" </tr>");

                    htmlBuilder.AppendLine(" <tr>");
                    htmlBuilder.AppendLine("   <th>Degrees of freedom</th>");
                    htmlBuilder.AppendLine("   <td>" + strdfBetweenValue + "</td>");
                    htmlBuilder.AppendLine(" </tr>");

                    htmlBuilder.AppendLine(" <tr>");
                    htmlBuilder.AppendLine("   <th>P Value</th>");
                    htmlBuilder.AppendLine("   <td>" + strKruskalPValue + "</td>");
                    htmlBuilder.AppendLine("</table>");
                }
            }

            return htmlBuilder.ToString();
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Generates Xml representation of this gadget
        /// </summary>
        /// <param name="doc">The Xml docment</param>
        /// <returns>XmlNode</returns>
        public override XmlNode Serialize(XmlDocument doc)
        {
            CreateInputVariableList();

            Dictionary<string, string> inputVariableList = GadgetOptions.InputVariableList;

            string freqVar = string.Empty;
            string strataVar = string.Empty;
            string weightVar = string.Empty;
            string sort = string.Empty;
            bool allValues = false;
            bool showConfLimits = true;
            bool showCumulativePercent = true;
            bool includeMissing = false;

            WordBuilder wb = new WordBuilder(",");
            if (lbxColumns.SelectedItems.Contains("Frequency")) wb.Add("1");
            if (lbxColumns.SelectedItems.Contains("Percent")) wb.Add("2");
            if (lbxColumns.SelectedItems.Contains("Cumulative Percent")) wb.Add("3");
            if (lbxColumns.SelectedItems.Contains("95% CI Lower")) wb.Add("4");
            if (lbxColumns.SelectedItems.Contains("95% CI Upper")) wb.Add("5");
            if (lbxColumns.SelectedItems.Contains("Percent bars")) wb.Add("6");

            if (inputVariableList.ContainsKey("freqvar"))
            {
                freqVar = inputVariableList["freqvar"].Replace("<", "&lt;");
            }
            if (inputVariableList.ContainsKey("stratavar"))
            {
                strataVar = inputVariableList["stratavar"].Replace("<", "&lt;");
            }
            if (inputVariableList.ContainsKey("weightvar"))
            {
                weightVar = inputVariableList["weightvar"].Replace("<", "&lt;");
            }
            if (inputVariableList.ContainsKey("sort"))
            {
                sort = inputVariableList["sort"];
            }
            if (inputVariableList.ContainsKey("allvalues"))
            {
                allValues = bool.Parse(inputVariableList["allvalues"]);
            }
            if (inputVariableList.ContainsKey("showconflimits"))
            {
                showConfLimits = bool.Parse(inputVariableList["showconflimits"]);
            }
            if (inputVariableList.ContainsKey("showcumulativepercent"))
            {
                showCumulativePercent = bool.Parse(inputVariableList["showcumulativepercent"]);
            }
            if (inputVariableList.ContainsKey("includemissing"))
            {
                includeMissing = bool.Parse(inputVariableList["includemissing"]);
            }

            CustomOutputHeading = headerPanel.Text;
            CustomOutputDescription = descriptionPanel.Text;

            string xmlString =
            "<mainVariable>" + freqVar + "</mainVariable>" +
            "<strataVariable>" + strataVar + "</strataVariable>" +
            "<weightVariable>" + weightVar + "</weightVariable>" +
            "<sort>" + sort + "</sort>" +
            "<allValues>" + allValues + "</allValues>" +
            "<showListLabels>" + checkboxCommentLegalLabels.IsChecked + "</showListLabels>" +
            "<useFieldPrompts>" + checkboxUsePrompts.IsChecked.ToString() + "</useFieldPrompts>" +
            "<columnsToShow>" + wb.ToString() + "</columnsToShow>" +
            "<includeMissing>" + includeMissing + "</includeMissing>" +
            "<customHeading>" + CustomOutputHeading.Replace("<", "&lt;") + "</customHeading>" +
            "<customDescription>" + CustomOutputDescription.Replace("<", "&lt;") + "</customDescription>" +
            "<customCaption>" + CustomOutputCaption + "</customCaption>";

            System.Xml.XmlElement element = doc.CreateElement("frequencyGadget");
            element.InnerXml = xmlString;
            element.AppendChild(SerializeFilters(doc));

            System.Xml.XmlAttribute locationY = doc.CreateAttribute("top");
            System.Xml.XmlAttribute locationX = doc.CreateAttribute("left");
            System.Xml.XmlAttribute collapsed = doc.CreateAttribute("collapsed");
            System.Xml.XmlAttribute type = doc.CreateAttribute("gadgetType");

            locationY.Value = Canvas.GetTop(this).ToString("F0");
            locationX.Value = Canvas.GetLeft(this).ToString("F0");
            collapsed.Value = "false"; // currently no way to collapse the gadget, so leave this 'false' for now
            type.Value = "Epi.WPF.Dashboard.Gadgets.Analysis.FrequencyControl";

            element.Attributes.Append(locationY);
            element.Attributes.Append(locationX);
            element.Attributes.Append(collapsed);
            element.Attributes.Append(type);

            return element;
        }
        /// <summary>
        /// Begins the process of importing records from the data package into the destination form
        /// </summary>
        /// <param name="form">The form that will receive the data</param>
        /// <param name="formNode">The XmlNode representing the form</param>
        /// <param name="records">The data to be imported</param>
        protected override void ImportRecords(View form, XmlNode formNode, List<PackageFieldData> records)
        {
            if (!IsUsingCustomMatchkeys) // Calling class should instantiate normal data packager if custom keys aren't used
            {
                throw new ApplicationException("This class should not be used without custom match keys.");
            }

            ImportInfo.RecordsAppended.Add(form, 0);
            ImportInfo.RecordsUpdated.Add(form, 0);

            IDbDriver destinationDb = DestinationProject.CollectedData.GetDatabase();

            DataTable destinationKeyTable = new DataTable();
            destinationKeyTable.Columns.Add(new DataColumn("GlobalRecordId", typeof(string)));
            destinationKeyTable.Columns.Add(new DataColumn("Update", typeof(bool)));
            destinationKeyTable.Columns.Add(new DataColumn("KeyDictionary", typeof(Dictionary<Field, object>)));

            DataColumn [] primaryKey = new DataColumn[1];
            primaryKey[0] = destinationKeyTable.Columns["GlobalRecordId"];
            destinationKeyTable.PrimaryKey = primaryKey;

            WordBuilder wb = new WordBuilder(",");
            wb.Add("t.GlobalRecordId");
            foreach (Field field in KeyFields)
            {
                wb.Add(field.Name);
            }

            Query selectQuery = destinationDb.CreateQuery("SELECT " + wb.ToString() + " " + form.FromViewSQL);
            using (IDataReader keyTableReader = destinationDb.ExecuteReader(selectQuery))
            {
                while (keyTableReader.Read())
                {
                    string guid = keyTableReader["GlobalRecordId"].ToString();
                    Dictionary<Field, object> keys = new Dictionary<Field, object>();

                    foreach (Field field in KeyFields)
                    {
                        keys.Add(field, keyTableReader[field.Name]);
                    }

                    destinationKeyTable.Rows.Add(guid, true, keys);
                }
            }

            var query = from record in records
                        group record by record.RecordGUID;

            IEnumerable<IEnumerable<PackageFieldData>> fieldDataLists = query as IEnumerable<IEnumerable<PackageFieldData>>;

            foreach (IEnumerable<PackageFieldData> fieldDataList in fieldDataLists)
            {
                PackageFieldData fieldData = fieldDataList.First();
                bool found = false;

                foreach (DataRow row in destinationKeyTable.Rows)
                {
                    Dictionary<Field, object> keyDictionary = row["KeyDictionary"] as Dictionary<Field, object>;

                    if (AreKeyFieldDictionariesEqual(keyDictionary, fieldData.KeyValues))
                    {
                        found = true;
                        if (!Update)
                        {
                            row["Update"] = false;
                        }
                        else
                        {
                            ImportInfo.TotalRecordsUpdated++;
                            ImportInfo.RecordsUpdated[form]++;
                        }
                    }
                }

                if (!found && Append) // no match, this is a new record that must be inserted
                {
                    CreateNewBlankRow(form, fieldData.RecordGUID, fieldData.KeyValues);
                    ImportInfo.TotalRecordsAppended++;
                    ImportInfo.RecordsAppended[form]++;
                }
            }

            System.Threading.Thread.Sleep(2000); // give time for DB to update

            destinationKeyTable.Clear();
            selectQuery = destinationDb.CreateQuery("SELECT " + wb.ToString() + " " + form.FromViewSQL);
            using (IDataReader keyTableReader = destinationDb.ExecuteReader(selectQuery))
            {
                while (keyTableReader.Read())
                {
                    string guid = keyTableReader["GlobalRecordId"].ToString();
                    Dictionary<Field, object> keys = new Dictionary<Field, object>();

                    foreach (Field field in KeyFields)
                    {
                        keys.Add(field, keyTableReader[field.Name]);
                    }

                    destinationKeyTable.Rows.Add(guid, true, keys);
                }
            }

            //Parallel.ForEach(records, rec =>

            // TODO: Make this faster (note that Parallel foreach seems to make it worse)
            foreach(PackageFieldData rec in records)
                {
                    bool found = false;
                    string targetGuid = String.Empty;
                    bool shouldUpdate = true;

                    foreach (DataRow row in destinationKeyTable.Rows)
                    {
                        Dictionary<Field, object> keyDictionary = row["KeyDictionary"] as Dictionary<Field, object>;

                        if (AreKeyFieldDictionariesEqual(keyDictionary, rec.KeyValues))
                        {
                            found = true;
                            targetGuid = row["GlobalRecordId"].ToString();
                            shouldUpdate = (bool)row["Update"];
                            break;
                        }
                    }

                    if (shouldUpdate && found && !String.IsNullOrEmpty(targetGuid) && rec.FieldValue != null && !String.IsNullOrEmpty(rec.FieldValue.ToString()))
                    {
                        Query updateQuery = destinationDb.CreateQuery("UPDATE " + rec.Page.TableName + " SET " +
                        "[" + rec.FieldName + "] = @" + rec.FieldName + " WHERE [GlobalRecordId] = @GlobalRecordId");

                        QueryParameter fieldParam = GetQueryParameterForField(rec, form, rec.Page);

                        if (fieldParam != null)
                        {
                            updateQuery.Parameters.Add(fieldParam);
                            updateQuery.Parameters.Add(new QueryParameter("@GlobalRecordId", DbType.String, targetGuid));
                            int rowsAffected = destinationDb.ExecuteNonQuery(updateQuery);

                            if (rowsAffected == 0)
                            {
                                throw new ApplicationException("No records affected.");
                            }
                            else if (rowsAffected > 1)
                            {
                                throw new ApplicationException("Too many records affected.");
                            }
                        }
                    }
                }
            //);
        }
        /// <summary>
        /// Converts the gadget's output to Html
        /// </summary>
        /// <returns></returns>
        public override string ToHTML(string htmlFileName = "", int count = 0)
        {
            if (IsCollapsed) return string.Empty;

            StringBuilder htmlBuilder = new StringBuilder();
            CustomOutputHeading = headerPanel.Text;
            CustomOutputDescription = descriptionPanel.Text;

            if (CustomOutputHeading == null || (string.IsNullOrEmpty(CustomOutputHeading) && !CustomOutputHeading.Equals("(none)")))
            {
                htmlBuilder.AppendLine("<h2 class=\"gadgetHeading\">Duplicates List</h2>");
            }
            else if (CustomOutputHeading != "(none)")
            {
                htmlBuilder.AppendLine("<h2 class=\"gadgetHeading\">" + CustomOutputHeading + "</h2>");
            }

            htmlBuilder.AppendLine("<p class=\"gadgetOptions\"><small>");
            htmlBuilder.AppendLine("<br />");

            if (Parameters.ColumnNames.Count > 0)
            {
                WordBuilder wb = new WordBuilder(", ");
                foreach (string s in Parameters.ColumnNames)
                {
                    wb.Add(s);
                }
                htmlBuilder.AppendLine("<em>Strata variable(s):</em> <strong>" + wb.ToString() + "</strong>");
                htmlBuilder.AppendLine("<br />");
            }

            htmlBuilder.AppendLine("<br />");
            htmlBuilder.AppendLine("</small></p>");

            if (!string.IsNullOrEmpty(CustomOutputDescription))
            {
                htmlBuilder.AppendLine("<p class=\"gadgetsummary\">" + CustomOutputDescription + "</p>");
            }

            if (!string.IsNullOrEmpty(messagePanel.Text) && messagePanel.Visibility == Visibility.Visible)
            {
                htmlBuilder.AppendLine("<p><small><strong>" + messagePanel.Text + "</strong></small></p>");
            }

            if (!string.IsNullOrEmpty(infoPanel.Text) && infoPanel.Visibility == Visibility.Visible)
            {
                htmlBuilder.AppendLine("<p><small><strong>" + infoPanel.Text + "</strong></small></p>");
            }

            foreach (Grid grid in this.StrataGridList)
            {
                string gridName = grid.Tag.ToString();

                string summaryText = "This tables represents fields of duplicate values. ";

                htmlBuilder.AppendLine("<div style=\"height: 7px;\"></div>");
                htmlBuilder.AppendLine("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" summary=\"" + summaryText + "\">");

                if (string.IsNullOrEmpty(CustomOutputCaption))
                {
                    if (Parameters.ColumnNames.Count > 0)
                    {
                        htmlBuilder.AppendLine("<caption>" + grid.Tag + "</caption>");
                    }
                }
                else
                {
                    htmlBuilder.AppendLine("<caption>" + CustomOutputCaption + "</caption>");
                }

                double barWidth = 0.0;

                foreach (UIElement control in grid.Children)
                {
                    if (control is TextBlock)
                    {
                        int rowNumber = Grid.GetRow(control);
                        int columnNumber = Grid.GetColumn(control);
                        string tableDataTagOpen = "<td>";
                        string tableDataTagClose = "</td>";

                        if (rowNumber == 0)
                        {
                            tableDataTagOpen = "<th>";
                            tableDataTagClose = "</th>";
                        }
                        if (columnNumber == 0)
                        {
                            if (((double)rowNumber) % 2.0 == 1)
                            {
                                htmlBuilder.AppendLine("<tr class=\"altcolor\">");
                            }
                            else
                            {
                                htmlBuilder.AppendLine("<tr>");
                            }
                        }
                        if (columnNumber == 0 && rowNumber > 0)
                        {
                            tableDataTagOpen = "<td class=\"value\">";
                        }

                        string value = ((TextBlock)control).Text;

                        if (string.IsNullOrEmpty(value))
                        {
                            value = "&nbsp;";
                        }
                        string formattedValue = value;

                        if (rowNumber == grid.RowDefinitions.Count - 1)
                        {
                            formattedValue = "<span class=\"total\">" + value + "</span>";
                        }

                        htmlBuilder.AppendLine(tableDataTagOpen + formattedValue + tableDataTagClose);

                        if (columnNumber == 2 && rowNumber > 0)
                        {
                            barWidth = 0;
                            double.TryParse(value.Trim().TrimEnd('%').Trim(), out barWidth);
                        }

                        if (columnNumber >= grid.ColumnDefinitions.Count - 2)
                        {
                            if (rowNumber > 0)
                            {
                                htmlBuilder.AppendLine("<td class=\"value\"><div class=\"percentBar\" style=\"width: " + ((int)barWidth * 2).ToString() + "px;\"></td>");
                            }
                            else
                            {
                                htmlBuilder.AppendLine(tableDataTagOpen + tableDataTagClose);
                            }
                            htmlBuilder.AppendLine("</tr>");
                        }
                    }
                }

                htmlBuilder.AppendLine("</table>");
            }
            return htmlBuilder.ToString();
        }
        /// <summary>
        /// Creates a new blank row for a given form's base table and all of its page tables.
        /// </summary>
        /// <param name="form">The form where the row should be added.</param>
        /// <param name="guid">The Guid value to use for the row.</param>
        /// <param name="keyValues">The key values to use for custom matching</param>
        /// <param name="fkey">The foreign key for the row.</param>
        /// <param name="firstSaveId">The user ID of the first person that saved this record.</param>
        /// <param name="firstSaveTime">The time when the record was first saved.</param>
        /// <param name="lastSaveId">The user ID of the last person that saved this record.</param>
        /// <param name="lastSaveTime">The time when the record was last saved.</param>
        protected virtual void CreateNewBlankRow(View form, string guid, Dictionary<Field, object> keyValues = null, string fkey = "", string firstSaveId = "", string lastSaveId = "", DateTime? firstSaveTime = null, DateTime? lastSaveTime = null)
        {
            #region Input Validation
            if (string.IsNullOrEmpty(guid)) { throw new ArgumentNullException("guid"); }
            if (form == null) { throw new ArgumentNullException("form"); }
            #endregion // Input Validation

            if (Conn.State != ConnectionState.Open)
            {
                Conn.Open();
            }

            IDbDriver db = DestinationProject.CollectedData.GetDatabase();
            StringBuilder sb = new StringBuilder();
            sb.Append(" insert into ");
            sb.Append(db.InsertInEscape(form.TableName));
            sb.Append(StringLiterals.SPACE);
            sb.Append(StringLiterals.SPACE);

            WordBuilder fields = new WordBuilder(",");
            fields.Append("[GlobalRecordId]");

            if (!string.IsNullOrEmpty(fkey)) { fields.Append("[FKEY]"); }
            if (!string.IsNullOrEmpty(firstSaveId)) { fields.Append("[FirstSaveLogonName]"); }
            if (!string.IsNullOrEmpty(lastSaveId)) { fields.Append("[LastSaveLogonName]"); }
            if (firstSaveTime.HasValue) { fields.Append("[FirstSaveTime]"); }
            if (lastSaveTime.HasValue) { fields.Append("[LastSaveTime]"); }

            sb.Append("(" + fields.ToString() + ")");
            sb.Append(" values (");

            List<QueryParameter> parameters = new List<QueryParameter>();
            WordBuilder values = new WordBuilder(",");
            values.Append("'" + guid + "'");

            if (!string.IsNullOrEmpty(fkey))
            {
                values.Append("@FKEY");
                parameters.Add(new QueryParameter("@FKEY", DbType.String, fkey));
            }
            if (!string.IsNullOrEmpty(firstSaveId))
            {
                values.Append("@FirstSaveLogonName");
                parameters.Add(new QueryParameter("@FirstSaveLogonName", DbType.String, firstSaveId));
            }
            if (!string.IsNullOrEmpty(lastSaveId))
            {
                values.Append("@LastSaveLogonName");
                parameters.Add(new QueryParameter("@LastSaveLogonName", DbType.String, lastSaveId));
            }
            if (firstSaveTime.HasValue)
            {
                values.Append("@FirstSaveTime");
                parameters.Add(new QueryParameter("@FirstSaveTime", DbType.DateTime, firstSaveTime));
            }
            if (lastSaveTime.HasValue)
            {
                values.Append("@LastSaveTime");
                parameters.Add(new QueryParameter("@LastSaveTime", DbType.DateTime, lastSaveTime));
            }

            sb.Append(values.ToString());
            sb.Append(") ");
            Epi.Data.Query insertQuery = db.CreateQuery(sb.ToString());
            insertQuery.Parameters = parameters;

            if (DestinationProject.CollectedDataDriver.ToLower().Contains("epi.data.office"))
            {
                IDbCommand command = GetCommand(insertQuery.SqlStatement, Conn, insertQuery.Parameters);
                object obj = command.ExecuteNonQuery();
            }
            else
            {
                db.ExecuteNonQuery(insertQuery);
            }

            //Parallel.ForEach(form.Pages, page =>
            foreach(Page page in form.Pages)
                {
                    WordBuilder wbFields = new WordBuilder(",");
                    WordBuilder wbParams = new WordBuilder(",");
                    List<QueryParameter> queryParams = new List<QueryParameter>();

                    wbFields.Add("[GlobalRecordId]");
                    wbParams.Add("@GlobalRecordId");
                    queryParams.Add(new QueryParameter("@GlobalRecordId", DbType.String, guid));

                    foreach (KeyValuePair<Field, object> kvp in keyValues)
                    {
                        RenderableField field = kvp.Key as RenderableField;

                        PackageFieldData fieldData = new PackageFieldData();
                        fieldData.FieldValue = kvp.Value;
                        fieldData.FieldName = field.Name;
                        fieldData.Page = field.Page;

                        if (field.Page.TableName.Equals(page.TableName))
                        {

                            wbFields.Add(db.InsertInEscape(fieldData.FieldName));
                            wbParams.Add("@" + fieldData.FieldName);

                            QueryParameter parameter = GetQueryParameterForField(fieldData, form, field.Page);
                            queryParams.Add(parameter);
                        }
                    }
                    sb = new StringBuilder();
                    sb.Append(" insert into ");
                    sb.Append(db.InsertInEscape(page.TableName));
                    sb.Append(StringLiterals.SPACE);
                    sb.Append(StringLiterals.SPACE);
                    sb.Append("(");
                    sb.Append(wbFields.ToString());
                    sb.Append(")");
                    sb.Append(" values (");
                    sb.Append(wbParams.ToString());
                    sb.Append(") ");
                    insertQuery = db.CreateQuery(sb.ToString());

                    foreach (QueryParameter queryParam in queryParams)
                    {
                        insertQuery.Parameters.Add(queryParam);
                    }

                    if (DestinationProject.CollectedDataDriver.ToLower().Contains("epi.data.office"))
                    {
                        IDbCommand command = GetCommand(insertQuery.SqlStatement, Conn, insertQuery.Parameters);
                        object obj = command.ExecuteNonQuery();
                    }
                    else
                    {
                        db.ExecuteNonQuery(insertQuery);
                    }
                }
            //);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Generates Xml representation of this gadget
        /// </summary>
        /// <param name="doc">The Xml docment</param>
        /// <returns>XmlNode</returns>
        public override XmlNode Serialize(XmlDocument doc)
        {
            Dictionary<string, string> inputVariableList = GadgetOptions.InputVariableList;

            string groupVar = string.Empty;

            if (cbxGroupField.SelectedItem != null)
            {
                groupVar = cbxGroupField.SelectedItem.ToString().Replace("<", "&lt;");
            }

            CustomOutputHeading = headerPanel.Text;
            //CustomOutputDescription = txtOutputDescription.Text.Replace("<", "&lt;");
            CustomOutputDescription = descriptionPanel.Text; //txtOutputDescription.Text.Replace("<", "&lt;");

            string xmlString =
            "<groupVariable>" + groupVar + "</groupVariable>" +
            "<maxRows>" + MaxRows.ToString() + "</maxRows>" +
            "<maxColumnNameLength>" + MaxColumnLength.ToString() + "</maxColumnNameLength>" +
            "<sortColumnsByTabOrder>" + checkboxTabOrder.IsChecked.ToString() + "</sortColumnsByTabOrder>" +
            "<useFieldPrompts>" + checkboxUsePrompts.IsChecked.ToString() + "</useFieldPrompts>" +
            "<showListLabels>" + checkboxListLabels.IsChecked + "</showListLabels>" +
            "<showLineColumn>" + checkboxLineColumn.IsChecked.ToString() + "</showLineColumn>" +
            "<showColumnHeadings>" + checkboxColumnHeaders.IsChecked.ToString() + "</showColumnHeadings>" +
            "<showNullLabels>" + checkboxShowNulls.IsChecked.ToString() + "</showNullLabels>" +
            //"<alternatingRowColors>" + checkboxAltRowColors.IsChecked.ToString() + "</alternatingRowColors>" +
            //"<allowUpdates>" + checkboxAllowUpdates.IsChecked.ToString() + "</allowUpdates>" +
            "<customHeading>" + CustomOutputHeading.Replace("<", "&lt;") + "</customHeading>" +
            "<customDescription>" + CustomOutputDescription.Replace("<", "&lt;") + "</customDescription>" +
            "<customCaption>" + CustomOutputCaption + "</customCaption>";

            xmlString = xmlString + SerializeAnchors();

            if (inputVariableList.ContainsKey("customusercolumnsort"))
            {
                string columns = inputVariableList["customusercolumnsort"];
                xmlString = xmlString + "<customusercolumnsort>" + columns + "</customusercolumnsort>";
            }
            else if (columnOrder != null && columnOrder.Count > 0) // when user has re-ordered columns but not refreshed
            {
                WordBuilder wb = new WordBuilder("^");
                for (int i = 0; i < columnOrder.Count; i++)
                {
                    wb.Add(columnOrder[i]);
                }
                xmlString = xmlString + "<customusercolumnsort>" + wb.ToString() + "</customusercolumnsort>";
            }

            System.Xml.XmlElement element = doc.CreateElement("lineListGadget");
            element.InnerXml = xmlString;
            element.AppendChild(SerializeFilters(doc));

            System.Xml.XmlAttribute id = doc.CreateAttribute("id");
            System.Xml.XmlAttribute locationY = doc.CreateAttribute("top");
            System.Xml.XmlAttribute locationX = doc.CreateAttribute("left");
            System.Xml.XmlAttribute collapsed = doc.CreateAttribute("collapsed");
            System.Xml.XmlAttribute type = doc.CreateAttribute("gadgetType");

            id.Value = this.UniqueIdentifier.ToString();
            locationY.Value = Canvas.GetTop(this).ToString("F0");
            locationX.Value = Canvas.GetLeft(this).ToString("F0");
            collapsed.Value = IsCollapsed.ToString();
            type.Value = "EpiDashboard.LineListControl";

            element.Attributes.Append(locationY);
            element.Attributes.Append(locationX);
            element.Attributes.Append(collapsed);
            element.Attributes.Append(type);
            element.Attributes.Append(id);

            if (lbxFields.Items.Count > 0 && lbxFields.SelectedItems.Count > 0)
            {
                string xmlListItemString = string.Empty;
                XmlElement listItemElement = doc.CreateElement("listFields");

                foreach (string s in lbxFields.SelectedItems)
                {
                    xmlListItemString = xmlListItemString + "<listField>" + s.Replace("<", "&lt;") + "</listField>";
                }

                listItemElement.InnerXml = xmlListItemString;
                element.AppendChild(listItemElement);
            }

            if (lbxSortFields.Items.Count > 0)
            {
                string xmlSortString = string.Empty;
                XmlElement sortElement = doc.CreateElement("sortFields");

                foreach (string s in lbxSortFields.Items)
                {
                    xmlSortString = xmlSortString + "<sortField>" + s.Replace("<", "&lt;") + "</sortField>";
                }

                sortElement.InnerXml = xmlSortString;
                element.AppendChild(sortElement);
            }

            return element;
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Converts the gadget's output to Html
        /// </summary>
        /// <returns></returns>
        public override string ToHTML(string htmlFileName = "", int count = 0)
        {
            if (IsCollapsed) return string.Empty;
            CrosstabParameters crosstabParameters = (CrosstabParameters)Parameters;

            StringWriter stringWriter = new StringWriter();
            //using (HTMTextWriter writer = new HTMTextWriter(stringWriter))

            using (HtmlTextWriter writer = new HtmlTextWriter(stringWriter))
            {
                //StringBuilder htmlBuilder = new StringBuilder();

                //CustomOutputHeading = headerPanel.Text;
                //CustomOutputDescription = descriptionPanel.Text;
                CustomOutputHeading = headerPanel.Text;
                CustomOutputDescription = descriptionPanel.Text;

                if (CustomOutputHeading == null || (string.IsNullOrEmpty(CustomOutputHeading) && !CustomOutputHeading.Equals("(none)")))
                {
                    //htmlBuilder.AppendLine("<h2 class=\"gadgetHeading\">Crosstabulation</h2>");
                    writer.AddAttribute(HtmlTextWriterAttribute.Class, "gadgetHeading");
                    writer.RenderBeginTag(HtmlTextWriterTag.H2);   // Begin #1
                    writer.Write("Crosstabulation");
                    writer.RenderEndTag(); // End #1
                }
                else if (CustomOutputHeading != "(none)")
                {
                    //htmlBuilder.AppendLine("<h2 class=\"gadgetHeading\">" + CustomOutputHeading + "</h2>");
                    writer.AddAttribute(HtmlTextWriterAttribute.Class, "gadgetHeading");
                    writer.RenderBeginTag(HtmlTextWriterTag.H2);   // Begin #1
                    writer.Write(CustomOutputHeading);
                    writer.RenderEndTag(); // End #1
                }

                //htmlBuilder.AppendLine("<p class=\"gadgetOptions\"><small>");
                writer.AddAttribute(HtmlTextWriterAttribute.Class, "gadgetOptions");
                writer.RenderBeginTag(HtmlTextWriterTag.P);  //Begin (B) #1
                writer.RenderBeginTag(HtmlTextWriterTag.Small);  //B 2

                //htmlBuilder.AppendLine("<em>Main variable:</em> <strong>" + cbxExposureField.Text + "</strong>");
                writer.RenderBeginTag(HtmlTextWriterTag.Em);  //B 3
                writer.Write("Main variable:");
                writer.RenderEndTag();  //E 3
                writer.RenderBeginTag(HtmlTextWriterTag.Strong); //B 3
                writer.Write(crosstabParameters.ColumnNames[0].ToString());
                writer.RenderEndTag();  //E 3

                //htmlBuilder.AppendLine("<br />");
                writer.WriteBreak();

                //htmlBuilder.AppendLine("<em>Crosstab variable:</em> <strong>" + cbxOutcomeField.Text + "</strong>");
                //htmlBuilder.AppendLine("<br />");
                writer.RenderBeginTag(HtmlTextWriterTag.Em);  //B 3
                writer.Write("Main variable:");
                writer.RenderEndTag();  //E 3
                writer.RenderBeginTag(HtmlTextWriterTag.Strong); //B 3
                writer.Write(crosstabParameters.CrosstabVariableName.ToString());
                writer.RenderEndTag();  //E 3
                writer.WriteBreak();

                //if (cbxFieldWeight.SelectedIndex >= 0)
                if (!String.IsNullOrEmpty(crosstabParameters.WeightVariableName))
                {
                    //htmlBuilder.AppendLine("<em>Weight variable:</em> <strong>" + cbxFieldWeight.Text + "</strong>");
                    //htmlBuilder.AppendLine("<br />");
                    writer.RenderBeginTag(HtmlTextWriterTag.Em);  //B 3
                    writer.Write("Weight variable:");
                    writer.RenderEndTag();  //E 3
                    writer.RenderBeginTag(HtmlTextWriterTag.Strong); //B 3
                    writer.Write(crosstabParameters.WeightVariableName.ToString());
                    writer.RenderEndTag();  //E 3
                    writer.WriteBreak();
                }

                //if (lbxFieldStrata.SelectedItems.Count > 0)
                if (crosstabParameters.StrataVariableNames.Count > 0)
                {
                    WordBuilder wb = new WordBuilder(", ");
                    foreach (string s in crosstabParameters.StrataVariableNames)
                    {
                        wb.Add(s);
                    }
                    //htmlBuilder.AppendLine("<em>Strata variable(s):</em> <strong>" + wb.ToString() + "</strong>");
                    //htmlBuilder.AppendLine("<br />");
                    writer.RenderBeginTag(HtmlTextWriterTag.Em);  //B 3
                    writer.Write("Strata variable(s):");
                    writer.RenderEndTag();  //E 3
                    writer.RenderBeginTag(HtmlTextWriterTag.Strong); //B 3
                    writer.Write(wb.ToString());
                    writer.RenderEndTag();  //E 3
                    writer.WriteBreak();
                }

                //htmlBuilder.AppendLine("<em>Include missing:</em> <strong>" + checkboxIncludeMissing.IsChecked.ToString() + "</strong>");
                //htmlBuilder.AppendLine("<br />");
                //htmlBuilder.AppendLine("</small></p>");
                writer.RenderBeginTag(HtmlTextWriterTag.Em);  //B 3
                writer.Write("Include missing:");
                writer.RenderEndTag();  //E 3
                writer.RenderBeginTag(HtmlTextWriterTag.Strong); //B 3
                writer.Write(crosstabParameters.IncludeMissing.ToString());
                writer.RenderEndTag();  //E 3
                writer.WriteBreak();
                writer.RenderEndTag();  //E 2
                writer.RenderEndTag();  //E 1

                if (!string.IsNullOrEmpty(CustomOutputDescription))
                {
                    //htmlBuilder.AppendLine("<p class=\"gadgetsummary\">" + CustomOutputDescription + "</p>");
                    writer.AddAttribute(HtmlTextWriterAttribute.Class, "gadgetsummary");
                    writer.RenderBeginTag(HtmlTextWriterTag.P);  // B1
                    writer.Write(CustomOutputDescription);
                    writer.RenderEndTag();  //E1
                }

                if (!string.IsNullOrEmpty(messagePanel.Text) && messagePanel.Visibility == Visibility.Visible)
                {
                    //htmlBuilder.AppendLine("<p><small><strong>" + messagePanel.Text + "</strong></small></p>");
                    writer.RenderBeginTag(HtmlTextWriterTag.P); // B1
                    writer.RenderBeginTag(HtmlTextWriterTag.Small);  //B2
                    writer.RenderBeginTag(HtmlTextWriterTag.Strong);  //B3
                    writer.Write(messagePanel.Text);
                    writer.RenderEndTag();  //E3
                    writer.RenderEndTag();  //E2
                    writer.RenderEndTag(); // E1
                }

                if (!string.IsNullOrEmpty(infoPanel.Text) && infoPanel.Visibility == Visibility.Visible)
                {
                    //htmlBuilder.AppendLine("<p><small><strong>" + infoPanel.Text + "</strong></small></p>");
                    writer.RenderBeginTag(HtmlTextWriterTag.P); // B1
                    writer.RenderBeginTag(HtmlTextWriterTag.Small);  //B2
                    writer.RenderBeginTag(HtmlTextWriterTag.Strong);  //B3
                    writer.Write(infoPanel.Text);
                    writer.RenderEndTag();  //E3
                    writer.RenderEndTag();  //E2
                    writer.RenderEndTag(); // E1
                }

                foreach (Grid grid in this.StrataGridList)
                {
                    string gridName = grid.Tag.ToString();

                    //htmlBuilder.AppendLine("<div style=\"height: 7px;\"></div>");
                    if (!string.IsNullOrEmpty(gridName))
                    {
                        //htmlBuilder.AppendLine("<h3>" + gridName + "</h3>");
                        writer.RenderBeginTag(HtmlTextWriterTag.H3);
                        writer.Write(gridName);
                        writer.RenderEndTag();

                    }
                    writer.AddAttribute(HtmlTextWriterAttribute.Style, "height: 7px;");
                    writer.RenderBeginTag(HtmlTextWriterTag.Div);
                    writer.RenderEndTag();

                    //htmlBuilder.AppendLine("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\">");
                    writer.AddAttribute(HtmlTextWriterAttribute.Align, "left");
                    writer.AddAttribute(HtmlTextWriterAttribute.Border, "0");
                    writer.AddAttribute(HtmlTextWriterAttribute.Cellpadding, "0");
                    writer.AddAttribute(HtmlTextWriterAttribute.Cellspacing, "0");
                    writer.RenderBeginTag(HtmlTextWriterTag.Table);

                    //htmlBuilder.AppendLine("<caption>" + cbxExposureField.Text + " * " + cbxOutcomeField.Text + "</caption>");
                    writer.RenderBeginTag(HtmlTextWriterTag.Caption);
                    writer.Write(crosstabParameters.ColumnNames[0].ToString() + " * " + crosstabParameters.CrosstabVariableName.ToString());
                    writer.RenderEndTag();

                    SolidColorBrush backColor = Brushes.White;

                    foreach (UIElement control in grid.Children)
                    {
                        string value = string.Empty;
                        int rowNumber = -1;
                        int columnNumber = -1;

                        if (control is TextBlock || control is StackPanel || control is Rectangle)
                        {
                            if (control is TextBlock)
                            {
                                rowNumber = Grid.GetRow(control);
                                columnNumber = Grid.GetColumn(control);
                                value = ((TextBlock)control).Text;
                            }
                            else if (control is StackPanel)
                            {
                                rowNumber = Grid.GetRow(control);
                                columnNumber = Grid.GetColumn(control);
                                value = (((control as StackPanel).Children[0]) as TextBlock).Text;
                                StackPanel panel = control as StackPanel;
                                foreach (UIElement element in panel.Children)
                                {
                                    if (element is Rectangle)
                                    {

                                    }
                                }
                            }
                            else if (control is Rectangle)
                            {
                                Rectangle rectangle = control as Rectangle;
                                backColor = rectangle.Fill as SolidColorBrush;
                                continue;
                            }

                            string tableDataTagOpen = "<td>";
                            string tableDataTagClose = "</td>";

                            if (columnNumber == 0)
                            {
                                //htmlBuilder.AppendLine("<tr>");
                                writer.RenderBeginTag(HtmlTextWriterTag.Tr);
                            }

                            //tableDataTagOpen
                            if (rowNumber == 0 && columnNumber < grid.ColumnDefinitions.Count - 1)
                            {
                                tableDataTagOpen = "<th>";
                                tableDataTagClose = "</th>";
                                writer.RenderBeginTag(HtmlTextWriterTag.Th);
                                writer.Write(value);
                                writer.RenderEndTag();
                            }
                            else if (rowNumber == 0 && columnNumber >= grid.ColumnDefinitions.Count - 1)
                            {
                                writer.RenderBeginTag(HtmlTextWriterTag.Th);
                            }
                            else if (rowNumber > 0 && rowNumber < grid.RowDefinitions.Count - 1 && columnNumber == 0)
                            {
                                //tableDataTagOpen = "<td class=\"value\">";
                                writer.AddAttribute(HtmlTextWriterAttribute.Class, "value");
                                writer.RenderBeginTag(HtmlTextWriterTag.Td);
                                writer.Write(value);
                                writer.RenderEndTag();
                            }
                            else if (rowNumber > 0 && rowNumber < grid.RowDefinitions.Count - 1 && columnNumber < grid.ColumnDefinitions.Count - 1)
                            {
                                //tableDataTagOpen = "<td style=\"background-color: rgb(" + backColor.Color.R.ToString() + ", " + backColor.Color.G.ToString() + ", " + backColor.Color.B.ToString() + ");\">";
                                writer.AddAttribute(HtmlTextWriterAttribute.Style, "background-color: rgb(" + backColor.Color.R.ToString() + ", " + backColor.Color.G.ToString() + ", " + backColor.Color.B.ToString() + ");");
                                writer.RenderBeginTag(HtmlTextWriterTag.Td);
                                writer.Write(value);
                                writer.RenderEndTag();
                            }
                            else if (rowNumber > 0 && rowNumber < grid.RowDefinitions.Count - 1 && columnNumber >= grid.ColumnDefinitions.Count - 1)
                            {
                                //tableDataTagOpen = "<td style=\"background-color: rgb(" + backColor.Color.R.ToString() + ", " + backColor.Color.G.ToString() + ", " + backColor.Color.B.ToString() + ");\">";
                                writer.RenderBeginTag(HtmlTextWriterTag.Td);
                            }
                            else if (rowNumber >= grid.RowDefinitions.Count - 1)
                            {
                                //tableDataTagOpen = "<td style=\"background-color: rgb(" + backColor.Color.R.ToString() + ", " + backColor.Color.G.ToString() + ", " + backColor.Color.B.ToString() + ");\">";
                                writer.RenderBeginTag(HtmlTextWriterTag.Td);
                            }

                            string formattedValue = value;

                            if ((rowNumber == grid.RowDefinitions.Count - 1) || (columnNumber == grid.ColumnDefinitions.Count - 1))
                            {
                                //formattedValue = "<span class=\"total\">" + value + "</span>";
                                writer.AddAttribute(HtmlTextWriterAttribute.Class, "total");
                                writer.RenderBeginTag(HtmlTextWriterTag.Span);
                                writer.Write(value);
                                try
                                {
                                    writer.RenderEndTag();
                                    writer.RenderEndTag();
                                }
                                catch (Exception ex)
                                {
                                    Exception eexx = ex;
                                }
                            }

                            //htmlBuilder.AppendLine(tableDataTagOpen + formattedValue + tableDataTagClose);
            //                            writer.RenderEndTag();

                            if (columnNumber >= grid.ColumnDefinitions.Count - 1)
                            {
                                //htmlBuilder.AppendLine("</tr>");
                                try
                                {
                                    writer.RenderEndTag();
                                }
                                catch (Exception ex)
                                {
                                    Exception eexx = ex;
                                }
                            }
                        }
                    }

                    //htmlBuilder.AppendLine("</table>");
                    try
                    {
                        writer.RenderEndTag();
                    }
                    catch (Exception ex)
                    {
                        Exception eexx = ex;
                    }

                    // Chi Square

                    Grid chiSquareGrid = GetStrataChiSquareGrid(grid.Tag.ToString());
                    //htmlBuilder.AppendLine("<p></p>");
                    //htmlBuilder.AppendLine("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\">");
                    writer.AddAttribute(HtmlTextWriterAttribute.Style, "clear: both");
                    writer.RenderBeginTag(HtmlTextWriterTag.P);
                    // </p>
                    writer.RenderEndTag();
                    writer.RenderBeginTag(HtmlTextWriterTag.Br);
                    writer.AddAttribute(HtmlTextWriterAttribute.Border, "0");
                    writer.AddAttribute(HtmlTextWriterAttribute.Cellpadding, "0");
                    writer.AddAttribute(HtmlTextWriterAttribute.Cellspacing, "0");
                    writer.RenderBeginTag(HtmlTextWriterTag.Table);

                    foreach (UIElement control in chiSquareGrid.Children)
                    {
                        if (control is TextBlock)
                        {
                            int rowNumber = Grid.GetRow(control);
                            int columnNumber = Grid.GetColumn(control);

                            string tableDataTagOpen = "<td>";
                            string tableDataTagClose = "</td>";

                            if (columnNumber == 0)
                            {
                                //htmlBuilder.AppendLine("<tr>");
                                writer.RenderBeginTag(HtmlTextWriterTag.Tr);
                            }

                            if (rowNumber == 0)
                            {
                                //tableDataTagOpen = "<th>";
                                //tableDataTagClose = "</th>";
                                writer.RenderBeginTag(HtmlTextWriterTag.Th);
                            }
                            else
                            {
                                writer.RenderBeginTag(HtmlTextWriterTag.Td);
                            }

                            string value = ((TextBlock)control).Text;
                            string formattedValue = value;

                            //htmlBuilder.AppendLine(tableDataTagOpen + formattedValue + tableDataTagClose);
                            writer.Write(formattedValue);
                            writer.RenderEndTag();

                            if (columnNumber >= chiSquareGrid.ColumnDefinitions.Count - 1)
                            {
                                //htmlBuilder.AppendLine("</tr>");
                                writer.RenderEndTag();
                            }
                        }
                    }

                    //htmlBuilder.AppendLine("</table>");
                    try
                    {
                        writer.RenderEndTag();
                    }
                    catch (Exception ex)
                    {
                        Exception eexx = ex;
                    }

                    string disclaimer = GetStrataChiSquareDisclaimer(grid.Tag.ToString()).Text;
                    if (!string.IsNullOrEmpty(disclaimer))
                    {
                        //htmlBuilder.AppendLine("<p></p>");
                        //htmlBuilder.AppendLine("<p>" + disclaimer.Replace("<", "&lt;") + "</p>");
                        writer.RenderBeginTag(HtmlTextWriterTag.P);
                        writer.RenderEndTag();
                        writer.RenderBeginTag(HtmlTextWriterTag.P);
                        writer.Write(disclaimer);
                        writer.RenderEndTag();
                    }

                    // End Chi Square
                }

                foreach (GadgetTwoByTwoPanel grid2x2 in this.strata2x2GridList)
                {
                    //string gridName = grid.Tag.ToString();
                    string gridName = string.Empty;
                    if (grid2x2.Tag != null)
                    {
                        gridName = grid2x2.Tag.ToString();
                    }
                    if (!string.IsNullOrEmpty(gridName))
                    {
                        //htmlBuilder.AppendLine("<h3>" + gridName + "</h3>");
                        writer.RenderBeginTag(HtmlTextWriterTag.H3);
                        writer.Write(gridName);
                        writer.RenderEndTag();

                    }
                    //htmlBuilder.AppendLine("<div style=\"height: 7px;\"></div>");
                    writer.AddAttribute(HtmlTextWriterAttribute.Style, "height: 7px;");
                    writer.RenderBeginTag(HtmlTextWriterTag.Div);
                    writer.RenderEndTag();
                    //htmlBuilder.AppendLine(grid2x2.ToHTML());
                    //htmlBuilder.AppendLine("<p></p>");
                    writer.Write(grid2x2.ToHTML());
                    writer.RenderBeginTag(HtmlTextWriterTag.P);
                    writer.RenderEndTag();
                }

                foreach (UIElement element in panelMain.Children)
                {
                    if (element is StratifiedTableAnalysisPanel)
                    {
                        StratifiedTableAnalysisPanel stap = element as StratifiedTableAnalysisPanel;
                        //htmlBuilder.AppendLine("<div style=\"height: 7px;\"></div>");
                        writer.AddAttribute(HtmlTextWriterAttribute.Style, "height: 7px;");
                        writer.RenderBeginTag(HtmlTextWriterTag.Div);
                        writer.RenderEndTag();

                        //htmlBuilder.AppendLine(stap.ToHTML());
                        //htmlBuilder.AppendLine("<p></p>");
                        writer.Write(stap.ToHTML());
                        writer.RenderBeginTag(HtmlTextWriterTag.P);
                        writer.RenderEndTag();
                    }
                }
                //return htmlBuilder.ToString();
                return stringWriter.ToString();
            }
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Processes all of the grid fields on a given form
        /// </summary>
        /// <param name="sourceView">The source form</param>
        /// <param name="destinationView">The destination form</param>        
        private void ProcessGridFields(View sourceView, View destinationView)
        {
            foreach (GridField gridField in sourceView.Fields.GridFields)
            {
                List<string> gridGUIDList = new List<string>();

                if (destinationView.Fields.GridFields.Contains(gridField.Name))
                {
                    int recordsUpdated = 0;
                    int recordsInserted = 0;
                    OnAddStatusMessage(string.Format(ImportExportSharedStrings.PROCESSING_GRID, gridField.Name));

                    try
                    {
                        List<string> gridColumnsToSkip = new List<string>();

                        string destinationGridTableName = destinationView.Fields.GridFields[gridField.Name].TableName;
                        GridField destinationGridField = destinationView.Fields.GridFields[gridField.Name];
                        IDataReader destinationGridTableReader = destinationProjectDataDriver.GetTableDataReader(destinationGridTableName);

                        foreach (GridColumnBase gridColumn in gridField.Columns)
                        {
                            bool found = false;
                            foreach (GridColumnBase destinationGridColumn in destinationGridField.Columns)
                            {
                                if (destinationGridColumn.Name.ToLower().Equals(gridColumn.Name.ToLower()))
                                {
                                    found = true;
                                }
                            }
                            if (!found)
                            {
                                gridColumnsToSkip.Add(gridColumn.Name);
                            }
                        }

                        string gridReference = sourceView.Name + ":" + gridField.Name;

                        if (GridColumnsToNull != null && GridColumnsToNull.ContainsKey(gridReference))
                        {
                            List<string> toNull = GridColumnsToNull[gridReference];

                            foreach (string s in toNull)
                            {
                                if (!gridColumnsToSkip.Contains(s))
                                {
                                    gridColumnsToSkip.Add(s);
                                }
                            }
                        }

                        while (destinationGridTableReader.Read())
                        {
                            gridGUIDList.Add(destinationGridTableReader["UniqueRowId"].ToString());
                        }

                        destinationGridTableReader.Close();
                        destinationGridTableReader.Dispose();

                        IDataReader sourceGridTableReader = sourceProjectDataDriver.GetTableDataReader(gridField.TableName);
                        while (sourceGridTableReader.Read())
                        {
                            string GUID = sourceGridTableReader["UniqueRowId"].ToString();
                            string FKEY = sourceGridTableReader["FKEY"].ToString();

                            if (sourceGUIDs != null && !sourceGUIDs.Contains(FKEY))
                            {
                                continue;
                            }

                            if (gridGUIDList.Contains(GUID) && update)
                            {
                                int columns = 0;
                                StringBuilder sb = new StringBuilder();
                                List<QueryParameter> fieldValueParams = new List<QueryParameter>();
                                sb.Append("UPDATE " + destinationProjectDataDriver.InsertInEscape(destinationGridTableName) + " SET ");
                                foreach (GridColumnBase gridColumn in gridField.Columns)
                                {
                                    object data = sourceGridTableReader[gridColumn.Name];
                                    if (data == null || string.IsNullOrEmpty(data.ToString()) || data == DBNull.Value)
                                    {
                                        continue; // don't update current data with null values (according to product requirements)
                                    }
                                    else if (gridColumnsToSkip.Contains(gridColumn.Name))
                                    {
                                        continue; // don't try and update a grid row that may not exist
                                    }

                                    sb.Append(destinationProjectDataDriver.InsertInEscape(gridColumn.Name));
                                    sb.Append(StringLiterals.EQUAL);
                                    sb.Append("@" + gridColumn.Name);
                                    switch (gridColumn.GridColumnType)
                                    {
                                        case MetaFieldType.Date:
                                        case MetaFieldType.DateTime:
                                        case MetaFieldType.Time:
                                            //sb.Append(destinationProjectDataDriver.FormatDateTime((DateTime)data));
                                            fieldValueParams.Add(new QueryParameter("@" + gridColumn.Name, DbType.DateTime, data));
                                            break;
                                        case MetaFieldType.CommentLegal:
                                        case MetaFieldType.LegalValues:
                                        case MetaFieldType.Codes:
                                        case MetaFieldType.Text:
                                        case MetaFieldType.TextUppercase:
                                        case MetaFieldType.PhoneNumber:
                                        case MetaFieldType.UniqueRowId:
                                        case MetaFieldType.ForeignKey:
                                        case MetaFieldType.GlobalRecordId:
                                            //sb.Append("'" + data.ToString().Replace("'", "''") + "'");
                                            fieldValueParams.Add(new QueryParameter("@" + gridColumn.Name, DbType.String, data));
                                            break;
                                        case MetaFieldType.Number:
                                        case MetaFieldType.RecStatus:
                                            fieldValueParams.Add(new QueryParameter("@" + gridColumn.Name, DbType.Single, data));
                                            break;
                                        default:
                                            throw new ApplicationException(string.Format(ImportExportSharedStrings.ERROR_GRID_COLUMN, gridColumn.Name));
                                    }
                                    sb.Append(StringLiterals.COMMA);
                                    columns++;
                                }

                                if (columns == 0)
                                {
                                    continue;
                                }

                                sb.Length = sb.Length - 1;

                                sb.Append(" WHERE ");
                                sb.Append("[UniqueRowId] = ");
                                sb.Append("'" + GUID + "'");

                                Query updateQuery = destinationProjectDataDriver.CreateQuery(sb.ToString());
                                updateQuery.Parameters = fieldValueParams;
                                destinationProjectDataDriver.ExecuteNonQuery(updateQuery);
                                recordsUpdated++;
                                OnSetProgress(1);
                                //this.BeginInvoke(new SetProgressBarDelegate(IncrementProgressBarValue), 1);

                            }
                            else if (!gridGUIDList.Contains(GUID) && append)
                            {
                                int columns = 0;
                                List<QueryParameter> fieldValueParams = new List<QueryParameter>();
                                WordBuilder fieldNames = new WordBuilder(",");
                                WordBuilder fieldValues = new WordBuilder(",");
                                foreach (GridColumnBase gridColumn in gridField.Columns)
                                {
                                    object data = sourceGridTableReader[gridColumn.Name];
                                    if (data == null || string.IsNullOrEmpty(data.ToString()) || data == DBNull.Value)
                                    {
                                        continue; // don't update current data with null values (according to product requirements)
                                    }
                                    else if (gridColumnsToSkip.Contains(gridColumn.Name))
                                    {
                                        continue; // don't try and update a grid row that may not exist
                                    }

                                    fieldNames.Add(destinationProjectDataDriver.InsertInEscape(gridColumn.Name));
                                    fieldValues.Add("@" + gridColumn.Name);

                                    switch (gridColumn.GridColumnType)
                                    {
                                        case MetaFieldType.Date:
                                        case MetaFieldType.DateTime:
                                        case MetaFieldType.Time:
                                            fieldValueParams.Add(new QueryParameter("@" + gridColumn.Name, DbType.DateTime, data));
                                            break;
                                        case MetaFieldType.CommentLegal:
                                        case MetaFieldType.LegalValues:
                                        case MetaFieldType.Codes:
                                        case MetaFieldType.Text:
                                        case MetaFieldType.TextUppercase:
                                        case MetaFieldType.PhoneNumber:
                                        case MetaFieldType.UniqueRowId:
                                        case MetaFieldType.ForeignKey:
                                        case MetaFieldType.GlobalRecordId:
                                            fieldValueParams.Add(new QueryParameter("@" + gridColumn.Name, DbType.String, data));
                                            break;
                                        case MetaFieldType.Number:
                                        case MetaFieldType.RecStatus:
                                            fieldValueParams.Add(new QueryParameter("@" + gridColumn.Name, DbType.Single, data));
                                            break;
                                        default:
                                            throw new ApplicationException(string.Format(ImportExportSharedStrings.ERROR_GRID_COLUMN, gridColumn.Name));
                                    }
                                    columns++;
                                }

                                if (columns == 0)
                                {
                                    continue;
                                }

                                StringBuilder sb = new StringBuilder();
                                sb.Append("INSERT INTO " + destinationProjectDataDriver.InsertInEscape(destinationGridTableName));
                                sb.Append(StringLiterals.SPACE);
                                sb.Append(Util.InsertInParantheses(fieldNames.ToString()));
                                sb.Append(" values (");
                                sb.Append(fieldValues.ToString());
                                sb.Append(") ");
                                Query insertQuery = destinationProjectDataDriver.CreateQuery(sb.ToString());
                                insertQuery.Parameters = fieldValueParams;

                                destinationProjectDataDriver.ExecuteNonQuery(insertQuery);
                                OnSetProgress(1);
                                //this.BeginInvoke(new SetProgressBarDelegate(IncrementProgressBarValue), 1);
                                recordsInserted++;
                            }
                            OnSetProgress(1);
                        } // end while source data reader reads

                        sourceGridTableReader.Close();
                        sourceGridTableReader.Dispose();

                        if (update && append)
                        {
                            OnAddStatusMessage(string.Format(ImportExportSharedStrings.IMPORT_GRID_UPDATED_AND_APPENDED, gridField.Name, recordsInserted.ToString(), recordsUpdated.ToString()));
                        }
                        else if (update && !append)
                        {
                            OnAddStatusMessage(string.Format(ImportExportSharedStrings.IMPORT_GRID_UPDATED, gridField.Name, recordsUpdated.ToString()));
                        }
                        else if (!update && append)
                        {
                            OnAddStatusMessage(string.Format(ImportExportSharedStrings.IMPORT_GRID_APPENDED, gridField.Name, recordsInserted.ToString()));
                        }
                    }
                    catch (Exception ex)
                    {
                        OnAddStatusMessage(string.Format(ImportExportSharedStrings.ERROR_WITH_MESSAGE, ex.Message));
                    }
                } // end if contains
            }
        }
        /// <summary>
        /// Converts the gadget's output to Html
        /// </summary>
        /// <returns></returns>
        public override string ToHTML(string htmlFileName = "", int count = 0)
        {
            if (IsCollapsed) return string.Empty;

            StringBuilder htmlBuilder = new StringBuilder();
            ComplexSampleCrosstabParameters cscrossParameters = (ComplexSampleCrosstabParameters)Parameters;
            CustomOutputHeading = headerPanel.Text;
            CustomOutputDescription = descriptionPanel.Text;

            if (CustomOutputHeading == null || (string.IsNullOrEmpty(CustomOutputHeading) && !CustomOutputHeading.Equals("(none)")))
            {
                htmlBuilder.AppendLine("<h2 class=\"gadgetHeading\">Complex Sample Tables</h2>");
            }
            else if(CustomOutputHeading != "(none)")
            {
                htmlBuilder.AppendLine("<h2 class=\"gadgetHeading\">" + CustomOutputHeading + "</h2>");
            }

            htmlBuilder.AppendLine("<p class=\"gadgetOptions\"><small>");
            htmlBuilder.AppendLine("<em>Exposure variable:</em> <strong>" + cscrossParameters.ColumnNames[0] + "</strong>");
            htmlBuilder.AppendLine("<br />");
            htmlBuilder.AppendLine("<em>Outcome variable:</em> <strong>" + cscrossParameters.CrosstabVariableName + "</strong>");
            htmlBuilder.AppendLine("<br />");
            htmlBuilder.AppendLine("<em>PSU variable:</em> <strong>" + cscrossParameters.PSUVariableName + "</strong>");
            htmlBuilder.AppendLine("<br />");

            if (!String.IsNullOrEmpty(cscrossParameters.WeightVariableName))
            {
                htmlBuilder.AppendLine("<em>Weight variable:</em> <strong>" + cscrossParameters.WeightVariableName + "</strong>");
                htmlBuilder.AppendLine("<br />");
            }
            if (cscrossParameters.StrataVariableNames.Count > 0)
            {
                WordBuilder wb = new WordBuilder(", ");
                foreach (string s in cscrossParameters.StrataVariableNames)
                {
                    wb.Add(s);
                }
                htmlBuilder.AppendLine("<em>Strata variable:</em> <strong>" + wb.ToString() + "</strong>");
                htmlBuilder.AppendLine("<br />");
            }
            //htmlBuilder.AppendLine("<em>Include missing:</em> <strong>" + checkboxIncludeMissing.IsChecked.ToString() + "</strong>");
            //htmlBuilder.AppendLine("<br />");
            htmlBuilder.AppendLine("</small></p>");

            if (!string.IsNullOrEmpty(CustomOutputDescription))
            {
                htmlBuilder.AppendLine("<p class=\"gadgetsummary\">" + CustomOutputDescription + "</p>");
            }

            if (!string.IsNullOrEmpty(messagePanel.Text) && messagePanel.Visibility == Visibility.Visible)
            {
                htmlBuilder.AppendLine("<p><small><strong>" + messagePanel.Text + "</strong></small></p>");
            }

            if (!string.IsNullOrEmpty(txtFilterString.Text) && txtFilterString.Visibility == Visibility.Visible)
            {
                htmlBuilder.AppendLine("<p><small><strong>" + txtFilterString.Text + "</strong></small></p>");
            }

            foreach (Grid grid in this.StrataGridList)
            {
                string gridName = grid.Tag.ToString();

                htmlBuilder.AppendLine("<div style=\"height: 7px;\"></div>");
                htmlBuilder.AppendLine("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\">");

                htmlBuilder.AppendLine("<tr>");

                htmlBuilder.AppendLine("    <th rowspan=\"2\">");
                htmlBuilder.AppendLine(cscrossParameters.ColumnNames[0]);
                htmlBuilder.AppendLine("    </th>");

                htmlBuilder.AppendLine("    <th style=\"text-align: center;\" colspan=\"" + (grid.ColumnDefinitions.Count - 2).ToString() + "\">");
                htmlBuilder.AppendLine(cscrossParameters.CrosstabVariableName);
                htmlBuilder.AppendLine("    </th>");

                htmlBuilder.AppendLine("    <th rowspan=\"2\">");
                htmlBuilder.AppendLine(SharedStrings.TOTAL);
                htmlBuilder.AppendLine("    </th>");

                htmlBuilder.AppendLine("</tr>");

                htmlBuilder.AppendLine("<tr>");

                for (int j = 1; j < grid.ColumnDefinitions.Count - 1; j++)
                {
                    IEnumerable<UIElement> elements = grid.Children.Cast<UIElement>().Where(x => Grid.GetRow(x) == 1 && Grid.GetColumn(x) == j);
                    TextBlock txt = null;
                    foreach (UIElement element in elements)
                    {
                        if (element is TextBlock)
                        {
                            txt = element as TextBlock;
                        }
                    }

                    string value = "&nbsp;";

                    if (txt != null)
                    {
                        value = txt.Text;
                    }

                    htmlBuilder.AppendLine("<th>" + value + "</th>");
                }

                htmlBuilder.AppendLine("</tr>");

                for(int i = 2; i < grid.RowDefinitions.Count; i++)
                {
                    for (int j = 0; j < grid.ColumnDefinitions.Count; j++)
                    {
                        string tableDataTagOpen = "<td>";
                        string tableDataTagClose = "</td>";

                        if (j == 0)
                        {
                            htmlBuilder.AppendLine("<tr>");
                        }
                        if (j == 0 && i > 0)
                        {
                            tableDataTagOpen = "<td class=\"value\">";
                        }

                        IEnumerable<UIElement> elements = grid.Children.Cast<UIElement>().Where(x => Grid.GetRow(x) == i && Grid.GetColumn(x) == j);
                        TextBlock txt = null;
                        foreach (UIElement element in elements)
                        {
                            if (element is TextBlock)
                            {
                                txt = element as TextBlock;
                            }
                        }

                        string value = "&nbsp;";

                        if (txt != null)
                        {
                            value = txt.Text;
                        }

                        htmlBuilder.AppendLine(tableDataTagOpen + value + tableDataTagClose);

                        if (j >= grid.ColumnDefinitions.Count - 1)
                        {
                            htmlBuilder.AppendLine("</tr>");
                        }
                    }
                }
                htmlBuilder.AppendLine("</table>");
            }

            foreach (UIElement element in panelMain.Children)
            {
                if (element is Grid && (element as Grid).Tag.ToString() == "2x2 grid")
                {
                    Grid statGrid = element as Grid;
                    htmlBuilder.AppendLine("<h3>");
                    htmlBuilder.AppendLine("CTABLES COMPLEX SAMPLE DESIGN ANALYSIS OF 2 X 2 TABLE");
                    htmlBuilder.AppendLine("</h3>");
                    htmlBuilder.AppendLine("<div style=\"height: 7px;\"></div>");
                    htmlBuilder.AppendLine("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\">");

                    for (int i = 1; i < statGrid.RowDefinitions.Count; i++)
                    {
                        for (int j = 0; j < statGrid.ColumnDefinitions.Count; j++)
                        {
                            string tableDataTagOpen = "<td>";
                            string tableDataTagClose = "</td>";

                            if (j == 0)
                            {
                                htmlBuilder.AppendLine("<tr>");
                            }
                            if (j == 0 && i > 0)
                            {
                                tableDataTagOpen = "<td class=\"value\">";
                            }

                            IEnumerable<UIElement> elements = statGrid.Children.Cast<UIElement>().Where(x => Grid.GetRow(x) == i && Grid.GetColumn(x) == j);
                            TextBlock txt = null;
                            foreach (UIElement e in elements)
                            {
                                if (e is TextBlock)
                                {
                                    txt = e as TextBlock;
                                }
                            }

                            string value = "&nbsp;";

                            if (txt != null)
                            {
                                value = txt.Text;
                            }

                            htmlBuilder.AppendLine(tableDataTagOpen + value + tableDataTagClose);

                            if (j >= statGrid.ColumnDefinitions.Count - 1)
                            {
                                htmlBuilder.AppendLine("</tr>");
                            }
                        }
                    }
                    htmlBuilder.AppendLine("</table>");
                }
            }

            return htmlBuilder.ToString();
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Converts the gadget's output to Html
        /// </summary>
        /// <returns></returns>
        public override string ToHTML(string htmlFileName = "", int count = 0)
        {
            if (IsCollapsed) return string.Empty;

            StringBuilder htmlBuilder = new StringBuilder();
            CustomOutputHeading = headerPanel.Text;
            CustomOutputDescription = descriptionPanel.Text;

            if (CustomOutputHeading == null || (string.IsNullOrEmpty(CustomOutputHeading) && !CustomOutputHeading.Equals("(none)")))
            {
                htmlBuilder.AppendLine("<h2 class=\"gadgetHeading\">Frequency</h2>");
            }
            else if (CustomOutputHeading != "(none)")
            {
                htmlBuilder.AppendLine("<h2 class=\"gadgetHeading\">" + CustomOutputHeading + "</h2>");
            }

            htmlBuilder.AppendLine("<p class=\"gadgetOptions\"><small>");
            htmlBuilder.AppendLine("<em>Frequency variable:</em> <strong>" + cbxField.Text + "</strong>");
            htmlBuilder.AppendLine("<br />");

            if (cbxFieldWeight.SelectedIndex >= 0)
            {
                htmlBuilder.AppendLine("<em>Weight variable:</em> <strong>" + cbxFieldWeight.Text + "</strong>");
                htmlBuilder.AppendLine("<br />");
            }
            //if (cbxFieldStrata.SelectedIndex >= 0)
            //{
            //    htmlBuilder.AppendLine("<em>Strata variable:</em> <strong>" + cbxFieldStrata.Text + "</strong>");
            //    htmlBuilder.AppendLine("<br />");
            //}
            if (lbxFieldStrata.SelectedItems.Count > 0)
            {
                WordBuilder wb = new WordBuilder(", ");
                foreach (string s in lbxFieldStrata.SelectedItems)
                {
                    wb.Add(s);
                }
                htmlBuilder.AppendLine("<em>Strata variable(s):</em> <strong>" + wb.ToString() + "</strong>");
                htmlBuilder.AppendLine("<br />");
            }

            htmlBuilder.AppendLine("<em>Include missing:</em> <strong>" + checkboxIncludeMissing.IsChecked.ToString() + "</strong>");
            htmlBuilder.AppendLine("<br />");
            htmlBuilder.AppendLine("</small></p>");

            if (!string.IsNullOrEmpty(CustomOutputDescription))
            {
                htmlBuilder.AppendLine("<p class=\"gadgetsummary\">" + CustomOutputDescription + "</p>");
            }

            if (!string.IsNullOrEmpty(messagePanel.Text) && messagePanel.Visibility == Visibility.Visible)
            {
                htmlBuilder.AppendLine("<p><small><strong>" + messagePanel.Text + "</strong></small></p>");
            }

            if (!string.IsNullOrEmpty(infoPanel.Text) && infoPanel.Visibility == Visibility.Visible)
            {
                htmlBuilder.AppendLine("<p><small><strong>" + infoPanel.Text + "</strong></small></p>");
            }

            foreach (Grid grid in this.StrataGridList)
            {
                string gridName = grid.Tag.ToString();

                string summaryText = "This tables represents the frequency of the field " + cbxField.Text + ". ";
                if (!string.IsNullOrEmpty(cbxFieldWeight.Text)) { summaryText += "The field " + cbxFieldWeight.Text + " has been specified as a weight. "; }
                if (lbxFieldStrata.SelectedItems.Count > 0) { summaryText += "The frequency data has been stratified. The data in this table is for the strata value " + grid.Tag.ToString() + ". "; }
                summaryText += "Each non-heading row in the table represents one of the distinct frequency values. The last row contains the total.";

                htmlBuilder.AppendLine("<div style=\"height: 7px;\"></div>");
                htmlBuilder.AppendLine("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" summary=\"" + summaryText + "\">");

                if (string.IsNullOrEmpty(CustomOutputCaption))
                {
                    if (lbxFieldStrata.SelectedItems.Count > 0)
                    {
                        htmlBuilder.AppendLine("<caption>" + grid.Tag + "</caption>");
                    }
                }
                else
                {
                    htmlBuilder.AppendLine("<caption>" + CustomOutputCaption + "</caption>");
                }

                for (int i = 0; i < grid.RowDefinitions.Count; i++)
                {
                    for (int j = 0; j < grid.ColumnDefinitions.Count; j++)
                    {
                        string tableDataTagOpen = "<td>";
                        string tableDataTagClose = "</td>";

                        if (i == 0)
                        {
                            tableDataTagOpen = "<th>";
                            tableDataTagClose = "</th>";
                        }

                        if (j == 0)
                        {
                            htmlBuilder.AppendLine("<tr>");
                        }
                        if (j == 0 && i > 0)
                        {
                            tableDataTagOpen = "<td class=\"value\">";
                        }

                        ColumnDefinition colDef = grid.ColumnDefinitions[j];
                        if (colDef.Width.Value > 0)
                        {
                            IEnumerable<UIElement> elements = grid.Children.Cast<UIElement>().Where(x => Grid.GetRow(x) == i && Grid.GetColumn(x) == j);
                            TextBlock txt = null;
                            Rectangle rct = null;
                            foreach (UIElement element in elements)
                            {
                                if (element is TextBlock)
                                {
                                    txt = element as TextBlock;
                                }
                                else if (element is Rectangle)
                                {
                                    rct = element as Rectangle;
                                }
                            }

                            if (rct != null && j > 0 && i > 0)
                            {
                                double barWidth = rct.ActualWidth;
                                htmlBuilder.AppendLine("<td class=\"value\"><div class=\"percentBar\" style=\"width: " + ((int)barWidth * 2).ToString() + "px;\"></td>");
                            }
                            else
                            {
                                string value = "&nbsp;";

                                if (txt != null)
                                {
                                    value = txt.Text;
                                }

                                if (i == grid.RowDefinitions.Count - 1)
                                {
                                    htmlBuilder.AppendLine(tableDataTagOpen + "<b>" + value + "</b>" + tableDataTagClose);
                                }
                                else
                                {
                                    htmlBuilder.AppendLine(tableDataTagOpen + value + tableDataTagClose);
                                }
                            }
                        }

                        if (j >= grid.ColumnDefinitions.Count - 1)
                        {
                            htmlBuilder.AppendLine("</tr>");
                        }
                    }
                }

                htmlBuilder.AppendLine("</table>");
            }
            return htmlBuilder.ToString();
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Generates Xml representation of this gadget
        /// </summary>
        /// <param name="doc">The Xml docment</param>
        /// <returns>XmlNode</returns>
        public override XmlNode Serialize(XmlDocument doc)
        {
            FrequencyParameters freqParameters = (FrequencyParameters)Parameters;

            System.Xml.XmlElement element = doc.CreateElement("frequencyGadget");
            string xmlString = string.Empty;
            element.InnerXml = xmlString;
            element.AppendChild(SerializeFilters(doc));

            System.Xml.XmlAttribute id = doc.CreateAttribute("id");
            System.Xml.XmlAttribute locationY = doc.CreateAttribute("top");
            System.Xml.XmlAttribute locationX = doc.CreateAttribute("left");
            System.Xml.XmlAttribute collapsed = doc.CreateAttribute("collapsed");
            System.Xml.XmlAttribute type = doc.CreateAttribute("gadgetType");

            id.Value = this.UniqueIdentifier.ToString();
            locationY.Value = Canvas.GetTop(this).ToString("F0");
            locationX.Value = Canvas.GetLeft(this).ToString("F0");
            collapsed.Value = IsCollapsed.ToString();
            type.Value = "EpiDashboard.FrequencyControl";

            element.Attributes.Append(locationY);
            element.Attributes.Append(locationX);
            element.Attributes.Append(collapsed);
            element.Attributes.Append(type);
            element.Attributes.Append(id);

            WordBuilder wb = new WordBuilder(",");
            if (freqParameters.ShowFrequencyCol) wb.Add("1");
            if (freqParameters.ShowPercentCol) wb.Add("2");
            if (freqParameters.ShowCumPercentCol) wb.Add("3");
            if (freqParameters.Show95CILowerCol) wb.Add("4");
            if (freqParameters.Show95CIUpperCol) wb.Add("5");
            if (freqParameters.ShowPercentBarsCol) wb.Add("6");

            this.CustomOutputHeading = freqParameters.GadgetTitle;
            this.CustomOutputDescription = freqParameters.GadgetDescription;

            XmlElement freqVarElements = doc.CreateElement("mainVariables");

            foreach (var mainVar in freqParameters.ColumnNames)
            {
            XmlElement freqVarElement = doc.CreateElement("mainVariable");
            if (freqParameters.ColumnNames.Count > 0)
            {
                    if (!String.IsNullOrEmpty(mainVar.ToString()))
                {
                        freqVarElement.InnerText = mainVar.ToString();
                        freqVarElements.AppendChild(freqVarElement);
                    }
                }
            }
            element.AppendChild(freqVarElements);
            // =========  Former Advanced Options section  ============
            //weightVariable
            XmlElement weightVariableElement = doc.CreateElement("weightVariable");
            if (!String.IsNullOrEmpty(freqParameters.WeightVariableName))
            {
                weightVariableElement.InnerText = freqParameters.WeightVariableName;
                element.AppendChild(weightVariableElement);
            }

            XmlElement StrataVariableNameElement = doc.CreateElement("strataVariable");
            XmlElement StrataVariableNamesElement = doc.CreateElement("strataVariables");
            if (freqParameters.StrataVariableNames.Count == 1)
            {
                StrataVariableNameElement.InnerText = freqParameters.StrataVariableNames[0].ToString();
                element.AppendChild(StrataVariableNameElement);
            }
            else if (freqParameters.StrataVariableNames.Count > 1)
            {
                foreach (string strataColumn in freqParameters.StrataVariableNames)
                {
                    XmlElement strataElement = doc.CreateElement("strataVariable");
                    strataElement.InnerText = strataColumn.Replace("<", "&lt;");
                    StrataVariableNamesElement.AppendChild(strataElement);
                }

                element.AppendChild(StrataVariableNamesElement);
            }

            //showAllListValues
            XmlElement allValuesElement = doc.CreateElement("allValues");
            allValuesElement.InnerText = freqParameters.ShowAllListValues.ToString();
            element.AppendChild(allValuesElement);

            //showListLabels
            XmlElement showListLabelsElement = doc.CreateElement("showListLabels");
            showListLabelsElement.InnerText = freqParameters.ShowCommentLegalLabels.ToString();
            element.AppendChild(showListLabelsElement);

            //sort
            XmlElement sortElement = doc.CreateElement("sort");
            if (freqParameters.SortHighToLow) sortElement.InnerText = "hightolow";
            element.AppendChild(sortElement);

            //includeMissing
            XmlElement includeMissingElement = doc.CreateElement("includeMissing");
            includeMissingElement.InnerText = freqParameters.IncludeMissing.ToString();
            element.AppendChild(includeMissingElement);

            // =========  Former Display Options section  ============

            //useFieldPrompts
            XmlElement useFieldPromptsElement = doc.CreateElement("useFieldPrompts");
            useFieldPromptsElement.InnerText = freqParameters.UseFieldPrompts.ToString();
            element.AppendChild(useFieldPromptsElement);

            //drawBorders
            XmlElement drawBordersElement = doc.CreateElement("drawBorders");
            drawBordersElement.InnerText = freqParameters.DrawBorders.ToString();
            element.AppendChild(drawBordersElement);

            //drawHeaderRow
            XmlElement drawHeaderRowElement = doc.CreateElement("drawHeaderRow");
            drawHeaderRowElement.InnerText = freqParameters.DrawHeaderRow.ToString();
            element.AppendChild(drawHeaderRowElement);

            //drawTotalRow
            XmlElement drawTotalRowElement = doc.CreateElement("drawTotalRow");
            drawTotalRowElement.InnerText = freqParameters.DrawTotalRow.ToString();
            element.AppendChild(drawTotalRowElement);

            //precision
            int precision = 2;
            bool precision_success = int.TryParse(freqParameters.Precision.ToString(), out precision);
            XmlElement precisionElement = doc.CreateElement("precision");
            if (precision_success)
            {
                precisionElement.InnerText = precision.ToString();
            }
            else
            {
                precisionElement.InnerText = "2";
                freqParameters.Precision = "2";
            }
            element.AppendChild(precisionElement);

            //rowsToDisplay
            string rowsToDisplay = String.Empty;
            XmlElement rowsToDisplayElement = doc.CreateElement("rowsToDisplay");
            if (freqParameters.RowsToDisplay.HasValue)
            {
                if (freqParameters.RowsToDisplay > 0)
                {
                    rowsToDisplay = freqParameters.RowsToDisplay.ToString();
                    rowsToDisplayElement.InnerText = rowsToDisplay;
                }
            }
            element.AppendChild(rowsToDisplayElement);

            //percentBarWidth
            XmlElement percentBarWidthElement = doc.CreateElement("percentBarWidth");
            int percentBarWidth = 100;
            bool success = int.TryParse(freqParameters.PercentBarWidth.ToString(), out percentBarWidth);
            if (success)
            {
                percentBarWidthElement.InnerText = freqParameters.PercentBarWidth.ToString();
            }
            else
            {
                percentBarWidthElement.InnerText = "100";
                freqParameters.PercentBarWidth = 100;
            }
            element.AppendChild(percentBarWidthElement);

            //columnsToShow
            XmlElement columnsToShowElement = doc.CreateElement("columnsToShow");
            columnsToShowElement.InnerText = wb.ToString();
            element.AppendChild(columnsToShowElement);

            //customHeading
            XmlElement customHeadingElement = doc.CreateElement("customHeading");
            customHeadingElement.InnerText = freqParameters.GadgetTitle; //CustomOutputHeading.Replace("<", "&lt;");
            element.AppendChild(customHeadingElement);

            //customDescription
            XmlElement customDescriptionElement = doc.CreateElement("customDescription");
            customDescriptionElement.InnerText = freqParameters.GadgetDescription; //CustomOutputDescription.Replace("<", "&lt;");
            element.AppendChild(customDescriptionElement);

            //customCaption
            XmlElement customCaptionElement = doc.CreateElement("customCaption");
            customCaptionElement.InnerText = CustomOutputCaption;
            element.AppendChild(customCaptionElement);

            SerializeAnchors(element);

            return element;
        }
        void computeWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            Result        result     = new Result();
            EpiDataHelper DataHelper = e.Argument as EpiDataHelper;

            if (DataHelper != null && DataHelper.Project != null && DataHelper.Project.CollectedData != null)
            {
                IDbDriver db    = DataHelper.Project.CollectedData.GetDatabase();
                int       total = (from caseVM in DataHelper.CaseCollection
                                   where caseVM.EpiCaseDef != Core.Enums.EpiCaseClassification.Excluded
                                   select caseVM).Count();
                string format = "P1";

                int count = (from caseVM in DataHelper.CaseCollection
                             where caseVM.FinalLabClass == Core.Enums.FinalLabClassification.ConfirmedAcute && caseVM.EpiCaseDef != Core.Enums.EpiCaseClassification.Excluded
                             select caseVM).Count();

                result.ConfirmedAcuteCount   = count.ToString();
                result.ConfirmedAcutePercent = ((double)count / (double)total).ToString(format);

                count = (from caseVM in DataHelper.CaseCollection
                         where caseVM.FinalLabClass == Core.Enums.FinalLabClassification.ConfirmedConvalescent && caseVM.EpiCaseDef != Core.Enums.EpiCaseClassification.Excluded
                         select caseVM).Count();

                result.ConfirmedConvalescentCount   = count.ToString();
                result.ConfirmedConvalescentPercent = ((double)count / (double)total).ToString(format);

                count = (from caseVM in DataHelper.CaseCollection
                         where caseVM.FinalLabClass == Core.Enums.FinalLabClassification.NotCase && caseVM.EpiCaseDef != Core.Enums.EpiCaseClassification.Excluded
                         select caseVM).Count();

                result.NegativeCount   = count.ToString();
                result.NegativePercent = ((double)count / (double)total).ToString(format);

                count = (from caseVM in DataHelper.CaseCollection
                         where caseVM.FinalLabClass == Core.Enums.FinalLabClassification.Indeterminate && caseVM.EpiCaseDef != Core.Enums.EpiCaseClassification.Excluded
                         select caseVM).Count();

                result.IndeterminateCount   = count.ToString();
                result.IndeterminatePercent = ((double)count / (double)total).ToString(format);

                count = (from caseVM in DataHelper.CaseCollection
                         where caseVM.FinalLabClass == Core.Enums.FinalLabClassification.NeedsFollowUpSample && caseVM.EpiCaseDef != Core.Enums.EpiCaseClassification.Excluded
                         select caseVM).Count();

                result.NeedsFollowUpCount   = count.ToString();
                result.NeedsFollowUpPercent = ((double)count / (double)total).ToString(format);

                Epi.Fields.RenderableField finalLabClassField = DataHelper.CaseForm.Fields["FinalLabClass"] as Epi.Fields.RenderableField;
                Epi.Fields.RenderableField epiCaseDefField    = DataHelper.CaseForm.Fields["EpiCaseDef"] as Epi.Fields.RenderableField;

                if (finalLabClassField != null && epiCaseDefField != null && finalLabClassField.Page != null && epiCaseDefField.Page != null)
                {
                    string finalLabClassTableName = finalLabClassField.Page.TableName;
                    string epiCaseClassTableName  = epiCaseDefField.Page.TableName;

                    string queryText = "";
                    if (db.ToString().ToLower().Contains("sql"))
                    {
                        queryText = "select count(*) from " + finalLabClassTableName + " AS crf INNER JOIN " + epiCaseClassTableName + " AS crfEpiCaseClass on crf.GlobalRecordId = crfEpiCaseClass.GlobalRecordId INNER JOIN LaboratoryResultsForm lrf on crf.GlobalRecordId = lrf.FKEY where ((crf.FinalLabClass = '' OR crf.FinalLabClass is null) AND (crfEpiCaseClass.EpiCaseDef <> '4'))";
                    }
                    else
                    {
                        queryText = "select count(*) from ((" + finalLabClassTableName + " AS crf) INNER JOIN " + epiCaseClassTableName + " AS crfEpiCaseClass on crf.GlobalRecordId = crfEpiCaseClass.GlobalRecordId) INNER JOIN LaboratoryResultsForm lrf on crf.GlobalRecordId = lrf.FKEY where ((crf.FinalLabClass = '' OR crf.FinalLabClass is null) AND (crfEpiCaseClass.EpiCaseDef <> '4'))";
                    }
                    Query selectQuery = db.CreateQuery(queryText);
                    count = (int)db.ExecuteScalar(selectQuery);

                    if (db.ToString().ToLower().Contains("sql"))
                    {
                        queryText = "select crfEpiCaseClass.ID from " + finalLabClassTableName + " AS crf INNER JOIN " + epiCaseClassTableName + " AS crfEpiCaseClass on crf.GlobalRecordId = crfEpiCaseClass.GlobalRecordId INNER JOIN LaboratoryResultsForm lrf on crf.GlobalRecordId = lrf.FKEY where ((crf.FinalLabClass = '' OR crf.FinalLabClass is null) AND (crfEpiCaseClass.EpiCaseDef <> '4'))";
                    }
                    else
                    {
                        queryText = "select crfEpiCaseClass.ID from ((" + finalLabClassTableName + " AS crf) INNER JOIN " + epiCaseClassTableName + " AS crfEpiCaseClass on crf.GlobalRecordId = crfEpiCaseClass.GlobalRecordId) INNER JOIN LaboratoryResultsForm lrf on crf.GlobalRecordId = lrf.FKEY where ((crf.FinalLabClass = '' OR crf.FinalLabClass is null) AND (crfEpiCaseClass.EpiCaseDef <> '4'))";
                    }
                    selectQuery = db.CreateQuery(queryText);
                    DataTable   dt = db.Select(selectQuery);
                    WordBuilder wb = new WordBuilder(",");

                    foreach (DataRow row in dt.Rows)
                    {
                        wb.Add(row["ID"].ToString());
                    }

                    result.PendingIDs = wb.ToString();

                    result.PendingCount   = count.ToString();
                    result.PendingPercent = ((double)count / (double)total).ToString(format);

                    if (db.ToString().ToLower().Contains("sql"))
                    {
                        queryText = "select count(*) from CaseInformationForm AS crf LEFT JOIN " + epiCaseClassTableName + " AS crfEpiCaseClass on crf.GlobalRecordId = crfEpiCaseClass.GlobalRecordId LEFT JOIN LaboratoryResultsForm lrf on crf.GlobalRecordId = lrf.FKEY where ((lrf.GlobalRecordId = '' OR lrf.GlobalRecordId is null) AND (crfEpiCaseClass.EpiCaseDef <> '4') AND crf.RecStatus = 1)";
                    }
                    else
                    {
                        queryText = "select count(*) from ((CaseInformationForm AS crf) LEFT JOIN " + epiCaseClassTableName + " AS crfEpiCaseClass on crf.GlobalRecordId = crfEpiCaseClass.GlobalRecordId) LEFT JOIN LaboratoryResultsForm lrf on crf.GlobalRecordId = lrf.FKEY where ((lrf.GlobalRecordId = '' OR lrf.GlobalRecordId is null) AND (crfEpiCaseClass.EpiCaseDef <> '4') AND crf.RecStatus = 1)";
                    }
                    selectQuery = db.CreateQuery(queryText);
                    count       = (int)db.ExecuteScalar(selectQuery);

                    result.NotSampledCount   = count.ToString();
                    result.NotSampledPercent = ((double)count / (double)total).ToString(format);

                    e.Result = result;
                }
                else
                {
                    throw new InvalidOperationException("FinalLabClass and EpiCaseDef must both be non-null fields in computeWorker_doWork in LabClassAllPatients.xaml.cs");
                }
            }
        }
Ejemplo n.º 30
0
 /// <summary>
 /// Returns contents of a table.
 /// </summary>
 /// <param name="tableName"></param>
 /// <param name="columnNames">List of column names to select. Column names should not be bracketed; this method will add brackets.</param>
 /// <returns>DataTable</returns>
 public virtual DataTable GetTableData(string tableName, List<string> columnNames)
 {
     WordBuilder wb = new WordBuilder(",");
     foreach (string s in columnNames)
     {
         wb.Add(this.InsertInEscape(s));
     }
     return GetTableData(tableName, wb.ToString(), string.Empty);
 }
Ejemplo n.º 31
0
        /// <summary>
        /// Gets table column names for a view.
        /// </summary>
        /// <param name="viewId">Id of the <see cref="Epi.View"/></param>
        /// <returns>string</returns>
        public string GetTableColumnNames(int viewId)
        {
            try
            {
                Query selectQuery = db.CreateQuery("select [Name] from [metaFields] " +
                    "where [ViewId] = @ViewID and " +
                    "[FieldTypeId] not in (2,13,15,20) " +
                    "order by [Name]");
                selectQuery.Parameters.Add(new QueryParameter("@ViewID", DbType.Int32, viewId));
                WordBuilder list = new WordBuilder(StringLiterals.COMMA);

                DataTable columns = db.Select(selectQuery);
                foreach (DataRow row in columns.Rows)
                {
                    list.Add(row[ColumnNames.NAME].ToString());
                }
                return list.ToString();
            }
            catch (Exception ex)
            {
                throw new GeneralException("Could not retrieve table column names", ex);
            }
        }
        /// <summary>
        /// Used to generate the list of variables and options for the GadgetParameters object
        /// </summary>
        protected override void CreateInputVariableList()
        {
            // Set data filters!
            this.DataFilters = RowFilterControl.DataFilters;

            //Parameters.ColumnNames used for the "Additional Variables to Display"
            Parameters.ColumnNames    = new List <string>();
            Parameters.KeyColumnNames = new List <string>();

            Parameters.SortVariables = new Dictionary <string, SortOrder>();

            Parameters.GadgetTitle       = txtTitle.Text;
            Parameters.GadgetDescription = txtDesc.Text;

            double height = 0;
            double width  = 0;

            bool success = double.TryParse(txtMaxHeight.Text, out height);

            if (success)
            {
                Parameters.Height = height;
            }

            success = double.TryParse(txtMaxWidth.Text, out width);
            if (success)
            {
                Parameters.Width = width;
            }

            List <string> listFields = new List <string>();

            if (lvVariables.SelectedItems.Count > 0)
            {
                foreach (FieldInfo fieldInfo in lvVariables.SelectedItems)
                {
                    if (!string.IsNullOrEmpty(fieldInfo.Name))
                    {
                        listFields.Add(fieldInfo.Name);
                    }
                }
            }

            listFields.Sort();
            foreach (string field in listFields)
            {
                if (!string.IsNullOrEmpty(field) && !Parameters.KeyColumnNames.Contains(field))
                {
                    Parameters.KeyColumnNames.Add(field);
                }
            }

            List <string> displayListFields = new List <string>();

            if (lvDisplayVariables.SelectedItems.Count > 0)
            {
                foreach (FieldInfo fieldInfo in lvDisplayVariables.SelectedItems)
                {
                    if (!string.IsNullOrEmpty(fieldInfo.Name))
                    {
                        displayListFields.Add(fieldInfo.Name);
                    }
                }
            }

            displayListFields.Sort();

            foreach (string field in displayListFields)
            {
                Parameters.ColumnNames.Add(field);
            }

            Parameters.SortColumnsByTabOrder  = checkboxTabOrder.IsChecked.Value;
            Parameters.UseFieldPrompts        = checkboxUsePrompts.IsChecked.Value;
            Parameters.ShowColumnHeadings     = checkboxColumnHeaders.IsChecked.Value;
            Parameters.ShowLineColumn         = checkboxLineColumn.IsChecked.Value;
            Parameters.ShowNullLabels         = checkboxShowNulls.IsChecked.Value;
            Parameters.ShowCommentLegalLabels = checkboxListLabels.IsChecked.Value;

            if (lbxSortOrder.Items.Count > 0)
            {
                foreach (string item in lbxSortOrder.Items)
                {
                    if (!string.IsNullOrEmpty(item))
                    {
                        //string baseStr = item;

                        //if (baseStr.EndsWith("(ascending)"))
                        //{
                        //    baseStr = "[" + baseStr.Remove(baseStr.Length - 12) + "] ASC";
                        //}
                        //if (baseStr.EndsWith("(descending)"))
                        //{
                        //    baseStr = "[" + baseStr.Remove(baseStr.Length - 13) + "] DESC";
                        //}
                        //inputVariableList.Add(baseStr, "sortfield");

                        string baseStr = item;

                        if (baseStr.EndsWith("(ascending)"))
                        {
                            baseStr = baseStr.Remove(baseStr.Length - 12);
                            Parameters.SortVariables.Add(baseStr, SortOrder.Ascending);
                        }
                        if (baseStr.EndsWith("(descending)"))
                        {
                            baseStr = baseStr.Remove(baseStr.Length - 13);
                            Parameters.SortVariables.Add(baseStr, SortOrder.Descending);
                        }
                    }
                }
            }

            if (cmbGroupField.SelectedIndex >= 0)
            {
                if (!string.IsNullOrEmpty(cmbGroupField.SelectedItem.ToString()))
                {
                    Parameters.PrimaryGroupField = cmbGroupField.SelectedItem.ToString();
                }
            }

            if (cmbSecondaryGroupField.SelectedIndex >= 0)
            {
                if (!string.IsNullOrEmpty(cmbSecondaryGroupField.SelectedItem.ToString()))
                {
                    Parameters.SecondaryGroupField = cmbSecondaryGroupField.SelectedItem.ToString();
                }
            }

            if (StrataGridList.Count >= 1)
            {
                Grid grid = StrataGridList[0];
                SortedDictionary <int, string> sortColumnDictionary = new SortedDictionary <int, string>();

                foreach (UIElement element in grid.Children)
                {
                    if (Grid.GetRow(element) == 0 && element is TextBlock)
                    {
                        TextBlock txtColumnName = element as TextBlock;
                        //columnOrder.Add(txtColumnName.Text);
                        sortColumnDictionary.Add(Grid.GetColumn(element), txtColumnName.Text);
                    }
                }

                ColumnOrder = new List <string>();
                foreach (KeyValuePair <int, string> kvp in sortColumnDictionary)
                {
                    ColumnOrder.Add(kvp.Value);
                }

                if (ColumnOrder.Count == listFields.Count || ColumnOrder.Count == (listFields.Count + 1))
                {
                    bool same = true;
                    foreach (string s in listFields)
                    {
                        if (!ColumnOrder.Contains(s))
                        {
                            same = false;
                        }
                    }

                    if (same)
                    {
                        WordBuilder wb = new WordBuilder("^");
                        foreach (string s in ColumnOrder)
                        {
                            wb.Add(s);
                        }

                        //inputVariableList.Add("customusercolumnsort", wb.ToString());
                        Parameters.CustomUserColumnSort.Add(wb.ToString());
                    }
                    else
                    {
                        ColumnOrder = new List <string>();
                    }
                }
                else
                {
                    ColumnOrder = new List <string>();
                }
            }

            //Parameters.InputVariableList = inputVariableList;
        }
        private void btnOK_Click(object sender, EventArgs e)
        {
            KeyFields = new List <Field>();

            if (lbxFields.SelectedItems.Count == 0)
            {
                return;
            }

            try
            {
                #region Check #1 - Make sure key is unique on parent form
                IDbDriver db = Project.CollectedData.GetDatabase();

                Query selectQuery = db.CreateQuery("SELECT Count(*) FROM [" + Form.TableName + "]");
                int   recordCount = (int)db.ExecuteScalar(selectQuery);

                WordBuilder wb = new WordBuilder(",");

                foreach (Field field in Form.Fields)
                {
                    if (field is RenderableField && lbxFields.SelectedItems.Contains(field.Name))
                    {
                        wb.Add(field.Name);
                    }
                }

                selectQuery = db.CreateQuery("SELECT DISTINCT " + wb.ToString() + " " + Form.FromViewSQL);
                int distinctCount = db.Select(selectQuery).Rows.Count; // probably better way to do this, but unsure if can be made generic... this query is most generic across DB types?

                if (distinctCount == recordCount)
                {
                    foreach (Field field in Form.Fields)
                    {
                        if (field is RenderableField && lbxFields.SelectedItems.Contains(field.Name))
                        {
                            KeyFields.Add(field);
                        }
                    }
                }
                else
                {
                    if (lbxFields.SelectedItems.Count == 1)
                    {
                        Epi.Windows.MsgBox.ShowError(String.Format("The selected match key ({0}) is not unique.", lbxFields.SelectedItem.ToString()));
                    }
                    else if (lbxFields.SelectedItems.Count > 1)
                    {
                        WordBuilder keyFields = new WordBuilder(",");
                        foreach (string s in lbxFields.SelectedItems)
                        {
                            keyFields.Add(s);
                        }
                        Epi.Windows.MsgBox.ShowError(String.Format("The selected match key ({0}) is not unique.", keyFields.ToString()));
                    }

                    this.DialogResult = System.Windows.Forms.DialogResult.None;
                    return;
                }
                #endregion // Check #1 - Make sure key is unique on parent form

                // Currently, disable match keys if related forms exist. TODO: Change this later?
                foreach (View otherForm in Project.Views)
                {
                    if (otherForm != Form && Epi.ImportExport.ImportExportHelper.IsFormDescendant(otherForm, Form))
                    {
                        Epi.Windows.MsgBox.ShowError("Custom match keys cannot be used to package a form that contains child forms.");
                        this.DialogResult = System.Windows.Forms.DialogResult.None;
                        return;
                    }
                }
                //#region Check #2 - Make sure key exists in other forms in the hierarchy and that it's the same field type
                //foreach (View otherForm in Project.Views)
                //{
                //    if (otherForm != Form && Epi.ImportExport.ImportExportHelper.IsFormDescendant(otherForm, Form))
                //    {
                //        foreach (Field field in KeyFields)
                //        {
                //            if (!otherForm.Fields.Contains(field.Name))
                //            {
                //                Epi.Windows.MsgBox.ShowError(
                //                    String.Format(
                //                    "The selected field {0} does not exist in the child form {1}. The keys selected in this dialog must exist across all child forms.",
                //                    field.Name, otherForm.Name));
                //                this.DialogResult = System.Windows.Forms.DialogResult.None;
                //                return;
                //            }
                //            else
                //            {
                //                Field otherField = otherForm.Fields[field.Name];
                //                if (otherField.FieldType != field.FieldType)
                //                {
                //                    Epi.Windows.MsgBox.ShowError(
                //                    String.Format(
                //                    "The selected field {0} is implemented as a different field type on child form {1}. The keys selected in this dialog must exist across all child forms and those fields must be of the same field type.",
                //                    field.Name, otherForm.Name));
                //                    this.DialogResult = System.Windows.Forms.DialogResult.None;
                //                    return;
                //                }
                //            }
                //        }
                //    }
                //}
                //#endregion // Check #2 - Make sure key exists in other forms in the hierarchy and that it's the same field type
            }
            catch (Exception ex)
            {
                Epi.Windows.MsgBox.ShowException(ex);
                this.DialogResult = System.Windows.Forms.DialogResult.None;
            }
        }
        /// <summary>
        /// Converts the gadget's output to Html
        /// </summary>
        /// <returns></returns>
        public override string ToHTML(string htmlFileName = "", int count = 0)
        {
            if (IsCollapsed) return string.Empty;
            ComplexSampleFrequencyParameters csfreqParameters = (ComplexSampleFrequencyParameters)Parameters;

            StringBuilder htmlBuilder = new StringBuilder();

            CustomOutputHeading = headerPanel.Text;
            CustomOutputDescription = descriptionPanel.Text;

            if (CustomOutputHeading == null || (string.IsNullOrEmpty(CustomOutputHeading) && !CustomOutputHeading.Equals("(none)")))
            {
                htmlBuilder.AppendLine("<h2 class=\"gadgetHeading\">Complex Sample Frequency</h2>");
            }
            else if(CustomOutputHeading != "(none)")
            {
                htmlBuilder.AppendLine("<h2 class=\"gadgetHeading\">" + CustomOutputHeading + "</h2>");
            }

            htmlBuilder.AppendLine("<p class=\"gadgetOptions\"><small>");
            htmlBuilder.AppendLine("<em>Frequency variable:</em> <strong>" + csfreqParameters.ColumnNames[0] + "</strong>");
            htmlBuilder.AppendLine("<br />");
            htmlBuilder.AppendLine("<em>PSU variable:</em> <strong>" + csfreqParameters.PSUVariableName + "</strong>");
            htmlBuilder.AppendLine("<br />");

            if (!String.IsNullOrEmpty(csfreqParameters.WeightVariableName))
            {
                htmlBuilder.AppendLine("<em>Weight variable:</em> <strong>" + csfreqParameters.WeightVariableName + "</strong>");
                htmlBuilder.AppendLine("<br />");
            }
            if (csfreqParameters.StrataVariableNames.Count > 0)
            {
                WordBuilder wb = new WordBuilder(", ");
                foreach (string s in csfreqParameters.StrataVariableNames)
                {
                    wb.Add(s);
                }
                htmlBuilder.AppendLine("<em>Strata variable:</em> <strong>" + wb.ToString() + "</strong>");
                htmlBuilder.AppendLine("<br />");
            }
            //htmlBuilder.AppendLine("<em>Include missing:</em> <strong>" + checkboxIncludeMissing.IsChecked.ToString() + "</strong>");
            //htmlBuilder.AppendLine("<br />");
            htmlBuilder.AppendLine("</small></p>");

            if (!string.IsNullOrEmpty(CustomOutputDescription))
            {
                htmlBuilder.AppendLine("<p class=\"gadgetsummary\">" + CustomOutputDescription + "</p>");
            }

            if (!string.IsNullOrEmpty(messagePanel.Text) && messagePanel.Visibility == Visibility.Visible)
            {
                htmlBuilder.AppendLine("<p><small><strong>" + messagePanel.Text + "</strong></small></p>");
            }

            if (!string.IsNullOrEmpty(txtFilterString.Text) && txtFilterString.Visibility == Visibility.Visible)
            {
                htmlBuilder.AppendLine("<p><small><strong>" + txtFilterString.Text + "</strong></small></p>");
            }

            foreach (Grid grid in this.StrataGridList)
            {
                string gridName = grid.Tag.ToString();

                htmlBuilder.AppendLine("<div style=\"height: 7px;\"></div>");
                htmlBuilder.AppendLine("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\">");

                foreach (UIElement control in grid.Children)
                {
                    if (control is TextBlock)
                    {
                        int rowNumber = Grid.GetRow(control);
                        int columnNumber = Grid.GetColumn(control);

                        string tableDataTagOpen = "<td>";
                        string tableDataTagClose = "</td>";

                        if (rowNumber == 0)
                        {
                            tableDataTagOpen = "<th>";
                            tableDataTagClose = "</th>";
                        }

                        if (columnNumber == 0)
                        {
                            htmlBuilder.AppendLine("<tr>");
                        }
                        if (columnNumber == 0 && rowNumber > 0)
                        {
                            tableDataTagOpen = "<td class=\"value\">";
                        }

                        string value = ((TextBlock)control).Text;
                        string formattedValue = value;

                        htmlBuilder.AppendLine(tableDataTagOpen + formattedValue + tableDataTagClose);

                        if (columnNumber >= grid.ColumnDefinitions.Count - 1)
                        {
                            htmlBuilder.AppendLine("</tr>");
                        }
                    }
                }

                htmlBuilder.AppendLine("</table>");
            }
            return htmlBuilder.ToString();
        }
        /// <summary>
        /// Helper method for the CreateFromXml method. Loads a list of row filter conditions from XML.
        /// </summary>
        /// <param name="element">XmlElement to process</param>
        private void CreateRowFiltersFromXML(XmlElement element)
        {
            if (element.Name.ToLower().Equals("rowfilter"))
            {
                foreach (XmlElement childElement in element.ChildNodes)
                {
                    if (childElement.Name.ToLower().Equals("rowfilterquery"))
                    {
                        selectQuery = sourceProject.CollectedData.GetDbDriver().CreateQuery(childElement.InnerText.Replace("&gt;", ">").Replace("&lt;", "<"));
                    }
                    else if (childElement.Name.ToLower().Equals("rowfilterparameters"))
                    {
                        foreach (XmlElement gcElement in childElement.ChildNodes)
                        {
                            System.Data.DbType dbType = System.Data.DbType.String;
                            string name = "";
                            object value = null;

                            foreach (XmlElement ggcElement in gcElement.ChildNodes)
                            {
                                switch (ggcElement.Name.ToLower())
                                {
                                    case "dbtype":
                                        dbType = ((DbType)Int32.Parse(ggcElement.InnerText));
                                        break;
                                    case "name":
                                        name = ggcElement.InnerText;
                                        break;
                                    case "value":
                                        value = ggcElement.InnerText;
                                        break;
                                }
                            }

                            QueryParameter queryParameter = new QueryParameter(name, dbType, value);
                            if (selectQuery != null)
                            {
                                selectQuery.Parameters.Add(queryParameter);
                            }
                        }
                    }
                    else if (childElement.Name.ToLower().Equals("rowfilterconditions"))
                    {
                        List<IRowFilterCondition> conditions = new List<IRowFilterCondition>();

                        foreach (XmlElement grandChildElement in childElement.ChildNodes)
                        {
                            if (grandChildElement.HasAttribute("filterType"))
                            {
                                string strType = grandChildElement.Attributes["filterType"].Value + ",Epi.ImportExport";
                                Type filterType = Type.GetType(strType, false, true);
                                if (filterType != null)
                                {
                                    IRowFilterCondition condition = (IRowFilterCondition)Activator.CreateInstance(filterType, new object[] { });
                                    condition.CreateFromXml(grandChildElement);
                                    conditions.Add(condition);
                                }
                            }
                        }

                        this.rowFilterConditions = conditions;
                    }
                }
            }

            string filter = String.Empty;
            if (this.rowFilterConditions.Count > 0)
            {
                filter = ImportExportSharedStrings.SCRIPT_FILTERS;
                WordBuilder wb = new WordBuilder(" and ");
                foreach (IRowFilterCondition rfc in this.rowFilterConditions)
                {
                    wb.Add(rfc.Description);
                }
                filter = filter + wb.ToString();
                CallbackAddStatusMessage(filter);
            }
        }
Ejemplo n.º 36
0
        /// <summary>
        /// Begins the process of importing records from the data package into the destination form
        /// </summary>
        /// <param name="form">The form that will receive the data</param>
        /// <param name="formNode">The XmlNode representing the form</param>
        /// <param name="records">The data to be imported</param>
        protected virtual void ImportRecords(View form, XmlNode formNode, List<PackageFieldData> records)
        {
            ImportInfo.RecordsAppended.Add(form, 0);
            ImportInfo.RecordsUpdated.Add(form, 0);

            IDbDriver destinationDb = DestinationProject.CollectedData.GetDatabase();
            Dictionary<string, bool> destinationGuids = new Dictionary<string, bool>();
            Dictionary<Dictionary<Field, object>, bool> destinationKeyValues = new Dictionary<Dictionary<Field, object>, bool>();

            using (IDataReader baseTableReader = destinationDb.GetTableDataReader(form.TableName))
            {
                while (baseTableReader.Read())
                {
                    destinationGuids.Add(baseTableReader["GlobalRecordId"].ToString(), true);
                }
            }

            #region Custom Keys
            if (this.IsUsingCustomMatchkeys)
            {
                WordBuilder wb = new WordBuilder(",");
                foreach(Field field in KeyFields)
                {
                    wb.Add(field.Name);
                }

                Query selectQuery = destinationDb.CreateQuery("SELECT " + wb.ToString() + " " + form.FromViewSQL);
                using (IDataReader keyTableReader = destinationDb.ExecuteReader(selectQuery))
                {
                    while (keyTableReader.Read())
                    {
                        Dictionary<Field, object> keys = new Dictionary<Field, object>();

                        foreach (Field field in KeyFields)
                        {
                            keys.Add(field, keyTableReader[field.Name]);
                            //destinationKeyValues.Add(keyTableReader["GlobalRecordId"].ToString(), true);
                        }

                        destinationKeyValues.Add(keys, true);
                    }
                }
            }
            #endregion // Custom Keys

            foreach (XmlNode recordNode in formNode.SelectSingleNode("Data").ChildNodes)
            {
                if (recordNode.Name.ToLower().Equals("record"))
                {
                    string guid = string.Empty;
                    string fkey = string.Empty;
                    string firstSaveId = string.Empty;
                    string lastSaveId = string.Empty;
                    DateTime? firstSaveTime = null;
                    DateTime? lastSaveTime = null;

                    foreach (XmlAttribute attrib in recordNode.Attributes)
                    {
                        if (attrib.Name.ToLower().Equals("id")) guid = attrib.Value;
                        if (attrib.Name.ToLower().Equals("fkey")) fkey = attrib.Value;
                        if (attrib.Name.ToLower().Equals("firstsaveuserid")) firstSaveId = attrib.Value;
                        if (attrib.Name.ToLower().Equals("lastsaveuserid")) lastSaveId = attrib.Value;
                        if (attrib.Name.ToLower().Equals("firstsavetime")) firstSaveTime = new DateTime(Convert.ToInt64(attrib.Value));
                        if (attrib.Name.ToLower().Equals("lastsavetime")) lastSaveTime = new DateTime(Convert.ToInt64(attrib.Value));
                    }

                    if (!destinationGuids.ContainsKey(guid))
                    {
                        if (Append)
                        {
                            destinationGuids.Add(guid, true);
                            CreateNewBlankRow(form, guid, fkey, firstSaveId, lastSaveId, firstSaveTime, lastSaveTime);
                            ImportInfo.TotalRecordsAppended++;
                            ImportInfo.RecordsAppended[form]++;
                        }
                    }
                    else
                    {
                        if (!Update)
                        {
                            destinationGuids[guid] = false;
                        }
                        else
                        {
                            ImportInfo.TotalRecordsUpdated++;
                            ImportInfo.RecordsUpdated[form]++;
                        }
                    }
                }
            }

            ImportRecordsToPageTables(form, records, destinationGuids);
        }
Ejemplo n.º 37
0
        /// <summary>
        /// Used to generate the list of variables and options for the GadgetParameters object
        /// </summary> 
        protected override void CreateInputVariableList()
        {
            // Set data filters!
            this.DataFilters = RowFilterControl.DataFilters;

            Dictionary<string, string> inputVariableList = new Dictionary<string, string>();
            Parameters.ColumnNames = new List<string>();

            Parameters.SortVariables = new Dictionary<string, SortOrder>();

            Parameters.GadgetTitle = txtTitle.Text;
            Parameters.GadgetDescription = txtDesc.Text;

            double height = 0;
            double width = 0;

            bool success = double.TryParse(txtMaxHeight.Text, out height);
            if (success)
            {
                Parameters.Height = height;
            }

            success = double.TryParse(txtMaxWidth.Text, out width);
            if (success)
            {
                Parameters.Width = width;
            }

            List<string> listFields = new List<string>();

            if (lvVariables.SelectedItems.Count > 0)
            {
                foreach (FieldInfo fieldInfo in lvVariables.SelectedItems)
                {
                    if (!string.IsNullOrEmpty(fieldInfo.Name))
                    {
                        listFields.Add(fieldInfo.Name);
                    }
                }
            }

            listFields.Sort();
            if ((Gadget as LineListControl).IsHostedByEnter)
            {
                //if (dashboardHelper.IsUsingEpiProject && checkboxAllowUpdates.IsChecked == true)
                //{
                    if (listFields.Contains("UniqueKey"))
                        listFields.Remove("UniqueKey");
                    listFields.Add("UniqueKey");
                //}
            }

            foreach (string field in listFields)
            {
                Parameters.ColumnNames.Add(field);
            }

            Parameters.SortColumnsByTabOrder = checkboxTabOrder.IsChecked.Value;
            Parameters.UsePromptsForColumnNames = checkboxUsePrompts.IsChecked.Value;
            Parameters.ShowColumnHeadings = checkboxColumnHeaders.IsChecked.Value;
            Parameters.ShowLineColumn = checkboxLineColumn.IsChecked.Value;
            Parameters.ShowNullLabels = checkboxShowNulls.IsChecked.Value;
            Parameters.ShowCommentLegalLabels = checkboxListLabels.IsChecked.Value;

            if (lbxSortOrder.Items.Count > 0)
            {
                foreach (string item in lbxSortOrder.Items)
                {
                    if (!string.IsNullOrEmpty(item))
                    {
                        //string baseStr = item;

                        //if (baseStr.EndsWith("(ascending)"))
                        //{
                        //    baseStr = "[" + baseStr.Remove(baseStr.Length - 12) + "] ASC";
                        //}
                        //if (baseStr.EndsWith("(descending)"))
                        //{
                        //    baseStr = "[" + baseStr.Remove(baseStr.Length - 13) + "] DESC";
                        //}
                        //inputVariableList.Add(baseStr, "sortfield");

                        string baseStr = item;

                        if (baseStr.EndsWith("(ascending)"))
                        {
                            baseStr = baseStr.Remove(baseStr.Length - 12);
                            Parameters.SortVariables.Add(baseStr, SortOrder.Ascending);
                        }
                        if (baseStr.EndsWith("(descending)"))
                        {
                            baseStr = baseStr.Remove(baseStr.Length - 13);
                            Parameters.SortVariables.Add(baseStr, SortOrder.Descending);
                        }
                    }
                }
            }

            if (cmbGroupField.SelectedIndex >= 0)
            {
                if (!string.IsNullOrEmpty(cmbGroupField.SelectedItem.ToString()))
                {
                    Parameters.PrimaryGroupField = cmbGroupField.SelectedItem.ToString();
                }
            }

            if (cmbSecondaryGroupField.SelectedIndex >= 0)
            {
                if (!string.IsNullOrEmpty(cmbSecondaryGroupField.SelectedItem.ToString()))
                {
                    Parameters.SecondaryGroupField = cmbSecondaryGroupField.SelectedItem.ToString();
                }
            }

            if (StrataGridList.Count >= 1)
            {
                Grid grid = StrataGridList[0];
                SortedDictionary<int, string> sortColumnDictionary = new SortedDictionary<int, string>();

                foreach (UIElement element in grid.Children)
                {
                    if (Grid.GetRow(element) == 0 && element is TextBlock)
                    {
                        TextBlock txtColumnName = element as TextBlock;
                        //columnOrder.Add(txtColumnName.Text);
                        sortColumnDictionary.Add(Grid.GetColumn(element), txtColumnName.Text);
                    }
                }

                ColumnOrder = new List<string>();
                foreach (KeyValuePair<int, string> kvp in sortColumnDictionary)
                {
                    ColumnOrder.Add(kvp.Value);
                }

                if (ColumnOrder.Count == listFields.Count || ColumnOrder.Count == (listFields.Count + 1))
                {
                    bool same = true;
                    foreach (string s in listFields)
                    {
                        if (!ColumnOrder.Contains(s))
                        {
                            same = false;
                        }
                    }

                    if (same)
                    {
                        WordBuilder wb = new WordBuilder("^");
                        foreach (string s in ColumnOrder)
                        {
                            wb.Add(s);
                        }

                        inputVariableList.Add("customusercolumnsort", wb.ToString());
                    }
                    else
                    {
                        ColumnOrder = new List<string>();
                    }
                }
                else
                {
                    ColumnOrder = new List<string>();
                }
            }

            Parameters.InputVariableList = inputVariableList;
        }
Ejemplo n.º 38
0
        /// <summary>
        /// Generates a FilterCondition object using primitive type inputs
        /// </summary>
        /// <param name="columnName">The name of the column on which to filter</param>
        /// <param name="rawColumnName">The name of the column on which to filter, without brackets</param>
        /// <param name="columnType">The data type of the column on which to filter</param>
        /// <param name="friendlyOperand">The friendly operand</param>
        /// <param name="friendlyValue">The friendly value</param>
        /// <returns>FilterCondition</returns>
        public FilterCondition GenerateFilterCondition(string columnName, string rawColumnName, string columnType, string friendlyOperand, string friendlyValue)
        {
            #region Input Validation
            if (string.IsNullOrEmpty(columnName))
            {
                throw new ApplicationException("Column name cannot be empty.");
            }
            else if (string.IsNullOrEmpty(friendlyOperand))
            {
                throw new ApplicationException("Friendly operand cannot be empty.");
            }
            else if (string.IsNullOrEmpty(columnType))
            {
                throw new ApplicationException("Column type cannot be empty.");
            }
            else if (!operandTypes.ContainsKey(friendlyOperand))
            {
                throw new ApplicationException("Operand not found in dictionary.");
            }
            #endregion // Input Validation

            Configuration config = dashboardHelper.Config;

            Epi.Fields.Field field = null;

            foreach (DataRow fieldRow in dashboardHelper.FieldTable.Rows)
            {
                if (fieldRow["columnname"].Equals(rawColumnName))
                {
                    if (fieldRow["epifieldtype"] is Epi.Fields.Field)
                    {
                        field = fieldRow["epifieldtype"] as Epi.Fields.Field;
                    }
                    break;
                }
            }

            string operand           = string.Empty;
            string value             = string.Empty;
            string friendlyCondition = string.Empty;

            operand = operandTypes[friendlyOperand];

            switch (columnType)
            {
            case "System.DateTime":
                value = "#" + friendlyValue.Trim() + "#";
                break;

            case "System.String":

                if (operand.Equals(operandTypes[SharedStrings.FRIENDLY_OPERATOR_IS_ANY_OF]) ||
                    operand.Equals(operandTypes[SharedStrings.FRIENDLY_OPERATOR_IS_NOT_ANY_OF]))
                {
                    string[]    values = friendlyValue.Split(',');
                    WordBuilder wb     = new WordBuilder(",");

                    foreach (string str in values)
                    {
                        wb.Add("'" + str.Trim().Replace("'", "''") + "'");
                    }

                    value = "(" + wb.ToString() + ")";
                }
                else
                {
                    value = "'" + friendlyValue.Trim().Replace("'", "''") + "'";
                    if (value.Equals("''") && operand.Equals(operandTypes[SharedStrings.FRIENDLY_OPERATOR_MISSING]))
                    {
                        operand = operandTypes[SharedStrings.FRIENDLY_OPERATOR_EQUAL_TO];
                    }
                    else if (value.Equals("''") && operand.Equals(operandTypes[SharedStrings.FRIENDLY_OPERATOR_NOT_MISSING]))
                    {
                        operand = operandTypes[SharedStrings.FRIENDLY_OPERATOR_NOT_EQUAL_TO];
                    }
                }
                break;

            case "System.Boolean":
                if (friendlyValue.Equals(config.Settings.RepresentationOfYes))
                {
                    value = "1";
                }
                else
                {
                    value = "0";
                }
                break;

            case "System.Int16":
            case "System.Byte":
                if (field != null && field is Epi.Fields.YesNoField)
                {
                    if (friendlyValue.Equals(config.Settings.RepresentationOfYes))
                    {
                        value = "1";
                    }
                    else if (friendlyValue.Equals(config.Settings.RepresentationOfNo))
                    {
                        value = "0";
                    }
                    else if (friendlyValue.Equals(config.Settings.RepresentationOfMissing))
                    {
                        value = string.Empty;
                    }
                }
                else
                {
                    value = friendlyValue.Trim();
                }
                break;

            default:
                value = friendlyValue.Trim();
                break;
            }

            if (friendlyValue.Equals(config.Settings.RepresentationOfMissing))
            {
                value         = string.Empty;
                friendlyValue = string.Empty;
                if (friendlyOperand.Equals(SharedStrings.FRIENDLY_OPERATOR_NOT_MISSING) || friendlyOperand.Equals(SharedStrings.FRIENDLY_OPERATOR_NOT_EQUAL_TO))
                {
                    operand = operandTypes[SharedStrings.FRIENDLY_OPERATOR_NOT_MISSING]; // "is not null";
                }
                else if (friendlyOperand.Equals(SharedStrings.FRIENDLY_OPERATOR_MISSING))
                {
                    operand = operandTypes[SharedStrings.FRIENDLY_OPERATOR_MISSING]; // "is null";
                    value   = string.Empty;
                }
                else
                {
                    operand = operandTypes[SharedStrings.FRIENDLY_OPERATOR_MISSING]; // "is null";
                }
            }

            if (operand.Equals("like"))
            {
                value = value.Trim().Replace('*', '%');
            }

            if (operand.Equals(operandTypes[SharedStrings.FRIENDLY_OPERATOR_NOT_MISSING]) || operand.Equals(operandTypes[SharedStrings.FRIENDLY_OPERATOR_MISSING]))
            {
                value = string.Empty;
            }

            if (columnType.Equals("System.DateTime") && !string.IsNullOrEmpty(value))
            {
                DateTime dt = DateTime.Parse(friendlyValue, System.Globalization.CultureInfo.InvariantCulture);
                friendlyValue = dt.ToString("d", System.Globalization.CultureInfo.CurrentCulture);
            }

            friendlyCondition = string.Format(SharedStrings.FRIENDLY_CONDITION_DATA_FILTER, columnName, friendlyOperand, friendlyValue);
            FilterCondition newCondition = new FilterCondition(friendlyCondition, columnName, rawColumnName, columnType, operand, friendlyOperand, value, friendlyValue);

            return(newCondition);
        }
Ejemplo n.º 39
0
        /// <summary>
        /// Initiates an export of the data to the specified file.
        /// </summary>
        public override void Export()
        {
            OnSetStatusMessage(ImportExportSharedStrings.WEB_CSV_EXPORT_CONNECTING);

            rowsExported = 0;
            WordBuilder  wb = new WordBuilder(SEPARATOR);
            StreamWriter sw = null;

            SurveyManagerService.SurveyAnswerRequest Request = new SurveyManagerService.SurveyAnswerRequest();
            Request.Criteria.SurveyId           = surveyKey.ToString();
            Request.Criteria.UserPublishKey     = secToken;
            Request.Criteria.OrganizationKey    = orgKey;
            Request.Criteria.ReturnSizeInfoOnly = true;
            SurveyManagerService.SurveyAnswerResponse Result = client.GetSurveyAnswer(Request);
            Pages    = Result.NumberOfPages;
            PageSize = Result.PageSize;

            Request.Criteria.ReturnSizeInfoOnly = false;

            int count = 0;

            List <SurveyManagerService.SurveyAnswerResponse> Results = new List <SurveyManagerService.SurveyAnswerResponse>();

            OnSetStatusMessage(ImportExportSharedStrings.WEB_CSV_EXPORT_BUILDING_COLUMN_HEADINGS);

            for (int i = 1; i <= Pages; i++)
            {
                Request.Criteria.PageNumber = i;
                Request.Criteria.PageSize   = PageSize;

                Result = client.GetSurveyAnswer(Request);
                Results.Add(Result);

                foreach (SurveyManagerService.SurveyAnswerDTO surveyAnswer in Result.SurveyResponseList)
                {
                    if (surveyAnswer.Status == 3)
                    {
                        count++;
                    }
                }
            }


            if (SetMaxProgressBarValue != null)
            {
                SetMaxProgressBarValue((double)count);
            }

            List <string> columnHeaders = new List <string>();

            foreach (SurveyManagerService.SurveyAnswerResponse R in Results)
            {
                wfList = ParseXML(R);

                foreach (WebFieldData wfData in wfList)
                {
                    if (!columnHeaders.Contains(wfData.FieldName))
                    {
                        columnHeaders.Add(wfData.FieldName);
                    }
                    else
                    {
                        break;
                    }
                }

                break;
            }

            try
            {
                OnSetStatusMessage(ImportExportSharedStrings.WEB_CSV_EXPORTING);

                sw = File.CreateText(fileName);

                foreach (string s in columnHeaders)
                {
                    wb.Add(s);
                }

                sw.WriteLine(wb.ToString());
                rowsExported = 0;


                foreach (SurveyManagerService.SurveyAnswerResponse R in Results)
                {
                    string currentGUID = string.Empty;
                    string lastGUID    = string.Empty;

                    wfList = ParseXML(R);

                    wb = new WordBuilder(SEPARATOR);

                    foreach (WebFieldData wfData in wfList)
                    {
                        currentGUID = wfData.RecordGUID;

                        if (!string.IsNullOrEmpty(currentGUID) && !string.IsNullOrEmpty(lastGUID) && currentGUID != lastGUID)
                        {
                            sw.WriteLine(wb.ToString());
                            wb = new WordBuilder(SEPARATOR);

                            OnSetStatusMessageAndProgressCount("", 1);
                        }

                        string rowValue = wfData.FieldValue.ToString().Replace("\r\n", " ");
                        if (rowValue.Contains(",") || rowValue.Contains("\""))
                        {
                            rowValue = rowValue.Replace("\"", "\"\"");
                            rowValue = Util.InsertIn(rowValue, "\"");
                        }
                        wb.Add(rowValue);

                        lastGUID = wfData.RecordGUID;
                    }

                    sw.WriteLine(wb.ToString());
                }

                OnSetStatusMessage(ImportExportSharedStrings.WEB_CSV_EXPORT_COMPLETE);

                if (FinishExport != null)
                {
                    FinishExport();
                }
            }

            catch (Exception ex)
            {
                OnSetStatusMessage(ex.Message);

                if (ExportFailed != null)
                {
                    ExportFailed(ex.Message);
                }
            }
            finally
            {
                // Clean up
                if (sw != null)
                {
                    sw.Close();
                    sw.Dispose();
                    sw = null;
                }
            }
        }
Ejemplo n.º 40
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            KeyFields = new List<Field>();

            if (lbxFields.SelectedItems.Count == 0)
            {
                return;
            }

            try
            {
                #region Check #1 - Make sure key is unique on parent form
                IDbDriver db = Project.CollectedData.GetDatabase();

                Query selectQuery = db.CreateQuery("SELECT Count(*) FROM [" + Form.TableName + "]");
                int recordCount = (int)db.ExecuteScalar(selectQuery);

                WordBuilder wb = new WordBuilder(",");

                foreach (Field field in Form.Fields)
                {
                    if (field is RenderableField && lbxFields.SelectedItems.Contains(field.Name))
                    {
                        wb.Add(field.Name);
                    }
                }

                selectQuery = db.CreateQuery("SELECT DISTINCT " + wb.ToString() + " " + Form.FromViewSQL);
                int distinctCount = db.Select(selectQuery).Rows.Count; // probably better way to do this, but unsure if can be made generic... this query is most generic across DB types?

                if (distinctCount == recordCount)
                {
                    foreach (Field field in Form.Fields)
                    {
                        if (field is RenderableField && lbxFields.SelectedItems.Contains(field.Name))
                        {
                            KeyFields.Add(field);
                        }
                    }
                }
                else
                {
                    if (lbxFields.SelectedItems.Count == 1)
                    {
                        Epi.Windows.MsgBox.ShowError(String.Format("The selected match key ({0}) is not unique.", lbxFields.SelectedItem.ToString()));
                    }
                    else if (lbxFields.SelectedItems.Count > 1)
                    {
                        WordBuilder keyFields = new WordBuilder(",");
                        foreach (string s in lbxFields.SelectedItems)
                        {
                            keyFields.Add(s);
                        }
                        Epi.Windows.MsgBox.ShowError(String.Format("The selected match key ({0}) is not unique.", keyFields.ToString()));
                    }

                    this.DialogResult = System.Windows.Forms.DialogResult.None;
                    return;
                }
                #endregion // Check #1 - Make sure key is unique on parent form

                // Currently, disable match keys if related forms exist. TODO: Change this later?
                foreach (View otherForm in Project.Views)
                {
                    if (otherForm != Form && Epi.ImportExport.ImportExportHelper.IsFormDescendant(otherForm, Form))
                    {
                        Epi.Windows.MsgBox.ShowError("Custom match keys cannot be used to package a form that contains child forms.");
                        this.DialogResult = System.Windows.Forms.DialogResult.None;
                        return;
                    }
                }
                //#region Check #2 - Make sure key exists in other forms in the hierarchy and that it's the same field type
                //foreach (View otherForm in Project.Views)
                //{
                //    if (otherForm != Form && Epi.ImportExport.ImportExportHelper.IsFormDescendant(otherForm, Form))
                //    {
                //        foreach (Field field in KeyFields)
                //        {
                //            if (!otherForm.Fields.Contains(field.Name))
                //            {
                //                Epi.Windows.MsgBox.ShowError(
                //                    String.Format(
                //                    "The selected field {0} does not exist in the child form {1}. The keys selected in this dialog must exist across all child forms.",
                //                    field.Name, otherForm.Name));
                //                this.DialogResult = System.Windows.Forms.DialogResult.None;
                //                return;
                //            }
                //            else
                //            {
                //                Field otherField = otherForm.Fields[field.Name];
                //                if (otherField.FieldType != field.FieldType)
                //                {
                //                    Epi.Windows.MsgBox.ShowError(
                //                    String.Format(
                //                    "The selected field {0} is implemented as a different field type on child form {1}. The keys selected in this dialog must exist across all child forms and those fields must be of the same field type.",
                //                    field.Name, otherForm.Name));
                //                    this.DialogResult = System.Windows.Forms.DialogResult.None;
                //                    return;
                //                }
                //            }
                //        }
                //    }
                //}
                //#endregion // Check #2 - Make sure key exists in other forms in the hierarchy and that it's the same field type
            }
            catch (Exception ex)
            {
                Epi.Windows.MsgBox.ShowException(ex);
                this.DialogResult = System.Windows.Forms.DialogResult.None;
            }
        }