示例#1
0
        private void buttonSolve_Click(object sender, EventArgs e)
        {
            StringBuilder errorMessage = new StringBuilder();

            // 对模型进行检查,看是否可以进行计算
            if (Model.Validate(ref errorMessage))
            {
                _Solver = new AnsysSolver(
                    workingDir: WorkingDir,
                    solverGui: Options.SolverGUI
                    );

                // 检查计算环境,文件配置
                if (_Solver.SetEnvironment(Model, ref errorMessage))
                {
                    // 求解计算
                    _bcParameters = new BgwParameters()
                    {
                        Solver       = _Solver,
                        ErrorMessage = errorMessage.ToString(),
                    };
                    //
                    progressBar1.Visible = true;
                    progressBar1.Style   = ProgressBarStyle.Marquee;

                    if (_bgw_Solver.IsBusy != true)
                    {
                        //
                        OnSdCalculationStart();
                        // Start the asynchronous operation.
                        _bgw_Solver.RunWorkerAsync(argument: _bcParameters);
                    }
                }
            }
        }
示例#2
0
        private async void BtnGuardar_Click(object sender, EventArgs e)
        {
            try
            {
                this.CleanErrors(errorProvider1, typeof(CancelacionVentaViewModel));
                var validationResults = Model.Validate();
                validationResults.ToString();
                if (validationResults.IsValid)
                {
                    VentasCancelaciones x = await Model.GuardarCancelacion(CurrentSession.IdCuentaUsuario);

                    if (x.Resultado == 1)
                    {
                        CIDMessageBox.ShowAlert(Messages.SystemName, Messages.SuccessMessage, TypeMessage.correcto);
                        LimpiarDatos();
                    }
                    else
                    {
                        CIDMessageBox.ShowAlert(Messages.SystemName, Messages.ErrorDeleteMessage, TypeMessage.error);
                    }
                }
                else
                {
                    this.ShowErrors(errorProvider1, typeof(CancelacionVentaViewModel), validationResults);
                }
            }
            catch (Exception ex)
            {
                ErrorLogHelper.AddExcFileTxt(ex, "FrmCancelacion() ~ BtnGuardar_Click(object sender, EventArgs e)");
                CIDMessageBox.ShowAlert(Messages.SystemName, Messages.ErrorFormulario, TypeMessage.error);
            }
        }
示例#3
0
 private void btnAgregar_Click(object sender, EventArgs e)
 {
     try
     {
         //flpBotonesGroup.Enabled = false;
         this.CleanErrors(errorProvider1, typeof(DireccionesClienteViewModel));
         var validaciones = Model.Validate();
         if (validaciones.IsValid)
         {
             var itemEstado    = ObtenerEstadoSeleccionado();
             var itemMunicipio = ObtenerMunicipioSeleccionado();
             Model.NombreEstado    = itemEstado.Descripcion;
             Model.NombreMunicipio = itemMunicipio.Descripcion;
             Model.Agregar();
             LimpiarPropiedades();
         }
         else
         {
             this.ShowErrors(errorProvider1, typeof(DireccionesClienteViewModel), validaciones);
         }
     }
     catch (Exception ex)
     {
         ErrorLogHelper.AddExcFileTxt(ex, "FrmDireccionesCliente ~ btnAgregar_Click(object sender, EventArgs e)");
         CIDMessageBox.ShowAlert(Messages.SystemName, Messages.ErrorMessage, TypeMessage.error);
     }
     finally
     {
         //flpBotonesGroup.Enabled = true;
     }
 }
        private void OnSaveNewAddress()
        {
            Model.Validate();
            if (Model.HasErrors)
            {
                return;
            }

            SelectedAddress.Validate();
            if (SelectedAddress.HasErrors)
            {
                return;
            }

            ShowAddressPopup = Visibility.Collapsed;

            if (Model.Addresses == null)
            {
                Model.Addresses = new List <MedicalPracticeAddress>();
            }

            if (IsEditingAddress)
            {
                IsEditingAddress = false;
                return;
            }

            Model.Addresses.Add(SelectedAddress);

            var tempAddresses = Model.Addresses;

            Model.Addresses = new List <MedicalPracticeAddress>();
            Model.Addresses = tempAddresses;
        }
        /// <summary>
        /// Validate Model Object Foe Errors
        /// </summary>
        /// <param name="trans"></param>
        /// <returns></returns>
        public String Validate(XbimReadWriteTransaction trans)
        {
            var sw     = new StringWriter();
            var errors = Model.Validate(trans.Modified(), sw);

            return(errors > 0 ? sw.ToString() : null);
        }
示例#6
0
        /// <summary>
        /// Called when [save].
        /// </summary>
        /// <param name="enableNotificantions">if set to <c>true</c> [enable notificantions].</param>
        public virtual void OnSave(bool enableNotificantions = true)
        {
            Model.CleanBeforeSave();
            Model.Validate();

            using (var session = DataServiceProvider.SessionFactory.OpenSession())
            {
                using (var trans = session.BeginTransaction())
                {
                    try
                    {
                        OnSaveInternal(session, Model);

                        trans.Commit();
                        //session.Flush();
                        //
                        if (enableNotificantions)
                        {
                            Notify(string.Format("{0} {1} has been successfully saved.", Model.Name,
                                                 typeof(TEntity).Name));
                        }
                    }
                    catch (Exception exc)
                    {
                        trans.Rollback();
                        NotifyError(exc, typeof(TEntity), Model.Name);

                        //throw;
                    }
                }
            }
        }
示例#7
0
        public bool ValidateModel()
        {
            // Ensure that the model has been created
            EnsureModelCreated();

            // Validate the model and write out validation messages
            int validationErrors = 0;
            var messages         = Model.Validate();

            foreach (var message in messages)
            {
                if (message.MessageType == DacMessageType.Error)
                {
                    validationErrors++;
                }

                Console.WriteLine(message.ToString());
            }

            if (validationErrors > 0)
            {
                _modelValid = false;
                Console.WriteLine($"Found {validationErrors} error(s), skip building package");
            }
            else
            {
                _modelValid = true;
            }

            return(_modelValid.Value);
        }
示例#8
0
    public void OnApplyCommadClicked ()
    {
      if (Model.Validate ()) {
        TDispatcher.Invoke (ApplyDispatcher);
      }

      ApplyChanges ();
    }
示例#9
0
 public override void Validate()
 {
     if (Model != null)
     {
         Model.Validate();
     }
     base.Validate();
 }
        private async void btnReservarCita_Click(object sender, EventArgs e)
        {
            try
            {
                this.CleanErrors(errorProvider1, typeof(CapturaCitaViewModel));
                errorProvider1.Clear();
                btnReservarCita.Enabled = false;
                ObtenerDatos();
                var validationResults = Model.Validate();
                validationResults.ToString();
                if (validationResults.IsValid)
                {
                    int res   = 0;
                    var Resul = await Model.GuardarCambios(CurrentSession.IdCuentaUsuario, CurrentSession.IdSucursal);

                    res = Resul.Resultado;
                    if (res == 1)
                    {
                        CIDMessageBox.ShowAlert(Messages.SystemName, Messages.SuccessMessage, TypeMessage.correcto);
                        await Model.GetCitaDetalle(f, CurrentSession.IdSucursal);

                        HorarioSucursal();
                        Model.Servicio = string.Empty;
                        await ServiciosPaquete(Model.IdOrdenPaquete);

                        if (Model.ListaServicioPaquete.Count == 1)
                        {
                            LimpiarPropiedades();
                            groupBoxCita.Enabled = false;
                        }
                        if (Model.State == EntityState.Update)
                        {
                            LimpiarPropiedades();
                            groupBoxCita.Enabled = false;
                        }
                        // IdServicioControl_SelectionChangeCommitted(IdServicioControl, e);
                    }
                    else
                    {
                        CIDMessageBox.ShowAlert(Messages.ErrorMessage, "Error", TypeMessage.error);
                    }
                }
                else
                {
                    this.ShowErrors(errorProvider1, typeof(CapturaCitaViewModel), validationResults);
                }
            }
            catch (Exception ex)
            {
                ErrorLogHelper.AddExcFileTxt(ex, "FrmServicioNuevo ~ btnGuardar_Click(object sender, EventArgs e)");
                CIDMessageBox.ShowAlert(Messages.SystemName, Messages.ErrorMessage, TypeMessage.error);
            }
            finally
            {
                btnReservarCita.Enabled = true;
            }
        }
示例#11
0
 private void btnAgregar_Click_1(object sender, EventArgs e)
 {
     try
     {
         errorProvider1.Clear();
         this.CleanErrors(errorProvider1, typeof(PromocionViewModel));
         if (String.IsNullOrEmpty(Model.Nombre))
         {
             errorProvider1.SetError(btnAgregar, "Selecione un producto o servicio");
         }
         else
         {
             if (String.IsNullOrEmpty(Model.NombrePromocion))
             {
                 errorProvider1.SetError(btnAgregar, "Ingrese un nombre de la promoción");
             }
             else
             {
                 var validationResults = Model.Validate();
                 validationResults.ToString();
                 if (validationResults.IsValid)
                 {
                     BindingList <PromocionMxN> ListaPromocionMxN = (BindingList <PromocionMxN>)GridPS.DataSource;
                     if (ListaPromocionMxN.Count > 0)
                     {
                         Model.TablaProducto = ObtenerTablaProducto(ListaPromocionMxN);
                         Model.TablaServicio = ObtenerTablaServicio(ListaPromocionMxN);
                         FrmPromocionDias promocionDias = new FrmPromocionDias(Model);
                         promocionDias.ShowDialog();
                         if (promocionDias.Resultado == 1)
                         {
                             this.Close();
                             Model.Resultado = 1;
                             LimpiarPropiedades();
                         }
                     }
                     else
                     {
                         errorProvider1.SetError(btnAgregar, "Seleccione al menos un articulo.");
                     }
                 }
                 else
                 {
                     this.ShowErrors(errorProvider1, typeof(PromocionViewModel), validationResults);
                 }
             }
         }
     }
     catch (Exception ex)
     {
         ErrorLogHelper.AddExcFileTxt(ex, "FrmPromocionMxN ~ btnAgregar_Click_1(object sender, EventArgs e)");
         CIDMessageBox.ShowAlert(Messages.SystemName, Messages.ErrorMessage, TypeMessage.error);
     }
 }
示例#12
0
 public bool ValidateUser()
 {
     if (View.SelectedUser != null && View.SelectedUser.Id > 0)
     {
         return(Model.Validate(View.UserName, View.SelectedUser.Id));
     }
     else
     {
         return(Model.Validate(View.UserName));
     }
 }
示例#13
0
 /// <summary>
 /// Inserts Person to DB
 /// </summary>
 /// <exception cref="ArgumentException">Throw if object is null or not valid</exception>
 /// <param name="person">Person to insert</param>
 public void Insert(Model.Person person)
 {
     if (person != null && person.Validate())
     {
         InsertPerson((Mock.PhoneBook.Person)person);
         InsertPhone((Mock.PhoneBook.Phone)person);
         InsertAddress((Mock.PhoneBook.Address)person);
     }
     else
         throw new ArgumentException("Object is not valid");
 }
示例#14
0
        public void ModelSanityNotSafe()
        {
            Model = new Common.Swagger12.Model(false);

            Assert.IsNull(Model.Description);
            Assert.IsNotNull(Model.Properties);
            Assert.IsNull(Model.SubTypes);
            Assert.IsNull(Model.Required);

            Model.Validate(Violations);
            Assert.AreEqual(0, Violations.Count);
        }
示例#15
0
        private async void btnAgregar_Click_1(object sender, EventArgs e)
        {
            try
            {
                int resultado = 0;
                this.CleanErrors(errorProvider1, typeof(PromocionViewModel));
                var validationResults = Model.Validate();
                validationResults.ToString();
                if (validationResults.IsValid)
                {
                    if (Model.IdTipoPromocion == 1)
                    {
                        PromocionDescuento promocionDescuento = await Model.GuardarPromocionDescuento(CurrentSession.IdCuentaUsuario);

                        resultado = promocionDescuento.Promocion.Resultado;
                    }
                    else if (Model.IdTipoPromocion == 2)
                    {
                        PromocionNxN promocionNxN = await Model.GuardarPromocionNxN(CurrentSession.IdCuentaUsuario);

                        resultado = promocionNxN.Promocion.Resultado;
                    }
                    else if (Model.IdTipoPromocion == 3)
                    {
                        PromocionMxN promocionMxN = await Model.GuardarPromocionMxN(CurrentSession.IdCuentaUsuario);

                        resultado = promocionMxN.Promocion.Resultado;
                    }

                    if (resultado == 1)
                    {
                        CIDMessageBox.ShowAlert(Messages.SystemName, Messages.SuccessMessage, TypeMessage.correcto);
                        this.Close();
                        Resultado = 1;
                    }
                    else
                    {
                        CIDMessageBox.ShowAlert(Messages.ErrorMessage, "Desconocido", TypeMessage.error);
                    }
                }
                else
                {
                    this.ShowErrors(errorProvider1, typeof(PromocionViewModel), validationResults);
                }
            }
            catch (Exception ex)
            {
                ErrorLogHelper.AddExcFileTxt(ex, "FrmPromocionDias ~ btnAgregar_Click_1(object sender, EventArgs e)");
                CIDMessageBox.ShowAlert(Messages.SystemName, Messages.ErrorMessage, TypeMessage.error);
            }
        }
示例#16
0
        private async void BtnNuevaEncuesta_Click(object sender, EventArgs e)
        {
            try
            {
                this.btnNuevaEncuesta.Enabled = false;

                Model.ListaPregunta.ToList().ForEach(x => x.Orden = Model.ListaPregunta.IndexOf(x));
                this.CleanErrors(errorProvider1, typeof(EncuestasViewModel));
                var validationResults = Model.Validate();
                validationResults.ToString();

                if (validationResults.IsValid)
                {
                    Model.TblPregunta  = ObtenerTablaPreguntas(Model.ListaPregunta.ToList());
                    Model.TblRespuesta = ObtenerTablaRepuestas(Model.ListaRespuesta.ToList());

                    if (this.Model.ListaPregunta.Count > 0)
                    {
                        int x = await Model.GuardarEncuesta(CurrentSession.IdCuentaUsuario);

                        if (x == 1)
                        {
                            CIDMessageBox.ShowAlert(Messages.SystemName, Messages.SuccessMessage, TypeMessage.informacion);
                            this.Close();
                        }
                        else
                        {
                            CIDMessageBox.ShowAlert(Messages.SystemName, Messages.ErrorMessage, TypeMessage.error);
                        }
                    }
                    else
                    {
                        CIDMessageBox.ShowAlert(Messages.SystemName, "LA ENCUESTA DEBE CONTENER AL MENOS UNA PREGUNTA", TypeMessage.informacion);
                    }
                }
                else
                {
                    this.ShowErrors(errorProvider1, typeof(EncuestasViewModel), validationResults);
                }
            }
            catch (Exception ex)
            {
                ErrorLogHelper.AddExcFileTxt(ex, "FrmNuevaEncuesta ~ BtnNuevaEncuesta_Click(object sender, EventArgs e)");
                CIDMessageBox.ShowAlert(Messages.SystemName, Messages.ErrorMessage, TypeMessage.error);
            }
            finally
            {
                this.btnNuevaEncuesta.Enabled = true;
            }
        }
示例#17
0
        /// <summary>
        /// Validate Model Object Foe Errors
        /// </summary>
        /// <param name="trans"></param>
        /// <returns></returns>
        public String Validate(XbimReadWriteTransaction trans)
        {
            StringWriter sw     = new StringWriter();
            int          errors = Model.Validate(trans.Modified(), sw);

            if (errors > 0)
            {
                return(sw.ToString());
            }
            else
            {
                return(null);
            }
        }
 public ChangePasswordWindowVM()
 {
     ValidateCommand.Subscribe(o =>
     {
         if (Model.Validate(CurrentUser, CurrentPassword) && NewPassword == NewRepeatPassword)
         {
             Model.Update(CurrentUser, NewPassword);
             Model.Save();
             Model.Load();
             Notification = "Пароль обновлён";
         }
         else
         {
             Notification = "Неверный пароль";
         }
     });
 }
示例#19
0
 private void btnAgregar_Click(object sender, EventArgs e)
 {
     try
     {
         errorProvider1.Clear();
         this.CleanErrors(errorProvider1, typeof(PromocionViewModel));
         if (String.IsNullOrEmpty(Model.Nombre))
         {
             errorProvider1.SetError(btnAgregar, "Selecione un producto o servicio");
         }
         else
         {
             if (String.IsNullOrEmpty(Model.NombrePromocion))
             {
                 errorProvider1.SetError(btnAgregar, "Ingrese un nombre de la promoción");
             }
             else
             {
                 var validationResults = Model.Validate();
                 validationResults.ToString();
                 if (validationResults.IsValid)
                 {
                     FrmPromocionDias dias = new FrmPromocionDias(Model);
                     dias.ShowDialog();
                     if (dias.Resultado == 1)
                     {
                         this.Close();
                         Model.Resultado = 1;
                         LimpiarPropiedades();
                     }
                 }
                 else
                 {
                     this.ShowErrors(errorProvider1, typeof(PromocionViewModel), validationResults);
                 }
             }
         }
     }
     catch (Exception ex)
     {
         ErrorLogHelper.AddExcFileTxt(ex, "FrmPromocionDias ~ btnAgregar_Click_1(object sender, EventArgs e)");
         CIDMessageBox.ShowAlert(Messages.SystemName, Messages.ErrorMessage, TypeMessage.error);
     }
 }
示例#20
0
        private async void btnGuardar_Click(object sender, EventArgs e)
        {
            try
            {
                btnGuardar.Enabled = false;
                errorProvider1.Clear();
                BindingList <EntradaSalidaAlmacen> ListaProductos = (BindingList <EntradaSalidaAlmacen>)dataGridsf1.DataSource;
                this.CleanErrors(errorProvider1, typeof(EntradaSalidaAlmacenViewModel));
                var validationResults = Model.Validate();
                validationResults.ToString();

                if (validationResults.IsValid)
                {
                    if (ListaProductos.Count > 0)
                    {
                        Model.TablaEntradaAlmacen = ObtenerEntradaSalidaProducto(ListaProductos);
                        EntradaSalidaAlmacen Resultado = await Model.GuardarEntradaSalida(CurrentSession.IdCuentaUsuario);

                        if (Resultado.Resultado == 1)
                        {
                            CIDMessageBox.ShowAlert(Messages.SystemName, Messages.SuccessMessage, TypeMessage.correcto);
                            LimpiarPropiedades();
                        }
                    }
                    else
                    {
                        errorProvider1.SetError(FolioProductoControl, "Seleccione al menos un articulo.");
                    }
                }
                else
                {
                    this.ShowErrors(errorProvider1, typeof(EntradaSalidaAlmacenViewModel), validationResults);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                btnGuardar.Enabled = true;
            }
        }
        public async void ChangePassword()
        {
            Model.UserId = AuthManager.User.Id;

            var validationResult = Model.Validate(ConfirmPassword);

            if (validationResult.Successful)
            {
                if ((await PerformNetworkOperation(SendResetPassword)).Successful)
                {
                    await Popups.ShowAsync(ClientResources.ChangePassword_Success);

                    await ViewModelNavigation.GoBackAsync();
                }
            }
            else
            {
                await ShowServerErrorMessageAsync(validationResult);
            }
        }
        private static async Task ValidateDataFields(Product product)
        {
            try
            {
                Name.Validate(product.Name);
                Description.Valdiate(product.Description);
                await ProductDataFields.Category.Validate(product.Category);

                await ProductDataFields.Brand.Validate(product.Brand);

                Model.Validate(product.Model);
                Color.Validate(product.Color);
                Warranty.Validate(product.Warranty);
                Pictures.Validate(product.PicturesUrls);
                Condition.Validate(product.Condition);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        private void SubmitExecute()
        {
            ValidationResult validationResult = Model.Validate();

            if (!validationResult.IsValid)
            {
                Billboard.ShowMessage(Infra.Wpf.Controls.MessageType.Error, validationResult.Errors[0].ErrorMessage);
                FocusByPropertyName(validationResult.Errors[0].PropertyName);
                return;
            }

            BusinessResult <bool> result;

            if (isEdit)
            {
                result = businessSet.Update(Model);
            }
            else
            {
                result = businessSet.Add(Model);
            }

            if (result.HasException == false && result.IsOnBeforExecute)
            {
                BusinessResult <int> saveResult = accountingUow.SaveChange();
                if (saveResult.HasException)
                {
                    result.Message = saveResult.Message;
                }
                else
                {
                    NavigationService.GoBack();
                    Messenger.Default.Send(Model.PersonId, "PersonListView_SaveItemId");
                }
            }

            Billboard.ShowMessage(result.Message.MessageType, result.Message.Message);
        }
示例#24
0
        private void BtnNuevaConsulta_Click(object sender, EventArgs e)
        {
            try
            {
                errorProvider1.Clear();
                var validationResults = Model.Validate();
                if (validationResults.IsValid)
                {
                    _tablaMedicion = ObtenerTablaMediciones();

                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
                else
                {
                    DibujarErrores(validationResults);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public override async void OnSave(bool enableNotificantions = false)
        {
            if (string.IsNullOrEmpty(Model.Name) || string.IsNullOrEmpty(Model.GroupPracticePacId))
            {
                MessageBox.Show("Orginization Name and Group Id fields are required", "Invalid Input");
                return;
            }

            int num;

            if (int.TryParse(NumberOfMembers, out num))
            {
                Model.NumberofGroupPracticeMembers = num;
            }
            else if (!string.IsNullOrEmpty(NumberOfMembers))
            {
                MessageBox.Show("Please enter a valid number for Group Practice Members", "Invalid Input");
                return;
            }

            Validate();
            Model.Validate();
            Model.Addresses.ForEach(a => a.Validate());

            if (HasErrors || Model.HasErrors || Model.Addresses.Any(a => a.HasErrors))
            {
                return;
            }

            try
            {
                using (var session = DataServiceProvider.SessionFactory.OpenStatelessSession())
                {
                    if (session.Query <MedicalPractice>().FirstOrDefault(x => x.Id != Model.Id && x.GroupPracticePacId == Model.GroupPracticePacId) != null)
                    {
                        MessageBox.Show("There is already a medical practice with the same Group Practice Pac Id. Group Practice Pac Id must be unique.", "Notification");
                        return;
                    }
                }

                Model.IsEdited = true;

                var       errorOccurred   = false;
                Exception errorException  = null;
                var       progressService = new ProgressService();

                progressService.SetProgress("Saving " + Inflector.Titleize2(typeof(MedicalPractice).Name), 0, false, true);

                // await Task.Delay(500);

                var operationComplete = await progressService.Execute(() => OnSave(Model),
                                                                      result =>
                {
                    if (!result.Status && result.Exception != null)
                    {
                        errorOccurred  = true;
                        errorException = result.Exception;
                    }
                    else
                    {
                        errorOccurred  = false;
                        errorException = null;
                    }
                },
                                                                      new CancellationToken());

                if (operationComplete)
                {
                    progressService.SetProgress("Completed", 100, true, false);

                    if (!errorOccurred || errorException == null)
                    {
                        EventAggregator.GetEvent <GenericNotificationEvent>()
                        .Publish(string.Format("MedicalPractice {0} has been saved successfully.", Model.Name));
                        EventAggregator.GetEvent <RequestLoadMappingTabEvent>().Publish(typeof(MedicalPracticeEditViewModel));
                        NavigateBack();
                    }
                    else
                    {
                        Logger.Write(errorException, "Error saving Medical Practice \"{0}\"", Model.Name);
                    }
                }
            }
            catch (Exception exc)
            {
                Logger.Write(exc, "Error saving Medical Practice \"{0}\"", Model.Name);
            }
        }
示例#26
0
        private async void btnGuardar_Click(object sender, EventArgs e)
        {
            try
            {
                btnGuardar.Enabled = false;
                this.CleanErrors(errorProvider1, typeof(ServicioViewModel));
                var validationResults = Model.Validate();
                validationResults.ToString();

                if (validationResults.IsValid)
                {
                    if (Model.UpdateImagen || (ClaveAux != Model.Clave && ClaveAux != null))//SI se cambia la clave o la imagen se sube la imagen
                    {
                        bool subir = false;
                        CIDWait.Show(async() =>
                        {
                            //Subimos la imagen al Servidor FTP
                            subir = await Model.UploadFTP(Model.RutaImagen,
                                                          ConfigurationManager.AppSettings.Get("ServerFtpTxt") + @"/imgServicios/" + Model.Clave + Model.Extencion,
                                                          ConfigurationManager.AppSettings.Get("UsuarioFtpTxt"),
                                                          ConfigurationManager.AppSettings.Get("ContraseñaFtpTxt"));
                        }, "Espere");

                        if (!subir)
                        {
                            //Mensaje de avertencia que la imagen no se pudo cargar
                            CIDMessageBox.ShowAlert(Messages.SystemName, "NO SE PUDO SUBIR LA IMAGEN", TypeMessage.informacion);
                        }
                    }
                    Model.UpdateImagen = false;
                    var      aux     = Model.Duracion;
                    var      otroAux = DuracionControl.Value;
                    Servicio Resul   = await Model.GuardarCambios(CurrentSession.IdCuentaUsuario);

                    if (Resul.Resultado == 1)
                    {
                        if (Model.RutaAux != "" && Model.RutaAux != null)
                        {
                            File.Delete(Model.RutaAux);//Borramos la imagen desde la carpeta RESOURCES
                        }
                        CIDMessageBox.ShowAlert(Messages.SystemName, Messages.SuccessMessage, TypeMessage.correcto);
                        LimpiarPropiedades();
                        //await Model.GetAllAsync();
                        this.Close();
                    }
                    else
                    {
                        CIDMessageBox.ShowAlert(Messages.ErrorMessage, "Error", TypeMessage.error);
                    }
                }
                else
                {
                    this.ShowErrors(errorProvider1, typeof(ServicioViewModel), validationResults);
                }
            }
            catch (Exception ex)
            {
                ErrorLogHelper.AddExcFileTxt(ex, "FrmServicioNuevo ~ btnGuardar_Click(object sender, EventArgs e)");
                CIDMessageBox.ShowAlert(Messages.SystemName, Messages.ErrorMessage, TypeMessage.error);
            }
            finally
            {
                btnGuardar.Enabled = true;
            }
        }
        /// <summary>
        /// Called when [save].
        /// </summary>
        /// <param name="enableNotificantions">if set to <c>true</c> [enable notificantions].</param>
        public override async void OnSave(bool enableNotificantions = true)
        {
            Validate();
            Model.Validate();

            if (HasErrors || Model.HasErrors)
            {
                return;
            }

            //TODO: uncomment this code for npi uniqueness validation
            //if (!IsNpiUnique())
            //{
            //    var result = MessageBox.Show("There is already a physician with the same NPI. NPI must be unique.", "Notification");
            //    return;
            //}

            if (!ValidateAddresses())
            {
                if (MessageBox.Show(string.Format("A location/address nor a medical practice with a defined locations/addresses has not been associated with physician \"{1}\".{0}Please press Cancel and go to the \"Hospital Affliation and Locations\" tab{0}to associate a location/address or medical practice with this physician \"{1}\".{0}If proceeding to save the physician \"{1}\" with out associating a location or a medical practice,{0}this physician may not appear in your published website.", Environment.NewLine, Model.Name), "Physical Details Validation", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
                {
                    return;
                }
            }

            try
            {
                var       errorOccurred   = false;
                Exception errorException  = null;
                var       progressService = new ProgressService();

                progressService.SetProgress("Saving physician", 0, false, true);

                //await Task.Delay(500);

                GenderEnum val;
                if (Enum.TryParse(SelectedGender, true, out val))
                {
                    Model.Gender = val;
                }
                if (SelectedMedicalAssignement != null && !string.IsNullOrEmpty(SelectedMedicalAssignement.EnumName))
                {
                    Model.AcceptsMedicareAssignment =
                        EnumExtensions.GetEnumValueFromString <db.MedicalAssignmentEnum>(
                            SelectedMedicalAssignement.EnumName);
                }

                Model.ForeignLanguages = new List <string>();
                if (!string.IsNullOrEmpty(Languages))
                {
                    Languages.Split(',').ToList().ForEach(x => Model.ForeignLanguages.Add(x));
                }

                Model.AffiliatedHospitals.Clear();
                Hospitals.ToList().ForEach(x => Model.AffiliatedHospitals.Add(new db.PhysicianAffiliatedHospital
                {
                    HospitalCmsProviderId = GetCmsProviderId(x)
                }));

                //	DeletedPhysicianAddressList was acting as an omni buffer for both Physician and MedicalPractice addresses.
                //	This is going to change for a buffer for both Physician and 'Associated' MedicalPractice addresses.
                //	Scrap This:  If the address.MedicalPractice name is null, delete from Physician Addresses; else delete from MPAssociated Addresses
                //	Scrap This:  Current logic is fine.  It deletes from both list in either case.  Since a single Address(Id) object cannot be both
                //				 Physician and MedicalPractice, there is no issue.
                foreach (var address in DeletedPhysicianAddressList)
                {
                    var physicianaAd = Model.Addresses != null
                        ? Model.Addresses.FirstOrDefault(x => x.Id == address.Id)
                        : null;

                    if (physicianaAd != null)
                    {
                        Model.Addresses.Remove(physicianaAd);
                    }

                    Model.PhysicianMedicalPractices.ToList().ForEach(pmp =>
                    {
                        if (pmp.AssociatedPMPAddresses.Contains(address.Id))
                        {
                            pmp.AssociatedPMPAddresses.Remove(address.Id);
                        }
                    });
                    Model.PhysicianMedicalPractices.ToList().RemoveAll(pmp => pmp.AssociatedPMPAddresses.Count == 0);

                    //	var medAddress = address as Monahrq.Infrastructure.Domain.Physicians.MedicalPracticeAddress;
                    //	if (medAddress != null)
                    //	{
                    //		var currentPMP = Model.PhysicianMedicalPractices.Where(pmp => pmp.MedicalPractice.Id == medAddress.MedicalPractice.Id).Single();
                    //		currentPMP.AssociatedPMPAddresses.Remove(address.Id);
                    //		if (currentPMP.AssociatedPMPAddresses.Count == 0)
                    //			Model.PhysicianMedicalPractices.Remove(currentPMP);
                    //	}
                }


                if (Model.States == null)
                {
                    Model.States = new List <string>();
                }

                if (Model.Addresses == null)
                {
                    Model.Addresses = new List <db.PhysicianAddress>();
                }

                if (Model.Addresses.Any() ||
                    Model.PhysicianMedicalPractices.Any(pmp => pmp.MedicalPractice.Addresses.Any()))
                {
                    Model.States.Clear();
                }

                if (Model.Addresses != null && Model.Addresses.Any())
                {
                    Model.Addresses.DistinctBy(x => x.State).Select(x => x.State).ToList().ForEach(add =>
                    {
                        if (!Model.States.Contains(add))
                        {
                            Model.States.Add(add);
                        }
                    });
                }
                if (Model.PhysicianMedicalPractices.Any(pmp => pmp.MedicalPractice.Addresses.Any()))
                {
                    Model.PhysicianMedicalPractices.Select(pmp => pmp.MedicalPractice).ToList()
                    .ForEach(mp => mp.Addresses.DistinctBy(x => x.State)
                             .Select(x => x.State).ToList().ForEach(add =>
                    {
                        if (!Model.States.Contains(add))
                        {
                            Model.States.Add(add);
                        }
                    }));
                }

                if (!Model.IsPersisted && !Model.States.Any())
                {
                    Model.States.Add(ConfigurationService.HospitalRegion.DefaultStates.OfType <string>().ToList().First());
                }

                if (Model.States != null && Model.States.Any())
                {
                    Model.States = Model.States.OrderBy(state => state).ToList();
                }

                DeletedPhysicianAddressList = new ObservableCollection <Address>();

                var operationComplete = await progressService.Execute(() =>
                {
                    //var configService = ServiceLocator.Current.GetInstance<IConfigurationService>();

                    Model.IsEdited = true;

                    using (var session = DataServiceProvider.SessionFactory.OpenSession())
                    {
                        //using (var trans = session.BeginTransaction())
                        {
                            try
                            {
                                OnSaveInternal(session, Model);

                                //trans.Commit();
                                session.Flush();
                                //
                            }
                            catch (Exception exc)
                            {
                                Logger.Write(exc, "Error saving details for physician \"{0}\"", Model.Name);
                                throw;
                            }
                        }
                    }

                    //base.OnSave(false);
                },
                                                                      opResult =>
                {
                    if (!opResult.Status && opResult.Exception != null)
                    {
                        errorOccurred  = true;
                        errorException = opResult.Exception;
                    }
                    else
                    {
                        errorOccurred  = false;
                        errorException = null;
                    }
                }, new CancellationToken());

                if (operationComplete)
                {
                    progressService.SetProgress("Completed", 100, true, false);

                    if (!errorOccurred && errorException == null)
                    {
                        Notify(string.Format("{1} \"{0}\" has been successfully saved.", Model.Name, typeof(db.Physician).Name));
                        NavigateBack();
                    }
                    else
                    {
                        Logger.Write(errorException, "Error saving details for physician \"{0}\"", Model.Name);
                    }
                }
            }
            catch (Exception exc)
            {
                // the error handling in this application is a mess and I don't have enough time to fix it the right way... #sorry
                Logger.Write(exc, "Error saving details for physician \"{0}\"", Model.Name);
            }
        }
        /// <summary>
        /// Called when the implementer has been navigated to.
        /// </summary>
        /// <param name="navigationContext">The navigation context.</param>
        public override void OnNavigatedTo(NavigationContext navigationContext)
        {
            base.OnNavigatedTo(navigationContext);
            ShowAddressPopup = Visibility.Collapsed;
            SearchText       = null;

            var physicianId = (navigationContext.Parameters["PhysicianId"] != null)
                                 ? int.Parse(navigationContext.Parameters["PhysicianId"])
                                 : (int?)null;

            try
            {
                Hospitals = new ObservableCollection <string>();
                DeletedPhysicianAddressList = new ObservableCollection <Address>();
                SelectedTabIndex            = 0;
                if (physicianId.HasValue && physicianId.Value > 0)
                {
                    LoadModel(physicianId);
                    ViewLabel = string.Format("Edit Physician: {0}, {1}", Model.LastName, Model.FirstName);
                }
                else
                {
                    Model     = new db.Physician();
                    ViewLabel = "Add New Physician";
                }

                SelectedMedicalAssignement = MedicalAssignementList.Find(ma => ma.EnumName.Equals(Model.AcceptsMedicareAssignment.ToString()));
                AvailableStates            = BaseDataService.States(state => state.Name != null)
                                             .Where(x => x.Data != null).Select(x => x.Data).ToObservableCollection();
                GenderList              = EnumExtensions.GetEnumStringValues <GenderEnum>();
                SpecialtyList           = GetProviderSpecialties();
                SelectedGender          = Model.Gender.ToString();
                NpiStringValue          = Model.Npi != 0 ? Model.Npi.ToString() : string.Empty;
                HospitalAffiliationList = new ObservableCollection <SelectListItem>();
                if (Model.ForeignLanguages != null)
                {
                    Languages = string.Join(",", Model.ForeignLanguages);
                }
                PropertyChanged       += (o, e) => Validate();
                Model.PropertyChanged += (o, e) => Model.Validate();

                // Correlate Model.*Specialties casing with specialties in DB base data.
                Model.PrimarySpecialty    = SpecialtyList.Find(x => x.EqualsIgnoreCase(Model.PrimarySpecialty));
                Model.SecondarySpecialty1 = SpecialtyList.Find(x => x.EqualsIgnoreCase(Model.SecondarySpecialty1));
                Model.SecondarySpecialty2 = SpecialtyList.Find(x => x.EqualsIgnoreCase(Model.SecondarySpecialty2));
                Model.SecondarySpecialty3 = SpecialtyList.Find(x => x.EqualsIgnoreCase(Model.SecondarySpecialty3));
                Model.SecondarySpecialty4 = SpecialtyList.Find(x => x.EqualsIgnoreCase(Model.SecondarySpecialty4));
                foreach (var pmp in Model.PhysicianMedicalPractices)
                {
                    pmp.MedicalPractice.Addresses.ToList().ForEach(x => x.PropertyChanged += (o, e) => x.Validate());
                }

                var opt1 = new SelectListItem {
                    Text = "Search Medical Practice", Value = "Search Medical Practice"
                };
                var opt2 = new SelectListItem {
                    Text = "Add New Address", Value = "Add New Address"
                };
                opt1.ValueChanged += (sender, args) => { IsSearchingMedicalPractice = opt1.IsSelected; };
                opt2.ValueChanged += (sender, args) => { IsSearchingMedicalPractice = opt1.IsSelected; };
                opt1.IsSelected    = true;
                NewLocationOptions = new List <SelectListItem> {
                    opt1, opt2
                };
                ProcessAddressForDisplay();

                OriginalModelHashCode = GetModelHashCode(Model);
            }
            catch (Exception exec)
            {
                Logger.Write(exec, "Error loading data for physician with ID {0}", physicianId == null ? "unknown" : physicianId.ToString());
                Notify("An error occurred while loading the physician, please restart the app.");
            }
        }
示例#29
0
        internal void Generate(Model model, DirectoryInfo outputDirectory, Log log)
        {
            var validation = model.Validate();

            if (validation.HasErrors)
            {
                log.Error(this, "Model has validation errors.");
                foreach (var error in validation.Errors)
                {
                    log.Error(this, error);
                }

                return;
            }

            try
            {
                TemplateGroup templateGroup = new TemplateGroupFile(this.fileInfo.FullName, '$', '$')
                {
                    ErrorManager = new ErrorManager(new LogAdapter(log)),
                };
                templateGroup.RegisterRenderer(typeof(string), new StringRenderer());

                var configurationTemplate = templateGroup.GetInstanceOf(TemplateConfiguration);
                configurationTemplate.Add(ModelKey, model);

                var configurationXml = new XmlDocument();
                configurationXml.LoadXml(configurationTemplate.Render());

                var outputs = new HashSet <string>();

                var location = new Location(outputDirectory);
                foreach (XmlElement generation in configurationXml.DocumentElement.SelectNodes(GenerationKey))
                {
                    var templateName = generation.GetAttribute(TemplateKey);
                    var template     = templateGroup.GetInstanceOf(templateName);
                    var output       = generation.GetAttribute(OutputKey);

                    var initialOutput = output;
                    for (var i = 2; outputs.Contains(output); i++)
                    {
                        const char separator = '.';
                        var        split     = initialOutput.Split(separator);
                        split[0] = split[0] + "_" + i;
                        output   = string.Join(separator, split);
                    }

                    outputs.Add(output);

                    template.Add(ModelKey, model);

                    if (generation.HasAttribute(InputKey))
                    {
                        var input = generation.GetAttribute(InputKey);
                        switch (input)
                        {
                        case MenuKey:
                            template.Add(MenuKey, model.Menu);
                            break;

                        default:

                            var project = model.Project;

                            if (project.DirectiveById.TryGetValue(input, out var directive))
                            {
                                template.Add(DirectiveKey, directive);
                            }

                            break;
                        }
                    }

                    var result = template.Render();
                    location.Save(output, result);
                }
            }
            catch (Exception e)
            {
                log.Error(this, "Generation error : " + e.Message + "\n" + e.StackTrace);
            }
        }
 public bool ValidateInput()
 {
     return(Model.Validate(View.SelectedUserId, View.SelectedRoleId));
 }
示例#31
0
 public static bool IsValid(this Model model)
 {
     return(!model.Validate().Any());
 }
        /// <summary>
        /// Called when the implementer has been navigated to.
        /// </summary>
        /// <param name="navigationContext">The navigation context.</param>
        public override void OnNavigatedTo(NavigationContext navigationContext)
        {
            base.OnNavigatedTo(navigationContext);

            var configService = ServiceLocator.Current.GetInstance <IConfigurationService>();
            var nursingHomeId = (navigationContext.Parameters["NursingHomeId"] != null)
                                       ? int.Parse(navigationContext.Parameters["NursingHomeId"])
                                       : (int?)null;

            AvailableStates   = Service.GetStates(configService.HospitalRegion.DefaultStates.Cast <string>().ToArray()).ToObservableCollection();
            AvailableCounties = Service.GetCounties(configService.HospitalRegion.DefaultStates.Cast <string>().ToArray()).ToObservableCollection();
            CmsCollection     = LoadCmsCollection();

            if (nursingHomeId.HasValue && nursingHomeId.Value > 0)
            {
                LoadModel(nursingHomeId);
                ViewLabel = string.Format("Edit Nursing Home: {0}", Model.Name);
            }
            else
            {
                ViewLabel = "Add New Nursing Home";
                Model     = new NursingHome();
            }

            IsProviderIdNew     = false;
            DateApproved        = Model.ParticipationDate.HasValue ? Model.ParticipationDate.Value.ToString("MM/dd/yyyy") : string.Empty;
            _previousProviderId = Model.ProviderId;


            SelectedProviderChangedOwnership = ConvertSprinklerStatusToString(Model.ChangedOwnership_12Mos);
            SelectedCouncil               = Model.ResFamCouncil.HasValue ? Model.ResFamCouncil.ToString() : ResFamCouncilEnum.None.ToString();
            SelectedSprinklerSystem       = Model.SprinklerStatus.HasValue && Model.SprinklerStatus != SprinklerStatusEnum.DataNotAvailable ? Model.SprinklerStatus.ToString() : SprinklerStatusEnum.DataNotAvailable.GetDescription();
            SelectedInHospital            = ConvertSprinklerStatusToString(Model.InHospital);
            SelectedInRetirementCommunity = ConvertSprinklerStatusToString(Model.InRetirementCommunity);
            SelectedSpecialFocus          = ConvertSprinklerStatusToString(Model.HasSpecialFocus);
            if (string.IsNullOrEmpty(Model.Accreditation))
            {
                Model.Accreditation = AccreditationOptions.First();
            }
            if (string.IsNullOrEmpty(Model.Certification))
            {
                Model.Certification = NursingHomeType.First();
            }


            SelectedCounty = Model.IsPersisted ? AvailableCounties.FirstOrDefault(x => x.CountySSA == Model.CountySSA && x.Name != null && x.Name.ContainsCaseInsensitive(Model.CountyName))
                : null;
            OriginalModelHashCode = GetModelHashCode(Model);

            PropertyChanged       += (o, e) => Validate();
            Model.PropertyChanged += (o, e) =>
            {
                if (e.PropertyName.Equals("ProviderId"))
                {
                    HasProviderIdChanged = true;
                    IsProviderIdNew      = !string.IsNullOrEmpty(Model.ProviderId) && Model.ProviderId.Length <= 6 && !CmsCollection.Contains(Model.ProviderId);
                }

                Validate();
                Model.Validate();
            };
        }