public static VehicleType GetVehicleType(String vehicleType) { if (vehicleType == null || vehicleType.Length == 0) { return(null); } string sql = "select type from vehicleType where type=@vehicleType"; VehicleType type = null; SqlCeCommand cmd = new SqlCeCommand(sql, DatabaseConnector.DatabaseConnection); cmd.Parameters.AddWithValue("@vehicleType", vehicleType); cmd.CommandType = CommandType.Text; SqlCeResultSet rs = cmd.ExecuteResultSet( ResultSetOptions.Scrollable); if (rs.HasRows) { int ordType = rs.GetOrdinal("type"); rs.ReadFirst(); type = new VehicleType(); type.Type = rs.GetString(ordType); } return(type); }
public static int GetTicketCount() { string sql = "select * from counter"; try { SqlCeCommand cmd = new SqlCeCommand(sql, DatabaseConnector.DatabaseConnection); SqlCeResultSet rs = cmd.ExecuteResultSet( ResultSetOptions.Scrollable); if (rs.HasRows) { int ordticketCounter = rs.GetOrdinal("ticketCounter"); rs.ReadFirst(); int count = rs.GetInt32(ordticketCounter); return(count); } } catch (Exception e) { Logger.Logger.Log(e); } return(-1); }
internal void getTrackingState(string SolutionName, string ProjectName, ref string LocalStoredPath, ref string RemoteStoredPath, ref bool bOverride) { try { SqlCeResultSet rsResult = null; cmd.CommandText = "select LocalStoredPath, RemoteStoredPath, ManualNotTracked from [Projects] where [SolutionName] = " + SolutionName + " and [ProjectName] = " + ProjectName; rsResult = cmd.ExecuteResultSet(ResultSetOptions.Scrollable); if (rsResult == null) { MessageBox.Show("Failed to execute command to get tracking info?"); return; } if (rsResult.RecordsAffected != 1) { MessageBox.Show("Seems we have too many rows in our tracker for this Solution.."); return; } rsResult.ReadFirst(); LocalStoredPath = (string)rsResult.GetString(0); RemoteStoredPath = (string)rsResult.GetString(1); bOverride = (bool)rsResult.GetBoolean(2); } catch (Exception ex) { } }
public static Price GetPrice(bool summerTariff, string ticketType, string vehicleType) { if (ticketType == null || ticketType.Length == 0 || vehicleType == null || vehicleType.Length == 0) { return(null); } string sql = "select charge, summerTariff, ticketType, vehicleType from price where summerTariff=@summerTariff and ticketType=@ticketType and vehicleType=@vehicleType"; Price price = null; SqlCeCommand cmd = new SqlCeCommand(sql, DatabaseConnector.DatabaseConnection); cmd.Parameters.AddWithValue("@summerTariff", summerTariff); cmd.Parameters.AddWithValue("@ticketType", ticketType); cmd.Parameters.AddWithValue("@vehicleType", vehicleType); cmd.CommandType = CommandType.Text; SqlCeResultSet rs = cmd.ExecuteResultSet( ResultSetOptions.Scrollable); if (rs.HasRows) { int ordCharge = rs.GetOrdinal("charge"); int ordSummerTariff = rs.GetOrdinal("summerTariff"); int ordTicketType = rs.GetOrdinal("ticketType"); int ordVehicleType = rs.GetOrdinal("vehicleType"); rs.ReadFirst(); price = new Price(); price.Charge = rs.GetDecimal(ordCharge); price.SummerTariff = rs.GetBoolean(ordSummerTariff); price.TicketType = rs.GetString(ordTicketType); price.VehicleType = rs.GetString(ordVehicleType); } return(price); }
public Employee GetEmployee(string barcode) { Employee emp = null; string selectCommand = @" SELECT CONVERT(INT,id_gamma) id_gamma, ename, case when barcode is not null then barcode else '' END barcode FROM Employee WHERE barcode IS NOT NULL AND barcode = CONVERT(NVARCHAR(12), @barcode) "; using (SqlCeConnection connect = new SqlCeConnection(Datasource)) { connect.Open(); using (SqlCeCommand command = new SqlCeCommand(selectCommand, connect)) { var param = command.Parameters.Add("barcode", SqlDbType.NVarChar); param.Value = barcode; using (SqlCeResultSet res = command.ExecuteResultSet(ResultSetOptions.Scrollable)) { if (res.ReadFirst()) { emp = new Employee() { GammaID = (int)res.GetInt32(res.GetOrdinal("id_gamma")), Barcode = (res.IsDBNull(res.GetOrdinal("barcode"))) ? "" : res.GetString(res.GetOrdinal("barcode")), Name = res.GetString(res.GetOrdinal("ename")) }; } } } } return(emp); }
// возвращает сканированный товар и количество public Scan GetScan(int artcode) { Scan scan = null; string selectCommand = @" SELECT artcode, id_gamma, qty FROM scan WHERE artcode = @artcode and id_gamma = @id_gamma"; using (SqlCeConnection connect = new SqlCeConnection(Datasource)) { connect.Open(); using (SqlCeCommand command = connect.CreateCommand()) { command.CommandText = selectCommand; var param = command.Parameters.Add("artcode", SqlDbType.Int); param.Value = artcode; param = command.Parameters.Add("id_gamma", SqlDbType.Int); param.Value = GlobalArea.CurrentEmployee.GammaID; using (SqlCeResultSet res = command.ExecuteResultSet(ResultSetOptions.Scrollable)) { if (!res.HasRows) { return(null); } if (!res.ReadFirst()) { return(null); } scan = new Scan((int)res.GetInt32(res.GetOrdinal("artcode")), (int)res.GetInt32(res.GetOrdinal("id_gamma")), (int)res.GetInt32(res.GetOrdinal("qty"))); } } return(scan); } }
public static List <Company> GetAllCompanies() { var list = new List <Company>(); SqlCeCommand sqlCeCommand = new SqlCeCommand("select * from company order by name", DatabaseConnector.DatabaseConnection); sqlCeCommand.CommandType = CommandType.Text; SqlCeResultSet sqlCeResultSet = sqlCeCommand.ExecuteResultSet(ResultSetOptions.Scrollable); if (sqlCeResultSet.HasRows) { int ordinal0 = sqlCeResultSet.GetOrdinal("id"); int ordinal1 = sqlCeResultSet.GetOrdinal("name"); int ordinal2 = sqlCeResultSet.GetOrdinal("address"); int ordinal3 = sqlCeResultSet.GetOrdinal("OIB"); sqlCeResultSet.ReadFirst(); list.Add(new Company() { Id = sqlCeResultSet.GetInt32(ordinal0), Name = sqlCeResultSet.GetString(ordinal1), Address = sqlCeResultSet.GetString(ordinal2), OIB = sqlCeResultSet.GetString(ordinal3) }); while (sqlCeResultSet.Read()) { list.Add(new Company() { Id = sqlCeResultSet.GetInt32(ordinal0), Name = sqlCeResultSet.GetString(ordinal1), Address = sqlCeResultSet.GetString(ordinal2), OIB = sqlCeResultSet.GetString(ordinal3) }); } } return(list); }
public static List <Subscriber> GetAllSubscribers() { List <Subscriber> subscribers = new List <Subscriber>(); string sql = "select licencePlates, validTo from subscriber"; SqlCeCommand cmd = new SqlCeCommand(sql, DatabaseConnector.DatabaseConnection); cmd.CommandType = CommandType.Text; SqlCeResultSet rs = cmd.ExecuteResultSet( ResultSetOptions.Scrollable); if (rs.HasRows) { int ordLicencePlates = rs.GetOrdinal("licencePlates"); int ordValidTo = rs.GetOrdinal("validTo"); rs.ReadFirst(); Subscriber subscriber = new Subscriber(); subscriber.LicencePlates = rs.GetString(ordLicencePlates); subscriber.ValidTo = rs.GetDateTime(ordValidTo); subscribers.Add(subscriber); while (rs.Read()) { subscriber = new Subscriber(); subscriber.LicencePlates = rs.GetString(ordLicencePlates); subscriber.ValidTo = rs.GetDateTime(ordValidTo); subscribers.Add(subscriber); } } return(subscribers); }
public static Vehicle GetVehicle(String licencePlates) { if (licencePlates == null || licencePlates.Length == 0) { return(null); } string sql = "select licencePlates, vehicleType, checkedIn, checkedInDate from vehicle where licencePlates=@licencePlates"; Vehicle vehicle = null; SqlCeCommand cmd = new SqlCeCommand(sql, DatabaseConnector.DatabaseConnection); cmd.Parameters.AddWithValue("@licencePlates", licencePlates); cmd.CommandType = CommandType.Text; SqlCeResultSet rs = cmd.ExecuteResultSet( ResultSetOptions.Scrollable); if (rs.HasRows) { int ordLicencePlates = rs.GetOrdinal("licencePlates"); int ordVehicleType = rs.GetOrdinal("vehicleType"); int ordCheckedIn = rs.GetOrdinal("checkedIn"); int ordCheckedInDate = rs.GetOrdinal("checkedInDate"); rs.ReadFirst(); vehicle = new Vehicle(); vehicle.LicencePlates = rs.GetString(ordLicencePlates); vehicle.VehicleType = rs.GetString(ordVehicleType); vehicle.CheckedIn = rs.GetBoolean(ordCheckedIn); vehicle.CheckedInDate = rs.GetDateTime(ordCheckedInDate); } return(vehicle); }
public static List <VehicleType> GetAllVehicleTypes() { List <VehicleType> vehicleTypes = new List <VehicleType>(); string sql = "select type from vehicleType"; SqlCeCommand cmd = new SqlCeCommand(sql, DatabaseConnector.DatabaseConnection); cmd.CommandType = CommandType.Text; SqlCeResultSet rs = cmd.ExecuteResultSet( ResultSetOptions.Scrollable); if (rs.HasRows) { int ordType = rs.GetOrdinal("type"); rs.ReadFirst(); VehicleType vehicleType = new VehicleType(); vehicleType.Type = rs.GetString(ordType); vehicleTypes.Add(vehicleType); while (rs.Read()) { vehicleType = new VehicleType(); vehicleType.Type = rs.GetString(ordType); vehicleTypes.Add(vehicleType); } } return(vehicleTypes); }
public static Company GetCompany(int id) { string sql = "select id, name, address, OIB from company where id=@id"; Company company = null; SqlCeCommand cmd = new SqlCeCommand(sql, DatabaseConnector.DatabaseConnection); cmd.Parameters.AddWithValue("@id", id); cmd.CommandType = CommandType.Text; SqlCeResultSet rs = cmd.ExecuteResultSet( ResultSetOptions.Scrollable); if (rs.HasRows) { int ordId = rs.GetOrdinal("id"); int ordName = rs.GetOrdinal("name"); int ordAddress = rs.GetOrdinal("address"); int ordOIB = rs.GetOrdinal("OIB"); rs.ReadFirst(); company = new Company(); company.Id = rs.GetInt32(ordId); company.Name = rs.GetString(ordName); company.Address = rs.GetString(ordAddress); company.OIB = rs.GetString(ordOIB); } return(company); }
public Usuario obtenerUsuario(string userName) { con.Open(); Usuario usuario = new Usuario(); string query = "select * from empleat where usu = @user"; SqlCeCommand command = new SqlCeCommand(query, con); command.Parameters.AddWithValue("@user", userName); SqlCeResultSet results = command.ExecuteResultSet(ResultSetOptions.Scrollable); if (results.HasRows) { results.ReadFirst(); usuario.idEmpleat = results.GetInt32(0); usuario.idEmpresa = results.GetInt32(1); usuario.usu = results.GetString(2); usuario.nom = results.GetString(4); usuario.email = results.GetString(5); return(usuario); } con.Close(); return(usuario); }
private ApplicationState() { // read the application state from db SqlCeConnection _dataConn = null; try { _dataConn = new SqlCeConnection("Data Source=FlightPlannerDB.sdf;Persist Security Info=False;"); _dataConn.Open(); SqlCeCommand selectCmd = new SqlCeCommand(); selectCmd.Connection = _dataConn; StringBuilder selectQuery = new StringBuilder(); selectQuery.Append("SELECT cruiseSpeed,cruiseFuelFlow,minFuel,speed,unit,utcOffset,locationFormat,deckHoldFuel,registeredClientName FROM ApplicationState"); selectCmd.CommandText = selectQuery.ToString(); SqlCeResultSet results = selectCmd.ExecuteResultSet(ResultSetOptions.Scrollable); if (results.HasRows) { results.ReadFirst(); cruiseSpeed = results.GetInt64(0); cruiseFuelFlow = results.GetInt64(1); minFuel = results.GetInt64(2); speed = results.GetSqlString(3).ToString(); unit = results.GetSqlString(4).ToString(); utcOffset = results.GetSqlString(5).ToString(); locationFormat = results.GetSqlString(6).ToString(); deckHoldFuel = results.IsDBNull(7) ? 0 : results.GetInt64(7); registeredClientName = results.IsDBNull(8) ? string.Empty : results.GetString(8); } } finally { _dataConn.Close(); } }
public static User GetUser(string username) { string sql = "select Username, Password, FirstName, LastName, UserType, OIB from users where Username=@username"; User user = null; SqlCeCommand cmd = new SqlCeCommand(sql, DatabaseConnector.DatabaseConnection); cmd.Parameters.AddWithValue("@username", username); cmd.CommandType = CommandType.Text; SqlCeResultSet rs = cmd.ExecuteResultSet( ResultSetOptions.Scrollable); if (rs.HasRows) { int ordUsername = rs.GetOrdinal("Username"); int ordPassword = rs.GetOrdinal("Password"); int ordUserType = rs.GetOrdinal("UserType"); int ordLastName = rs.GetOrdinal("LastName"); int ordFirstname = rs.GetOrdinal("FirstName"); int ordOIB = rs.GetOrdinal("OIB"); rs.ReadFirst(); user = new User(); user.FirstName = rs.GetString(ordFirstname); user.LastName = rs.GetString(ordLastName); user.Username = rs.GetString(ordUsername); user.Password = rs.GetString(ordPassword); user.UserType = rs.GetString(ordUserType); user.OIB = rs.GetString(ordOIB); } return(user); }
private void btnLerRegis_Click(object sender, EventArgs e) { SqlCeConnection cn = new SqlCeConnection(stringConexao()); try { if (cn.State == ConnectionState.Closed) { cn.Open(); } // Monta a consulta SQL string sql = "select sobrenome, nome from " + nomeTabela; SqlCeCommand cmd = new SqlCeCommand(sql, cn); cmd.CommandType = CommandType.Text; SqlCeResultSet rs = cmd.ExecuteResultSet(ResultSetOptions.Scrollable); // se você precisa atualizar o result set então use: // SqlCeResultSet rs = cmd.ExecuteResultSet(ResultSetOptions.Scrollable | ResultSetOptions.Updatable); if (rs.HasRows) { int ordSobrenome = rs.GetOrdinal("sobrenome"); int ordNome = rs.GetOrdinal("nome"); // trata a saida StringBuilder saida = new StringBuilder(); // le o primeiro registro e pega os dados rs.ReadFirst(); saida.AppendLine(rs.GetString(ordNome) + " " + rs.GetString(ordSobrenome)); while (rs.Read()) { saida.AppendLine(rs.GetString(ordNome) + " " + rs.GetString(ordSobrenome)); } // defina a saida lblEncontrado.Text = saida.ToString(); } else { lblEncontrado.Text = "Nenhum registro encontrado."; } } catch (SqlCeException sqlexception) { MessageBox.Show(sqlexception.Message, "Entre com um banco para acessar os registros", MessageBoxButtons.OK, MessageBoxIcon.Error); } catch (Exception ex) { MessageBox.Show(ex.Message, "Bah Tchê.", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { cn.Close(); } }
public static List <User> GetAllUsers() { List <User> users = new List <User>(); string sql = "select Username, Password, FirstName, LastName, UserType, OIB from users"; SqlCeCommand cmd = new SqlCeCommand(sql, DatabaseConnector.DatabaseConnection); cmd.CommandType = CommandType.Text; SqlCeResultSet rs = cmd.ExecuteResultSet( ResultSetOptions.Scrollable); if (rs.HasRows) { int ordUsername = rs.GetOrdinal("Username"); int ordPassword = rs.GetOrdinal("Password"); int ordUserType = rs.GetOrdinal("UserType"); int ordLastName = rs.GetOrdinal("LastName"); int ordFirstname = rs.GetOrdinal("FirstName"); int ordOIB = rs.GetOrdinal("OIB"); rs.ReadFirst(); User user = new User(); user.FirstName = rs.GetString(ordFirstname); user.LastName = rs.GetString(ordLastName); user.Username = rs.GetString(ordUsername); user.Password = rs.GetString(ordPassword); user.UserType = rs.GetString(ordUserType); user.OIB = rs.GetString(ordOIB); users.Add(user); while (rs.Read()) { user = new User(); user.FirstName = rs.GetString(ordFirstname); user.LastName = rs.GetString(ordLastName); user.Username = rs.GetString(ordUsername); user.Password = rs.GetString(ordPassword); user.UserType = rs.GetString(ordUserType); user.OIB = rs.GetString(ordOIB); users.Add(user); } } return(users); }
// возвращает одну запись справочника public Ean GetEan(string barcode) { Ean ean = null; string commandText = @" SELECT top(1) s.artcode, s.ean13, s.names, s.koef, p.qty, s.nds, s.Manufacturer FROM sprean s LEFT OUTER JOIN pereuchet p ON s.artcode = p.artcode WHERE s.ean13 = @barcode ORDER BY (CASE WHEN p.qty IS NULL THEN 0 ELSE p.qty END) DESC, s.artcode desc "; using (SqlCeConnection connect = new SqlCeConnection(Datasource)) { connect.Open(); using (SqlCeCommand command = connect.CreateCommand()) { command.CommandText = commandText; command.Parameters.Add("barcode", SqlDbType.NVarChar).Value = barcode; using (SqlCeResultSet res = command.ExecuteResultSet(ResultSetOptions.Scrollable)) { try { if (res.HasRows) { res.ReadFirst(); { ean = new Ean(); ean.ArtCode = res.GetInt32(0); ean.Ean13 = res.GetString(1); ean.Name = res.GetString(2); ean.Koef = res.GetInt32(3); ean.ControlQty = res.IsDBNull(4) ? 0 : res.GetInt32(4); ean.Nds = res.GetInt32(5); ean.Manufacturer = res.GetString(6); } } } finally { res.Close(); } } } } return(ean); }
public void InitializePilotsDataFromDatabase() { try { _dataConn = new SqlCeConnection("Data Source=FlightPlannerDB.sdf;Persist Security Info=False;"); _dataConn.Open(); SqlCeCommand selectCmd = new SqlCeCommand(); selectCmd.Connection = _dataConn; StringBuilder selectQuery = new StringBuilder(); selectQuery.Append("SELECT [First Name],[Last Name],[Weight]"); selectQuery.Append(" FROM Airports"); selectCmd.CommandText = selectQuery.ToString(); SqlCeResultSet results = selectCmd.ExecuteResultSet(ResultSetOptions.Scrollable); if (results.HasRows) { results.ReadFirst(); while (true) { Pilot currPilot = new Pilot(); currPilot.FName = results.GetSqlString(0).ToString(); currPilot.LName = results.GetSqlString(1).ToString(); currPilot.Weight = results.GetDouble(2); PersonId pid = new PersonId(currPilot.FName, currPilot.LName); if (!listofPilots.ContainsKey(pid)) { listofPilots.Add(pid, new List <Pilot>()); } listofPilots[pid].Add(currPilot); nameList.Add(pid); if (!results.Read()) { break; } } } } catch (Exception ex) { } finally { _dataConn.Close(); } }
public List <string> getIdentsFromRoute(string routeIdent) { List <string> idents = new List <string>(); try { _dataConn = new SqlCeConnection("Data Source=FlightPlannerDB.sdf;Persist Security Info=False;"); _dataConn.Open(); // first delete the existing data SqlCeCommand selectCmd = new SqlCeCommand(); selectCmd.Connection = _dataConn; StringBuilder selectQuery = new StringBuilder(); selectQuery.Append(string.Format("SELECT AirportIdent FROM RouteIdents where RouteId = '{0}' order by RouteSequenceNumber asc", routeIdent)); selectCmd.CommandText = selectQuery.ToString(); SqlCeResultSet results = selectCmd.ExecuteResultSet(ResultSetOptions.Scrollable); if (results.HasRows) { results.ReadFirst(); while (true) { idents.Add(results.GetSqlString(0).ToString()); if (!results.Read()) { break; } } } return(idents); } catch (Exception ex) { return(idents); } finally { if (_dataConn != null) { _dataConn.Close(); } } }
public static Subscriber GetSubscriber(string licencePlates) { string sql = "select licencePlates, validTo from subscriber where licencePlates=@licencePlates"; Subscriber subscriber = null; SqlCeCommand cmd = new SqlCeCommand(sql, DatabaseConnector.DatabaseConnection); cmd.Parameters.AddWithValue("@licencePlates", licencePlates); cmd.CommandType = CommandType.Text; SqlCeResultSet rs = cmd.ExecuteResultSet( ResultSetOptions.Scrollable); if (rs.HasRows) { int ordLicencePlates = rs.GetOrdinal("licencePlates"); int ordValidTo = rs.GetOrdinal("validTo"); rs.ReadFirst(); subscriber = new Subscriber(); subscriber.LicencePlates = rs.GetString(ordLicencePlates); subscriber.ValidTo = rs.GetDateTime(ordValidTo); } return(subscriber); }
protected void btnLogin_Click(object sender, EventArgs e) { con.Open(); string query = "select * from empleat where usu = @usuario and psw = @password and dataBaixa IS NOT NULL"; SqlCeCommand command = new SqlCeCommand(query, con); command.Parameters.AddWithValue("@usuario", txtbUser.Text); command.Parameters.AddWithValue("@password", txtbPass.Text); //SqlCeDataReader reader = command.ExecuteReader(); //SqlCeDataReader reader = command.ExecuteResultSet(ResultSetOptions.Scrollable); SqlCeResultSet results = command.ExecuteResultSet(ResultSetOptions.Scrollable); if (results.HasRows) //Si el usuario existe lo redireccionamos a la pagina Home { results.ReadFirst(); Session["idEmpleat"] = results.GetInt32(0); Session["idEmpresa"] = results.GetInt32(1); FormsAuthentication.RedirectFromLoginPage(txtbUser.Text, chkRecuerda.Checked); } else //Si el usuario no existe { lblMensaje.Text = "Usuario y/o contraseña incorrectos."; dvMensaje.Visible = true; txtbUser.Text = ""; txtbPass.Text = ""; txtbUser.Focus(); } con.Close(); }
public frmMain() { InitializeComponent(); if (!File.Exists(string.Format("{0}\\MyPersonalIndex\\MPI.sqlite", Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)))) { MessageBox.Show("Error updating! Please run MyPersonalIndex version 3.0 (and then close it) before using this upgrade program.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); throw new Exception(); } if (!File.Exists(string.Format("{0}\\MyPersonalIndex\\MPI.sdf", Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)))) { MessageBox.Show("Error updating! It does not appear you have MyPersonalIndex version 2.0 or later installed.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); throw new Exception(); } try { cnLite = new SQLiteConnection(string.Format("Data Source={0}\\MyPersonalIndex\\MPI.sqlite", Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData))); cnCe = new SqlCeConnection(string.Format("Data Source={0}\\MyPersonalIndex\\MPI.sdf", Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData))); if (cnCe.State == ConnectionState.Closed) { cnCe.Open(); } if (cnLite.State == ConnectionState.Closed) { cnLite.Open(); } using (SQLiteCommand c = new SQLiteCommand("BEGIN", cnLite)) c.ExecuteNonQuery(); // Portfolios if (Convert.ToDouble(ExecuteScalar("SELECT Version FROM Settings")) < 2.01) { MessageBox.Show("Error updating! Upgrade to version 2.0.1 before running this installer.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); throw new Exception(); } Dictionary <int, int> portfolioMapping = new Dictionary <int, int>(); using (SqlCeResultSet rs = ExecuteResultSet("SELECT * FROM Portfolios")) { foreach (SqlCeUpdatableRecord rec in rs) { int ID = rec.GetInt32(rec.GetOrdinal("ID")); string Name = rec.GetString(rec.GetOrdinal("Name")); bool Dividends = rec.GetBoolean(rec.GetOrdinal("Dividends")); bool HoldingsShowHidden = rec.GetBoolean(rec.GetOrdinal("HoldingsShowHidden")); int CostCalc = rec.GetInt32(rec.GetOrdinal("CostCalc")); bool NAVSort = rec.GetBoolean(rec.GetOrdinal("NAVSort")); decimal NAVStartValue = rec.GetDecimal(rec.GetOrdinal("NAVStartValue")); int AAThreshold = rec.GetInt32(rec.GetOrdinal("AAThreshold")); bool AAShowBlank = rec.GetBoolean(rec.GetOrdinal("AAShowBlank")); bool AcctShowBlank = rec.GetBoolean(rec.GetOrdinal("AcctShowBlank")); bool CorrelationShowHidden = rec.GetBoolean(rec.GetOrdinal("CorrelationShowHidden")); DateTime StartDate = rec.GetDateTime(rec.GetOrdinal("StartDate")); using (SQLiteCommand c = new SQLiteCommand("INSERT INTO Portfolios (Description, StartValue, AAThreshold, ThresholdMethod, " + " CostBasis, StartDate, Dividends, HoldingsShowHidden, AAShowBlank, CorrelationShowHidden, AcctShowBlank, " + " NAVSortDesc) VALUES (@Description, @StartValue, @AAThreshold, @ThresholdMethod, " + " @CostBasis, @StartDate, @Dividends, @HoldingsShowHidden, @AAShowBlank, @CorrelationShowHidden, @AcctShowBlank, " + " @NAVSortDesc)", cnLite)) { c.Parameters.AddWithValue("@Description", Name); c.Parameters.AddWithValue("@StartValue", NAVStartValue); c.Parameters.AddWithValue("@AAThreshold", AAThreshold); c.Parameters.AddWithValue("@ThresholdMethod", 0); c.Parameters.AddWithValue("@CostBasis", CostCalc + 1); c.Parameters.AddWithValue("@StartDate", ConvertDateToJulian(StartDate)); c.Parameters.AddWithValue("@Dividends", Dividends ? 1 : 0); c.Parameters.AddWithValue("@HoldingsShowHidden", HoldingsShowHidden ? 1 : 0); c.Parameters.AddWithValue("@AAShowBlank", AAShowBlank ? 1 : 0); c.Parameters.AddWithValue("@CorrelationShowHidden", CorrelationShowHidden ? 1 : 0); c.Parameters.AddWithValue("@AcctShowBlank", AcctShowBlank ? 1 : 0); c.Parameters.AddWithValue("@NAVSortDesc", NAVSort ? 1 : 0); c.ExecuteNonQuery(); } portfolioMapping.Add(ID, getIdentity()); } } // Asset Allocation Dictionary <int, int> aaMapping = new Dictionary <int, int>(); using (SqlCeResultSet rs = ExecuteResultSet("SELECT * FROM AA")) { foreach (SqlCeUpdatableRecord rec in rs) { int ID = rec.GetInt32(rec.GetOrdinal("ID")); int PortfolioID = rec.GetInt32(rec.GetOrdinal("Portfolio")); string Description = rec.GetString(rec.GetOrdinal("AA")); decimal?Target = null; if (rec.GetValue(rec.GetOrdinal("Target")) != System.DBNull.Value) { Target = rec.GetDecimal(rec.GetOrdinal("Target")) / 100; } using (SQLiteCommand c = new SQLiteCommand("INSERT INTO AA (PortfolioID, Description, Target) " + " VALUES (@PortfolioID, @Description, @Target)", cnLite)) { c.Parameters.AddWithValue("@PortfolioID", portfolioMapping[PortfolioID]); c.Parameters.AddWithValue("@Description", Description); c.Parameters.AddWithValue("@Target", Target.HasValue ? Target.Value : (object)System.DBNull.Value); c.ExecuteNonQuery(); } aaMapping.Add(ID, getIdentity()); } } // Accounts Dictionary <int, int> acctMapping = new Dictionary <int, int>(); using (SqlCeResultSet rs = ExecuteResultSet("SELECT * FROM Accounts")) { foreach (SqlCeUpdatableRecord rec in rs) { int ID = rec.GetInt32(rec.GetOrdinal("ID")); int PortfolioID = rec.GetInt32(rec.GetOrdinal("Portfolio")); string Description = rec.GetString(rec.GetOrdinal("Name")); bool OnlyGain = rec.GetBoolean(rec.GetOrdinal("OnlyGain")); decimal?TaxRate = null; if (rec.GetValue(rec.GetOrdinal("TaxRate")) != System.DBNull.Value) { TaxRate = rec.GetDecimal(rec.GetOrdinal("TaxRate")) / 100; } using (SQLiteCommand c = new SQLiteCommand("INSERT INTO Acct (PortfolioID, Description, TaxRate, TaxDeferred, CostBasis) " + " VALUES (@PortfolioID, @Description, @TaxRate, @TaxDeferred, @CostBasis)", cnLite)) { c.Parameters.AddWithValue("@PortfolioID", portfolioMapping[PortfolioID]); c.Parameters.AddWithValue("@Description", Description); c.Parameters.AddWithValue("@TaxDeferred", !OnlyGain); c.Parameters.AddWithValue("@CostBasis", 0); c.Parameters.AddWithValue("@TaxRate", TaxRate.HasValue ? TaxRate.Value : (object)System.DBNull.Value); c.ExecuteNonQuery(); } acctMapping.Add(ID, getIdentity()); } } // Securities Dictionary <int, int> securityMapping = new Dictionary <int, int>(); using (SqlCeResultSet rs = ExecuteResultSet("SELECT * FROM Tickers")) { foreach (SqlCeUpdatableRecord rec in rs) { int ID = rec.GetInt32(rec.GetOrdinal("ID")); int PortfolioID = rec.GetInt32(rec.GetOrdinal("Portfolio")); string Ticker = rec.GetString(rec.GetOrdinal("Ticker")); bool Active = rec.GetBoolean(rec.GetOrdinal("Active")); int AA = rec.GetInt32(rec.GetOrdinal("AA")); bool Hide = rec.GetBoolean(rec.GetOrdinal("Hide")); int Account = rec.GetInt32(rec.GetOrdinal("Acct")); using (SQLiteCommand c = new SQLiteCommand("INSERT INTO Security (PortfolioID, Symbol, Account, DivReinvest, CashAccount, IncludeInCalc, Hide) " + " VALUES (@PortfolioID, @Symbol, @Account, @DivReinvest, @CashAccount, @IncludeInCalc, @Hide)", cnLite)) { c.Parameters.AddWithValue("@PortfolioID", portfolioMapping[PortfolioID]); c.Parameters.AddWithValue("@Symbol", Ticker); c.Parameters.AddWithValue("@Account", Account == -1 ? (object)System.DBNull.Value : acctMapping[Account]); c.Parameters.AddWithValue("@DivReinvest", 0); c.Parameters.AddWithValue("@CashAccount", Ticker == "$" ? 1 : 0); c.Parameters.AddWithValue("@IncludeInCalc", Active ? 1 : 0); c.Parameters.AddWithValue("@Hide", Hide ? 1 : 0); c.ExecuteNonQuery(); } securityMapping.Add(ID, getIdentity()); if (AA == -1 || !aaMapping.ContainsKey(AA)) { continue; } using (SQLiteCommand c = new SQLiteCommand("INSERT INTO SecurityAA (SecurityID, AAID, Percent) " + " VALUES (@SecurityID, @AAID, @Percent)", cnLite)) { c.Parameters.AddWithValue("@SecurityID", securityMapping[ID]); c.Parameters.AddWithValue("@AAID", aaMapping[AA]); c.Parameters.AddWithValue("@Percent", 1); c.ExecuteNonQuery(); } } } using (SqlCeResultSet rs = ExecuteResultSet("SELECT * FROM Trades WHERE Custom IS NULL")) { foreach (SqlCeUpdatableRecord rec in rs) { DateTime TradeDate = rec.GetDateTime(rec.GetOrdinal("Date")); int TickerID = rec.GetInt32(rec.GetOrdinal("TickerID")); decimal Shares = rec.GetDecimal(rec.GetOrdinal("Shares")); decimal Price = rec.GetDecimal(rec.GetOrdinal("Price")); using (SQLiteCommand c = new SQLiteCommand("INSERT INTO SecurityTrades (SecurityID, Type, Value, Price, Frequency, Date) " + " VALUES (@SecurityID, @Type, @Value, @Price, @Frequency, @Date)", cnLite)) { c.Parameters.AddWithValue("@SecurityID", securityMapping[TickerID]); c.Parameters.AddWithValue("@Type", Shares < 0 ? 1 : 0); c.Parameters.AddWithValue("@Value", Math.Abs(Shares)); c.Parameters.AddWithValue("@Price", Price); c.Parameters.AddWithValue("@Frequency", 0); c.Parameters.AddWithValue("@Date", ConvertDateToJulian(TradeDate)); c.ExecuteNonQuery(); } } } using (SqlCeResultSet rs = ExecuteResultSet("SELECT * FROM CustomTrades")) { foreach (SqlCeUpdatableRecord rec in rs) { string Dates = rec.GetString(rec.GetOrdinal("Dates")); int TickerID = rec.GetInt32(rec.GetOrdinal("TickerID")); int TradeType = rec.GetInt32(rec.GetOrdinal("TradeType")); int Frequency = rec.GetInt32(rec.GetOrdinal("Frequency")); decimal Value = rec.GetDecimal(rec.GetOrdinal("Value")); tradeType newTradeType = tradeType.tradeType_Purchase; tradeFreq newFrequency = tradeFreq.tradeFreq_Once; List <DateTime> ConvertedDates = new List <DateTime>(); switch ((DynamicTradeFreq)Frequency) { case DynamicTradeFreq.Daily: ConvertedDates.Add(DateTime.MinValue); newFrequency = tradeFreq.tradeFreq_Daily; break; case DynamicTradeFreq.Monthly: ConvertedDates.Add(new DateTime(2009, 1, Convert.ToInt32(Dates))); newFrequency = tradeFreq.tradeFreq_Monthly; break; case DynamicTradeFreq.Weekly: ConvertedDates.Add(new DateTime(2009, 1, 4 + Convert.ToInt32(Dates))); newFrequency = tradeFreq.tradeFreq_Weekly; break; case DynamicTradeFreq.Yearly: ConvertedDates.Add(new DateTime(2009, 1, 1).AddDays(Convert.ToInt32(Dates) - 1)); newFrequency = tradeFreq.tradeFreq_Yearly; break; case DynamicTradeFreq.Once: foreach (string s in Dates.Split('|')) { ConvertedDates.Add(new DateTime(Convert.ToInt32(s.Substring(0, 4)), Convert.ToInt32(s.Substring(4, 2)), Convert.ToInt32(s.Substring(6, 2)))); } newFrequency = tradeFreq.tradeFreq_Once; break; } switch ((DynamicTradeType)TradeType) { case DynamicTradeType.AA: newTradeType = tradeType.tradeType_AA; break; case DynamicTradeType.Fixed: newTradeType = Value < 0 ? tradeType.tradeType_FixedSale : tradeType.tradeType_FixedPurchase; break; case DynamicTradeType.Shares: newTradeType = Value < 0 ? tradeType.tradeType_Sale : tradeType.tradeType_Purchase; break; case DynamicTradeType.TotalValue: newTradeType = tradeType.tradeType_TotalValue; break; } foreach (DateTime d in ConvertedDates) { using (SQLiteCommand c = new SQLiteCommand("INSERT INTO SecurityTrades (SecurityID, Type, Value, Frequency, Date) " + " VALUES (@SecurityID, @Type, @Value, @Frequency, @Date)", cnLite)) { c.Parameters.AddWithValue("@SecurityID", securityMapping[TickerID]); c.Parameters.AddWithValue("@Type", (int)newTradeType); c.Parameters.AddWithValue("@Value", Math.Abs(Value)); c.Parameters.AddWithValue("@Frequency", (int)newFrequency); c.Parameters.AddWithValue("@Date", d == DateTime.MinValue ? (object)System.DBNull.Value : ConvertDateToJulian(d)); c.ExecuteNonQuery(); } } } } // Settings using (SqlCeResultSet rs = ExecuteResultSet("SELECT * FROM Settings")) { rs.ReadFirst(); DateTime DataStartDate = rs.GetDateTime(rs.GetOrdinal("DataStartDate")); int? LastPortfolio = null; if (rs.GetValue(rs.GetOrdinal("LastPortfolio")) != System.DBNull.Value) { LastPortfolio = rs.GetInt32(rs.GetOrdinal("LastPortfolio")); } int WindowX = rs.GetInt32(rs.GetOrdinal("WindowX")); int WindowY = rs.GetInt32(rs.GetOrdinal("WindowY")); int WindowHeight = rs.GetInt32(rs.GetOrdinal("WindowHeight")); int WindowWidth = rs.GetInt32(rs.GetOrdinal("WindowWidth")); int WindowState = rs.GetInt32(rs.GetOrdinal("WindowState")); bool Splits = rs.GetBoolean(rs.GetOrdinal("Splits")); bool TickerDiv = rs.GetBoolean(rs.GetOrdinal("TickerDiv")); using (SQLiteCommand c = new SQLiteCommand("UPDATE Settings SET DataStartDate = @DataStartDate, LastPortfolio = @LastPortfolio, " + " WindowX = @WindowX, WindowY = @WindowY, WindowHeight = @WindowHeight, WindowWidth = @WindowWidth, " + " WindowState = @WindowState, Splits = @Splits, CompareIncludeDividends = @CompareIncludeDividends", cnLite)) { c.Parameters.AddWithValue("@DataStartDate", ConvertDateToJulian(DataStartDate)); c.Parameters.AddWithValue("@LastPortfolio", LastPortfolio.HasValue ? portfolioMapping[LastPortfolio.Value] : (object)System.DBNull.Value); c.Parameters.AddWithValue("@WindowX", WindowX); c.Parameters.AddWithValue("@WindowY", WindowY); c.Parameters.AddWithValue("@WindowHeight", WindowHeight); c.Parameters.AddWithValue("@WindowWidth", WindowWidth); c.Parameters.AddWithValue("@WindowState", WindowState); c.Parameters.AddWithValue("@Splits", Splits ? 1 : 0); c.Parameters.AddWithValue("@CompareIncludeDividends", TickerDiv ? 1 : 0); c.ExecuteNonQuery(); } } using (SQLiteCommand c = new SQLiteCommand("COMMIT", cnLite)) c.ExecuteNonQuery(); MessageBox.Show("Upgrade successful!", "Success"); } catch (Exception e) { if (cnLite.State == ConnectionState.Open) { using (SQLiteCommand c = new SQLiteCommand("ROLLBACK", cnLite)) c.ExecuteNonQuery(); } MessageBox.Show("Error updating! You can run this program again from the installation folder.\nError:\n" + e.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } finally { cnCe.Close(); cnLite.Close(); throw new Exception(); } }
protected override bool InternalFirst() { return(_resultSet.ReadFirst()); }
private void FlushTimings(SqlCeResultSet resultSet) { foreach (KeyValuePair <int, List <long> > timingKvp in m_timings) { if (timingKvp.Value.Count == 0) { continue; } int funcOrdinal = resultSet.GetOrdinal("FunctionId"); int minOrdinal = resultSet.GetOrdinal("RangeMin"); int maxOrdinal = resultSet.GetOrdinal("RangeMax"); int hitsOrdinal = resultSet.GetOrdinal("HitCount"); for (int t = 0; t < timingKvp.Value.Count; ++t) { bool foundBin = true; long time = timingKvp.Value[t]; if (!resultSet.Seek(DbSeekOptions.BeforeEqual, timingKvp.Key, time)) { foundBin = false; } if (foundBin) { resultSet.Read(); var id = resultSet.GetInt32(funcOrdinal); if (id != timingKvp.Key) { if (!resultSet.Read()) { foundBin = false; } } if (foundBin) { var min = resultSet.GetInt64(minOrdinal); var max = resultSet.GetInt64(maxOrdinal); if (id != timingKvp.Key || time < min || time > max) { foundBin = false; } } } if (foundBin) { //we've got a usable bin, increment and move on var hits = resultSet.GetInt32(hitsOrdinal); resultSet.SetInt32(hitsOrdinal, hits + 1); resultSet.Update(); continue; } //didn't find a bin, create a new one for this entry var row = resultSet.CreateRecord(); row[funcOrdinal] = timingKvp.Key; row[minOrdinal] = time; row[maxOrdinal] = time; row[hitsOrdinal] = 1; resultSet.Insert(row, DbInsertOptions.KeepCurrentPosition); //we need to bin-merge //start by seeking to the first record for this function if (!resultSet.Seek(DbSeekOptions.BeforeEqual, timingKvp.Key, 0.0f)) { resultSet.ReadFirst(); } else { resultSet.Read(); } var mergeId = resultSet.GetInt32(funcOrdinal); if (mergeId != timingKvp.Key) { resultSet.Read(); } mergeId = resultSet.GetInt32(funcOrdinal); //we know at least one exists, cause we just inserted one Debug.Assert(mergeId == timingKvp.Key); //Search for the merge that produces the smallest merged bucket long lastMin = resultSet.GetInt64(minOrdinal); int lastHits = resultSet.GetInt32(hitsOrdinal); bool shouldMerge = resultSet.Read(); //these store all the data about the best merge so far long smallestRange = long.MaxValue; long bestMin = 0; long bestMax = 0; int mergedHits = 0; for (int b = 0; b < kTimingBuckets && shouldMerge; ++b) { long max = resultSet.GetInt64(maxOrdinal); long range = max - lastMin; if (range < smallestRange) { smallestRange = range; bestMin = lastMin; bestMax = max; mergedHits = lastHits + resultSet.GetInt32(hitsOrdinal); } lastMin = resultSet.GetInt64(minOrdinal); lastHits = resultSet.GetInt32(hitsOrdinal); //if this read fails, we have insufficient buckets to bother merging shouldMerge = resultSet.Read(); } if (shouldMerge) { //seek to the first (lower) bin resultSet.Seek(DbSeekOptions.FirstEqual, timingKvp.Key, bestMin); resultSet.Read(); //expand this bin to include the next one resultSet.SetInt64(maxOrdinal, bestMax); resultSet.SetInt32(hitsOrdinal, mergedHits); //go to the now redundant bin resultSet.Update(); resultSet.Read(); //delete the bin resultSet.Delete(); } } #if FALSE //DEBUG ONLY HACK: display buckets if (!resultSet.Seek(DbSeekOptions.BeforeEqual, timingKvp.Key, 0.0f)) { resultSet.ReadFirst(); } else { resultSet.Read(); } var tempId = resultSet.GetInt32(funcOrdinal); if (tempId != timingKvp.Key) { resultSet.Read(); } Console.WriteLine("Buckets for function {0}:", timingKvp.Key); for (int b = 0; b < kTimingBuckets; ++b) { long min = resultSet.GetInt64(minOrdinal); long max = resultSet.GetInt64(maxOrdinal); int hits = resultSet.GetInt32(hitsOrdinal); Console.WriteLine("[{0}, {1}]: {2}", min, max, hits); resultSet.Read(); } #endif } }
public void SqlCeReadAfterUpdateTest() { SqlCeEngine LEngine = new SqlCeEngine(@"Data Source=TestDatabase.sdf"); if (!File.Exists("TestDatabase.sdf")) { LEngine.CreateDatabase(); } using (SqlCeConnection LConnection = new SqlCeConnection("Data Source=TestDatabase.sdf")) { LConnection.Open(); using (SqlCeCommand LCommand = LConnection.CreateCommand()) { LCommand.CommandText = "select count(*) from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'Test'"; if ((int)LCommand.ExecuteScalar() != 0) { LCommand.CommandText = "drop table Test"; LCommand.ExecuteNonQuery(); } LCommand.CommandText = "create table Test ( ID int not null, Name nvarchar(20), constraint PK_Test primary key ( ID ) )"; LCommand.ExecuteNonQuery(); LCommand.CommandText = "insert into Test ( ID, Name ) values ( 1, 'Joe' )"; LCommand.ExecuteNonQuery(); } using (SqlCeTransaction LTransaction = LConnection.BeginTransaction(System.Data.IsolationLevel.ReadCommitted)) { try { using (SqlCeCommand LCommand = LConnection.CreateCommand()) { LCommand.CommandType = System.Data.CommandType.TableDirect; LCommand.CommandText = "Test"; LCommand.IndexName = "PK_Test"; LCommand.SetRange(DbRangeOptions.Default, null, null); using (SqlCeResultSet LResultSet = LCommand.ExecuteResultSet(ResultSetOptions.Scrollable | ResultSetOptions.Sensitive | ResultSetOptions.Updatable)) { if (!LResultSet.Read()) { throw new Exception("Expected row"); } if ((string)LResultSet[1] != "Joe") { throw new Exception("Expected Joe row"); } LResultSet.SetValue(1, "Joes"); LResultSet.Update(); LResultSet.ReadFirst(); //if (!LResultSet.Read()) // throw new Exception("Expected row"); if ((string)LResultSet[1] != "Joes") { throw new Exception("Expected Joes row"); } LResultSet.SetValue(1, "Joe"); LResultSet.Update(); } } LTransaction.Commit(CommitMode.Immediate); } catch { LTransaction.Rollback(); throw; } } using (SqlCeTransaction LTransaction = LConnection.BeginTransaction(System.Data.IsolationLevel.ReadCommitted)) { } } }
private void FlushTimings(SqlCeResultSet resultSet) { foreach(KeyValuePair<int, List<long>> timingKvp in m_timings) { if(timingKvp.Value.Count == 0) continue; int funcOrdinal = resultSet.GetOrdinal("FunctionId"); int minOrdinal = resultSet.GetOrdinal("RangeMin"); int maxOrdinal = resultSet.GetOrdinal("RangeMax"); int hitsOrdinal = resultSet.GetOrdinal("HitCount"); for(int t = 0; t < timingKvp.Value.Count; ++t) { bool foundBin = true; long time = timingKvp.Value[t]; if(!resultSet.Seek(DbSeekOptions.BeforeEqual, timingKvp.Key, time)) { foundBin = false; } if(foundBin) { resultSet.Read(); var id = resultSet.GetInt32(funcOrdinal); if(id != timingKvp.Key) { if(!resultSet.Read()) { foundBin = false; } } if(foundBin) { var min = resultSet.GetInt64(minOrdinal); var max = resultSet.GetInt64(maxOrdinal); if(id != timingKvp.Key || time < min || time > max) foundBin = false; } } if(foundBin) { //we've got a usable bin, increment and move on var hits = resultSet.GetInt32(hitsOrdinal); resultSet.SetInt32(hitsOrdinal, hits + 1); resultSet.Update(); continue; } //didn't find a bin, create a new one for this entry var row = resultSet.CreateRecord(); row[funcOrdinal] = timingKvp.Key; row[minOrdinal] = time; row[maxOrdinal] = time; row[hitsOrdinal] = 1; resultSet.Insert(row, DbInsertOptions.KeepCurrentPosition); //we need to bin-merge //start by seeking to the first record for this function if(!resultSet.Seek(DbSeekOptions.BeforeEqual, timingKvp.Key, 0.0f)) resultSet.ReadFirst(); else resultSet.Read(); var mergeId = resultSet.GetInt32(funcOrdinal); if(mergeId != timingKvp.Key) resultSet.Read(); mergeId = resultSet.GetInt32(funcOrdinal); //we know at least one exists, cause we just inserted one Debug.Assert(mergeId == timingKvp.Key); //Search for the merge that produces the smallest merged bucket long lastMin = resultSet.GetInt64(minOrdinal); int lastHits = resultSet.GetInt32(hitsOrdinal); bool shouldMerge = resultSet.Read(); //these store all the data about the best merge so far long smallestRange = long.MaxValue; long bestMin = 0; long bestMax = 0; int mergedHits = 0; for(int b = 0; b < kTimingBuckets && shouldMerge; ++b) { long max = resultSet.GetInt64(maxOrdinal); long range = max - lastMin; if(range < smallestRange) { smallestRange = range; bestMin = lastMin; bestMax = max; mergedHits = lastHits + resultSet.GetInt32(hitsOrdinal); } lastMin = resultSet.GetInt64(minOrdinal); lastHits = resultSet.GetInt32(hitsOrdinal); //if this read fails, we have insufficient buckets to bother merging shouldMerge = resultSet.Read(); } if(shouldMerge) { //seek to the first (lower) bin resultSet.Seek(DbSeekOptions.FirstEqual, timingKvp.Key, bestMin); resultSet.Read(); //expand this bin to include the next one resultSet.SetInt64(maxOrdinal, bestMax); resultSet.SetInt32(hitsOrdinal, mergedHits); //go to the now redundant bin resultSet.Update(); resultSet.Read(); //delete the bin resultSet.Delete(); } } #if FALSE //DEBUG ONLY HACK: display buckets if(!resultSet.Seek(DbSeekOptions.BeforeEqual, timingKvp.Key, 0.0f)) resultSet.ReadFirst(); else resultSet.Read(); var tempId = resultSet.GetInt32(funcOrdinal); if(tempId != timingKvp.Key) resultSet.Read(); Console.WriteLine("Buckets for function {0}:", timingKvp.Key); for(int b = 0; b < kTimingBuckets; ++b) { long min = resultSet.GetInt64(minOrdinal); long max = resultSet.GetInt64(maxOrdinal); int hits = resultSet.GetInt32(hitsOrdinal); Console.WriteLine("[{0}, {1}]: {2}", min, max, hits); resultSet.Read(); } #endif } }
public void InitializeAirportdataFromDatabase() { try { _dataConn = new SqlCeConnection("Data Source=FlightPlannerDB.sdf;Persist Security Info=False;"); _dataConn.Open(); // first delete the existing data SqlCeCommand selectCmd = new SqlCeCommand(); selectCmd.Connection = _dataConn; StringBuilder selectQuery = new StringBuilder(); selectQuery.Append("SELECT airport_id, airport_ident, airport_type, airport_name, airport_latdeg, airport_longdeg, airport_elev_ft, airport_muncipality, airport_freqkhz, airport_gps_code,"); selectQuery.Append("airport_iata_code, airport_magnetic_deg, associated_airport FROM Airports"); selectCmd.CommandText = selectQuery.ToString(); SqlCeResultSet results = selectCmd.ExecuteResultSet(ResultSetOptions.Scrollable); if (results.HasRows) { results.ReadFirst(); while (true) { Airport currAirport = new Airport(); currAirport.ID = results.GetSqlString(0).ToString(); currAirport.ident = results.GetSqlString(1).ToString(); currAirport.type = results.GetSqlString(2).ToString(); currAirport.name = results.GetSqlString(3).ToString(); currAirport.latitude_deg = results.GetSqlString(4).ToString(); currAirport.longitude_deg = results.GetSqlString(5).ToString(); currAirport.elev_ft = results.GetSqlString(6).ToString(); currAirport.municipality = results.GetSqlString(7).ToString(); currAirport.frequency_khz = results.GetSqlString(8).ToString(); currAirport.gps_code = results.GetSqlString(9).ToString(); currAirport.iata_code = results.GetSqlString(10).ToString(); currAirport.magnetic_variation_deg = results.GetSqlString(11).ToString(); currAirport.associated_airport = results.GetSqlString(12).ToString(); if (!listofAirports.ContainsKey(currAirport.ident)) { listofAirports.Add(currAirport.ident, new List <Airport>()); } listofAirports[currAirport.ident].Add(currAirport); identList.Add(currAirport.ident); if (!results.Read()) { break; } } } } catch (Exception ex) { } finally { if (_dataConn != null) { _dataConn.Close(); } } }