private void AdminLevelMultiselect_Load(object sender, EventArgs e)
        {
            if (!DesignMode)
            {
                Localizer.TranslateControl(this);
                demography = new DemoRepository();
                settings = new SettingsRepository();
                levels = settings.GetAllAdminLevels();
                bsLevels.DataSource = levels;
                cbLevels.SelectedItem = levels.FirstOrDefault();
                LoadTrees();
                treeAvailable.CanExpandGetter = model => ((AdminLevel)model).
                                                              Children.Count > 0;
                treeAvailable.ChildrenGetter = delegate(object model)
                {
                    return ((AdminLevel)model).
                            Children;
                };
                treeSelected.CanExpandGetter = model => ((AdminLevel)model).
                                                              Children.Count > 0;
                treeSelected.ChildrenGetter = delegate(object model)
                {
                    return ((AdminLevel)model).
                            Children;
                };

                cbLevels.DropDownWidth = BaseForm.GetDropdownWidth(levels.Select(a => a.DisplayName));

            }
        }
Пример #2
0
 private void AdminLevelView_Load(object sender, EventArgs e)
 {
     if (!DesignMode)
     {
         Localizer.TranslateControl(this);
         r = new DemoRepository();
         bsAdminLevel.DataSource = adminLevel;
         // Foreach type of disease load the dashboard, add tabs, 
         LoadDash(adminLevel);
     }
 }
        private void CountryView_Load(object sender, EventArgs e)
        {
            if (!DesignMode)
            {
                h3Required3.SetMaxWidth(370);
                lblYear.SetMaxWidth(370);

                DemoRepository demo = new DemoRepository();
                model = demo.GetCountryLevelStatsRecent();
                CreateIncomeStatusDropdown(comboBox1);
                bsCountryDemo.DataSource = model;
            }
        }
Пример #4
0
        private bool SaveDemo()
        {
            countryDemographyView1.DoValidate();
            model = countryDemographyView1.GetDemo();
            if (!model.IsValid() || !countryDemographyView1.IsValid())
            {
                MessageBox.Show(Translations.ValidationError, Translations.ValidationErrorTitle);
                return false;
            }

            int userId = ApplicationData.Instance.GetUserId();
            var demo = new DemoRepository();
            demo.Save(model, userId);
            return true;
        }
        private void TaskForceAdminLevelStep_Load(object sender, EventArgs e)
        {
            if (!DesignMode)
            {
                Localizer.TranslateControl(this);

                DemoRepository demo = new DemoRepository();
                var country = demo.GetCountry();
                var adminLevels = demo.GetAdminLevelByLevel(types[typeIndex].LevelNumber);

                foreach (var u in adminLevels)
                {
                    List<TaskForceAdminUnit> available = new List<TaskForceAdminUnit>();
                    if (u.ParentId == country.Id)
                        available = units.Where(x => x.LevelIndex == 0).ToList();
                    else
                        available = units.Where(x => x.LevelIndex == typeIndex && x.Parent.NadaId == u.ParentId).ToList();

                    // has value
                    if (!string.IsNullOrEmpty(u.TaskForceName))
                    {
                        existingIds.Add(u.TaskForceId);
                        var existing = available.FirstOrDefault(f => f.Id == u.TaskForceId);
                        existing.NadaId = u.Id;
                        continue;
                    }

                    var match = available.FirstOrDefault(a => a.Name.ToLower() == u.Name.ToLower());
                    if (match != null)
                    {
                        SaveMatch(match, u, demo);
                        continue;
                    }
                    else
                    {
                        var index = tblNewUnits.RowStyles.Add(new RowStyle { SizeType = SizeType.AutoSize });
                        var chooser = new AdminUnitMatcher(u, available);
                        chooser.Margin = new Padding(0, 5, 10, 5);
                        tblNewUnits.Controls.Add(chooser, 0, index);
                        matchers.Add(chooser);
                    }
                }

                if (matchers.Count == 0)
                    DoNextStep();
            }
        }
Пример #6
0
        private void LoadAdminLevels()
        {
            SettingsRepository settings = new SettingsRepository();
            DemoRepository repo = new DemoRepository();
            var levels = settings.GetAllAdminLevels();
            var t = repo.GetAdminLevelTree(levels.OrderByDescending(l => l.LevelNumber).ToArray()[1].Id, 0, true, true, levelType);
            treeAvailable.CanExpandGetter = m => ((AdminLevel)m).Children.Count > 0;
            treeAvailable.ChildrenGetter = delegate(object m)
            {
                return ((AdminLevel)m).Children;
            };
            treeAvailable.SetObjects(t);

            foreach (var l in t)
            {
                treeAvailable.Expand(l);
                foreach (var l2 in l.Children)
                    treeAvailable.Expand(l2);
            }
        }
Пример #7
0
 private void Init(AdminLevelType type, IWizardStep step, bool demoOnly, int? cid)
 {
     countryDemoId = cid;
     isDemoOnly = demoOnly;
     locationType = type;
     prev = step;
     SettingsRepository settings = new SettingsRepository();
     DemoRepository demo = new DemoRepository();
     if (!isDemoOnly)
         demoDate = demo.GetCountryDemoRecent().DateDemographyData;
     if (!isSingleImport)
     {
         nextType = settings.GetNextLevel(locationType.LevelNumber);
         stepTitle = isDemoOnly ? Translations.UpdateDemography + " - " + locationType.DisplayName : Translations.ImportAdminLevels + locationType.DisplayName;
         importer = new AdminLevelDemoImporter(locationType, countryDemoId);
     }
     else
         stepTitle = Translations.Demography + " - " + locationType.DisplayName;
     updater = new AdminLevelDemoUpdater(locationType, countryDemoId);
     InitializeComponent();
 }
Пример #8
0
        private void Demo_Load(object sender, EventArgs e)
        {
            if (!DesignMode)
            {
                adminLevelBoundToGlobalTree = adminLevel;
                adminLevel = Util.DeepClone<AdminLevel>(adminLevel);

                Localizer.TranslateControl(this);
                demo = new DemoRepository();
                if (model == null)
                {
                    model = new AdminLevelDemography();
                    model.AdminLevelId = adminLevel.Id;
                }
                else
                    originalDate = model.DateDemographyData;

                lblType.Text = Translations.Demography;
                   
                StatusChanged(model.UpdatedBy);

                if (!canEdit)
                {
                    btnTopSave.Visible = false;
                    btnBottomSave.Visible = false;
                }

                if(!Roles.IsUserInRole(ApplicationData.Instance.CurrentUser.UserName, "RoleDataEnterer") &&
                !Roles.IsUserInRole(ApplicationData.Instance.CurrentUser.UserName, "RoleAdmin"))
                {
                    lnkEditAdminLevelUnit.Visible = false;
                    btnTopSave.Visible = false;
                    btnBottomSave.Visible = false;
                }

                bsDemo.DataSource = model;

                BindAdminLevel();
            }
        }
Пример #9
0
        public void LoadTree()
        {
            treeListView1.ClearObjects();
            DemoRepository r = new DemoRepository();
            var t = r.GetAdminLevelTree();
            treeListView1.CanExpandGetter = model => ((AdminLevel)model).
                                                          Children.Count > 0;
            treeListView1.ChildrenGetter = delegate(object model)
            {
                return ((AdminLevel)model).
                        Children;
            };
            treeListView1.SetObjects(t);

            if (preloadedLevel != null)
                LoadDashboard(preloadedLevel);
            else if (t.Count > 0)
                LoadDashboard(t.FirstOrDefault());

            var root = t.FirstOrDefault();
            treeListView1.Expand(root);
        }
Пример #10
0
        public void BindData(AdminLevel e, List<TaskForceAdminUnit> u)
        {
            Localizer.TranslateControl(this);
            existing = e;
            taskForceUnits = u;
            h3Required1.SetMaxWidth(300);
            DemoRepository demo = new DemoRepository();
            var parentNames = demo.GetAdminLevelParentNames(existing.Id);
            if (parentNames.Count == 0)
                h3Required1.Text = e.Name;
            else
                h3Required1.Text = "";
            foreach (var pname in parentNames)
                h3Required1.Text += pname.Name + " > ";

            if (h3Required1.Text.EndsWith(" > "))
                h3Required1.Text = h3Required1.Text.Substring(0, h3Required1.Text.LastIndexOf(" > "));

            taskForceUnits.Insert(0, new TaskForceAdminUnit { Id = -1, Name = "" });
            bindingSource1.DataSource = taskForceUnits;

            if (taskForceUnits.Count > 1)
                cbUnits.DropDownWidth = BaseForm.GetDropdownWidth(taskForceUnits.Select(a => a.Name));
        }
 public void Select(int id)
 {
     DemoRepository repo = new DemoRepository();
     AdminLevel level = repo.GetAdminLevelById(id);
     Select(level);
 }
Пример #12
0
        public void DoNext()
        {
            var invalid = matchers.FirstOrDefault(m => !m.IsValid());
            if (invalid != null)
            {
                MessageBox.Show(Translations.SplittingMustAllocateSaes, Translations.ValidationErrorTitle);
                return;
            }

            options.Saes = new List<Model.Process.ProcessBase>();
            DemoRepository demo = new DemoRepository();
            foreach (SaeMatcher m in matchers)
            {
                var sae = m.GetSae();
                if(sae != null)
                    options.Saes.Add(sae);
            }

            DoNextStep();
        }
Пример #13
0
        private bool SaveCountry()
        {
            countryView1.DoValidate();
            if (!model.IsValid())
            {
                MessageBox.Show(Translations.ValidationError, Translations.ValidationErrorTitle);
                return false;
            }
            if (!adminLevelTypesControl1.HasAggregatingLevel())
            {
                MessageBox.Show(Translations.MustMakeAggregatingLevel, Translations.ValidationErrorTitle);
                return false;
            }

            int userId = ApplicationData.Instance.GetUserId();
            var demo = new DemoRepository();
            demo.UpdateCountry(model, userId);
            return true;
        }
        public override ReportResult Run(SavedReport report)
        {
            EliminationReportOptions standardOpts = (EliminationReportOptions)report.StandardReportOptions;
            ReportOptions options = report.ReportOptions;
            DistributionReportGenerator gen = new DistributionReportGenerator();
            DiseaseRepository repo = new DiseaseRepository();
            DemoRepository demo = new DemoRepository();
            foreach (var disease in standardOpts.Diseases)
            {
                DiseaseDistroPc dd = repo.Create((DiseaseType)disease.Id);

                switch (disease.Id)
                {
                    case (int)DiseaseType.Lf:
                        AddIndicators(disease.Id, "DDLFDiseaseDistributionPcInterventions", dd, options);
                        break;
                    case (int)DiseaseType.Trachoma:
                        AddIndicators(disease.Id, "DDTraDiseaseDistributionPcInterventions", dd, options);
                        break;
                    case (int)DiseaseType.Oncho:
                        AddIndicators(disease.Id, "DDOnchoDiseaseDistributionPcInterventio", dd, options);
                        break;
                    case (int)DiseaseType.STH:
                        AddIndicators(disease.Id, "DDSTHDiseaseDistributionPcInterventions", dd, options);
                        break;
                    case (int)DiseaseType.Schisto:
                        AddIndicators(disease.Id, "DDSchistoDiseaseDistributionPcIntervent", dd, options);
                        break;
                    default:
                        break;
                }
            }

            // need to add the proper sumation stuff
            report.ReportOptions.IsByLevelAggregation = true;
            report.ReportOptions.IsCountryAggregation = false;
            report.ReportOptions.IsNoAggregation = false;
            report.ReportOptions.SelectedAdminLevels = demo.GetAdminLevelByLevel(standardOpts.DistrictType.LevelNumber).Where(a => a.LevelNumber == standardOpts.DistrictType.LevelNumber).ToList();

            // run report
            ReportResult result = gen.Run(report);

            Dictionary<string, DataRow> years = new Dictionary<string,DataRow>();
            DataTable summed = new DataTable();
            summed.Columns.Add(new DataColumn(TranslationLookup.GetValue("Location")));
            summed.Columns.Add(new DataColumn(TranslationLookup.GetValue("Year"), typeof(string)));
            summed.Columns.Add(new DataColumn(string.Format(TranslationLookup.GetValue("EliminationEndemicDistricts"), standardOpts.DistrictType.DisplayName), typeof(int)));
            summed.Columns.Add(new DataColumn(string.Format(TranslationLookup.GetValue("EliminationStoppedDistricts"), standardOpts.DistrictType.DisplayName), typeof(int)));
            
            foreach (DataRow row in result.DataTableResults.Rows)
            {
                string endemicty = "";
                int totalEndemic = 0, totalStopped = 0;
                if (result.DataTableResults.Columns.Contains(TranslationLookup.GetValue("DDLFDiseaseDistributionPcInterventions") + " - " + TranslationLookup.GetValue("LF")))
                {
                    endemicty = row[TranslationLookup.GetValue("DDLFDiseaseDistributionPcInterventions") + " - " + TranslationLookup.GetValue("LF")].ToString();
                    if (endemicty == TranslationLookup.GetValue("LfEnd1") || endemicty == TranslationLookup.GetValue("LfEndPending"))
                        totalEndemic++;
                    else if (endemicty == TranslationLookup.GetValue("LfEnd100"))
                        totalStopped++;
                }
                if (result.DataTableResults.Columns.Contains(TranslationLookup.GetValue("DDOnchoDiseaseDistributionPcInterventio") + " - " + TranslationLookup.GetValue("Oncho")))
                {
                    endemicty = row[TranslationLookup.GetValue("DDOnchoDiseaseDistributionPcInterventio") + " - " + TranslationLookup.GetValue("Oncho")].ToString();
                    if (endemicty == TranslationLookup.GetValue("Oncho1") || endemicty == TranslationLookup.GetValue("OnchoPending"))
                        totalEndemic++;
                    else if (endemicty == TranslationLookup.GetValue("Oncho100"))
                        totalStopped++;
                }
                if (result.DataTableResults.Columns.Contains(TranslationLookup.GetValue("DDSchistoDiseaseDistributionPcIntervent") + " - " + TranslationLookup.GetValue("Schisto")))
                {
                    endemicty = row[TranslationLookup.GetValue("DDSchistoDiseaseDistributionPcIntervent") + " - " + TranslationLookup.GetValue("Schisto")].ToString();
                    if (endemicty == TranslationLookup.GetValue("Sch1") || endemicty == TranslationLookup.GetValue("Sch2") || endemicty == TranslationLookup.GetValue("Sch2a") || endemicty == TranslationLookup.GetValue("Sch3") || endemicty == TranslationLookup.GetValue("Sch3a")
                        || endemicty == TranslationLookup.GetValue("Sch3b") || endemicty == TranslationLookup.GetValue("Sch20") || endemicty == TranslationLookup.GetValue("Sch30") || endemicty == TranslationLookup.GetValue("Sch40")
                        || endemicty == TranslationLookup.GetValue("SchPending"))
                        totalEndemic++;
                    else if (endemicty == TranslationLookup.GetValue("Sch100"))
                        totalStopped++;
                }

                if (result.DataTableResults.Columns.Contains(TranslationLookup.GetValue("DDSTHDiseaseDistributionPcInterventions") + " - " + TranslationLookup.GetValue("STH")))
                {
                    endemicty = row[TranslationLookup.GetValue("DDSTHDiseaseDistributionPcInterventions") + " - " + TranslationLookup.GetValue("STH")].ToString();
                    if (endemicty == TranslationLookup.GetValue("Sth2") || endemicty == TranslationLookup.GetValue("Sth3") || endemicty == TranslationLookup.GetValue("Sth10") || endemicty == TranslationLookup.GetValue("Sth20")
                        || endemicty == TranslationLookup.GetValue("Sth30") || endemicty == TranslationLookup.GetValue("Sth40") || endemicty == TranslationLookup.GetValue("SthPending"))
                        totalEndemic++;
                    else if (endemicty == TranslationLookup.GetValue("Sth100"))
                        totalStopped++;
                }
                if (result.DataTableResults.Columns.Contains(TranslationLookup.GetValue("DDTraDiseaseDistributionPcInterventions") + " - " + TranslationLookup.GetValue("Trachoma")))
                {
                    endemicty = row[TranslationLookup.GetValue("DDTraDiseaseDistributionPcInterventions") + " - " + TranslationLookup.GetValue("Trachoma")].ToString();
                    if (endemicty == TranslationLookup.GetValue("Tra1") || endemicty == TranslationLookup.GetValue("Tra4") || endemicty == TranslationLookup.GetValue("Tra5")
                        || endemicty == TranslationLookup.GetValue("TraPending"))
                        totalEndemic++;
                    else if (endemicty == TranslationLookup.GetValue("Tra100"))
                        totalStopped++;
                }

                if (!years.ContainsKey(row[TranslationLookup.GetValue("Year")].ToString()))
                {
                    DataRow dr = summed.NewRow();
                    dr[TranslationLookup.GetValue("Year")] = row[TranslationLookup.GetValue("Year")];
                    dr[string.Format(TranslationLookup.GetValue("EliminationEndemicDistricts"), standardOpts.DistrictType.DisplayName)] = totalEndemic;
                    dr[string.Format(TranslationLookup.GetValue("EliminationStoppedDistricts"), standardOpts.DistrictType.DisplayName)] = totalStopped;
                    years.Add(row[TranslationLookup.GetValue("Year")].ToString(), dr);
                    summed.Rows.Add(dr);
                }
                else
                {
                    years[row[TranslationLookup.GetValue("Year")].ToString()][string.Format(TranslationLookup.GetValue("EliminationEndemicDistricts"), standardOpts.DistrictType.DisplayName)] =
                        totalEndemic + (int)years[row[TranslationLookup.GetValue("Year")].ToString()][string.Format(TranslationLookup.GetValue("EliminationEndemicDistricts"), standardOpts.DistrictType.DisplayName)];
                    years[row[TranslationLookup.GetValue("Year")].ToString()][string.Format(TranslationLookup.GetValue("EliminationStoppedDistricts"), standardOpts.DistrictType.DisplayName)] =
                        totalStopped + (int)years[row[TranslationLookup.GetValue("Year")].ToString()][string.Format(TranslationLookup.GetValue("EliminationStoppedDistricts"), standardOpts.DistrictType.DisplayName)];
                }
            }

            result.DataTableResults = summed;
            result.ChartData = summed.Copy();
            report.ReportOptions.IsByLevelAggregation = false;
            report.ReportOptions.IsCountryAggregation = true; // to show only year

            return result;
        }
Пример #15
0
        public void CreateUpdateFile(string filename, List<IHaveDynamicIndicatorValues> forms)
        {
            ReloadDropdownValues();
            LoadRelatedLists();
            System.Globalization.CultureInfo oldCI = System.Threading.Thread.CurrentThread.CurrentCulture;
            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
            Microsoft.Office.Interop.Excel.Application xlsApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
            Microsoft.Office.Interop.Excel.Workbook xlsWorkbook;
            Microsoft.Office.Interop.Excel.Workbooks xlsWorkbooks;
            Microsoft.Office.Interop.Excel.Sheets xlsWorksheets;
            Microsoft.Office.Interop.Excel.Worksheet xlsWorksheet;
            Microsoft.Office.Interop.Excel.Worksheet xlsValidation;
            object oMissing = System.Reflection.Missing.Value;
            validationRanges = new Dictionary<string, string>();

            //Create new workbook
            xlsWorkbooks = xlsApp.Workbooks;
            xlsWorkbook = xlsWorkbooks.Add(true);
            xlsWorksheets = xlsWorkbook.Worksheets;

            //Get the first worksheet
            xlsWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)(xlsWorkbook.Worksheets[1]);

            // add hidden validation worksheet
            xlsValidation = (Microsoft.Office.Interop.Excel.Worksheet)xlsWorksheets.Add(oMissing, xlsWorksheet, oMissing, oMissing);
            xlsValidation.Name = validationSheetName;
            xlsValidation.Visible = Microsoft.Office.Interop.Excel.XlSheetVisibility.xlSheetHidden;

            xlsWorksheet.Cells[1, 1] = "* " + TranslationLookup.GetValue("ID");
            xlsWorksheet.Cells[1, 2] = "* " + TranslationLookup.GetValue("Location");
            int locationCount = 2;
            int xlsColCount = 2;
            xlsColCount = AddTypeSpecific(xlsWorksheet, xlsColCount);
            int colCountAfterStatic = xlsColCount;

            foreach (var item in Indicators)
            {
                if (item.Value.DataTypeId == (int)IndicatorDataType.SentinelSite || item.Value.IsCalculated || item.Value.IsMetaData)
                    continue;
                string isReq = "";
                if (item.Value.IsRequired)
                    isReq = "* ";

                xlsColCount++;
                xlsWorksheet.Cells[1, xlsColCount] = isReq + TranslationLookup.GetValue(item.Key, item.Key);
            }
            //xlsWorksheet.Cells[1, xlsColCount + 1] = TranslationLookup.GetValue("Notes");

            // row 2+ admin levels
            DemoRepository repo = new DemoRepository();
            int xlsRowCount = 2;
            foreach (var form in forms)
            {

                var adminLevel = repo.GetAdminLevelById(form.AdminLevelId.Value);
                xlsWorksheet.Cells[xlsRowCount, 1] = form.Id;
                xlsWorksheet.Cells[xlsRowCount, 2] = GetAdminLevelName(adminLevel, form);
                AddTypeSpecificLists(xlsWorksheet, xlsValidation, adminLevel.Id, xlsRowCount, oldCI, locationCount);
                AddTypeSpecificListValues(xlsWorksheet, xlsValidation, adminLevel.Id, xlsRowCount, oldCI, locationCount, form);
                int colCount = colCountAfterStatic;
                foreach (var key in Indicators.Keys)
                {
                    if (Indicators[key].DataTypeId == (int)IndicatorDataType.SentinelSite || Indicators[key].IsCalculated || Indicators[key].IsMetaData)
                        continue;

                    string value = "";
                    var iv = form.IndicatorValues.FirstOrDefault(x => x.IndicatorId == Indicators[key].Id);
                    if (iv != null)
                        value = iv.DynamicValue;
                    colCount++;
                    colCount = AddValueToCell(xlsWorksheet, xlsValidation, colCount, xlsRowCount, value, Indicators[key], oldCI, true);
                }
                xlsRowCount++;
            }

            // Auto fit
            var last = xlsWorksheet.Cells.SpecialCells(Microsoft.Office.Interop.Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
            var range = xlsWorksheet.get_Range("A1", last);
            range.Columns.AutoFit();

            // Save and display
            xlsApp.DisplayAlerts = false;
            xlsWorkbook.SaveAs(filename, Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook, oMissing,
                oMissing, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
                Microsoft.Office.Interop.Excel.XlSaveConflictResolution.xlUserResolution, true,
                oMissing, oMissing, oMissing);
            xlsApp.Visible = true;
            Marshal.ReleaseComObject(xlsWorksheets);
            Marshal.ReleaseComObject(xlsWorksheet);
            Marshal.ReleaseComObject(xlsValidation);
            Marshal.ReleaseComObject(xlsWorkbooks);
            Marshal.ReleaseComObject(xlsWorkbook);
            Marshal.ReleaseComObject(xlsApp);
            System.Threading.Thread.CurrentThread.CurrentCulture = oldCI;
        }
Пример #16
0
        public virtual void CreateImportFile(string filename, List<AdminLevel> adminLevels, AdminLevelType adminLevelType, ImportOptions opts)
        {
            options = opts;
            ReloadDropdownValues();
            LoadRelatedLists();
            System.Globalization.CultureInfo oldCI = System.Threading.Thread.CurrentThread.CurrentCulture;
            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
            Microsoft.Office.Interop.Excel.Application xlsApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
            Microsoft.Office.Interop.Excel.Workbook xlsWorkbook;
            Microsoft.Office.Interop.Excel.Workbooks xlsWorkbooks;
            Microsoft.Office.Interop.Excel.Sheets xlsWorksheets;
            Microsoft.Office.Interop.Excel.Worksheet xlsWorksheet;
            Microsoft.Office.Interop.Excel.Worksheet xlsValidation;
            object oMissing = System.Reflection.Missing.Value;
            validationRanges = new Dictionary<string, string>();

            //Create new workbook
            xlsWorkbooks = xlsApp.Workbooks;
            xlsWorkbook = xlsWorkbooks.Add(true);
            xlsWorksheets = xlsWorkbook.Worksheets;

            //Get the first worksheet
            xlsWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)(xlsWorkbook.Worksheets[1]);

            // add hidden validation worksheet
            xlsValidation = (Microsoft.Office.Interop.Excel.Worksheet)xlsWorksheets.Add(oMissing, xlsWorksheet, oMissing, oMissing);
            xlsValidation.Name = validationSheetName;
            xlsValidation.Visible = Microsoft.Office.Interop.Excel.XlSheetVisibility.xlSheetHidden;

            // row 1 column headers
            DemoRepository repo = new DemoRepository();
            List<string> names = adminLevelType == null? new List<string>() : repo.GetAdminLevelTypeNames(adminLevelType.Id);

            if (options.SurveyNames.Count > 0) // Multiple admin units for surveys
                xlsWorksheet.Cells[1, 1] = "* " + TranslationLookup.GetValue("SurveyName");
            else
                xlsWorksheet.Cells[1, 1] = "* " + TranslationLookup.GetValue("ID");
            
            for (int i = 0; i < names.Count; i++)
                xlsWorksheet.Cells[1, 2 + i] = "* " + names[i];
            int locationCount = names.Count + 1;
            int xlsColCount = names.Count + 1; // add one for id;
            xlsColCount = AddTypeSpecific(xlsWorksheet, xlsColCount);
            int colCountAfterStatic = xlsColCount;

            foreach (var item in Indicators)
            {
                if (item.Value.DataTypeId == (int)IndicatorDataType.SentinelSite || item.Value.IsCalculated || item.Value.IsMetaData)
                    continue;
                string isReq = "";
                if (item.Value.IsRequired)
                    isReq = "* ";

                // if the filtered list still has more than 7 possible multiselect values, do some weird shit.
                if (options.IndicatorValuesSublist.ContainsKey(item.Value.DisplayName) && options.IndicatorValuesSublist[item.Value.DisplayName].Count > 6)
                {
                    int optionNumber = 1;
                    foreach (string opt in options.IndicatorValuesSublist[item.Value.DisplayName])
                    {
                        xlsColCount++;
                        xlsWorksheet.Cells[1, xlsColCount] = isReq + TranslationLookup.GetValue(item.Key, item.Key) + Translations.ImportSelectionOption + optionNumber;
                        optionNumber++;
                    }
                }
                else
                {
                    xlsColCount++;
                    xlsWorksheet.Cells[1, xlsColCount] = isReq + TranslationLookup.GetValue(item.Key, item.Key);
                }
            }
            //xlsWorksheet.Cells[1, xlsColCount + 1] = TranslationLookup.GetValue("Notes");

            // row 2+ admin levels
            int xlsRowCount = 2;
            if (options.SurveyNames.Count > 0) // Multiple admin units for surveys
            {
                foreach (var survey in options.SurveyNames.OrderBy(a => a.DisplayName))
                {
                    xlsWorksheet.Cells[xlsRowCount, 1] = survey.DisplayName;
                    AddTypeSpecificLists(xlsWorksheet, xlsValidation, 0, xlsRowCount, oldCI, locationCount);
                    xlsRowCount = AddIndicatorColumns(oldCI, xlsWorksheet, xlsValidation, colCountAfterStatic, xlsRowCount);
                }
            }
            else
            {
                foreach (AdminLevel l in adminLevels.OrderBy(a => a.SortOrder))
                {
                    xlsWorksheet.Cells[xlsRowCount, 1] = l.Id;
                    List<AdminLevel> parents = repo.GetAdminLevelParentNames(l.Id);
                    int aCol = 2;
                    foreach (AdminLevel adminlevel in parents)
                    {
                        xlsWorksheet.Cells[xlsRowCount, aCol] = adminlevel.Name;
                        aCol++;
                    }
                    AddTypeSpecificLists(xlsWorksheet, xlsValidation, l.Id, xlsRowCount, oldCI, locationCount);
                    xlsRowCount = AddIndicatorColumns(oldCI, xlsWorksheet, xlsValidation, colCountAfterStatic, xlsRowCount);
                }
            }

            // Auto fit
            var last = xlsWorksheet.Cells.SpecialCells(Microsoft.Office.Interop.Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
            var range = xlsWorksheet.get_Range("A1", last);
            range.Columns.AutoFit();

            // Save and display
            xlsApp.DisplayAlerts = false;
            xlsWorkbook.SaveAs(filename, Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook, oMissing,
                oMissing, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
                Microsoft.Office.Interop.Excel.XlSaveConflictResolution.xlUserResolution, true,
                oMissing, oMissing, oMissing);
            xlsApp.Visible = true;
            Marshal.ReleaseComObject(xlsWorksheets);
            Marshal.ReleaseComObject(xlsWorksheet);
            Marshal.ReleaseComObject(xlsValidation);
            Marshal.ReleaseComObject(xlsWorkbooks);
            Marshal.ReleaseComObject(xlsWorkbook);
            Marshal.ReleaseComObject(xlsApp);
            System.Threading.Thread.CurrentThread.CurrentCulture = oldCI;
        }
 private void SaveMatch(TaskForceAdminUnit match, AdminLevel u, DemoRepository demo)
 {
     match.NadaId = u.Id;
     var adminLevel = demo.GetAdminLevelById(u.Id);
     adminLevel.TaskForceId = match.Id;
     adminLevel.TaskForceName = match.Name;
     demo.UpdateTaskForceData(adminLevel, ApplicationData.Instance.GetUserId());
 }
 public SentinelSitePickerControl()
 {
     r = new SurveyRepository();
     demo = new DemoRepository();
     InitializeComponent();
 }
Пример #19
0
        private DataTable CreateInsertDataTable(AdminLevelType type)
        {
            DataTable data = new System.Data.DataTable();
            data.Columns.Add(new System.Data.DataColumn("* " + TranslationLookup.GetValue("Location") + "#"));
            data.Columns.Add(new System.Data.DataColumn("* " + TranslationLookup.GetValue("YearCensus")));
            data.Columns.Add(new System.Data.DataColumn("* " + TranslationLookup.GetValue("GrowthRate")));
            data.Columns.Add(new System.Data.DataColumn("* " + TranslationLookup.GetValue("TotalPopulation")));
            data.Columns.Add(new System.Data.DataColumn(TranslationLookup.GetValue("Pop0Month")));
            data.Columns.Add(new System.Data.DataColumn(TranslationLookup.GetValue("PopPsac")));
            data.Columns.Add(new System.Data.DataColumn("* " + TranslationLookup.GetValue("PopSac")));
            data.Columns.Add(new System.Data.DataColumn(TranslationLookup.GetValue("Pop5yo")));
            data.Columns.Add(new System.Data.DataColumn(TranslationLookup.GetValue("PopAdult")));
            data.Columns.Add(new System.Data.DataColumn(TranslationLookup.GetValue("PopFemale")));
            data.Columns.Add(new System.Data.DataColumn(TranslationLookup.GetValue("PopMale")));
            data.Columns.Add(new System.Data.DataColumn(TranslationLookup.GetValue("PercentRural")));
            data.Columns.Add(new System.Data.DataColumn(TranslationLookup.GetValue("Notes")));

            DemoRepository drepo = new DemoRepository();
            var allUnits = drepo.GetAdminLevelByLevel(type.LevelNumber);
            foreach (AdminLevel l in allUnits)
            {
                DataRow row = data.NewRow();
                row["* " + TranslationLookup.GetValue("Location") + "#"] = l.Id; 

                List<AdminLevel> parents = demo.GetAdminLevelParentNames(l.Id);
                for (int i = 0; i < parents.Count; i++)
                {
                    if (!data.Columns.Contains("* " + parents[i].LevelName))
                    {
                        DataColumn dc = new DataColumn("* " + parents[i].LevelName);
                        data.Columns.Add(dc);
                        dc.SetOrdinal(i + 1);
                    }
                    row["* " + parents[i].LevelName] = parents[i].Name;
                }
                
                data.Rows.Add(row);
            }
            return data;
        }
        public void DoNext()
        {
            var selectedIds = new List<int>();
            selectedIds.AddRange(existingIds);
            var invalid = matchers.FirstOrDefault(m => !m.IsValid(selectedIds));
            if (invalid != null)
            {
                MessageBox.Show(Translations.RtiErrorMustMatchAll, Translations.ValidationErrorTitle);
                return;
            }
            if (selectedIds.Distinct().Count() != selectedIds.Count())
            {
                MessageBox.Show(Translations.RtiErrorMustBeUnique, Translations.ValidationErrorTitle);
                return;
            }

            DemoRepository demo = new DemoRepository();
            foreach (AdminUnitMatcher m in matchers)
                SaveMatch(m.GetSelected(), m.GetAdminUnit(), demo);

            DoNextStep();
        }
Пример #21
0
        public void CreateImportFile(string filename, bool importDemography, int rows, AdminLevel filterLevel)
        {
            // Get data
            filterBy = filterLevel;
            int dropdownCol = GetParams();
            DataTable data = CreateNewImportDataTable(importDemography);
            DemoRepository demo = new DemoRepository();
            CountryDemography recentCountryDemo = demo.GetCountryDemoRecent();

            // Create excel
            System.Globalization.CultureInfo oldCI = System.Threading.Thread.CurrentThread.CurrentCulture;
            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
            Microsoft.Office.Interop.Excel.Application xlsApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
            Microsoft.Office.Interop.Excel.Workbook xlsWorkbook;
            Microsoft.Office.Interop.Excel.Worksheet xlsWorksheet;
            Microsoft.Office.Interop.Excel.Worksheet xlsValidation;
            object oMissing = System.Reflection.Missing.Value;
            validationRanges = new Dictionary<string, string>();

            //Create new workbook
            xlsWorkbook = xlsApp.Workbooks.Add(true);

            //Get the first worksheet
            xlsWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)(xlsWorkbook.Worksheets[1]);

            // add hidden validation worksheet
            xlsValidation = (Microsoft.Office.Interop.Excel.Worksheet)xlsWorkbook.Worksheets.Add(oMissing, xlsWorksheet, oMissing, oMissing);
            xlsValidation.Name = validationSheetName;
            xlsValidation.Visible = Microsoft.Office.Interop.Excel.XlSheetVisibility.xlSheetHidden;

            // Add columns
            int iCol = 0;
            foreach (DataColumn c in data.Columns)
            {
                iCol++;
                xlsWorksheet.Cells[1, iCol] = c.ColumnName;
            }
            string totalPopColumn = "F";
            // Add rows
            for (int r = 1; r <= rows + 1; r++)
            {
                for (int i = 1; i < data.Columns.Count + 1; i++)
                {
                    if (r == 1)
                    {
                        // Add the header the first time through 
                        xlsWorksheet.Cells[1, i] = data.Columns[i - 1].ColumnName;
                    }
                    else
                    {
                        if (i == 1 && filterByType != null)
                            xlsWorksheet.Cells[r, i] = filterLevel.Name;
                        if (dropdownCol == i && dropdownValues.Count > 0)
                        {
                            AddDataValidation(xlsWorksheet, xlsValidation, Util.GetExcelColumnName(i), r, dropdownBy.DisplayName, TranslationLookup.GetValue("PleaseSelect"), dropdownValues, oldCI);
                        }

                        if (data.Columns[i - 1].ColumnName == TranslationLookup.GetValue("UrbanOrRural"))
                            AddDataValidation(xlsWorksheet, xlsValidation, Util.GetExcelColumnName(i), r, TranslationLookup.GetValue("UrbanOrRural"), TranslationLookup.GetValue("PleaseSelect"), 
                                new List<string> { TranslationLookup.GetValue("AdminUnitUrban"),  TranslationLookup.GetValue("AdminUnitRural"),  TranslationLookup.GetValue("AdminUnitPeriRural")}, oldCI);
                        
                        if (importDemography)
                        {
                            if (data.Columns[i - 1].ColumnName == "* " + TranslationLookup.GetValue("YearCensus"))
                                xlsWorksheet.Cells[r, i] = recentCountryDemo.YearCensus;
                            if (data.Columns[i - 1].ColumnName == "* " + TranslationLookup.GetValue("GrowthRate"))
                                xlsWorksheet.Cells[r, i] = recentCountryDemo.GrowthRate;
                            if (data.Columns[i - 1].ColumnName == "* " + TranslationLookup.GetValue("TotalPopulation"))
                                totalPopColumn = Util.GetExcelColumnName(i);
                            if (data.Columns[i - 1].ColumnName == TranslationLookup.GetValue("Pop0Month") && recentCountryDemo.Percent6mos.HasValue)
                                xlsWorksheet.Cells[r, i] = string.Format("={2}{1}*{0}/100", recentCountryDemo.Percent6mos, r, totalPopColumn);
                            if (data.Columns[i - 1].ColumnName == TranslationLookup.GetValue("PopPsac") && recentCountryDemo.PercentPsac.HasValue)
                                xlsWorksheet.Cells[r, i] = string.Format("={2}{1}*{0}/100", recentCountryDemo.PercentPsac, r, totalPopColumn);
                            if (data.Columns[i - 1].ColumnName == "* " + TranslationLookup.GetValue("PopSac") && recentCountryDemo.PercentSac.HasValue)
                                xlsWorksheet.Cells[r, i] = string.Format("={2}{1}*{0}/100", recentCountryDemo.PercentSac, r, totalPopColumn);
                            if (data.Columns[i - 1].ColumnName == TranslationLookup.GetValue("Pop5yo") && recentCountryDemo.Percent5yo.HasValue)
                                xlsWorksheet.Cells[r, i] = string.Format("={2}{1}*{0}/100", recentCountryDemo.Percent5yo, r, totalPopColumn);
                            if (data.Columns[i - 1].ColumnName == TranslationLookup.GetValue("PopAdult") && recentCountryDemo.PercentAdult.HasValue)
                                xlsWorksheet.Cells[r, i] = string.Format("={2}{1}*{0}/100", recentCountryDemo.PercentAdult, r, totalPopColumn);
                            if (data.Columns[i - 1].ColumnName == TranslationLookup.GetValue("PopFemale") && recentCountryDemo.PercentFemale.HasValue)
                                xlsWorksheet.Cells[r, i] = string.Format("={2}{1}*{0}/100", recentCountryDemo.PercentFemale, r, totalPopColumn);
                            if (data.Columns[i - 1].ColumnName == TranslationLookup.GetValue("PopMale") && recentCountryDemo.PercentMale.HasValue)
                                xlsWorksheet.Cells[r, i] = string.Format("={2}{1}*{0}/100", recentCountryDemo.PercentMale, r, totalPopColumn);
                            if (data.Columns[i - 1].ColumnName == TranslationLookup.GetValue("PercentRural") && recentCountryDemo.PercentRural.HasValue)
                                xlsWorksheet.Cells[r, i] = string.Format("={2}{1}*{0}/100", recentCountryDemo.PercentRural, r, totalPopColumn);
                        }
                    }
                }
            }

            var last = xlsWorksheet.Cells.SpecialCells(Microsoft.Office.Interop.Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
            var range = xlsWorksheet.get_Range("A1", last);
            range.Columns.AutoFit();

            xlsApp.DisplayAlerts = false;
            xlsWorkbook.SaveAs(filename, Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook, oMissing,
                oMissing, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
                Microsoft.Office.Interop.Excel.XlSaveConflictResolution.xlUserResolution, true,
                oMissing, oMissing, oMissing);
            xlsApp.Visible = true;
            xlsWorksheet = null;
            xlsValidation = null;
            xlsWorkbook = null;
            xlsApp = null;
            System.Threading.Thread.CurrentThread.CurrentCulture = oldCI;
        }
Пример #22
0
        protected string GetRecentDistroIndicator(int adminLevelId, string indicatorName, DiseaseType diseaseType, DateTime start, DateTime end, ref string errors)
        {
            // If there is a RecentDistro instance, look for the value there
            RecentDistro recentDistro = RecentDistro.GetInstance(false /* don't instantiate */);
            if (recentDistro != null)
            {
                string storedVal = recentDistro.GetRecentDistroIndicator(adminLevelId, indicatorName, diseaseType, start, end, ref errors);
                if (storedVal != null)
                {
                    return storedVal;
                }
            }

            AdminLevelIndicators levelInds = null;
            string key = adminLevelId + start.ToShortDateString() + end.ToShortDateString() + diseaseType.ToString();
            if (distroDict.ContainsKey(key))
                levelInds = distroDict[key];
            else
            {
                ReportOptions options = new ReportOptions();
                DistributionReportGenerator gen = new DistributionReportGenerator();
                DiseaseRepository repo = new DiseaseRepository();
                DemoRepository demo = new DemoRepository();
                var disease = repo.GetDiseaseById((int)diseaseType);
                DiseaseDistroPc dd = repo.Create(diseaseType);
                if (diseaseType == DiseaseType.STH)
                {
                    options.SelectedIndicators.Add(ReportRepository.CreateReportIndicator((int)diseaseType,
                        new KeyValuePair<string, Indicator>(indicatorName, new Indicator { Id = 141, DisplayName = "DDSTHPopulationRequiringPc" })));
                    options.SelectedIndicators.Add(ReportRepository.CreateReportIndicator((int)diseaseType,
                        new KeyValuePair<string, Indicator>(indicatorName, new Indicator { Id = 142, DisplayName = "DDSTHPsacAtRisk" })));
                    options.SelectedIndicators.Add(ReportRepository.CreateReportIndicator((int)diseaseType,
                        new KeyValuePair<string, Indicator>(indicatorName, new Indicator { Id = 143, DisplayName = "DDSTHSacAtRisk" })));
                    options.SelectedIndicators.Add(ReportRepository.CreateReportIndicator((int)diseaseType,
                        new KeyValuePair<string, Indicator>(indicatorName, new Indicator { Id = 140, DisplayName = "DDSTHPopulationAtRisk" })));
                }
                else if (diseaseType == DiseaseType.Lf)
                {
                    options.SelectedIndicators.Add(ReportRepository.CreateReportIndicator((int)diseaseType,
                    new KeyValuePair<string, Indicator>(indicatorName, new Indicator { Id = 98, DisplayName = "DDLFPopulationAtRisk" })));
                    options.SelectedIndicators.Add(ReportRepository.CreateReportIndicator((int)diseaseType,
                        new KeyValuePair<string, Indicator>(indicatorName, new Indicator { Id = 99, DisplayName = "DDLFPopulationRequiringPc" })));
                }
                else if (diseaseType == DiseaseType.Oncho)
                {
                    options.SelectedIndicators.Add(ReportRepository.CreateReportIndicator((int)diseaseType,
                    new KeyValuePair<string, Indicator>(indicatorName, new Indicator { Id = 111, DisplayName = "DDOnchoPopulationAtRisk" })));
                    options.SelectedIndicators.Add(ReportRepository.CreateReportIndicator((int)diseaseType,
                        new KeyValuePair<string, Indicator>(indicatorName, new Indicator { Id = 112, DisplayName = "DDOnchoPopulationRequiringPc" })));
                }
                else if (diseaseType == DiseaseType.Schisto)
                {
                    options.SelectedIndicators.Add(ReportRepository.CreateReportIndicator((int)diseaseType,
                        new KeyValuePair<string, Indicator>(indicatorName, new Indicator { Id = 125, DisplayName = "DDSchistoPopulationAtRisk" })));
                    options.SelectedIndicators.Add(ReportRepository.CreateReportIndicator((int)diseaseType,
                        new KeyValuePair<string, Indicator>(indicatorName, new Indicator { Id = 126, DisplayName = "DDSchistoPopulationRequiringPc" })));
                    options.SelectedIndicators.Add(ReportRepository.CreateReportIndicator((int)diseaseType,
                        new KeyValuePair<string, Indicator>(indicatorName, new Indicator { Id = 127, DisplayName = "DDSchistoSacAtRisk" })));
                }
                else if (diseaseType == DiseaseType.Trachoma)
                options.SelectedIndicators.Add(ReportRepository.CreateReportIndicator((int)diseaseType,
                    new KeyValuePair<string, Indicator>(indicatorName, new Indicator { Id = 161, DisplayName = "DDTraPopulationAtRisk" })));

                options.StartDate = start;
                options.EndDate = end;
                options.MonthYearStarts = start.Month;
                var adminlevel = demo.GetAdminLevelById(adminLevelId);
                options.SelectedAdminLevels = new List<AdminLevel> { adminlevel };
                options.IsNoAggregation = false;
                options.IsByLevelAggregation = true;
                options.IsAllLocations = false;

                levelInds = gen.GetRecentDiseaseDistribution(options);
                levelInds.StartDate = start;
                levelInds.EndDate = end;
                levelInds.DiseaseName = disease.DisplayName;
            }
            if (levelInds.Indicators.ContainsKey(indicatorName) )
            {
                if(!string.IsNullOrEmpty(levelInds.Indicators[indicatorName].Value))
                    return levelInds.Indicators[indicatorName].Value.ToString();
                else
                    return "";
            }
            string error = string.Format(Translations.ReportsNoDdInDateRange, levelInds.Name, start.ToShortDateString(), end.ToShortDateString(), levelInds.DiseaseName) + Environment.NewLine;
            if (!errors.Contains(error))
                errors += error;
            return Translations.NA;
        }
Пример #23
0
        private void AddFootnote(DataTable dataTable)
        {
            for (int i = 0; i < 3; i++)
            {
                var row = dataTable.NewRow();
                dataTable.Rows.Add(row);
            }

            DemoRepository demo = new DemoRepository();
            var country = demo.GetCountry();
            var name = dataTable.NewRow();
            name[0] = country.Name + " " + DateTime.Now.ToString("yyyy-MM-dd");
            dataTable.Rows.Add(name);
            var daterange = dataTable.NewRow();
            daterange[0] = Translations.DateRange + ": " + report.ReportOptions.StartDate.ToString("yyyy-MM-dd") + " -- " + report.ReportOptions.EndDate.ToString("yyyy-MM-dd");
            dataTable.Rows.Add(daterange);
            var startmonth = dataTable.NewRow();
            startmonth[0] = Translations.StartMonthOfReportingYear + ": " + CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(report.ReportOptions.MonthYearStarts) ;
            dataTable.Rows.Add(startmonth);
            var cat = dataTable.NewRow();
            cat[0] = Translations.Category + ": " + report.ReportOptions.CategoryName;
            dataTable.Rows.Add(cat);
            
            // Add diseases selected in report?
            if(report.ReportOptions.EntityType != Model.IndicatorEntityType.Demo)
            {
            }

            var agg = dataTable.NewRow();
            if(report.ReportOptions.IsByLevelAggregation)
                agg[0] = Translations.AggregatedBy + ": " + Translations.AggLevel;
            else if (report.ReportOptions.IsCountryAggregation)
                agg[0] = Translations.AggregatedBy + ": " + Translations.AggCountry;
            else 
                agg[0] = Translations.AggregatedBy + ": " + Translations.AggListAll;
            dataTable.Rows.Add(agg);

            //[Only administrative units before redistricting] (only show if checked)
            if(report.ReportOptions.ShowOnlyRedistrictedUnits)
            {
                var redist = dataTable.NewRow();
                redist[0] = Translations.RedistrictedAdminUnits;
                dataTable.Rows.Add(redist);
            }
        }
Пример #24
0
        public DataTable RunRedistrictingReport()
        {
            DemoRepository demo = new DemoRepository();
            DataTable dataTable = new DataTable();
            dataTable.Columns.Add(new DataColumn(TranslationLookup.GetValue("RedistrictDate")));
            dataTable.Columns.Add(new DataColumn(TranslationLookup.GetValue("RedistOrigName")));
            dataTable.Columns.Add(new DataColumn(TranslationLookup.GetValue("RedistOrigPop")));
            dataTable.Columns.Add(new DataColumn(TranslationLookup.GetValue("RedistLevel")));
            dataTable.Columns.Add(new DataColumn(TranslationLookup.GetValue("RedistOrigParent")));
            dataTable.Columns.Add(new DataColumn(TranslationLookup.GetValue("RedistNewName")));
            dataTable.Columns.Add(new DataColumn(TranslationLookup.GetValue("RedistNewPop")));
            dataTable.Columns.Add(new DataColumn(TranslationLookup.GetValue("RedistNewParent")));
            dataTable.Columns.Add(new DataColumn(TranslationLookup.GetValue("RedistType")));
            dataTable.Columns.Add(new DataColumn(TranslationLookup.GetValue("RedistEventDate")));
            dataTable.Columns.Add(new DataColumn(TranslationLookup.GetValue("ID")));
            OleDbConnection connection = new OleDbConnection(DatabaseData.Instance.AccessConnectionString);
            using (connection)
            {
                connection.Open();
                try
                {
                    OleDbCommand command = new OleDbCommand(@"Select ID, CreatedAt, RedistrictTypeId, RedistrictDate
                        FROM RedistrictEvents 
                        ORDER BY CreatedAt DESC", connection);
                    using (OleDbDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            int id = reader.GetValueOrDefault<int>("ID");
                            Nullable<DateTime> redistrictDate = reader.GetValueOrDefault<Nullable<DateTime>>("RedistrictDate");
                            DateTime date = reader.GetValueOrDefault<DateTime>("CreatedAt");
                            SplittingType t = (SplittingType)reader.GetValueOrDefault<int>("RedistrictTypeId");
                            List<RedistrictedReportUnit> daughters = new List<RedistrictedReportUnit>();
                            List<RedistrictedReportUnit> mothers = new List<RedistrictedReportUnit>();
                            string typeName = "";

                            command = new OleDbCommand(@"Select a.ID as AID, a.DisplayName as AName, p.DisplayName as PName, u.RelationshipId, t.DisplayName as TName
                                FROM (((RedistrictUnits u INNER JOIN  AdminLevels a on a.ID = u.AdminLevelUnitId)
                                    INNER JOIN AdminLevels p on a.ParentId = p.ID)
                                    INNER JOIN AdminLevelTypes t on a.AdminLevelTypeId = t.ID)
                                WHERE u.RedistrictEventID = @id", connection);
                            command.Parameters.Add(new OleDbParameter("@id", id));
                            using (OleDbDataReader reader2 = command.ExecuteReader())
                            {
                                while (reader2.Read())
                                {
                                    typeName = reader2.GetValueOrDefault<string>("TName");
                                    if (RedistrictingRelationship.Daughter == (RedistrictingRelationship)reader2.GetValueOrDefault<int>("RelationshipId"))
                                        daughters.Add(new RedistrictedReportUnit { Id = reader2.GetValueOrDefault<int>("AID"), Name = reader2.GetValueOrDefault<string>("AName"), Parent = reader2.GetValueOrDefault<string>("PName") });
                                    else if (RedistrictingRelationship.Mother == (RedistrictingRelationship)reader2.GetValueOrDefault<int>("RelationshipId"))
                                        mothers.Add(new RedistrictedReportUnit { Id = reader2.GetValueOrDefault<int>("AID"), Name = reader2.GetValueOrDefault<string>("AName"), Parent = reader2.GetValueOrDefault<string>("PName") });
                                }
                            }

                            if (t == SplittingType.Split)
                            {
                                var source = mothers.FirstOrDefault();
                                source.Pop = GetRecentPopulation(source.Id, redistrictDate, connection, demo);
                                foreach (var dest in daughters)
                                {
                                    dest.Pop = GetRecentPopulation(dest.Id, redistrictDate, connection, demo);
                                    AddRedistrictingReportRow(dataTable, source, dest, TranslationLookup.GetValue("RedistrictTypeSplit"), date, typeName, id, redistrictDate);
                                }
                            }
                            else if (t == SplittingType.Merge)
                            {
                                var dest = daughters.FirstOrDefault();
                                dest.Pop = GetRecentPopulation(dest.Id, redistrictDate, connection, demo);
                                foreach (var source in mothers)
                                {
                                    source.Pop = GetRecentPopulation(source.Id, redistrictDate, connection, demo);
                                    AddRedistrictingReportRow(dataTable, source, dest, TranslationLookup.GetValue("RedistrictTypeMerge"), date, typeName, id, redistrictDate);
                                }
                            }
                            else // splitcomb
                            {
                                var dest = daughters.FirstOrDefault();
                                dest.Pop = GetRecentPopulation(dest.Id, redistrictDate, connection, demo);
                                foreach (var source in mothers)
                                {
                                    source.Pop = GetRecentPopulation(source.Id, redistrictDate, connection, demo);
                                    AddRedistrictingReportRow(dataTable, source, dest, TranslationLookup.GetValue("RedistrictTypeSplitCombine"), date, typeName, id, redistrictDate);
                                }
                            }
                        }
                    }

                }
                catch (Exception)
                {
                    throw;
                }
            }
            return dataTable;
        }
Пример #25
0
 private int GetRecentPopulation(int adminLevelId, DateTime? redistrictDate, OleDbConnection connection, DemoRepository demo)
 {
     var recentDemo = demo.GetRecentDemography(adminLevelId, null, redistrictDate, connection);
     if (recentDemo != null)
         if (recentDemo.TotalPopulation.HasValue)
             return Convert.ToInt32(recentDemo.TotalPopulation.Value);
     return 0;
 }