Exemplo n.º 1
0
        public App()
        {
            //Local do banco

            var pasta = new LocalRootFolder();

            //crio o arquivo do banco
            //se ele existir, abro ele

            var arquivo = pasta.CreateFile("BancoProvectoLogia.db", PCLExt.FileStorage.CreationCollisionOption.OpenIfExists);

            //faço a "Conexão"

            conexao = new SQLite.SQLiteConnection(arquivo.Path);

            //criar tabela, se ela não existir

            conexao.Execute("CREATE TABLE IF NOT EXISTS Usuarios (id INTEGER PRIMARY KEY AUTOINCREMENT, NomeDeUsuario TEXT, SenhaDeUsuario TEXT)");

            conexao.Execute("CREATE TABLE IF NOT EXISTS DataHora (id INTEGER PRIMARY KEY AUTOINCREMENT, Horarios TEXT, Opcao TEXT)");

            InitializeComponent();


            MainPage = new NavigationPage(new MainPage());
        }
        private void ConfirmarNuevosDatos()
        {
            var domiciliosSinConfirmar = db.Table <MDomicilio>().Where(x => x.Nuevo && x.Confirmado == false).ToList();

            foreach (var a in domiciliosSinConfirmar)
            {
                db.Execute("UPDATE MDomicilio SET Confirmado = ? WHERE IdCliente = ? AND Calle = ? AND Numero = ? ", true, a.IdCliente, a.Calle, a.Numero);
            }

            var   paisSeleccinado = spinnerPaises.SelectedItem.ToString();
            MPais paisDb          = db.Table <MPais>().FirstOrDefault(x => x.Nombre == paisSeleccinado);

            var     idiomaSeleccionado = spinnerIdiomas.SelectedItem.ToString();
            MIdioma idiomaDb           = db.Table <MIdioma>().FirstOrDefault(x => x.Nombre == idiomaSeleccionado);

            db.Execute(
                @"UPDATE MCliente SET Nombre = ?, ApellidoPaterno = ?, ApellidoMaterno = ?, 
            Email = ?, TelefonoPrimario = ?, TelefonoSecundario = ?, NombreCompleto = ?, IdPais = ?,
            IdIdioma = ?, PaisNombre = ?, IdiomaNombre = ?, Modificado = ? WHERE Id = ?",
                textNombre.EditText.Text.ToUpper(),
                textApellidoPaterno.EditText.Text.ToUpper(),
                textApellidoMaterno.EditText.Text.ToUpper(),
                textEmail.EditText.Text.ToUpper(),
                textTelefono1.EditText.Text.ToUpper(),
                textTelefono2.EditText.Text.ToUpper(),
                textNombre.EditText.Text.ToUpper() + " " + textApellidoPaterno.EditText.Text.ToUpper() + " " + textApellidoMaterno.EditText.Text.ToUpper(),
                paisDb.Id, idiomaDb.Id, paisDb.Nombre, idiomaDb.Nombre,
                true,
                cliente.Id);
        }
Exemplo n.º 3
0
 public void Delete(int sourceId)
 {
     using (var db = new SQLite.SQLiteConnection(Settings.DatabasePath))
     {
         db.Execute("delete from Translation where SourceId = ?", sourceId);
         db.Execute("delete from Source where Id = ?", sourceId);
     }
 }
Exemplo n.º 4
0
 public static void DeleteWorker(string name)
 {
     using (var db = new SQLite.SQLiteConnection(CreateDB.GetDataBasePath, true))
     {
         var id = db.ExecuteScalar <int>("select  id from TableDepartment where Name ='" + name + "'");
         db.Delete <CreateDB.TableDepartment>(id);
         db.Execute("delete from TableSubordination where chief_id =" + id);
         db.Execute("delete from TableSubordination where department_id =" + id);
         db.Dispose();
     }
 }
Exemplo n.º 5
0
 public void Delete(IEnumerable<int> itemIds)
 {
     using (var db = new SQLite.SQLiteConnection(Settings.DatabasePath))
     {
         foreach (var id in itemIds)
         {
             db.Execute("delete from Item where Id = ?", id);
             db.Execute("delete from Translation where ItemId = ?", id);
         }
     }
 }
Exemplo n.º 6
0
        public ISQLiteConnection GetSqliteConnection()
        {
            lock (connectionPoolLock) {
                if (getConnectionsAllowed)
                {
                    ISQLiteConnection conn = null;
                    if (availableConnections.Count > 0)
                    {
                        // Grab an existing connection
                        conn = availableConnections.Pop();
                    }
                    else if (usedConnections < maxConnections)
                    {
                        // There are no available connections, and we have room for more open connections, so make a new one
                        conn = new SQLite.SQLiteConnection(databasePath);
                        conn.Execute("PRAGMA synchronous = OFF");
                        // Five second busy timeout
                        conn.BusyTimeout = new TimeSpan(0, 0, 5);
                    }

                    if (!ReferenceEquals(conn, null))
                    {
                        // We got a connection, so increment the counter
                        usedConnections++;
                        return(conn);
                    }
                }
            }

            // If no connection available, sleep for 50ms and try again
            Thread.Sleep(50);

            // Recurse to try to get another connection
            return(GetSqliteConnection());
        }
Exemplo n.º 7
0
        public string updateToRead2(string quetion)
        {
            string isUpdated = "";
            string yes       = "yes";
            string no        = "no";

            using (var db = new SQLite.SQLiteConnection(app.dbPath))
            {
                try
                {
                    var existing = db.Execute("update English set read ='" + yes + "' where question ='" + question + "'");
                    if (existing != null)
                    {
                        isUpdated = "true";
                    }
                    else
                    {
                        isUpdated = "false";
                    }
                }

                catch (Exception e)
                {
                }
            }
            return(isUpdated);
        }
Exemplo n.º 8
0
 public void UpdateText(string newText, int id)
 {
     using (var db = new SQLite.SQLiteConnection(Settings.DatabasePath))
     {
         db.Execute("update Item set Text = ? where Id = ?", newText, id);
     }
 }
Exemplo n.º 9
0
        public async void GetAllCountriesFromAPIAsync()
        {
            string queryFilter = "?fields=name;capital;currencies;flag;";

            string url = baseUrl + queryFilter;


            try
            {
                HttpResponseMessage response = await client.GetAsync(new Uri(url));

                string responseBody = response.Content.ReadAsStringAsync().Result;

                var countries = JsonConvert.DeserializeObject <List <Country> >(responseBody);

                //Now let's insert the record

                using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(App._dB_PATH))
                {
                    conn.CreateTable <Country>();
                    conn.Execute("DELETE FROM Country");
                    conn.InsertAll(countries, true);
                }
            }
            catch (Exception ex)
            {
            }
        }
 public static void ClearDB()
 {
     using (var db = new SQLite.SQLiteConnection(DBPath))
     {
         db.Execute("DELETE FROM RootDTO");
     }
 }
Exemplo n.º 11
0
 public static void RemoveFavoritedProduct(string ean_code)
 {
     using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(LOCAL_DB_PATH))
     {
         conn.Execute("delete from FavoritedProduct where Product_EAN_Code=?", ean_code);
     }
 }
Exemplo n.º 12
0
 public void MarkPaid(int billID, decimal amount)
 {
     using (var db = new SQLite.SQLiteConnection(DBPath))
     {
         db.Execute("INSERT INTO PaidBill (BillID, PaidDate, Amount) values (?,?,?)", billID, DateTime.Today.ToString("MM/dd/yyyy"), amount);
     }
 }
Exemplo n.º 13
0
        public App()
        {
            var pasta = new LocalRootFolder();

            var arquivo = pasta.CreateFile("BancoDecoracoes.db", PCLExt.FileStorage.CreationCollisionOption.OpenIfExists);

            conexao = new SQLite.SQLiteConnection(arquivo.Path);

            conexao.Execute("CREATE TABLE IF NOT EXISTS Usuarios (ID INTEGER PRIMARY KEY AUTOINCREMENT,NOME TEXT,NomeUsuario TEXT,SENHA TEXT)");

            conexao.Execute("CREATE TABLE IF NOT EXISTS Orcamento (ID INTEGER PRIMARY KEY AUTOINCREMENT,Nome TEXT,Endereco TEXT,Bairro TEXT,Complemento TEXT,Telefone INTEGER)");


            InitializeComponent();

            MainPage = new NavigationPage(new TeladeLogin());
        }
Exemplo n.º 14
0
		public void ClearDatabase()
		{
			if (databaseCreated) 
			{
				using (var db = new SQLite.SQLiteConnection (GetDatabasePath ())) 
				{
					db.Execute ("Delete from Person");
				}
			}
		}
Exemplo n.º 15
0
        // insertGekoppeldKledingadvies
        public void UpdateGekoppeldProduct(string product, string seizoenstype, string lichaamstype)
        {
            // zoek product & update

            // update product in database met toeveogingen van seizoenstype, lichaamstype en gekoppeldwaardestatus
            using (var database = new SQLite.SQLiteConnection(getDatabasePath()))
            {
                string gekoppeldWaarde = "true";
                database.Execute("UPDATE PRODUCT SET SEIZOENSTYPE = ?, LICHAAMSTYPE = ?, GEKOPPELD = ? WHERE NAAM = ?", seizoenstype, lichaamstype, gekoppeldWaarde, product);
            }
        }
Exemplo n.º 16
0
        public App()
        {
            var Pasta   = new LocalRootFolder();
            var Arquivo = Pasta.CreateFile("BancoX.db", PCLExt.FileStorage.CreationCollisionOption.OpenIfExists);

            Conexao = new SQLite.SQLiteConnection(Arquivo.Path);

            Conexao.Execute("CREATE TABLE IF NOT EXISTS Login (ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE" +
                            ",Nome TEXT (300) NOT NULL," +
                            " Usuario TEXT (500) NOT NULL UNIQUE," +
                            " Email TEXT (300) NOT NULL UNIQUE," +
                            " Senha TEXT (255) NOT NULL," +
                            " CEP INTEGER (8) NOT NULL)");

            Conexao.Execute("CREATE TABLE IF NOT EXISTS Pedido (ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE" +
                            ",Quarto INTEGER NOT NULL" +
                            ",Banheiro INTEGER NOT NULL" +
                            ",Cozinha INTEGER NOT NULL" +
                            ",Sala INTEGER NOT NULL" +
                            ",Data TEXT (10) NOT NULL" +
                            ",Hora TEXT (10) NOT NULL" +
                            ",Empregado TEXT (300) NOT NULL" +
                            ",Total INTEGER NOT NULL)");

            Conexao.Execute("CREATE TABLE IF NOT EXISTS Funcionario (ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE" +
                            ",Nome TEXT (200) NOT NULL" +
                            ",CPF TEXT (11) NOT NULL" +
                            ",CEP TEXT (8) NOT NULL" +
                            ",RG TEXT (12) NOT NULL" +
                            ",Observacao TEXT (300) NOT NULL)");



            InitializeComponent();

            MainPage = new NavigationPage(new MainPage());
            NavigationPage.SetHasNavigationBar(this, false);
        }
Exemplo n.º 17
0
        public App()
        {
            var Pasta = new LocalRootFolder();
            var Banco = Pasta.CreateFile("BancoX.db", PCLExt.FileStorage.CreationCollisionOption.OpenIfExists);

            Conexao = new SQLite.SQLiteConnection(Banco.Path);

            Conexao.Execute("CREATE TABLE IF NOT EXISTS Login (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE" +
                            ", nome TEXT NOT NULL, usuario TEXT NOT NULL UNIQUE, email TEXT NOT NULL UNIQUE, senha TEXT NOT NULL, cep NOT NULL)");

            InitializeComponent();

            MainPage = new NavigationPage(new TelaHamburguer());
        }
Exemplo n.º 18
0
        private bool decryptAndroid(string encryptDb, string key, string decryptDb)
        {
            bool result = true;

            SQLite.SQLiteConnection connection = null;
            try
            {
                connection = new SQLite.SQLiteConnection(encryptDb, true, key);
                connection.Execute("ATTACH DATABASE '" + decryptDb + "' AS plaintext KEY '';");
                connection.ExecuteScalar <string>("SELECT sqlcipher_export('plaintext');");
                connection.Execute("DETACH DATABASE plaintext;");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                result = false;
            }
            if (connection != null)
            {
                connection.Close();
            }
            return(result);
        }
Exemplo n.º 19
0
 public ISQLiteConnection GetQueryLogSqliteConnection()
 {
     if (isPoolingEnabled)
     {
         return(logPool.GetSqliteConnection());
     }
     else
     {
         ISQLiteConnection conn = new SQLite.SQLiteConnection(QuerylogPath);
         conn.Execute("PRAGMA synchronous = OFF");
         // Five second busy timeout
         conn.BusyTimeout = new TimeSpan(0, 0, 5);
         return(conn);
     }
 }
Exemplo n.º 20
0
        public void Banco()
        {
            try
            {
                var Pasta = new LocalRootFolder();
                var Banco = Pasta.CreateFile("BancoX.db", PCLExt.FileStorage.CreationCollisionOption.OpenIfExists);
                Conexao = new SQLite.SQLiteConnection(Banco.Path);

                Conexao.Execute("CREATE TABLE IF NOT EXISTS Login (id INTEGER PRIMARY KEY AUTOINCREMENT NOTNULL UNIQUE" +
                                ", nome TEXT NOTNULL, usuario TEXT NOTNULL UNIQUE, email TEXT NOTNULL UNIQUE, senha TEXT NOTNULL, cep NOTNULL)");
            }
            catch
            {
                //DisplayAlert("Houveu um Problema", "Banco de dados", "OK");
            }
        }
Exemplo n.º 21
0
 public void Save(Preference model)
 {
     using (var db = new SQLite.SQLiteConnection(Settings.DatabasePath))
     {
         var existingCount = db.ExecuteScalar<int>("select count(Name) from Preference where Name = ?",
            model.Name);
         if (existingCount == 0)
         {
             db.Insert(model);
         }
         else
         {
             db.Execute("update Preference set Value = ? where Name = ?",
                 model.Value, model.Name);
         }
     }
 }
Exemplo n.º 22
0
        public static void AddWage(string groupName, int id)
        {
            double wage;

            using (var db = new SQLite.SQLiteConnection(CreateDB.GetDataBasePath, true))
            {
                List <CreateDB.TableGroup> dataGroup = new List <CreateDB.TableGroup>();
                double AllSalarySub = 0;
                var    tableGroup   = from s in db.Table <CreateDB.TableGroup>()
                                      where s.Name_group == groupName
                                      select s;
                var tableDepartment = db.Get <CreateDB.TableDepartment>(id);
                tableGroup.ToList().ForEach(item => dataGroup.Add(item));
                var querySub = db.Query <CreateDB.Show>("select b.name, d.name_group, b.Date, b.wage" +
                                                        " from TableDepartment as a, TableSubordination as c, TableDepartment as b, TableGroup as d" +
                                                        " where  c.chief_id = a.id" +
                                                        " and c.department_id = b.id" +
                                                        " and a.group_id = d.id" +
                                                        " and c.chief_id =" + id);

                querySub.ToList().ForEach((x) => AllSalarySub += x.Wage);
                double percent;
                switch (dataGroup[0].Id)
                {
                case 1:
                    percent = GetYear(tableDepartment.Date, DateTime.Now) * dataGroup[0].Percent > 0.30 ? 0.30 : GetYear(tableDepartment.Date, DateTime.Now) * dataGroup[0].Percent;
                    break;

                case 2:
                    percent = GetYear(tableDepartment.Date, DateTime.Now) * dataGroup[0].Percent > 0.40 ? 0.40 : GetYear(tableDepartment.Date, DateTime.Now) * dataGroup[0].Percent;
                    break;

                case 3:
                    percent = GetYear(tableDepartment.Date, DateTime.Now) * dataGroup[0].Percent > 0.35 ? 0.35 : GetYear(tableDepartment.Date, DateTime.Now) * dataGroup[0].Percent;
                    break;

                default:
                    percent = 0;
                    break;
                }

                wage = dataGroup[0].Rate + percent * dataGroup[0].Rate + AllSalarySub * dataGroup[0].Percent_worker;
                db.Execute("update TableDepartment set wage =" + Convert.ToInt32(wage) + " where id = " + id);
                db.Dispose();
            }
        }
Exemplo n.º 23
0
        public void updateToRead(string quetion)
        {
            string yes = "yes";
            string no  = "no";

            using (var db = new SQLite.SQLiteConnection(app.dbPath))
            {
                try
                {
                    //var existing = db.Query<English>("update English set read ='" + yes + "' where question ='" + question + "'");
                    var existing = db.Execute("update English set read ='" + yes + "' where answer ='" + question + "'");
                    //var q = db.Execute("update English set read ='" + yes + "'");
                }

                catch (Exception e)
                {
                }
            }
        }
Exemplo n.º 24
0
        public App()
        {
            //Local do banco
            var pasta = new LocalRootFolder();

            //Crio o arquivo do banco (se ele não existir)
            // se ele existir, abor ele
            var arquivo = pasta.CreateFile("banco.db", PCLExt.FileStorage.CreationCollisionOption.OpenIfExists);

            //faço a "conexao"
            Conexao = new SQLite.SQLiteConnection(arquivo.Path);

            // Criar uma tabela, se ela não existir
            Conexao.Execute("CREATE TABLE IF NOT EXISTS informacoes (id INTEGER PRIMARY KEY AUTOINCREMENT, info TEXT)");

            InitializeComponent();

            MainPage = new MainPage();
        }
Exemplo n.º 25
0
        async void ButtonClicked(object sender, EventArgs e)
        {
            script.endDate = RxEnd.Date.ToShortDateString();
            using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(App.FilePath))
            {
                if (script.PrescriptionNotificationIDs != null)
                {
                    foreach (PrescriptionNotificationID notifID in script.PrescriptionNotificationIDs)
                    {
                        CrossLocalNotifications.Current.Cancel(notifID.Id);
                    }
                    //Delete the old notification IDs from the table
                    conn.Execute("DELETE FROM PrescriptionNotificationID WHERE pId = " + script.Id);
                }

                //Set the new reminders using the new reminder time.
                PrescriptionNotifClass.PrescriptionNotifHandler(script);

                conn.Update(script);
            }
            await Navigation.PopAsync();
        }
Exemplo n.º 26
0
        public App()
        {
            var pasta = new LocalRootFolder();

            var arquivo = pasta.CreateFile("banco.db", PCLExt.FileStorage.CreationCollisionOption.OpenIfExists);

            Conexao = new SQLite.SQLiteConnection(arquivo.Path);

            Conexao.Execute("CREATE TABLE IF NOT EXISTS cliente (ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, nome_cliente TEXT (255) NOT NULL, cpf BIGINTEGER UNIQUE NOT NULL, data_nascimento TEXT (15) NOT NULL, sexo TEXT (15) NOT NULL, email TEXT (255) UNIQUE NOT NULL, telefone_celular INTEGER (15) NOT NULL, observacao TEXT (255) NOT NULL)");
            Conexao.Execute("CREATE TABLE IF NOT EXISTS funcionario (ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, nome_funcionario TEXT (255) NOT NULL, cpf BIGINTEGER UNIQUE NOT NULL, data_nascimento TEXT (15) NOT NULL, sexo TEXT (15) NOT NULL, email TEXT (255) UNIQUE NOT NULL, telefone_celular INTEGER (15) NOT NULL, horario_atendimento TEXT (255) NOT NULL)");
            Conexao.Execute("CREATE TABLE IF NOT EXISTS promocao (ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, status TEXT (50) NOT NULL, nome_promocao TEXT (255) UNIQUE NOT NULL, descricao TEXT (255) NOT NULL, tempo TEXT (50) NOT NULL, valor TEXT NOT NULL)");
            Conexao.Execute("CREATE TABLE IF NOT EXISTS servico (ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, status TEXT (50) NOT NULL, nome_servico TEXT (255) UNIQUE NOT NULL, descricao TEXT (255) NOT NULL, tempo TEXT (50) NOT NULL, valor TEXT NOT NULL)");
            Conexao.Execute("CREATE TABLE IF NOT EXISTS usuario (ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, usuario TEXT (100) UNIQUE NOT NULL, senha TEXT (100) NOT NULL, email TEXT (255) UNIQUE NOT NULL)");
            Conexao.Execute("CREATE TABLE IF NOT EXISTS agendamento (ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, nome_cliente TEXT (255) NOT NULL, nome_funcionario TEXT (255) NOT NULL, servico TEXT (255) NOT NULL, horario TEXT (50) NOT NULL, duracao TEXT (50) NOT NULL, data TEXT (50) NOT NULL)");

            InitializeComponent();

            MainPage = new NavigationPage(new MainPage());
            //MainPage = new MainPage();
        }
Exemplo n.º 27
0
        }                                                            //conexao com o banco de dados

        public App()
        {
            var pasta = new LocalRootFolder();

            ////crio o arquivo do banco (se ele não existir)
            ////Se ele existir, só quero que abra

            var arquivo = pasta.CreateFile("confrariapp.db", PCLExt.FileStorage.CreationCollisionOption.OpenIfExists);

            ////faço a "conexao"
            conexao = new SQLite.SQLiteConnection(arquivo.Path);

            ////criar a tabela, se ela não existir
            conexao.Execute("CREATE TABLE IF NOT EXISTS CadastroCliente (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, nome TEXT NOT NULL, login TEXT NOT NULL, data TEXT NOT NULL, telefone INTEGER NOT NULL, senha TEXT NOT NULL)");
            conexao.Execute("CREATE TABLE IF NOT EXISTS CadastroBebida (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, nome TEXT NOT NULL, descricao TEXT NOT NULL, valor TEXT NOT NULL, categoria TEXT NOT NULL)");
            conexao.Execute("CREATE TABLE IF NOT EXISTS CadastroPorcao (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, nome TEXT NOT NULL, descricao TEXT NOT NULL, valor TEXT NOT NULL, categoria TEXT NOT NULL)");
            conexao.Execute("CREATE TABLE IF NOT EXISTS CadastroSuvenir (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, nome TEXT NOT NULL, descricao TEXT NOT NULL, valor TEXT NOT NULL, categoria TEXT NOT NULL)");
            conexao.Execute("CREATE TABLE IF NOT EXISTS CadastroReserva (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, nomeCliente TEXT NOT NULL, qtdpessoas INTEGER NOT NULL, data TEXT NOT NULL, observacao TEXT NOT NULL)");
            conexao.Execute("CREATE TABLE IF NOT EXISTS CadastroProgramacao (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, nomeprog TEXT NOT NULL, data TEXT NOT NULL, descricao TEXT NOT NULL)");

            InitializeComponent();
            MainPage = new NavigationPage(new LoginPage());
        }
Exemplo n.º 28
0
        public string updateToRead2(string quetion)
        {
            string isUpdated = "";
            string yes = "yes";
            string no = "no";
            using (var db = new SQLite.SQLiteConnection(app.dbPath))
            {
                try
                {
                    var existing = db.Execute("update English set read ='" + yes + "' where question ='" + question + "'");
                    if (existing != null)
                    {
                        isUpdated = "true";
                    }
                    else
                    {
                        isUpdated = "false";
                    }
                }

                catch (Exception e)
                {

                }
            }
            return isUpdated;
        }
 private void test(int id)
 {
     using (var db = new SQLite.SQLiteConnection(app.dbPath))
     {
         db.Execute("Delete from PowerBallResults where Id = ?", id);
     }
 }
Exemplo n.º 30
0
 public ISQLiteConnection GetSqliteConnection()
 {
     if (isPoolingEnabled)
     {
         return mainPool.GetSqliteConnection();
     }
     else
     {
         ISQLiteConnection conn = new SQLite.SQLiteConnection(DatabasePath);
         conn.Execute("PRAGMA synchronous = OFF");
         // Five second busy timeout
         conn.BusyTimeout = new TimeSpan(0, 0, 5);
         return conn;
     }
 }
Exemplo n.º 31
0
        public void updateToRead(string quetion)
        {
            string yes = "yes";
            string no = "no";
            using (var db = new SQLite.SQLiteConnection(app.dbPath))
            {
                try
                {
                    //var existing = db.Query<English>("update English set read ='" + yes + "' where question ='" + question + "'");
                    var existing = db.Execute("update English set read ='" + yes + "' where answer ='" + question + "'");
                    //var q = db.Execute("update English set read ='" + yes + "'");
                }

                catch (Exception e)
                {

                }
            }
        }
		private void SettingsAction()
		{
			try {
				UIActionSheet actionSheet;
				actionSheet = new UIActionSheet();

				actionSheet.AddButton("Refresh Securecom Contacts");
				actionSheet.AddButton("Re-register");
				actionSheet.AddButton("Cancel");

				actionSheet.Clicked += delegate(object a, UIButtonEventArgs b) {
					if (b.ButtonIndex == (0)) {
						try {
							LoadingOverlay loadingOverlay;

							// Determine the correct size to start the overlay (depending on device orientation)
							var bounds = UIScreen.MainScreen.Bounds; // portrait bounds
							if (UIApplication.SharedApplication.StatusBarOrientation == UIInterfaceOrientation.LandscapeLeft || UIApplication.SharedApplication.StatusBarOrientation == UIInterfaceOrientation.LandscapeRight) {
								bounds.Size = new SizeF(bounds.Size.Height, bounds.Size.Width);
							}
							// show the loading overlay on the UI thread using the correct orientation sizing
							loadingOverlay = new LoadingOverlay(bounds);
							this.View.Add(loadingOverlay);

							Task taskA = Task.Factory.StartNew(StextUtil.RefreshPushDirectory);
							taskA.Wait();
							loadingOverlay.Hide();

						} catch (Exception e) {
							UIAlertView alert = new UIAlertView("Failed!", "Contact Refresh Failed!", null, "Ok");
							alert.Show();
						}

					} else if (b.ButtonIndex == (1)) {
							var alert = new UIAlertView {
								Title = "Re-register?", 
								Message = "This action will delete your preivious conversations!"
							};
							alert.AddButton("Yes");
							alert.AddButton("No");
							// last button added is the 'cancel' button (index of '2')
							alert.Clicked += delegate(object a1, UIButtonEventArgs b1) {
								if (b1.ButtonIndex == (0)) {
									using (var conn = new SQLite.SQLiteConnection(AppDelegate._dbPath)) {
										conn.Execute("DELETE FROM PushContact");
										conn.Execute("DELETE FROM PushChatThread");
										conn.Execute("DELETE FROM PushMessage");
										conn.Commit();
										conn.Close();
									}
									Session.ClearSessions();
									appDelegate.GoToView(appDelegate.registrationView);
								}
							};
							alert.Show();
						} 
				};
				actionSheet.ShowInView(View);
			} catch (Exception ex) {
				Console.Write(ex.Message);
			}
		}
Exemplo n.º 33
0
		public static void RefreshPushDirectory()
		{
			Console.WriteLine("starting contacts sync");
			AddressBook book = new AddressBook();
			PhoneNumberUtil phoneUtil = PhoneNumberUtil.GetInstance();
			book.RequestPermission().ContinueWith(t => {
				if (!t.Result) {
					Console.WriteLine("Permission denied by user or manifest");
					return;
				}
				long now = Utils.CurrentTimeMillis();
				Dictionary<String, String> map = new Dictionary<String, String>();
				int i = 0, j = 0, k = 0;
				foreach (Contact contact in book) {
					if (String.IsNullOrEmpty(contact.DisplayName))
						continue;
					foreach (Phone phone in contact.Phones) {
						j++;
						if (phone.Number.Contains("*") || phone.Number.Contains("#"))
							continue;
						try {
							String number = phoneUtil.Format(phoneUtil.Parse(phone.Number, AppDelegate.GetCountryCode()), PhoneNumberFormat.E164);
							if (!map.ContainsKey(number))
								map.Add(number, contact.DisplayName);
						} catch (Exception e) {
							Console.WriteLine("Exception parsing/formatting '" + phone.Number + "': " + e.Message);
						}
					}
					foreach (Email email in contact.Emails) {
						k++;
						if (!map.ContainsKey(email.Address))
							map.Add(email.Address, contact.DisplayName);
					}
					i++;
				}
				Console.WriteLine(i + " contacts in address book with " + j + " phone numbers and " + k + " email addresses");
				Dictionary<String, String> tokens = hashNumbers(map.Keys.ToList());
				List<String> response = MessageManager.RetrieveDirectory(tokens.Keys.ToList());
				Console.WriteLine("found " + response.Count + " securecom users");
				using (var conn = new SQLite.SQLiteConnection(AppDelegate._dbPath)) {
					conn.BeginTransaction();
					conn.Execute("DELETE FROM PushContact");
					foreach (String key in response) {
						String number = tokens[key];
						if (number == null) // is this needed?
							continue;
						conn.Insert(new PushContact { Number = number, Name = map[number] });
					}
					conn.Commit();

				}
				Console.WriteLine("contacts sync finished, took " + ((Utils.CurrentTimeMillis() - now) / 1000.0) + " seconds");
			}, TaskScheduler.Current);
		}
Exemplo n.º 34
0
		private void AddDataToConversation()
		{
			messages = new List<string>();
			timeStamps = new List<string>();
			isLeft = new List<Boolean>();
			message_ids = new List<long>();
			isdelivered = new List<bool>();
			using (var conn = new SQLite.SQLiteConnection(AppDelegate._dbPath)) {
				// Check if there is an existing thread for this sender
				List<PushMessage> pmList = conn.Query<PushMessage>("SELECT * FROM PushMessage WHERE Thread_id = ?", ThreadID);

				foreach (PushMessage pm in pmList) {
					messages.Add(pm.Message);
					DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddSeconds(pm.TimeStamp / 1000).ToLocalTime();

					timeStamps.Add("" + epoch.ToString("ddd HH:mm tt"));
					message_ids.Add(pm.TimeStamp);
					isdelivered.Add(pm.Status);
					isLeft.Add(pm.Service == "Push");
				}
				conn.Execute("UPDATE PushChatThread Set Read = ? WHERE ID = ?", 0, ThreadID);
				conn.Commit();
				conn.Close();
			}

		}
Exemplo n.º 35
0
        //Update child details in the database
        public int updateChildInfo(int id, string parentId, string name, string surname, string age, string grade)
        {
            int updated = 0;
            using (var db = new SQLite.SQLiteConnection(app.dbPath))
            {
                updated = db.Execute("Update Child set Name='" +name+ "',Surname='" +surname+ "',Age='" +age+"',Grade='" +grade+ "' where Id=" +id+ " and ParentId='" +parentId+ "'");

            }
            return updated;
        }
Exemplo n.º 36
0
        public ISQLiteConnection GetSqliteConnection()
        {
            lock (connectionPoolLock)
            {
                if (getConnectionsAllowed)
                {
                    ISQLiteConnection conn = null;
                    if (availableConnections.Count > 0)
                    {
                        // Grab an existing connection
                        conn = availableConnections.Pop();
                    }
                    else if (usedConnections < maxConnections)
                    {
                        // There are no available connections, and we have room for more open connections, so make a new one
                        conn = new SQLite.SQLiteConnection(databasePath);
                        conn.Execute("PRAGMA synchronous = OFF");
                        // Five second busy timeout
                        conn.BusyTimeout = new TimeSpan(0, 0, 5);
                    }

                    if (!ReferenceEquals(conn, null))
                    {
                        // We got a connection, so increment the counter
                        usedConnections++;
                        return conn;
                    }
                }
            }

            // If no connection available, sleep for 50ms and try again
            Thread.Sleep(50);

            // Recurse to try to get another connection
            return GetSqliteConnection();
        }
		public void RowSelected(UITableView tableView, NSIndexPath indexPath)
		{

			ChatCell selectedCell = (ChatCell)source.CellGroups[indexPath.Section].Cells[indexPath.Row];
			appDelegate.chatView.setThreadSelected(selectedCell.GetHeader());
			using (var conn = new SQLite.SQLiteConnection(AppDelegate._dbPath)) {
				conn.Execute("UPDATE PushChatThread Set Read = ? WHERE ID = ?", 0, selectedCell.GetThreadID());
				conn.Commit();
				conn.Close();
			}
			appDelegate.chatView.setThreadID(selectedCell.GetThreadID());
			appDelegate.chatView.setNumber(selectedCell.GetNumber());
			appDelegate.GoToView(appDelegate.chatView);
//			UIAlertView alert = new UIAlertView("Chat index selected", ""+indexPath.Row, null, "Ok");
//			alert.Show();

		}
Exemplo n.º 38
0
		public static void UpdateThreadNames()
		{
			var conn = new SQLite.SQLiteConnection(AppDelegate._dbPath);
			List<PushChatThread> pct = conn.Query<PushChatThread>("SELECT * FROM PushChatThread where DisplayName is null or DisplayName = ''");
			PhoneNumberUtil phoneUtil = PhoneNumberUtil.GetInstance();
			AddressBook book = new AddressBook();
			foreach (PushChatThread thread in pct) {
				String display_name = null;
				foreach (Contact c in book) {
					if (thread.Number.Contains("@")) {
						if (!c.Emails.Any())
							continue;
						foreach (Email e in c.Emails) {
							if (thread.Number.Equals(e.Address)) {
								display_name = c.DisplayName;
								break;
							}
						}
					} else {
						if (!c.Phones.Any())
							continue;
						foreach (Phone p in c.Phones) {
							if (p.Number.Contains("*") || p.Number.Contains("#"))
								continue;
							try {
								String number = phoneUtil.Format(phoneUtil.Parse(p.Number, AppDelegate.GetCountryCode()), PhoneNumberFormat.E164);
								if (thread.Number.Equals(number)) {
									display_name = c.DisplayName;
									break;
								}
							} catch (Exception e) {
								Console.WriteLine("Exception parsing/formatting '" + p.Number + "': " + e.Message);
							}
						}
					}
					if (display_name != null) {
						conn.Execute("UPDATE PushChatThread Set DisplayName = ? WHERE ID = ?", display_name, thread.ID);
						break;
					}
				}
			}
			conn.Commit();
			conn.Close();
		}
		public void DeleteSelected(UITableView tableView, NSIndexPath indexPath)
		{
			ChatCell selectedCell = (ChatCell)source.CellGroups[indexPath.Section].Cells[indexPath.Row];
			try {
				using (var conn = new SQLite.SQLiteConnection(AppDelegate._dbPath)) {
					conn.Execute("DELETE FROM PushChatThread WHERE ID = ?", selectedCell.GetThreadID());
					conn.Execute("DELETE FROM PushMessage WHERE Thread_id = ?", selectedCell.GetThreadID());
					conn.Commit();
					conn.Close();
				}
			} catch (Exception e) {
				Console.WriteLine("Error while deleting thread " + e.Message);
			}
			ShowEditButton();
//			UIAlertView alert = new UIAlertView("Deleted Conversation with", ""+selectedCell.GetNumber(), null, "Ok");
//			alert.Show();
		}
Exemplo n.º 40
0
        public static async void InsertForeignData(int user_id, int box_id)
        {
            ApiService apiService = new ApiService();

            int  user_I      = user_id;
            var  apiSecurity = Application.Current.Resources["APISecurity"].ToString();
            User box_detail  = new User();

            AddViewToUser(user_I);
            box_detail = await apiService.GetUserId(apiSecurity,
                                                    "/api",
                                                    "/Users",
                                                    user_I);

            using (var connSQLite = new SQLite.SQLiteConnection(App.root_db))
            {
                connSQLite.CreateTable <ForeingProfile>();
            }

            ForeingBox     foreingBox;
            ForeingProfile foreingProfile;
            ForeingBox     A          = new ForeingBox();
            ForeingBox     oldForeing = new ForeingBox();;

            //Validar que la box no exista
            using (var connSQLite = new SQLite.SQLiteConnection(App.root_db))
            {
                A = connSQLite.FindWithQuery <ForeingBox>("select * from ForeingBox where ForeingBox.BoxId = " + box_id + " and ForeingBox.UserRecivedId = " + MainViewModel.GetInstance().User.UserId);
            }

            if (A == null)
            {
                //Inicializar la box foranea
                foreingBox = new ForeingBox
                {
                    BoxId  = box_id,
                    UserId = user_I,
                    //Time = Convert.ToDateTime(nfcData[0].time).ToUniversalTime(),
                    Time          = DateTime.Now,
                    ImagePath     = box_detail.ImagePath,
                    UserTypeId    = box_detail.UserTypeId,
                    FirstName     = box_detail.FirstName,
                    LastName      = box_detail.LastName,
                    Edad          = box_detail.Edad,
                    Ubicacion     = box_detail.Ubicacion,
                    Ocupacion     = box_detail.Ocupacion,
                    Conexiones    = box_detail.Conexiones,
                    UserRecivedId = MainViewModel.GetInstance().User.UserId
                };

                //Insertar la box foranea
                using (var connSQLite = new SQLite.SQLiteConnection(App.root_db))
                {
                    connSQLite.Insert(foreingBox);
                }
            }
            else
            {
                using (var connSQLite = new SQLite.SQLiteConnection(App.root_db))
                {
                    oldForeing = A;
                    connSQLite.ExecuteScalar <ForeingBox>("UPDATE ForeingBox SET Conexiones = ? WHERE ForeingBox.UserId = ?", box_detail.Conexiones, box_detail.UserId);
                    connSQLite.ExecuteScalar <ForeingBox>("UPDATE ForeingBox SET Time = ? WHERE ForeingBox.BoxId = ?", DateTime.Now, A.BoxId);
                    A = connSQLite.FindWithQuery <ForeingBox>("select * from ForeingBox where ForeingBox.BoxId = ?", box_id);
                }
                foreingBox = A;
            }
            try
            {
                if (box_id != 0)
                {
                    //using (var connSQLite = new SQLite.SQLiteConnection(App.root_db))
                    //{
                    //    connSQLite.CreateTable<Profile_get>();
                    //}
                    if (A != null)
                    {
                        using (var connSQLite = new SQLite.SQLiteConnection(App.root_db))
                        {
                            connSQLite.Execute("Delete from ForeingProfile Where ForeingProfile.BoxId = ?", A.BoxId);
                        }
                    }
                    #region ForeignProfiles
                    System.Text.StringBuilder sb;
                    string cadenaConexion = @"data source=serverappmynfo.database.windows.net;initial catalog=mynfo;user id=adminmynfo;password=4dmiNFC*Atx2020;Connect Timeout=60";

                    //string cadenaConexion = @"data source=serverappmynfo1.database.windows.net;initial catalog=mynfo;user id=adminmynfo;password=4dmiNFC*Atx2020;Connect Timeout=60";

                    //Creación de perfiles locales de box local
                    string queryGetBoxEmail = "select * from dbo.ProfileEmails " +
                                              "join dbo.Box_ProfileEmail on" +
                                              "(dbo.ProfileEmails.ProfileEmailId = dbo.Box_ProfileEmail.ProfileEmailId) " +
                                              "where dbo.Box_ProfileEmail.BoxId = " + box_id;
                    string queryGetBoxPhone = "select * from dbo.ProfilePhones " +
                                              "join dbo.Box_ProfilePhone on" +
                                              "(dbo.ProfilePhones.ProfilePhoneId = dbo.Box_ProfilePhone.ProfilePhoneId) " +
                                              "where dbo.Box_ProfilePhone.BoxId = " + box_id;
                    string queryGetBoxSMProfiles = "select * from dbo.ProfileSMs " +
                                                   "join dbo.Box_ProfileSM on" +
                                                   "(dbo.ProfileSMs.ProfileMSId = dbo.Box_ProfileSM.ProfileMSId) " +
                                                   "join dbo.RedSocials on(dbo.ProfileSMs.RedSocialId = dbo.RedSocials.RedSocialId) " +
                                                   "where dbo.Box_ProfileSM.BoxId = " + box_id;
                    string queryGetBoxWhatsappProfiles = "select * from dbo.ProfileWhatsapps " +
                                                         "join dbo.Box_ProfileWhatsapp on" +
                                                         "(dbo.ProfileWhatsapps.ProfileWhatsappId = dbo.Box_ProfileWhatsapp.ProfileWhatsappId) " +
                                                         "where dbo.Box_ProfileWhatsapp.BoxId = " + box_id;

                    //Consulta para obtener perfiles email
                    using (SqlConnection conn1 = new SqlConnection(cadenaConexion))
                    {
                        sb = new System.Text.StringBuilder();
                        sb.Append(queryGetBoxEmail);

                        string sql = sb.ToString();

                        using (SqlCommand command = new SqlCommand(sql, conn1))
                        {
                            conn1.Open();
                            using (SqlDataReader reader = command.ExecuteReader())
                            {
                                while (reader.Read())
                                {
                                    foreingProfile = new ForeingProfile
                                    {
                                        BoxId       = box_id,
                                        UserId      = (int)reader["UserId"],
                                        ProfileName = (string)reader["Name"],
                                        value       = (string)reader["Email"],
                                        ProfileType = "Email"
                                    };
                                    //Crear perfil de correo de box local predeterminada
                                    using (var connSQLite = new SQLite.SQLiteConnection(App.root_db))
                                    {
                                        connSQLite.Insert(foreingProfile);
                                    }
                                }
                            }

                            conn1.Close();
                        }
                    }

                    //Consulta para obtener perfiles teléfono
                    using (SqlConnection conn1 = new SqlConnection(cadenaConexion))
                    {
                        sb = new System.Text.StringBuilder();
                        sb.Append(queryGetBoxPhone);

                        string sql = sb.ToString();

                        using (SqlCommand command = new SqlCommand(sql, conn1))
                        {
                            conn1.Open();
                            using (SqlDataReader reader = command.ExecuteReader())
                            {
                                while (reader.Read())
                                {
                                    foreingProfile = new ForeingProfile
                                    {
                                        BoxId       = box_id,
                                        UserId      = (int)reader["UserId"],
                                        ProfileName = (string)reader["Name"],
                                        value       = (string)reader["Number"],
                                        ProfileType = "Phone"
                                    };
                                    //Crear perfil de teléfono de box local predeterminada
                                    using (var connSQLite = new SQLite.SQLiteConnection(App.root_db))
                                    {
                                        connSQLite.Insert(foreingProfile);
                                    }
                                }
                            }

                            conn1.Close();
                        }
                    }

                    //Consulta para obtener perfiles de redes sociales
                    using (SqlConnection conn1 = new SqlConnection(cadenaConexion))
                    {
                        sb = new System.Text.StringBuilder();
                        sb.Append(queryGetBoxSMProfiles);

                        string sql = sb.ToString();

                        using (SqlCommand command = new SqlCommand(sql, conn1))
                        {
                            conn1.Open();
                            using (SqlDataReader reader = command.ExecuteReader())
                            {
                                while (reader.Read())
                                {
                                    foreingProfile = new ForeingProfile
                                    {
                                        BoxId       = box_id,
                                        UserId      = (int)reader["UserId"],
                                        ProfileName = (string)reader["ProfileName"],
                                        value       = (string)reader["link"],
                                        ProfileType = (string)reader["Name"]
                                    };
                                    //Crear perfil de teléfono de box local predeterminada
                                    using (var connSQLite = new SQLite.SQLiteConnection(App.root_db))
                                    {
                                        connSQLite.Insert(foreingProfile);
                                    }
                                }
                            }
                            conn1.Close();
                        }
                    }

                    //Consulta para obtener perfiles Whatsapp
                    using (SqlConnection conn1 = new SqlConnection(cadenaConexion))
                    {
                        sb = new System.Text.StringBuilder();
                        sb.Append(queryGetBoxWhatsappProfiles);

                        string sql = sb.ToString();

                        using (SqlCommand command = new SqlCommand(sql, conn1))
                        {
                            conn1.Open();
                            using (SqlDataReader reader = command.ExecuteReader())
                            {
                                while (reader.Read())
                                {
                                    foreingProfile = new ForeingProfile
                                    {
                                        BoxId       = box_id,
                                        UserId      = (int)reader["UserId"],
                                        ProfileName = (string)reader["Name"],
                                        value       = (string)reader["Number"],
                                        ProfileType = "Whatsapp"
                                    };
                                    //Crear perfil de Whatsapp de box local predeterminada
                                    using (var connSQLite = new SQLite.SQLiteConnection(App.root_db))
                                    {
                                        connSQLite.Insert(foreingProfile);
                                    }
                                }
                            }

                            conn1.Close();
                        }
                    }
                    #endregion
                    Device.BeginInvokeOnMainThread(() =>
                    {
                        //App.Navigator.PushAsync(new ForeingBoxPage(foreingBox, true));
                        MainViewModel.GetInstance().ForeingBox = new ForeingBoxViewModel(foreingBox);
                        //App.Navigator.PopAsync();
                        if (PopupNavigation.PopupStack.Count != 0)
                        {
                            PopupNavigation.Instance.PopAllAsync();
                        }
                        //PopupNavigation.Instance.PushAsync(new ForeingBoxPage(foreingBox, true));
                        if (A == null)
                        {
                            MainViewModel.GetInstance().ListForeignBox.AddList(foreingBox);
                        }
                        else
                        {
                            //Box anterior
                            //oldForeing
                            MainViewModel.GetInstance().ListForeignBox.UpdateList(foreingBox.UserId);
                        }
                        PopupNavigation.Instance.PushAsync(new ForeingBoxPage(foreingBox, true));
                    });
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Exemplo n.º 41
0
		public void DeleteSelected(UITableView tableView, NSIndexPath indexPath)
		{
			ChatBubbleCell selectedCell = (ChatBubbleCell)source.CellGroups[indexPath.Section].Cells[indexPath.Row];
			try {
				lock (this) {
					using (var conn = new SQLite.SQLiteConnection(AppDelegate._dbPath)) {
						conn.Execute("DELETE FROM PushMessage WHERE TimeStamp = ?", selectedCell.getMessageID());
						conn.Commit();
						conn.Close();
						ViewWillAppear(true);
					}
				}
			} catch (Exception e) {
				Console.WriteLine("Error while deleting thread " + e.Message);
			}
		}
Exemplo n.º 42
0
 public void deletePowerballSaved(int gg)
 {
     using (var db = new SQLite.SQLiteConnection(app.dbPath))
     {
         db.Execute("Delete from PowerBallSaved where Id = ?", gg);
     }
 }
Exemplo n.º 43
0
        private void UpdateDatbase()
        {
            try {
                using (var conn = new SQLite.SQLiteConnection (pathToDatabase)) {

                    var num = conn.ExecuteScalar<Int32> ("SELECT count(name) FROM sqlite_master WHERE type='table' and name='CNNote'", new object[]{ });
                    int count = Convert.ToInt32 (num);
                    if (count > 0)
                        return;

                    conn.CreateTable<CNNote> ();
                    conn.CreateTable<CNNoteDtls> ();
                    conn.DropTable<AdPara> ();
                    conn.CreateTable<AdPara> ();
                    conn.DropTable<AdNumDate> ();
                    conn.CreateTable<AdNumDate> ();
                    conn.DropTable<CompanyInfo> ();
                    conn.CreateTable<CompanyInfo> ();
                    conn.DropTable<Trader> ();
                    conn.CreateTable<Trader> ();
                    conn.DropTable<AdUser> ();
                    conn.CreateTable<AdUser> ();

                    string sql = @"ALTER TABLE Invoice RENAME TO sqlitestudio_temp_table;
                                    CREATE TABLE Invoice (invno varchar PRIMARY KEY NOT NULL, trxtype varchar, invdate bigint, created bigint, amount float, taxamt float, custcode varchar, description varchar, uploaded bigint, isUploaded integer, isPrinted integer);
                                    INSERT INTO Invoice (invno, trxtype, invdate, created, amount, taxamt, custcode, description, uploaded, isUploaded,isPrinted) SELECT invno, trxtype, invdate, created, amount, taxamt, custcode, description, uploaded, isUploaded,0 FROM sqlitestudio_temp_table;
                                    DROP TABLE sqlitestudio_temp_table";
                    string[] sqls = sql.Split (new char[]{ ';' });
                    foreach (string ssql in sqls) {
                        conn.Execute (ssql, new object[]{ });
                    }
                }
            } catch (Exception ex) {
                AlertShow (ex.Message);
            }
        }
Exemplo n.º 44
0
        //Update all field for parent in the database
        public int updateParentDetails(int id, string name, string surname, string email, string phone, string password)
        {
            int updated = 0;
            using (var db = new SQLite.SQLiteConnection(app.dbPath))
            {
                updated = db.Execute("Update Parents set Name='" + name +
                                                         "',Surname='" + surname +
                                                         "',Email='" + email +
                                                         "',PhoneNo='" + phone +
                                                         "',Password='******' where Id=" + id);

            }
            return updated;
        }
Exemplo n.º 45
0
 public void deleteRowOnLottoSaved(int id)
 {
     using (var db = new SQLite.SQLiteConnection(app.dbPath))
     {
         db.Execute("Delete from LottoSaved where Id = ?", id);
     }
 }
		private void updateChatThread(IncomingMessage message, string msg)
		{
			// Figure out where the SQLite database will be.
			var conn = new SQLite.SQLiteConnection(_dbPath);
			String number = message.Sender;
			// Check if there is an existing thread for this sender

			PushChatThread thread = conn.FindWithQuery<PushChatThread>("select * from PushChatThread where Number = ?", number);
			if (thread != null) {
				conn.Execute("UPDATE PushChatThread Set Snippet = ?, TimeStamp = ?, Message_count = ?, Read = ?, Type = ? WHERE ID = ?", msg, message.MessageId, 1, 1, "Push", thread.ID);
				conn.Commit();
			} else {
				PushContact contact = conn.FindWithQuery<PushContact>("select * from PushContact where Number = ?", number);
				thread = new PushChatThread {
					DisplayName = contact.Name,
					Number = number,
					Recipient_id = 0,
					TimeStamp = Convert.ToInt64(message.MessageId),
					Message_count = 1,
					Snippet = msg,
					Read = 1,
					Type = "Push"
				};
				conn.Insert(thread);
				//conn.Execute("UPDATE PushChatThread Set Recipient_id = ? WHERE Number = ?", present_thread_id, sender);
			}

			var pmessage = new PushMessage {
				Thread_id = thread.ID,
				Number = number,
				TimeStamp = CurrentTimeMillis(),
				TimeStamp_Sent = Convert.ToInt64(message.MessageId),
				Read = 1,
				Message = msg,
				Status = true,
				Service = "Push"
			};
			conn.Insert(pmessage);
			conn.Commit();
			conn.Close();
			RefreshChatListView();
		}
Exemplo n.º 47
0
        public async void InsertForeignData(int user_id, int box_id)
        {
            try
            {
                var apiSecurity = Application.Current.Resources["APISecurity"].ToString();
                AddViewToUser(user_id);
                var ForeingUser = await apiService.GetUserId(apiSecurity,
                                                             "/api",
                                                             "/Users",
                                                             user_id);

                using (var connSQLite = new SQLite.SQLiteConnection(App.root_db))
                {
                    connSQLite.CreateTable <ForeingProfile>();
                }

                ForeingBox foreingBox;
                ForeingBox A          = new ForeingBox();
                ForeingBox oldForeing = new ForeingBox();

                //Validar que la box no exista
                using (var connSQLite = new SQLite.SQLiteConnection(App.root_db))
                {
                    A = connSQLite.FindWithQuery <ForeingBox>("select * from ForeingBox where ForeingBox.BoxId = " + box_id + " and ForeingBox.UserRecivedId = " + MainViewModel.GetInstance().User.UserId);
                }

                if (A == null)
                {
                    //Inicializar la box foranea
                    foreingBox = new ForeingBox
                    {
                        BoxId         = box_id,
                        UserId        = user_id,
                        Time          = DateTime.Now,
                        ImagePath     = ForeingUser.ImagePath,
                        UserTypeId    = ForeingUser.UserTypeId,
                        FirstName     = ForeingUser.FirstName,
                        LastName      = ForeingUser.LastName,
                        Edad          = ForeingUser.Edad,
                        Ubicacion     = ForeingUser.Ubicacion,
                        Ocupacion     = ForeingUser.Ocupacion,
                        Conexiones    = ForeingUser.Conexiones,
                        UserRecivedId = MainViewModel.GetInstance().User.UserId
                    };

                    //Insertar la box foranea
                    using (var connSQLite = new SQLite.SQLiteConnection(App.root_db))
                    {
                        connSQLite.CreateTable <ForeingBox>();
                        connSQLite.Insert(foreingBox);
                    }
                }
                else
                {
                    using (var connSQLite = new SQLite.SQLiteConnection(App.root_db))
                    {
                        oldForeing = A;
                        connSQLite.ExecuteScalar <ForeingBox>("UPDATE ForeingBox SET Conexiones = ? WHERE ForeingBox.UserId = ?", ForeingUser.Conexiones, ForeingUser.UserId);
                        connSQLite.ExecuteScalar <ForeingBox>("UPDATE ForeingBox SET Time = ? WHERE ForeingBox.BoxId = ?", DateTime.Now, A.BoxId);
                        A = connSQLite.FindWithQuery <ForeingBox>("select * from ForeingBox where ForeingBox.BoxId = ?", box_id);
                    }
                    foreingBox = A;
                }

                if (box_id != 0)
                {
                    if (A != null)
                    {
                        using (var connSQLite = new SQLite.SQLiteConnection(App.root_db))
                        {
                            connSQLite.Execute("Delete from ForeingProfile Where ForeingProfile.BoxId = ?", A.BoxId);
                        }
                    }

                    #region Foreing Profiles New Code
                    await GetListEmail(user_id, box_id);
                    await GetListPhone(user_id, box_id);
                    await GetListSM(user_id, box_id);
                    await GetListWhatsapp(user_id, box_id);

                    #endregion

                    if (NotNull1 == true && NotNull2 == true && NotNull3 == true && NotNull4 == true)
                    {
                        Device.BeginInvokeOnMainThread(() =>
                        {
                            MainViewModel.GetInstance().ForeingBox = new ForeingBoxViewModel(foreingBox);
                            if (PopupNavigation.PopupStack.Count != 0)
                            {
                                PopupNavigation.Instance.PopAllAsync();
                            }

                            if (A == null)
                            {
                                MainViewModel.GetInstance().ListForeignBox.AddList(foreingBox);
                            }
                            else
                            {
                                //Box anterior
                                //oldForeing
                                MainViewModel.GetInstance().ListForeignBox.UpdateList(foreingBox.UserId);
                            }
                            PopupNavigation.Instance.PushAsync(new ForeingBoxPage(foreingBox, true));
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Exemplo n.º 48
0
        public App()
        {
            //Local do banco
            var pasta = new LocalRootFolder();

            //crio o arquivo do banco, se ele existir abro ele

            var arquivo = pasta.CreateFile("Banco.db", PCLExt.FileStorage.CreationCollisionOption.OpenIfExists);

            //faço a Conexão
            conexao = new SQLite.SQLiteConnection(arquivo.Path);

            //criar tabela, se ela não existir

            conexao.Execute("CREATE TABLE IF NOT EXISTS Clientes (ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
                            "Nome TEXT(255) NOT NULL, " +
                            "CPF BIGINTEGER(11) NOT NULL, " +
                            "RG INTEGER(9) NOT NULL, " +
                            "DataNascimento TEXT(8) NOT NULL, " +
                            "Sexo TEXT(10) NOT NULL, " +
                            "TelefoneCelular INTEGER(11) NOT NULL, " +
                            "TelefoneResidencial INTEGER(11) NOT NULL, " +
                            "Email TEXT(255) NOT NULL, " +
                            "Rua TEXT(255) NOT NULL, " +
                            "Bairro TEXT(100)  NOT NULL, " +
                            "Numero INTEGER(5) NOT NULL, " +
                            "UF TEXT(2) NOT NULL, " +
                            "CEP INTEGER(20) NOT NULL)");

            conexao.Execute("CREATE TABLE IF NOT EXISTS Produtos (ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
                            "NomeProduto TEXT(255) NOT NULL, " +
                            "Categoria TEXT(100) NOT NULL, " +
                            "DescricaoProduto TEXT(255)  NOT NULL, " +
                            "Quantidade INTEGER(50) NOT NULL, " +
                            "Fornecedores TEXT(255) NOT NULL, " +
                            "Unidade INTEGER(5) NOT NULL, " +
                            "Total INTEGER(5)  NOT NULL)");

            conexao.Execute("CREATE TABLE IF NOT EXISTS Categoria (ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
                            "categoria TEXT(100) NOT NULL)");

            conexao.Execute("CREATE TABLE IF NOT EXISTS Fornecedores (ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
                            "NomeFornecedor TEXT(255) NOT NULL, " +
                            "CNPJ INTEGER(14) NOT NULL, " +
                            "DataNascimento TEXT(8) NOT NULL, " +
                            "Sexo TEXT(10) NOT NULL, " +
                            "TelefoneCelular INTEGER(11) NOT NULL, " +
                            "TelefoneResidencial iNTEGER(11) NOT NULL, " +
                            "Email TEXT(255) NOT NULL, " +
                            "Rua TEXT(255) NOT NULL, " +
                            "Bairro TEXT(100) NOT NULL, " +
                            "Numero INTEGER(5)  NOT NULL, " +
                            "UF TEXT(2)  NOT NULL, " +
                            "CEP INTEGER(20) NOT NULL)");

            conexao.Execute("CREATE TABLE IF NOT EXISTS Usuarios (ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
                            "Usuario TEXT(200) NOT NULL, " +
                            "senha TEXT(100) NOT NULL, " +
                            "confirmarsenha TEXT(100) NOT NULL, " +
                            "Email TEXT(255) NOT NULL)");
            InitializeComponent();

            MainPage = new NavigationPage(new MainPage());
        }
Exemplo n.º 49
0
        public void Clear(string tableName)
        {
//			db.Delete(tableName);
//			db.CreateCommand ("DELETE FROM" + tableName);
            db.Execute("DELETE FROM " + tableName);
        }
Exemplo n.º 50
0
        //Update new password for parent in the database
        public int updatePassword(int id, string password)
        {
            int updated = 0;
            using (var db = new SQLite.SQLiteConnection(app.dbPath))
            {
                updated = db.Execute("Update Parents set Password='******' where Id=" + id);

            }
            return updated;
        }