I'm developing windows phone 8 application.
I'm having some difficulty with my sqlite prepare statement. I get an error saying my table does not exist, although I've checked in multiple places for it, and it does exist.
It did work until I added some new tables to the SQLite database and now it just doesn't recognise any of the tables - so I'm confused!
I have also tried hardcoding the full path.. e.g. C:\App\datbase.db etc
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.IO.IsolatedStorage;
using SQLitePCL;
namespace WP7.VideoScanZXing.SampleApp
{
public partial class Page1 : PhoneApplicationPage
{
string connLOCDAT = "Data Source =\\Resources\\DB\\MCRS_Data.sdf;Persist Security Info=False";
string connLOCLUDAT = "Data Source =\\Resources\\DB\\MCRSLU_MYCUBE.sdf;Persist Security Info=False";
public Page1()
{
InitializeComponent();
//check the isolated storage to see if the user has saved a username and password.
CheckIsoStore();
}
public void CheckIsoStore() {
if (IsolatedStorageSettings.ApplicationSettings.Contains("UsrEmail"))
{
//The user has saved details
//populate the email and password box automatically
//Dont forget to check the save details box too
tbEmail.Text = IsolatedStorageSettings.ApplicationSettings["UsrEmail"].ToString();
pbPassword.Password = IsolatedStorageSettings.ApplicationSettings["UsrPassword"].ToString();
cbSaveDetails.IsChecked = true;
}
}
public void failedLogin()
{
MessageBox.Show("Error: Email or Password are incorrect. Please try again.");
tbEmail.Focus();
}
private void btnLogin_Click(object sender, RoutedEventArgs e)
{
//validate user
string strEmail = tbEmail.Text;
string strPassword = pbPassword.Password.ToString();
//bool bolValidUser = false;
//validate username and password here!
if (bolValidUser(strEmail, strPassword) == true)
{
//user has been validated and can continue.
if (cbSaveDetails.IsChecked == true)
{
//save the users details here
IsolatedStorageSettings.ApplicationSettings["UsrEmail"] = strEmail;
IsolatedStorageSettings.ApplicationSettings["UsrPassword"] = strPassword;
IsolatedStorageSettings.ApplicationSettings.Save();
}
else {
IsolatedStorageSettings.ApplicationSettings.Remove("UsrEmail");
IsolatedStorageSettings.ApplicationSettings.Remove("UsrPassword");
IsolatedStorageSettings.ApplicationSettings.Save();
}
NavigationService.Navigate(new Uri("/MenuPage.xaml", UriKind.Relative));
}
else {
//redirect the user back to the home screen with a message
//NavigationService.Navigate(new Uri("/LoginPage.xaml?message=Login error ", UriKind.Relative));
failedLogin();
}
}
public static SQLiteConnection dbConn;
public bool bolValidUser(string Uname, string PWord)
{
dbConn = new SQLitePCL.SQLiteConnection(Windows.ApplicationModel.Package.Current.InstalledLocation.Path + #"\bizData.db", SQLiteOpen.READWRITE);
{
//StorageFile databaseFile = await .GetFileAsync("bizData.db");
//await databaseFile.CopyAsync(ApplicationData.Current.LocalFolder);
}
//using (var statement = dbConn.Prepare(#"SELECT * FROM [MCRS_LU_Login] WHERE [Email] = " + Uname + " AND [Password] = " + PWord))
using (var statement = dbConn.Prepare(#"SELECT * FROM [BARCODES]"))
{
if (statement.Step() == SQLiteResult.ROW)
{
//new MessageDialog(Convert.ToString(statement.DataCount)).ShowAsync();
//if ()
string strLinkedUser;
strLinkedUser = statement[3].ToString();
IsolatedStorageSettings.ApplicationSettings["UsrADName"] = statement[0].ToString();
return true;
}
else
{
return false;
//await msgDialog.ShowAsync();
}
}
}
private void tbEmail_GotFocus(object sender, RoutedEventArgs e)
{
imgMail.Visibility = Visibility.Collapsed;
}
private void tbEmail_LostFocus(object sender, RoutedEventArgs e)
{
if(tbEmail.Text =="") {
imgMail.Visibility = Visibility.Visible;
}
}
private void pbPassword_LostFocus(object sender, RoutedEventArgs e)
{
if (pbPassword.Password == "")
{
imgPassword.Visibility = Visibility.Visible;
}
}
private void pbPassword_GotFocus(object sender, RoutedEventArgs e)
{
imgPassword.Visibility = Visibility.Collapsed;
}
}
}
Related
I created a WCF service using Visual Studio 2017 Community version (employing TAP). I used the AsyncAutoResetEvent from the Microsoft.VisualStudio.Threading reference but it seems that this waithandle is not getting signalled after calling the Set function. The service is hosted in a console application. The traces generated by the NonBlockingConsole.WriteLine display properly however.
server:
AsyncAutoResetEvent aare = new AsyncAutoResetEvent(false);
public async Task<string> TestfuncAsync()
{
string strRet = "finished";
NonBlockingConsole.WriteLine("before autoresetevent");
await aare.WaitAsync();
NonBlockingConsole.WriteLine("after autoresetevent"); //is not traced even if asyncautoresetevent is set
return strRet;
}
void SetEvent()
{
aare.Set();
NonBlockingConsole.WriteLine("auto reset event set");
}
client UI:
private async void button1_Click(object sender, EventArgs e)
{
string value = await client.TestfuncAsync();
...
}
private void button2_Click(object sender, EventArgs e)
{
client.SetEvent();
}
NonBlockingConsole class: (reused from Does Console.WriteLine block?)
public static class NonBlockingConsole
{
private static BlockingCollection<string> m_Queue = new BlockingCollection<string>();
static NonBlockingConsole()
{
var thread = new Thread(
() =>
{
while (true) Console.WriteLine(m_Queue.Take());
}
);
thread.IsBackground = true;
thread.Start();
}
public static void WriteLine(string value)
{
value = DateTime.Now.ToString("<HH:mm:ss.fff>") + " " + value + " <ThreadID>: " + Thread.CurrentThread.ManagedThreadId.ToString();
m_Queue.Add(value);
}
}
I have class GetInfo (get object from server), Page1.xaml, Page2.xaml. I want tranmission object value from Page1 to Page2
This is my code
Class GetInfo
Class GetInfo{
Info use_info; //(Info is class)
public GetInfo(Info user_info)
{
this.user_info = user_info;
}
public void UseWebClient()
{
var client = new WebClient();
client.DownloadStringCompleted += (sender, e) =>
{
if (!string.IsNullOrEmpty(e.Result))
getInfo(e.Result);
};
client.DownloadStringAsync(new Uri("http://example.com/user_info.php?id=1"));
}
void getInfo()
{
I will Parse JSon string get from server become Info object...
}
}
Class Page1.cs//
Info user_info;
GetInfo userInfo;
public Page1()//constructor
{
userInfo = new GetInfo(user_info);
}
private void LayoutRoot_Loaded(object sender, RoutedEventArgs e)
{
userInfo.UseWebClient();
//THIS IS PROBLEM
if(user_info.name != null) //name is public properties;
{
PhoneApplicationService.Current.State["user_info"] = user_info;
NavigationService.Navigate(new Uri("/Page2.xaml", UriKind.Relative));
}
else
{
MessageBox.Show("Check Connect!", "Warning", MessageBoxButton.OK)
if(result == MessageBoxResult.OK)
Application.Current.Terminate();
}
}
I know DownloadStringCompleted call when event LayoutRoot_Loaded() finish. Problem is I can't move to Page2 if LayoutRoot_Loaded() not finish.
I need solution to solve the problem
Thanks!
I can't seem to figure out how to display Account ID and Account Balance into a textbox after the selected index is changed in the listbox. I have a Customer class and a Checking account class(which is a subclass of a Bank Account class). The part of the code that is messing up is at the bottom.
This is the part of my code that I'm having trouble with:
txtAccountID.Text = frmStart.GetCustomer()[lstTabPage1.SelectedIndex].GetCheckers()[lstFrmStartChecking.SelectedIndex].GetAcctNumber();
txtBalance.Text = frmStart.GetCustomer()[lstTabPage1.SelectedIndex].GetCheckers()[lstFrmStartChecking.SelectedIndex].GetBalance().ToString();
This is the rest of the code:
public partial class frmStart : Form
{
private static List<Customer_Account> customers;
private Customer_Account aCustomer;
private Saving_Account aSaver;
private static List<Saving_Account> savers;
private Checking_Account aChecker;
private static List<Checking_Account> checkers;
public frmStart()
{
InitializeComponent();
customers = new List<Customer_Account>();
checkers = new List<Checking_Account>();
savers = new List<Saving_Account>();
}
#region New form for Savings and Checking
private void lstFrmStartChecking_DoubleClick(object sender, EventArgs e)
{
//Shows Checking form
frmChecking showCheckingForm = new frmChecking();
this.Hide();
showCheckingForm.ShowDialog();
this.Close();
}
private void lstFrmStartSavings_SelectedIndexChanged(object sender, EventArgs e)
{
//Show Savings form
frmSavings showSavingForm = new frmSavings();
this.Hide();
showSavingForm.ShowDialog();
this.Close();
}
#endregion
#region Everything needed for TabPage1
//Sets CheckChanged event handler for either New customer or Existing Customer
private void rdoNewCustomer_CheckedChanged(object sender, EventArgs e)
{
groupBox2.Visible = true;
groupBox3.Visible = false;
}
private void rdoExistingCustomer_CheckedChanged(object sender, EventArgs e)
{
groupBox3.Visible = true;
groupBox2.Visible = false;
}//End of CheckChanged event handler
//Button controls for Adding customer to our bank and Clearing the textboxes
//in the 1st group panel
private void btnAddCustomer_Click(object sender, EventArgs e)
{
AddCustomerAccountToList();
PopulateListBox(customers);
}
private void AddCustomerAccountToList()
{
double socialSecurity;
double phoneNumber;
double zipCode;
if (double.TryParse(txtTab1SocialSecurity.Text, out socialSecurity) && double.TryParse(txtTab1PhoneNumber.Text, out phoneNumber)
&& double.TryParse(txtTab1Zip.Text, out zipCode))
{
aCustomer = new Customer_Account(txtTab1SocialSecurity.Text, txtTab1Name.Text, txtTab1Address.Text, txtTab1City.Text,
txtTab1State.Text, txtTab1Zip.Text, txtTab1PhoneNumber.Text, txtTab1Email.Text);
customers.Add(aCustomer);
}
else
{
MessageBox.Show("Please be sure to use only numeric entries for: \nSocial Security \nPhone Number \nZip Code", "Non-numeric Entry");
}
}//End of AddCustomerAccount
private void btnTab1Clear_Click(object sender, EventArgs e)
{
foreach (Control ctrl in groupBox2.Controls)
{
if (ctrl is TextBox)
{
((TextBox)ctrl).Clear();
}
txtTab1SocialSecurity.Focus();
}
}//end of button controls for 1st group panel
//Add CheckingAccount to List()
//Populate ListBox for List<>
private void PopulateListBox(List<Customer_Account> aListCustomerAccount)
{
lstTabPage1.Items.Clear();
lstTabPage2Checking.Items.Clear();
foreach (Customer_Account customer in aListCustomerAccount)
{
lstTabPage1.Items.Add(customer.GetCustomerName().ToUpper());
lstTabPage2Checking.Items.Add(customer.GetCustomerName().ToUpper());
}
}//End of Populate listbox
//Search for an existing member with name
private void txtTabPage1Search_TextChanged(object sender, EventArgs e)
{
for (int i = 0; i < lstTabPage1.Items.Count; i++)
{
if (string.IsNullOrEmpty(txtTabPage1Search.Text))
{
lstTabPage1.SetSelected(i, false);
}
else if (lstTabPage1.GetItemText(lstTabPage1.Items[i]).StartsWith(txtTabPage1Search.Text.ToUpper()))
{
lstTabPage1.SetSelected(i, true);
}
else
{
lstTabPage1.SetSelected(i, false);
}
}
}//End of search
//This button will open a checking account for the customer
private void btnOpenCheckingAccount_Click(object sender, EventArgs e)
{
string acctID;
acctID = txtAccountID.Text;
aChecker = new Checking_Account(acctID, DateTime.Today, 0,
200, frmStart.GetCustomer()[lstTabPage1.SelectedIndex]);
}
//This button will open a saving account for the customer
private void btnOpenSavingsAccount_Click(object sender, EventArgs e)
{
aSaver = new Saving_Account(txtAccountID.Text, DateTime.Today, 0, 0.05,
frmStart.GetCustomer()[lstTabPage1.SelectedIndex]);
}
private static List<Customer_Account> GetCustomer()
{
return customers;
}
#endregion
#region Everything Needed for TabPage2
//Search TabPage 2 Checkers
private void txtTabPage2SearchChecking_TextChanged(object sender, EventArgs e)
{
for (int i = 0; i < lstTabPage2Checking.Items.Count; i++)
{
if (string.IsNullOrEmpty(txtTabPage2SearchChecking.Text))
{
lstTabPage2Checking.SetSelected(i, false);
}
else if (lstTabPage1.GetItemText(lstTabPage2Checking.Items[i]).StartsWith(txtTabPage2SearchChecking.Text.ToUpper()))
{
lstTabPage2Checking.SetSelected(i, true);
}
else
{
lstTabPage2Checking.SetSelected(i, false);
}
}
}//End Search TabPage2 Checkers
//Display values in textboxes depending on user selection in listbox
private void lstTabPage2Checking_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
txtTab2SocialSecurity.Text = customers[lstTabPage2Checking.SelectedIndex].GetSocialSecurity().ToString();
txtTab2Name.Text = customers[lstTabPage2Checking.SelectedIndex].GetCustomerName().ToString();
txtTab2City.Text = customers[lstTabPage2Checking.SelectedIndex].GetCity().ToString();
txtTab2State.Text = customers[lstTabPage2Checking.SelectedIndex].GetState().ToString();
txtTab2Zip.Text = customers[lstTabPage2Checking.SelectedIndex].GetZip().ToString();
txtTab2PhoneNumber.Text = customers[lstTabPage2Checking.SelectedIndex].GetPhoneNumber().ToString();
txtTab2Email.Text = customers[lstTabPage2Checking.SelectedIndex].GetEmail().ToString();
txtTab2Address.Text = customers[lstTabPage2Checking.SelectedIndex].GetAddress().ToString();
txtAccountID.Text = frmStart.GetCustomer()[lstTabPage1.SelectedIndex].GetCheckers()[lstFrmStartChecking.SelectedIndex].GetAcctNumber();
txtBalance.Text = frmStart.GetCustomer()[lstTabPage1.SelectedIndex].GetCheckers()[lstFrmStartChecking.SelectedIndex].GetBalance().ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
#endregion
}
(This is what the error message says)
System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Welcome to SO, Guy!
It looks to me that you are appending the .ToString() method to all of your controls except for this one:
txtAccountID.Text = frmStart.GetCustomer()[lstTabPage1.SelectedIndex].GetCheckers()[lstFrmStartChecking.SelectedIndex].GetAcctNumber();
Change your code to:
txtAccountID.Text = frmStart.GetCustomer()[lstTabPage1.SelectedIndex].GetCheckers()[lstFrmStartChecking.SelectedIndex].GetAcctNumber().ToString();
And you should be fine!
I am creating a REST Web Service using Java and Jersey API. The basic REST service works fine,but when I add in a DB connection it gives me a Class Not Found Exception and a SQL Exception - No driver found. I have included the ojdbc6.jar file in the Eclipse build path. Using the same code if I create a Java application it runs fine.
I have added my code below. Can some one plz suggest something.
EDIT: I included the jar file in the WEB-INF lib directory. But when I try to execute the code I get the following error: HTTP Status 405 - Method Not Allowed
public class Note {
private int noteId;
private String content;
private Date createdDate;
public Note() {}
public Note(int noteId, String content, Date createdDate) {
this.noteId = noteId;
this.content = content;
this.createdDate = createdDate;
}
public int getNoteId() {
return noteId;
}
public void setNoteId(int noteId) {
this.noteId = noteId;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
#Override
public String toString() {
return "Note [content=" + content + ", createdDate=" + createdDate
+ ", noteId=" + noteId + "]";
}
}
public class NoteDAO {
DatabaseAccess data;
Connection connection;
public NoteDAO()
{
try {
data = new DatabaseAccess();
connect();
} catch (SQLException e) {
e.printStackTrace();
}
}
private void connect() throws SQLException
{
try
{
data.connect();
connection = data.connection;
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public Note getNoteById(int id)
{
PreparedStatement prepStmt = null;
try {
String cSQL = "SELECT * FROM NOTE WHERE NOTEID = 12 ";
prepStmt = connection.prepareStatement(cSQL);
prepStmt.setInt(1, id);
ResultSet result = prepStmt.executeQuery();
Note note = new Note();
while (result.next())
{
note.setNoteId(result.getInt(1));
note.setContent(result.getString(2));
note.setCreatedDate( (Date) new java.util.Date(result.getDate(3).getTime()));
}
return note;
} catch (SQLException e) {
e.printStackTrace();
prepStmt = null;
return null;
}
}
}
#Path("/notes")
public class Notes {
#Context
UriInfo uriInfo;
#Context
Request request;
NoteDAO dao = new NoteDAO();
#Path("{note}")
#GET
#Produces(MediaType.APPLICATION_XML)
public Note getNote(
#PathParam("note") String idStr) {
int id = Integer.parseInt(idStr);
Note note = dao.getNoteById(id);
if(note==null)
throw new RuntimeException("Get: Note with " + id + " not found");
return note;
}
public class DatabaseAccess {
Connection connection = null;
public void connect() throws SQLException
{
String DRIVER = "oracle.jdbc.driver.OracleDriver";
String URL = "jdbc:oracle:thin:#xx.xxx.xx.xxx:1521:XXXX";
String UserName = "username";
String Password = "password";
try
{
Class.forName(DRIVER);
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
try
{
connection = DriverManager.getConnection(URL,UserName,Password);
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public void disconnect() throws SQLException
{
connection.close();
}
}
If you are using datasources that are managed by the application server, you need to put the ojdbc6.jar library inside the lib folder of your application server.
On JBoss for example, it would be $JBOSS_HOME/server/default/lib.
This is required, because in such case, the datasource is being build when the server starts and independently from your application, which means the server cannot use your application JARs.
If, however, you are pooling the connections yourself, you need to make sure, that the ojdbc6.jar is inside the lib folder of your application WAR archive.
This code doesn't work :-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using SilverlightPlainWCF.CustomersServiceRef;
using System.Diagnostics;
using System.Collections.ObjectModel;
using System.ComponentModel;
namespace SilverlightPlainWCF
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
this.DataContext = Customers;
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}
public static readonly string CustomersPropertyName = "Customers";
// public DependencyProperty CustomersProperty = DependencyProperty.Register(CustomersPropertyName,typeof(ObservableCollection<Customer>)
// ,typeof(MainPage),new PropertyMetadata(null));
private ObservableCollection<Customer> customers;
public ObservableCollection<Customer> Customers
{
//get { return GetValue(CustomersProperty) as ObservableCollection<Customer>; }
//set
//{
// SetValue(CustomersProperty, value);
//}
get
{
return customers;
}
set
{
customers = value;
}
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
CustomersServiceClient objCustomersServiceClient = new CustomersServiceClient();
objCustomersServiceClient.GetAllCustomersCompleted += (s, res) =>
{
if (res.Error == null)
{
Customers = res.Result;
}
else
{
MessageBox.Show(res.Error.Message);
}
};
objCustomersServiceClient.GetAllCustomersAsync();
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
// Do not load your data at design time.
// if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
// {
// //Load your data here and assign the result to the CollectionViewSource.
// System.Windows.Data.CollectionViewSource myCollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["Resource Key for CollectionViewSource"];
// myCollectionViewSource.Source = your data
// }
// Do not load your data at design time.
// if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
// {
// //Load your data here and assign the result to the CollectionViewSource.
// System.Windows.Data.CollectionViewSource myCollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["Resource Key for CollectionViewSource"];
// myCollectionViewSource.Source = your data
// }
}
private void LayoutRoot_MouseLeave(object sender, MouseEventArgs e)
{
}
private void customerDataGrid_RowEditEnded(object sender, DataGridRowEditEndedEventArgs e)
{
var Customer = Customers[e.Row.GetIndex()];
Debug.WriteLine(Customer);
}
private void customerDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
}
}
Whereas if i just change the above property of Customers to this :-
public static readonly string CustomersPropertyName = "Customers";
public DependencyProperty CustomersProperty = DependencyProperty.Register(CustomersPropertyName,typeof(ObservableCollection<Customer>)
,typeof(MainPage),new PropertyMetadata(null));
private ObservableCollection<Customer> customers;
public ObservableCollection<Customer> Customers
{
get { return GetValue(CustomersProperty) as ObservableCollection<Customer>; }
set
{
SetValue(CustomersProperty, value);
}
}
it works. Why is it that only with DependencyProperty the grid gets populated? Please explain me in little detail. Also, do i have to compulsorily use ObservableCollection or even List is fine?
Short answer: Dependency properties are wrappers which know how to 'dispatch changes'.
See Dependency Properties Overview