Windows Mobile C# application with database - database

I am writing a prototype application in Windows Mobile 6.5 device.
The objective of the app is to ask user for some inputs, collect data and store into local database and on a server.
I am done with creating GUI (in C#) of the application which takes all the necessary inputs from user.
Now, I need to insert this data into local DB and upload to server DB. Both the DBs will need to synced over HTTP when user selects to do so. I have not worked on databases much, except for writing some queries to fetch data from PostgreSQL in the past in Linux environment a few years ago.
So my question is, what is the easiest way to achieve the thing I am trying to? I don't need lot of features. The data is only strings and numbers (no files, multimedia stuff etc.)
What server I should install and run? What components should I use on client side?
Thanks
Ashish

To use database on windows mobile you need Microsoft SQL Server Compact 3.5 for Windows Mobile . http://www.microsoft.com/en-in/download/details.aspx?id=8831 . You can download and install from the link given. After installation C:\Program Files\Microsoft SQL Server Compact Edition\v3.5\Devices\wce500\armv4i will have all CAB files that needs to be installed to your mobile.
Install
sqlce.ppc.wce5.armv4i.CAB
sqlce.repl.ppc.wce5.armv4i.CAB
For more information on what to install refer http://msdn.microsoft.com/en-us/library/bb986876.aspx
I have written a small helper class to do all database transactions.
public class DataBaseHelper
{
public enum typeOfQuery
{
insert,
update,
delete,
getScalar,
getDataSet,
getDataTable
};
private string connectionString = Program.Connection;
public object ExecuteDatabaseQuery(string query, Dictionary<string, object> dictionary, typeOfQuery typeOfQuery)
{
try
{
using (SqlCeConnection oCon = new SqlCeConnection(connectionString))
{
oCon.Open();
string oSql = query;
using (SqlCeCommand oCmd = new SqlCeCommand(oSql, oCon))
{
oCmd.CommandType = CommandType.Text;
if (dictionary != null)
{
if (dictionary.Count != 0)
{
foreach (KeyValuePair<string, object> pair in dictionary)
{
if (pair.Value is DateTime)
oCmd.Parameters.Add(pair.Key, SqlDbType.DateTime).Value = pair.Value ?? DBNull.Value;
else if (pair.Value is bool || pair.Value is Boolean)
oCmd.Parameters.Add(pair.Key, SqlDbType.Bit).Value = pair.Value ?? DBNull.Value;
else
oCmd.Parameters.Add(pair.Key, SqlDbType.NVarChar).Value = pair.Value ?? DBNull.Value;
}
}
}
// check what type of query using the enums in the constants.cs file
if ((typeOfQuery == (typeOfQuery.insert)) || (typeOfQuery == typeOfQuery.update) ||
(typeOfQuery == typeOfQuery.delete))
{
return oCmd.ExecuteNonQuery();
}
else if (typeOfQuery == typeOfQuery.getDataSet)
{
SqlCeDataAdapter adapter = new SqlCeDataAdapter(oCmd);
DataSet dataSet = new DataSet();
adapter.Fill(dataSet);
return dataSet;
}
else if (typeOfQuery == typeOfQuery.getDataTable)
{
SqlCeDataAdapter adapter = new SqlCeDataAdapter(oCmd);
DataSet dataSet = new DataSet();
adapter.Fill(dataSet);
return dataSet.Tables[0];
}
else if (typeOfQuery == typeOfQuery.getScalar)
{
object returnValue = oCmd.ExecuteScalar();
if (returnValue == null)
{
return string.Empty;
}
else
return returnValue;
}
}
}
}
catch (SqlCeException ex)
{
throw;
}
catch (Exception ex)
{
throw;
}
finally
{
}
return false;
}
}
You can call this class as follows
string query = #"SELECT * FROM TABLE
WHERE COL1 = #COL1";
Dictionary<string, object> dictionaryToInsert = new Dictionary<string, object>();
dictionaryToInsert.Add("#COL1", Col1Value);
return (DataTable)new DataBaseHelper().ExecuteDatabaseQuery(query,
dictionaryToInsert, DataBaseHelper.typeOfQuery.getDataTable);
Similarly you can query database for other purposes also. use the enum and change the query and you will get the result.

Related

Create Database in PervasiveSQL from Command Line

How do I create a database in PervasiveSQL using the command line.
I know how to do it via Control Center, but I would rather create it via the command line. I am working to automate the standup of a PervasiveSQL box for a project I am working on. I have the server install happening silently and I am adjusting the Server Configuration using a RegKey import.
Now i just need to script the creation of the database. The new database will use existing database files which are already copied to the server.
In the documentation I am using found here: there is a utility called dbMaint (page 264) which seems like it would do the job, but I do not seem to have that tool on my server.
Thank you in advance for your help.
dbMaint is only provided for PSQL on Linux. There is a way to write a utility using the Distributed Tuning Interface (DTI) or Distributed Tuning Object (DTO) to create the database. I can't link to the PSQL documentation but there is a PSQL_DTI_GUIDE.pdf and PSQL_DTO_Guide.pdf in the PSQL v11 documentation download that describes how to use those APIs.
Found a C# sample I put together a while back. The Pervasive DTO library will need to be added as a reference. It's a COM object. The simple sample is:
using System;
using DTOLib;
namespace dtoTest
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
string compName = null;
string userName = null;
string password = null;
string dbname = null;
string ddflocation = null;
string datalocation = null;
dtoDbFlags dbflags = DTOLib.dtoDbFlags.dtoDbFlagDefault;
DTOLib.dtoResult result;
if (args.LongLength < 1)
{
Console.WriteLine("Invalid options.\n");
Console.WriteLine("Usage: dtoDBN.EXE <computername> <username> <password> <dbname> <ddf location> <data location> <DBFlage>");
Console.WriteLine("NOTE: locations must be relative to the computer where the PSQL engine is running.");
Console.WriteLine("DB Flags must be passed as integer in this example with these values: ");
Console.WriteLine(" P_DBFLAG_BOUND = 1; (* bound database - must have P_DBFLAG_CREATE_DDF too *)");
Console.WriteLine(" P_DBFLAG_RI = 2; (*relational integrity *)");
Console.WriteLine(" P_DBFLAG_CREATE_DDF = 4; (*create ddf flag *)");
Console.WriteLine(" P_DBFLAG_NA = 2147483648; (*not applicable *)");
Console.WriteLine(" P_DBFLAG_DEFAULT = (P_DBFLAG_BOUND or P_DBFLAG_RI); ");
return;
}
if (args.LongLength == 7)
{
compName = args[0].ToString();
userName = args[1].ToString();
password = args[2].ToString();
dbname = args[3].ToString();
ddflocation = args[4].ToString();
datalocation = args[5].ToString();
dbflags = (dtoDbFlags)Convert.ToInt32(args[6]);
}
Console.WriteLine("Create Pervasive Database using DTO and C#");
DtoSession mDtoSession = new DTOLib.DtoSession();
try
{
result = mDtoSession.Connect(compName, userName, password);
if (result != 0)
{
Console.WriteLine("Error connecting to server. Error code:");
}
else
{
//Create a Database name here.
DtoDatabase db = new DtoDatabase();
db.Name = dbname;
db.DdfPath = ddflocation;
db.DataPath = datalocation;
db.Flags = dbflags;
result = mDtoSession.Databases.Add(db);
if (result !=0)
{
Console.WriteLine(string.Format("Error creating the datbase ({0}). Error code: {1}", dbname, result.ToString()));
}
else
{
Console.WriteLine(string.Format("Database ({0}) created. ", dbname));
}
result = mDtoSession.Disconnect();
Console.ReadLine();
}
}
catch (Exception e1)
{
Console.WriteLine(e1.Message.ToString());
}
}
}
}

How to get data from sql DB in selenium webdriver?

How to get data from sql DB in selenium webdriver?
I would like to connect the selenium webdriver and sql DB, and need to get value from DB and to use in the selenium testNg framework.
Can any one provide me the right solution.
First you need to make connection with database by using following commands,
DriverManager.getConnection(URL of database, "username", "password" )
To get value, use following commands
ResultSet result = stmt.executeQuery(select * from tablename;);
You need to implement DB connector helper for connect, execute query and close data base connection. After than you can use result of query in your test.
Data Base connector depends on DB type(you need use specify DB driver).
Folowing java methodis illustrated connection with SQL Server Driver:
public java.sql.Connection getConnection() {
try {
Class.forName(SQLServerDriver.class.getName());
con = java.sql.DriverManager.getConnection(getConnectionUrl(), userName, password);
if (con != null) System.out.println("Connection Successful!");
} catch (Exception e) {}
return con;
}
and execute query:
public void executeQuery(String query) {
con = this.getConnection();
if (con != null) {
Statement st = null;
try {
st = con.createStatement();
st.executeQuery(query);
} catch (SQLException e) {}
}
this.closeConnection();
}
than close connection:
public void closeConnection() {
try {
if (con != null)
con.close();
con = null;
} catch (Exception e) {}
}

SQL Server DAC FX SchemaComparison SchemaCompareDatabaseEndpoint fails with no IntegratedSecuirty

I am trying to find newly created tables in the target database on publishing. Using DAC Fx I am able to find the differences and delete the tables after moving the newly created table to another db.
I developed and tested the code with IntegratedSecurity. Started failing on machines with SQLServer logins.
The moment I toggle the IntegratedSecurity to true it works. Is it a bug?
private void Analyse()
{
try
{
var sourceDacpac = new SchemaCompareDacpacEndpoint(DacPacSrc);
var csb = new SqlConnectionStringBuilder(ConnectionString);
csb.IntegratedSecurity = false;
var targetDatabase =new SchemaCompareDatabaseEndpoint(csb.ToString());
var comparison = new SchemaComparison(sourceDacpac, targetDatabase);
comparison.Options.DropObjectsNotInSource = true;
var result = comparison.Compare();
if (result.GetErrors().Any())
{
throw new Exception("Compare failed " + result.GetErrors().FirstOrDefault().Message);
}
var delta = new List<string>();
if (result.Differences != null && result.Differences.Any())
{
var deltaTables = result.Differences.Where(x => x.Name == "Table" && x.UpdateAction == SchemaUpdateAction.Delete);
delta = deltaTables.Select(x => x.TargetObject.Name.ToString()).ToList();
}
FindingDeltaCompleted?.Invoke(this, new DeltaEventArgs(delta));
}
catch (Exception ex)
{
Logging.HandleException(ex);
}
}
Try setting Persist Security Info=True in the SQL Authentication connection string.
SSDT/DAC Fx saves connection strings in registry under HKEY_CURRENT_USER\SOFTWARE\Microsoft\SSDT\ConnectionStrings. When Persist Security Info=True is not set, it won't restore the password when loading the connection strings from registry.

cannot bind on a new display member combobox c#

When I run my program on my machine it works totally fine but when I run the code from other machine, I get an Error that says "Cannot bind on a new display member"? I just don't understand why? Here is my code.
private DataTable effectivity, filesTable, cgmFiles;
private void FillEffectivity()
{
cbEffectivity.ComboBox.DataSource = null;
effectivity = FillDataTable("SELECT * FROM Projects ORDER BY Project ASC");
cbEffectivity.ComboBox.DataSource = effectivity;
cbEffectivity.ComboBox.DisplayMember = "project";
cbEffectivity.ComboBox.ValueMember = "RecNo";
}
private DataTable FillTable(string sql)
{
DataTable table = new DataTable();
try
{
using (OleDbDataAdapter da = new OleDbDataAdapter(sql, cn))
{
da.Fill(table);
}
}
catch (Exception ex)
{
if (ex.Message == "Not a valid password.")
{
SetPassword();
return FillTable(sql);
}
return new DataTable();
}
finally
{
cn.Close();
}
return table;
}
It seems like problem in your query instead of effectivity = FillDataTable("SELECT * FROM Projects ORDER BY Project ASC"); try FillDataTable("SELECT * FROM Projects ORDER BY project ASC");
also it is recommended that dont use * while selecting it will affect on performance.
try this
FillDataTable("SELECT project FROM Projects ORDER BY project ASC");

Would singleton database connection affect performance in a weblogic clustered environment?

I have a Java EE struts web application using a singleton database connection. In the past, there is only one weblogic server, but now, there are two weblogic servers in a cluster.
Session replication have been tested to be working in this cluster. The web application consist of a few links that will open up different forms for the user to fill in. Each form has a dynamic dropdownlist that will populate some values depending on which form is clicked. These dropdownlist values are retrieved from the oracle database.
One unique issue is that the first form that is clicked, might took around 2-5 seconds, and the second form clicked could take forever to load or more than 5 mins. I have checked the codes and happened to know that the issue lies when an attempt to call the one instance of the db connection. Could this be a deadlock?
public static synchronized DataSingleton getDataSingleton()
throws ApplicationException {
if (myDataSingleton == null) {
myDataSingleton = new DataSingleton();
}
return myDataSingleton;
}
Any help in explaining such a scenario would be appreciated.
Thank you
A sample read operation calling Singleton
String sql = "...";
DataSingleton myDataSingleton = DataSingleton.getDataSingleton();
conn = myDataSingleton.getConnection();
try {
PreparedStatement pstmt = conn.prepareStatement(sql);
try {
pstmt.setString(1, userId);
ResultSet rs = pstmt.executeQuery();
try {
while (rs.next()) {
String group = rs.getString("mygroup");
}
} catch (SQLException rsEx) {
throw rsEx;
} finally {
rs.close();
}
} catch (SQLException psEx) {
throw psEx;
} finally {
pstmt.close();
}
} catch (SQLException connEx) {
throw connEx;
} finally {
conn.close();
}
The Singleton class
/**
* Private Constructor looking up for Server's Datasource through JNDI
*/
private DataSingleton() throws ApplicationException {
try {
Context ctx = new InitialContext();
SystemConstant mySystemConstant = SystemConstant
.getSystemConstant();
String fullJndiPath = mySystemConstant.getFullJndiPath();
ds = (DataSource) ctx.lookup(fullJndiPath);
} catch (NamingException ne) {
throw new ApplicationException(ne);
}
}
/**
* Singleton: To obtain only 1 instance throughout the system
*
* #return DataSingleton
*/
public static synchronized DataSingleton getDataSingleton()
throws ApplicationException {
if (myDataSingleton == null) {
myDataSingleton = new DataSingleton();
}
return myDataSingleton;
}
/**
* Fetching SQL Connection through Datasource
*
*/
public Connection getConnection() throws ApplicationException {
Connection conn = null;
try {
if (ds == null) {
}
conn = ds.getConnection();
} catch (SQLException sqlE) {
throw new ApplicationException(sqlE);
}
return conn;
}
It sounds like you may not be committing the transaction at the end of your use of the connection.
What's in DataSingleton - is it a database connection? Allowing multiple threads to access the same database connection is not going to work, for example once you have more than one user. Why don't you use a database connection pool, for example a DataSource?

Resources