Beispiel #1
0
        public Boolean alterarFuncionario(Funcionario objFuncionarioAlterar)
        {
            try
            {
                if (!temDuplicidade(objFuncionarioAlterar, "Alterar"))
                {
                    db = ServidorSingleton.obterServidor().OpenClient();
                    Funcionario objFuncionarioProt = FactoryClasses.criarFuncionario();
                    objFuncionarioProt.Codigo = objFuncionarioAlterar.Codigo;
                    IObjectSet leitor = db.QueryByExample(objFuncionarioProt);
                    if (leitor.HasNext())
                    {
                        Funcionario objFuncionario = (Funcionario)leitor.Next();
                        //Atribui o cargo
                        IObjectSet leitorCargo = db.QueryByExample(objFuncionarioAlterar.Cargo);
                        if (leitorCargo.HasNext())
                        {
                            Cargo objCargo = (Cargo)leitorCargo.Next();
                            objFuncionario.Cargo = objCargo;
                        }
                        leitorCargo = null;

                        objFuncionario.DataAdmissao = objFuncionarioAlterar.DataAdmissao;
                        objFuncionario.DataDemissao = objFuncionarioAlterar.DataDemissao;
                        objFuncionario.Email = objFuncionarioAlterar.Email;
                        objFuncionario.Login = objFuncionarioAlterar.Login;
                        objFuncionario.Nome = objFuncionarioAlterar.Nome;
                        objFuncionario.Senha = objFuncionarioAlterar.Senha;
                        objFuncionario.Telefone = objFuncionarioAlterar.Telefone;
                        db.Store(objFuncionario);
                        db.Commit();
                        leitor = null;
                        return true;
                    }
                    else
                    {
                        leitor = null;
                        return false;
                    }

                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                db.Rollback();
                throw new Exception("Erro atualizando o funcionario :" + ex.ToString());
            }
            finally
            {
                db.Close();
                db.Dispose();
            }
        }
Beispiel #2
0
        public Boolean alterarFilme(clsFilme objAtualizar)
        {
            try
            {
                db = ServidorSingleton.obterServidor().OpenClient();
                clsFilme filmeBuscar = new clsFilme();
                filmeBuscar.Codigo = objAtualizar.Codigo;
                IObjectSet leitor = db.QueryByExample(filmeBuscar);
                if (leitor.HasNext())
                {
                    clsFilme objFilme = (clsFilme)leitor.Next();
                    objFilme.Ano = objAtualizar.Ano;
                    objFilme.Avaliacao = objAtualizar.Avaliacao;
                    objFilme.TituloBr = objAtualizar.TituloBr;
                    objFilme.TituloOriginal = objAtualizar.TituloOriginal;

                    IObjectSet leitorGenero = db.QueryByExample(objAtualizar.Genero);
                    if (leitorGenero.HasNext()) {
                        objFilme.Genero = (clsGenero)leitorGenero.Next();
                    }
                    leitorGenero = null;

                    IObjectSet leitorStatus = db.QueryByExample(objAtualizar.Status);
                    if (leitorStatus.HasNext())
                    {
                        objFilme.Status = (clsStatus)leitorStatus.Next();
                    }
                    leitorStatus = null;

                    db.Store(objFilme);
                    db.Commit();
                    return true;
                }
                else
                {
                    return false;
                }
                leitor = null;
            }
            catch (Exception ex)
            {
                db.Rollback();
                throw new Exception("Erro atualizando o filme :" + ex.ToString());
            }
            finally {
                db.Close();
                db.Dispose();
            }
        }
        public EditAuthorWindow(ref IObjectContainer db, Author author)
        {
            InitializeComponent();
            _db = db;
            _author = author;
            Title += _author.LastName;

            // fill form
            LastNameTxtBox.Text = _author.LastName;
            BirthDatepicker.SelectedDate = _author.BirthDate;

            var collection = new ObservableCollection<PublicationEditableGrid>();
            foreach (var item in _db.QueryByExample(new Publication()))
            {
                var itemPub = item as Publication;
                collection.Add(new PublicationEditableGrid()
                {
                    Title = itemPub.Title,
                    Year = itemPub.Year,
                    IsAuthor = _author.Publications.Contains(itemPub)
                });
            }
            publicationsGrid.ItemsSource = collection.OrderBy(x => x.Title);
            publicationsGrid.SelectedItem = null;
        }
Beispiel #4
0
        public Boolean alterarStatus(clsStatus objAtualizar)
        {
            try
            {
                if (!temDuplicidade(objAtualizar, "Alterar"))
                {
                    clsStatus objStatusBuscar = new clsStatus();

                    objStatusBuscar.Codigo = objAtualizar.Codigo;
                    db = ServidorSingleton.obterServidor().OpenClient();
                    IObjectSet leitor = db.QueryByExample(objStatusBuscar);

                    clsStatus objStatus = (clsStatus)leitor.Next();
                    objStatus.Descricao = objAtualizar.Descricao;
                    db.Store(objStatus);
                    db.Commit();
                    db.Close();
                    db.Dispose();
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Erro atualizando o status :" + ex.ToString());
            }
        }
Beispiel #5
0
		public static void ClearDatabase(IObjectContainer db)
		{
			IObjectSet result = db.QueryByExample(typeof(Pilot));
			while (result.HasNext())
			{
				db.Delete(result.Next());
			}
		}
Beispiel #6
0
		public static void DeleteAll(IObjectContainer db) 
		{
			IObjectSet result = db.QueryByExample(typeof(Object));
			foreach (object item in result)
			{
				db.Delete(item);
			}
		}		
Beispiel #7
0
        private static void AllObjectsOfAType(IObjectContainer container)
        {
            // #example: All objects of a type by passing the type
            IList result = container.QueryByExample(typeof (Pilot));
            // #end example

            ListResult(result);
        }
Beispiel #8
0
 public static void RetrieveAllSnapshots(IObjectContainer db)
 {
     IObjectSet result = db.QueryByExample(typeof(SensorReadout));
     while (result.HasNext())
     {
         Console.WriteLine(result.Next());
     }
 }
Beispiel #9
0
        private static void AllObjects(IObjectContainer container)
        {
            // #example: All objects
            IList result = container.QueryByExample(null);
            // #end example

            ListResult(result);
        }
Beispiel #10
0
 public static void RetrieveCarByPilotQBE(IObjectContainer db)
 {
     Pilot pilotproto = new Pilot("Rubens Barrichello", 0);
     Car carproto = new Car(null);
     carproto.Pilot = pilotproto;
     IObjectSet result = db.QueryByExample(carproto);
     ListResult(result);
 }
Beispiel #11
0
 public static void UpdatePilot(IObjectContainer db)
 {
     IObjectSet result = db.QueryByExample(new Pilot("Michael Schumacher", 0));
     Pilot found = (Pilot)result.Next();
     found.AddPoints(11);
     db.Store(found);
     Console.WriteLine("Added 11 points for {0}", found);
     RetrieveAllPilots(db);
 }
Beispiel #12
0
 public static void CarSnapshotRollback(IObjectContainer db)
 {
     IObjectSet result = db.QueryByExample(new Car("BMW"));
     Car car = (Car)result.Next();
     car.Snapshot();
     db.Store(car);
     db.Rollback();
     Console.WriteLine(car);
 }
Beispiel #13
0
		public static void RetrieveCarQBE(IObjectContainer db)
		{
			SensorReadout protoReadout = new SensorReadout(new double[] { 0.6, 0.2 }, DateTime.MinValue, null);
			IList protoHistory = new ArrayList();
			protoHistory.Add(protoReadout);
			Car protoCar = new Car(null, protoHistory);
			IObjectSet result = db.QueryByExample(protoCar);
			ListResult(result);
		}
Beispiel #14
0
        private static void QueryForAge(IObjectContainer container)
        {
            // #example: Query for 33 year old pilots
            Pilot theExample = new Pilot();
            theExample.Age = 33;
            IList result = container.QueryByExample(theExample);
            // #end example

            ListResult(result);
        }
Beispiel #15
0
        private static void QueryForName(IObjectContainer container)
        {
            // #example: Query for John by example
            Pilot theExample = new Pilot();
            theExample.Name = "John";
            IList result = container.QueryByExample(theExample);
            // #end example

            ListResult(result);
        }
 public static void RetrieveSnapshotsSequentially(IObjectContainer db)
 {
     IObjectSet result = db.QueryByExample(typeof (Car));
     Car car = (Car) result.Next();
     SensorReadout readout = car.History;
     while (readout != null)
     {
         Console.WriteLine(readout);
         readout = readout.Next;
     }
 }
Beispiel #17
0
        private static void QueryForNameAndAge(IObjectContainer container)
        {
            // #example: Query a 29 years old Jo
            Pilot theExample = new Pilot();
            theExample.Name = "Jo";
            theExample.Age = 29;
            IList result = container.QueryByExample(theExample);
            // #end example

            ListResult(result);
        }
        public Boolean atualizarSolicitacao(SolicitacaoMateriais objSolicitacao)
        {
            SolicitacaoMateriais objSolicitacaoProt = FactoryClasses.criarSolicitacaoMateriais();
            objSolicitacaoProt.Codigo = objSolicitacao.Codigo;
            try
            {
                db = ServidorSingleton.obterServidor().OpenClient();
                IObjectSet leitor = db.QueryByExample(objSolicitacaoProt);
                if (leitor.HasNext())
                {
                    SolicitacaoMateriais objSolicitacaoCache = (SolicitacaoMateriais)leitor.Next();
                    objSolicitacaoCache.GestorObra = objSolicitacao.GestorObra;

                    int i = 0;
                    foreach (Materiais material in objSolicitacaoCache.Materiais) {
                        if (material.Codigo == objSolicitacao.Codigo) {
                            Fornecedor objFornecedor = FactoryClasses.criarFornecedor();
                            objFornecedor.Codigo = objSolicitacao.Materiais[i].Fornecedor.Codigo;
                            material.Fornecedor = objFornecedor;
                        }
                        i++;
                    }

                    objSolicitacaoCache.Materiais = objSolicitacao.Materiais;
                    objSolicitacaoCache.Status = objSolicitacao.Status;
                    objSolicitacaoCache.DataEntrega = objSolicitacao.DataEntrega;
                    objSolicitacaoCache.NumNotaFiscal = objSolicitacao.NumNotaFiscal;
                    objSolicitacaoCache.DataEntrega = objSolicitacao.DataEntrega;
                    objSolicitacaoCache.Msg = objSolicitacao.Msg;
                    db.Store(objSolicitacaoCache);
                    db.Commit();
                    db.Close();
                    db.Dispose();
                    return true;
                }
                else
                {
                    db.Close();
                    db.Dispose();
                    return false;
                }
            }
            catch (Exception e)
            {
                db.Rollback();
                db.Close();
                db.Dispose();
                throw new Exception("Erro atualizando a solicitação :" + e.Message);
            }
        }
Beispiel #19
0
 private Boolean temDuplicidadeEng(EngenheiroCampo objEng)
 {
     bool retorno;
     db = ServidorSingleton.obterServidor().OpenClient();
     IObjectSet leitor = db.QueryByExample(objEng);
     if (leitor.HasNext())
     {
         retorno = true;
     }
     else
     {
         retorno = false;
     }
     leitor = null;
     return retorno;
 }
Beispiel #20
0
        public Boolean alterarFornecedor(Fornecedor objFornecedorAtualizar)
        {
            try
            {
                if (!temDuplicidade(objFornecedorAtualizar, "Alterar"))
                {
                    db = ServidorSingleton.obterServidor().OpenClient();
                    Fornecedor objFornecedorPrototipo = FactoryClasses.criarFornecedor();
                    objFornecedorPrototipo.Codigo = objFornecedorAtualizar.Codigo;
                    IObjectSet leitor = db.QueryByExample(objFornecedorPrototipo);
                    if (leitor.HasNext())
                    {
                        Fornecedor objFornecedor = (Fornecedor)leitor.Next();
                        objFornecedor.Cidade = objFornecedorAtualizar.Cidade;
                        objFornecedor.Cnpj = objFornecedorAtualizar.Cnpj;
                        objFornecedor.Email = objFornecedorAtualizar.Email;
                        objFornecedor.Endereco = objFornecedorAtualizar.Endereco;
                        objFornecedor.InscrEstadual = objFornecedorAtualizar.InscrEstadual;
                        objFornecedor.RazaoSocial = objFornecedorAtualizar.RazaoSocial;
                        db.Store(objFornecedor);
                        db.Commit();
                        leitor = null;
                        return true;
                    }
                    else
                    {
                        leitor = null;
                        return false;
                    }

                }
                else {
                    return false;
                }
            }
            catch (Exception ex)
            {
                db.Rollback();
                throw new Exception("Erro atualizando o fornecedor :" + ex.ToString());
            }
            finally
            {
                db.Close();
                db.Dispose();
            }
        }
        public AddAuthorWindow(ref IObjectContainer db)
        {
            InitializeComponent();
            _db = db;

            var collection = new ObservableCollection<PublicationEditableGrid>();
            foreach (var item in _db.QueryByExample(new Publication()))
            {
                var itemPub = item as Publication;
                collection.Add(new PublicationEditableGrid()
                {
                    Title = itemPub.Title,
                    Year = itemPub.Year,
                    IsAuthor = false
                });
            }
            publicationsGrid.ItemsSource = collection.OrderBy(x => x.Title);
            publicationsGrid.SelectedItem = null;
        }
Beispiel #22
0
        public ProxyAuthenticator ReturnProxyAuthenticationInfo()
        {
            try
            {
                if (Db4oClient.RecentConnFile == null)
                {
                	Db4oClient.RecentConnFile = Config.OMNConfigDatabasePath();
                }
                _container = Db4oClient.RecentConn;
                IObjectSet ObjSet = _container.QueryByExample(typeof(ProxyAuthenticator));
            	
				return ObjSet.Count > 0 ? (ProxyAuthenticator) ObjSet.Next() : null;
            }
            catch (Exception e)
            {
                LoggingHelper.HandleException(e);
                return null;
            }
        }
Beispiel #23
0
        public Boolean alterarCliente(Cliente objClienteAtualizar)
        {
            try
            {
                if (!temDuplicidade(objClienteAtualizar, "Alterar"))
                {
                    db = ServidorSingleton.obterServidor().OpenClient();

                    Cliente objClientePrototipo = FactoryClasses.criarCliente();
                    objClientePrototipo.Codigo = objClienteAtualizar.Codigo;
                    IObjectSet leitor = db.QueryByExample(objClientePrototipo);
                    if (leitor.HasNext())
                    {
                        Cliente objCliente = (Cliente)leitor.Next();
                        objCliente.Cnpj = objClienteAtualizar.Cnpj;
                        objCliente.Nome = objClienteAtualizar.Nome;
                        db.Store(objCliente);
                        db.Commit();
                        leitor = null;
                        return true;
                    }
                    else
                    {
                        leitor = null;
                        return false;
                    }

                }
                else {
                    return false;
                }
            }
            catch (Exception ex)
            {
                db.Rollback();
                throw new Exception("Erro atualizando o cliente :" + ex.ToString());
            }
            finally
            {
                db.Close();
                db.Dispose();
            }
        }
        public EditPublicationWindow(ref IObjectContainer db, dynamic publication)
        {
            InitializeComponent();
            TypeCombo.ItemsSource = StaticData.publicationTypes;
            _db = db;
            _publication = publication;
            _isBook = _publication is Book;
            Title += _publication.Title;

            // fill form
            TitleTxtBox.Text = _publication.Title;
            PublisherTxtBox.Text = _publication.Publisher;
            YearTxtBox.Text = _publication.Year.ToString();
            if (_isBook)
            {
                TypeCombo.SelectedIndex = 1;
                PriceTxtBox.Text = _publication.Price.ToString();
                PageFromTxtBox.Text = String.Empty;
                PageToTxtBox.Text = String.Empty;
            } else {
                TypeCombo.SelectedIndex = 0;
                PriceTxtBox.Text = String.Empty;
                PageFromTxtBox.Text = _publication.PageFrom.ToString();
                PageToTxtBox.Text = _publication.PageTo.ToString();
            }
            TypeCombo.IsEnabled = false;
            toggleTxtBoxesVisibility();

            var collection = new ObservableCollection<AuthorEditableGrid>();
            foreach (var item in _db.QueryByExample(new Author()))
            {
                var itemAut = item as Author;
                collection.Add(new AuthorEditableGrid()
                {
                    LastName = itemAut.LastName,
                    BirthDate = itemAut.BirthDate.ToShortDateString(),
                    IsPublication = _publication.Authors.Contains(itemAut)
                });
            }
            authorsGrid.ItemsSource = collection.OrderBy(x => x.LastName);
            authorsGrid.SelectedItem = null;
        }
        public AddPublicationWindow(ref IObjectContainer db)
        {
            InitializeComponent();
            TypeCombo.ItemsSource = StaticData.publicationTypes;
            _db = db;

            var collection = new ObservableCollection<AuthorEditableGrid>();
            foreach (var item in _db.QueryByExample(new Author()))
            {
                var itemAut = item as Author;
                collection.Add(new AuthorEditableGrid()
                {
                    LastName = itemAut.LastName,
                    BirthDate = itemAut.BirthDate.ToShortDateString(),
                    IsPublication = false
                });
            }
            authorsGrid.ItemsSource = collection.OrderBy(x => x.LastName);
            authorsGrid.SelectedItem = null;
        }
Beispiel #26
0
 static EventHandler<CancellableObjectEventArgs> IncrementIds(IObjectServer server, IObjectContainer container)
 {
     // mostly taken from Tuna Toksoz' excellent article at http://tunatoksoz.com/post/Id-Generation-for-db4o.aspx
      return (sender, args) =>
            {
               var entity = args.Object as Entity;
               if (entity != null)
               {
                  var set = container.QueryByExample(new IncrementTypeValuePair {Type = args.Object.GetType()});
                  IncrementTypeValuePair pair;
                  if (set.Count == 0)
                     pair = new IncrementTypeValuePair {Type = args.Object.GetType()};
                  else
                     pair = (IncrementTypeValuePair) set[0];
                  entity.Id = ++pair.Value;
                  var client = server.OpenClient();
                  client.Store(pair);
                  client.Commit();
               }
            };
 }
Beispiel #27
0
 public clsFilme listarFilmePorCodigo(clsFilme objFilme)
 {
     db = ServidorSingleton.obterServidor().OpenClient();
     try
     {
         IObjectSet leitor = db.QueryByExample(objFilme);
         if (leitor.HasNext())
         {
             return (clsFilme)leitor.Next();
         }
         else {
             return null;
         }
     }
     catch(Exception ex) {
         throw new Exception("Erro obtendo os dados do filme :" + ex.ToString());
     }
 }
Beispiel #28
0
        private bool historyAES()
        {
            try
            {
                ArrayList parts = new ArrayList();

                try
                {
                    banco.Close();
                }
                catch (Exception)
                {
                }
                finally
                {
                    banco = Db4oFactory.OpenFile(caminhoBanco);
                }

                dataGridViewAES.Rows.Clear();
                //Usuario new_user = new Usuario();
                //new_user.nome = usuario.nome;

                IObjectSet retorno = banco.QueryByExample(usuario);
                string     msg     = "";
                bool       exists  = false;

                if (retorno.HasNext())
                {
                    Usuario tmp = (Usuario)retorno.Next();
                    if (!String.IsNullOrEmpty(tmp.historicoAES))
                    {
                        msg    = tmp.historicoAES;
                        exists = true;
                    }
                }

                if (exists == true)
                {
                    foreach (string splitado in msg.Split('ק'))
                    {
                        parts.Add(splitado);
                    }


                    for (int i = 0; i < parts.Count; i++)
                    {
                        dataGridViewAES.Rows.Add(parts[i], parts[i + 1], parts[i + 2], parts[i + 3]);
                        i += 3;
                    }

                    parts.Clear();
                    banco.Close();
                    return(true);
                }
                else
                {
                    if (contador_entra == 0)
                    {
                        contador_entra++;
                        banco.Close();
                        return(false);
                    }
                    else
                    {
                        banco.Close();
                        MessageBox.ShowMessageBoxOK("warning", "Não há atividades registradas no AES!", "Histórico vazio", DarkTheme);
                        return(false);
                    }
                }
            }
            catch (Exception)
            {
                return(false);
            }
        }
Beispiel #29
0
        public static void UpdatePhone()
        {
            IEmbeddedConfiguration config = Db4oEmbedded.NewConfiguration();

            config.Common.ObjectClass(typeof(Person)).CascadeOnUpdate(true);
            using (IObjectContainer db = Db4oEmbedded.OpenFile(config, @"C:\DBO\ODB.yap"))
            {
                string userSurename;

                Console.WriteLine("\nInsert person surename who phone You want modificate: \n");

                userSurename = Console.ReadLine();

                string TempPhoneNumber;

                Console.WriteLine("\nSelect phone witch You want modificate by number: \n");

                Console.WriteLine("Number: \n");
                TempPhoneNumber = Console.ReadLine();

                string forStoreNumber = "";


                IObjectSet result = db.QueryByExample(new Person(null, userSurename, new Address(null, null, null), new Phone(null, null, null)));
                Person     found;

                if (result.HasNext())
                {
                    found = (Person)result.Next();

                    foreach (Phone phones in found.PersonPhones.Where(x => x.Number == TempPhoneNumber))
                    {
                        Console.Write("Person phone - Number: ");
                        phones.Number  = Console.ReadLine().ToString();
                        forStoreNumber = phones.Number;

                        Console.Write("Person phone - Operator: ");
                        phones.Operator = Console.ReadLine().ToString();

                        Console.Write("Person phone - Phone type: ");
                        phones.PhoneType = Console.ReadLine().ToString();
                    }

                    foreach (var item in found.PersonPhones)
                    {
                        Console.WriteLine(item.Number);
                    }



                    db.Activate(found, 100);



                    db.Store(found.PersonPhones.Find(x => x.Number == forStoreNumber));
                }
                else
                {
                    Console.WriteLine("\nThis peron don't exist in database");
                }
            }
        }
Beispiel #30
0
        public virtual void Update(T entidade)
        {
            Type tipo = typeof(T);

            string nomeProprieadeID   = getNomePropriedadeID <T>();
            string nomeProprieadeGUID = getNomePropriedadeGUID <T>();

            IObjectContainer db = Db4oFactory.OpenFile(nomeBanco);

            try
            {
                if (!string.IsNullOrEmpty(nomeProprieadeID))
                {
                    var properties = tipo.GetProperties();

                    PropertyInfo propertyInfo = properties.FirstOrDefault(x => x.Name.Equals(nomeProprieadeID));

                    var id = (int)propertyInfo.GetValue(entidade, null);

                    var instanceQuery = (T)defineInstanciaID(id, tipo, nomeProprieadeID);

                    //atualizar(entidade, properties, instanceQuery);

                    IObjectSet result = db.QueryByExample(instanceQuery);
                    var        found  = (T)result.Next();

                    foreach (var propInfo in properties)
                    {
                        var v = propInfo.GetValue(entidade, null);
                        propInfo.SetValue(found, v, null);
                    }

                    db.Store(found);
                }
                else if (!string.IsNullOrEmpty(nomeProprieadeGUID))
                {
                    var properties = tipo.GetProperties();

                    PropertyInfo propertyInfo = properties.FirstOrDefault(x => x.Name.Equals(nomeProprieadeGUID));

                    var guid = (string)propertyInfo.GetValue(entidade, null);


                    var instanceQuery = (T)defineInstanciaGuid(guid, tipo, nomeProprieadeGUID);

                    IObjectSet result = db.QueryByExample(instanceQuery);
                    var        found  = (T)result.Next();

                    foreach (var propInfo in properties)
                    {
                        var v = propInfo.GetValue(entidade, null);
                        propInfo.SetValue(found, v, null);
                    }

                    db.Store(found);
                }
            }
            catch (Exception ex)
            {
                db.Rollback();

                throw new Exception("Erro ao inserir entidade: " + ex.Message);
            }
            finally
            {
                db.Close();
            }
        }
Beispiel #31
0
        private void tbcMenuHistorico_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tbcMenuHistorico.SelectedIndex == 2)
            {
                try
                {
                    banco.Close();
                }
                finally
                {
                    banco = Db4oFactory.OpenFile(caminhoBanco);
                }

                dgvHistoricoRSA.Rows.Clear();
                IObjectSet pesquisar = banco.QueryByExample(usuario);
                if (pesquisar.HasNext())
                {
                    Usuario usuarioRSA = (Usuario)pesquisar.Next();

                    if (String.IsNullOrEmpty(usuarioRSA.historicoRSA))
                    {
                        MessageBox.ShowMessageBoxOK("warning", "Não há atividades registradas no RSA!", "Histórico vazio", DarkTheme);
                        return;
                    }

                    for (int pos = 0; pos < 4; pos++)
                    {
                        teste[pos] = "";
                    }

                    for (int i = 0; i < usuarioRSA.historicoRSA.Length; i++)
                    {
                        if (!usuarioRSA.historicoRSA[i].Equals('ק'))
                        {
                            write += usuarioRSA.historicoRSA[i];
                        }
                        else
                        {
                            for (int index = 0; index < 4; index++)
                            {
                                if (teste[index].Equals(""))
                                {
                                    teste[index] = write;
                                    write        = "";
                                }
                            }

                            cont = 0;
                            for (int index = 0; index < 4; index++)
                            {
                                if (!teste[index].Equals(""))
                                {
                                    cont++;
                                }
                            }

                            if (cont == 4)
                            {
                                dgvHistoricoRSA.Rows.Add(teste);
                                for (int pos = 0; pos < 4; pos++)
                                {
                                    teste[pos] = "";
                                }
                                teste[0] = write;
                                write    = "";
                            }
                        }
                    }
                    banco.Close();
                }
            }
            if (tbcMenuHistorico.SelectedIndex == 3)
            {
                try
                {
                    banco.Close();
                }
                finally
                {
                    banco = Db4oFactory.OpenFile(caminhoBanco);
                }


                dgvHistoricoEsteganografia.Rows.Clear();
                IObjectSet pesquisar = banco.QueryByExample(usuario);
                if (pesquisar.HasNext())
                {
                    Usuario usuarioEsteganografia = (Usuario)pesquisar.Next();

                    if (String.IsNullOrEmpty(usuarioEsteganografia.historicoEsteganografia))
                    {
                        banco.Close();
                        MessageBox.ShowMessageBoxOK("warning", "Não há atividades registradas na Esteganografia!", "Histórico vazio", DarkTheme);
                        return;
                    }

                    for (int pos = 0; pos < 4; pos++)
                    {
                        teste[pos] = "";
                    }

                    for (int i = 0; i < usuarioEsteganografia.historicoEsteganografia.Length; i++)
                    {
                        if (!usuarioEsteganografia.historicoEsteganografia[i].Equals('ק'))
                        {
                            write += usuarioEsteganografia.historicoEsteganografia[i];
                        }
                        else
                        {
                            for (int index = 0; index < 4; index++)
                            {
                                if (teste[index].Equals(""))
                                {
                                    teste[index] = write;
                                    write        = "";
                                }
                            }

                            cont = 0;
                            for (int index = 0; index < 4; index++)
                            {
                                if (!teste[index].Equals(""))
                                {
                                    cont++;
                                }
                            }

                            if (cont == 4)
                            {
                                dgvHistoricoEsteganografia.Rows.Add(teste);
                                for (int pos = 0; pos < 4; pos++)
                                {
                                    teste[pos] = "";
                                }
                                teste[0] = write;
                                write    = "";
                            }
                            banco.Close();
                        }
                    }
                }
            }
            if (tbcMenuHistorico.SelectedIndex == 0)
            {
                if (!historyAES())
                {
                    return;
                }
            }

            if (tbcMenuHistorico.SelectedIndex == 1)
            {
                // AES COM ARQUIVO
                if (!historyAESArquivo())
                {
                    return;
                }
            }
            if (tbcMenuHistorico.SelectedIndex == 4)
            {
                try
                {
                    banco.Close();
                }
                finally
                {
                    banco = Db4oFactory.OpenFile(caminhoBanco);
                }

                dgvCesar.Rows.Clear();
                IObjectSet procurar = banco.QueryByExample(usuario);
                if (procurar.HasNext())
                {
                    Usuario usuarioCesar = (Usuario)procurar.Next();

                    if (String.IsNullOrEmpty(usuarioCesar.historicoCesar))
                    {
                        banco.Close();
                        MessageBox.ShowMessageBoxOK("warning", "Não foi salva nenhuma atividade em Cifra de Cesar!!", "Histórico vazio", DarkTheme);
                        return;
                    }
                    for (int pos = 0; pos < 5; pos++)
                    {
                        teste2[pos] = "";
                    }

                    for (int i = 0; i < usuarioCesar.historicoCesar.Length; i++)
                    {
                        if (!usuarioCesar.historicoCesar[i].Equals('ק'))
                        {
                            write += usuarioCesar.historicoCesar[i];
                        }
                        else
                        {
                            for (int index = 0; index < 5; index++)
                            {
                                if (teste2[index].Equals(""))
                                {
                                    teste2[index] = write;
                                    write         = "";
                                }
                            }

                            cont = 0;
                            for (int index = 0; index < 5; index++)
                            {
                                if (!teste2[index].Equals(""))
                                {
                                    cont++;
                                }
                            }

                            if (cont == 5)
                            {
                                dgvCesar.Rows.Add(teste2);
                                for (int pos = 0; pos < 5; pos++)
                                {
                                    teste2[pos] = "";
                                }
                                teste2[0] = write;
                                write     = "";
                            }
                            banco.Close();
                        }
                    }
                }
            }
            if (tbcMenuHistorico.SelectedIndex == 5)
            {
                try
                {
                    banco.Close();
                }
                finally
                {
                    banco = Db4oFactory.OpenFile(caminhoBanco);
                }

                dgvMorse.Rows.Clear();
                IObjectSet procurar = banco.QueryByExample(usuario);
                if (procurar.HasNext())
                {
                    Usuario usuarioMorse = (Usuario)procurar.Next();

                    if (String.IsNullOrEmpty(usuarioMorse.historicoMorse))
                    {
                        banco.Close();
                        MessageBox.ShowMessageBoxOK("warning", "Não foi salva nenhuma atividade em Código Morse!!", "Histórico vazio", DarkTheme);
                        return;
                    }
                    for (int pos = 0; pos < 4; pos++)
                    {
                        teste[pos] = "";
                    }

                    for (int i = 0; i < usuarioMorse.historicoMorse.Length; i++)
                    {
                        if (!usuarioMorse.historicoMorse[i].Equals('ק'))
                        {
                            write += usuarioMorse.historicoMorse[i];
                        }
                        else
                        {
                            for (int index = 0; index < 4; index++)
                            {
                                if (teste[index].Equals(""))
                                {
                                    teste[index] = write;
                                    write        = "";
                                }
                            }

                            cont = 0;
                            for (int index = 0; index < 4; index++)
                            {
                                if (!teste[index].Equals(""))
                                {
                                    cont++;
                                }
                            }

                            if (cont == 4)
                            {
                                dgvMorse.Rows.Add(teste);
                                for (int pos = 0; pos < 4; pos++)
                                {
                                    teste[pos] = "";
                                }
                                teste[0] = write;
                                write    = "";
                            }
                            banco.Close();
                        }
                    }
                }
            }
        }
Beispiel #32
0
        public static void RetrieveAllSensorReadoutsQBEAlternative(IObjectContainer db)
        {
            IObjectSet result = db.QueryByExample(typeof(SensorReadout));

            ListResult(result);
        }
Beispiel #33
0
        private void btnEnviar_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(txtEmail.Text))
            {
                MessageBox.ShowMessageBoxOK("warning", "Insira um endereço de e-mail", "Aviso", DarkTheme);
                return;
            }
            else
            {
                if (!cboxEmail.Checked)
                {
                    Usuario usuario = new Usuario();
                    usuario.email = txtEmail.Text;
                    IObjectSet pesquisa = banco.QueryByExample(usuario);
                    if (pesquisa.HasNext())
                    {
                        usuario = (Usuario)pesquisa.Next();
                        //Gerar senha aleatoria
                        for (int i = 0; i < 5; i++)
                        {
                            novaSenha += Convert.ToChar(gerador.Next(65, 90));
                            novaSenha += gerador.Next(0, 10).ToString();
                        }

                        MD5           md5     = MD5.Create();
                        byte[]        hash    = md5.ComputeHash(Encoding.UTF8.GetBytes(novaSenha));
                        StringBuilder stringg = new StringBuilder();
                        for (int i = 0; i < hash.Length; i++)
                        {
                            stringg.Append(hash[i].ToString("x2")); // hexa
                        }
                        usuario.senha = stringg.ToString();
                        banco.Store(usuario);
                        informacoes = "Informações da conta" +
                                      "\n" +
                                      "\nNome    : " + usuario.nome +
                                      "\nUsuario : " + usuario.usuario +
                                      "\n" +
                                      "\nAbaixo está sua nova senha, utilize-a para" +
                                      "\nfazer login e altere-a no Menu Principal" +
                                      "\n" +
                                      "\nNova senha : " + novaSenha;
                    }
                    else
                    {
                        MessageBox.ShowMessageBoxOK("warning", "Este e-mail não está cadastrado", "Aviso", DarkTheme);
                        txtEmail.Focus();
                        return;
                    }
                }
                else
                {
                    if (String.IsNullOrEmpty(txtNome.Text))
                    {
                        MessageBox.ShowMessageBoxOK("warning", "Você deve digitar um nome!", "Aviso", DarkTheme);
                        txtNome.Focus();
                        return;
                    }
                    Usuario usuario = new Usuario();
                    usuario.nome = txtNome.Text;
                    IObjectSet pesquisa = banco.QueryByExample(usuario);
                    if (pesquisa.HasNext())
                    {
                        usuario = (Usuario)pesquisa.Next();
                        //Gerar senha aleatoria
                        for (int i = 0; i < 5; i++)
                        {
                            novaSenha += Convert.ToChar(gerador.Next(65, 90));
                            novaSenha += gerador.Next(0, 10).ToString();
                        }

                        MD5           md5     = MD5.Create();
                        byte[]        hash    = md5.ComputeHash(Encoding.UTF8.GetBytes(novaSenha));
                        StringBuilder stringg = new StringBuilder();
                        for (int i = 0; i < hash.Length; i++)
                        {
                            stringg.Append(hash[i].ToString("x2")); // hexa
                        }
                        usuario.senha = stringg.ToString();
                        banco.Store(usuario);
                        informacoes = "Informações da conta" +
                                      "\n" +
                                      "\nNome    : " + usuario.nome +
                                      "\nUsuario : " + usuario.usuario +
                                      "\n" +
                                      "\nAbaixo está sua nova senha, utilize-a para" +
                                      "\nfazer login e altere-a no Menu Principal" +
                                      "\n" +
                                      "\nNova senha : " + novaSenha;
                    }
                    else
                    {
                        MessageBox.ShowMessageBoxOK("warning", "Este nome não está cadastrado", "Aviso", DarkTheme);
                        return;
                    }
                }


                try
                {
                    MailMessage email = new MailMessage();
                    email.From = new MailAddress("*****@*****.**");
                    email.To.Add(new MailAddress(txtEmail.Text));
                    email.Subject = "iCrypto: Informações da conta e nova senha";
                    email.Body    = informacoes;
                    SmtpClient cliente = new SmtpClient("smtp.live.com", 587);
                    using (cliente)
                    {
                        cliente.Credentials = new System.Net.NetworkCredential("*****@*****.**", "projeto1osemestre2020criptografia");
                        cliente.EnableSsl   = true;
                        cliente.Send(email);
                    }
                    MessageBox.ShowMessageBoxOK("warning", "E-mail enviado com sucesso!", "Aviso", DarkTheme);
                    banco.Close();
                    this.Close();
                }
                catch (Exception erro)
                {
                    MessageBox.ShowMessageBoxOK("null", erro.Message, "", DarkTheme);
                }
            }
        }
Beispiel #34
0
        public static void UpdateAddress()
        {
            IEmbeddedConfiguration config = Db4oEmbedded.NewConfiguration();

            config.Common.ObjectClass(typeof(Person)).CascadeOnUpdate(true);
            using (IObjectContainer db = Db4oEmbedded.OpenFile(config, @"C:\DBO\ODB.yap"))
            {
                string userSurename;

                Console.WriteLine("\nInsert person surename who address You want modificate: \n");

                userSurename = Console.ReadLine();

                string TempAddressCity;
                string TempAddressStreet;

                Console.WriteLine("\nSelect address witch You want modificate by city and street: \n");

                Console.WriteLine("Street: \n");
                TempAddressStreet = Console.ReadLine();
                Console.WriteLine("City: \n");
                TempAddressCity = Console.ReadLine();

                string forStoreStreet = "";
                string forStoreCity   = "";

                IObjectSet result = db.QueryByExample(new Person(null, userSurename, new Address(null, null, null), new Phone(null, null, null)));
                Person     found;

                if (result.HasNext())
                {
                    found = (Person)result.Next();

                    foreach (Address address in found.PersonAddresses.Where((x => x.City == TempAddressCity)).Where((x => x.Street == TempAddressStreet)))
                    {
                        Console.Write("Person address - Street: ");
                        address.Street = Console.ReadLine().ToString();
                        forStoreStreet = address.Street;

                        Console.Write("Person address - City: ");
                        address.City = Console.ReadLine().ToString();
                        forStoreCity = address.City;

                        Console.Write("Person address - Postal code: ");
                        address.PostalCode = Console.ReadLine().ToString();
                    }

                    foreach (var item in found.PersonAddresses)
                    {
                        Console.WriteLine(item.City);
                    }



                    db.Activate(found, 100);



                    db.Store(found.PersonAddresses.Find(x => (x.City == forStoreCity) && (x.Street == forStoreStreet)));
                }
                else
                {
                    Console.WriteLine("\nThis peron don't exist in database");
                }
            }
        }
Beispiel #35
0
        public static void ListAllCars(IObjectContainer db)
        {
            IObjectSet result = db.QueryByExample(typeof(Car));

            ListResult(result);
        }
Beispiel #36
0
        private void btnCadastrar_Click(object sender, EventArgs e)
        {
            if (validarCampos() && validarSMTP())
            {
                Usuario usuario = new Usuario();
                if (cboxSMTP.Checked)
                {
                    try
                    {
                        ServidorSMTP smtp = new ServidorSMTP();
                        smtp.emailSMTP       = txtEmailSMTP.Text;
                        smtp.senhaSMTP       = txtSenhaSMTP.Text;
                        smtp.servidorSMTP    = txtServidor.Text;
                        smtp.portaSMTP       = Convert.ToInt32(txtPorta.Text);
                        smtp.SSL             = cboxSSL.Checked;
                        usuario.servidorSMTP = smtp;
                    }
                    catch (FormatException)
                    {
                        MessageBox.ShowMessageBoxOK("error", "A porta deve ser um número!", "Formato incorreto", DarkTheme);
                        txtPorta.Focus();
                        return;
                    }
                }

                usuario.nome = txtNome.Text;
                IObjectSet procurar = banco.QueryByExample(usuario);
                if (procurar.HasNext())
                {
                    usuario = (Usuario)procurar.Next();
                    if (usuario.nome.Equals(txtNome.Text))
                    {
                        MessageBox.ShowMessageBoxOK("warning", "Este nome já está sendo utilizado", "Aviso", DarkTheme);
                        txtNome.Focus();
                        return;
                    }
                }

                usuario.email = txtEmail.Text;
                Usuario u2 = new Usuario();
                u2.email = txtEmail.Text;
                IObjectSet p2 = banco.QueryByExample(u2);
                if (p2.HasNext())
                {
                    Usuario u = (Usuario)p2.Next();
                    if (u.email.Equals(txtEmail.Text))
                    {
                        MessageBox.ShowMessageBoxOK("warning", "Este e-mail já está sendo utilizado", "Aviso", DarkTheme);
                        txtEmail.Focus();
                        return;
                    }
                }

                usuario.usuario = txtUsuario.Text;
                Usuario u3 = new Usuario();
                u3.usuario = txtUsuario.Text;
                IObjectSet p3 = banco.QueryByExample(u3);
                if (p3.HasNext())
                {
                    Usuario u = (Usuario)p3.Next();
                    if (u.usuario.Equals(txtUsuario.Text))
                    {
                        MessageBox.ShowMessageBoxOK("warning", "Este usuário já está sendo utilizado", "Aviso", DarkTheme);
                        txtEmail.Focus();
                        return;
                    }
                }


                Usuario u4 = new Usuario();

                // hash da senha
                MD5           md5     = MD5.Create();
                byte[]        hash    = md5.ComputeHash(Encoding.UTF8.GetBytes(txtSenha.Text));
                StringBuilder stringg = new StringBuilder();
                for (int i = 0; i < hash.Length; i++)
                {
                    stringg.Append(hash[i].ToString("x2")); // hexa
                }


                usuario.senha = stringg.ToString();
                u4.senha      = txtSenha.Text;

                banco.Store(usuario);
                MessageBox.ShowMessageBoxOK("correct", "Cadastro realizado com sucesso!", "", DarkTheme);
                banco.Close();
                this.Close();
            }
        }
Beispiel #37
0
        public Boolean alterarMaterial(Materiais objMaterialAtualizar)
        {
            try
            {
                if (!temDuplicidade(objMaterialAtualizar, "Alterar"))
                {
                    db = ServidorSingleton.obterServidor().OpenClient();

                    //Carrega o fornecedor
                    IObjectSet leitorFornecedor = db.QueryByExample(objMaterialAtualizar.Fornecedor);
                    if (leitorFornecedor.HasNext())
                    {
                        objMaterialAtualizar.Fornecedor = (Fornecedor)leitorFornecedor.Next();
                    }
                    leitorFornecedor = null;

                    //Carrega o comprador
                    IObjectSet leitorComprador = db.QueryByExample(objMaterialAtualizar.Comprador);
                    if (leitorComprador.HasNext())
                    {
                        objMaterialAtualizar.Comprador = (Comprador)leitorComprador.Next();
                    }
                    leitorComprador = null;

                    Materiais objMaterialPrototipo = FactoryClasses.criarMateriais();
                    objMaterialPrototipo.Codigo = objMaterialAtualizar.Codigo;
                    IObjectSet leitor = db.QueryByExample(objMaterialPrototipo);
                    if (leitor.HasNext())
                    {
                        Materiais objMaterial = (Materiais)leitor.Next();
                        objMaterial.Unidade          = objMaterialAtualizar.Unidade;
                        objMaterial.Comprador        = objMaterialAtualizar.Comprador;
                        objMaterial.Descricao        = objMaterialAtualizar.Descricao;
                        objMaterial.DescricaoPopular = objMaterialAtualizar.DescricaoPopular;
                        objMaterial.Fornecedor       = objMaterialAtualizar.Fornecedor;
                        objMaterial.ValorCompra      = objMaterialAtualizar.ValorCompra;
                        objMaterial.ValorVenda       = objMaterialAtualizar.ValorVenda;
                        db.Store(objMaterial);
                        db.Commit();
                        leitor = null;
                        return(true);
                    }
                    else
                    {
                        leitor = null;
                        return(false);
                    }
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                db.Rollback();
                throw new Exception("Erro atualizando o material :" + ex.ToString());
            }
            finally
            {
                db.Close();
                db.Dispose();
            }
        }
Beispiel #38
0
        public void SaveModifiedPersonToDatabase()
        {
            IObjectContainer db                 = Db4oFactory.OpenFile("person.data");
            var personToModifiy                 = db.QueryByExample(new PersonModel(SelectedPerson.Name)).Next() as PersonModel;
            var allPeopleInDatabase             = db.QueryByExample(new PersonModel());
            List <PersonModel> personHelperList = new List <PersonModel>();

            foreach (var person in allPeopleInDatabase)
            {
                var p = (PersonModel)person;
                personHelperList.Add(p);
            }
            if (Name == null)
            {
                MessageBox.Show("Nie można dodać osoby bez imienia", "Błąd", MessageBoxButton.OK, MessageBoxImage.Error);
                db.Close();
            }
            else if (Name != SelectedPerson.Name && personHelperList.Any(x => x.Name == Name))
            {
                MessageBox.Show("Osoba z podanym imieniem jest już w bazie", "Błąd", MessageBoxButton.OK, MessageBoxImage.Error);
                db.Close();
            }
            else
            {
                personToModifiy.Name = Name;
                if (Name != SelectedPerson.Name)
                {
                    if (personToModifiy.Father != String.Empty && personToModifiy.Father != null)
                    {
                        var father       = db.QueryByExample(new PersonModel(personToModifiy.Father)).Next() as PersonModel;
                        var child        = father.Children.Where(x => x == SelectedPerson.Name).FirstOrDefault();
                        var newNameChild = Name;
                        int index        = father.Children.IndexOf(child);
                        if (index != -1)
                        {
                            father.Children[index] = newNameChild;
                        }
                        db.Store(father.Children);
                    }
                    if (personToModifiy.Mother != String.Empty && personToModifiy.Mother != null)
                    {
                        var mother       = db.QueryByExample(new PersonModel(personToModifiy.Mother)).Next() as PersonModel;
                        var child        = mother.Children.Where(x => x == SelectedPerson.Name).FirstOrDefault();
                        var newNameChild = Name;
                        int index        = mother.Children.IndexOf(child);
                        if (index != -1)
                        {
                            mother.Children[index] = newNameChild;
                        }
                        db.Store(mother.Children);
                    }
                }

                personToModifiy.BirthDate = BirthDate;

                if (DeathDate != null)
                {
                    bool isDeathDatePossible = IsDeathDatePossible(DeathDate.Value, personToModifiy, db);
                    if (isDeathDatePossible == true)
                    {
                        personToModifiy.DeathDate = DeathDate;
                    }
                    else
                    {
                        db.Close();
                        MessageBox.Show("Nie można ustawić podanej daty śmierci - osoba posiada dzieci urodzone później"
                                        , "Błąd", MessageBoxButton.OK, MessageBoxImage.Error);
                        return;
                    }
                }

                if (Gender == EGender.brak)
                {
                    personToModifiy.Gender = null;

                    if (SelectedPerson.Gender == EGender.Male)
                    {
                        var personsChildren         = db.QueryByExample(PersonModel.WithFather(Name));
                        List <PersonModel> children = new List <PersonModel>();
                        foreach (var child in personsChildren)
                        {
                            children.Add(child as PersonModel);
                        }
                        foreach (var child in children)
                        {
                            child.Father = String.Empty;
                        }
                        foreach (var child in personsChildren)
                        {
                            db.Store(child);
                        }
                        if (personToModifiy.Children != null)
                        {
                            personToModifiy.Children = null;
                        }
                    }
                    else if (SelectedPerson.Gender == EGender.Female)
                    {
                        var personsChildren         = db.QueryByExample(PersonModel.WithMother(Name));
                        List <PersonModel> children = new List <PersonModel>();
                        foreach (var child in personsChildren)
                        {
                            children.Add(child as PersonModel);
                        }
                        foreach (var child in children)
                        {
                            child.Mother = String.Empty;
                        }
                        foreach (var child in personsChildren)
                        {
                            db.Store(child);
                        }
                        if (personToModifiy.Children != null)
                        {
                            personToModifiy.Children = null;
                        }
                    }
                }
                else
                {
                    personToModifiy.Gender = Gender;
                    if (SelectedPerson.Gender != Gender)
                    {
                        if (personToModifiy.Children != null)
                        {
                            personToModifiy.Children = null;
                            if (Gender == EGender.Male && SelectedPerson.Gender == EGender.Female)
                            {
                                var personsChildren         = db.QueryByExample(PersonModel.WithMother(Name));
                                List <PersonModel> children = new List <PersonModel>();
                                foreach (var child in personsChildren)
                                {
                                    children.Add(child as PersonModel);
                                }
                                foreach (var child in children)
                                {
                                    child.Mother = String.Empty;
                                }
                                foreach (var child in personsChildren)
                                {
                                    db.Store(child);
                                }
                            }
                            else if (Gender == EGender.Female && SelectedPerson.Gender == EGender.Male)
                            {
                                var personsChildren         = db.QueryByExample(PersonModel.WithFather(Name));
                                List <PersonModel> children = new List <PersonModel>();
                                foreach (var child in personsChildren)
                                {
                                    children.Add(child as PersonModel);
                                }
                                foreach (var child in children)
                                {
                                    child.Father = String.Empty;
                                }
                                foreach (var child in personsChildren)
                                {
                                    db.Store(child);
                                }
                            }
                        }
                    }
                }

                if (Father != null)
                {
                    if (Father != null && Father.Name == "-brak-")
                    {
                        personToModifiy.Father = String.Empty;
                        var previousFather = db.QueryByExample(new PersonModel(SelectedPerson.Father)).Next() as PersonModel;
                        previousFather.Children.Remove(personToModifiy.Name);
                        if (previousFather.Children.Count == 0)
                        {
                            previousFather.Children = null;
                        }
                        db.Store(previousFather);
                    }
                    else
                    {
                        personToModifiy.Father = Father.Name;
                        var newFather = db.QueryByExample(new PersonModel(Father.Name)).Next() as PersonModel;
                        if (newFather.Children == null)
                        {
                            newFather.Children = new List <string>();
                            newFather.Children.Add(Name);
                            db.Store(newFather);
                        }
                        else
                        {
                            newFather.Children.Add(Name);
                            db.Store(newFather.Children);
                        }
                        if (SelectedPerson.Father != null && SelectedPerson.Father != String.Empty)
                        {
                            var previousFather = db.QueryByExample(new PersonModel(SelectedPerson.Father)).Next() as PersonModel;
                            previousFather.Children.Remove(personToModifiy.Name);
                            if (previousFather.Children.Count == 0)
                            {
                                previousFather.Children = null;
                            }
                            db.Store(previousFather);
                        }
                    }
                }
                else
                {
                    if (SelectedPerson.Father != String.Empty && SelectedPerson.BirthDate != BirthDate)
                    {
                        MessageBox.Show("Ojciec musi zostać wybrany", "Błąd", MessageBoxButton.OK, MessageBoxImage.Error);
                        db.Close();
                        return;
                    }
                }
                if (Mother != null)
                {
                    if (Mother.Name == "-brak-")
                    {
                        personToModifiy.Mother = String.Empty;
                        var previousMother = db.QueryByExample(new PersonModel(SelectedPerson.Mother)).Next() as PersonModel;
                        previousMother.Children.Remove(personToModifiy.Name);
                        if (previousMother.Children.Count == 0)
                        {
                            previousMother.Children = null;
                        }
                        db.Store(previousMother);
                    }
                    else
                    {
                        personToModifiy.Mother = Mother.Name;
                        var newMother = db.QueryByExample(new PersonModel(Mother.Name)).Next() as PersonModel;
                        if (newMother.Children == null)
                        {
                            newMother.Children = new List <string>();
                            newMother.Children.Add(Name);
                            db.Store(newMother);
                        }
                        else
                        {
                            newMother.Children.Add(Name);
                            db.Store(newMother.Children);
                        }
                        if (SelectedPerson.Mother != null && SelectedPerson.Mother != String.Empty)
                        {
                            var previousMother = db.QueryByExample(new PersonModel(SelectedPerson.Mother)).Next() as PersonModel;
                            previousMother.Children.Remove(personToModifiy.Name);
                            if (previousMother.Children.Count == 0)
                            {
                                previousMother.Children = null;
                            }
                            db.Store(previousMother);
                        }
                    }
                }
                else
                {
                    if (SelectedPerson.Mother != String.Empty && SelectedPerson.BirthDate != BirthDate)
                    {
                        MessageBox.Show("Matka musi zostać wybrana", "Błąd", MessageBoxButton.OK, MessageBoxImage.Error);
                        db.Close();
                        return;
                    }
                }
            }
            db.Store(personToModifiy);
            db.Close();
            NotifyOfPropertyChange(() => AllPeopleInDatabase);
            Name      = null;
            Father    = null;
            Mother    = null;
            Gender    = null;
            BirthDate = null;
            DeathDate = null;
        }
Beispiel #39
0
 public void AddPersonToDatabase()
 {
     if (Name == null)
     {
         MessageBox.Show("Nie można dodać osoby bez imienia", "Błąd", MessageBoxButton.OK, MessageBoxImage.Error);
     }
     else
     {
         IObjectContainer db                 = Db4oFactory.OpenFile("person.data");
         var allPeopleInDatabase             = db.QueryByExample(new PersonModel());
         List <PersonModel> personHelperList = new List <PersonModel>();
         foreach (var person in allPeopleInDatabase)
         {
             var p = (PersonModel)person;
             personHelperList.Add(p);
         }
         if (personHelperList.Any(x => x.Name == Name))
         {
             MessageBox.Show("Osoba o podanym imieniu jest już w bazie", "Błąd", MessageBoxButton.OK, MessageBoxImage.Error);
             db.Close();
             Name = null;
             return;
         }
         else
         {
             PersonModel newPerson = new PersonModel
             {
                 Name      = Name,
                 BirthDate = BirthDate,
                 DeathDate = DeathDate,
             };
             if (Gender == EGender.brak)
             {
                 newPerson.Gender = null;
             }
             else
             {
                 newPerson.Gender = Gender;
             }
             if (Father != null)
             {
                 newPerson.Father = Father.Name;
             }
             if (Mother != null)
             {
                 newPerson.Mother = Mother.Name;
             }
             if (newPerson.Father != null)
             {
                 var newPersonFather = (PersonModel)db.QueryByExample(new PersonModel(newPerson.Father)).Next();
                 if (newPersonFather.Children == null)
                 {
                     newPersonFather.Children = new List <string>();
                     newPersonFather.Children.Add(newPerson.Name);
                     db.Store(newPersonFather);
                 }
                 else
                 {
                     newPersonFather.Children.Add(newPerson.Name);
                     db.Store(newPersonFather.Children);
                 }
             }
             if (newPerson.Mother != null)
             {
                 var newPersonMother = (PersonModel)db.QueryByExample(new PersonModel(newPerson.Mother)).Next();
                 if (newPersonMother.Children == null)
                 {
                     newPersonMother.Children = new List <string>();
                     newPersonMother.Children.Add(newPerson.Name);
                     db.Store(newPersonMother);
                 }
                 else
                 {
                     newPersonMother.Children.Add(newPerson.Name);
                     db.Store(newPersonMother.Children);
                 }
             }
             db.Store(newPerson);
             db.Close();
             Name      = null;
             Father    = null;
             Mother    = null;
             BirthDate = null;
             DeathDate = null;
             Gender    = null;
             NotifyOfPropertyChange(nameof(PossibleFathers));
             NotifyOfPropertyChange(nameof(PossibleMothers));
         }
     }
 }
Beispiel #40
0
        public static void RetrieveAll(IObjectContainer db)
        {
            IObjectSet result = db.QueryByExample(new Employee(0, null, null, 0, null, null));

            ListResult(result);
        }
        protected void AssertAliasedData(IObjectContainer container)
        {
            AssertAliasedData(container.QueryByExample(GetAliasedDataType()));

            AssertAliasedData(QueryAliasedData(container));
        }
Beispiel #42
0
        public static void RetrieveAllCompany(IObjectContainer db)
        {
            IObjectSet result = db.QueryByExample(typeof(Company));

            ListResult(result);
        }
Beispiel #43
0
        public static void ModifyPhone(IObjectContainer db)
        {
            Console.WriteLine("Podaj osobę, której chcesz zmodyfikować telefon:");
            Console.WriteLine();
            Console.Write("Imię:\t\t");
            string firstName = Console.ReadLine();

            Console.Write("Nazwisko:\t");
            string lastName = Console.ReadLine();

            try
            {
                Person     ex     = new Person(firstName, lastName);
                IObjectSet result = db.QueryByExample(ex);
                Person     found  = (Person)result.Next();

                if (found.Phones == null)
                {
                    Console.WriteLine();
                    Console.WriteLine("Brak telefonów w bazie.");
                    return;
                }
                else
                {
                    Console.WriteLine("Telefony:\t");
                    foreach (var phone in found.Phones)
                    {
                        Console.WriteLine($"\t\t{phone}");
                    }
                }

                Console.WriteLine();
                Console.WriteLine("Podaj numer telefonu do zmiany:");
                Console.WriteLine();
                var phoneNumber = Console.ReadLine();

                int selectedPhone = found.Phones.FindIndex(x => x.Number == phoneNumber);

                if (found.Phones[selectedPhone].Number != phoneNumber)
                {
                    Console.WriteLine("Taki numer nie istnieje. Nie można kontynuować.");
                    return;
                }

                Console.WriteLine();
                Console.WriteLine("Podaj nowy telefon:");
                Console.WriteLine();

                Console.Write("Numer\t\t");
                found.Phones[selectedPhone].Number = Console.ReadLine();
                Console.Write("Operator\t");
                found.Phones[selectedPhone].Type = Console.ReadLine();
                Console.Write("Typ\t\t");
                found.Phones[selectedPhone].OperatorName = Console.ReadLine();

                db.Store(found);

                Console.WriteLine("Pomyślnie zmieniono telefon!");
            }
            catch (Exception e)
            {
                Console.WriteLine();
                Console.WriteLine("Taki obiekt nie istnieje. Nie można kontynuować.");
            }
        }
Beispiel #44
0
        public static void RetrieveAllEmployee(IObjectContainer db)
        {
            IObjectSet result = db.QueryByExample(typeof(Employee));

            ListResult(result);
        }
Beispiel #45
0
        public static void RetrieveAllObjects(IObjectContainer db)
        {
            IObjectSet result = db.QueryByExample(new object());

            ListResult(result);
        }
 public void DeletePerson()
 {
     if (SelectedPerson == null)
     {
         MessageBox.Show("Nie wybrano osoby", "Informacja", MessageBoxButton.OK, MessageBoxImage.Information);
         return;
     }
     else
     {
         var result = MessageBox.Show("Czy chcesz usunąć wybraną osobę?", "Pytanie", MessageBoxButton.YesNo, MessageBoxImage.Question);
         if (result == MessageBoxResult.Yes)
         {
             IObjectContainer db             = Db4oFactory.OpenFile("person.data");
             var personToRemove              = db.QueryByExample(new PersonModel(SelectedPerson.Name)).Next();
             var personToRemoveAsPersonModel = personToRemove as PersonModel;
             if (personToRemoveAsPersonModel.Children != null)
             {
                 if (personToRemoveAsPersonModel.Gender == EGender.Male)
                 {
                     var personsChildren       = db.QueryByExample(PersonModel.WithFather(personToRemoveAsPersonModel.Name));
                     var childrenAsPersonModel = new List <PersonModel>();
                     foreach (var child in personsChildren)
                     {
                         childrenAsPersonModel.Add(child as PersonModel);
                     }
                     foreach (var child in childrenAsPersonModel)
                     {
                         child.Father = null;
                         db.Store(child);
                     }
                     personToRemoveAsPersonModel.Children = null;
                 }
                 else
                 {
                     var personsChildren       = db.QueryByExample(PersonModel.WithMother(personToRemoveAsPersonModel.Name));
                     var childrenAsPersonModel = new List <PersonModel>();
                     foreach (var child in personsChildren)
                     {
                         childrenAsPersonModel.Add(child as PersonModel);
                     }
                     foreach (var child in childrenAsPersonModel)
                     {
                         child.Mother = null;
                         db.Store(child);
                     }
                     personToRemoveAsPersonModel.Children = null;
                 }
             }
             if (personToRemoveAsPersonModel.Father != null && personToRemoveAsPersonModel.Father != String.Empty)
             {
                 var personsFather = db.QueryByExample(new PersonModel(personToRemoveAsPersonModel.Father)).Next();
                 var personsFatherAsPersonModel = personsFather as PersonModel;
                 personsFatherAsPersonModel.Children.Remove(personToRemoveAsPersonModel.Name);
                 if (personsFatherAsPersonModel.Children.Count == 0)
                 {
                     personsFatherAsPersonModel.Children = null;
                 }
                 db.Store(personsFatherAsPersonModel);
             }
             if (personToRemoveAsPersonModel.Mother != null && personToRemoveAsPersonModel.Mother != String.Empty)
             {
                 var personsMother = db.QueryByExample(new PersonModel(personToRemoveAsPersonModel.Mother)).Next();
                 var personsMotherAsPersonModel = personsMother as PersonModel;
                 personsMotherAsPersonModel.Children.Remove(personToRemoveAsPersonModel.Name);
                 if (personsMotherAsPersonModel.Children.Count == 0)
                 {
                     personsMotherAsPersonModel.Children = null;
                 }
                 db.Store(personsMotherAsPersonModel);
             }
             db.Delete(personToRemove);
             db.Commit();
             db.Close();
             NotifyOfPropertyChange(() => AllPeopleInDatabase);
         }
         else if (result == MessageBoxResult.No)
         {
             return;
         }
     }
 }
Beispiel #47
0
        //Display all computer (contain status)
        public static void DisplayAllComputers(IObjectContainer db)
        {
            IObjectSet result = db.QueryByExample(typeof(Computer));

            UserManagement.ListResult(result);
        }
Beispiel #48
0
        public static void RetrieveCollections(IObjectContainer db)
        {
            var result = db.QueryByExample(new ArrayList());

            ListResult(result);
        }
Beispiel #49
0
        private void Init()
        {
            nameBox.Text               = _user.Name;
            birthDayBox.Text           = _user.BirthDay;
            surnameBox.Text            = _user.Surname;
            phoneBox.Text              = _user.Phone;
            cityComboBox.SelectedIndex = cityComboBox.FindStringExact(_user.City);
            addressBox.Text            = _user.Addres;
            if (_user.Gender == "Male")
            {
                maleButton.Select();
            }
            else
            {
                femaleButton.Select();
            }

            IEnumerable <Project> projects = from Project p in _db select p;

            _lastProjectId = projects.Any() ? projects.Last().Id : 0;

            IEnumerable <Task> tasks = from Task t in _db select t;

            _lastTaskId = tasks.Any() ? tasks.Last().Id : 0;

            UpdateProjectsGrid();

            IObjectSet result = _db.QueryByExample(new Person());

            employees.DataSource = result;
            showTaskEmployeesList.Items.Add("All");
            employeesComboBox.Items.Add("All");
            //showTasksProjectList.Items.Add("All");
            foreach (Person person in result)
            {
                employeeList.Items.Add(person);
                if (!person.IsAdmin)
                {
                    employeesComboBox.Items.Add(person);
                    newTaskAssignEmp.Items.Add(person);
                    showTaskEmployeesList.Items.Add(person);
                    normalUsersList.Items.Add(person);
                }
                else
                {
                    adminsList.Items.Add(person);
                }
            }

            for (int i = 2016; i > 1950; i--)
            {
                yearsComboBox.Items.Add(i);
            }

            if (employeesComboBox.Items.Count > 0)
            {
                employeesComboBox.SelectedIndex = 0;
            }
            UpdateShowTasksView();
            UpdateAnalyzeView();
        }
Beispiel #50
0
        public static void RetrieveArrays(IObjectContainer db)
        {
            IObjectSet result = db.QueryByExample((Array) new double[] { 0.6, 0.4 });

            ListResult(result);
        }
Beispiel #51
0
        private void RemoveLinhaUnica(DataGridView datagrid, DataGridViewCellEventArgs e)
        {
            // argumentos: Datagrid a ser manipulado e Eventos da célula (retirada do evento cell content click)
            try
            {
                string msg = "";

                /*
                 * if (tbcMenuHistorico.SelectedIndex != 2)
                 * {
                 *  for (int i = 0; i < 4; i++) //4 colunas p/datagrid
                 *  {
                 *      if (i == 3)
                 *      {
                 *          msg += datagrid.Rows[e.RowIndex].Cells[i].Value.ToString();
                 *          continue;
                 *      }
                 *      msg += datagrid.Rows[e.RowIndex].Cells[i].Value.ToString() + delimitadorInicial;
                 *  }
                 *  msg += delimitadorFinal;
                 * }
                 */
                ///Aqui foi o que deu certo no histórico do RSA, só adaptar pra outras cifras
                ///Não sei qual delimitador utilizaram, mas acho melhor usar um só, o malakoi do hebraico lá

                for (int i = 0; i < 4; i++) //4 colunas p/datagrid
                {
                    msg += datagrid.Rows[e.RowIndex].Cells[i].Value.ToString() + delimitadorFinal;
                }


                //busca no banco

                string msgBanco = "";
                banco.Close();
                banco = Db4oFactory.OpenFile(caminhoBanco);

                IObjectSet resultado = banco.QueryByExample(usuario);

                string actualTab = tbcMenuHistorico.SelectedTab.Text;
                switch (actualTab)
                {
                case "AES":
                    if (resultado.HasNext())
                    {
                        Usuario tmp = (Usuario)resultado.Next();
                        msgBanco         = tmp.historicoAES;
                        msgBanco         = msgBanco.Replace(msg, "");
                        tmp.historicoAES = msgBanco;
                        banco.Store(tmp);
                    }
                    break;

                case "AES Arquivos":
                    if (resultado.HasNext())
                    {
                        Usuario tmp = (Usuario)resultado.Next();
                        msgBanco = tmp.historicoAESArquivo;
                        msgBanco = msgBanco.Replace(msg, "");
                        tmp.historicoAESArquivo = msgBanco;
                        banco.Store(tmp);
                    }
                    break;

                case "RSA":
                    if (resultado.HasNext())
                    {
                        Usuario tmp = (Usuario)resultado.Next();
                        msgBanco         = tmp.historicoRSA;
                        msgBanco         = msgBanco.Replace(msg, "");
                        tmp.historicoRSA = msgBanco;
                        banco.Store(tmp);
                    }
                    break;

                case "Esteganografia":
                    if (resultado.HasNext())
                    {
                        Usuario tmp = (Usuario)resultado.Next();
                        msgBanco = tmp.historicoEsteganografia;
                        msgBanco = msgBanco.Replace(msg, "");
                        tmp.historicoEsteganografia = msgBanco;
                        banco.Store(tmp);
                    }
                    break;

                case "Código Morse":
                    if (resultado.HasNext())
                    {
                        Usuario tmp = (Usuario)resultado.Next();
                        msgBanco           = tmp.historicoMorse;
                        msgBanco           = msgBanco.Replace(msg, "");
                        tmp.historicoMorse = msgBanco;
                        banco.Store(tmp);
                    }
                    break;

                case "Cifra de Cesar":
                    if (resultado.HasNext())
                    {
                        msg = "";
                        for (int i = 0; i < 5; i++)
                        {
                            msg += datagrid.Rows[e.RowIndex].Cells[i].Value.ToString() + delimitadorFinal;
                        }
                        Usuario tmp = (Usuario)resultado.Next();
                        msgBanco           = tmp.historicoCesar;
                        msgBanco           = msgBanco.Replace(msg, "");
                        tmp.historicoCesar = msgBanco;
                        banco.Store(tmp);
                    }
                    break;

                default:
                    break;
                }
                banco.Close();
            }
            catch (Exception)
            {
                return;
            }
        }
Beispiel #52
0
        public void cadastrarPedido(SolicitacaoMateriais objSolicitacao)
        {
            //Atualiza a solicitação no db
            SolicitacaoMateriaisDAO objSolicitacaoDAO = FactoryDAO.criarSolicitacaoMateriaisDAO();

            if (objSolicitacaoDAO.atualizarSolicitacao(objSolicitacao))
            {
                SolicitacaoMateriais objSolicitacaoProt = FactoryClasses.criarSolicitacaoMateriais();
                objSolicitacaoProt.Codigo = objSolicitacao.Codigo;
                db = ServidorSingleton.obterServidor().OpenClient();
                IObjectSet leitor = db.QueryByExample(objSolicitacaoProt);
                if (leitor.HasNext())
                {
                    objSolicitacaoProt = null;
                    objSolicitacaoProt = (SolicitacaoMateriais)leitor.Next();
                }
                leitor = null;
                Collection <Pedido> objPedidoColecao = new Collection <Pedido>();

                foreach (Materiais material in objSolicitacaoProt.Materiais)
                {
                    Pedido objPedido = FactoryClasses.criarPedido();
                    objPedido.SolicitacaoMateriais = objSolicitacaoProt;
                    Collection <Materiais> objMateriaisColecao = new Collection <Materiais>();
                    objMateriaisColecao.Add(material);
                    objPedido.Materiais = objMateriaisColecao;
                    objPedido.Codigo    = obtemNovoId();
                    db = ServidorSingleton.obterServidor().OpenClient();
                    db.Store(objPedido);
                    db.Commit();
                }

                //Le os pedidos
                Pedido objPedidoProt = FactoryClasses.criarPedido();
                objPedidoProt.SolicitacaoMateriais = objSolicitacaoProt;
                db = ServidorSingleton.obterServidor().OpenClient();
                IObjectSet leitorPedidoCache = db.QueryByExample(objPedidoProt);
                int        codFornecedor     = 0;
                int        contador          = 0;
                int        codPedido         = 0;

                while (leitorPedidoCache.HasNext())
                {
                    Pedido objPedidoLer = (Pedido)leitorPedidoCache.Next();
                    if (contador == 0)
                    {
                        codFornecedor = objPedidoLer.Materiais[0].Fornecedor.Codigo;
                    }
                    else
                    {
                        if (codFornecedor == objPedidoLer.Materiais[0].Fornecedor.Codigo)
                        {
                            //Retira os itens deste pedido e coloca no anterior
                            Collection <Materiais> objMateriaisColecaoTmp = new Collection <Materiais>();
                            foreach (Materiais item in objPedidoLer.Materiais)
                            {
                                objMateriaisColecaoTmp.Add(item);
                            }
                            //exclui o pedido atual
                            db.Delete(objPedidoLer);
                            //Carrega o anterior em cache
                            Pedido p = FactoryClasses.criarPedido();
                            p.Codigo = codPedido;
                            IObjectSet leitorPedido2 = db.QueryByExample(p);
                            if (leitorPedido2.HasNext())
                            {
                                p = null;
                                p = (Pedido)leitorPedido2.Next();
                                //Atualiza o pedido anterior com os dados do pedido que foi apagado
                                foreach (Materiais item in p.Materiais)
                                {
                                    objMateriaisColecaoTmp.Add(item);
                                }
                                p.Materiais = objMateriaisColecaoTmp;
                                db.Store(p);
                                db.Commit();
                            }
                            leitorPedido2 = null;
                        }
                    }
                    codFornecedor = objPedidoLer.Materiais[0].Fornecedor.Codigo;
                    codPedido     = objPedidoLer.Codigo;
                    contador++;
                }
                leitorPedidoCache = null;
                db.Close();
                db.Dispose();
            }
        }
Beispiel #53
0
 public IObjectSet QueryByExample(object template)
 {
     return(session.QueryByExample(template));
 }
Beispiel #54
0
        private void btnEsteganografar_Click(object sender, EventArgs e)
        {
            if (validarCampos() && validarNomeArquivo())
            {
                nome = txtNomeArquivo.Text;
                if (nome.Contains(" "))
                {
                    nome = nome.Replace(' ', '_');
                }

                try
                {
                    if (File.Exists(@"C:\iCrypto\Zipado.rar"))
                    {
                        File.Delete(@"C:\iCrypto\Zipado.rar");
                    }

                    if (!Directory.Exists(@"C:\iCrypto\Esteganografia"))
                    {
                        Directory.CreateDirectory(@"C:\iCrypto\Esteganografia");
                    }
                    else
                    {
                        Directory.Delete(@"C:\iCrypto\Esteganografia", true);
                        Directory.CreateDirectory(@"C:\iCrypto\Esteganografia");
                    }

                    File.Copy(txtFileHide.Text, @"C:\iCrypto\Esteganografia\ArquivoEsteganografado" + extensaoHide, true);
                    ZipFile.CreateFromDirectory(@"C:\iCrypto\Esteganografia", @"C:\iCrypto\Zipado.rar");

                    gerado = '"' + txtSalvarArquivo.Text + @"\" + '"' + nome + extensao + '"';
                    ProcessStartInfo infos = new ProcessStartInfo();
                    infos.FileName        = "cmd.exe";
                    infos.UseShellExecute = true;
                    infos.CreateNoWindow  = true;
                    infos.WindowStyle     = ProcessWindowStyle.Hidden;
                    infos.Arguments       = "/C copy /b " + '"' + txtArquivoOriginal.Text + '"' + "+" + '"' + @"C:\iCrypto\Zipado.rar" + '"' + " " + gerado;
                    Process processo = new Process();
                    processo.StartInfo = infos;
                    processo.Start();

                    gerado   = txtSalvarArquivo.Text + @"\" + "" + nome + "" + extensao;
                    mensagem = "Foi criado um novo arquivo esteganografado no seguinte diretório:" +
                               "\n" +
                               "\n" + gerado;

                    MessageBox.ShowMessageBoxOK("correct", mensagem, "Processo concluído!", DarkTheme);

                    timerAntiBug.Start();

                    FileInfo novoArquivo = new FileInfo(gerado);
                    txtDiretorioFinal.Text = gerado;
                    arquivo[0]             = novoArquivo.Name;
                    nomeArqFinal           = novoArquivo.Name;
                    arquivo[1]             = novoArquivo.Length.ToString() + " bytes";
                    arquivo[2]             = novoArquivo.Extension;
                    dgvArquivoFinal.Rows.Clear();

                    if (cboxAnexar.Checked)
                    {
                        fileAnexo[0] = arquivo[0];
                        fileAnexo[1] = arquivo[1];
                        fileAnexo[2] = arquivo[2];
                        fileAnexo[3] = gerado;
                        dgvAnexos.Rows.Add(fileAnexo);
                        anexos.Add(gerado);
                    }
                    dgvArquivoFinal.Rows.Insert(0, arquivo);

                    Usuario usuarioPesquisa = new Usuario();
                    usuarioPesquisa.nome = usuario.nome;

                    IObjectSet pesquisarUsuario = banco.QueryByExample(usuarioPesquisa);
                    if (pesquisarUsuario.HasNext())
                    {
                        usuario = (Usuario)pesquisarUsuario.Next();

                        if (String.IsNullOrEmpty(usuario.historicoEsteganografia))
                        {
                            usuario.historicoEsteganografia = nomeArqOriginal + "ק" + nomeArqOculto + "ק" + nomeArqFinal + "ק" + DateTime.Now.ToString("dd /MM/yyyy") + "ק";
                        }
                        else
                        {
                            usuario.historicoEsteganografia += nomeArqOriginal + "ק" + nomeArqOculto + "ק" + nomeArqFinal + "ק" + DateTime.Now.ToString("dd /MM/yyyy") + "ק";
                        }

                        banco.Store(usuario);
                    }


                    File.Delete(@"C:\iCrypto\Zipado.rar");
                    Directory.Delete(@"C:\iCrypto\Esteganografia", true);
                }
                catch (Exception erro)
                {
                    MessageBox.ShowMessageBoxOK("error", erro.Message, "Ocorreu um erro inesperado", DarkTheme);
                }
            }
        }
Beispiel #55
0
 public Boolean excluirFilme(clsFilme objFilme)
 {
     db = ServidorSingleton.obterServidor().OpenClient();
     try
     {
         IObjectSet leitor = db.QueryByExample(objFilme);
         if (leitor.HasNext())
         {
             db.Delete((clsFilme)leitor.Next());
             db.Commit();
             return true;
         }
         else {
             return false;
         }
     }
     catch
     {
         db.Rollback();
         return false;
     }
     finally {
         db.Close();
         db.Dispose();
     }
 }
Beispiel #56
0
        public static void UpdatePilotSeparateSessionsImprovedPart2(IObjectContainer db)
        {
            IObjectSet result = db.QueryByExample(new Car("Ferrari"));

            ListResult(result);
        }
Beispiel #57
0
 public Boolean temStatusEmFilme(clsStatus objStatus)
 {
     bool temfilme;
     try
     {
         db = ServidorSingleton.obterServidor().OpenClient();
         clsFilme objFilme = new clsFilme();
         objFilme.Status = objStatus;
         IObjectSet leitor = db.QueryByExample(objFilme);
         if (leitor.HasNext())
         {
             temfilme = true;
         }
         else
         {
             temfilme = false;
         }
         leitor = null;
     }
     catch (Exception ex)
     {
         throw new Exception("Erro verificando possibilidade de exclusão do status:" + ex.ToString());
     }
     finally
     {
         db.Close();
         db.Dispose();
     }
     return temfilme;
 }
Beispiel #58
0
        public static void RetrieveAllPilots(IObjectContainer db)
        {
            IObjectSet result = db.QueryByExample(typeof(Pilot));

            ListResult(result);
        }
Beispiel #59
0
        public void cadastrarFilme(clsFilme objFilme)
        {
            objFilme.Codigo = obtemNovoId();
            db = ServidorSingleton.obterServidor().OpenClient();
            try
            {
                //Coloca o genero em cache para não ser inserido novamente
                IObjectSet leitorGenero = db.QueryByExample(objFilme.Genero);
                if (leitorGenero.HasNext())
                {
                    objFilme.Genero = (clsGenero)leitorGenero.Next();
                }
                leitorGenero = null;

                //Coloca o status em cache para não ser inserido novamente
                IObjectSet leitorStatus = db.QueryByExample(objFilme.Status);
                if (leitorStatus.HasNext()) {
                    objFilme.Status = (clsStatus)leitorStatus.Next();
                }
                leitorStatus = null;
                //Grava o filme
                db.Store(objFilme);
                db.Commit();
            }
            catch (Exception)
            {
                db.Rollback();
                throw new Exception("Erro cadastrando o filme :" + ex.ToString());
            }
            finally {
                db.Close();
                db.Dispose();
            }
        }
Beispiel #60
0
        static void Main(string[] args)
        {
            //UpisiNoveUBazu();

            #region Jednostavni upiti
            #region QBE
            Console.WriteLine("Obavljam QBE za pilote");
            IObjectSet rezultatQBE = dataBase.QueryByExample(typeof(Pilot));
            ListResult(rezultatQBE);
            Console.WriteLine();
            #endregion

            #region NQ
            Console.WriteLine("Dohvacam po imenu");
            string ime = Console.ReadLine();

            //Dohvacanje svih pilota koji imaju ime ucitano iz konzole
            IList<Pilot> rezultatNQ = dataBase.Query<Pilot>(delegate(Pilot pilot)
            {
                return pilot.Ime == ime;
            });
            foreach (Pilot p in rezultatNQ)
            {
                Console.WriteLine("{0} {1} {2} {3} {4}", p.Ime, p.Prezime, p.Sifra, p.Momcad.Naziv, p.Vrsta);
            }

            Console.WriteLine();
            #endregion

            #region SODA

            Console.WriteLine("SODA upit");
            string prviSodaString = Console.ReadLine();
            string drugiSodaStrnig = Console.ReadLine();
            IQuery query = dataBase.Query();
            query.Constrain(typeof(Pilot));
            query.Descend("_ime").Constrain(prviSodaString).Or(query.Descend("_ime").Constrain(drugiSodaStrnig));

            IObjectSet rezultatSodaUpita = query.Execute();
            ListResult(rezultatSodaUpita);
            Console.WriteLine();

            #endregion

            #region LINQ
            Console.WriteLine("LINQ upit");
            string linqString = Console.ReadLine();

            IEnumerable<Pilot> rezultatLINQUpita = from Pilot p in dataBase
                                                   where p.Ime == linqString
                                                   select p;
            ListResult(rezultatLINQUpita
            Console.WriteLine();
            #endregion
            #endregion

            #region (malo)Slozeniji upiti
            #region QBE
            //Dohvacamo pilota preko drzave
            Drzava drzavaSlozenijiQBE = new Drzava();
            drzavaSlozenijiQBE.Naziv = "Hrvatska";
            Pilot pilotSlozenijiQBE = new Pilot();
            pilotSlozenijiQBE.Drzava = drzavaSlozenijiQBE;

            Console.WriteLine("Slozeniji QBE\nTrazimo sve vozace iz Hrvatske\n");
            IObjectSet rezultatSlozenijegQBE = dataBase.QueryByExample(pilotSlozenijiQBE);
            ListResult(rezultatSlozenijegQBE);
            Console.WriteLine();
            #endregion

            #region NQ

            Drzava drzavaSlozenijiNQ = new Drzava();
            drzavaSlozenijiQBE.Naziv = "Hrvatska";

            //Pilot pilotSlozenijiNQ = new Pilot();
            //pilotSlozenijiNQ.Drzava = drzavaSlozenijiNQ;

            IList<Drzava> rezultatDrzavaSlozenijiNQ = dataBase.Query<Drzava>(delegate(Drzava drzava)
            {
                return drzava.Naziv == "Hrvatska";
            });

            //ako postoji drzava imena Hrvatska onda trazi pilote iz te drzave
            if(rezultatDrzavaSlozenijiNQ.Count > 0)
            {
                Console.WriteLine("Slozeniji NQ\nTrazimo vozace iz Hrvatske\n");
                IList<Pilot> rezultatSlozenijegNQ = dataBase.Query<Pilot>(delegate(Pilot pilot)
                {
                    return pilot.Drzava.Naziv == rezultatDrzavaSlozenijiNQ[0].Naziv;
                });
                ListResult(rezultatSlozenijegNQ);
                Console.WriteLine();
            }
            #endregion

            #region SODA
            //Definiramo upit za dohvacanje drzave
            //Ovo je vec malo teze kemijanje. Ovakvo nesto nece sigurno biti ;)
            //Isto se radi i u LINQ upitima.
            //Buduci da ne znam kako se preko samog naziva drzave dokopati pilota isao sam za svaku
            //pronadenu drzavu traziti onaj element koji ju sadrzi
            IQuery slozenijiSODAUpitDrzava = dataBase.Query();
            slozenijiSODAUpitDrzava.Constrain(typeof(Drzava));
            slozenijiSODAUpitDrzava.Descend("_naziv").Constrain("Hrvatska");

            IObjectSet rezultatDrzavaSlozenijiSODA = slozenijiSODAUpitDrzava.Execute();

            //Ako smo pronasli drzavu dohvacamo pilote iz te drzave
            if (rezultatDrzavaSlozenijiSODA.Count > 0)
            {
                Console.WriteLine("Slozeniji SODA\nTrazimo vozace iz Hrvatske \n");

                for (int i = 0; i < rezultatDrzavaSlozenijiSODA.Count; i++)
                {
                    IQuery slozenijiSODAUpitPilot = dataBase.Query();
                    slozenijiSODAUpitPilot.Constrain(typeof(Pilot));
                    slozenijiSODAUpitPilot.Descend("_drzava").Constrain(rezultatDrzavaSlozenijiSODA[i]);

                    IObjectSet rezultatPilotSlozenijiSODA = slozenijiSODAUpitPilot.Execute();
                    ListResult(rezultatPilotSlozenijiSODA);  
                }
            }
            #endregion

            #region  LINQ
            Console.WriteLine("LINQ upit");
            IEnumerable<Drzava> rezultatDrzavaSlozenijeLINQ = from Drzava d in dataBase
                                                   where d.Naziv == "Hrvatska"
                                                   select d;

            foreach (Drzava drzavaUSlozenijemLINQ in rezultatDrzavaSlozenijeLINQ)
            {
                IEnumerable<Pilot> rezultatLINQUpita = from Pilot p in dataBase
                                                       where p.Drzava == drzavaUSlozenijemLINQ
                                                       select p;
                ListResult(rezultatLINQUpita);
            }
            
            Console.WriteLine();
            #endregion
            #endregion
        }