public static bool HasData(OmrPageOutput page, OmrBarcodeField barcode) { String tPath = Path.GetTempFileName(); using (Bitmap bmp = new Bitmap((int)barcode.TopRight.X - (int)barcode.TopLeft.X, (int)barcode.BottomLeft.Y - (int)barcode.TopLeft.Y, PixelFormat.Format24bppRgb)) { using (Graphics g = Graphics.FromImage(bmp)) using (System.Drawing.Image img = System.Drawing.Image.FromFile(page.AnalyzedImage)) { g.DrawImage(img, 0, 0, new Rectangle(new Point((int)barcode.TopLeft.X, (int)barcode.TopLeft.Y), bmp.Size), GraphicsUnit.Pixel); // is g empty? } // Blobs BlobCounter blobCounter = new BlobCounter(); blobCounter.MinHeight = 30; blobCounter.MinWidth = 30; blobCounter.FilterBlobs = true; //blobCounter.BackgroundThreshold = Color.Gray;// new Color(255, 255, 255); using (var grayscale = new GrayscaleY().Apply(bmp)) { Threshold binaryThreshold = new Threshold(page.Template.ScanThreshold); binaryThreshold.ApplyInPlace(grayscale); new Invert().ApplyInPlace(grayscale); // Check for circles blobCounter.ProcessImage(grayscale); Blob[] blobs = blobCounter.GetObjectsInformation(); return(blobs.Where(o => o.ColorMean == Color.FromArgb(255, 255, 255, 255)).Count() > 0); } } }
public BarcodeCorrection(OmrPageOutput page, OmrBarcodeField barcode) { this.m_page = page; this.m_expectedArea = barcode; InitializeComponent(); // Crop the image String tPath = Path.GetTempFileName(); using (Bitmap bmp = new Bitmap((int)barcode.TopRight.X - (int)barcode.TopLeft.X, (int)barcode.BottomLeft.Y - (int)barcode.TopLeft.Y, PixelFormat.Format24bppRgb)) using (Graphics g = Graphics.FromImage(bmp)) using (Image img = Image.FromFile(this.m_page.AnalyzedImage)) { g.DrawImage(img, 0, 0, new Rectangle(new Point((int)barcode.TopLeft.X, (int)barcode.TopLeft.Y), bmp.Size), GraphicsUnit.Pixel); bmp.Save(tPath); } // Rotate using (Image img = Image.FromFile(tPath)) using (var rotated = new AForge.Imaging.Filters.RotateBilinear(-90).Apply((Bitmap)img)) using (var scaled = new AForge.Imaging.Filters.ResizeBilinear((int)(rotated.Width * 0.75), (int)(rotated.Height * .75)).Apply(rotated)) { tPath = Path.GetTempFileName(); scaled.Save(tPath); pbBarcode.ImageLocation = tPath; } }
/// <summary> /// Dump the page output tree /// </summary> private void DumpPageOutputTree(OmrPageOutput output) { lblCurrentPage.Text = string.Format("Page {0}", output.Id); trvDocument.Nodes.Clear(); foreach (var itm in output.Details) { trvDocument.Nodes.Add(this.CreateTreeNode(itm)); } }
/// <summary> /// The output visualizer /// </summary> public OutputVisualizationStencil(OmrPageOutput pageOutput) { m_data = pageOutput; // Find the bounds and that is our size Size = new SizeF(pageOutput.BottomRight.X, pageOutput.BottomRight.Y); Position = new PointF(0, 0); DrawItems(pageOutput.Details); Add(new TextShape { FillBrush = Brushes.White, Font = new Font(FontFamily.GenericSansSerif, 16f, FontStyle.Bold), Position = new PointF(0, 0), Text = string.Format("Scan ID: {0}", pageOutput.Id) }); }
/// <summary> /// Make a summary /// </summary> private string MakeSummary(OmrPageOutput pageData) { StringBuilder sb = new StringBuilder(); sb.AppendFormat("Following Data was Scanned for {0}:\r\nParms:", pageData.TemplateId); if (pageData.Parameters != null) { foreach (var parm in pageData.Parameters) { sb.AppendFormat("{0}; ", parm); } } foreach (var itm in pageData.Details) { if (itm is OmrOutputDataCollection) { sb.AppendFormat("(Row {0}: ", itm.Id); foreach (var subItm in (itm as OmrOutputDataCollection).Details) { if (subItm is OmrBubbleData) { var bubItm = subItm as OmrBubbleData; sb.AppendFormat("{0} = {1}; ", bubItm.Key, bubItm.Value); } else if (subItm is OmrBarcodeData) { sb.AppendFormat("Barcode {0}; ", (subItm as OmrBarcodeData).BarcodeData); } } sb.Append(")\r\n"); } else if (itm is OmrBubbleData) { var bubItm = itm as OmrBubbleData; sb.AppendFormat("{0} = {1} \r\n ", bubItm.Key, bubItm.Value); } else if (itm is OmrBarcodeData) { sb.AppendFormat("Barcode {0} \r\n ", (itm as OmrBarcodeData).BarcodeData); } } return(sb.ToString()); }
public ChildSearch(FormTZ02.Tz02RowData rowData) { this.m_page = rowData.Page; InitializeComponent(); // Crop the image String tPath = Path.GetTempFileName(); using (Bitmap bmp = new Bitmap((int)rowData.Page.BottomRight.Y / 3, (int)rowData.RowBounds.Width / 3)) using (Graphics g = Graphics.FromImage(bmp)) using (Image img = Image.FromFile(rowData.Page.AnalyzedImage)) using (Image scaled = (Image) new AForge.Imaging.Filters.ResizeNearestNeighbor(img.Width / 3, img.Height / 3).Apply((Bitmap)img)) using (Image rotated = (Image) new AForge.Imaging.Filters.RotateBilinear(-90).Apply((Bitmap)scaled)) { g.DrawImage(rotated, 0, 0, new Rectangle(0, (int)rowData.RowBounds.X / 3, (int)rowData.Page.BottomRight.Y / 3, (int)rowData.RowBounds.Width / 3), GraphicsUnit.Pixel); bmp.Save(tPath); this.pbBarcode.ImageLocation = tPath; } cbxVillage.Items.AddRange(ReferenceData.Current.Places.Select(o => new Registration.PlaceListItem() { Place = o as Place }).OfType <Object>().ToArray()); }
/// <summary> /// Process the template data /// </summary> public void Run(OmrTemplate template, OmrPageOutput processedOutput) { if (template.Script == null) { return; } // First we need to compile the script Assembly asmToRun = null; if (!s_compiledScripts.TryGetValue(template.Id, out asmToRun)) { using ( var strm = new StreamReader( typeof(TemplateScriptUtil).Assembly.GetManifestResourceStream( "OmrMarkEngine.Core.Template.Scripting.ScriptTemplate.txt"))) { var scriptTemplate = strm.ReadToEnd(); scriptTemplate = scriptTemplate.Replace("$$script$$", template.Script.Script); var asmOption = new CompilerParameters { GenerateExecutable = false, GenerateInMemory = true, CompilerOptions = "/d:TRACE /d:DEBUG", IncludeDebugInformation = true }; // Add assemblies asmOption.ReferencedAssemblies.Add(typeof(INotifyPropertyChanged).Assembly.Location); asmOption.ReferencedAssemblies.Add(typeof(string).Assembly.Location); asmOption.ReferencedAssemblies.Add(typeof(Enumerable).Assembly.Location); asmOption.ReferencedAssemblies.Add(typeof(OmrTemplate).Assembly.Location); asmOption.ReferencedAssemblies.Add(typeof(DataContractAttribute).Assembly.Location); foreach (var asmRef in template.Script.Assemblies) { var asmLocation = asmRef; if (!Path.IsPathRooted(asmLocation)) { asmLocation = Path.Combine(Path.GetDirectoryName(template.FileName), asmLocation); } Assembly.LoadFile(asmLocation); asmOption.ReferencedAssemblies.Add(asmLocation); } // Compile var compileResult = CodeDomProvider.CreateProvider("CS") .CompileAssemblyFromSource(asmOption, scriptTemplate); if (compileResult.Errors.HasErrors) { foreach (var err in compileResult.Errors) { Trace.TraceError("{0}", err); } throw new InvalidOperationException("Error exeucting post processing script"); } asmToRun = compileResult.CompiledAssembly; s_compiledScripts.Add(template.Id, asmToRun); } } // Now we need to run the script var templateScript = asmToRun.GetType("OmrScannerApplication.Scripting.Script"); if (templateScript == null) { throw new InvalidOperationException("Cannot execute post processing script"); } var errField = templateScript.GetField("Err"); var runMethod = templateScript.GetMethod("Run", new[] { typeof(OmrPageOutput) }); if ((runMethod == null) || (errField == null)) { throw new InvalidOperationException("Cannot execute post processing script"); } // Invoke try { lock (s_syncLock) { errField.SetValue(null, null); runMethod.Invoke(null, new object[] { processedOutput }); if (!string.IsNullOrEmpty(errField.GetValue(null) as string)) { throw new ScriptingErrorException(errField.GetValue(null).ToString()); } } } catch { throw; } }
public void UploadData(OmrPageOutput page) { if (!Connectivity.CheckForInternetConnection()) { MessageBox.Show( "Username is empty, This is usually caused by lack of internet connectivity. Please try again later"); Exception e = new Exception("No internet connection"); Trace.TraceError("Error:{0}", e); throw e; } StatusDialog dlg = new StatusDialog(); dlg.Show(); try { int facilityId = FacilitySelectionContext.FacilityId; // Non-remembered facility if (facilityId == 0) { LocationSelectionBox location = new LocationSelectionBox(); if (location.ShowDialog() != System.Windows.Forms.DialogResult.OK) { throw new InvalidOperationException("Cannot upload data without selecting a facility"); } if (location.Remember) { FacilitySelectionContext.FacilityId = location.FacilityId; } facilityId = location.FacilityId; } var monthBubble = page.Details.OfType <OmrBubbleData>().FirstOrDefault(o => o.Key == "Month"); if (monthBubble == null) { throw new InvalidOperationException("Missing month selection on form"); } // Now we want to upload the data BirthDoseSubmission submission = new BirthDoseSubmission() { Month = (int)monthBubble.ValueAsFloat, FacilityId = facilityId, Data = new List <BirthDoseData>() }; // Iterate through the rows foreach (var dtl in page.Details.OfType <OmrRowData>()) { OmrBubbleData genderData = dtl.Details.OfType <OmrBubbleData>().FirstOrDefault(o => o.Key == "Gender"); OmrBubbleData[] birthDose = dtl.Details.OfType <OmrBubbleData>().Where(o => o.Key == "BirthDose").ToArray(), ttDose = dtl.Details.OfType <OmrBubbleData>().Where(o => o.Key == "TTDose").ToArray(); if (genderData == null) { Err += String.Format("Row {0} is missing gender group, skipping; ", dtl.Id); continue; } var data = new BirthDoseData() { Gender = genderData.Value, Doses = new List <string>() }; // Doses data.Doses.AddRange(birthDose.Select(o => o.Value)); data.Doses.AddRange(ttDose.Select(o => o.Value)); submission.Data.Add(data); } RestUtil restUtil = new RestUtil(new Uri(ConfigurationManager.AppSettings["GIIS_URL"])); restUtil.Post("AnonymousDataManagement.svc/PostBirthDose", submission); } catch (Exception e) { Trace.TraceError("Error:{0}", e); throw; } finally { dlg.Close(); } }
public void UploadData(OmrPageOutput page) { if (!Connectivity.CheckForInternetConnection()) { MessageBox.Show( "Username is empty, This is usually caused by lack of internet connectivity. Please try again later"); Exception e = new Exception("No internet connection"); Trace.TraceError("Error:{0}", e); throw e; } StatusDialog dlg = new StatusDialog(); dlg.Show(); try { int facilityId = FacilitySelectionContext.FacilityId; // Non-remembered facility if (facilityId == 0) { LocationSelectionBox location = new LocationSelectionBox(); if (location.ShowDialog() != System.Windows.Forms.DialogResult.OK) { throw new InvalidOperationException("Cannot upload data without selecting a facility"); } if (location.Remember) { FacilitySelectionContext.FacilityId = location.FacilityId; } facilityId = location.FacilityId; } var monthBubble = page.Details.OfType <OmrBubbleData>().FirstOrDefault(o => o.Key == "month"); if (monthBubble == null) { Err += "Must select month!; "; return; } RestUtil restUtil = new RestUtil(new Uri(ConfigurationManager.AppSettings["GIIS_URL"])); var userInfo = restUtil.Get <User>("UserManagement.svc/GetUserInfo", new KeyValuePair <string, object>("username", restUtil.GetCurrentUserName)); var placeInfo = restUtil.Get <Place[]>("PlaceManagement.svc/GetPlaceByHealthFacilityId", new KeyValuePair <string, object>("hf_id", facilityId)); foreach (var dtl in page.Details.OfType <OmrRowData>()) { string rowNum = dtl.Id.Substring(dtl.Id.Length - 1, 1); if (dtl.Details.Count == 0) { continue; } // (string barcodeId, string firstname1, string firstname2, string lastname1, DateTime birthdate, bool gender, // int healthFacilityId, int birthplaceId, int domicileId, string address, string phone, string motherFirstname, // string motherLastname, string notes, int userId, DateTime modifiedOn) OmrBarcodeData omrBarcode = dtl.Details.OfType <OmrBarcodeData>().FirstOrDefault(); OmrBubbleData omrDobDay = dtl.Details.OfType <OmrBubbleData>().FirstOrDefault(o => o.Key == "dobDay"), omrDobDay10 = dtl.Details.OfType <OmrBubbleData>().FirstOrDefault(o => o.Key == "dobDay10"), omrDobMonth = dtl.Details.OfType <OmrBubbleData>().FirstOrDefault(o => o.Key == "dobMonth"), omrDobYear = dtl.Details.OfType <OmrBubbleData>().FirstOrDefault(o => o.Key == "dobYear"), omrGender = dtl.Details.OfType <OmrBubbleData>().FirstOrDefault(o => o.Key == "gender"), omrOutreach = dtl.Details.OfType <OmrBubbleData>().FirstOrDefault(o => o.Key == "Outreach"), omrVaccDay10 = dtl.Details.OfType <OmrBubbleData>().FirstOrDefault(o => o.Key == "vaccDay10"), omrVaccDay = dtl.Details.OfType <OmrBubbleData>().FirstOrDefault(o => o.Key == "vaccDay"), omrNew = dtl.Details.OfType <OmrBubbleData>().FirstOrDefault(o => o.Key == "newInfo"), omrUpdate = dtl.Details.OfType <OmrBubbleData>().FirstOrDefault(o => o.Key == "correct"), omrIgnore = dtl.Details.OfType <OmrBubbleData>().FirstOrDefault(o => o.Key == "moved"); OmrBubbleData[] omrBcg = dtl.Details.OfType <OmrBubbleData>().Where(o => o.Key == "BCG").ToArray(), omrOpv = dtl.Details.OfType <OmrBubbleData>().Where(o => o.Key == "OPV").ToArray(), omrPenta = dtl.Details.OfType <OmrBubbleData>().Where(o => o.Key == "PENTA").ToArray(), omrPcv = dtl.Details.OfType <OmrBubbleData>().Where(o => o.Key == "PCV").ToArray(), omrRota = dtl.Details.OfType <OmrBubbleData>().Where(o => o.Key == "ROTA").ToArray(), omrMr = dtl.Details.OfType <OmrBubbleData>().Where(o => o.Key == "MR").ToArray(), omrVaccine = dtl.Details.OfType <OmrBubbleData>().Where(o => o.Key == "vaccine").ToArray(); // From WCF Call // Create row data for the verification form OmrBarcodeField barcodeField = page.Template.FlatFields.Find(o => o.Id == String.Format("{0}Barcode", dtl.Id)) as OmrBarcodeField; OmrBubbleField outreachField = page.Template.FlatFields.OfType <OmrBubbleField>() .SingleOrDefault(o => o.AnswerRowGroup == dtl.Id && o.Question == "Outreach"), monthField = page.Template.FlatFields.OfType <OmrBubbleField>() .SingleOrDefault(o => o.AnswerRowGroup == dtl.Id && o.Question == "dobMonth" && o.Value == "12"); // Barcode bounds Tz02RowData rowData = new Tz02RowData() { RowBounds = new RectangleF() { Location = new PointF(barcodeField.TopLeft.X, monthField.TopLeft.Y - 20), Width = outreachField.TopLeft.X - barcodeField.TopLeft.X, Height = barcodeField.BottomLeft.Y - monthField.TopLeft.Y - 20 }, UserInfo = userInfo, Page = page, FacilityId = facilityId }; if (omrBarcode != null) { rowData.Barcode = omrBarcode.BarcodeData; } if (omrDobDay != null && omrDobDay10 != null && omrDobMonth != null && omrDobYear != null) { try { rowData.DateOfBirth = new DateTime((int)omrDobYear.ValueAsFloat, (int)omrDobMonth.ValueAsFloat, (int)omrDobDay10.ValueAsFloat + (int)omrDobDay.ValueAsFloat); } catch { } } if (omrGender != null) { rowData.Gender = omrGender.Value == "M" ? true : false; } if (omrOutreach != null) { rowData.Outreach = omrOutreach.Value == "T"; } // Doses rowData.Doses = new List <Dose>(); if (omrBcg != null && omrBcg.Length > 0) { rowData.Doses.Add(this.FindDoseOrThrow("BCG")); } if (omrOpv != null) { foreach (var bub in omrOpv) { VaccinationEvent opvEvent = null; rowData.Doses.Add(ReferenceData.Current.Doses .Single(d => (d.DoseNumber == Helper.ConvertToInt(bub.Value) && d.ScheduledVaccinationId == (ReferenceData.Current.Vaccines .Single(v => v.Name.ToLower().Contains("opv")).Id)))); } } if (omrPenta != null) { foreach (var bub in omrPenta) { rowData.Doses.Add(ReferenceData.Current.Doses .Single(d => (d.DoseNumber == Helper.ConvertToInt(bub.Value) && d.ScheduledVaccinationId == (ReferenceData.Current.Vaccines .Single(v => (v.Name.ToLower().Contains("dtp") || v.Name.ToLower().Contains("penta"))).Id)))); } } if (omrPcv != null) { foreach (var bub in omrPcv) { rowData.Doses.Add(ReferenceData.Current.Doses .Single(d => (d.DoseNumber == Helper.ConvertToInt(bub.Value) && d.ScheduledVaccinationId == (ReferenceData.Current.Vaccines .Single(v => v.Name.ToLower().Contains("pcv")).Id)))); } } if (omrRota != null) { foreach (var bub in omrRota) { rowData.Doses.Add(ReferenceData.Current.Doses .Single(d => (d.DoseNumber == Helper.ConvertToInt(bub.Value) && d.ScheduledVaccinationId == (ReferenceData.Current.Vaccines .Single(v => v.Name.ToLower().Contains("rota")).Id)))); } } if (omrMr != null) { foreach (var bub in omrMr) { rowData.Doses.Add(ReferenceData.Current.Doses .Single(d => (d.DoseNumber == Helper.ConvertToInt(bub.Value) && d.ScheduledVaccinationId == (ReferenceData.Current.Vaccines .Single(v => v.Name.ToLower().Contains("mr")) .Id)))); } } // Given vaccines rowData.VaccineGiven = new List <ScheduledVaccination>(); foreach (var vacc in omrVaccine) { string antigenName = vacc.Value; if (antigenName == "ROTA") { antigenName = ReferenceData.Current.Vaccines .Single(d => d.Name.ToLower().Contains("rota")).Name; } else if (antigenName == "PENTA") { antigenName = ReferenceData.Current.Vaccines.Single(d => (d.Name.ToLower().Contains("dtp") || d.Name.ToLower().Contains("penta"))).Name; } else if (antigenName == "MR") { antigenName = ReferenceData.Current.Vaccines .Single(d => (d.Name.ToLower().Contains("mr"))) .Name; } else if (antigenName == "PCV") { antigenName = ReferenceData.Current.Vaccines .Single(d => d.Name.ToLower().Contains("pcv")).Name; } else if (antigenName == "OPV") { antigenName = ReferenceData.Current.Vaccines .Single(d => d.Name.ToLower().Contains("opv")).Name; } var refData = ReferenceData.Current.Vaccines.FirstOrDefault(v => v.Name == antigenName); if (refData != null) { rowData.VaccineGiven.Add(refData); } else { MessageBox.Show(String.Format("The form expected a vaccination named {0} but the server did not respond with such a vaccine. Server vaccinations: [{1}]", antigenName, String.Join(",", ReferenceData.Current.Vaccines.Select(o => o.Name).ToArray()))); } } // Date of vaccination rowData.VaccineDate = DateTime.Now; if (omrVaccDay10 != null && omrVaccDay != null) { rowData.VaccineDate = new DateTime(DateTime.Now.Month < monthBubble.ValueAsFloat ? DateTime.Now.Year - 1 : DateTime.Now.Year, (int)monthBubble.ValueAsFloat, (int)omrVaccDay10.ValueAsFloat + (int)omrVaccDay.ValueAsFloat); } // Determine what to do if (omrUpdate?.Value == "T") { ChildSearch bc = new ChildSearch(rowData); if (bc.ShowDialog() == DialogResult.OK) { rowData.Barcode = bc.Child.BarcodeId; rowData.ChildId = bc.Child.Id; } else { continue; } } else if (omrIgnore?.Value == "T") { continue; } if (BarcodeUtil.HasData(page, barcodeField) || dtl.Details.Count > 2) { Registration registration = new Registration(rowData); registration.ShowDialog(); } } } catch (Exception e) { Trace.TraceError("Error:{0}", e); throw; } finally { dlg.Close(); } }
/// <summary> /// Apply template /// </summary> /// <param name="template"></param> /// <param name="image"></param> public OmrPageOutput ApplyTemplate(OmrTemplate template, ScannedImage image) { // Image ready for scan if (!image.IsReadyForScan) { if (!image.IsScannable) { image.Analyze(); } image.PrepareProcessing(); } // Page output OmrPageOutput retVal = new OmrPageOutput() { Id = image.TemplateName + DateTime.Now.ToString("yyyyMMddHHmmss"), TemplateId = image.TemplateName, Parameters = image.Parameters, StartTime = DateTime.Now, Template = template }; // Save directory for output images string saveDirectory = String.Empty; var parmStr = new StringBuilder(); if (this.SaveIntermediaryImages) { if (image.Parameters != null) { foreach (var pv in image.Parameters) { parmStr.AppendFormat("{0}.", pv); } } retVal.RefImages = new List <string>() { String.Format("{0}-{1}-init.bmp", retVal.Id, parmStr), String.Format("{0}-{1}-tx.bmp", retVal.Id, parmStr), String.Format("{0}-{1}-fields.bmp", retVal.Id, parmStr), String.Format("{0}-{1}-gs.bmp", retVal.Id, parmStr), String.Format("{0}-{1}-bw.bmp", retVal.Id, parmStr), String.Format("{0}-{1}-inv.bmp", retVal.Id, parmStr) }; saveDirectory = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "imgproc"); if (!Directory.Exists(saveDirectory)) { Directory.CreateDirectory(saveDirectory); } image.Image.Save(Path.Combine(saveDirectory, string.Format("{0}-{1}-init.bmp", DateTime.Now.ToString("yyyyMMddHHmmss"), parmStr))); } // First, we want to get the image from the scanned image and translate it to the original // position in the template Bitmap bmp = null; try { bmp = new Bitmap((int)template.BottomRight.X, (int)template.BottomRight.Y, System.Drawing.Imaging.PixelFormat.Format24bppRgb); // Scale float width = template.TopRight.X - template.TopLeft.X, height = template.BottomLeft.Y - template.TopLeft.Y; // Translate to original using (Graphics g = Graphics.FromImage(bmp)) { ResizeBicubic bc = new ResizeBicubic((int)width, (int)height); g.DrawImage(bc.Apply((Bitmap)image.Image), template.TopLeft.X, template.TopLeft.Y); } if (this.SaveIntermediaryImages) { bmp.Save(Path.Combine(saveDirectory, string.Format("{0}-{1}-tx.bmp", DateTime.Now.ToString("yyyyMMddHHmmss"), parmStr))); } // Now try to do hit from the template if (this.SaveIntermediaryImages) { using (var tbmp = bmp.Clone() as Bitmap) { using (Graphics g = Graphics.FromImage(tbmp)) { foreach (var field in template.Fields) { g.DrawRectangle(Pens.Black, field.TopLeft.X, field.TopLeft.Y, field.TopRight.X - field.TopLeft.X, field.BottomLeft.Y - field.TopLeft.Y); g.DrawString(field.Id, SystemFonts.CaptionFont, Brushes.Black, field.TopLeft); } } tbmp.Save(Path.Combine(saveDirectory, string.Format("{0}-{1}-fields.bmp", DateTime.Now.ToString("yyyyMMddHHmmss"), parmStr))); } } // Now convert to Grayscale GrayscaleY grayFilter = new GrayscaleY(); var gray = grayFilter.Apply(bmp); bmp.Dispose(); bmp = gray; if (this.SaveIntermediaryImages) { bmp.Save(Path.Combine(saveDirectory, string.Format("{0}-{1}-gs.bmp", DateTime.Now.ToString("yyyyMMddHHmmss"), parmStr))); } // Prepare answers Dictionary <OmrQuestionField, OmrOutputData> hitFields = new Dictionary <OmrQuestionField, OmrOutputData>(); BarcodeReader barScan = new BarcodeReader(); barScan.Options.UseCode39ExtendedMode = true; barScan.Options.UseCode39RelaxedExtendedMode = true; barScan.Options.TryHarder = true; barScan.TryInverted = true; barScan.Options.PureBarcode = false; barScan.AutoRotate = true; foreach (var itm in template.Fields.Where(o => o is OmrBarcodeField)) { PointF position = itm.TopLeft; SizeF size = new SizeF(itm.TopRight.X - itm.TopLeft.X, itm.BottomLeft.Y - itm.TopLeft.Y); using (var areaOfInterest = new Crop(new Rectangle((int)position.X, (int)position.Y, (int)size.Width, (int)size.Height)).Apply(bmp)) { // Scan the barcode var result = barScan.Decode(areaOfInterest); if (result != null) { hitFields.Add(itm, new OmrBarcodeData() { BarcodeData = result.Text, Format = result.BarcodeFormat, Id = itm.Id, TopLeft = new PointF(result.ResultPoints[0].X + position.X, result.ResultPoints[0].Y + position.Y), BottomRight = new PointF(result.ResultPoints[1].X + position.X, result.ResultPoints[0].Y + position.Y + 10) }); } } } // Now binarize Threshold binaryThreshold = new Threshold(template.ScanThreshold); binaryThreshold.ApplyInPlace(bmp); if (this.SaveIntermediaryImages) { bmp.Save(Path.Combine(saveDirectory, string.Format("{0}-{1}-bw.bmp", DateTime.Now.ToString("yyyyMMddHHmmss"), parmStr))); } // Set return parameters String tAnalyzeFile = Path.Combine(Path.GetTempPath(), Path.GetTempFileName()); bmp.Save(tAnalyzeFile, System.Drawing.Imaging.ImageFormat.Jpeg); retVal.AnalyzedImage = tAnalyzeFile; retVal.BottomRight = new PointF(bmp.Width, bmp.Height); // Now Invert Invert invertFiter = new Invert(); invertFiter.ApplyInPlace(bmp); if (this.SaveIntermediaryImages) { bmp.Save(Path.Combine(saveDirectory, string.Format("{0}-{1}-inv.bmp", DateTime.Now.ToString("yyyyMMddHHmmss"), parmStr))); } // Crop out areas of interest List <KeyValuePair <OmrQuestionField, Bitmap> > areasOfInterest = new List <KeyValuePair <OmrQuestionField, Bitmap> >(); foreach (var itm in template.Fields.Where(o => o is OmrBubbleField)) { PointF position = itm.TopLeft; SizeF size = new SizeF(itm.TopRight.X - itm.TopLeft.X, itm.BottomLeft.Y - itm.TopLeft.Y); areasOfInterest.Add(new KeyValuePair <OmrQuestionField, Bitmap>( itm, new Crop(new Rectangle((int)position.X, (int)position.Y, (int)size.Width, (int)size.Height)).Apply(bmp)) ); } // Queue analysis WaitThreadPool wtp = new WaitThreadPool(); Object syncLock = new object(); foreach (var itm in areasOfInterest) { wtp.QueueUserWorkItem(img => { var parm = (KeyValuePair <OmrQuestionField, Bitmap>)itm; try { var areaOfInterest = parm.Value; var field = parm.Key; BlobCounter blobCounter = new BlobCounter(); blobCounter.FilterBlobs = true; // Check for circles blobCounter.ProcessImage(areaOfInterest); Blob[] blobs = blobCounter.GetObjectsInformation(); var blob = blobs.FirstOrDefault(o => o.Area == blobs.Max(b => b.Area)); if (blob != null) { //var area = new AForge.Imaging.ImageStatistics(blob).PixelsCountWithoutBlack; if (blob.Area < 30) { return; } var bubbleField = field as OmrBubbleField; lock (syncLock) hitFields.Add(field, new OmrBubbleData() { Id = field.Id, Key = bubbleField.Question, Value = bubbleField.Value, TopLeft = new PointF(blob.Rectangle.X + field.TopLeft.X, blob.Rectangle.Y + field.TopLeft.Y), BottomRight = new PointF(blob.Rectangle.X + blob.Rectangle.Width + field.TopLeft.X, blob.Rectangle.Y + blob.Rectangle.Height + field.TopLeft.Y), BlobArea = blob.Area }); } } catch (Exception e) { Trace.TraceError(e.ToString()); } finally { parm.Value.Dispose(); } }, itm); } wtp.WaitOne(); // Organize the response foreach (var res in hitFields) { if (String.IsNullOrEmpty(res.Key.AnswerRowGroup)) { this.AddAnswerToOutputCollection(retVal, res); } else { // Rows of data OmrRowData rowGroup = retVal.Details.Find(o => o.Id == res.Key.AnswerRowGroup) as OmrRowData; if (rowGroup == null) { rowGroup = new OmrRowData() { Id = res.Key.AnswerRowGroup }; retVal.Details.Add(rowGroup); } this.AddAnswerToOutputCollection(rowGroup, res); } } // Remove temporary images //foreach (var f in retVal.RefImages) // File.Delete(Path.Combine(saveDirectory, f)); // Outcome is success retVal.Outcome = OmrScanOutcome.Success; } catch (Exception e) { retVal.Outcome = OmrScanOutcome.Failure; retVal.ErrorMessage = e.Message; Trace.TraceError(e.ToString()); } finally { retVal.StopTime = DateTime.Now; bmp.Dispose(); } return(retVal); }
public void UploadData(OmrPageOutput page) { if (!Connectivity.CheckForInternetConnection()) { MessageBox.Show( "Username is empty, This is usually caused by lack of internet connectivity. Please try again later"); Exception e = new Exception("No internet connection"); Trace.TraceError("Error:{0}", e); throw e; } StatusDialog dlg = new StatusDialog(); dlg.Show(); try { int facilityId = Int32.Parse(page.Parameters[0]); int month = Int32.Parse(page.Parameters[1]); int year = Int32.Parse(page.Parameters[2]); this.Err = ""; Trace.TraceInformation("Reporting for facility {0} of {1}-{2}", facilityId, month, year); RestUtil restUtil = new RestUtil(new Uri(ConfigurationManager.AppSettings["GIIS_URL"])); User userInfo = null; try { userInfo = restUtil.Get <User>("UserManagement.svc/GetUserInfo", new KeyValuePair <string, object>("username", restUtil.GetCurrentUserName)); } catch { userInfo = restUtil.Get <User>("UserManagement.svc/GetUserInfo", new KeyValuePair <string, object>("username", restUtil.GetCurrentUserName)); } var placeInfo = restUtil.Get <Place[]>("PlaceManagement.svc/GetPlaceByHealthFacilityId", new KeyValuePair <string, object>("hf_id", facilityId)); foreach (var patientRow in page.Details.OfType <OmrRowData>().Where(o => !o.Id.Contains("-"))) { // Master patient row processing string rowNum = patientRow.Id.Substring(patientRow.Id.Length - 1, 1); if (patientRow.Details.Count == 0) { continue; } // Create row data for the verification form OmrBarcodeField barcodeField = page.Template.FlatFields.Find(o => o.Id == String.Format("{0}Barcode", patientRow.Id)) as OmrBarcodeField, omrStickerField = page.Template.FlatFields.Find(o => o.Id == String.Format("{0}Sticker", patientRow.Id)) as OmrBarcodeField; Tz01RowData rowData = new Tz01RowData() { RowBounds = new RectangleF() { Location = barcodeField.TopLeft, Width = page.BottomRight.X - barcodeField.TopLeft.X, Height = omrStickerField.BottomRight.Y - barcodeField.TopLeft.Y }, UserInfo = userInfo, Page = page }; // Barcodes only at this level OmrBarcodeData omrBarcode = patientRow.Details.OfType <OmrBarcodeData>().FirstOrDefault(o => o.Id == String.Format("{0}Barcode", patientRow.Id)), omrSticker = patientRow.Details.OfType <OmrBarcodeData>().FirstOrDefault(o => o.Id == String.Format("{0}Sticker", patientRow.Id)); if (omrBarcode == null) { rowData.Barcode = String.Empty; } else { rowData.Barcode = omrBarcode.BarcodeData; } rowData.StickerValue = omrSticker?.BarcodeData; // Try to lookup the poor chap if (rowData.Barcode.StartsWith("T")) // TEMP ID AUTH { rowData.StickerValue = omrSticker?.BarcodeData; var childDataList = restUtil.Get <List <ChildEntity> >("ChildManagement.svc/GetChildById", new KeyValuePair <string, object>("childId", rowData.Barcode.Replace("T", "")) ); if (childDataList == null) { throw new InvalidOperationException("Could not deserialize response"); } else if (childDataList.Count == 0) { throw new InvalidOperationException("Child with barcode " + rowData.Barcode + " not found!"); } rowData.Child = childDataList[0].childEntity; } else { var childDataList = restUtil.Get <List <ChildEntity> >("ChildManagement.svc/SearchByBarcode", new KeyValuePair <string, object>("barcodeId", rowData.Barcode)); if (childDataList == null) { throw new InvalidOperationException("Could not deserialize response"); } else if (childDataList.Count == 0) { if (!String.IsNullOrEmpty(rowData.StickerValue)) { childDataList = restUtil.Get <List <ChildEntity> >("ChildManagement.svc/SearchByBarcode", new KeyValuePair <string, object>("barcodeId", rowData.StickerValue)); } if (childDataList == null) { throw new InvalidOperationException("Could not deserialize response"); } else if (childDataList.Count == 0) { throw new InvalidOperationException("Child with barcode " + rowData.Barcode + " not found!"); } } rowData.Child = childDataList[0].childEntity; } // Get appointments and vaccinations for child VaccinationAppointment[] appts = restUtil.Get <VaccinationAppointment[]>("VaccinationAppointmentManagement.svc/GetVaccinationAppointmentsByChildId", new KeyValuePair <string, object>("childId", rowData.Child.Id)); VaccinationEvent[] vaccinationEvent = restUtil.Get <VaccinationEvent[]>("VaccinationEvent.svc/GetVaccinationEventListByChildId", new KeyValuePair <string, object>("childId", rowData.Child.Id)); rowData.Appointment = new List <Tz01Vaccination>(); // iterate over the sub-rows foreach (var aptRow in page.Details.OfType <OmrRowData>().Where(o => o.Id.StartsWith(String.Format("{0}-", patientRow.Id))).OrderBy(r => r.Id)) { OmrBarcodeData omrAptId = aptRow.Details.OfType <OmrBarcodeData>().FirstOrDefault(); OmrBubbleData omrDay10 = aptRow.Details.OfType <OmrBubbleData>().FirstOrDefault(o => o.Key == "day10"), omrDay = aptRow.Details.OfType <OmrBubbleData>().FirstOrDefault(o => o.Key == "day"), omrOutreach = aptRow.Details.OfType <OmrBubbleData>().FirstOrDefault(o => o.Key == "outreach"), omrVaccine = aptRow.Details.OfType <OmrBubbleData>().FirstOrDefault(o => o.Key == "vaccine"); // First, get the appointment data Tz01Vaccination vaccineData = new Tz01Vaccination(); if (omrAptId == null) { barcodeField = page.Template.Fields.FirstOrDefault(o => o.AnswerRowGroup == aptRow.Id) as OmrBarcodeField; // Show a correction form ... BarcodeCorrection bc = new BarcodeCorrection(page, barcodeField); if (BarcodeUtil.HasData(page, barcodeField) && bc.ShowDialog() == System.Windows.Forms.DialogResult.OK) { vaccineData.Appointment = appts.FirstOrDefault(o => o.ScheduledDate.Date.Equals(DateTime.ParseExact(bc.BarcodeId, "MM-dd-yyyy", CultureInfo.InvariantCulture))); } } else { vaccineData.Appointment = appts.FirstOrDefault(o => o.Id.ToString() == omrAptId.BarcodeData); } // Validate we got an appointment if (vaccineData.Appointment == null) { throw new InvalidOperationException(String.Format("Could not find appointment data for update on row {0}", rowNum)); } vaccineData.All = omrVaccine?.Value == "all"; vaccineData.Outreach = Boolean.Parse(omrOutreach?.Value ?? "false"); if (omrDay != null || omrDay10 != null) { try { vaccineData.Date = new DateTime(vaccineData.Appointment.ScheduledDate.Year, vaccineData.Appointment.ScheduledDate.Month, (int)(omrDay?.ValueAsFloat + omrDay10?.ValueAsFloat)); if (vaccineData.Date > DateTime.Now) { vaccineData.Date = new DateTime(year, month, (int)(omrDay.ValueAsFloat + omrDay10.ValueAsFloat)); } } catch (Exception e) { Trace.TraceError(e.ToString()); } } rowData.Appointment.Add(vaccineData); } if (rowData.Appointment[0].Date.HasValue || rowData.Appointment[1].Date.HasValue || rowData.Appointment[0].All || rowData.Appointment[1].All || BarcodeUtil.HasData(page, omrStickerField)) { VaccineCorrection vc = new VaccineCorrection(rowData, vaccinationEvent, ReferenceData.Current.Doses); vc.ShowDialog(); } } } catch (Exception e) { Trace.TraceError("Error:{0}", e); throw; } finally { dlg.Close(); } }
public void UploadData(OmrPageOutput page) { if (!Connectivity.CheckForInternetConnection()) { MessageBox.Show( "Username is empty, This is usually caused by lack of internet connectivity. Please try again later"); Exception e = new Exception("No internet connection"); Trace.TraceError("Error:{0}", e); throw e; } try { this.Err = ""; var restUtil = new RestUtil(new Uri(ConfigurationManager.AppSettings["GIIS_URL"])); Trace.TraceInformation("Need to sync {0} children with TIIS at {1}", page.Details.Count, ConfigurationManager.AppSettings["GIIS_URL"]); foreach (var dtl in page.Details.OfType <OmrRowData>()) { // Get the barcode information for this child var barcodes = dtl.Details.OfType <OmrBarcodeData>(); if (barcodes.Count() == 0) { throw new InvalidOperationException("No barcode found on row!"); } // Child code var childCode = barcodes.FirstOrDefault(o => o.Id == dtl.Id + "_TempId"); if (childCode == null) { throw new InvalidOperationException("No GIIS TempId Found on Row!"); } GIIS.DataLayer.Child childData = null; // Get the child by barcode id var childDataList = restUtil.Get <List <ChildEntity> >("ChildManagement.svc/GetChildById", new KeyValuePair <string, object>("childId", childCode.BarcodeData.Replace("T", "")) ); if (childDataList == null) { throw new InvalidOperationException("Could not deserialize response"); } else if (childDataList.Count == 0) { throw new InvalidOperationException("Child with id " + childCode.BarcodeData + " not found!"); } childData = childDataList[0].childEntity; var permCode = barcodes.FirstOrDefault(o => o.Id == dtl.Id + "_Barcode"); // Permcode == null = no association if (permCode == null) { Err += String.Format("{0}, {1} will not be associated with a barcode sticker; ", childData.Lastname1, childData.Firstname1); continue; } // Now to update the child Trace.TraceInformation("Will associated child id {0} with barcode {1}", childData.Id, permCode.BarcodeData); childData.BarcodeId = permCode.BarcodeData; // Send the update restUtil.Get <RestReturn>("ChildManagement.svc/UpdateChild", new KeyValuePair <string, object>("barcode", childData.BarcodeId), new KeyValuePair <string, object>("firstname1", childData.Firstname1), new KeyValuePair <string, object>("lastname1", childData.Lastname1), new KeyValuePair <string, object>("birthdate", childData.Birthdate.ToString("yyyy-MM-dd")), new KeyValuePair <string, object>("gender", childData.Gender), new KeyValuePair <string, object>("healthFacilityId", childData.HealthcenterId), new KeyValuePair <string, object>("birthplaceId", childData.BirthplaceId), new KeyValuePair <string, object>("domicileId", childData.DomicileId), new KeyValuePair <string, object>("statusId", childData.StatusId), new KeyValuePair <string, object>("address", childData.Address), new KeyValuePair <string, object>("phone", childData.Phone), new KeyValuePair <string, object>("motherFirstname", childData.MotherFirstname), new KeyValuePair <string, object>("motherLastname", childData.MotherLastname), new KeyValuePair <string, object>("notes", "Updated by form scanning application"), new KeyValuePair <string, object>("userId", 1), new KeyValuePair <string, object>("childId", childData.Id) ); } } catch (Exception ex) { Trace.TraceError(ex.ToString()); throw; } }
public void UploadData(OmrPageOutput page) { if (!Connectivity.CheckForInternetConnection()) { MessageBox.Show( "Username is empty, This is usually caused by lack of internet connectivity. Please try again later"); Exception e = new Exception("No internet connection"); Trace.TraceError("Error:{0}", e); throw e; } try { this.Err = ""; var restUtil = new RestUtil(new Uri(ConfigurationManager.AppSettings["GIIS_URL"])); Trace.TraceInformation("Need to sync {0} children with TIIS at {1}", page.Details.Count, ConfigurationManager.AppSettings["GIIS_URL"]); var refDoses = restUtil.Get <List <GIIS.DataLayer.Dose> >("DoseManagement.svc/GetDoseList"); var refVaccines = restUtil.Get <List <GIIS.DataLayer.ScheduledVaccination> >("ScheduledVaccinationManagement.svc/GetScheduledVaccinationList"); var refItems = restUtil.Get <List <GIIS.DataLayer.Item> >("ItemManagement.svc/GetItemList"); var refItemLots = restUtil.Get <List <GIIS.DataLayer.ItemLot> >("StockManagement.svc/GetItemLots"); foreach (var dtl in page.Details.OfType <OmrRowData>()) { // Get the barcode information for this child var barcodes = dtl.Details.OfType <OmrBarcodeData>(); if (barcodes.Count() > 1) { throw new InvalidOperationException("Only one barcode per row is supported by this template"); } else if (barcodes.Count() == 0) { throw new InvalidOperationException("No barcode found on row!"); } // Child code var childCode = barcodes.FirstOrDefault(); // Output sync Trace.TraceInformation("Syncing child {0} to GIIS - Step 1 - Resolve Barcode ID", childCode.BarcodeData); GIIS.DataLayer.Child childData = null; // Get the child by barcode id if (childCode.BarcodeData.StartsWith("T")) { var childDataList = restUtil.Get <List <ChildEntity> >("ChildManagement.svc/GetChildById", new KeyValuePair <string, object>("childId", childCode.BarcodeData.Replace("T", "")) ); if (childDataList == null) { throw new InvalidOperationException("Could not deserialize response"); } else if (childDataList.Count == 0) { throw new InvalidOperationException("Child with barcode " + childCode.BarcodeData + " not found!"); } childData = childDataList[0].childEntity; } else { var childDataList = restUtil.Get <List <ChildEntity> >("ChildManagement.svc/SearchByBarcode", new KeyValuePair <string, object>("barcodeId", childCode.BarcodeData)); if (childDataList == null) { throw new InvalidOperationException("Could not deserialize response"); } else if (childDataList.Count == 0) { throw new InvalidOperationException("Child with barcode " + childCode.BarcodeData + " not found!"); } childData = childDataList[0].childEntity; } int childId = childData.Id; // Is this child a non-vaccination? var bubbleData = dtl.Details.OfType <OmrBubbleData>(); // Load questions OmrBubbleData weight10 = bubbleData.FirstOrDefault(o => o.Key == "weight10"), weight1 = bubbleData.FirstOrDefault(o => o.Key == "weight"), weight10ths = bubbleData.FirstOrDefault(o => o.Key == "weightD"), date10 = bubbleData.FirstOrDefault(o => o.Key == "date10"), date = bubbleData.FirstOrDefault(o => o.Key == "date"), ebfr = bubbleData.FirstOrDefault(o => o.Key == "ebfr"), vaccines = bubbleData.FirstOrDefault(o => o.Key == "vaccines"), outreach = bubbleData.FirstOrDefault(o => o.Key == "outreach"); // No vaccinations? if (vaccines == null) { Trace.TraceInformation("No vaccines detected!"); continue; } // Weight float weight = 0.0f; if (weight10 != null) { weight = weight + weight10.ValueAsFloat; } if (weight1 != null) { weight = weight + weight1.ValueAsFloat; } if (weight10ths != null) { weight = weight + (weight10ths.ValueAsFloat * 0.1f); } // Date int day = 0; if (date10 != null) { day += (int)date10.ValueAsFloat; } if (date != null) { day += (int)date.ValueAsFloat; } int txYear = DateTime.Now.Year; int txMonth = Int32.Parse(page.Parameters[1]); if (txMonth > DateTime.Now.Month) // We got a form whose month (ex: 11) is greater than the current month (ex: 10), since we cannot scan in the future, it must be last year { txYear--; } Trace.TraceInformation("Using Date {0}-{1}-{2}", day, txMonth, txYear); DateTime dateOfTx = new DateTime(txYear, txMonth, day); // Register child weight restUtil.Get <object>("ChildManagement.svc/RegisterChildWeight", new KeyValuePair <string, object>("childId", childId), new KeyValuePair <string, object>("date", dateOfTx.ToString("yyyy-MM-dd HH:mm:ss")), new KeyValuePair <string, object>("weight", weight), new KeyValuePair <string, object>("modifiedOn", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")), new KeyValuePair <string, object>("modifiedBy", 1) ); // Register child vaccinations if (vaccines == null || vaccines.Value == "none") { Trace.TraceInformation(string.Format("Child {0}, {1} was not vaccinated", childData.Lastname1, childData.Firstname1)); if (Err == null) { Err = String.Empty; } Err += String.Format("Child {0}, {1} requires manual reconciliation - Not all vaccinations given; ", childData.Lastname1, childData.Firstname1); continue; } else { // Get child's vaccination card var izCard = restUtil.Get <List <GIIS.DataLayer.VaccinationEvent> >("VaccinationEvent.svc/GetImmunizationCard", new KeyValuePair <string, object>("childId", childId), new KeyValuePair <string, object>("scheduledDate", dateOfTx.ToString("yyyy-MM-dd HH:MM:ss")) ); foreach (var vacc in izCard.Where(o => o.NonvaccinationReasonId == 0 && !o.VaccinationStatus && o.IsActive && (o.ScheduledDate.Month == txMonth || o.ScheduledDate.AddMonths(1).Month == txMonth) && o.ScheduledDate.Year == txYear)) { var dose = refDoses.Find(o => o.Id == vacc.DoseId); var vaccine = refVaccines.Find(o => o.Id == dose.ScheduledVaccinationId); var item = refItems.Find(o => o.Id == vaccine.ItemId); var itemLot = refItemLots.FindAll(o => o.ItemId == item.Id); var facilityBalance = restUtil.Get <List <GIIS.DataLayer.HealthFacilityBalance> >("StockManagement.svc/GetCurrentStockByLot", new KeyValuePair <String, Object>("hfId", page.Parameters[0])); var balance = facilityBalance.FindAll(o => itemLot.Exists(il => il.Gtin == o.Gtin && il.LotNumber == o.LotNumber)).OrderByDescending(p => p.Balance).FirstOrDefault(); if (balance == null) { Trace.TraceWarning("Facility has no balance for {0}! Can't determine vaccine lot / gtin", dose.Fullname); Err += String.Format("Child {0} cannot receive immunization {1} because facility has no {1} in stock. Please update stock and retry", childId, dose.Fullname); } Trace.TraceInformation("Giving child {0} immunization {1} (stock GTIN: {2} LN {3})", childId, dose.Fullname, balance.Gtin, balance.LotNumber); restUtil.Get <RestReturn>("VaccinationEvent.svc/UpdateVaccinationEvent", new KeyValuePair <String, Object>("vaccineLotId", itemLot.Find(o => o.Gtin == balance.Gtin && o.LotNumber == balance.LotNumber).Id), new KeyValuePair <String, Object>("healthFacilityId", page.Parameters[0]), new KeyValuePair <String, Object>("vaccinationDate", dateOfTx.ToString("yyyy-MM-dd HH:mm:ss")), new KeyValuePair <String, Object>("notes", "From Paper Register"), new KeyValuePair <String, Object>("vaccinationStatus", true), new KeyValuePair <String, Object>("userId", 1), new KeyValuePair <String, Object>("vaccinationEventId", vacc.Id), new KeyValuePair <String, Object>("outreach", outreach != null) ); if (outreach != null) { Trace.TraceInformation("Updating appointment {0} to be outreach", vacc.AppointmentId); restUtil.Get <RestReturn>("VaccinationAppointmentManagement.svc/UpdateVaccinationAppointment", new KeyValuePair <String, Object>("childId", childId), new KeyValuePair <String, Object>("vaccinationAppointmentId", vacc.AppointmentId), new KeyValuePair <String, Object>("outreach", true), new KeyValuePair <String, Object>("userId", 1), new KeyValuePair <String, Object>("scheduledFacilityId", page.Parameters[0]), new KeyValuePair <String, Object>("notes", "From Paper Form") ); } } } } } catch (Exception e) { Trace.TraceError(e.ToString()); Err = e.Message; } }
public void UploadData(OmrPageOutput page) { if (!Connectivity.CheckForInternetConnection()) { MessageBox.Show( "Username is empty, This is usually caused by lack of internet connectivity. Please try again later"); Exception e = new Exception("No internet connection"); Trace.TraceError("Error:{0}", e); throw e; } StatusDialog dlg = new StatusDialog(); dlg.Show(); try { int facilityId = FacilitySelectionContext.FacilityId; // Non-remembered facility if (facilityId == 0) { LocationSelectionBox location = new LocationSelectionBox(); if (location.ShowDialog() != System.Windows.Forms.DialogResult.OK) { throw new InvalidOperationException("Cannot upload data without selecting a facility"); } if (location.Remember) { FacilitySelectionContext.FacilityId = location.FacilityId; } facilityId = location.FacilityId; } var monthBubble = page.Details.OfType <OmrBubbleData>().FirstOrDefault(o => o.Key == "Month"); if (monthBubble == null) { Err += "Form is missing month!; "; return; } // Now we want to upload the data WeighTallySubmission submission = new WeighTallySubmission() { Month = (int)monthBubble.ValueAsFloat, FacilityId = facilityId, Data = new List <WeighTallyData>() }; // Iterate through the rows foreach (var dtl in page.Details.OfType <OmrRowData>()) { OmrBubbleData ageData = dtl.Details.OfType <OmrBubbleData>().FirstOrDefault(o => o.Key == "Age"), genderData = dtl.Details.OfType <OmrBubbleData>().FirstOrDefault(o => o.Key == "Gender"), weightData = dtl.Details.OfType <OmrBubbleData>().FirstOrDefault(o => o.Key == "Weight"), ebfData = dtl.Details.OfType <OmrBubbleData>().FirstOrDefault(o => o.Key == "EBF"), rfData = dtl.Details.OfType <OmrBubbleData>().FirstOrDefault(o => o.Key == "RF"); if (ageData == null) { Err += String.Format("Row {0} is missing age group, skipping; ", dtl.Id); continue; } else if (weightData == null) { Err += String.Format("Row {0} is missing weight group, skipping; ", dtl.Id); continue; } else if (genderData == null) { Err += String.Format("Row {0} is missing gender group, skipping; ", dtl.Id); continue; } bool ebf = ebfData != null; bool rf = rfData != null; submission.Data.Add(new WeighTallyData() { AgeGroup = ageData.Value, Gender = genderData.Value, WeightGroup = weightData.Value, Ebf = ebf, Rf = rf }); } RestUtil restUtil = new RestUtil(new Uri(ConfigurationManager.AppSettings["GIIS_URL"])); restUtil.Post("AnonymousDataManagement.svc/PostWeighTally", submission); } catch (Exception e) { Trace.TraceError("Error:{0}", e); throw; } finally { dlg.Close(); } }