public static SQLite.SQLiteConnection Connection() { var conn = new SQLite.SQLiteConnection(DBPath); if (!Initialized) { conn.CreateTable<Car.Car>(); conn.CreateTable<Fillup.Fillup>(); conn.CreateTable<Maintenance.Maintenance>(); conn.CreateTable<Reminder.Reminder>(); var cars = conn.Table<Car.Car>(); if (cars.Count() == 0) { Car.Car car = new Car.Car(); conn.Insert(car); } var firstCar = cars.First(); if (cars.Where(vehicle => vehicle.ID == Settings.CurrentCarID).Count() == 0) Settings.CurrentCarID = firstCar.ID; Initialized = true; } return conn; }
public bool InsertEvent(Event ae1) { try { //Create event if (db.GetTableInfo("Event").Count == 0) { db.CreateTable <Event>(); } int numberOfRows = db.Insert(ae1); //Inserted event if (numberOfRows > 0) { return(true); } else { return(false); } } catch { return(false); } }
public CredentialsService() { try { database = DependencyService.Get <ISQLiteSetup>().GetConnection(); database.CreateTable <Person>(); database.CreateTable <Verification>(); if (database.Table <Person>().Count() == 0) { Person demo = new Person() { Name = "John", Surname = "Doe", Admin = true, Position = "Manager" }; database.Insert(demo); database.Insert(new Verification() { Username = "******", Password = "******", PersonId = demo.Id }); } database.CreateTable <CheckInOut>(); } catch (Exception e) { Debug.WriteLine($"Error instantiating connection to the database!! {e.Message}"); } }
public SqlLiteOrderRepository() { _connection = Xamarin.Forms.DependencyService.Get <ISqlLiteConnection>().GetConnection(); _connection.CreateTable <OrderEntity>(); _connection.CreateTable <OrderItemEntity>(); _connection.CreateTable <OrderCustomerEntity>(); }
public App() { string fileName = "StadiYUMdb.db"; string fileLocation = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); string fullPath = Path.Combine(fileLocation, fileName); DB_PATH = fullPath; using (SQLite.SQLiteConnection db = new SQLite.SQLiteConnection(DB_PATH)) { db.DropTable <Concession>(); db.DropTable <ConcessionItem>(); db.DropTable <Item>(); db.DropTable <Order>(); db.DropTable <RealUser>(); db.CreateTable <Concession>(); db.CreateTable <ConcessionItem>(); db.CreateTable <Item>(); db.CreateTable <Order>(); db.CreateTable <RealUser>(); //var AJBombers = db.Table<Concession>().Where(c => c.Name == "AJ Bombers").FirstOrDefault(); //ConcessionItem concession1 = new ConcessionItem { ConcessionId = (int)AJBombers.Id, ItemId=0 }; //db.Insert(concession1); //ConcessionItem concession2 = new ConcessionItem { ConcessionId = (int)AJBombers.Id, ItemId = 1 }; //db.Insert(concession2); //ConcessionItem concession3 = new ConcessionItem { ConcessionId = (int)AJBombers.Id, ItemId = 2 }; //db.Insert(concession3); //ConcessionItem concession4 = new ConcessionItem { ConcessionId = (int)AJBombers.Id, ItemId = 3 }; //db.Insert(concession4); } InitializeComponent(); MainPage = new NavigationPage(new MainPage()); }
public bool createDataBase() { try { using (var conecction = new SQLite.SQLiteConnection(System.IO.Path.Combine(folder, "AndroidConsultorioDos.db"))) { /*Crear las tablas Locales*/ conecction.CreateTable <Usuario>(); conecction.CreateTable <Doctor>(); conecction.CreateTable <Paciente>(); conecction.CreateTable <PacienteConsulta>(); conecction.CreateTable <Estudios>(); //Consultorio.Usuario Usuario = new Consultorio.Usuario //{ // Nombre = "Ivan" // ,User = "******" // ,Contraseña = "p81bg8f7" //}; //conecction.Insert(Usuario); return(true); } } catch (SQLite.SQLiteException ex) { Log.Info("SQLiteEx", ex.Message); return(false); } }
public static async Task NavigateToProfile(Models.FacebookResponse profile) { if (profile == null) { Application.Current.MainPage = new NavigationPage(new LoginPage()); return; } var apiService = new ApiService(); var apiSecurity = Application.Current.Resources["APISecurity"].ToString(); var token = await apiService.LoginFacebook( apiSecurity, "/api", "/Users/LoginFacebook", profile); if (token == null) { Application.Current.MainPage = new NavigationPage(new LoginPage()); return; } var user = await apiService.GetUserByEmail( apiSecurity, "/api", "/Users/GetUserByEmail", token.TokenType, token.AccessToken, token.UserName); UserLocal userLocal = null; if (user != null) { userLocal = Converter.ToUserLocal(user); //Save Local User in SQLite using (var conn = new SQLite.SQLiteConnection(App.root_db)) { conn.CreateTable <UserLocal>(); conn.CreateTable <TokenResponse>(); conn.Insert(token); conn.Insert(userLocal); } } var mainViewModel = MainViewModel.GetInstance(); mainViewModel.Token = token; mainViewModel.User = userLocal; mainViewModel.Lands = new LandsViewModel(); Application.Current.MainPage = new MasterPage(); Settings.IsRemembered = "true"; mainViewModel.Lands = new LandsViewModel(); Application.Current.MainPage = new MasterPage(); }
/** * Saves the data of a hole * game : the game * hole : the hole to save * save : true to save the hole stats, false otherwise. false returns the ScoreHole anyway * return the created ScoreHole */ public static ScoreHole saveForStats(Partie game, Hole hole, bool save) { ScoreHole h = new ScoreHole(hole, game.getPenalityCount(), game.getCurrentScore(), isHit(game.Shots, hole.Par), nbCoupPutt(game.Shots), DateTime.Now); if (save) { if (game.Shots.Count == 0) { throw new Exception("0 shots dans la liste des shots."); } SQLite.SQLiteConnection connection = DependencyService.Get <ISQLiteDb>().GetConnection(); connection.CreateTable <Club>(); connection.CreateTable <MyPosition>(); connection.CreateTable <Shot>(); //first let's insert in the database all the shots currently stored in the game SQLiteNetExtensions.Extensions.WriteOperations.InsertOrReplaceAllWithChildren(connection, game.Shots, true); connection.CreateTable <ScoreHole>(); //then creates a ScoreHole object that stores the hole statistics and insert it in the database SQLiteNetExtensions.Extensions.WriteOperations.InsertWithChildren(connection, h, false); string sql = @"select last_insert_rowid()"; h.Id = connection.ExecuteScalar <int>(sql); } return(h); }
async void ButtonClicked(object sender, EventArgs e) { User user = new User() { Name = nameEntry.Text, Birthday = (bdayPick.Date).ToShortDateString(), Email = emailEntry.Text, }; if (user.Name == "") { } else { user.Appointments = new List <Appointment> { }; user.Prescriptions = new List <Prescription> { }; using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(App.FilePath)) { conn.CreateTable <User>(); conn.CreateTable <Appointment>(); conn.CreateTable <Prescription>(); conn.Insert(user); await Navigation.PopModalAsync(); } } }
/// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used when the application is launched to open a specific file, to display /// search results, and so forth. /// </summary> /// <param name="args">Details about the launch request and process.</param> protected override void OnLaunched(LaunchActivatedEventArgs args) { Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); if (args.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } // Get a reference to the SQLite database this.DBPath = Path.Combine( Windows.Storage.ApplicationData.Current.LocalFolder.Path, "budget.sqlite"); // Initialize the database if necessary using (var db = new SQLite.SQLiteConnection(this.DBPath)) { // Create the tables if they don't exist db.CreateTable<Budget>(); db.CreateTable<BudgetEnvelope>(); db.CreateTable<Account>(); db.CreateTable<Transaction>(); db.DeleteAll<Budget>(); db.Insert(new Budget() { Id = 1, PaycheckAmount = 1000.0f, Frequency = PaycheckFrequency.SemiMonthly, Name = "My New Budget" }); Budget b = db.Table<Budget>().First(); } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter if (!rootFrame.Navigate(typeof(MainPage), args.Arguments)) { throw new Exception("Failed to create initial page"); } } // Ensure the current window is active Window.Current.Activate(); }
private void CreateTables(SQLite.SQLiteConnection connection) { connection.CreateTable <MediaStatusEntity>(); connection.CreateTable <MediaTypeEntity>(); connection.CreateTable <VersionEntity>(); connection.CreateTable <FavoriteMusicEntity>(); connection.CreateTable <FavoriteSportEntity>(); }
async void ButtonClicked(object sender, EventArgs e) { Conditions cond = new Conditions { Type = "" }; condition.Type = NameEntry.Text; using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(App.FilePath)) { conn.CreateTable <Conditions>(); { try { var c = conn.Query <Conditions>("select * from Conditions where Type=?", condition.Type); cond = conn.GetWithChildren <Conditions>(condition.Type); } catch (Exception f) { } } } if (cond.Type.Equals("")) { using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(App.FilePath)) { conn.CreateTable <Conditions>(); conn.CreateTable <User>(); conn.Insert(condition); conn.UpdateWithChildren(condition); await Navigation.PopModalAsync(); } } else { foreach (User u in cond.Users) { if (u.Id == condition.Users[0].Id) { exists = true; } } if (exists) { await DisplayAlert("Oops!", "You already have this condition listed", "OK"); } else { cond.Users.Add(condition.Users[0]); using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(App.FilePath)) { conn.CreateTable <Conditions>(); conn.UpdateWithChildren(cond); } await Navigation.PopModalAsync(); } } }
async void ButtonClicked(object sender, EventArgs e) { bool exists = false; Allergy a = new Allergy { Type = "" }; allergy.Type = NameEntry.Text; try { using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(App.FilePath)) { conn.CreateTable <Allergy>(); var allergies = conn.Query <Allergy>("select * from Allergy where Type=?", allergy.Type); a = conn.GetWithChildren <Allergy>(allergy.Type); } } catch (Exception f) { } if (a.Type.Equals("")) { using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(App.FilePath)) { conn.CreateTable <Allergy>(); conn.CreateTable <User>(); conn.Insert(allergy); conn.UpdateWithChildren(allergy); } await Navigation.PopModalAsync(); } else { foreach (User u in a.Users) { if (u.Id == allergy.Users[0].Id) { exists = true; break; } } if (exists) { await DisplayAlert("Oops!", "You already have this allergy listed", "OK"); } else { a.Users.Add(allergy.Users[0]); using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(App.FilePath)) { conn.CreateTable <Allergy>(); conn.UpdateWithChildren(a); } await Navigation.PopModalAsync(); } } }
public bool Update(Construction obj) { using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(App.DB_PATH)) { conn.CreateTable <Construction>(); conn.CreateTable <ConstrucionEmployee>(); return(conn.Update(obj) > 0); } }
public Construction GetWithChildren(int id) { using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(App.DB_PATH)) { conn.CreateTable <Construction>(); conn.CreateTable <ConstrucionEmployee>(); return(conn.GetWithChildren <Construction>(id)); } }
public Construction GetById(int id) { using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(App.DB_PATH)) { conn.CreateTable <Construction>(); conn.CreateTable <ConstrucionEmployee>(); return(conn.Query <Construction>("SELECT * FROM Construction WHERE ID = ?", id).FirstOrDefault()); } }
private void SetupDb() { using (var db = new SQLite.SQLiteConnection(AppState.State.Instance.DbPath)) { db.CreateTable <User>(); db.CreateTable <Model.ChallengeProgress>(); db.CreateTable <Model.TaskProgress>(); } }
private void DB_Seed() { using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(App.DbPath)) { conn.CreateTable <TrackLevel>(); if (conn.Table <TrackLevel>().Count() == 0) { TrackLevel Easy = new TrackLevel() { Name = "Easy", Description = "Easy" }; TrackLevel Moderate = new TrackLevel() { Name = "Moderate", Description = "Moderate" }; TrackLevel Difficult = new TrackLevel() { Name = "Difficult", Description = "Difficult" }; conn.Insert(Easy); conn.Insert(Moderate); conn.Insert(Difficult); } conn.CreateTable <TrackType>(); if (conn.Table <TrackType>().Count() == 0) { TrackType Enduro = new TrackType() { Name = "Enduro", Description = "Enduro" }; TrackType Motocross = new TrackType() { Name = "Motocross", Description = "Motocross" }; TrackType Outrides = new TrackType() { Name = "Outrides", Description = "Outrides" }; TrackType MountainBike = new TrackType() { Name = "Mountain Bike", Description = "Mountain Bike" }; TrackType Other = new TrackType() { Name = "Other", Description = "Other" }; conn.Insert(Enduro); conn.Insert(Motocross); conn.Insert(Outrides); conn.Insert(MountainBike); conn.Insert(Other); } } }
/// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } //初始化库 using var db = new SQLite.SQLiteConnection(Application.FileServerService.SQLiteConn); db.CreateTable <Model.SysApp>(); db.CreateTable <Model.FileRecord>(); //配置swagger app.UseSwagger().UseSwaggerUI(c => { c.DocumentTitle = "FileServer API"; c.SwaggerEndpoint("/swagger/v1/swagger.json", "FileServer API"); c.InjectStylesheet("/Home/SwaggerCustomStyle"); }); //静态资源允许跨域 app.UseStaticFiles(new StaticFileOptions() { OnPrepareResponse = (x) => { x.Context.Response.Headers.Add("Access-Control-Allow-Origin", "*"); }, ServeUnknownFileTypes = true }); //目录浏览 string vrootdir = GlobalTo.GetValue("StaticResource:RootDir"); string prootdir = Fast.PathTo.Combine(GlobalTo.WebRootPath, vrootdir); if (!System.IO.Directory.Exists(prootdir)) { System.IO.Directory.CreateDirectory(prootdir); } app.UseFileServer(new FileServerOptions() { FileProvider = new PhysicalFileProvider(prootdir), RequestPath = new Microsoft.AspNetCore.Http.PathString(vrootdir), EnableDirectoryBrowsing = GlobalTo.GetValue <bool>("Safe:EnableDirectoryBrowsing"), EnableDefaultFiles = false }); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); }
public static void CrearTablas() { using (SQLite.SQLiteConnection con = new SQLite.SQLiteConnection(App.RutaDB)) { con.DropTable <Models.Employee>(); con.CreateTable <Models.Employee>(); con.DropTable <Models.EmployeeProduct>(); con.CreateTable <Models.EmployeeProduct>(); } }
public int Create(Construction obj) { using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(App.DB_PATH)) { conn.CreateTable <Construction>(); conn.CreateTable <ConstrucionEmployee>(); conn.Insert(obj); return(conn.ExecuteScalar <int>("SELECT MAX(Id) FROM Construction")); } }
public static void InitializeTournamentMain(SQLite.SQLiteConnection conn) { //Need to create all tables for SQLite conn.CreateTable <TournamentMain>(); conn.CreateTable <TournamentMainPlayer>(); conn.CreateTable <TournamentMainRound>(); //conn.CreateTable<TournamentMainRoundPlayer>(); conn.CreateTable <TournamentMainRoundTable>(); conn.CreateTable <Player>(); }
static DatabaseModel() { string filename = "users_db.sqlite"; string fileLocation = Environment.GetFolderPath(Environment.SpecialFolder.Personal); databaseConnection = new SQLite.SQLiteConnection(Path.Combine(fileLocation, filename)); databaseConnection.CreateTable <User>(); databaseConnection.CreateTable <ImageInfo>(); databaseConnection.CreateTable <Emotion>(); databaseConnection.CreateTable <Group>(); }
public (Dictionary <long, string> Teams, HashSet <long> Results) Get() { using (var conn2 = new SQLite.SQLiteConnection(_name)) { conn2.CreateTable <Team>(); conn2.CreateTable <Result>(); var dictTeams = conn2.Table <Team>().ToList().ToDictionary(_ => _.Id, _ => _.Name); var hsResults = new HashSet <long>(conn2.Table <Result>().ToList().Select(_ => _.Id)); return(dictTeams, hsResults); } }
protected override void OnAppearing() { base.OnAppearing(); User user; using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(App.FilePath)) { conn.CreateTable <User>(); //Ignored if the table already exists conn.CreateTable <Doctor>(); conn.CreateTable <UsersDoctors>(); conn.CreateTable <Vaccine>(); conn.CreateTable <Allergy>(); conn.CreateTable <UsersAllergies>(); conn.CreateTable <Prescription>(); conn.CreateTable <Tables.Conditions>(); conn.CreateTable <UsersConditions>(); user = conn.GetWithChildren <User>(uid); } string allergies = ""; string conditions = ""; if (!(user.Allergies.Count == 0)) { using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(App.FilePath)) { conn.CreateTable <User>(); //Ignored if the table already exists conn.CreateTable <Doctor>(); conn.CreateTable <UsersDoctors>(); conn.CreateTable <Vaccine>(); conn.CreateTable <Allergy>(); conn.CreateTable <UsersAllergies>(); conn.CreateTable <Prescription>(); conn.CreateTable <Tables.Conditions>(); user = conn.GetWithChildren <User>(uid); } foreach (Allergy a in user.Allergies) { allergies = allergies + a.Type + ", "; } allergies = allergies.Remove(allergies.Length - 2); } if (!(user.Conditions.Count == 0)) { foreach (Tables.Conditions c in user.Conditions) { conditions = conditions + c.Type + ", "; } conditions = conditions.Remove(conditions.Length - 2); } Allergies.Text = allergies; Name.Text = user.Name; Bday.Text = user.Birthday; Conditions.Text = conditions; Email.Text = user.Email; }
public static void CreateTables() { _db.CreateTable <Manufacturer>(); _db.CreateTable <Nozzle>(); _db.CreateTable <WaterFlow>(); _db.CreateTable <Pressure>(); _db.CreateTable <CalcSprayQuality>(); _db.CreateTable <SprayQuality>(); _db.CreateTable <WindSpeed>(); _db.CreateTable <LabelSprayQuality>(); _db.CreateTable <BoomHeight>(); _db.CreateTable <Multiplier>(); }
public static void CreateDataBase() { using (var db = new SQLite.SQLiteConnection(DataBasePath)) { db.CreateTable <DataVersionsEntity>(); if (!db.Table <DataVersionsEntity>().Any()) { db.Insert(new DataVersionsEntity()); } db.CreateTable <CategoryLargeEntity>(); if (!db.Table <CategoryLargeEntity>().Any()) { db.Insert(new CategoryLargeEntity() { Id = 1, ContentCategoryLargeName = ResourceTexts.CategorySpecial, IconFileName = nameof(ResourceImages.CategorySpecial) }); db.Insert(new CategoryLargeEntity() { Id = 4, ContentCategoryLargeName = ResourceTexts.CategoryTransferLife, IconFileName = nameof(ResourceImages.CategoryTransferLife) }); db.Insert(new CategoryLargeEntity() { Id = 5, ContentCategoryLargeName = ResourceTexts.CategoryStaySpring, IconFileName = nameof(ResourceImages.CategoryStaySpring) }); db.Insert(new CategoryLargeEntity() { Id = 2, ContentCategoryLargeName = ResourceTexts.CategoryGourmet, IconFileName = nameof(ResourceImages.CategoryGourmet) }); db.Insert(new CategoryLargeEntity() { Id = 3, ContentCategoryLargeName = ResourceTexts.CategoryLocalGourmet, IconFileName = nameof(ResourceImages.CategoryLocalGourmet) }); db.Insert(new CategoryLargeEntity() { Id = 6, ContentCategoryLargeName = ResourceTexts.CategoryToiletParking, IconFileName = nameof(ResourceImages.CategoryToiletParking) }); db.Insert(new CategoryLargeEntity() { Id = 7, ContentCategoryLargeName = ResourceTexts.CategoryPresent, IconFileName = nameof(ResourceImages.CategoryPresent) }); } db.CreateTable <ContentSummaryEntity>(); db.CreateTable <ContentDetailEntity>(); // Plugins foreach (var plugin in App.Plugins) { plugin.CreateDataBase(db); } } }
/// <summary> /// Tworzy potrzebne tabele w bazie danych /// Tworzy folder do zapisu tresci notatek /// </summary> private void CreateTables() { using (SQLite.SQLiteConnection cn = new SQLite.SQLiteConnection(DatabaseHelper.dbFile)) { cn.CreateTable <Notebook>(); cn.CreateTable <Note>(); } //utworzenie folderu na notatki if (!Directory.Exists(NotesPath)) { Directory.CreateDirectory(NotesPath); } }
public DataBase() { var path = GetDatabasePath(DBFileName); if (!File.Exists(path)) { database = new SQLite.SQLiteConnection(path); database.CreateTable <ModelCategory>(); database.CreateTable <ModelDataFile>(); } else { database = new SQLite.SQLiteConnection(path); } }
private void Button_Clicked(object sender, EventArgs e) { if (zvali == -1) { DisplayAlert("Greška", "Stisnite na MI / VI kako biste odabrali ekipu koja je zvala.", "Ok"); return; } if (String.IsNullOrWhiteSpace(miRezEntry.Text) || !miRezEntry.Text.All(char.IsDigit) || String.IsNullOrWhiteSpace(viRezEntry.Text) || !viRezEntry.Text.All(char.IsDigit)) { DisplayAlert("Greška", "Unesite pravilne podatke.", "Ok"); return; } GetResult(ref a, ref b, ref c, ref d); using (SQLite.SQLiteConnection connection = new SQLite.SQLiteConnection(App.DB_PATH)) { connection.CreateTable <Result>(); if (resultToChange == null) { connection.CreateTable <Result>(); connection.Insert(new Result { MiResult = b, ViResult = d, MiZvanje = a, ViZvanje = c, Zvali = zvali }); } else { resultToChange.MiResult = b; resultToChange.ViResult = d; resultToChange.MiZvanje = a; resultToChange.ViZvanje = c; resultToChange.Zvali = zvali; connection.Update(resultToChange); } } if (CheckPad()) { Application.Current.MainPage.Navigation.PushAsync(new Pad(this)); } else { Zavrsi(); } }
/// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used when the application is launched to open a specific file, to display /// search results, and so forth. /// </summary> /// <param name="args">Details about the launch request and process.</param> protected override void OnLaunched(LaunchActivatedEventArgs args) { Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); //Associate the frame with a SuspensionManager key SuspensionManager.RegisterFrame(rootFrame, "AppFrame"); if (args.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } // Get a reference to the SQLite database DBPath = Path.Combine( Windows.Storage.ApplicationData.Current.LocalFolder.Path, "customers.s3db"); // Initialize the database if necessary using (var db = new SQLite.SQLiteConnection(DBPath)) { // Create the tables if they don't exist db.CreateTable <Customer>(); db.CreateTable <Project>(); } ResetData(); // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter if (!rootFrame.Navigate(typeof(MainPage), args.Arguments)) { throw new Exception("Failed to create initial page"); } } // Ensure the current window is active Window.Current.Activate(); }
private void Button_Clicked(object sender, EventArgs e) { Journal journal = new Journal() { JournalName = titleEntry.Text, JournalDetail = detailEntry.Text, PostDate = DateTime.Now }; //create connection to database. when you use "using", you dont need close connection using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(App.DB_PATH)) { //make sure the table exist conn.CreateTable <Journal>(); //number of rows in table var numberOfRows = conn.Insert(journal); if (numberOfRows > 0) { DisplayAlert("Success", "Journal succesfully inserted", "Great!"); } else { DisplayAlert("Failure", "Journal failed to be inserted", "Dang it!"); } } Navigation.PushAsync(new MainPage()); }
private void CreateTable() { using (var conn = new SQLite.SQLiteConnection(GetDatabasePath())) { conn.CreateTable<Person>(); } }
private void btnAdd_Click(object sender, RoutedEventArgs e) { if (FieldValidationExtensions.GetIsValid(AddressbookUserName) && FieldValidationExtensions.GetIsValid(AddressbookEmail)) { var dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "db.sqlite"); using (var db = new SQLite.SQLiteConnection(dbPath)) { db.CreateTable<AddressBookEntree>(); User addressbookuser = new User(); addressbookuser.UserName = AddressbookUserName.Text; addressbookuser.EmailAddress = AddressbookEmail.Text; db.RunInTransaction(() => { db.Insert(addressbookuser); db.Insert(new AddressBookEntree() { OwnerUserID = App.loggedInUser.Id, EntreeUserID = addressbookuser.Id }); }); } } this.Frame.Navigate(typeof(Dashboard)); }
/// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used when the application is launched to open a specific file, to display /// search results, and so forth. /// </summary> /// <param name="args">Details about the launch request and process.</param> protected override void OnLaunched(LaunchActivatedEventArgs args) { // Initialize the database if necessary using (var db = new SQLite.SQLiteConnection(DBPath)) { // Create the tables if they don't exist db.CreateTable<Day>(); db.CreateTable<Intake>(); Day day = new Day(); day.Date = DateTime.Today; db.Insert(day); } CurrentDay = DayViewModel.GetDayByDate(DateTime.Today); Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); if (args.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter if (!rootFrame.Navigate(typeof(MainPage), args.Arguments)) { throw new Exception("Failed to create initial page"); } } // Ensure the current window is active Window.Current.Activate(); }
private async void Button_Click_1(object sender, RoutedEventArgs e) { baza = TextBoxNazwaNowejBazy.Text; string komunikat = textboxkomunikatistniejacabaza.Text; string komunikat2 = TextBoxKomunikatNazwaZastrzezona.Text; string komunikat3 = TextBoxZaKrotkaNazwa.Text; if (baza.Equals("AppData") | baza.Equals("eFiszki") | baza.Equals("efiszki")) { MessageDialog dialog = new MessageDialog(komunikat2); await dialog.ShowAsync(); } else if (baza.Length < 2) { MessageDialog dialog = new MessageDialog(komunikat3); await dialog.ShowAsync(); } else { StorageFolder folder = Windows.Storage.ApplicationData.Current.LocalFolder; IReadOnlyList<StorageFile> fList = await folder.GetFilesAsync(); int sprawdz = 0; foreach (var f in fList) { if (baza.Equals(f.DisplayName)) { sprawdz = 1; } }; if (sprawdz == 1) { MessageDialog dialog = new MessageDialog(komunikat); await dialog.ShowAsync(); } else { string DBPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, baza + ".sqlite"); using (var db = new SQLite.SQLiteConnection(DBPath)) { db.CreateTable<UserDefaultDataBase>(); } this.Frame.Navigate(typeof(DodajSlowko)); } } }
private List<OldMessageSettings> loadOldMessages() { var oldMessages = new List<OldMessageSettings>(); using (var db = new SQLite.SQLiteConnection(this.DBPath)) { db.CreateTable<OldMessageSettings>(); foreach (var oldMessage in db.Table<OldMessageSettings>().OrderByDescending(msg => msg.Added)) { oldMessages.Add(oldMessage); } } return oldMessages; }
private List<FavoriteMessageSettings> loadFavoriteMessage() { var favMessages = new List<FavoriteMessageSettings>(); using (var db = new SQLite.SQLiteConnection(this.DBPath)) { db.CreateTable<FavoriteMessageSettings>(); foreach (var favMessage in db.Table<FavoriteMessageSettings>().OrderByDescending(msg => msg.Added)) { favMessages.Add(favMessage); } } return favMessages; }
public EmprestimoViewModel() { using (var db = new SQLite.SQLiteConnection(DB_PATH)) { db.CreateTable<Model.Emprestimo>(); } ListaDeEmprestimos = GetAllEmprestimos(); ListaDeEmprestimosAtivos = ListaDeEmprestimos.Where(i => !i.DataDevolucao.HasValue).ToList(); SalvarEmprestimo = new ViewModel.DelegateCommand<Model.Emprestimo>(Salvar); DevolverLivro = new ViewModel.DelegateCommand<Model.Emprestimo>(Devolver); VisualizarEmprestimo = new ViewModel.DelegateCommand<Model.Emprestimo>(Visualizar); }
public static Array BindRequests() { var dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "db.sqlite"); using (var db = new SQLite.SQLiteConnection(dbPath)) { db.CreateTable<Appointment>(); var appoinmentquery = (from x in db.Table<Appointment>() where x.OwnerUserID == App.loggedInUser.Id orderby x.Date select x).ToArray(); return appoinmentquery; } }
private void btnRegister_Click(object sender, RoutedEventArgs e) { if (FieldValidationExtensions.GetIsValid(RegisterUserName) && FieldValidationExtensions.GetIsValid(RegisterPassword) && FieldValidationExtensions.GetIsValid(RegisterEmail)) { var dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "db.sqlite"); using (var db = new SQLite.SQLiteConnection(dbPath)) { db.CreateTable<User>(); db.RunInTransaction(() => { db.Insert(new User() { UserName = RegisterUserName.Text, PassWord = RegisterPassword.Password, EmailAddress = RegisterEmail.Text }); }); } this.Frame.Navigate(typeof(MainPage)); } }
public UsuarioViewModel() { using (var db = new SQLite.SQLiteConnection(DB_PATH)) { db.CreateTable<Model.Usuario>(); } ListaDeUsuarios = GetAllUsuario().Where(i => String.IsNullOrEmpty(i.Senha)).ToList(); ListaDeUsuariosComSenha = GetAllUsuario().Where(i => !String.IsNullOrEmpty(i.Senha)).ToList(); DeleteUsuario = new ViewModel.DelegateCommand<Model.Usuario>(Delete); UpdateUsuario = new ViewModel.DelegateCommand<Model.Usuario>(Update); EditUsuario = new ViewModel.DelegateCommand<Model.Usuario>(Edit); SalvarUsuarioAcesso = new ViewModel.DelegateCommand<Model.Usuario>(Salvar); LoginUsuario = new ViewModel.DelegateCommand<Model.Usuario>(Logar); SelecionarUsuarioParaEmprestimo = new ViewModel.DelegateCommand<Model.Usuario>(SelecionarParaEmprestimo); }
/// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used when the application is launched to open a specific file, to display /// search results, and so forth. /// </summary> /// <param name="args">Details about the launch request and process.</param> protected override void OnLaunched(LaunchActivatedEventArgs args) { Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); if (args.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = rootFrame; } DBPath = Path.Combine( Windows.Storage.ApplicationData.Current.LocalFolder.Path, "customers.s3db"); // Initialize the database if necessary using (var db = new SQLite.SQLiteConnection(DBPath)) { // Create the tables if they don't exist db.CreateTable<Customer>(); } LoadData(); if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter if (!rootFrame.Navigate(typeof(MainPage), args.Arguments)) { throw new Exception("Failed to create initial page"); } } // Ensure the current window is active Window.Current.Activate(); }
public void addMeterBox(string meterBoxNumber, double current) { string result = string.Empty; using (var db = new SQLite.SQLiteConnection(app.DBPath)) try { db.CreateTable<MeterBox>(); int success1 = db.Insert(new MeterBox() { ID = 0, meterBoxNumber = meterBoxNumber, currentUnits = current }); var existing = db.Query<MeterBox>("select * from MeterBox").First(); if (existing == null) { int success = db.Insert(new MeterBox() { ID = 0, meterBoxNumber = meterBoxNumber, currentUnits = current }); } else if(existing != null) { existing.meterBoxNumber = meterBoxNumber; existing.currentUnits = current; db.RunInTransaction(() => { db.Update(existing); }); } } catch (Exception e) { } //return "Success"; }
public static Array BindAddressBook() { var dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "db.sqlite"); using (var db = new SQLite.SQLiteConnection(dbPath)) { db.CreateTable<AddressBookEntree>(); var addressquery = (from x in db.Table<AddressBookEntree>() where x.OwnerUserID == App.loggedInUser.Id select x).ToArray(); var tempquery = addressquery.Select(x => x.EntreeUserID).ToArray(); var userquery = (from x in db.Table<User>() where tempquery.Contains(x.Id) select x).ToArray(); return userquery; } }
public override void ViewDidLoad () { base.ViewDidLoad (); #region observadores del teclado // Keyboard popup NSNotificationCenter.DefaultCenter.AddObserver (UIKeyboard.DidShowNotification,KeyBoardUpNotification); // Keyboard Down NSNotificationCenter.DefaultCenter.AddObserver (UIKeyboard.WillHideNotification,KeyBoardDownNotification); #endregion if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone) { this.cmpContraseñaIphone.SecureTextEntry = true; } else { this.cmpContraseña.SecureTextEntry = true; } // Figure out where the SQLite database will be. var documents = Environment.GetFolderPath(Environment.SpecialFolder.Personal); _pathToDatabase = Path.Combine(documents, "db_sqlite-net.db"); this.btnEntrar.TouchUpInside += (sender, e) => { try{ if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone) { contraseña = cmpContraseñaIphone; } else{ contraseña = cmpContraseña; } if(cmpEmail.Text == "" || contraseña.Text == ""){ UIAlertView alert = new UIAlertView () { Title = "Espera!", Message = "Debes ingresar tu email y tu contraseña primero" }; alert.AddButton ("Aceptar"); alert.Show (); } else{ //Creamos la base de datos y la tabla de persona using (var conn= new SQLite.SQLiteConnection(_pathToDatabase)) { conn.DropTable<Person>(); conn.CreateTable<Person>(); } if(UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone){ loginService.setUserData(cmpEmail.Text.Trim(), cmpContraseñaIphone.Text); }else{ loginService.setUserData(cmpEmail.Text.Trim(), cmpContraseña.Text); } LoginService userData = loginService.Find(); if(userData.Id.Equals("Invalido")){ UIAlertView alert = new UIAlertView () { Title = "Lo sentimos", Message = "Tus datos fueron invalidos, intentalo de nuevo" }; alert.AddButton ("Aceptar"); alert.Show (); }else{ var person = new Person {ID = int.Parse(userData.Id), Name = userData.nombre, LastName = userData.paterno, SecondLastName = userData.materno}; using (var db = new SQLite.SQLiteConnection(_pathToDatabase )) { db.Insert(person); } UIAlertView alert = new UIAlertView () { Title = "Bienvenido", Message = "Bienvenido a Fixbuy " + userData.nombre }; alert.AddButton ("Aceptar"); alert.Show (); Console.WriteLine("Este el es ID de usuario: " + userData.Id); this.NavigationController.PopViewController(true); } } }catch(System.Net.WebException){ UIAlertView alerta = new UIAlertView () { Title = "Ups =S", Message = "Algo salio mal, verifica tu conexión a internet e intentalo de nuevo" }; alerta.AddButton ("Aceptar"); alerta.Show (); }catch(Exception){ UIAlertView alerta = new UIAlertView () { Title = "Ups =S", Message = "Algo salio mal, por favor intentalo de nuevo" }; alerta.AddButton ("Aceptar"); alerta.Show (); } }; this.btnRegistro.TouchUpInside += (sender, e) => { RegistryView registry = new RegistryView(); this.NavigationController.PushViewController(registry, true); }; }
/// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used such as when the application is launched to open a specific file. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override void OnLaunched(LaunchActivatedEventArgs e) { #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { this.DebugSettings.EnableFrameRateCounter = true; } #endif Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); // Set the default language rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0]; rootFrame.NavigationFailed += OnNavigationFailed; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } this.DBPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "journal.sqlite"); using (var db = new SQLite.SQLiteConnection(this.DBPath)) { db.CreateTable<JournalEntry>(); } //ResetData.ResetDBData(); // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter rootFrame.Navigate(typeof(MainPage), e.Arguments); } // Ensure the current window is active Window.Current.Activate(); }
protected void initializeDatabase() { var docsFolder = System.Environment.GetFolderPath (System.Environment.SpecialFolder.MyDocuments); var pathToDatabase = System.IO.Path.Combine (docsFolder, "db_sqlnet.db"); using (var connection= new SQLite.SQLiteConnection(pathToDatabase)) { var info = connection.GetTableInfo ("GcmMessage"); if (!info.Any ()) { connection.CreateTable<GcmMessage> (); Console.WriteLine ("Creating database ...."); } else { Console.WriteLine ("Database exists"); } } }
private void LoadUserInfo() { this.siteList.Items.Clear(); ListItemTemplate addNew = new ListItemTemplate(); addNew.siteTitle.Text = "+ Add Account"; this.siteList.Items.Add(addNew); var dbPath = System.IO.Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, dbName); SiteListSolution siteList = new SiteListSolution(); if (IsInternet()) { connectTest.Visibility = Windows.UI.Xaml.Visibility.Collapsed; connectTest2.Visibility = Windows.UI.Xaml.Visibility.Visible; using (var db = new SQLite.SQLiteConnection(dbPath)) { db.CreateTable<Authorization>(); ObservableCollection<Authorization> list = new ObservableCollection<Authorization>(db.Query<Authorization>("select * from Authorization")); for (int i = 0; i < list.Count; i++) { if (list[i].Site.Equals("Facebook")) { siteList.FacebookHandle(list[i].AccessToken, this.siteList); } } } } else { connectTest2.Visibility = Windows.UI.Xaml.Visibility.Collapsed; connectTest.Visibility = Windows.UI.Xaml.Visibility.Visible; } }
/// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used when the application is launched to open a specific file, to display /// search results, and so forth. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override void OnLaunched(LaunchActivatedEventArgs e) { #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { this.DebugSettings.EnableFrameRateCounter = true; } #endif try { this.dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "Studdy.db"); using (var dbase = new SQLite.SQLiteConnection(dbPath)) { dbase.CreateTable<Accounting>(); dbase.CreateTable<Business>(); dbase.CreateTable<English>(); dbase.CreateTable<Geography>(); dbase.CreateTable<History>(); dbase.CreateTable<Life>(); dbase.CreateTable<Physics>(); dbase.CreateTable<Maths>(); } } catch { } Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); // TODO: change this value to a cache size that is appropriate for your application rootFrame.CacheSize = 1; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { // TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { #if WINDOWS_PHONE_APP // Removes the turnstile navigation for startup. if (rootFrame.ContentTransitions != null) { this.transitions = new TransitionCollection(); foreach (var c in rootFrame.ContentTransitions) { this.transitions.Add(c); } } rootFrame.ContentTransitions = null; rootFrame.Navigated += this.RootFrame_FirstNavigated; #endif // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter if (!rootFrame.Navigate(typeof(DemoPage), e.Arguments)) { throw new Exception("Failed to create initial page"); } } // Ensure the current window is active Window.Current.Activate(); }
public static void Insert() { var entities = GetEntities().ToArray(); using (Siaqodb siaqodb = new Siaqodb()) { siaqodb.Open(siaqodbPath, 100 * OneMB, 20); Console.WriteLine("InsertSiaqodb..."); var stopwatch = new Stopwatch(); stopwatch.Start(); for (int i = 0; i < ENTITY_COUNT; i++) { siaqodb.StoreObject(entities[i]); } stopwatch.Stop(); Console.WriteLine("InsertSiaqodb took:" + stopwatch.Elapsed); } using (var dbsql = new SQLite.SQLiteConnection(sqLitePath)) { dbsql.CreateTable<MyEntity>(); Console.WriteLine("InsertSQLite..."); var stopwatch = new Stopwatch(); stopwatch.Start(); for (int i = 0; i < ENTITY_COUNT; i++) { dbsql.Insert(entities[i]); } stopwatch.Stop(); Console.WriteLine("InsertSQLite took:" + stopwatch.Elapsed); } }
// void ExitApp () // { // ((GlobalvarsApp)this.Application).ISLOGON = false; // Finish (); // Android.OS.Process.KillProcess (Android.OS.Process.MyPid ()); // // } void createTable(string pathToDatabase) { using (var conn= new SQLite.SQLiteConnection(pathToDatabase)) { conn.CreateTable<Item>(); conn.CreateTable<Invoice>(); conn.CreateTable<InvoiceDtls>(); conn.CreateTable<Trader> (); conn.CreateTable<AdUser> (); conn.CreateTable<CompanyInfo> (); conn.CreateTable<AdPara> (); conn.CreateTable<AdNumDate> (); conn.CreateTable<CNNote>(); conn.CreateTable<CNNoteDtls>(); conn.CreateTable<SaleOrder>(); conn.CreateTable<SaleOrderDtls>(); conn.CreateTable<DelOrder>(); conn.CreateTable<DelOrderDtls>(); } }
private void ResetData() { using (var db = new SQLite.SQLiteConnection(this.DBPath)) { // Empty the Customer and Project tables //db.DeleteAll<Collection>(); //db.DeleteAll<Album>(); db.DropTable<Collection>(); db.DropTable<Album>(); db.CreateTable<Collection>(); db.CreateTable<Album>(); // Add seed customers and projects db.Insert(new Collection() { Id = 1, Title = "Relaxing Music", DateCreated = DateTime.Now.AddDays(-3), Image = "Assets/DarkGray.png", Void = false }); db.Insert(new Collection() { Id = 2, Title = "Hardcore Metal", DateCreated = DateTime.Now.AddDays(-2), Image = "Assets/MediumGray.png", Void = false }); db.Insert(new Collection() { Id = 3, Title = "Best 90s Music", DateCreated = DateTime.Now.AddDays(-1), Image = "Assets/LightGray.png", Void = false }); db.Insert(new Album() { Id = 1, Title = "Believe", Artist = "Cher", CollectionId = 1, LastFmId = "2026126", MusicBrainzId = "61bf0388-b8a9-48f4-81d1-7eb02706dfb0", DateAdded = DateTime.Now.AddDays(-4), Void = false }); db.Insert(new Album() { Id = 2, Title = "Believe 2", Artist = "Cher", CollectionId = 1, LastFmId = "2026126", MusicBrainzId = "61bf0388-b8a9-48f4-81d1-7eb02706dfb0", DateAdded = DateTime.Now.AddDays(-3), Void = false }); db.Insert(new Album() { Id = 3, Title = "Believe 3", Artist = "Cher", CollectionId = 2, LastFmId = "2026126", MusicBrainzId = "61bf0388-b8a9-48f4-81d1-7eb02706dfb0", DateAdded = DateTime.Now.AddDays(-2), Void = false }); db.Insert(new Album() { Id = 4, Title = "Believe 4", Artist = "Cher", CollectionId = 3, LastFmId = "2026126", MusicBrainzId = "61bf0388-b8a9-48f4-81d1-7eb02706dfb0", DateAdded = DateTime.Now.AddDays(-1), Void = false }); //2026126","mbid":"61bf0388-b8a9-48f4-81d1-7eb02706dfb0" } }
public override void ViewDidLoad () { base.ViewDidLoad (); //Declaramos el actionsheet donde se mostrara el picker //actionSheetPicker = new ActionSheetPicker(this.View, null); this.pickerStates.Hidden = true; this.btnAceptar.Hidden = true; //Declaramos el data model para el estado pickerDataModel = new PickerDataModel (); //Declaramos el data model para la localidad pickerDataModelLocality = new PickerDataModelLocality (); var documents = Environment.GetFolderPath(Environment.SpecialFolder.Personal); _pathToDatabase = Path.Combine(documents, "db_sqlite-net.db"); using (var db = new SQLite.SQLiteConnection(_pathToDatabase )) { states = new List<State> (from s in db.Table<State> () select s); } if(states.Count > 0){ State estado = states.ElementAt(0); this.btnEstado.SetTitle (estado.state, UIControlState.Normal); this.btnLocalidad.SetTitle (estado.locality, UIControlState.Normal); } this.btnEstado.TouchUpInside += (sender, e) => { try{ statesService = new StatesService(); List<StatesService> estados = statesService.All(); pickerDataModel.Items = estados; pickerStates.Model = pickerDataModel; pickerStates.Hidden = false; btnAceptar.Hidden = false; //actionSheetPicker.Picker.Source = pickerDataModel; //actionSheetPicker.Show(); }catch (System.Net.WebException){ UIAlertView alert = new UIAlertView () { Title = "Ups =S", Message = "No se puede mostrar la lista de estados, verifica tu conexión a internet e intentalo de nuevo." }; alert.AddButton ("Aceptar"); alert.Show (); }catch(Exception excep){ Console.WriteLine("ESTE ES EL ERROR: " + excep.ToString()); UIAlertView alert = new UIAlertView () { Title = "Ups =S", Message = excep.ToString() }; alert.AddButton("Aceptar"); alert.Show (); } }; btnAceptar.TouchUpInside += (sender, e) => { this.pickerStates.Hidden = true; this.btnAceptar.Hidden = true; }; pickerDataModel.ValueChanged += (sender, e) => { this.btnEstado.SetTitle(pickerDataModel.SelectedItem.ToString(), UIControlState.Normal); this.stateId = pickerDataModel.SelectedItem.id; this.state = pickerDataModel.SelectedItem.ToString(); }; this.btnLocalidad.TouchUpInside += (sender, e) => { try{ if(stateId != ""){ localityService = new LocalityService(); localityService.setState(stateId); List<LocalityService> localidades = localityService.All(); pickerDataModelLocality.Items = localidades; pickerStates.Model = pickerDataModelLocality; pickerStates.Hidden = false; btnAceptar.Hidden = false; //actionSheetPicker.Picker.Source = pickerDataModelLocality; //actionSheetPicker.Show(); } }catch(System.Net.WebException){ UIAlertView alert = new UIAlertView () { Title = "Ups =S", Message = "No se puede mostrar la lista de localidades, verifica tu conexión a internet e intentalo de nuevo." }; alert.AddButton ("Aceptar"); alert.Show (); }catch(Exception){ UIAlertView alert = new UIAlertView () { Title = "Ups =S", Message = "Algo salio mal, por favor intentalo de nuevo." }; alert.AddButton("Aceptar"); alert.Show (); } }; pickerDataModelLocality.ValueChanged += (sender, e) => { this.btnLocalidad.SetTitle(pickerDataModelLocality.SelectedItem.ToString(),UIControlState.Normal); this.localityId = pickerDataModelLocality.SelectedItem.id; this.locality = pickerDataModelLocality.SelectedItem.ToString(); }; btnGuardar.TouchUpInside += (sender, e) => { try{ if(this.stateId != "" && this.localityId != ""){ var state = new State {stateId = int.Parse( this.stateId), state = this.locality, localityId = int.Parse(this.localityId), locality = this.locality}; using (var db = new SQLite.SQLiteConnection(_pathToDatabase )) { db.DropTable<State>(); db.CreateTable<State>(); db.Insert(state); } MainView.localityId = state.localityId; UIAlertView alert = new UIAlertView () { Title = "Bien! =D", Message = "Gracias por definir tu estado y localidad ahora puedes empezar a buscar productos con FixBuy =D" }; alert.AddButton ("Aceptar"); alert.Show (); this.NavigationController.PopViewController(true); } }catch(Exception){ UIAlertView alert = new UIAlertView () { Title = "Ups =S", Message = "Algo salio mal, por favor intentalo de nuevo." }; alert.AddButton("Aceptar"); alert.Show (); } }; }
public override void ViewDidLoad () { base.ViewDidLoad (); this.Add (faceBookView); this.Add (facebookView2); iPhoneLocationManager = new CLLocationManager (); iPhoneLocationManager.DesiredAccuracy = CLLocation.AccuracyNearestTenMeters; iPhoneLocationManager.LocationsUpdated += (object sender, CLLocationsUpdatedEventArgs e) => { }; iPhoneLocationManager.RequestAlwaysAuthorization (); if (CLLocationManager.LocationServicesEnabled) { iPhoneLocationManager.StartUpdatingLocation (); } #region observadores del teclado // Keyboard popup NSNotificationCenter.DefaultCenter.AddObserver (UIKeyboard.DidShowNotification,KeyBoardUpNotification); // Keyboard Down NSNotificationCenter.DefaultCenter.AddObserver (UIKeyboard.WillHideNotification,KeyBoardDownNotification); #endregion #region declaracion de vista de Facebook // Create the Facebook LogIn View with the needed Permissions // https://developers.facebook.com/ios/login-ui-control/ loginView = new FBLoginView (ExtendedPermissions) { Frame = new CGRect (0,0,45, 45) }; // Create view that will display user's profile picture // https://developers.facebook.com/ios/profilepicture-ui-control/ pictureView = new FBProfilePictureView () { Frame = new CGRect (0, 0, 45, 45) }; pictureView.UserInteractionEnabled = true; // Hook up to FetchedUserInfo event, so you know when // you have the user information available loginView.FetchedUserInfo += (sender, e) => { user = e.User; pictureView.ProfileID = user.GetId (); MainView.isWithFacebook = true; loginView.Alpha = 0.1f; pictureView.Hidden = false; }; // Clean user Picture and label when Logged Out loginView.ShowingLoggedOutUser += (sender, e) => { pictureView.ProfileID = null; pictureView.Hidden = true; lblUserName.Text = string.Empty; loginView.Alpha = 1f; MainView.isWithFacebook = false; }; this.faceBookView.Add(pictureView); this.faceBookView.Add(loginView); #endregion var documents = Environment.GetFolderPath(Environment.SpecialFolder.Personal); _pathToDatabase = Path.Combine(documents, "db_sqlite-net.db"); //Creamos la base de datos y la tabla de persona using (var conn= new SQLite.SQLiteConnection(_pathToDatabase)) { conn.CreateTable<Person>(); conn.CreateTable<State> (); conn.CreateTable<Terms> (); conn.CreateTable<PrivacyNotice> (); } using (var db = new SQLite.SQLiteConnection(_pathToDatabase )) { people = new List<Person> (from p in db.Table<Person> () select p); states = new List<State> (from s in db.Table<State> () select s); terms = new List<Terms> (from t in db.Table<Terms> ()select t); privacyNotices = new List<PrivacyNotice> (from pr in db.Table<PrivacyNotice> () select pr); } if(people.Count > 0){ Person user = people.ElementAt(0); MainView.userId = user.ID; Console.WriteLine ("El Id de usuario es: "+ user.ID); } if(states.Count > 0){ State estado = states.ElementAt(0); MainView.localityId = estado.localityId; Console.WriteLine ("El Id de localidad es: "+ estado.stateId); } //Boton para entrar al menu de la aplicacion. this.btnEntrar.TouchUpInside += (sender, e) => { scanView = new ScanView(); this.NavigationController.PushViewController(scanView, true); }; this.btnListas.TouchUpInside += (sender, e) => { using (var db = new SQLite.SQLiteConnection(_pathToDatabase )) { people = new List<Person> (from p in db.Table<Person> () select p); } if(people.Count > 0){ MyListsView mylists = new MyListsView(); this.NavigationController.PushViewController(mylists,true); }else{ UIAlertView alert = new UIAlertView () { Title = "Espera!", Message = "Debes iniciar sesion para acceder a tus listas" }; alert.AddButton ("Aceptar"); alert.Show (); } }; //Boton para hacer busqueda por nombre de producto this.btnBuscar.TouchUpInside += (sender, e) => { if(this.cmpNombre.Text == ""){ UIAlertView alert = new UIAlertView () { Title = "Espera!", Message = "Debes ingresar el nombre del producto a buscar" }; alert.AddButton ("Aceptar"); alert.Show (); } else if (states.Count < 1){ UIAlertView alert = new UIAlertView () { Title = "Espera!", Message = "Debes seleccionar tu ubicacion antes de comenzar a usar FixBuy, por favor ingresa " + "Al menu de opciones para establecerla" }; alert.AddButton ("Aceptar"); alert.Clicked += (s, o) => { StatesView statesView = new StatesView(); this.NavigationController.PushViewController(statesView, true); }; alert.Show (); } else{ this._loadPop = new LoadingOverlay (UIScreen.MainScreen.Bounds); this.View.Add ( this._loadPop ); this.cmpNombre.ResignFirstResponder(); Task.Factory.StartNew ( () => { System.Threading.Thread.Sleep ( 1 * 1000 ); } ).ContinueWith ( t => { nsr = new NameSearchResultView(); nsr.setProductName(this.cmpNombre.Text.Trim()); this.NavigationController.PushViewController(nsr,true); this._loadPop.Hide (); }, TaskScheduler.FromCurrentSynchronizationContext() ); } }; this.cmpNombre.ShouldReturn += (textField) => { if(this.cmpNombre.Text == ""){ UIAlertView alert = new UIAlertView () { Title = "Espera!", Message = "Debes ingresar el nombre del producto a buscar" }; alert.AddButton ("Aceptar"); alert.Show (); } else if (states.Count < 1){ UIAlertView alert = new UIAlertView () { Title = "Espera!", Message = "Debes seleccionar tu ubicacion antes de comenzar a usar FixBuy, por favor ingresa " + "Al menu de opciones para establecerla" }; alert.AddButton ("Aceptar"); alert.Clicked += (s, o) => { StatesView statesView = new StatesView(); this.NavigationController.PushViewController(statesView, true); }; alert.Show (); } else{ this._loadPop = new LoadingOverlay (UIScreen.MainScreen.Bounds); this.View.Add ( this._loadPop ); this.cmpNombre.ResignFirstResponder(); Task.Factory.StartNew ( () => { System.Threading.Thread.Sleep ( 1 * 1000 ); } ).ContinueWith ( t => { nsr = new NameSearchResultView(); nsr.setProductName(this.cmpNombre.Text.Trim()); this.NavigationController.PushViewController(nsr,true); this._loadPop.Hide (); }, TaskScheduler.FromCurrentSynchronizationContext() ); } return true; }; //Boton para iniciar el escaner de codigo de barras this.btnCodigo.TouchUpInside += (sender, e) => { if(states.Count > 0){ // Configurar el escaner de codigo de barras. picker = new ScanditSDKRotatingBarcodePicker (appKey); picker.OverlayController.Delegate = new overlayControllerDelegate(picker, this); picker.OverlayController.ShowToolBar(true); picker.OverlayController.ShowSearchBar(true); picker.OverlayController.SetToolBarButtonCaption("Cancelar"); picker.OverlayController.SetSearchBarKeyboardType(UIKeyboardType.Default); picker.OverlayController.SetSearchBarPlaceholderText("Búsqueda por nombre de producto"); picker.OverlayController.SetCameraSwitchVisibility(SICameraSwitchVisibility.OnTablet); picker.OverlayController.SetTextForInitializingCamera("Iniciando la camara"); this.PresentViewController (picker, true, null); picker.StartScanning (); }else{ UIAlertView alert = new UIAlertView () { Title = "Espera!", Message = "Debes seleccionar tu ubicacion antes de comenzar a usar FixBuy, por favor ingresa " + "Al menu de opciones para establecerla" }; alert.AddButton ("Aceptar"); alert.Clicked += (s, o) => { StatesView statesView = new StatesView(); this.NavigationController.PushViewController(statesView, true); }; alert.Show (); } }; }
public void Devolver(Model.Emprestimo emprestimo) { emprestimo.DataDevolucao = DateTime.Now; using (var db = new SQLite.SQLiteConnection(DB_PATH)) { db.CreateTable<Model.Emprestimo>(); } using (var db = new SQLite.SQLiteConnection(DB_PATH)) { if (db.InsertOrReplace(emprestimo) > 0) { int index = this.ListaDeEmprestimos.IndexOf(emprestimo); if (index > -1) this.ListaDeEmprestimos[index] = emprestimo; else this.ListaDeEmprestimos.Add(emprestimo); } } Frame rootFrame = Window.Current.Content as Frame; rootFrame.Navigate(typeof(View.PivotPage)); }
public bool CreateTableLogin() { try { dbConn = new SQLite.SQLiteConnection (dbPath); var creatingTable = dbConn.CreateTable<MMenu_LoginInfo> (); Console.WriteLine("[InitialStartup] Table creating LoginInfo with status: {0}",creatingTable); Console.WriteLine("[InitialStartup] Table creating LoginInfo success"); return true; } catch(Exception e) { Console.WriteLine("[InitialStartup] Table creating LoginInfo error with status: {0}",e); return false; } }
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); } }
/// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used such as when the application is launched to open a specific file. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override void OnLaunched(LaunchActivatedEventArgs e) { Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } // Get a reference to the SQLite database DBPath = Path.Combine( Windows.Storage.ApplicationData.Current.LocalFolder.Path, "meals.db"); // Initialize the database if necessary using (var db = new SQLite.SQLiteConnection(DBPath)) { // Create the tables if they don't exist db.CreateTable<Meal>(); db.CreateTable<MealItem>(); db.CreateTable<Ingredient>(); db.CreateTable<FoodCategory>(); db.CreateTable<UnitOfMeasure>(); db.CreateTable<Contact>(); db.CreateTable<MealSuggestion>(); db.CreateTable <MealSuggestionCategory>(); } //this.ResetData(); //addFoodCategories(); // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter rootFrame.Navigate(typeof(StartPage), e.Arguments); } // Ensure the current window is active Window.Current.Activate(); }
public bool CreateTableUserSettings() { try { dbConn = new SQLite.SQLiteConnection (dbPath); var creatingTable = dbConn.CreateTable<UserSettings> (); Console.WriteLine("[InitialStartup] Table creating UserSettings with status: {0}",creatingTable); Console.WriteLine("[InitialStartup] Table creating UserSettings success"); return true; } catch(Exception e) { Console.WriteLine("[InitialStartup] Table creating UserSettings error with status: {0}",e); return false; } }