protected void ValidateVaccinationDate(object sender, ServerValidateEventArgs e)
    {
        if (Page.IsValid)
        {
            for (int rowIndex = 0; rowIndex < gvVaccinationEvent.Rows.Count; rowIndex++)
            {
                //extract the TextBox values
                TextBox           txtVaccinationDate = (TextBox)gvVaccinationEvent.Rows[rowIndex].Cells[3].FindControl("txtVaccinationDate");
                Label             lblId      = (Label)gvVaccinationEvent.Rows[rowIndex].Cells[7].FindControl("lblId");
                int               id         = int.Parse(lblId.Text);
                VaccinationEvent  v          = VaccinationEvent.GetVaccinationEventById(id);
                Child             c          = v.Child;
                ConfigurationDate dateformat = ConfigurationDate.GetConfigurationDateById(int.Parse(Configuration.GetConfigurationByName("DateFormat").Value));

                DateTime date = DateTime.ParseExact(txtVaccinationDate.Text, dateformat.DateFormat, CultureInfo.CurrentCulture);

                e.IsValid = date <= DateTime.Today && date >= c.Birthdate;

                if (e.IsValid == false)
                {
                    break;
                }
            }
        }
    }
        /// <summary>
        /// Updates Vaccination Event with default data
        /// </summary>
        /// <param name="ve">Vaccination Event to be updated</param>
        /// <returns></returns>
        public VaccinationEvent RemoveVaccinationEvent(VaccinationEvent ve, int userId)
        {
            if (ve == null)
            {
                throw new ArgumentNullException("ve");
            }
            if (userId <= 0)
            {
                throw new ArgumentException("userId");
            }

            int            lotid    = ve.VaccineLotId;
            HealthFacility facility = ve.HealthFacility;

            ve.VaccineLotId           = 0;
            ve.VaccineLotText         = String.Empty;
            ve.VaccinationDate        = ve.ScheduledDate;
            ve.Notes                  = String.Empty;
            ve.VaccinationStatus      = false;
            ve.NonvaccinationReasonId = 0;
            ve.HealthFacilityId       = ve.Appointment.ScheduledFacilityId;

            ve.ModifiedOn = DateTime.Now;
            ve.ModifiedBy = userId;
            int i = VaccinationEvent.Update(ve);

            if (i > 0)
            {
                RescheduleNextDose(ve, true);
                //update balance
                StockManagementLogic sml = new StockManagementLogic();
                int update = sml.ClearBalance(facility, lotid);
            }
            return(ve);
        }
        /// <summary>
        /// Recalculates scheduled date for vaccination event following <paramref name="ve"/> with the difference between scheduled date and vaccination date
        /// </summary>
        /// <param name="ve">The vaccination event that triggers the reschedule of the following vaccination event </param>
        /// <param name="daysdiff">The difference between scheduled date and actual vaccination date</param>
        /// <param name="remove"> If the vaccination event is being rolled back so rescheduling needs to be rolled back also</param>
        /// <returns></returns>
        public VaccinationEvent RescheduleNextDose(VaccinationEvent ve, bool remove)
        {
            if (ve == null)
            {
                throw new ArgumentNullException("ve");
            }

            VaccinationEvent vaccevent = new VaccinationEvent();
            int currAgeDef             = ve.Dose.AgeDefinition.Days;
            int daysdiff = 0;

            int dosenum = ve.Dose.DoseNumber + 1;

            if (dosenum > 1)
            {
                int vid = VaccinationEvent.NextDose(ve.Dose.ScheduledVaccinationId, ve.ChildId, dosenum);
                if (vid != -1)
                {
                    vaccevent = VaccinationEvent.GetVaccinationEventById(vid);
                    int nextAgeDef = vaccevent.Dose.AgeDefinition.Days;
                    daysdiff = nextAgeDef - currAgeDef;

                    if (remove)
                    {
                        VaccinationEvent.UpdateIsActive(vid, false);
                        VaccinationEvent.UpdateEvent(vid, ve.ScheduledDate.AddDays(daysdiff), ve.ModifiedBy);
                    }
                    else
                    {
                        VaccinationEvent.UpdateIsActive(vid, true);
                        VaccinationEvent.UpdateEvent(vid, ve.VaccinationDate.AddDays(daysdiff), ve.ModifiedBy);

                        //update others if the vaccination date is later
                        List <VaccinationEvent> vacceventlist = VaccinationEvent.GetVaccinationEventByAppointmentId(ve.AppointmentId);
                        foreach (VaccinationEvent v in vacceventlist)
                        {
                            if (ve.Id != v.Id)
                            {
                                if (v.VaccinationStatus || v.NonvaccinationReasonId != 0)
                                {
                                    if (ve.VaccinationDate > v.VaccinationDate)
                                    {
                                        VaccinationEvent nv = VaccinationEvent.GetVaccinationEventById(VaccinationEvent.NextDose(v.Dose.ScheduledVaccinationId, v.ChildId, dosenum));
                                        VaccinationEvent vn = VaccinationEvent.GetVaccinationEventById(vid);
                                        if (!nv.VaccinationStatus)
                                        {
                                            VaccinationEvent.UpdateEvent(nv.Id, vn.ScheduledDate, ve.ModifiedBy);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(vaccevent);
        }
    protected void gvVaccinationEvent_DataBound(object sender, EventArgs e)
    {
        if (gvVaccinationEvent.Rows.Count > 0)
        {
            foreach (GridViewRow gvr in gvVaccinationEvent.Rows)
            {
                gvr.Cells[6].Visible = false;
                gvr.Cells[0].Visible = false;
            }

            gvVaccinationEvent.HeaderRow.Cells[6].Visible = false;
            gvVaccinationEvent.HeaderRow.Cells[0].Visible = false;
            string _appid = Request.QueryString["appId"];
            if (!String.IsNullOrEmpty(_appid))
            {
                foreach (GridViewRow gvr in gvVaccinationEvent.Rows)
                {
                    Label            lblId = (Label)gvr.FindControl("lblId");
                    VaccinationEvent ve    = VaccinationEvent.GetVaccinationEventById(int.Parse(lblId.Text));

                    if ((!ve.VaccinationStatus) && (ve.NonvaccinationReasonId == 0 || ve.NonVaccinationReason.KeepChildDue == true))
                    {
                        gvr.Visible = true;
                        //int datediff = DateTime.Today.Date.Subtract(ve.Child.Birthdate).Days;
                        //if (ve.Dose.ToAgeDefinitionId != 0 && ve.Dose.ToAgeDefinitionId != null)
                        //    if (datediff > ve.Dose.ToAgeDefinition.Days)
                        //        gvr.Visible = false;
                    }
                    else
                    {
                        gvr.Visible = false;
                    }
                }
            }

            string _id = Request.QueryString["id"];
            if (!String.IsNullOrEmpty(_id))
            {
                foreach (GridViewRow gvr in gvVaccinationEvent.Rows)
                {
                    int              id    = int.Parse(_id);
                    Label            lblId = (Label)gvr.FindControl("lblId");
                    VaccinationEvent ve    = VaccinationEvent.GetVaccinationEventById(int.Parse(lblId.Text));

                    if (ve.Id == id)
                    {
                        gvr.Visible = true;
                    }
                    else
                    {
                        gvr.Visible = false;
                    }
                }
            }
        }
    }
Esempio n. 5
0
        /// <summary>
        /// Update vaccination
        /// </summary>
        /// <param name="evt"></param>
        private void UpdateVaccination(VaccinationEvent evt)
        {
            RestUtil restUtil = new RestUtil(new Uri(ConfigurationManager.AppSettings["GIIS_URL"]));

            restUtil.Get <RestReturn>("VaccinationEvent.svc/UpdateVaccinationEventById",
                                      new KeyValuePair <string, object>("vaccinationEventId", evt.Id),
                                      new KeyValuePair <String, Object>("vaccinationDate", evt.ScheduledDate.ToString("yyyy-MM-dd HH:mm:ss")),
                                      new KeyValuePair <String, Object>("notes", "From form scanner"),
                                      new KeyValuePair <String, Object>("vaccinationStatus", true));
        }
    private void BindByHealthFacilityMonthYear(int healthfacilityid, int month, int year)
    {
        DateTime monthDate     = new DateTime(year, month, DateTime.DaysInMonth(year, month));
        int      maximumRows   = int.MaxValue;
        int      startRowIndex = 0;

        gvVaccinationEvent.DataSource = VaccinationEvent.GetMonthlyPlan(ref maximumRows, ref startRowIndex, healthfacilityid, monthDate);
        gvVaccinationEvent.DataBind();
        string s = HealthFacility.GetAllChildsForOneHealthFacility(healthfacilityid);

        gvTotalVaccinesRequired.DataSource = VaccineQuantity.GetQuantityMonthlyPlan(s, monthDate);
        gvTotalVaccinesRequired.DataBind();
    }
        /// <summary>
        /// Updates Vaccination Event with given id <paramref name="id"/> with all the other parameters.
        /// </summary>
        /// <param name="id">The id of the vaccination event that is being updated </param>
        /// <param name="lotId">The vaccine lot used for this vaccination event</param>
        /// <param name="vaccinationdate">The vaccination date for this vaccination event</param>
        /// <param name="hfId">The health facility where this vaccination event happened</param>
        /// <param name="done">Status of the vaccination event</param>
        /// <param name="nonvaccreasonId">The reason for not vaccinating for this vaccination event</param>
        /// <returns></returns>
        public VaccinationEvent UpdateVaccinationEvent(int id, int lotId, DateTime vaccinationdate, int hfId, bool done, int nonvaccreasonId, int userId, DateTime modifiedOn)
        {
            if (id <= 0)
            {
                throw new ArgumentException("id");
            }
            if (hfId <= 0)
            {
                throw new ArgumentException("hfId");
            }
            if (userId <= 0)
            {
                throw new ArgumentException("userId");
            }

            VaccinationEvent o = VaccinationEvent.GetVaccinationEventById(id);

            o.VaccineLotId = lotId;

            o.VaccinationDate   = vaccinationdate;
            o.HealthFacilityId  = hfId;
            o.VaccinationStatus = done;
            if (done)
            {
                o.NonvaccinationReasonId = 0;
            }
            else
            {
                o.NonvaccinationReasonId = nonvaccreasonId;
                o.VaccineLotId           = 0;
            }
            o.ModifiedOn = modifiedOn;
            o.ModifiedBy = userId;

            int i = VaccinationEvent.Update(o);

            if (i > 0)
            {
                if (done || o.NonVaccinationReason.KeepChildDue == false)
                {
                    RescheduleNextDose(o, false);
                }

                if (o.VaccineLotId > 0)
                {
                    StockManagementLogic sml = new StockManagementLogic();
                    ItemTransaction      it  = sml.Vaccinate(o.HealthFacility, o);
                }
            }
            return(o);
        }
    protected void btnEdit_Click(object sender, EventArgs e)
    {
        try
        {
            if (Page.IsValid)
            {
                int i       = 0;
                int childId = 0;
                for (int rowIndex = 0; rowIndex < gvVaccinationEvent.Rows.Count; rowIndex++)
                {
                    //extract the TextBox values
                    DropDownList     ddlVaccineLot           = (DropDownList)gvVaccinationEvent.Rows[rowIndex].Cells[2].FindControl("ddlVaccineLot");
                    TextBox          txtVaccinationDate      = (TextBox)gvVaccinationEvent.Rows[rowIndex].Cells[3].FindControl("txtVaccinationDate");
                    CheckBox         chkDoneStatus           = (CheckBox)gvVaccinationEvent.Rows[rowIndex].Cells[4].FindControl("chkStatus");
                    DropDownList     ddlNonvaccinationReason = (DropDownList)gvVaccinationEvent.Rows[rowIndex].Cells[5].FindControl("ddlNonvaccinationReason");
                    Label            lblId = (Label)gvVaccinationEvent.Rows[rowIndex].Cells[7].FindControl("lblId");
                    int              id    = int.Parse(lblId.Text);
                    VaccinationEvent v     = VaccinationEvent.GetVaccinationEventById(id);
                    childId = v.ChildId;
                    if ((ddlVaccineLot.SelectedIndex > 0 || ddlNonvaccinationReason.SelectedIndex > 0) && gvVaccinationEvent.Rows[rowIndex].Visible)
                    {
                        i = UpdateOneRecord(id, int.Parse(ddlVaccineLot.SelectedValue), txtVaccinationDate.Text, chkDoneStatus.Checked, int.Parse(ddlNonvaccinationReason.SelectedValue));
                    }
                }
                if (i > 0)
                {
                    gvChild.Visible = true;
                    odsChild.SelectParameters.Clear();
                    odsChild.SelectParameters.Add("childId", childId.ToString());

                    lblSuccess.Visible = true;
                    lblWarning.Visible = false;
                    lblError.Visible   = false;
                }
                else
                {
                    lblSuccess.Visible = false;
                    lblWarning.Visible = false;
                    lblError.Visible   = true;
                }
            }
        }
        catch (Exception ex)
        {
            lblSuccess.Visible = false;
            lblWarning.Visible = false;
            lblError.Visible   = true;
        }
    }
        /// <summary>
        /// Update vaccination
        /// </summary>
        /// <param name="evt"></param>
        private void UpdateVaccination(VaccinationEvent evt)
        {
            var retVal = this.m_restUtil.Get <RestReturn>("VaccinationEvent.svc/UpdateVaccinationEvent",
                                                          new KeyValuePair <string, object>("vaccinationEventId", evt.Id),
                                                          new KeyValuePair <String, Object>("vaccinationDate", evt.VaccinationDate.ToString("yyyy-MM-dd")),
                                                          new KeyValuePair <String, Object>("notes", "From form scanner"),
                                                          new KeyValuePair <String, Object>("userId", this.m_rowData.UserInfo.Id),
                                                          new KeyValuePair <String, Object>("healthFacilityId", evt.HealthFacilityId),
                                                          new KeyValuePair <String, Object>("vaccineLotId", -2),
                                                          new KeyValuePair <String, Object>("vaccinationStatus", evt.VaccinationStatus));

            if (retVal.Id < 0)
            {
                MessageBox.Show("TIIS Service reported Error code, please attempt to submit again in a few moments");
                return;
            }
        }
    protected void ddlHealthFacility_SelectedIndexChanged(object sender, EventArgs e)
    {
        int    id  = 0;
        string _id = Request.QueryString["appId"];

        if (!String.IsNullOrEmpty(_id))
        {
            int.TryParse(_id, out id);
            //VaccinationEvent o = VaccinationEvent.GetVaccinationEventById(id);
            int hfId = int.Parse(ddlHealthFacility.SelectedValue);
            if (hfId != -1)
            {
                bool isUsed = SystemModule.GetSystemModuleByName("StockManagement").IsUsed;
                if (isUsed)
                {
                    if (gvVaccinationEvent.Rows.Count > 0)
                    {
                        foreach (GridViewRow gvr in gvVaccinationEvent.Rows)
                        {
                            if (gvr.RowType == DataControlRowType.DataRow)
                            {
                                int vid                        = int.Parse(gvr.Cells[0].Text);
                                VaccinationEvent o             = VaccinationEvent.GetVaccinationEventById(vid);
                                DropDownList     ddlVaccineLot = (DropDownList)gvr.FindControl("ddlVaccineLot");
                                ObjectDataSource odsItemLot    = (ObjectDataSource)gvr.FindControl("odsItemLot");
                                string           hfcode        = HealthFacility.GetHealthFacilityById(int.Parse(ddlHealthFacility.SelectedValue)).Code;
                                odsItemLot.SelectParameters.Clear();
                                odsItemLot.SelectParameters.Add("itemId", o.Dose.ScheduledVaccination.ItemId.ToString());
                                odsItemLot.SelectParameters.Add("hfId", hfcode);
                                odsItemLot.DataBind();
                                ddlVaccineLot.DataBind();
                                if (ddlVaccineLot.Items.Count > 2)
                                {
                                    ddlVaccineLot.SelectedIndex = 2;
                                }
                                else
                                {
                                    ddlVaccineLot.SelectedIndex = 0;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    private int RemoveOneRecord(int id)
    {
        int i      = -1;
        int userId = CurrentEnvironment.LoggedUser.Id;

        VaccinationEvent o = VaccinationEvent.GetVaccinationEventById(id);

        VaccinationLogic vl = new VaccinationLogic();

        o = vl.RemoveVaccinationEvent(o, userId);

        if (o != null)
        {
            UpdateVaccinationAppointment(o.AppointmentId, false);
            i = 1;
        }
        return(i);
    }
    /// <summary>
    /// Populate controls on the page by vaccination event
    /// </summary>
    /// <param name="v">The vaccination event that is being called</param>
    private void PopulateControls(VaccinationEvent v)
    {
        lnkChild.Text          = v.Child.Name;
        lnkChild.PostBackUrl   = "Child.aspx?id=" + v.Child.Id;
        lblChildBirthdate.Text = v.Child.Birthdate.ToString("dd-MMM-yyyy");
        chbxOutreach.Checked   = v.Appointment.Outreach;
        string doses = v.Dose.Fullname;

        lblVaccineDose.Text   = doses;
        lblScheduledDate.Text = v.ScheduledDate.ToString("dd-MMM-yyyy");
        lblHealthCenter.Text  = v.HealthFacility.Name;

        if (v.VaccinationStatus || v.NonvaccinationReasonId != 0)
        {
            if (v.HealthFacilityId == CurrentEnvironment.LoggedUser.HealthFacilityId || v.HealthFacility.ParentId == CurrentEnvironment.LoggedUser.HealthFacilityId || CurrentEnvironment.LoggedUser.HealthFacility.ParentId == 0)
            {
                string s = HealthFacility.GetAllChildsForOneHealthFacility(CurrentEnvironment.LoggedUser.HealthFacilityId, true);
                string where = string.Format(@"AND ""ID"" in ( {0})", s);
                odsHealthF.SelectParameters.Clear();
                odsHealthF.SelectParameters.Add("ids", where);
                odsHealthF.DataBind();

                ddlHealthFacility.SelectedValue = v.HealthFacilityId.ToString();
            }
            else
            {
                lblWarning.Text             = "You can not modify this record!";
                lblWarning.Visible          = true;
                ddlHealthFacility.Visible   = false;
                gvVaccinationEvent.Visible  = false;
                btnEdit.Visible             = false;
                btnRemove.Visible           = false;
                lblHealthFacilityId.Visible = false;
                chbxOutreach.Visible        = false;
            }
        }
        odsVaccinationEvent.SelectParameters.Clear();
        odsVaccinationEvent.SelectParameters.Add("appId", v.AppointmentId.ToString());

        tblsupp.Visible = false;
    }
    protected void btnImmunizationCard_Click(object sender, EventArgs e)
    {
        int    id      = -1;
        int    childId = 0;
        string _id     = Request.QueryString["id"];

        if (!String.IsNullOrEmpty(_id))
        {
            int.TryParse(_id, out id);
            VaccinationEvent o = VaccinationEvent.GetVaccinationEventById(id);
            childId = o.ChildId;
        }
        int    appid  = -1;
        string _appid = Request.QueryString["appid"];

        if (!String.IsNullOrEmpty(_appid))
        {
            int.TryParse(_appid, out appid);
            VaccinationAppointment o = VaccinationAppointment.GetVaccinationAppointmentById(appid);
            childId = o.ChildId;
        }
        Response.Redirect("ViewImmunizationCard.aspx?id=" + childId, false);
    }
    private int UpdateOneRecord(int id, int vaccineLotId, string vaccinationDate, bool done, int nonvaccinationReason)
    {
        int i = -1;

        int      hfId   = CurrentEnvironment.LoggedUser.HealthFacilityId;
        int      userId = CurrentEnvironment.LoggedUser.Id;
        DateTime date   = DateTime.ParseExact(vaccinationDate, ConfigurationDate.GetConfigurationDateById(int.Parse(Configuration.GetConfigurationByName("DateFormat").Value)).DateFormat.ToString(), CultureInfo.CurrentCulture);

        if (ddlHealthFacility.SelectedIndex != 0)
        {
            hfId = int.Parse(ddlHealthFacility.SelectedValue);
        }

        VaccinationLogic vl = new VaccinationLogic();
        VaccinationEvent ve = vl.UpdateVaccinationEvent(id, vaccineLotId, date, hfId, done, nonvaccinationReason, userId, DateTime.Now);

        if (ve != null)
        {
            UpdateVaccinationAppointment(ve.AppointmentId, chbxOutreach.Checked);
            UpdateSupplements(ve.ChildId);
            i = 1;
        }
        return(i);
    }
    protected void gvVaccinationEvent_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (!this.IsPostBack)
        {
            e.Row.Cells[0].Visible = false;
            VaccinationEvent o = (VaccinationEvent)e.Row.DataItem;
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                TextBox txtVaccinationDate = (TextBox)e.Row.FindControl("txtVaccinationDate");

                CheckBox     chkDoneStatus           = (CheckBox)e.Row.FindControl("chkStatus");
                DropDownList ddlNonvaccinationReason = (DropDownList)e.Row.FindControl("ddlNonvaccinationReason");

                DropDownList     ddlVaccineLot = (DropDownList)e.Row.FindControl("ddlVaccineLot");
                ObjectDataSource odsItemLot    = (ObjectDataSource)e.Row.FindControl("odsItemLot");
                if (ddlHealthFacility.SelectedIndex != 0)
                {
                    string hfcode = HealthFacility.GetHealthFacilityById(int.Parse(ddlHealthFacility.SelectedValue)).Code;
                    odsItemLot.SelectParameters.Clear();
                    odsItemLot.SelectParameters.Add("itemId", o.Dose.ScheduledVaccination.ItemId.ToString());
                    odsItemLot.SelectParameters.Add("hfId", hfcode);
                    odsItemLot.DataBind();
                    ddlVaccineLot.DataBind();
                    if (ddlVaccineLot.Items.Count > 2)
                    {
                        ddlVaccineLot.SelectedIndex = 2;
                    }
                    else
                    {
                        ddlVaccineLot.SelectedIndex = 0;
                    }
                }
                AjaxControlToolkit.CalendarExtender ceVaccinationDate  = (AjaxControlToolkit.CalendarExtender)e.Row.FindControl("ceVaccinationDate");
                RegularExpressionValidator          revVaccinationDate = (RegularExpressionValidator)e.Row.FindControl("revVaccinationDate");

                ConfigurationDate dateformat = ConfigurationDate.GetConfigurationDateById(int.Parse(Configuration.GetConfigurationByName("DateFormat").Value));
                ceVaccinationDate.Format                = dateformat.DateFormat;
                revVaccinationDate.ErrorMessage         = dateformat.DateFormat;
                revVaccinationDate.ValidationExpression = dateformat.DateExpresion;
                ceVaccinationDate.EndDate               = DateTime.Today.Date;
                ceVaccinationDate.StartDate             = o.Child.Birthdate;
                txtVaccinationDate.Text = DateTime.Today.ToString(dateformat.DateFormat);

                if (o.VaccinationStatus)
                {
                    chkDoneStatus.Checked           = true;
                    ddlVaccineLot.SelectedValue     = o.VaccineLotId.ToString();
                    txtVaccinationDate.Text         = o.VaccinationDate.ToString(dateformat.DateFormat);
                    ddlNonvaccinationReason.Visible = false;
                }
                else if (!o.VaccinationStatus && o.NonvaccinationReasonId != 0)
                {
                    chkDoneStatus.Checked                 = false;
                    ddlVaccineLot.SelectedIndex           = 0;
                    txtVaccinationDate.Text               = o.VaccinationDate.ToString(dateformat.DateFormat);
                    ddlNonvaccinationReason.Visible       = true;
                    ddlNonvaccinationReason.SelectedValue = o.NonvaccinationReasonId.ToString();
                }
            }
        }
    }
    /// <summary>
    /// Populate Controls on the page by using the vaccination appointment
    /// </summary>
    /// <param name="app">The vaccination appointment that is being called</param>
    private void PopulateControls(VaccinationAppointment app)
    {
        List <VaccinationEvent> le = VaccinationEvent.GetVaccinationEventByAppointmentId(app.Id);

        lnkChild.Text          = app.Child.Name;
        lnkChild.PostBackUrl   = "Child.aspx?id=" + app.Child.Id;
        lblChildBirthdate.Text = app.Child.Birthdate.ToString("dd-MMM-yyyy");
        chbxOutreach.Checked   = app.Outreach;
        string           doses = "";
        VaccinationEvent o     = null;

        foreach (VaccinationEvent ve in le)
        {
            doses += ve.Dose.Fullname + " ";
            lblHealthCenter.Text = ve.HealthFacility.Name;
            o = ve;
        }
        lblVaccineDose.Text   = doses;
        lblScheduledDate.Text = app.ScheduledDate.ToString("dd-MMM-yyyy"); //ConfigurationDate.GetConfigurationDateById(int.Parse(Configuration.GetConfigurationByName("DateFormat").Value)).DateFormat);

        if (!o.IsActive)
        {
            lblInfo.Visible            = true;
            btnEdit.Visible            = false;
            btnRemove.Visible          = false;
            gvVaccinationEvent.Visible = false;
        }

        foreach (VaccinationEvent ve in le)
        {
            int datediff = DateTime.Today.Date.Subtract(ve.Child.Birthdate).Days;
            if (ve.Dose.FromAgeDefinitionId != 0 && ve.Dose.FromAgeDefinitionId != null)
            {
                if (datediff < ve.Dose.FromAgeDefinition.Days)
                {
                    lblInfo.Visible = true;
                    break;
                }
            }
            if (ve.Dose.ToAgeDefinitionId != 0 && ve.Dose.ToAgeDefinitionId != null)
            {
                if (datediff > ve.Dose.ToAgeDefinition.Days)
                {
                    lblInfo.Visible = true;
                    break;
                }
            }
        }

        // populate supplements table
        lblVitADate.Text       = DateTime.Today.Date.ToString("dd-MMM-yyyy");
        lblMebendezolDate.Text = DateTime.Today.Date.ToString("dd-MMM-yyyy");

        ChildSupplements su = ChildSupplements.GetChildSupplementsByChild(app.Child.Id, DateTime.Today.Date); //get by date

        if (su != null)
        {
            chkVitA.Checked       = su.Vita;
            chkMebendezol.Checked = su.Mebendezol;
        }
        else
        {
            chkVitA.Checked       = false;
            chkMebendezol.Checked = false;
        }

        //populate facility dropdownlist

        int            hfId = CurrentEnvironment.LoggedUser.HealthFacilityId;
        HealthFacility hf   = HealthFacility.GetHealthFacilityById(hfId);

        string where = string.Empty;
        if (!hf.TopLevel)
        {
            string s = HealthFacility.GetAllChildsForOneHealthFacility(hfId, true);
            where = string.Format(@"AND ""ID"" in ( {0})", s);
        }
        odsHealthF.SelectParameters.Clear();
        odsHealthF.SelectParameters.Add("ids", where);
        odsHealthF.DataBind();
        if (hf.VaccinationPoint)
        {
            ddlHealthFacility.SelectedValue = hfId.ToString();
        }

        //populate events grid
        odsVaccinationEvent.SelectParameters.Clear();
        odsVaccinationEvent.SelectParameters.Add("appId", app.Id.ToString());
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.Page.IsPostBack)
        {
            List <string> actionList        = null;
            string        sessionNameAction = "";
            if (CurrentEnvironment.LoggedUser != null)
            {
                sessionNameAction = "__GIS_actionList_" + CurrentEnvironment.LoggedUser.Id;
                actionList        = (List <string>)Session[sessionNameAction];
            }

            if ((actionList != null) && actionList.Contains("ViewVaccinationEvent") && (CurrentEnvironment.LoggedUser != null))
            {
                int    userId     = CurrentEnvironment.LoggedUser.Id;
                string language   = CurrentEnvironment.Language;
                int    languageId = int.Parse(language);
                Dictionary <string, string> wtList = (Dictionary <string, string>)HttpContext.Current.Cache["VaccinationEvent-dictionary" + language];
                if (wtList == null)
                {
                    List <WordTranslate> wordTranslateList = WordTranslate.GetWordByLanguage(languageId, "VaccinationEvent");
                    wtList = new Dictionary <string, string>();
                    foreach (WordTranslate vwt in wordTranslateList)
                    {
                        wtList.Add(vwt.Code, vwt.Name);
                    }
                    HttpContext.Current.Cache.Insert("VaccinationEvent-dictionary" + language, wtList);
                }

                //controls
                this.lbChild.Text          = wtList["VaccinationEventChild"];
                this.lbVaccineDose.Text    = wtList["VaccinationEventDose"];
                this.lbHealthCenter.Text   = wtList["VaccinationEventHealthFacility"];
                this.lbScheduledDate.Text  = wtList["VaccinationEventScheduledDate"];
                this.lbChildBirthdate.Text = wtList["VaccinationEventBirthdate"];
                //this.cvVaccinationdate.ErrorMessage = wtList["VaccinationEventDateValidator"];

                //grid header text
                gvVaccinationEvent.Columns[1].HeaderText = wtList["VaccinationEventDose"];
                gvVaccinationEvent.Columns[2].HeaderText = wtList["VaccinationEventVaccineLot"];
                gvVaccinationEvent.Columns[3].HeaderText = wtList["VaccinationEventVaccinationDate"];
                gvVaccinationEvent.Columns[4].HeaderText = wtList["VaccinationEventVaccinationStatus"];
                gvVaccinationEvent.Columns[5].HeaderText = wtList["VaccinationEventNonvaccinationReason"];

                //actions
                this.btnEdit.Visible   = actionList.Contains("EditVaccinationEvent");
                this.btnRemove.Visible = actionList.Contains("RemoveVaccinationEvent");

                //buttons
                this.btnEdit.Text   = wtList["VaccinationEventEditButton"];
                this.btnRemove.Text = wtList["VaccinationEventRemoveButton"];

                //message
                this.lblSuccess.Text = wtList["VaccinationEventSuccessText"];
                this.lblWarning.Text = wtList["VaccinationEventWarningText"];
                this.lblError.Text   = wtList["VaccinationEventErrorText"];

                //Page Title
                this.lblTitle.Text = wtList["VaccinationEventPageTitle"];

                //selected object by id
                int    appId  = -1;
                string _appid = Request.QueryString["appId"];
                if (!String.IsNullOrEmpty(_appid))
                {
                    int.TryParse(_appid, out appId);
                    VaccinationAppointment app = VaccinationAppointment.GetVaccinationAppointmentById(appId);
                    PopulateControls(app);
                }
                int    id  = -1;
                string _id = Request.QueryString["id"];
                if (!String.IsNullOrEmpty(_id))
                {
                    id = int.Parse(_id);
                    VaccinationEvent v = VaccinationEvent.GetVaccinationEventById(id);
                    PopulateControls(v);
                }
            }
            else
            {
                Response.Redirect("Default.aspx");
            }
        }
    }
Esempio n. 18
0
        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>
        /// Performs stock transaction for a vaccination event
        /// </summary>
        /// <param name="facility">The facility in which the vaccination event occurred</param>
        /// <param name="vaccination">The vaccination event</param>
        /// <returns>The <see cref="T:GIIS.DataLayer.ItemTransaction"/> representing the transfer</returns>
        public ItemTransaction Vaccinate(HealthFacility facility, VaccinationEvent vaccination)
        {
            // Vaccination not given = no transaction
            if (!vaccination.VaccinationStatus)
            {
                return(null);
            }

            List <ItemLot> lots = new List <ItemLot>();

            // Verify
            if (facility == null)
            {
                throw new ArgumentNullException("facility");
            }
            else if (vaccination == null)
            {
                throw new ArgumentNullException("vaccination");
            }
            else if (String.IsNullOrEmpty(vaccination.VaccineLot))
            {
                ItemManufacturer     gtin = ItemManufacturer.GetItemManufacturerByItem(vaccination.Dose.ScheduledVaccination.ItemId);
                OrderManagementLogic oml  = new OrderManagementLogic();
                lots.Add(oml.GetOldestLot(facility, gtin.Gtin));
            }

            //throw new ArgumentException("Vaccination event missing lot#", "vaccination");

            // Item lot that was used
            if (lots.Count == 0)
            {
                lots.Add(ItemLot.GetItemLotById(vaccination.VaccineLotId));
            }
            //lots.Add(ItemLot.GetItemLotByLotNumber(vaccination.VaccineLot));
            if (lots.Count == 0)
            {
                return(null);
            }


            // throw new InvalidOperationException("Cannot find the specified ItemLot relation (GTIN)");

            // Transaction type
            TransactionType vaccinationType = TransactionType.GetTransactionTypeList().FirstOrDefault(o => o.Name == "Vaccination");

            if (vaccinationType == null)
            {
                throw new InvalidOperationException("Cannot find transaction type 'Vaccination'");
            }

            // Return value
            ItemTransaction retVal = null;

            // Iterate through lots
            for (int i = 0; i < lots.Count; i++)
            {
                var lot = lots[i];

                // Get balance
                HealthFacilityBalance balance = this.GetCurrentBalance(facility, lot.Gtin, lot.LotNumber);
                //if (balance.Balance < 1)
                //    throw new InvalidOperationException("Insufficient doses to register vaccination event");

                // Create a transaction
#if XAMARIN
#else
#endif
                ItemTransaction itl = new ItemTransaction()
                {
                    Gtin                    = lot.Gtin,
                    GtinLot                 = lot.LotNumber,
                    HealthFacilityCode      = facility.Code,
                    ModifiedBy              = vaccination.ModifiedBy,
                    ModifiedOn              = vaccination.ModifiedOn,
                    RefIdNum                = vaccination.Id,
                    TransactionDate         = vaccination.VaccinationDate,
                    TransactionQtyInBaseUom = -1,
                    TransactionTypeId       = vaccinationType.Id
                };
                if (String.IsNullOrEmpty(vaccination.VaccineLot))
                {
                    vaccination.VaccineLotId = lot.Id;
                    VaccinationEvent.Update(vaccination);
                }

                // Update facility balances
                balance.Balance -= 1;
                balance.Used    += 1;

                // Now save
                HealthFacilityBalance.Update(balance);
                itl.Id = ItemTransaction.Insert(itl);

                if (retVal == null)
                {
                    retVal = itl;
                }

                // Linked or kitted items
                var lotGtinItem = ItemManufacturer.GetItemManufacturerByGtin(lot.Gtin);
                foreach (var im in lotGtinItem.KitItems)
                {
                    lots.Add(new OrderManagementLogic().GetOldestLot(facility, im.Gtin));
                }
            }

            return(retVal);
        }
Esempio n. 20
0
    protected void btnEdit_Click(object sender, EventArgs e)
    {
        try
        {
            if (Page.IsValid)
            {
                int    id  = -1;
                string _id = Request.QueryString["id"];
                if (String.IsNullOrEmpty(_id))
                {
                    if (HttpContext.Current.Session["_lastChildId"] != null)
                    {
                        id = (int)HttpContext.Current.Session["_lastChildId"];
                    }
                }
                else
                {
                    int.TryParse(_id, out id);
                }
                int userId = CurrentEnvironment.LoggedUser.Id;

                birthplaceId = ddlBirthplace.SelectedValue;
                if (birthplaceId == null || Birthplace.GetBirthplaceById(int.Parse(birthplaceId)) == null)
                {
                    if (spanBirthplaceId.Visible == true)
                    {
                        revBirthplace.Visible = true;
                        return;
                    }
                }
                if (domicileId == null || Place.GetPlaceById(int.Parse(domicileId)) == null)
                {
                    if (spanDomicileId.Visible == true)
                    {
                        revDomicile.Visible = true;
                        return;
                    }
                }
                if (communityId == null || Community.GetCommunityById(int.Parse(communityId)) == null)
                {
                    if (spanCommunityId.Visible == true)
                    {
                        revCommunity.Visible = true;
                        return;
                    }
                }
                if (healthFacilityId == null || HealthFacility.GetHealthFacilityById(int.Parse(healthFacilityId)) == null)
                {
                    revHealthcenter.Visible = true;
                    return;
                }

                Child o = Child.GetChildById(id);

                o.Firstname1 = txtFirstname1.Text.Trim();
                o.Firstname2 = txtFirstname2.Text.Trim();
                o.Lastname1  = txtLastname1.Text.Trim();
                //o.Lastname2 = txtLastname2.Text.Replace("'", @"''");

                DateTime date     = DateTime.ParseExact(txtBirthdate.Text, ConfigurationDate.GetConfigurationDateById(int.Parse(Configuration.GetConfigurationByName("DateFormat").Value)).DateFormat.ToString(), CultureInfo.CurrentCulture);
                int      datediff = Int32.MaxValue;
                if (o.Birthdate != date)
                {
                    if (o.Birthdate.Year != date.Year)
                    {
                        datediff = date.Subtract(o.Birthdate).Days;
                    }
                    else
                    {
                        datediff = date.Subtract(o.Birthdate).Days;
                    }
                }
                o.Birthdate = date;

                o.Gender = bool.Parse(rblGender.SelectedValue);

                int healthcenter = 0;
                if (o.HealthcenterId != int.Parse(healthFacilityId))
                {
                    healthcenter = int.Parse(healthFacilityId);
                }
                o.HealthcenterId = int.Parse(healthFacilityId);

                if (birthplaceId != null && birthplaceId != "0" && birthplaceId != "-1")
                {
                    o.BirthplaceId = int.Parse(birthplaceId);
                }
                else
                {
                    o.BirthplaceId = null;
                }
                if (communityId != null && communityId != "0")
                {
                    o.CommunityId = int.Parse(communityId);
                }
                else
                {
                    o.CommunityId = null;
                }
                if (domicileId != null && domicileId != "0")
                {
                    o.DomicileId = int.Parse(domicileId);
                }
                else
                {
                    o.DomicileId = null;
                }
                o.StatusId = int.Parse(ddlStatus.SelectedValue);
                bool appstatus = true;
                if (o.StatusId != 1) //== 2 || o.StatusId == 3 || o.StatusId == 4 )
                {
                    appstatus = false;
                }
                if (!String.IsNullOrEmpty(txtAddress.Text))
                {
                    o.Address = txtAddress.Text;
                }
                if (!String.IsNullOrEmpty(txtPhone.Text))
                {
                    o.Phone = txtPhone.Text;
                }
                //  o.Mobile = txtMobile.Text;
                //o.Email = txtEmail.Text.Replace("'", @"''");
                //  o.MotherId = txtMotherId.Text.Replace("'", @"''");
                if (!String.IsNullOrEmpty(txtMotherFirstname.Text))
                {
                    o.MotherFirstname = txtMotherFirstname.Text;
                }
                if (!String.IsNullOrEmpty(txtMotherLastname.Text))
                {
                    o.MotherLastname = txtMotherLastname.Text;
                }
                //o.FatherId = txtFatherId.Text.Replace("'", @"''");
                //o.FatherFirstname = txtFatherFirstname.Text.Replace("'", @"''");
                //o.FatherLastname = txtFatherLastname.Text.Replace("'", @"''");
                //o.CaretakerId = txtCaretakerId.Text.Replace("'", @"''");
                //o.CaretakerFirstname = txtCaretakerFirstname.Text.Replace("'", @"''");
                //o.CaretakerLastname = txtCaretakerLastname.Text.Replace("'", @"''");
                o.Notes      = txtNotes.Text.Replace("'", @"''");
                o.IsActive   = true; // bool.Parse(rblIsActive.SelectedValue);
                o.ModifiedOn = DateTime.Now;
                o.ModifiedBy = userId;
                if (!String.IsNullOrEmpty(txtIdentificationNo1.Text))
                {
                    o.IdentificationNo1 = txtIdentificationNo1.Text;
                }
                if (!String.IsNullOrEmpty(txtIdentificationNo2.Text))
                {
                    o.IdentificationNo2 = txtIdentificationNo2.Text;
                }
                if (!String.IsNullOrEmpty(txtIdentificationNo3.Text))
                {
                    o.IdentificationNo3 = txtIdentificationNo3.Text;
                }
                if (!String.IsNullOrEmpty(txtBarcodeId.Text))
                {
                    o.BarcodeId = txtBarcodeId.Text.Trim();
                    if (Child.GetChildByBarcode(o.BarcodeId) != null && Child.GetChildByBarcode(o.BarcodeId).Id != id)
                    {
                        lblWarningBarcode.Visible = true;
                        return;
                    }
                }
                if (!String.IsNullOrEmpty(txtTempId.Text))
                {
                    o.TempId = txtTempId.Text.Trim();
                }

                int i = Child.Update(o);

                if (i > 0)
                {
                    List <VaccinationAppointment> applist    = VaccinationAppointment.GetVaccinationAppointmentsByChildNotModified(id);
                    List <VaccinationAppointment> applistall = VaccinationAppointment.GetVaccinationAppointmentsByChild(id);
                    if (!appstatus)
                    {
                        foreach (VaccinationAppointment app in applist)
                        {
                            VaccinationAppointment.Update(appstatus, app.Id);
                        }
                    }

                    if (healthcenter != 0)
                    {
                        foreach (VaccinationAppointment app in applist)
                        {
                            VaccinationAppointment.Update(o.HealthcenterId, app.Id);
                            VaccinationEvent.Update(app.Id, o.HealthcenterId);
                        }
                    }
                    if (datediff != Int32.MaxValue)
                    {
                        bool done = false;
                        foreach (VaccinationAppointment app in applistall)
                        {
                            VaccinationEvent ve = VaccinationEvent.GetVaccinationEventByAppointmentId(app.Id)[0];
                            if (ve.VaccinationStatus || ve.NonvaccinationReasonId != 0)
                            {
                                done = true;
                                break;
                            }
                        }

                        foreach (VaccinationAppointment app in applist)
                        {
                            if (done)
                            {
                                break;
                            }
                            VaccinationAppointment.Update(app.ScheduledDate.AddDays(datediff), app.Id);
                            VaccinationEvent.Update(app.Id, app.ScheduledDate.AddDays(datediff));
                        }
                    }
                    HttpContext.Current.Session["_successUpdateChild"] = "1";

                    lblSuccess.Visible = true;
                    lblWarning.Visible = false;
                    lblError.Visible   = false;
                    gvVaccinationEvent.DataBind();
                }
                else
                {
                    lblSuccess.Visible = false;
                    lblWarning.Visible = false;
                    lblError.Visible   = true;
                }
            }
        }
        catch (Exception ex)
        {
            lblSuccess.Visible = false;
            lblWarning.Visible = false;
            lblError.Visible   = true;
        }
    }