i am newbie of c# and win phone 7
i create a simple database i read this example
http://f5debug.net/2012/02/26/learn-windows-phone-7-development-in-31-days-day-26-working-with-creating-a-local-database-in-wp7/
i open Db in Mainpage
public partial class MainPage : PhoneApplicationPage
{
// short connection string format
private const string strConnectionString = #"isostore:/ManutenzioneDB.sdf";
// Costruttore
public MainPage()
{
InitializeComponent();
using (SampleData.EventoDataContext Empdb = new SampleData.EventoDataContext(strConnectionString))
{
// se il db non esiste creo il db
if (Empdb.DatabaseExists() == false)
{
Empdb.CreateDatabase();
// MessageBox.Show("Employee Database Created Successfully!!!");
}
}
now in Main page i create a button than open an other page
private void button1_Click(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri("/InsertData.xaml", UriKind.Relative));
}
now i don't know can access to Db from InsertData page (InsertData.xaml.cs),
best regads
Antonio
Simpler than you think. :)
var db = new SampleData.EventoDataContext();
db.MyTable.InsertOnSubmit(new MyTable() { ... });
db.Submit();
"MyTable" is the name of the table you defined inside the database.
Make sure you define a primary key, or inserting into the table will fail.
You will need to initialize your table inside the {...} part.
To get items from the table:
foreach (var item in db.MyTable.Where(x => x.SomeProp == 1))
{
//…
}
This will return all the rows where SomeProp is 1. You can now inspect item to see what the row contains.
Try to study the vici cool stored procedure. It is very very simple to create, add, and retrieve data from any db in WP7 applications
http://viciproject.com/wiki/projects/coolstorage/home
Related
The 'Customer' form has a variable called AcctReferenceNbr (Variable that I'm trying to grab shown in yellow) which takes a two-letter abbreviation of the customer name. I am currently editing the Projects form, and I want to use this abbreviation as part of the External Ref. Nbr.
The attached image End Result I'm trying to achieve shows what the end result should look like. The number from the QuoteID is appended to the abbreviation.
I am able to successfully grab the QuoteID as it is part of the Projects table, but I am currently unable to grab the AcctReference Nbr from the Customer table.
I have a RowSelected event on the QuoteID field, which is shown below:
namespace PX.Objects.PM
{
public class ProjectEntry_Extension : PXGraphExtension<ProjectEntry>
{
#region Event Handlers
protected void PMProject_RowSelected(PXCache cache, PXRowSelectedEventArgs e)
{
PMProject row = (PMProject)e.Row;
if (row.ContractCD != null) {
PMProject item = PXSelectorAttribute.Select<PMProject.contractCD>(cache, row) as PMProject;
// The "UP" string is where the abbreviation is supposed to be,
// but I just added two letters to test if the appending works, which it does.
row.ExtRefNbr = "UP" + item.ContractCD;
}
}
#endregion
}
}
What I've tried so far:
Accessing the Customer table namespace to grab the value and pass it to the Projects form, which didn't work because it didn't accept the Customer type in the Projects form.
Adding a PXDefault attribute to the External Ref. Nbr which would try and grab the variable using SQL.
I'm a bit stuck on what else I can try. Any help would be appreciated :)
UPDATED
Below is how I went about trying to grab the AcctReferenceNbr value from the Customer table.
The reason why I tried using the PXSelectorAttribute method was that I added the AcctReferenceNbr as a column to the Quote ID selector (selector is shown in the link above called 'End Result I'm trying to achieve').
So I figured I could try and grab that value in the Customer namespace, as that is where the variable resides, and pass that up to the Project namespace above.
Then, I would call the public method below in the Project namespace to get the required abbreviation:
// instead of this
row.ExtRefNbr = "UP" + item.ContractCD;
// it would be this
row.ExtRefNbr = PX.Objects.AR.CustomerMaint_Extension.getAcctReferenceNbr(cache, e) + item.ContractCD;
namespace PX.Objects.AR
{
public class CustomerMaint_Extension : PXGraphExtension<CustomerMaint>
{
#region Event Handlers
public static string getAcctReferenceNbr(PXCache cache, PXRowSelectedEventArgs e)
{
BAccount row = (BAccount)e.Row;
BAccount item = PXSelectorAttribute.Select<BAccount.acctReferenceNbr>(cache, row) as BAccount;
return item.acctReferenceNbr;
}
}
#endregion
}
}
Is there a proper way to target the actual table?
try this. I haven't tested this but give it a go.
protected void PMProject_RowSelected(PXCache cache, PXRowSelectedEventArgs e)
{
PMProject row = (PMProject)e.Row;
if (row.ContractCD != null && row.CustomerID != null)
{
BAccount ba = (BAccount )PXSelectorAttribute.Select<PMProject.customerID>(cache, row) ;
row.ExtRefNbr = ba.AcctReferenceNbr+ row.ContractCD;
}
}
you certainly don't need to extend the CustomerMaint graph.
I am testing the workings of WPF with Entity Framework. I have a SS table called Vendors {VendorCode, VendorName, Phone}.
I am sticking with only EF and I am able to display and navigate the recordset on a WPF form with buttons first, next, last etc. I used the instructions on the MSDN site (Create a simple data application with WPF and Entity Framework 6)
My problem is the recordset is sorted only in the order it was entered into SS. I would like to sort it by VendorCode or by VendorName to make it easier on the user. I can't seem to make it sort the recordset or table data coming through EF.
Can you please help? Thank you!
Here is a snippet of my code:
public Vendor newVendor { get; set; }
VendorsEntities context = new VendorsEntities();
CollectionViewSource VendorViewSource;
public MainWindow()
{
InitializeComponent();
newVendor = new Vendor();
VendorViewSource = ((CollectionViewSource)
(FindResource("VendorViewSource")));
DataContext = this;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
// this next line doesn't do it
context.Vendors.OrderBy(Vendor => Vendor.VendorCode);
context.Vendors.Load();
VendorViewSource.Source = context.Vendors.Local;
}
private void NextCommandHandler(object sender, ExecutedRoutedEventArgs e)
{
VendorViewSource.View.MoveCurrentToNext();
}
You would need to set the result of OrderBy method in to some variable and then use that as OrderBy will return a new reference, or you can use the set the reference of context.Vendors to the reference returned by OrderBy() method.
Try doing it like:
var ordered = context.Vendors.OrderBy(Vendor => Vendor.VendorCode);
VendorViewSource.Source = ordered;
another way can be to order it after bringing the result back, but it is not a recommended approach, first approach should be preferred, but just giving another option which is also possible:
var vendors = context.Vendors.Load().OrderBy(Vendor => Vendor.VendorCode);
VendorViewSource.Source = vendors;
Hope it helps!
You are sorting context, not displayed items. Try:
VendorViewSource.Source = context.Vendors.OrderBy(Vendor => Vendor.VendorCode);
I have a database consist of 3 column which are Id(int), Title(nvarchar) and Description(nvarchar). I added a new column name more(nvarchar) and generated a new database context to replace the old one. I am not able to run my application after adding a new column. What am I missing? Thanks
Below is the error message:
A first chance exception of type 'System.Data.SqlServerCe.SqlCeException' occurred in Microsoft.Phone.Data.Internal.ni.dll
Extra:
After removing the new column more(nvarchar), and regenerated a new database context to replace it again, it works as normal. Meaning its back as the old one without adding a new column to the table.
Below is some code for the MainPage.xaml.cs:
namespace PhoneApp
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
// Set the data context of the LongListSelector control to the sample data
DataContext = App.ViewModel;
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
}
// Load data for the ViewModel Items
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (!App.ViewModel.IsDataLoaded)
{
App.ViewModel.LoadData();
}
using (DatabaseContext c = new DatabaseContext(DatabaseContext.ConnectionString))
{
c.CreateIfNotExists();
c.LogDebug = true;
//output todolist data from database
MLongListSelector.ItemsSource = c.ToDoList.ToList();
}
}
// Handle selection changed on LongListSelector
private void MainLongListSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// If selected item is null (no selection) do nothing
if (MLongListSelector.SelectedItem == null)
return;
//select the item selected from the class.property
var title = (MLongListSelector.SelectedItem as PhoneApp.ToDoList).Title;
var desc = (MLongListSelector.SelectedItem as PhoneApp.ToDoList).Description;
var id = (MLongListSelector.SelectedItem as PhoneApp.ToDoList).Id;
//send data through Title and Desc
NavigationService.Navigate(new Uri("/ToDoDetailPage.xaml?Title=" + title + "&Desc=" + desc + "&Id=" + id, UriKind.Relative));
// Navigate to the new page
//NavigationService.Navigate(new Uri("/ToDoDetailPage.xaml", UriKind.Relative));
// Reset selected item to null (no selection)
MLongListSelector.SelectedItem = null;
}
private void LongListSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var si = MainLongListSelector.SelectedItem as PhoneApp.ViewModels.ItemViewModel;
if (MainLongListSelector.SelectedItem == null)
return;
if (si.LineOne.Equals("+ To Do List"))
NavigationService.Navigate(new Uri("/todolistPage.xaml", UriKind.Relative));
else if (si.LineOne.Equals("+ Reminder"))
NavigationService.Navigate(new Uri("/reminderPage.xaml", UriKind.Relative));
// Reset selected item to null (no selection)(//important)
MainLongListSelector.SelectedItem = null;
}
}
}
I ran into a similar issue. As far as I could tell the issue is attempting to modify the schema against an existing database. In my case the code does not initialize the DB if it already exists.
if (db.DatabaseExists() == false)
{
// Create database.
db.CreateDatabase();
}
...so the schema changes were not reflected, resulting in a null reference when selecting the new column. I resolved by restarting the phone emulator which removed the previous db file.
I have a Web Form application using VS2013 and Entity Framework 6. Just upgraded from VS2012 and EF5 with no changes required.
There is an article editor form that once an item is inserted, will redirect the user to another form by Id. (Like a wizard)
Inserting records works without issue. The problem is capturing the new record Id. InsertItem does return the new Id from the DB.
I have tried creating an event handler which does not seem to have the value.
Any idea how to capture the returned Id? Alternatives will be appreciated.
Thanks in advance.
// Web Form ArticleEditor code behind
public partial class ArticleEditor : System.Web.UI.Page
{
// page level variables
private readonly IArticleRepository _repository = new ArticleRepository();
// more stuff here
frmArticle_OnItemInserted(object sender, formViewInsertedEventArgs e)
{
// I assume the value can be captured here???
}
// FormView
<asp:FormView runat="server" ID="frmArticle" RenderOuterTable="True"
ItemType="WebApplication.BLL.Model.Article" DataKeyNames="ArticleId"
DefaultMode="ReadOnly"
SelectMethod="GetItem"
InsertMethod="InsertItem"
UpdateMethod="UpdateItem"
DeleteMethod="DeleteItem"
OnItemInserted="frmArticle_OnItemInserted"
CssClass="FormView">
<InsertItemTemplate>
// controls here
</InsertItemTemplate>
</FormView>
// repository ArticleRepository
private readonly AppDbContext _db = new AppDbContext();
public int InsertItem(ModelMethodContext modelMethodContext)
{
// create new model object
var obj = new Article();
// attempt to save model
modelMethodContext.TryUpdateModel(obj);
if (!modelMethodContext.ModelState.IsValid)
{
// model is in an invalid state
return 0;
}
_db.Articles.Add(obj);
_db.SaveChanges();
return obj.ArticleId;
}
i am designing a local database in .net with wpf as gui. I have added a new database, and added a new table. Through the TableAdapter i generated 2 statements ( 1 statement is a select stmt and 1 is a insert) , i insert name and firstname (id is auto generated). It works fine, i can display the table in a datagrid (wpf toolkit) and also add new items (name,firstname), when i close and start the application everything is fine (data in table is stored) BUT when i try to preview data in my database dataset (where my Adapters exist) , no data is displayed and then the table gets deleted.. why?
public partial class MainWindow : Window
{
public MainWindow()
{
this.InitializeComponent();
PlayerTableAdapter objPlayerTableAdapter = new PlayerTableAdapter();
objDataGridResults.ItemsSource = objPlayerTableAdapter.GetDataAllPlayer();
}
//Button Event onClick
private void m_voidAddPlayer(object sender, System.Windows.RoutedEventArgs e)
{
PlayerTableAdapter objPlayerTableAdapter = new PlayerTableAdapter();
objPlayerTableAdapter.InsertQueryPlayer(objTextBoxPlayerName.Text.ToString(), objTextBoxPlayerFirstName.Text.ToString());
objDataGridResults.ItemsSource = objPlayerTableAdapter.GetDataAllPlayer();
}
}
the reason is that you modify not database, but dataset - the in-memory snapshot of database. When you close app it gets lost. You should call objPlayerTableAdapter.Update. And consider moving to Linq to SQL or Entity Framework, DataSets are outdated.