I created a working Windows Forms project in C# that accesses an Access database of recipes. Using table adapters and the dataset I am able to query, update and insert new data into the database.
I created a new VS project, imported my database and started a new class. My problem is when I try to set up the table adapters I get errors, specifically with the .Fill() method. When I check the datasource.xsd I can see that the .get() and .Fill() methods were created but I can't seem to access them like I did when I just dragged and dropped the binding source onto the WinForm previously.
I copied the code to programmatically create the table adapters from the MSDN website but I get the error on the line where I call ingredientTableAdapter.Fill(recipiesNewDataSet); method. Any one have a clue why? Here's my code on this project so far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyRecipeDataBase
{
class QueryClass
{
recipiesNewDataSet recipiesNewDataSet = new recipiesNewDataSet();
recipiesNewDataSetTableAdapters.IngredientTableAdapter ingredientTableAdapter = new recipiesNewDataSetTableAdapters.IngredientTableAdapter();
ingredientTableAdapter.Fill(recipiesNewDataSet);
}
}
The answer was staring me in the face!
You're putting code directly in the class body. It should be inside a function. Inside the class constructor, for instance.
class QueryClass
{
public QueryClass()
{
recipiesNewDataSet recipiesNewDataSet = new recipiesNewDataSet();
recipiesNewDataSetTableAdapters.IngredientTableAdapter ingredientTableAdapter = new recipiesNewDataSetTableAdapters.IngredientTableAdapter();
ingredientTableAdapter.Fill(recipiesNewDataSet);
}
}
Related
I am getting the titled error when I declare a list with object type in a class file in my Asp.Net web application. I have other classes running so the class system does work. The same declaration is fine in a webform c# code behind. Any help is appreciated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Text;
/// <summary>
/// Summary description for TriviaUtilities
/// </summary>
public class TriviaClass
{
public TriviaClass()
{
//
// TODO: Add constructor logic here
//
}
public void getRegistration()
{
List<Activity> sampleREG = new List<Activity>();
}
}
UPDATE: Declaring List<int> sampleREG = new List<int>() or List<string> sampleREG = new List<string>() in the class file poses no problem and this works in a webform also as expected. Declaring the type as an object gives the namespace error in the class file but in the webform it is fine. Since it works on the webform and I have the same namespaces in both the webform and class files, I am suspecting that fixing this is complicated and it needs someone with a higher scope of programming to help with it.
Yes, Rainbolt, Captain Wibble, Quergo. The original use of the object type for the list is in a web page that contains 3000 lines. Buried in there was the Activity class that the IDE was looking for, for the Activity object type of the list.
See here to create a class.
I'm developing a POS in WPF.
For CRUD operations, I'm using Entity Framework.
Created a WPF View ProductADD
Product Add View Snap
Created a Class ProductController in Controller Folder
Made object of Entity Framework in ProductController Class ProductController Calss Snap
Created a method: SaveProduct(Product product) which is taking product object as argument and saving it to database using EF.
And From Xaml.Cs I'm calling ProductController Class's Saveproduct method and sending the new product data to it.
private void Button_Click(object sender, RoutedEventArgs e)
{
ProductController pc = new ProductController();
PRODUCT product = new PRODUCT();
product.PRODUCT_NAME = Product_Name.Text.ToString();
product.UNITPRICE = Convert.ToInt32(Unit_Price.Text.ToString());
product.CATEGORY_Id = 1;
pc.SaveProduct(product);
MessageBox.Show("Product Added Successfully");
this.Close();
}
And in ProductController the following code is updating the database
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PizzaLounge.Models;
namespace PizzaLounge.Controllers
{
public class ProductController
{
PizzaLoungeEntities db = new PizzaLoungeEntities();
public void SaveProduct(PRODUCT product)
{
db.PRODUCTs.Add(product);
db.SaveChanges();
}
}
}
The code executes successfully but it doesn't save the product in database. P.S. I have used db.savechanges().
Am I missing something or using wrong approach to update database?
You are probably using |DataDirectory| in your connection string. If debugging in Visual Studio, the database you are using is in the bin/debug folder.
Unfortunately if you look at the db through Server Explorer it has a different connection string so you don't see the changes.
Also if the database property "Copy to Output directory" is set to Copy Always then every time you debug you will overwrite your db and you won't see the data you added. You can check if this is happening by using a new db context in the same debug session where you add the records. If the new context can get the records from the db then you know they must be being written (as well as the other checks listed in the comments)
This can be fixed by changing Copy To Output Directory to Never Copy or Copy If Newer.
Because you are using mdf file attached to your project so your problem is like this question
Attaching database to my project
You are saving data to database that is in bin\debug folders ,and then you see the mdf file that is in your project folder and you don't see the data .
change your connection string from DataDirectory to
absolute path to the project database file. When deploying, just change it back to |DataDirectory|
How did you checked that the products haven't been added, from db.PRODUCTs or from the Database Explorer?
Maybe you just need to dispose your context, change your ProductController for something like:
using(var db = new PizzaLoungeEntities()){
db.PRODUCTs.Add(product);
db.SaveChanges();
}
Or to dispose ProductController after you finish to use it.
I am pretty new to coding ADO.Net/entity framework stuff. I am trying to follow "Microsoft ADO.NET Entity Framework Step by Step", Microsoft Press Mueller. I'm using VS 2012 with EF6 installed.
Start a new project, and adding an new Empty ADO.NET Entity Data Model. It's pretty simple, a few scalars and one Enumeration called UserFavorites. Then add a data source > Object > Drilling down to my UserFavorites object and finishing. I change toe UserFavorites object on the data source tab to detail view ( and a couple other changes like combo box and label on the others). Then drag the UserFavorites object to the form. It creates a Binding source and binding navigator all as it should. After enabling the save button and entering the code below it runs great and gets the records from the database that can be scrolled between. The problem is when I click the plus to add a record, fill it in, and click save, I get validation errors. on the
Hide Copy Code
UserFavoritesContext.SaveChanges();
line. The first error is
"Exception:Thrown: "Value of '1/1/0001 12:00:00 AM' is not valid for 'Value'. 'Value' should be between 'MinDate' and 'MaxDate'." (System.ArgumentOutOfRangeException)"
There is a date picker on the form, and it's filled out correctly. If I remove that item from my model I get errors on the next item in the model. For some reason it's not pulling the data filled in on the form and trying to use defaults (or null).
I can't find anyone else with this problem online, so I guess I am missing something silly. I followed the book exactly ( and can't find a help forum for the book). I hope this is clear enough for someone to offer some guidance.
Images of Form and Data Source,Model,Error, and zip of project are at
https://www.dropbox.com/sh/z6yhvbp1uk7bobm/AADa7fnS82PzwNLlPrycnCYza?dl=0
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace UserFavoritesEF6
{
public partial class Form1 : Form
{
// Define the context used to access the database.
UserFavoritesModelContainer UserFavoritesContext;
<pre>
public Form1()
{
InitializeComponent();
// Initialize the database context.
UserFavoritesContext = new UserFavoritesModelContainer();
// Query the database for the records you want.
var dbQuery =
UserFavoritesContext.UserFavorites.Where(id => id.UserId >= 0).ToArray();
}
private void userFavoritesBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
UserFavoritesContext.SaveChanges();
}
private void Form1_Load(object sender, EventArgs e)
{
// Assign a local copy of the queried records to the
// binding source.
userFavoritesBindingSource.DataSource =
UserFavoritesContext.UserFavorites.Local;
// Fill the Favorite Colors list with acceptable colors and
// choose a default.
favoriteColorComboBox.DataSource = Enum.GetValues(typeof(ColorNames));
favoriteColorComboBox.SelectedItem = ColorNames.Red;
}
}
}
This code works fine within a Kentico website:
var users = UserInfoProvider.GetUsers();
for (int x = 0; x < users.Count(); x++
{
UserInfo currentUser = users.ElementAt(x);
currentUser.SetValue("AcceptsAlerts", equivalentSubscriber.Status != SubscriberStatus.Unsubscribed);
UserInfoProvider.SetUserInfo(currentUser);
}
When I move the code to a console app, any calls to UserInfoProvider result in the error: "Object type 'cms.usersettings' not found"
For the initial call to get the users, I can do it like this in the console app:
DataSet usersds = new CMS.DataEngine.DataQuery("cms.user.selectall").Execute();
then loop through Table1 of the dataset using the user data:
UserInfo currentUser = new UserInfo(dtUsers.Rows[x]);
All is fine and working, until I come to write the updated user back to the database. I cannot find another way of writing the data apart from calling:
UserInfoProvider.SetUserInfo(currentUser);
Does anyone know another way to save the user data? or to resolve the error. The error is a runtime error and as far as I know, I have referenced everything I need to. The field I am editing is a custom field added to the cmsUser table.
using statements for info:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using CMS;
using CMS.CustomTables;
using CMS.DataEngine;
using CMS.Membership;
Before you start working with Kentico CMS API from an external application make sure you call the following lines:
CMS.DataEngine.ConnectionHelper.ConnectionString = "your connection string";
CMS.Base.SystemContext.WebApplicationPhysicalPath = Application.StartupPath;
CMS.DataEngine.CMSApplication.Init();
Then, you'll be also able to use UserInfoProvider.GetUsers() object query instead of using DataQuery.Execute().
Are you sure you are referencing all necessary assemblies?
Following scenario works on my machine with configuration: Kentico 8.x, Web Application project
Reference in your Console application these assemblies from lib folder
CMS.Base
CMS.DataEngine
CMS.DataProviderSQL
CMS.Membership
Then copy your Connection String from Web Application's web.config to Console Application's App.config.
After that you can use this code to set custom user properties
static void Main(string[] args)
{
var users = UserInfoProvider.GetUsers();
foreach (var user in users)
{
user.SetValue("myTestString", "test");
user.Generalized.SetObject();
}
}
For anyone looking to get a SiteID to use in API calls from an external app such as getting an email template, this might help you. In Kentico 8.1 you can go to Sites > General and get the code name for your site. Then you can do this:
int siteID = CMS.SiteProvider.SiteInfoProvider.GetSiteID("<your site code name>");
Hope it helps!
I'm learning about ADO.Net entity framework, and
I'm stuck at adding entity table object to the database.
I have a local database in solution called testDB.
It has two columns - id(primary, unique, identiy),name(varchar(100))
and entity for it. The main application code is here below.
Problem is, that using this code it doesn't add anything to the table, but also
I'm not having any errors.
What could go wrong?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace entityproject
{
class Program
{
static void Main(string[] args)
{
String someString;
someString = "Just a test";
testDBEntities tdbEntity = new testDBEntities();
test tblTest = new test();
tblTest.name = someString;
tdbEntity.test.Add(tblTest);
tdbEntity.SaveChanges();
}
}
}
App.config here
http://pastie.org/6980938
I think I know the problem - had the same thing last time I tried using SQL CE.
The connection string doesn't point to the sdf file that you created - it uses a new one that I believe gets put into your bin\Debug or bin\Release directory (in your config file as data source=|DataDirectory|\testDB.sdf), with your EXE and DLLs. If you check that directory, I bet you'll find another sdf file there, that has a bunch of records added.
If you want to use the sdf that you've already created, change the connection string to point specifically to that file.