/// <summary> /// Method invoked when the user clicks on Use Windows Hello. /// Checks user's trustworthiness and enable Windows Hello. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void CheckBox_Click(object sender, RoutedEventArgs e) { if (UseWindowsHelloCheckBox.IsChecked == true) { if (await SecurityExtensions.Authenticate()) { UseWindowsHelloCheckBox.IsChecked = true; SecurityExtensions.RegisterKey(); } else { UseWindowsHelloCheckBox.IsChecked = false; SecurityExtensions.RemoveKey(); } } else { SecurityExtensions.RemoveKey(); } }
protected AsyncServerClientBase(string serverUrl, TConvention convention, OperationCredentials credentials, HttpJsonRequestFactory jsonRequestFactory, Guid?sessionId, NameValueCollection operationsHeaders, Func <string, TReplicationInformer> replicationInformerGetter, string resourceName) { WasDisposed = false; ServerUrl = serverUrl.TrimEnd('/'); Conventions = convention ?? new TConvention(); CredentialsThatShouldBeUsedOnlyInOperationsWithoutReplication = credentials; RequestFactory = jsonRequestFactory ?? new HttpJsonRequestFactory(DefaultNumberOfCachedRequests, authenticationScheme: Conventions.AuthenticationScheme); if (jsonRequestFactory == null) { SecurityExtensions.InitializeSecurity(Conventions, RequestFactory, ServerUrl); } SessionId = sessionId; OperationsHeaders = operationsHeaders ?? DefaultNameValueCollection; ReplicationInformerGetter = replicationInformerGetter ?? DefaultReplicationInformerGetter(); replicationInformer = new Lazy <TReplicationInformer>(() => ReplicationInformerGetter(resourceName), true); MaxQuerySizeForGetRequest = 8 * 1024; }
/// <summary> /// Удаляет у текущего пользователя имя входа у внешнего провайдера. /// </summary> private async Task <object> UnlinkExternalLogin(IHttpRequest request) { if (!IsAuthenticated()) { return(CreateErrorResponse(Resources.RequestIsNotAuthenticated, 401)); } dynamic unlinkExternalLoginForm = request.Form; string provider = unlinkExternalLoginForm.Provider; string providerKey = unlinkExternalLoginForm.ProviderKey; if (string.IsNullOrWhiteSpace(provider)) { return(CreateErrorResponse(Resources.ExternalProviderCannotBeNullOrWhiteSpace, 400)); } if (string.IsNullOrWhiteSpace(providerKey)) { return(CreateErrorResponse(Resources.ExternalProviderKeyCannotBeNullOrWhiteSpace, 400)); } // Определение текущего пользователя var userId = SecurityExtensions.GetUserId(Identity); // Удаление имени входа пользователя var removeLoginTask = await ApplicationUserManager.RemoveLoginAsync(userId, new UserLoginInfo(provider, providerKey)); if (!removeLoginTask.Succeeded) { var errorMessage = !removeLoginTask.Succeeded ? string.Join(Environment.NewLine, removeLoginTask.Errors) : null; return(CreateErrorResponse(errorMessage, 400)); } return(CreateSuccesResponse <object>(null)); }
protected override List <ReporteTicketVo> GetListData() { var inicio = DateTime.UtcNow; var desde = dpDesde.SelectedDate.HasValue ? SecurityExtensions.ToDataBaseDateTime(dpDesde.SelectedDate.Value) : inicio; var hasta = dpHasta.SelectedDate.HasValue ? SecurityExtensions.ToDataBaseDateTime(dpHasta.SelectedDate.Value) : inicio; try { var results = DAOFactory.SupportTicketDAO.GetList(cbEmpresa.SelectedValues, cbCategoria.SelectedValues, cbSubcategoria.SelectedValues, cbNivel.SelectedValues, desde, hasta); var estados = cbEstados.GetSelectedIndices(); if (Enumerable.Any <int>(estados) && !Enumerable.Contains(estados, -1)) { results = results.Where(ts => Enumerable.Contains <int>(estados, ts.CurrentState)).ToList(); } var duracion = (DateTime.UtcNow - inicio).TotalSeconds.ToString("##0.00"); STrace.Trace("Reporte de Soporte", String.Format("Duración de la consulta: {0} segundos", duracion)); return(results.Select(st => new ReporteTicketVo(st)).ToList()); } catch (Exception e) { STrace.Exception("Reporte de Soporte", e, String.Format("Reporte: Reporte de Soporte. Duración de la consulta: {0:##0.00} segundos", (DateTime.UtcNow - inicio).TotalSeconds)); throw; } }
protected override List <DocumentoVo> GetListData() { var user = DAOFactory.UsuarioDAO.FindById(Usuario.Id); if (chkFiltrar.Checked) { return(DAOFactory.DocumentoDAO.FindByTipoAndUsuario(user, cbTipoDocumento.Selected, cbEmpresa.Selected, cbLinea.Selected, cbTransportista.Selected) .OfType <Documento>() .Where(x => x.FechaAlta >= SecurityExtensions.ToDataBaseDateTime(dtpDesde.SelectedDate.Value) && x.FechaAlta <= SecurityExtensions.ToDataBaseDateTime(dtpHasta.SelectedDate.Value)) .Select(d => new DocumentoVo(d)) .ToList() ); } else { return(DAOFactory.DocumentoDAO.FindByTipoAndUsuario(user, cbTipoDocumento.Selected, cbEmpresa.Selected, cbLinea.Selected, cbTransportista.Selected) .OfType <Documento>() .Select(d => new DocumentoVo(d)) .ToList() ); } }
/// <summary> /// Perfmorms custom search actions. /// </summary> private void RealizarBusqueda() { var desde = SecurityExtensions.ToDataBaseDateTime(dpDesde.SelectedDate.GetValueOrDefault()); var hasta = SecurityExtensions.ToDataBaseDateTime(dpHasta.SelectedDate.GetValueOrDefault()); Stadistics = ReportFactory.MobileStadisticsDAO.GetMobileStadistics(ddlVehiculo.Selected, desde, hasta); var showResults = Stadistics.HasActiveDays(); if (showResults) { MobileDrivers = ReportFactory.MobileDriversDAO.GetMobileDrivers(ddlVehiculo.Selected, desde, hasta).Select(md => new MobileDriversVo(md)).ToList(); AddResultsToSession(); } ifDetalleVehiculo.Visible = ifConductores.Visible = showResults; if (NotFound != null) { NotFound.Text = !showResults?CultureManager.GetSystemMessage("NO_RESULT_FOR_CURRENT_FILTERS") : null; } }
public static SearchData Create(Fichada page) { int duracion; int.TryParse(page.txtDuracion.Text, out duracion); var sd = new SearchData { Empresa = page.cbEmpresa.Selected, Linea = page.cbLinea.Selected, CentrosCostos = page.cbCentroDeCostos.SelectedValues, TiposEmpleados = page.cbTipoEmpleado.SelectedValues, Departamentos = page.cbDepartamento.SelectedValues, Empleado = page.txtEmpleado.Selected, TextEmpleado = page.txtEmpleado.Text, Puertas = page.cbPuerta.SelectedValues, Desde = SecurityExtensions.ToDataBaseDateTime(page.dtDesde.SelectedDate.Value), Hasta = SecurityExtensions.ToDataBaseDateTime(page.dtHasta.SelectedDate.Value), Duracion = duracion, Periodo = page.cbPeriodo.Selected }; return(sd); }
/// <summary> /// the method where we change the password of the user /// </summary> /// <param name="user"></param> /// <param name="pwd"></param> public static Users ChangePassword(Users user, string pwd) { try { if (string.IsNullOrWhiteSpace(pwd)) { pwd = StringExtensions.GetRandomString(8); } var _salt = SecurityExtensions.GetSalt(); var _encryptedPwd = SecurityExtensions.Encrypt(pwd + _salt.ToString()); user.Salt = _salt.ToString(); user.Password = _encryptedPwd; return(user); } catch (Exception) { throw; } }
protected void BtnSearchClick(object sender, EventArgs e) { Distrito = ddlDistrito.Selected; Location = ddlPlanta.Selected; Chofer = ddlEmpleado.Selected; Mobile = ddlMovil.Selected; InitialDate = SecurityExtensions.ToDataBaseDateTime(dtDesde.SelectedDate.Value); FinalDate = SecurityExtensions.ToDataBaseDateTime(dtHasta.SelectedDate.Value); Stopped = tpStopped.SelectedTime; Distance = npDistance.Number; StoppedEvent = npStoppedEvent.Number; MessageType = ddlTipo.Selected; MessagesIds = lbMessages.SelectedStringValues; PoisTypesIds = lbPuntosDeInteres.SelectedValues; var deltaTime = FinalDate.Subtract(InitialDate); if (deltaTime > dtvalidator.MaxRange) { ShowError("El rango de tiempo debe ser menor o igual a " + dtvalidator.MaxRange.ToString()); return; } SearchPositions(); }
protected override List <EntregaVo> GetResults() { var inicio = DateTime.UtcNow; try { var results = new List <EntregaVo>(); var viajes = DAOFactory.ViajeDistribucionDAO.GetList(new[] { ddlLocacion.Selected }, new[] { ddlPlanta.Selected }, lbTransportista.SelectedValues, new[] { -1 }, // DEPARTAMENTOS lbCentroDeCostos.SelectedValues, lbSubCentroDeCostos.SelectedValues, lbVehiculo.SelectedValues, new[] { -1 }, // EMPLEADOS new[] { -1 }, // ESTADOS new[] { cbTipoDistribucion.Selected }, SecurityExtensions.ToDataBaseDateTime(dpDesde.SelectedDate.GetValueOrDefault()), SecurityExtensions.ToDataBaseDateTime(dpHasta.SelectedDate.GetValueOrDefault())); foreach (var viajeDistribucion in viajes) { EntregaDistribucion anterior = null; var detalles = viajeDistribucion.Detalles; if (chkVerOrdenManual.Checked) { detalles = viajeDistribucion.GetEntregasPorOrdenManual(); } else if (viajeDistribucion.Tipo == ViajeDistribucion.Tipos.Desordenado) { detalles = viajeDistribucion.GetEntregasPorOrdenReal(); } var orden = 0; foreach (var entrega in detalles) { var tiempoRecorrido = new TimeSpan(0); var kms = 0.0; DateTime?desde = null; if (anterior != null && (entrega.Estado.Equals(EntregaDistribucion.Estados.Completado) || entrega.Estado.Equals(EntregaDistribucion.Estados.Visitado))) { desde = anterior.SalidaOManualExclusiva.HasValue ? anterior.SalidaOManualExclusiva.Value : (DateTime?)null; if (entrega.EntradaOManualExclusiva.HasValue && anterior.SalidaOManualExclusiva.HasValue) { tiempoRecorrido = entrega.EntradaOManualExclusiva.Value.Subtract(anterior.SalidaOManualExclusiva.Value); if (tiempoRecorrido.TotalMinutes < 0) { tiempoRecorrido = new TimeSpan(0); } } if (entrega.Viaje.Vehiculo != null && anterior.FechaMin < entrega.FechaMin && entrega.FechaMin < DateTime.MaxValue) { kms = DAOFactory.CocheDAO.GetDistance(entrega.Viaje.Vehiculo.Id, anterior.FechaMin, entrega.FechaMin); } } results.Add(new EntregaVo(orden, entrega, tiempoRecorrido, kms, desde)); orden++; if (entrega.Estado.Equals(EntregaDistribucion.Estados.Completado) || entrega.Estado.Equals(EntregaDistribucion.Estados.Visitado)) { anterior = entrega; } } } var duracion = (DateTime.UtcNow - inicio).TotalSeconds.ToString("##0.00"); STrace.Trace("Retraso de Ruta", String.Format("Duración de la consulta: {0} segundos", duracion)); return(results); } catch (Exception e) { STrace.Exception("Retraso de Ruta", e); throw; } }
/// <summary> /// The main entry point for the application. /// </summary> private static void Main(String[] args) { // Trace copyright information Assembly entryAsm = Assembly.GetEntryAssembly(); // Dump some info Trace.TraceInformation("SanteDB Startup : v{0}", entryAsm.GetName().Version); Trace.TraceInformation("SanteDB Working Directory : {0}", entryAsm.Location); Trace.TraceInformation("Operating System: {0} {1}", Environment.OSVersion.Platform, Environment.OSVersion.VersionString); Trace.TraceInformation("CLI Version: {0}", Environment.Version); AppDomain.CurrentDomain.SetData( "DataDirectory", Path.GetDirectoryName(typeof(Program).Assembly.Location)); // Handle Unahndled exception AppDomain.CurrentDomain.UnhandledException += (o, e) => { Trace.TraceError("++++++ FATAL APPLICATION ERROR ++++++++\r\n{0}", e.ExceptionObject); EventLog.WriteEntry("SanteDB Host Process", $"++++++ FATAL APPLICATION ERROR ++++++++\r\n{e.ExceptionObject}", EventLogEntryType.Error, 999); Environment.Exit(999); }; // Parser ParameterParser <ConsoleParameters> parser = new ParameterParser <ConsoleParameters>(); bool hasConsole = true; try { var parameters = parser.Parse(args); var instanceSuffix = !String.IsNullOrEmpty(parameters.InstanceName) ? $"-{parameters.InstanceName}" : null; // What to do? if (parameters.ShowHelp) { parser.WriteHelp(Console.Out); } else if (parameters.InstallCerts) { Console.WriteLine("Installing security certificates..."); SecurityExtensions.InstallCertsForChain(); } else if (parameters.Install) { if (!ServiceTools.ServiceInstaller.ServiceIsInstalled($"SanteDB{instanceSuffix}")) { Console.WriteLine("Installing Service..."); if (!String.IsNullOrEmpty(instanceSuffix)) { var configFile = parameters.ConfigFile; if (String.IsNullOrEmpty(configFile)) { configFile = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), $"santedb.config.{parameters.InstanceName}.xml"); } else if (!Path.IsPathRooted(configFile)) { configFile = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), configFile); } ServiceTools.ServiceInstaller.Install($"SanteDB{instanceSuffix}", $"SanteDB Host Process - {parameters.InstanceName}", $"{Assembly.GetEntryAssembly().Location} --name={parameters.InstanceName} --config={configFile}", null, null, ServiceTools.ServiceBootFlag.AutoStart); } else { ServiceTools.ServiceInstaller.Install($"SanteDB", "SanteDB Host Process", $"{Assembly.GetEntryAssembly().Location}", null, null, ServiceTools.ServiceBootFlag.AutoStart); } } } else if (parameters.UnInstall) { if (ServiceTools.ServiceInstaller.ServiceIsInstalled($"SanteDB{instanceSuffix}")) { Console.WriteLine("Un-Installing Service..."); ServiceTools.ServiceInstaller.StopService($"SanteDB{instanceSuffix}"); ServiceTools.ServiceInstaller.Uninstall($"SanteDB{instanceSuffix}"); } } else if (parameters.GenConfig) { SanteDBConfiguration configuration = new SanteDBConfiguration(); ApplicationServiceContextConfigurationSection serverConfiguration = new ApplicationServiceContextConfigurationSection(); Console.WriteLine("Will generate full default configuration..."); foreach (var file in Directory.GetFiles(Path.GetDirectoryName(typeof(Program).Assembly.Location), "*.dll")) { try { var asm = Assembly.LoadFile(file); Console.WriteLine("Adding service providers from {0}...", file); serverConfiguration.ServiceProviders.AddRange(asm.ExportedTypes.Where(t => typeof(IServiceImplementation).IsAssignableFrom(t) && !t.IsAbstract && !t.ContainsGenericParameters && t.GetCustomAttribute <ServiceProviderAttribute>() != null).Select(o => new TypeReferenceConfiguration(o))); Console.WriteLine("Adding sections from {0}...", file); configuration.Sections.AddRange(asm.ExportedTypes.Where(t => typeof(IConfigurationSection).IsAssignableFrom(t)).Select(t => CreateFullXmlObject(t))); } catch (Exception e) { Console.WriteLine("Skipping {0} due to {1}", file, e.Message); } } configuration.RemoveSection <ApplicationServiceContextConfigurationSection>(); serverConfiguration.ThreadPoolSize = Environment.ProcessorCount * 16; configuration.AddSection(serverConfiguration); using (var fs = File.Create(Path.Combine(Path.GetDirectoryName(typeof(Program).Assembly.Location), "default.config.xml"))) configuration.Save(fs); } else if (parameters.ConsoleMode) { Console.WriteLine("SanteDB (SanteDB) {0} ({1})", entryAsm.GetName().Version, entryAsm.GetCustomAttribute <AssemblyInformationalVersionAttribute>().InformationalVersion); Console.WriteLine("{0}", entryAsm.GetCustomAttribute <AssemblyCopyrightAttribute>().Copyright); Console.WriteLine("Complete Copyright information available at http://SanteDB.codeplex.com/wikipage?title=Contributions"); ServiceUtil.Start(typeof(Program).GUID, new FileConfigurationService(parameters.ConfigFile)); if (!parameters.StartupTest) { // Did the service start properly? if (!ApplicationServiceContext.Current.IsRunning) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Application context did not start properly and is in maintenance mode..."); Console.ResetColor(); } if (Environment.OSVersion.Platform == PlatformID.Win32NT) { ManualResetEvent quitEvent = new ManualResetEvent(false); Console.CancelKeyPress += (o, e) => { Console.WriteLine("Service shutting down..."); ServiceUtil.Stop(); quitEvent.Set(); }; Console.WriteLine("Service started (CTRL+C to stop)..."); quitEvent.WaitOne(); } else { // Now wait until the service is exiting va SIGTERM or SIGSTOP UnixSignal[] signals = new UnixSignal[] { new UnixSignal(Mono.Unix.Native.Signum.SIGINT), new UnixSignal(Mono.Unix.Native.Signum.SIGTERM), new UnixSignal(Mono.Unix.Native.Signum.SIGQUIT), new UnixSignal(Mono.Unix.Native.Signum.SIGHUP) }; int signal = UnixSignal.WaitAny(signals); // Gracefully shutdown ServiceUtil.Stop(); try // remove the lock file { File.Delete("/tmp/SanteDB.exe.lock"); } catch { } } } } else { hasConsole = false; ServiceBase[] servicesToRun = new ServiceBase[] { new SanteDBService() }; ServiceBase.Run(servicesToRun); } } catch (Exception e) { #if DEBUG Trace.TraceError("011 899 981 199 911 9725 3!!! {0}", e.ToString()); EventLog.WriteEntry("SanteDB Host Process", $"011 899 981 199 911 9725 3!!! {e}", EventLogEntryType.Error, 911); #else Trace.TraceError("Error encountered: {0}. Will terminate", e); #endif if (hasConsole) { Console.WriteLine("011 899 981 199 911 9725 3!!! {0}", e.ToString()); } try { EventLog.WriteEntry("SanteDB Host Process", $"011 899 981 199 911 9725 3!!! {e}", EventLogEntryType.Error, 911); } catch (Exception e1) { Trace.TraceWarning("Could not emit the error to the EventLog - {0}", e1); } Environment.Exit(911); } }
public void It_should_throw_if_password_is_null() { Assert.ThrowsException <ArgumentNullException>(() => SecurityExtensions.Pbkdf2((byte[])null, (r, k, s) => { }, new byte[0], 1, 1)); Assert.ThrowsException <ArgumentNullException>(() => SecurityExtensions.Pbkdf2((string)null, (r, k, s) => { }, new byte[0], 1, 1)); }
/// <summary> /// Method invoked when the user clicks on Accedi. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void Button_Click(object sender, RoutedEventArgs e) { StatusProgressBar.Opacity = 1; UsernameTextBox.IsEnabled = false; PasswordPasswordBox.IsEnabled = false; LoginButton.IsEnabled = false; bool authenticated; try { if (ApplicationData.Current.LocalSettings.Values.ContainsKey("HelloAuthenticationEnabled")) { if (await SecurityExtensions.Authenticate()) { authenticated = await Singleton <ClientExtensions> .Instance.AuthenticateAndInitDataAsync(new UserCredentials(UsernameTextBox.Text, PasswordPasswordBox.Password), true); } else { PasswordPasswordBox.Password = ""; UsernameTextBox.IsEnabled = true; PasswordPasswordBox.IsEnabled = true; LoginButton.IsEnabled = true; StatusProgressBar.Opacity = 0; return; } } else { authenticated = await Singleton <ClientExtensions> .Instance.AuthenticateAndInitDataAsync(new UserCredentials(UsernameTextBox.Text, PasswordPasswordBox.Password), true); } SecurityExtensions.AddCredentials(UsernameTextBox.Text, PasswordPasswordBox.Password); BackgroundTaskExtensions.Register(120); } catch (Exception ex) { Analytics.TrackEvent(ex.Message, new Dictionary <string, string> { { "exception", ex.ToString() } }); AppNotification.IsOpen = true; AppNotification.Title = "Attention".GetLocalized(); if (ex is UnauthorizedUserException) { AppNotification.Subtitle = ex.Message; UsernameTextBox.IsEnabled = true; PasswordPasswordBox.IsEnabled = true; LoginButton.IsEnabled = true; StatusProgressBar.Opacity = 0; return; } else if (ex is HttpRequestException) { AppNotification.Subtitle = "HttpRequestException".GetLocalized(); UsernameTextBox.IsEnabled = true; PasswordPasswordBox.IsEnabled = true; LoginButton.IsEnabled = true; StatusProgressBar.Opacity = 0; return; } else { AppNotification.Subtitle = "UnhandledException".GetLocalized(); } } NavigationService.Navigate(typeof(MainPage), new EntranceNavigationTransitionInfo()); navigationView.SelectedItem = navigationView.MenuItems[0]; IsBackEnabled = false; NavigationService.Frame.BackStack.Clear(); Loader.IsLoading = false; _avoidCheck = false; UsernameTextBox.IsEnabled = true; PasswordPasswordBox.IsEnabled = true; LoginButton.IsEnabled = true; StatusProgressBar.Opacity = 0; }
protected override void OnSave() { var lastState = EditObject.CurrentState; var now = DateTime.UtcNow; var usuario = DAOFactory.UsuarioDAO.FindById(Usuario.Id); EditObject.Nombre = txtNombre.Text.Trim(); EditObject.Telefono = txtTelefono.Text.Trim(); EditObject.Mail = txtMail.Text.Trim(); EditObject.TipoProblema = (short)cbTipoProblema.SelectedIndex; EditObject.Descripcion = txtDescripcion.Text.Trim(); EditObject.Nivel = (short)cbNivel.Selected; EditObject.NivelObj = cbNivel.Selected > 0 ? DAOFactory.NivelDAO.FindById(cbNivel.Selected) : null; EditObject.CategoriaObj = cbCategoria.Selected > 0 ? DAOFactory.CategoriaDAO.FindById(cbCategoria.Selected) : null; EditObject.Subcategoria = cbSubcategoria.Selected > 0 ? DAOFactory.SubCategoriaDAO.FindById(cbSubcategoria.Selected) : null; EditObject.MailList = txtMailList.Text.Trim(); if (dtInicio.SelectedDate.HasValue) { EditObject.FechaInicio = SecurityExtensions.ToDataBaseDateTime(dtInicio.SelectedDate.Value); } EditObject.Empresa = cbEmpresa.Selected <= 0 ? null : DAOFactory.EmpresaDAO.FindById(cbEmpresa.Selected); EditObject.Vehiculo = cbVehiculo.Selected > 0 ? DAOFactory.CocheDAO.FindById(cbVehiculo.Selected) : null; EditObject.Dispositivo = cbDispositivo.Selected > 0 ? DAOFactory.DispositivoDAO.FindById(cbDispositivo.Selected) : null; EditObject.NroParte = EditMode ? txtNroParte.Text.Trim() : string.Empty; if (!EditMode) { EditObject.Fecha = now; EditObject.Usuario = usuario; } var estado = (short)(!EditMode ? 0 : cbEstado.SelectedIndex); if (EditObject.CurrentState == 4 && cbResolucion.SelectedIndex != 0) { estado = (short)(cbResolucion.SelectedIndex == 1 ? 5 : 6); } var detail = new SupportTicketDetail { Estado = estado, Fecha = now, SupportTicket = EditObject, Usuario = usuario, Descripcion = Server.HtmlEncode(txtComentario.Text.Trim()).Replace("\r\n", "<br />") }; EditObject.AddDetail(detail); if (lastState != estado) { var le = DAOFactory.SupportTicketDAO.GetEstados()[lastState]; var ne = DAOFactory.SupportTicketDAO.GetEstados()[estado]; if (!string.IsNullOrEmpty(detail.Descripcion)) { detail.Descripcion += "<br /><br />"; } detail.Descripcion += string.Concat("[", CultureManager.GetLabel("SUPPORT_STATE_CHANGED"), ": ", le, " > ", ne, "]"); upGridEstados.Update(); } if (filUpload.HasFile) { CheckDirectory(); var filename = GetFileName(filUpload.FileName); filUpload.SaveAs(Path.Combine(AttachDirectory, filename)); if (string.IsNullOrEmpty(EditObject.FileName)) { EditObject.FileName = filename; } else { EditObject.FileName += ";" + filename; } if (!string.IsNullOrEmpty(detail.Descripcion)) { detail.Descripcion += "<br /><br />"; } detail.Descripcion += string.Concat("[", CultureManager.GetLabel("SUPPORT_FILE_UPLOADED"), ": ", filename, "]"); } DAOFactory.SupportTicketDAO.SaveOrUpdate(EditObject); InformarPorMail(!EditMode); upComentarios.Update(); }
protected override List <KmHsProductivosVo> GetResults() { var inicio = DateTime.UtcNow; try { var results = DAOFactory.CocheDAO.GetList((IEnumerable <int>)ddlLocacion.SelectedValues, (IEnumerable <int>)ddlPlanta.SelectedValues, (IEnumerable <int>)ddlTipoVehiculo.SelectedValues) .Where(v => ddlVehiculo.SelectedValues.Contains(v.Id)) .Select(v => new KmHsProductivosVo(v, dpDesde.SelectedDate != null ? SecurityExtensions.ToDataBaseDateTime(dpDesde.SelectedDate.Value) : DateTime.Today, dpHasta.SelectedDate != null ? SecurityExtensions.ToDataBaseDateTime(dpHasta.SelectedDate.Value) : DateTime.Today.AddDays(1))) .ToList(); STrace.Trace("Reporte de Horas Productivas", String.Format("Duración de la consulta: {0:##0.00} segundos", (DateTime.UtcNow - inicio).TotalSeconds)); return(results); } catch (Exception e) { STrace.Exception("Reporte de Horas Productivas", e, String.Format("Reporte: Reporte de Horas Productivas. Duración de la consulta: {0:##0.00} segundos", (DateTime.UtcNow - inicio).TotalSeconds)); throw; } }
protected override List <ConsumoCCVo> GetResults() { ToogleItems(lbMovil); ToogleItems(lbTipo); var inicio = DateTime.UtcNow; try { var consumos = DAOFactory.ConsumoCabeceraDAO.GetList(ddlLocation.SelectedValues, ddlPlanta.SelectedValues, new[] { -1 }, // Departamentos new[] { -1 }, // Transportistas new[] { -1 }, // Centros de costo lbTipo.SelectedValues, lbMovil.SelectedValues, new[] { -1 }, // Tipos de empleado new[] { -1 }, // Empleados new[] { -1 }, // Tipos de proveedor new[] { -1 }, // Proveedores new[] { -1 }, // Depositos Origen new[] { -1 }, // Depositos Destino SecurityExtensions.ToDataBaseDateTime(dtDesde.SelectedDate.Value), SecurityExtensions.ToDataBaseDateTime(dtHasta.SelectedDate.Value)) .Where(c => c.Estado != -1);; var documentos = DAOFactory.DocumentoDAO.GetListForConsumos(ddlLocation.SelectedValues, ddlPlanta.SelectedValues, lbTipo.SelectedValues, lbMovil.SelectedValues, dtDesde.SelectedDate.Value, dtHasta.SelectedDate.Value); var results = new List <ConsumoCCVo>(); foreach (var consumo in consumos) { if (consumo.Vehiculo == null) { continue; } var vehiculo = consumo.Vehiculo; var fecha = consumo.Fecha; // BUSCO DOCUMENTO DE ASIGNACION DEL VEHICULO EN LA FECHA DEL CONSUMO var documento = documentos.FirstOrDefault(d => d.Vehiculo.Id == vehiculo.Id && fecha > d.Fecha && fecha < d.FechaCierre); if (documento != null && documento.Id != 0) { var valores = documento.Parametros.Cast <DocumentoValor>(); valores = valores.Where(v => v.Parametro.TipoDato.Equals("centrocostos") && v.Parametro.Nombre.Equals("Destino")).ToList(); var centros = QueryExtensions.IncludesAll((IEnumerable <int>)lbCentroDeCostos.SelectedValues) ? DAOFactory.CentroDeCostosDAO.FindByEmpresasAndLineas(new List <int> { ddlLocation.Selected }, new List <int> { ddlPlanta.Selected }) .Cast <CentroDeCostos>().Select(cc => cc.Id).ToList() : lbCentroDeCostos.SelectedValues; var docs = valores.Where(v => centros.Contains(Convert.ToInt32(v.Valor))); if (docs.Any()) { results.Add(new ConsumoCCVo(consumo, Convert.ToInt32(docs.FirstOrDefault().Valor))); } } else { if (vehiculo.CentroDeCostos != null && (lbCentroDeCostos.SelectedValues.Contains(vehiculo.CentroDeCostos.Id) || QueryExtensions.IncludesAll((IEnumerable <int>)lbCentroDeCostos.SelectedValues))) { results.Add(new ConsumoCCVo(consumo, vehiculo.CentroDeCostos.Id)); } } } var duracion = (DateTime.UtcNow - inicio).TotalSeconds.ToString("##0.00"); STrace.Trace("Reporte de Consumos por Centro de Costo", String.Format("Duración de la consulta: {0} segundos", duracion)); return(results); } catch (Exception e) { STrace.Exception("Reporte de Consumos por Centro de Costo", e, String.Format("Reporte: Reporte de Consumos por Centro de Costo. Duración de la consulta: {0:##0.00} segundos", (DateTime.UtcNow - inicio).TotalSeconds)); throw; } }
protected override List <RendimientoVo> GetResults() { var inicio = DateTime.UtcNow; try { var desde = dpDesde.SelectedDate != null?SecurityExtensions.ToDataBaseDateTime(dpDesde.SelectedDate.Value) : DateTime.Today; var hasta = dpHasta.SelectedDate != null?SecurityExtensions.ToDataBaseDateTime(dpHasta.SelectedDate.Value) : DateTime.Today.AddDays(1); var vehiculos = DAOFactory.CocheDAO.GetList(ddlLocacion.SelectedValues, ddlPlanta.SelectedValues, new[] { -1 }, // TIPO VEHICULO ddlTransportista.SelectedValues, new[] { -1 }) // DEPARTAMENTOS .Where(v => QueryExtensions.IncludesAll((IEnumerable <int>)ddlVehiculo.SelectedValues) || ddlVehiculo.SelectedValues.Contains(v.Id)); var despachos = DAOFactory.ConsumoDetalleDAO.GetList(ddlLocacion.SelectedValues, ddlPlanta.SelectedValues, ddlTransportista.SelectedValues, new[] { -1 }, // DEPARTAMENTOS new[] { -1 }, // CC new[] { -1 }, // TIPO VEHICULO ddlVehiculo.SelectedValues, new[] { -1 }, // TIPO EMPLEADO new[] { -1 }, // EMPLEADO new[] { -1 }, // TIPO PROVEEDOR new[] { -1 }, // PROOVEDOR new[] { -1 }, // DEPOSITO ORIGEN new[] { -1 }, // DEPOSITO DESTINO desde, hasta, new[] { -1 }) // CABECERA .Where(c => c.Insumo.TipoInsumo.DeCombustible); var viajes = new List <ViajeDistribucion>(); if (chkControlaCiclo.Checked) { viajes = DAOFactory.ViajeDistribucionDAO.GetList(ddlLocacion.SelectedValues, ddlPlanta.SelectedValues, ddlTransportista.SelectedValues, new[] { -1 }, // DEPARTAMENTOS new[] { -1 }, // CC new[] { -1 }, // SUB CC ddlVehiculo.SelectedValues, desde, hasta); } var results = vehiculos.Select(vehiculo => new RendimientoVo(vehiculo, desde, hasta, despachos.Where(d => d.ConsumoCabecera.Vehiculo == vehiculo).Sum(d => d.Cantidad), viajes.Count(d => d.Vehiculo == vehiculo && d.InicioReal.HasValue), chkControlaCiclo.Checked)) .ToList(); var duracion = (DateTime.UtcNow - inicio).TotalSeconds.ToString("##0.00"); STrace.Trace("Listado de Rendimiento M2M", String.Format("Duración de la consulta total: {0} segundos", duracion)); return(results); } catch (Exception e) { STrace.Exception("Listado de Rendimiento M2M", e, String.Format("Duración de la consulta total: {0:##0.00} segundos", (DateTime.UtcNow - inicio).TotalSeconds)); throw; } }
protected override List <AccessEventVo> GetResults() { return(DAOFactory.EventoAccesoDAO.FindByEmpresaLineaEmpleadosAndFecha(ddlLocacion.Selected, ddlPlanta.Selected, lbEmpleado.SelectedValues, SecurityExtensions.ToDataBaseDateTime(dpDesde.SelectedDate.Value), SecurityExtensions.ToDataBaseDateTime(dpHasta.SelectedDate.Value)).Select(e => new AccessEventVo(e)).ToList()); }
protected override List <DetentionTimes> GetResults() { return(ReportFactory.DetentionTimesDAO.GetDetentionTimes(Convert.ToInt32((string)ddlMovil.SelectedValue), SecurityExtensions.ToDataBaseDateTime(dpDesde.SelectedDate.GetValueOrDefault()), SecurityExtensions.ToDataBaseDateTime(dpHasta.SelectedDate.GetValueOrDefault()))); }
protected override List <ResumenDeEntregasVo> GetResults() { var inicio = DateTime.UtcNow; try { var results = new List <ResumenDeEntregasVo>(); var viajes = DAOFactory.ViajeDistribucionDAO.GetList(new[] { ddlLocacion.Selected }, new[] { ddlPlanta.Selected }, lbTransportista.SelectedValues, lbDepartamento.SelectedValues, lbCentroDeCostos.SelectedValues, lbSubCentroDeCostos.SelectedValues, lbVehiculo.SelectedValues, SecurityExtensions.ToDataBaseDateTime(dpDesde.SelectedDate.GetValueOrDefault()), SecurityExtensions.ToDataBaseDateTime(dpHasta.SelectedDate.GetValueOrDefault())) .Where(v => v.Vehiculo != null) .Where(v => chkPendientes.Checked || v.Estado != ViajeDistribucion.Estados.Pendiente) .OrderBy(v => v.Vehiculo); var completados = 0; var noCompletados = 0; var visitados = 0; var noVisitados = 0; var enSitio = 0; var enZona = 0; var totalCompletados = 0; var totalNoCompletados = 0; var totalVisitados = 0; var totalNoVisitados = 0; var totalEnSitio = 0; var totalEnZona = 0; var rutas = 0; Coche vehiculo = null; ResumenDeEntregasVo resumenEntrega; foreach (var viajeDistribucion in viajes) { if (vehiculo == null) { vehiculo = viajeDistribucion.Vehiculo; } var cocheActual = viajeDistribucion.Vehiculo; if (vehiculo != cocheActual) { resumenEntrega = new ResumenDeEntregasVo(vehiculo, completados, noCompletados, visitados, noVisitados, enSitio, enZona, rutas); results.Add(resumenEntrega); completados = noCompletados = visitados = noVisitados = enSitio = enZona = rutas = 0; vehiculo = cocheActual; } var detalles = viajeDistribucion.Detalles.Where(d => d.Linea == null); rutas++; foreach (var entrega in detalles) { switch (entrega.Estado) { case EntregaDistribucion.Estados.Completado: completados++; totalCompletados++; break; case EntregaDistribucion.Estados.NoCompletado: noCompletados++; totalNoCompletados++; break; case EntregaDistribucion.Estados.Visitado: visitados++; totalVisitados++; break; case EntregaDistribucion.Estados.EnSitio: enSitio++; totalEnSitio++; break; case EntregaDistribucion.Estados.EnZona: enZona++; totalEnZona++; break; default: noVisitados++; totalNoVisitados++; break; } } } if (vehiculo != null) { resumenEntrega = new ResumenDeEntregasVo(vehiculo, completados, noCompletados, visitados, noVisitados, enSitio, enZona, rutas); results.Add(resumenEntrega); } if (results.Count > 0) { divChart.Visible = true; divChart.InnerHtml = FusionCharts.RenderChartHTML(ChartXmlDefinition, "", GetGraphXml(results), "Report", "1050", "500", false); } ShowLabels(totalCompletados, totalNoCompletados, totalVisitados, totalNoVisitados, totalEnSitio, totalEnZona); var duracion = (DateTime.UtcNow - inicio).TotalSeconds.ToString("##0.00"); STrace.Trace("Resumen de entregas", String.Format("Duración de la consulta: {0} segundos", duracion)); return(results); } catch (Exception e) { STrace.Exception("Resumen de entregas", e, String.Format("Reporte: Resumen de entregas. Duración de la consulta: {0:##0.00} segundos", (DateTime.UtcNow - inicio).TotalSeconds)); throw; } }
protected override void OnSave() { EditObject.Taller = cbTaller.Selected > 0 ? DAOFactory.TallerDAO.FindById(cbTaller.Selected) : null; if (dtInicio.SelectedDate.HasValue) { EditObject.FechaSolicitud = SecurityExtensions.ToDataBaseDateTime(dtInicio.SelectedDate.Value); } EditObject.Codigo = txtCodigo.Text; EditObject.NivelComplejidad = (short)cbNivel.Selected; EditObject.Estado = (short)cbEstado.Selected; EditObject.Empresa = cbEmpresa.Selected > 0 ? DAOFactory.EmpresaDAO.FindById(cbEmpresa.Selected) : null; EditObject.Vehiculo = cbVehiculo.Selected > 0 ? DAOFactory.CocheDAO.FindById(cbVehiculo.Selected) : null; EditObject.Empleado = cbEmpleado.Selected > 0 ? DAOFactory.EmpleadoDAO.FindById(cbEmpleado.Selected) : null; EditObject.FechaTurno = dtTurno.SelectedDate.HasValue ? SecurityExtensions.ToDataBaseDateTime(dtTurno.SelectedDate.Value) : (DateTime?)null; EditObject.FechaRecepcion = dtRecepcion.SelectedDate.HasValue ? SecurityExtensions.ToDataBaseDateTime(dtRecepcion.SelectedDate.Value) : (DateTime?)null; EditObject.FechaVerificacion = dtVerificacion.SelectedDate.HasValue ? SecurityExtensions.ToDataBaseDateTime(dtVerificacion.SelectedDate.Value) : (DateTime?)null; EditObject.FechaTrabajoTerminado = dtTrabajoTerminado.SelectedDate.HasValue ? SecurityExtensions.ToDataBaseDateTime(dtTrabajoTerminado.SelectedDate.Value) : (DateTime?)null; EditObject.FechaEntrega = dtEntrega.SelectedDate.HasValue ? SecurityExtensions.ToDataBaseDateTime(dtEntrega.SelectedDate.Value) : (DateTime?)null; EditObject.FechaTrabajoAceptado = dtTrabajoAceptado.SelectedDate.HasValue ? SecurityExtensions.ToDataBaseDateTime(dtTrabajoAceptado.SelectedDate.Value) : (DateTime?)null; EditObject.Presupuesto = txtPresupuesto.Text; double monto; double.TryParse(txtMonto.Text, out monto); EditObject.Monto = monto; EditObject.FechaPresupuestada = dtPresupuesto.SelectedDate.HasValue ? SecurityExtensions.ToDataBaseDateTime(dtPresupuesto.SelectedDate.Value) : (DateTime?)null; EditObject.EstadoPresupuesto = (short)cbEstadoPresupuesto.Selected; EditObject.PrimerPresupuesto = txtPrimerPresupuesto.Text; EditObject.FechaPresupuestoOriginal = dtPrimerPresupuesto.SelectedDate.HasValue ? SecurityExtensions.ToDataBaseDateTime(dtPrimerPresupuesto.SelectedDate.Value) : (DateTime?)null; EditObject.FechaRecotizacion = dtRecotizacion.SelectedDate.HasValue ? SecurityExtensions.ToDataBaseDateTime(dtRecotizacion.SelectedDate.Value) : (DateTime?)null; EditObject.FechaAprobacion = dtAprobacion.SelectedDate.HasValue ? SecurityExtensions.ToDataBaseDateTime(dtAprobacion.SelectedDate.Value) : (DateTime?)null; EditObject.Descripcion = txtDescripcion.Text; var historia = new HistoriaTicketMantenimiento { Codigo = EditObject.Codigo, Descripcion = EditObject.Descripcion, Empleado = EditObject.Empleado, Empresa = EditObject.Empresa, Estado = EditObject.Estado, EstadoPresupuesto = EditObject.EstadoPresupuesto, Fecha = DateTime.UtcNow, FechaAprobacion = EditObject.FechaAprobacion, FechaEntrega = EditObject.FechaEntrega, FechaPresupuestada = EditObject.FechaPresupuestada, FechaPresupuestoOriginal = EditObject.FechaPresupuestoOriginal, FechaRecepcion = EditObject.FechaRecepcion, FechaRecotizacion = EditObject.FechaRecotizacion, FechaSolicitud = EditObject.FechaSolicitud, FechaTrabajoAceptado = EditObject.FechaTrabajoAceptado, FechaTrabajoTerminado = EditObject.FechaTrabajoTerminado, FechaTurno = EditObject.FechaTurno, FechaVerificacion = EditObject.FechaVerificacion, Monto = EditObject.Monto, NivelComplejidad = EditObject.NivelComplejidad, Presupuesto = EditObject.Presupuesto, PrimerPresupuesto = EditObject.PrimerPresupuesto, Taller = EditObject.Taller, TicketMantenimiento = EditObject, Usuario = DAOFactory.UsuarioDAO.FindById(Usuario.Id), Vehiculo = EditObject.Vehiculo }; EditObject.Historia.Add(historia); DAOFactory.TicketMantenimientoDAO.SaveOrUpdate(EditObject); }
private void LoadTable() { dias.InnerHtml = string.Empty; var horas = npHoraHasta.Value - npHoraDesde.Value + 1; var ancho = (100 / horas) - 0.2; var indice = 0.0; for (var i = (int)npHoraDesde.Value; i < npHoraHasta.Value + 1; i++) { var div = string.Format(@"<div style=""position: absolute; height: 20px; left: {0}%; width: {1}%; background-color:{2}"">{3}</div>", indice.ToString("0.00"), ancho.ToString("0.00"), Gris, "<b>" + i + "</b>"); indice += ancho + 0.2; dias.InnerHtml += div.Replace(',', '.'); } var coches = Enumerable.Where <int>(cbVehiculo.SelectedValues, id => id > 0).Select(id => DAOFactory.CocheDAO.FindById(id)).Where(c => c.Dispositivo != null); foreach (var coche in coches) { var routes = GetRoutes(coche.Id); var rowContent = new HtmlTableRow(); var cellContent = new HtmlTableCell(); var cellVehiculos = new HtmlTableCell(); cellVehiculos.InnerHtml += "<div id='" + "cont" + coche.Id + "' runat='server' style='position: relative; height:30px;'>"; cellContent.InnerHtml += "<div id='" + "content" + coche.Id + "' runat='server' style='position: relative; height:30px;'>"; var porcentajeAcumulado = 0.0; if (routes.Count() == 0) { cellContent.InnerText = "NO SE ENCONTRARON POSICIONES PARA EL PERIODO SELECCIONADO."; cellContent.Align = "center"; cellContent.VAlign = "middle"; cellContent.Style.Add("font-weight", "bold"); } else { foreach (var route in routes) { var porcentajeDelDia = route.Duration / horas * 100; var color = Blanco; switch (route.VehicleStatus) { case "Detenido": switch (route.EngineStatus) { case "Encendido": color = route.Duration > 0.083 ? Azul : Verde; // 0.083 horas = 5 minutos break; case "Apagado": color = route.Duration >= 8 ? Blanco : route.Duration >= 1 ? Amarillo : Gris; break; } break; case "En Movimiento": color = route.AverageSpeed >= 120 ? Rojo : route.AverageSpeed >= 80 ? Naranja : route.AverageSpeed > 2 ? Verde : Gris; break; } var desde = SecurityExtensions.ToDataBaseDateTime(dtFecha.SelectedDate.GetValueOrDefault().AddHours(npHoraDesde.Value)).ToString(CultureInfo.InvariantCulture); var hasta = SecurityExtensions.ToDataBaseDateTime(dtFecha.SelectedDate.GetValueOrDefault().AddHours(npHoraHasta.Value)).AddMinutes(59).ToString(CultureInfo.InvariantCulture); var div = string.Format( @"<div style=""position: absolute; cursor:pointer; font-size:bold; height: 30px; left: {0}%; width: {1}%; background-color:{2}"" onclick=""{3}"" runat=""server"" ></div>", porcentajeAcumulado.ToString(CultureInfo.InvariantCulture), (porcentajeDelDia + 0.1).ToString(CultureInfo.InvariantCulture), color, "docb(" + coche.Id + ",'" + desde + "','" + hasta + "')" ); cellContent.InnerHtml += div; porcentajeAcumulado += porcentajeDelDia; } } cellContent.InnerHtml += "</div>"; cellVehiculos.InnerText = coche.Interno; cellVehiculos.Align = "center"; cellVehiculos.VAlign = "middle"; cellVehiculos.Style.Add("font-weight", "bold"); cellVehiculos.Style.Add("background-color", "#EEEEEE"); rowContent.Cells.Add(cellVehiculos); rowContent.Cells.Add(cellContent); tblContent.Rows.Add(rowContent); } updContent.Update(); tblReferencias.Visible = true; }
/// <summary> /// Gets data associated to the specified filter values. /// </summary> /// <returns></returns> protected override List <MaxSpeeds> GetResults() { var inicio = DateTime.UtcNow; try { var results = ReportFactory.MaxSpeedDAO.GetMobileMaxSpeeds(ddlVehiculo.Selected, SecurityExtensions.ToDataBaseDateTime(dpDesde.SelectedDate.GetValueOrDefault()), SecurityExtensions.ToDataBaseDateTime(dpHasta.SelectedDate.GetValueOrDefault())); var duracion = (DateTime.UtcNow - inicio).TotalSeconds.ToString("##0.00"); STrace.Trace("Resumen Vehicular", String.Format("Duración de la consulta: {0} segundos", duracion)); return(results); } catch (Exception ex) { STrace.Exception("Resumen Vehicular", ex, String.Format("Reporte: Resumen Vehicular. Duración de la consulta: {0:##0.00} segundos", (DateTime.UtcNow - inicio).TotalSeconds)); throw; } }
public void It_should_not_throw_if_source_is_null() { SecurityExtensions.Clear((byte[])null); }
public void It_should_throw_if_values_are_null() { Assert.ThrowsException <ArgumentNullException>(() => SecurityExtensions.Xor(null, new byte[1])); Assert.ThrowsException <ArgumentNullException>(() => SecurityExtensions.Xor(new byte[1], null)); }
public void It_should_not_throw_if_source_is_empty() { SecurityExtensions.Clear(new byte[0]); }
public void It_should_not_throw_if_source_buffer_is_null() { SecurityExtensions.Clear((IBuffer)null); }
public void It_should_not_throw_if_source_buffer_is_empty() { SecurityExtensions.Clear(new Windows.Storage.Streams.Buffer(0)); }
protected override List <VehicleUtilization> GetResults() { return(ReportFactory.VehicleUtilizationDAO.GetMobileUtilizations(Convert.ToInt32((string)ddlMovil.SelectedValue), SecurityExtensions.ToDataBaseDateTime(dpDesde.SelectedDate.Value), SecurityExtensions.ToDataBaseDateTime(dpHasta.SelectedDate.Value))); }
protected override void OnSave() { using (var transaction = SmartTransaction.BeginTransaction()) { EditObject.Vehiculo = cbVehiculo.Selected > 0 ? DAOFactory.CocheDAO.FindById(cbVehiculo.Selected) : null; EditObject.Proveedor = cbProveedor.Selected > 0 ? DAOFactory.ProveedorDAO.FindById(cbProveedor.Selected) : null; EditObject.Deposito = cbDeposito.Selected > 0 ? DAOFactory.DepositoDAO.FindById(cbDeposito.Selected) : null; EditObject.DepositoDestino = cbDepositoDestino.Selected > 0 ? DAOFactory.DepositoDAO.FindById(cbDepositoDestino.Selected) : null; EditObject.Empleado = cbEmpleado.Selected > 0 ? DAOFactory.EmpleadoDAO.FindById(cbEmpleado.Selected) : null; EditObject.TipoMovimiento = (short)cbTipoMovimiento.Selected; EditObject.Estado = ConsumoCabecera.Estados.Pagado; EditObject.Fecha = dtFecha.SelectedDate.HasValue ? SecurityExtensions.ToDataBaseDateTime(dtFecha.SelectedDate.Value) : new DateTime(); int km; EditObject.KmDeclarados = int.TryParse(txtKilometros.Text, NumberStyles.Integer, CultureInfo.InvariantCulture, out km) ? km : 0; EditObject.NumeroFactura = txtFactura.Text; EditObject.ImporteTotal = Convert.ToDouble((string)txtImporte.Text.Replace(".", ",")); foreach (var cons in ParaBorrar) { var consumoDetalle = DAOFactory.ConsumoDetalleDAO.FindById(cons); if (EditObject.Deposito != null) { var stock = DAOFactory.StockDAO.GetByDepositoAndInsumo(EditObject.Deposito.Id, consumoDetalle.Insumo.Id); stock.Cantidad += consumoDetalle.Cantidad; DAOFactory.StockDAO.SaveOrUpdate(stock); } if (EditObject.DepositoDestino != null) { var stock = DAOFactory.StockDAO.GetByDepositoAndInsumo(EditObject.DepositoDestino.Id, consumoDetalle.Insumo.Id); stock.Cantidad -= consumoDetalle.Cantidad; DAOFactory.StockDAO.SaveOrUpdate(stock); } DAOFactory.ConsumoDetalleDAO.Delete(consumoDetalle); } var list = GetConsumosFromView(); EditObject.Detalles.Clear(); foreach (var consumoDetalleAux in list) { EditObject.Detalles.Add(consumoDetalleAux.ConsumoDetalle); ////// ACTUALIZAR STOCK ////// if (consumoDetalleAux.ConsumoDetalle.Cantidad != consumoDetalleAux.ConsumoAnterior) { if (EditObject.Deposito != null) { var stock = DAOFactory.StockDAO.GetByDepositoAndInsumo(EditObject.Deposito.Id, consumoDetalleAux.ConsumoDetalle.Insumo.Id); stock.Cantidad += consumoDetalleAux.ConsumoAnterior - consumoDetalleAux.ConsumoDetalle.Cantidad; DAOFactory.StockDAO.SaveOrUpdate(stock); if (stock.AlarmaActiva) { var msgSaver = new MessageSaver(DAOFactory); if (stock.Cantidad < stock.StockCritico) { msgSaver.Save(MessageIdentifier.StockCritic.ToString("d"), EditObject.Vehiculo, EditObject.Fecha, null, "Alarma Stock Crítico"); } else if (stock.Cantidad < stock.PuntoReposicion) { msgSaver.Save(MessageIdentifier.StockReposition.ToString("d"), EditObject.Vehiculo, EditObject.Fecha, null, "Alarma Reposición de Stock"); } } } if (EditObject.DepositoDestino != null) { var stock = DAOFactory.StockDAO.GetByDepositoAndInsumo(EditObject.DepositoDestino.Id, consumoDetalleAux.ConsumoDetalle.Insumo.Id) ?? new Stock { Deposito = EditObject.DepositoDestino, Insumo = consumoDetalleAux.ConsumoDetalle.Insumo }; stock.Cantidad += consumoDetalleAux.ConsumoDetalle.Cantidad - consumoDetalleAux.ConsumoAnterior; DAOFactory.StockDAO.SaveOrUpdate(stock); } } ////// ACTUALIZAR PRECIO ////// var insumo = consumoDetalleAux.ConsumoDetalle.Insumo; insumo.ValorReferencia = consumoDetalleAux.ConsumoDetalle.ImporteUnitario; DAOFactory.InsumoDAO.SaveOrUpdate(insumo); } DAOFactory.ConsumoCabeceraDAO.SaveOrUpdate(EditObject); if (EditObject.Vehiculo != null) { VerificarOdometros(EditObject.Vehiculo); } transaction.Commit(); } }