예제 #1
0
        private static void KyPowerball(SQLiteConnection connection)
        {
            string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            path = Path.Combine(path, "Powerball.txt");

            using (var stream = File.OpenRead(path))
            {
                using (var reader = new StreamReader(stream))
                {
                    while (!reader.EndOfStream)
                    {
                        string line = reader.ReadLine();
                        var split = line.Split('\t');

                        var win = new Win
                        {
                            Date = DateTime.Parse(split[0]),
                        };
                        connection.Insert(win);

                        var numbers = split[1].Split('–');
                        for (int i = 0; i < numbers.Length; i++)
                        {
                            connection.Insert(new Numbers
                            {
                                Number = int.Parse(numbers[i].Trim()),
                                Win = win.ID,
                                MegaBall = i == 5,
                            });
                        }
                    }
                }
            }
        }
예제 #2
0
		/// <returns>
		/// Output of test query
		/// </returns>
		public static string DoSomeDataAccess ()
		{
			var output = "";
			output += "\nCreating database, if it doesn't already exist";
			string dbPath = Path.Combine (
				Environment.GetFolderPath (Environment.SpecialFolder.Personal), "ormdemo.db3");

			var db = new SQLiteConnection (dbPath);
			db.CreateTable<Stock> ();

			if (db.Table<Stock> ().Count() == 0) {
				// only insert the data if it doesn't already exist
				var newStock = new Stock ();
				newStock.Symbol = "AAPL";
				db.Insert (newStock); 

				newStock = new Stock ();
				newStock.Symbol = "GOOG";
				db.Insert (newStock); 

				newStock = new Stock ();
				newStock.Symbol = "MSFT";
				db.Insert (newStock);
			}

			output += "\nReading data using Orm";
			var table = db.Table<Stock> ();
			foreach (var s in table) {
				output += "\n" + s.Id + " " + s.Symbol;
			}

			return output;
		}
예제 #3
0
        public async void Initialize()
        {
            using (var db = new SQLite.SQLiteConnection(_dbPath))
            {
                db.CreateTable <Customer>();

                //Note: This is a simplistic initialization scenario
                if (db.ExecuteScalar <int>("select count(1) from Customer") == 0)
                {
                    db.RunInTransaction(() =>
                    {
                        db.Insert(new Customer()
                        {
                            FirstName = "Phil", LastName = "Japikse"
                        });
                        db.Insert(new Customer()
                        {
                            FirstName = "Jon", LastName = "Galloway"
                        });
                        db.Insert(new Customer()
                        {
                            FirstName = "Jesse", LastName = "Liberty"
                        });
                    });
                }
                else
                {
                    await Load();
                }
            }
        }
예제 #4
0
        private void fillTb_Click(object sender, RoutedEventArgs e)
        {
            using (var m_dbConnection = new SQLite.SQLiteConnection(dbPath))
            {
                try
                {
                    m_dbConnection.Insert(new highscore()
                    {
                        name  = "Me",
                        score = 9001
                    });
                    m_dbConnection.Insert(new highscore()
                    {
                        name  = "Me",
                        score = 3000
                    });
                    m_dbConnection.Insert(new highscore()
                    {
                        name  = "Myself",
                        score = 6000
                    });
                    m_dbConnection.Insert(new highscore()
                    {
                        name  = "And I",
                        score = 9001
                    });

                    Logger.Info("Filled table");
                }
                catch (System.Exception ex)
                {
                    Logger.Error(ex.Message);
                }
            }
        }
		private SQLiteConnection GetDatabaseConnection() {
			var documents = Environment.GetFolderPath (Environment.SpecialFolder.Desktop);
			string db = Path.Combine (documents, "Occupation.db3");
			OccupationModel Occupation;

			// Create the database if it doesn't already exist
			bool exists = File.Exists (db);

			// Create connection to database
			var conn = new SQLiteConnection (db);

			// Initially populate table?
			if (!exists) {
				// Yes, build table
				conn.CreateTable<OccupationModel> ();

				// Add occupations
				Occupation = new OccupationModel ("Documentation Manager", "Manages the Documentation Group");
				conn.Insert (Occupation);

				Occupation = new OccupationModel ("Technical Writer", "Writes technical documentation and sample applications");
				conn.Insert (Occupation);

				Occupation = new OccupationModel ("Web & Infrastructure", "Creates and maintains the websites that drive documentation");
				conn.Insert (Occupation);

				Occupation = new OccupationModel ("API Documentation Manager", "Manages the API Doucmentation Group");
				conn.Insert (Occupation);

				Occupation = new OccupationModel ("API Documentor", "Creates and maintains API documentation");
				conn.Insert (Occupation);
			}

			return conn;
		}
예제 #6
0
        public TradeTable(SQLiteConnection database, TradeInstance trade)
        {
            var tradeClient0 = new TradeClient(database, trade.Client0Id, trade.Client0Monster);
            database.Insert(tradeClient0);
            TradeClient0Id = tradeClient0.Id;

            var tradeClient1 = new TradeClient(database, trade.Client1Id, trade.Client1Monster);
            database.Insert(tradeClient1);
            TradeClient1Id = tradeClient1.Id;
        }
예제 #7
0
        public static void Save(IEnumerable<Country> countryList, string connectionString)
        {
            if (countryList == null)
                throw new ArgumentNullException("countryList");

            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                foreach (Country country in countryList)
                {
                    CountryDataObject countryDataObject = new CountryDataObject
                    {
                        name = country.Name,
                        is_important = country.IsHot ? 1 : 0
                    };

                    connection.Insert(countryDataObject);

                    foreach (Location location1 in country.Locations)
                    {
                        LocationDataObject location1DataObject = GetLocationDataObject(
                            location: location1,
                            parent_id: null,
                            country_id: countryDataObject.id);

                        connection.Insert(location1DataObject);

                        foreach (Location location2 in location1.Locations)
                        {
                            LocationDataObject location2DataObject = GetLocationDataObject(
                                location: location2,
                                parent_id: location1DataObject.id,
                                country_id: countryDataObject.id);

                            connection.Insert(location2DataObject);

                            foreach (Location location3 in location2.Locations)
                            {
                                LocationDataObject location3DataObject = GetLocationDataObject(
                                    location: location3,
                                    parent_id: location2DataObject.id,
                                    country_id: countryDataObject.id);

                                connection.Insert(location3DataObject);
                            }
                        }
                    }
                }
            }
        }
예제 #8
0
파일: Worker.cs 프로젝트: fireelf/Winuibuh
        public string CreateAccount(double _sum, String _name)
        {
            string res = "1;1";
            var dbPath = Path.Combine(ApplicationData.Current.LocalFolder.Path, dbname);
            using (var db = new SQLiteConnection(dbPath))
            {
                // Работа с БД
                var _acc = new AccountTable() { _Name = _name, CurrentMoneyAmount = _sum };
                db.Insert(_acc);
                var _change = new ChangesTable() { _DBString = "INSERT INTO AccountTable(_Name, CurrentMoneyAmount) VALUES('" + _name + "', '" + _sum + "');", _ChangesDatetime = DateTime.Now };
                db.Insert(_change);
            }

            return res;
        }
 public void Insert(Chinese chinese)
 {
     using (var db = new SQLiteConnection(dbPath))
     {
         db.RunInTransaction(() => db.Insert(chinese));
     }
 }
예제 #10
0
		public void insertTerms(){
			var term = new Terms {TermAcepted="Aceptado"};
			using (var db = new SQLite.SQLiteConnection(_pathToDatabase ))
			{
				db.Insert(term);
			}
		}
예제 #11
0
 public void InsertLog(Log log)
 {
     using (var connection = new SQLiteConnection(_dbPath) { Trace = true })
     {
         connection.Insert(log);
     }
 }
예제 #12
0
 public int Insert(T entity)
 {
     lock (m_lock)
     {
         return(_db.Insert(entity, typeof(T)));
     }
 }
예제 #13
0
        private void InsertItemIntoDb(string result)
        {
            string pathToDatabase = ((GlobalvarsApp)CallingActivity.Application).DATABASE_PATH;

            string[] para = result.Split(new char[] { '|' });
            if (para [0] != "OK")
            {
                Downloadhandle.Invoke(CallingActivity, 0, CallingActivity.Resources.GetString(Resource.String.msg_faillogin));
                return;
            }
            EditText passw = CallingActivity.FindViewById <EditText> (Resource.Id.login_password);

            using (var db = new SQLite.SQLiteConnection(pathToDatabase))
            {
                var list2 = db.Table <AdUser>().ToList <AdUser>();
                list2.RemoveAll(x => x.UserID == para[1]);
                AdUser user = new AdUser();
                user.BranchCode  = para [3];
                user.CompCode    = para [2];
                user.Islogon     = true;
                user.Password    = passw.Text;
                user.UserID      = para [1];
                user.LastConnect = DateTime.Now;
                db.Insert(user);
            }
            ((GlobalvarsApp)CallingActivity.Application).USERID_CODE  = para [1];
            ((GlobalvarsApp)CallingActivity.Application).COMPANY_CODE = para [2];
            ((GlobalvarsApp)CallingActivity.Application).BRANCH_CODE  = para [3];
            //DownloadCOmpleted ("Successfully Logon.");
            //Downloadhandle.Invoke(CallingActivity,0,"Successfully Logon.");
            FireEvent(EventID.LOGIN_SUCCESS);
        }
예제 #14
0
 //Insert
 public int InsertDetails(CartRecord custDB)
 {
     lock (locker)
     {
         return(conn.Insert(custDB));
     }
 }
예제 #15
0
 public void InsertOffender(Offender offender)
 {
     using (var connection = new SQLiteConnection(_dbPath) { Trace = true })
     {
         connection.Insert(offender);
     }
 }
예제 #16
0
            public Task <bool> AddAsync(IActiveLock activeLock, CancellationToken cancellationToken)
            {
                var entry        = ToEntry(activeLock);
                var affectedRows = _connection.Insert(entry);

                return(Task.FromResult(affectedRows != 0));
            }
예제 #17
0
		private static void AddStocksToDb(SQLiteConnection db, string symbol, string name, string file)
		{
			// parse the stock csv file
			const int NUMBER_OF_FIELDS = 7;    // The text file will have 7 fields, The first is the date, the last is the adjusted closing price
			TextParser parser = new TextParser(",", NUMBER_OF_FIELDS);     // instantiate our general purpose text file parser object.
			List<string[]> stringArrays;    // The parser generates a List of string arrays. Each array represents one line of the text file.
			stringArrays = parser.ParseText(File.Open(@"../../../DataAccess-Console/DAL/" + file,FileMode.Open));     // Open the file as a stream and parse all the text

			// Don't use the first array, it's a header
			stringArrays.RemoveAt(0);
			// Copy the List of strings into our Database
			int pk = 0;
			foreach (string[] stockInfo in stringArrays) {
				pk += db.Insert (new Stock () {
					Symbol = symbol,
					Name = name,
					Date = Convert.ToDateTime (stockInfo [0]),
					ClosingPrice = decimal.Parse (stockInfo [6])
				});
				// Give an update every 100 rows
				if (pk % 100 == 0)
					Console.WriteLine ("{0} {1} rows inserted", pk, symbol);
			}
			// Show the final count of rows inserted
			Console.WriteLine ("{0} {1} rows inserted", pk, symbol);			
		}
예제 #18
0
partial         void btnAdd_TouchUpInside(UIButton sender)
        {
            // Input Validation: only insert a book if the title is not empty
            if (!string.IsNullOrEmpty(txtTitle.Text))
            {
                // Insert a new book into the database
                var newBook = new Book { BookTitle = txtTitle.Text, ISBN = txtISBN.Text };

                var db = new SQLiteConnection (filePath);
                db.Insert (newBook);

                // TODO: Add code to populate the Table View with the new values

                // show an alert to confirm that the book has been added
                new UIAlertView(
                    "Success",
                    string.Format("Book ID: {0} with Title: {1} has been successfully added!", newBook.BookId, newBook.BookTitle),
                    null,
                    "OK").Show();

                PopulateTableView();

                // call this method to refresh the Table View data
                tblBooks.ReloadData ();
            }
            else
            {
                new UIAlertView("Failed", "Enter a valid Book Title",null,"OK").Show();
            }
        }
예제 #19
0
        private void SaveThisAnaliseToBaseOfAnalises()
        {
            string allActionsOfThisAnalise      = "";
            string allTimesPeriodsOfThisAnalise = "";

            using (var dbActions = new SQLite.SQLiteConnection(localSettings.Values["ActionsDBPath"] as string))
            {
                var allActions = dbActions.Query <Actions>("SELECT * FROM Actions");
                foreach (Actions iter in allActions)
                {
                    allActionsOfThisAnalise      += iter.Title + ";";
                    allTimesPeriodsOfThisAnalise += iter.SpendedTimeInSeconds.ToString() + ";";
                }
            }
            string analiseName = FormStringOfAnaliseNameFromCurrentDate();

            using (var db = new SQLite.SQLiteConnection(localSettings.Values["OldAnalisesDBPath"] as string))
            {
                var analise = new OldAnalises()
                {
                    Title = analiseName.ToString(), ActionsList = allActionsOfThisAnalise, TimesForActions = allTimesPeriodsOfThisAnalise, DateTimeOfSave = DateTime.Now
                };
                db.Insert(analise);
            }
        }
예제 #20
0
        public MainPage()
        {
            this.InitializeComponent();

            speech = new SpeechSynthesizer(CLIENT_ID, CLIENT_SECRET);
            speech.AudioFormat = SpeakStreamFormat.MP3;
            speech.AudioQuality = SpeakStreamQuality.MaxQuality;
            speech.AutoDetectLanguage = false;
            speech.AutomaticTranslation = false;

            /* Database transactions */
            var db = new SQLiteConnection(Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "mydb.sqlite"));
            db.CreateTable<Button>();

            /* Get and insert sample buttons from system colors */
            var _Colors = typeof(Colors)
                .GetRuntimeProperties()
                .Select((x, i) => new
                {
                    Color = (Color)x.GetValue(null),
                    Name = x.Name,
                    Index = i,
                    ColSpan = 1,
                    RowSpan = 1
                });

            foreach (var c in _Colors)
            {
                db.Insert(new Button { Text = c.Name, ColSpan = c.ColSpan, RowSpan = c.RowSpan, Order = c.Index, ColorHex = c.Color.ToString() });
            }
            
            /* Set data context to Button table */
            this.DataContext = db.Table<Button>().ToList();
        }
예제 #21
0
 public void Save(FootballPlayer player)
 {
     using (SQLite.SQLiteConnection database = DependencyService.Get <ISQLite> ().GetConnection())
     {
         database.Insert(player);
     }
 }
예제 #22
0
        public int AddNewUser(string username, string email, string password)
        {
            int result = 0;

            try
            {
                if (string.IsNullOrEmpty(username) && string.IsNullOrEmpty(email) && string.IsNullOrEmpty(password))
                {
                    EstadoMensaje = string.Format("Complete todos los campos.");
                }
                else
                {
                    result = con.Insert(new User()
                    {
                        Username = username,
                        Email    = email,
                        Password = password
                    });



                    EstadoMensaje = string.Format("Cantidad de filas afectadas {0}", result);
                }
            }
            catch (Exception e)
            {
                EstadoMensaje = e.Message;
            } return(result);
        }
예제 #23
0
 public void CreateWeighingEntry(Weighing myWeighing)
 {
     using (var dbConn = new SQLiteConnection(App.DB_PATH))
     {
         dbConn.Insert(myWeighing);
     }
 }
예제 #24
0
        public override void SaveSetting()
        {
            if (!AutoSave)
            {
                return;
            }
            using (var conn = new SQLite.SQLiteConnection(DBSettingPath))
            {
                conn.CreateTable <AppSettings>();
                AppSettings save = new AppSettings();
                foreach (PropertyInfo property in typeof(AppSettings).GetProperties())
                {
                    if (property.CanWrite)
                    {
                        property.SetValue(save, property.GetValue(this, null), null);
                    }
                }

                int count;
                if (conn.Table <AppSettings>().Count() == 0)
                {
                    count = conn.Insert(save);
                }
                else
                {
                    count = conn.Update(save);
                }
                Debug.WriteLine("SaveSetting: " + DBSettingPath);
                Debug.WriteLine("SaveSettingCount : " + count);
            }
        }
예제 #25
0
		public void insertPrivacyNotice(){
			var privacyNotice = new PrivacyNotice {PrivacyNoticeAcepted="Aceptado"};
			using (var db = new SQLite.SQLiteConnection(_pathToDatabase ))
			{
				db.Insert(privacyNotice);
			}
		}
예제 #26
0
        private async void Button_Clicked(object sender, EventArgs e)
        {
            Product product = new Product()
            {
                Image       = Image.Text,
                Title       = Title.Text,
                Price       = Price.Text,
                Description = Description.Text
            };

            Console.WriteLine("THIS IS PRE INSERT USER OBJECT: " + product.Title);
            using (conn)
            {
                conn.CreateTable <Product>();
                var numberOfRows = conn.Insert(product);
                if (numberOfRows > 0)
                {
                    await DisplayAlert("sucess", "Product has been added", "okay!");

                    await Navigation.PushAsync(new Products());
                }
                else
                {
                    await DisplayAlert("Failure", "Something went wrong, the product wasn't added", "Return");
                }
            }
        }
예제 #27
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate (bundle);
            SetContentView (Resource.Layout.gmail);

            // Create your application here
            EditText ed1 = FindViewById<EditText> (Resource.Id.editText1);
            EditText ed2 = FindViewById<EditText> (Resource.Id.editText2);
            Button save = FindViewById<Button> (Resource.Id.save);
            save.Click += delegate {
                string path = System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal);
                SQLiteConnection dbConn = new SQLiteConnection (System.IO.Path.Combine (path, DbName));

                dbConn.CreateTable<Mail> ();
                // only insert the data if it doesn't already exist
                Mail newRw = new Mail ();
                newRw.mailId = ed1.Text;
                newRw.password = ed2.Text;
                dbConn.Insert (newRw);
                Toast toast = Toast.MakeText(this, "Sucessful", ToastLength.Long);
                toast.Show();
                StartActivity(typeof(MainActivity));
                Finish();

            };
        }
        private void A1_button_Click(object sender, RoutedEventArgs e)
        {
            Konto newCustomer = new Konto()
            {
                Role         = "Customer",
                Nazwa_firmy  = Company_name.Text,
                Imie         = Name.Text,
                Nazwisko     = Surname.Text,
                Pesel        = PESEL.Text,
                Regon        = REGON.Text,
                Nip          = NIP.Text,
                Ulica        = Street.Text,
                Numer        = Number.Text,
                Kod_pocztowy = ZIP_code.Text,
                Miasto       = City.Text,
                Email        = E_mail.Text,
                Login        = Login.Text,
                Haslo        = Haslo.Text,
                Points       = 0
            };

            using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(App.databasePath))
            {
                conn.CreateTable <Konto>();
                conn.Insert(newCustomer);
            }

            Customers_Window custWindow = new Customers_Window(_loggedInAccount);

            custWindow.Show();

            this.Close();
        }
예제 #29
0
 public int SaveScore(Scoreboard scoreInstance)
 {
     lock (collisionLock)
     {
         if (scoreInstance.Id != 0)
         {
             database.Update(scoreInstance);
             return(scoreInstance.Id);
         }
         else
         {
             database.Insert(scoreInstance);
             return(scoreInstance.Id);
         }
     }
 }
예제 #30
0
 public void Insert(string FullNamee)
 {
     var db = new SQLiteConnection(dbPath);
          var newDepartments = new Departments();
          newDepartments.FullName = FullNamee;
          db.Insert(newDepartments);
 }
예제 #31
0
 private void BtnAddText_Click(object sender, EventArgs e)
 {
     if (Check())
     {
         if (cbSqLite.Checked == true)
         {
             var databasePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), "MyNote.csv");
             var db           = new SQLiteConnection(databasePath);
             db.CreateTable <Note>();
             var notes = new Note()
             {
                 Title = txtTitle.Text,
                 Text  = txtText.Text,
                 Date  = DateTime.Now
             };
             db.Insert(notes);
             dgvShowTexts.DataSource = db.Table <Note>().ToList();
             txtTitle.Text           = "";
             txtText.Text            = "";
         }
         else
         {
             MessageBox.Show("ابتدا باید دیتابیس مورد نظر خود را انتخاب کنید");
         }
     }
 }
예제 #32
0
파일: LineStore.cs 프로젝트: yingfangdu/BNR
        public static void addCompletedCircle(Circle circle)
        {
            completeCircles.Add(circle);

            string dbPath = GetDBPath();
            SQLiteConnection db;
            db = new SQLiteConnection(dbPath);
            db.Insert(circle);

            var result = db.Query<Line>("SELECT * FROM Lines");
            foreach (Line l in result) {
                Console.WriteLine("Line DB: bx {0}, by {1}, ex {2}, ey {3}", l.begin.X, l.begin.Y, l.end.X, l.end.Y);
            }
            var result2 = db.Query<Circle>("SELECT * FROM Circles");
            foreach (Circle c in result2) {
                Console.WriteLine("Circle DB: cx {0}, cy {1}, p2x {2}, p2yy {3}", c.center.X, c.center.Y, c.point2.X, c.point2.Y);
            }

            db.Close();
            db = null;

            foreach (Line l in completeLines) {
                Console.WriteLine("Line CL: bx {0}, by {1}, ex {2}, ey {3}", l.begin.X, l.begin.Y, l.end.X, l.end.Y);
            }
            foreach (Circle c in completeCircles) {
                Console.WriteLine("Circle CC: cx {0}, cy {1}, p2x {2}, p2yy {3}", c.center.X, c.center.Y, c.point2.X, c.point2.Y);
            }
        }
예제 #33
0
        public void ByteArrays()
        {
            //Byte Arrays for comparisson
            ByteArrayClass[] byteArrays = new ByteArrayClass[] {
                new ByteArrayClass() { bytes = new byte[] { 1, 2, 3, 4, 250, 252, 253, 254, 255 } }, //Range check
                new ByteArrayClass() { bytes = new byte[] { 0 } }, //null bytes need to be handled correctly
                new ByteArrayClass() { bytes = new byte[] { 0, 0 } },
                new ByteArrayClass() { bytes = new byte[] { 0, 1, 0 } },
                new ByteArrayClass() { bytes = new byte[] { 1, 0, 1 } },
                new ByteArrayClass() { bytes = new byte[] { } }, //Empty byte array should stay empty (and not become null)
                new ByteArrayClass() { bytes = null } //Null should be supported
            };

            SQLiteConnection database = new SQLiteConnection(TestPath.GetTempFileName());
            database.CreateTable<ByteArrayClass>();

            //Insert all of the ByteArrayClass
            foreach (ByteArrayClass b in byteArrays)
                database.Insert(b);

            //Get them back out
            ByteArrayClass[] fetchedByteArrays = database.Table<ByteArrayClass>().OrderBy(x => x.ID).ToArray();

            Assert.AreEqual(fetchedByteArrays.Length, byteArrays.Length);
            //Check they are the same
            for (int i = 0; i < byteArrays.Length; i++)
            {
                byteArrays[i].AssertEquals(fetchedByteArrays[i]);
            }
        }
예제 #34
0
        public void SaveNote()
        {
            Note note = new Note {
                CourseId = course.Id,
                Content  = noteEntry.Text
            };

            try
            {
                using (SQLite.SQLiteConnection connection = new SQLite.SQLiteConnection(App.DBPath))
                {
                    connection.CreateTable <Note>();
                    var successfulUpdate = connection.Insert(note);
                    if (successfulUpdate > 0)
                    {
                        DisplayAlert("SUCCESS", "The Note has been added successfully.", "OK");
                    }
                }
            }
            catch (Exception e)
            {
                DisplayAlert("ERROR", "The Note was not added to the database. " + e.Message, "OK");
            }
            Navigation.PopAsync();
        }
예제 #35
0
 public void Enqueue(object obj)
 {
     lock (store)
     {
         store.Insert(obj.ToQueueItem <QueueItemType>());
     }
 }
예제 #36
0
        private async void BluetoothServerOnClientConnected(BluetoothServer Server, ClientConnectedEventArgs Args)
        {
            var device = Args.Device;

            _connection = Args.Connection;

            SafeInvoke(() => {
                LogTextBlock.Text = string.Format("Connected to {0} hostname {1} service {2}", device.DisplayName, device.HostName, device.ServiceName);
            });

            var connection = Args.Connection;
            
            // The number of locations to sync
            var count = await connection.ReceiveUInt32();
            
            var app = (App)Application.Current;
            using (var db = new SQLiteConnection(app.DatabasePath))
            {
                for (int i = 0; i < count; ++i)
                {
                    var location = await connection.ReceiveObject<Models.Location>();
                    location.CountryId = _quadtree.Query(new Coordinate((float) location.Longitude, (float) location.Latitude));
                    db.Insert(location);
                }
            }

            SafeInvoke(() =>
            {
                LogTextBlock.Text += string.Format("\n\rSynced {0} locations!", count);
            });
        }
예제 #37
0
        async private void save_Click(object sender, RoutedEventArgs e)
        {
            MainPage mp = new MainPage();


            if (firstname_box.Text != "" && lastname_box.Text != "" && zipcode_box.Text != "" && place_box.Text != "")
            {
                int i    = 1;
                var conn = new SQLite.SQLiteConnection(Class1.dbPath); //creates db if does not exist
                                                                       //if db exists continues with that db
                conn.CreateTable <userdata>();                         //creates table if does not exists
                                                                       //if table exists continues with that table by adding new data with out deleting old data.
                conn.Insert(new userdata()
                {
                    id = i, firstname = firstname_box.Text, lastname = lastname_box.Text, zipcode = zipcode_box.Text, place = place_box.Text, dateandtime = DateTime.Now.ToString()
                });
                MessageDialog msg = new MessageDialog("Updated Successfully", "Success!");
                await msg.ShowAsync();

                // this.Frame.Navigate(typeof(MainPage));
            }
            else
            {
                MessageDialog msg = new MessageDialog("Missed some fields,please enter them to update profile sucessfully", "Error");
                await msg.ShowAsync();
            }
        }
예제 #38
0
파일: Database.cs 프로젝트: peterdn/Geomoir
 public static void InsertLocation(Location Location)
 {
     using (var db = new SQLiteConnection(DatabasePath))
     {
         db.Insert(Location);
     }
 }
예제 #39
0
        async Task RunCreateTest()
        {
            await Task.Factory.StartNew(() =>
            {
                using (var db = new SQLiteConnection(DatabasePath))
                {
                    db.CreateTable<Person>();
                    db.RunInTransaction(() =>
                    {
                        for (var i = 0; i < 10; i++)
                            db.Insert(new Person { FullName = "Person " + i });
                    });

                    var count = 0;
                    db.RunInTransaction(() =>
                    {
                        var table = db.Table<Person>();
                        count = table.Count();
                    });

                    var message = count == 10
                                ? "Completed!"
                                : string.Format("Only inserted {0} rows!", count);

                    dispatcher.RunIdleAsync(o => { CreateResult = message; });
                }

                
            });
        }
예제 #40
0
 private async Task AccountStore(ObservableCollection <AccountsModel> account)
 {
     try
     {
         var dbpath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "data.db3");
         using (var db = new SQLite.SQLiteConnection(dbpath))
         {
             foreach (AccountsModel accountM in Accounts)
             {
                 var accountInDB = db.Find <AccountsModel>(accountM.Accountid);
                 if (accountInDB != null)
                 {
                     db.Delete(accountM);
                 }
                 db.Insert(accountM);
             }
             db.Commit();
             db.Dispose();
             db.Close();
         }
     }
     catch (SQLiteException)
     {
     }
 }
예제 #41
0
 public void Add(Account acc)
 {
     using (var connection = new SQLiteConnection(_dbPath))
     {
         connection.Insert(acc);
     }
 }
        public string AddEmergencyContanct(EmerygencyContact emerygencycontact)
        {
            var data = _SQLiteConnection.Table <EmerygencyContact>();
            var d1   = data.Where(x => x.name.ToLower() == emerygencycontact.name.ToLower()).FirstOrDefault();

            if (d1 == null)
            {
                _SQLiteConnection.Insert(emerygencycontact);
                return("Sucessfully Added");
            }
            else
            {
                var d2 = (from values in data
                          where values.name == d1.name
                          select values).FirstOrDefault();
                if (d2 != null)
                {
                    d2.phone1   = emerygencycontact.phone1;
                    d2.name     = emerygencycontact.name;
                    d2.relation = emerygencycontact.relation;
                    return("Sucessfully Updated");
                }
                else
                {
                    return("Already exist");
                }
            }
        }
예제 #43
0
 public void Save(Person person)
 {
     using (var conn = new SQLite.SQLiteConnection (path))
     {
         conn.Insert (person);
     }
 }
예제 #44
0
 public void CreateLogEntry(LogEntry myEntrie)
 {
     using (var dbConn = new SQLiteConnection(App.DB_PATH))
     {
         dbConn.Insert(myEntrie);
     }
 }
        /// <inheritdoc />
        protected override Task <EntityTag> GetDeadETagAsync(IEntry entry, CancellationToken cancellationToken)
        {
            var key  = GetETagProperty.PropertyName;
            var prop = _connection
                       .CreateCommand("SELECT * FROM props WHERE id=?", key)
                       .ExecuteQuery <PropertyEntry>()
                       .FirstOrDefault();

            if (prop == null)
            {
                var etag = new EntityTag(false);
                prop = new PropertyEntry()
                {
                    Id       = CreateId(key, entry),
                    Language = null,
                    Path     = entry.Path.ToString(),
                    XmlName  = key.ToString(),
                    Value    = etag.ToXml().ToString(SaveOptions.OmitDuplicateNamespaces),
                };

                _connection.Insert(prop);
                return(Task.FromResult(etag));
            }

            var result = EntityTag.FromXml(XElement.Parse(prop.Value));

            return(Task.FromResult(result));
        }
예제 #46
0
 public static void AddItem <T>(T item) where T : new()
 {
     lock (_locker)
     {
         _db.Insert(item);
     }
 }
예제 #47
0
 //기본 카테고리 생성
 public void BasicSetting()
 {
     try
     {
         //DB와 연결
         SQLiteConnection conn = new SQLiteConnection(dbPath, true);
         //기본 카테고리들 생성
         string[] basicIncomeCategory = { "Salary", "Interest", "Installment Saving", "Allowance" };
         string[] basicExpenseCategory = { "Electronics", "Food", "Internet", "Transport", "Housing" };
         //돌아가면서 Income category insert
         foreach (string tempCategory in basicIncomeCategory)
         {
             IncomeCategoryForm basicCategory = new IncomeCategoryForm
             {
                 categoryName = tempCategory
             };
             conn.Insert(basicCategory);
         }
         //돌아가면서 expense category insert
         foreach (string tempCategory in basicExpenseCategory)
         {
             ExpenseCategoryForm expenseCategory = new ExpenseCategoryForm
             {
                 categoryName = tempCategory
             };
             conn.Insert(expenseCategory);
         }
     }
     catch (Exception ex)
     {
         ex.Message.ToString();
     }
 }
        public bool AddCategoryOffline(CategoryOfflineViewModel newCategoryOffline, string _synced)
        {
            bool result = false;
            try
            {
                using (var db = new SQLite.SQLiteConnection(_dbPath))
                {
                    CategoryOffline objCategoryOffline = new CategoryOffline();

                    objCategoryOffline.categoryId = Convert.ToString(newCategoryOffline.categoryId);
                    objCategoryOffline.organizationId = Convert.ToString(newCategoryOffline.organizationId);
                    objCategoryOffline.categoryCode = Convert.ToString(newCategoryOffline.categoryCode);
                    objCategoryOffline.categoryDescription = newCategoryOffline.categoryDescription;
                    objCategoryOffline.parentCategoryId = newCategoryOffline.parentCategoryId;
                    objCategoryOffline.imageName = newCategoryOffline.imageName;
                    objCategoryOffline.active = newCategoryOffline.active;

                    objCategoryOffline.synced = _synced;  // i.e. Need to synced when online and Update the synced status = "True"

                    db.RunInTransaction(() =>
                    {
                        db.Insert(objCategoryOffline);
                    });
                }

                result = true;
            }//try
            catch (Exception ex)
            {

            }//catch
            return result;
        }
		private int CreateRecord(SQLiteConnection connection, int commentId, bool commentCreated, bool full)
		{
			// nulls are not supported
			pDefaultMain.C = full ? "W" : null;
			pDefaultMain.D = full ? pRandomString : null;
			pDefaultMain.CommentId = commentCreated ? commentId : -1;
			return connection.Insert(pDefaultMain);
		}
예제 #50
0
 public bool InsertData(Employee employee)
 {
     using (var connection = new SQLite.SQLiteConnection(dbPath))
     {
         connection.Insert(employee);
         return(true);
     }
 }
예제 #51
0
        public TradeClient(SQLiteConnection database, int playerId, Monster monster)
        {
            ClientId = playerId;

            var mon = new MonsterDB(monster);
            database.Insert(mon);
            MonsterId = mon.Id;
        }
예제 #52
0
        //SAVING STUFF
        public static bool SavingShortEvents(string usedEventsDB, EventShort[] dwEvents)
        {
            bool eventSaved = false;

            for (int i = 0; i < dwEvents.Length; i++)
            {
                bool eventAlreadyInDB = false;
                eventSaved = false;
                if (IsNullOrDefault(dwEvents[i].Id) || IsNullOrDefault(dwEvents[i].Name) || IsNullOrDefault(dwEvents[i].Date) || IsNullOrDefault(dwEvents[i].OrganizerName))
                {
                }                                                                                                                                                                      // || IsNullOrDefault(dwEvents[i].PrimaryPhotoId)
                else
                {
                    //Проверка, нет ли уже такой записи
                    using (var checkingEventExist = new SQLite.SQLiteConnection(Path.Combine(WorkingInetAndSQL.destinationPath, usedEventsDB), true))
                    {
                        var idOfEvent = dwEvents[i].Id;
                        var query     = checkingEventExist.Table <EventsShort>().Where(v => v.EventServerID == idOfEvent);
                        //foreach (var checkedEvent in query) Console.WriteLine("We have information about Event with EventServerID: " + checkedEvent.EventServerID);
                        if (query.FirstOrDefault() != null)
                        {
                            eventAlreadyInDB = true; return(eventAlreadyInDB);
                        }
                    }

                    //Если данное событие отсутствует в базе данных, то:
                    if (!eventAlreadyInDB)
                    {
                        EventsShort curEvent;
                        if (dwEvents[i].PrimaryPhotoId.HasValue)
                        {
                            curEvent = new EventsShort {
                                EventServerID = dwEvents[i].Id, EventName = dwEvents[i].Name, EventDateTime = dwEvents[i].Date, OrganizerName = dwEvents[i].OrganizerName, PhotoID = dwEvents[i].PrimaryPhotoId.Value
                            };                                                                                                                                                                                                                         //
                        }
                        else
                        {
                            curEvent = new EventsShort {
                                EventServerID = dwEvents[i].Id, EventName = dwEvents[i].Name, EventDateTime = dwEvents[i].Date, OrganizerName = dwEvents[i].OrganizerName
                            };
                        }
                        //SYNCHRONOUS is Simpler
                        using (var db = new SQLite.SQLiteConnection(Path.Combine(WorkingInetAndSQL.destinationPath, usedEventsDB), true))
                        {
                            db.CreateTable <EventsShort>();
                            db.Insert(curEvent);
                            eventSaved = true;
                        }
                        //ASYNCHRONOUS is Cooler
                        //var db = new SQLite.SQLiteAsyncConnection(Path.Combine(WorkingInetAndSQL.destinationPath, usedEventsDB));
                        //db.CreateTableAsync<EventsShort>().ContinueWith (t => {db.InsertAsync(curEvent);});
                        //eventSaved = true;
                    }
                }
            }

            return(eventSaved);
        }
예제 #53
0
파일: DAL.cs 프로젝트: samfar5161/RSVP4
        // Inserts an event into the Event table
        public bool InsertEventToDB(Event ev)
        {
            if (db.GetTableInfo("Event").Count == 0)
            {
                db.CreateTable <Event>();
            }

            int numberOfRows = db.Insert(ev);

            if (numberOfRows > 0)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
예제 #54
0
        public IEnumerable <string> Get()
        {
            var s = db.Insert(new Master()
            {
                key = 1
            });

            return(new string[] { "value1", "value2" });
        }
예제 #55
0
 public async Task GetGameDataAndStoreInLocalDb(string filePath)
 {
     var user = await SimpleIoc.Default.GetInstance<IUserService>().GetCurrentUserAsync();
     var fileExists = await FileExistInStorageLocation(filePath,PuzzleDb);
     if (!fileExists)
     {
         var puzzleGroupDatasTaskResponse = GetPuzzleGroupDataFromServiceAsync();
         var puzzleGroupDatas = await puzzleGroupDatasTaskResponse;
         var puzzleGroupGameDatas = GenerateUserGameDataFromPuzzleGroupData(puzzleGroupDatas, user);
         using (var db = new SQLiteConnection(Path.Combine(filePath,PuzzleDb)))
         {
             db.CreateTable<PuzzleGroupData>();
             db.CreateTable<PuzzleGroupGameData>();
             db.Insert(puzzleGroupDatas);
             db.Insert(puzzleGroupGameDatas);
         }
     }
 }
예제 #56
0
        public void CreateWOTable()
        {
            //setup connection to database
            var db = new SQLite.SQLiteConnection(dbPath);

            //create table
            db.CreateTable <Workorder>();


            //create employee
            Workorder wo1 = new Workorder(2564, 'A', "Dishwasher Not draining", null);
            Workorder wo2 = new Workorder(8004, 'F', "AC unit not blowing cold air", "9326");


            ////store the object
            db.Insert(wo1);
            db.Insert(wo2);
        }
예제 #57
0
        public void CreateBldgTable()
        {
            //setup connection to database
            var db = new SQLite.SQLiteConnection(dbPath);

            //create table
            db.CreateTable <Building>();


            //create employee
            Building bldg1 = new Building(2564, 'A');
            Building bldg2 = new Building(8004, 'F');


            ////store the object
            db.Insert(bldg1);
            db.Insert(bldg2);
        }
예제 #58
0
        public void CreateEmpTable()
        {
            //setup connection to database
            var db = new SQLite.SQLiteConnection(dbPath);

            //create table
            db.CreateTable <Employee>();


            //create employee
            Employee emp1 = new Employee("9326", "Sam", "Samson", "P@ssword");
            Employee emp2 = new Employee("1203", "Bob", "Smith", "madness");


            ////store the object
            db.Insert(emp1);
            db.Insert(emp2);
        }
예제 #59
0
        public void AddProduct(string name, Double price, long barCode)
        {
            var newProduct = new Product
            {
                name    = name,
                barCode = barCode,
                price   = price
            };

            sqlConnection.Insert(newProduct);
        }
예제 #60
0
        private void cont_overview_Click(object sender, RoutedEventArgs e)
        {
            var con = new SQLite.SQLiteConnection(Class1.dbPath);

            con.CreateTable <testdata>(); //creates table if does not exist. If table exist continues with existing table
            con.Insert(new testdata()
            {
                id = 442 /*this values does not effect*/, testname = testname_box.Text, soiltype = soil_type_combo.SelectedItem.ToString(), landcovered = land_covered_box.Text, season = season_box_combo.SelectedItem.ToString(), temperature = temp_to_db_block.Text, humidity = humidity_to_db_block.Text, nitrogen = amount_n_to_db_block.Text, phosphorous = amount_p_to_db_block.Text, potassium = amount_k_to_db_block.Text, ph = ph_to_db_block.Text, moisture = moisture_to_db_block.Text, ec = ec_to_db_block.Text, mode = "sensor", datetime = DateTime.Now.ToString()
            });
            this.Frame.Navigate(typeof(recommendedcrops));
        }