Error when trying to loop through entities from an Azure Table - c#

i keep getting this error, "The current value 'String.Empty' type is not compatible with the expected 'System.Boolean' type", when i try to loop through a bunch of entities from an Azure table, i am only new to using Azure so this could be something very easy, the error that i am getting.
my code :
private void registerButton_Click(object sender, RoutedEventArgs e)
{
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("StorageConnectionString"));
// Create the table client
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
// Get the data service context
TableServiceContext serviceContext = tableClient.GetDataServiceContext();
// Create a new customer entity
user = new UserDetailsEntity();
//Setting the fields of the new userEntity
user.username = usernameText.Text;
user.password = passwordText.Text;
user.subscriptionID = subText.Text;
user.subscriptionName = subscriptionNameText.Text;
user.thumbprint = thumbprintText.Text;
user.email = emailText.Text;
user.phoneNumber = "3530" + numberText.Text;
int rowCount = 1;
CloudTableQuery<UserDetailsEntity> Query = (from en in serviceContext.CreateQuery<UserDetailsEntity>("userdetails")
select en).AsTableServiceQuery<UserDetailsEntity>();
//error occurs in the next line
foreach (UserDetailsEntity ent in Query)
{
rowCount++;
}
user.RowKey = rowCount.ToString();
// Add the new customer to the people table
serviceContext.AddObject("userdetails", user);
// Submit the operation to the table service
serviceContext.SaveChangesWithRetries();
//Set the variables so they can be retrieved when the next screen loads
Application.Current.Properties["username"] = usernameText.Text;
Application.Current.Properties["password"] = passwordText.Text;
Window1 userHome = new Window1();
this.Close(); //to close Password window
userHome.Show(); //to show Main form
}

Without more code, I cannot tell you exactly where the problem is, however the exception is fairly explanatory. You are trying to set a boolean property to a value of a string.
If the error is occurring in your foreach as you noted in the code comment, then I would check how your UserDetailsEntity object is set up. There is probably a property that is set up as a boolean, yet your data is coming back as a String.Empty. The reason you are getting this in your foreach is because your LINQ query is of type IQueryable, so it will not actually execute and fill your objects until you actually access the data (by your foreach)*. So, you could put breakpoints in your UserDetailsEntity properties to see which one it is if this is not blatent from looking at the code.
*Keep in mind that this is the N+1 problem, where you are making a call to the database on each iteration of your loop. You can resolve this by calling .ToList() to eager load all of your data at once into your query...if this is a problem for you, that is.

Related

changing the sourcetable of a linked table in access 2007 with C#

I'll start by asking am I right in thinking that in the image below:
the 'TABLE=CLOASEUCDBA.T_BASIC_POLICY' is not part of the connection string? in fact it is the source table name?
I'm looking to alter this to another linked table on the same database. The connection string should there be the same and the name that appears in ACCESS should be the same. The only difference should be under the hood it is actually referencing another table and of course if you open the table it will contain different fields and data.
my code for far to do this is:
var dbe = new DBEngine();
Database db = dbe.OpenDatabase(#"C:\Users\xxxx\Documents\Test.accdb");
foreach (TableDef tbd in db.TableDefs)
{
if (tbd.Name.Contains("CLOASEUCDBA_T_BASIC_POLICY"))
{
tbd.SourceTableName = "CLOASEUCDBA_T_BILLING_INFORMATION";
}
}
db.Close();
However I'm getting a big fat COMException "Cannot set this property once the object is part of a collection.". I'm not sure exactly why and all the examples I can find online are all written in VB/VBA and I only have very very limited exposure to this. Any help is appreciated.
EDIT:
I have tried to go a different route with no futher success using the code:
if (tbd.Name.Contains("CLOASEUCDBA_T_BASIC_POLICY"))
{
var newtable = db.CreateTableDef("this is a new table");
newtable.Name = "new table";
newtable.Connect = tbd.Connect;
newtable.SourceTableName = "CLOASEUCDBA_T_BILLING_INFORMATION";
db.TableDefs.Append(newtable);
//tbd.SourceTableName = "CLOASEUCDBA_T_BILLING_INFORMATION";
}
In this case I get the error "ODBC--call failed."
Since we're not allowed to change the SourceTableName of a TableDef object that already exists in the TableDefs collection we need to create a new TableDef object, .Delete the old one, and then .Append the new one:
// This code requires the following COM reference in your project:
//
// Microsoft Office 14.0 Access Database Engine Object Library
//
// and the declaration
//
// using Microsoft.Office.Interop.Access.Dao;
//
// at the top of the class file
string tableDefName = "CLOASEUCDBA_T_BASIC_POLICY";
var dbe = new DBEngine();
Database db = dbe.OpenDatabase(#"C:\Users\xxxx\Documents\Test.accdb");
var tbdOld = db.TableDefs[tableDefName];
var tbdNew = db.CreateTableDef(tableDefName);
tbdNew.Connect = tbdOld.Connect;
tbdNew.SourceTableName = "CLOASEUCDBA_T_BILLING_INFORMATION";
db.TableDefs.Delete(tableDefName); // remove the old TableDef ...
db.TableDefs.Append(tbdNew); // ... and append the new one
db.Close();

Nhibernate transaction locks a tabel

I have developed a WCF api which is using nHibernate. I am new to this. I have used session.update to take care of transaction. I have a for loop in which based on select condition I am updating a record ie. If A is present in tabel1 then I am updating the table else inserting a new entry.
I am getting "could not execute query." when trying to execute a select query on a table which was previously being updated by adding a new entry in the table.
What I think is, because I am using session.save(table1) and then trying select entries from that table I am getting an error. Since session.save temporarily locks the table I am not able to execute a select query on that table.
What can be the solution on this?
Update:
This the for loop I am using to check in the database for some field:
using (ITransaction tranx = session.BeginTransaction())
{
savefunction();
tranx.Commit();
}
Save function:
public void savefunction()
{
for (int i = 0; i < dictionary.Count; i++)
{
ICandidateAttachmentManager candidateAttach = new ManagerFactory().GetCandidateAttachmentManager();
CandidateAttachment attach = new CandidateAttachment();
attach = checkCV();
if(attach == null)
{
//insert new entry into table attach
session.save(attach);
}
}
}
checkCV function:
public void checkCV()
{
using (ICandidateAttachmentManager CandidateAttachmentManager = new ManagerFactory().GetCandidateAttachmentManager())
{
IList<CandidateAttachment> lstCandidateAttachment = CandidateAttachmentManager.GetByfkCandidateId(CandidateId);
if (lstCandidateAttachment.Count > 0)
{
CandidateAttachment attach = lstCandidateAttachment.Where(x => x.CandidateAttachementType.Id.Equals(FileType)).FirstOrDefault();
if (attach != null)
{
return null;
}
else
{
return "some string";
}
}
}
}
What happening here is in the for loop if say for i=2 the attach value comes to null that I am entering new entry into attach table. Then for i=3 when it enters checkCV function I get an error at this line:
IList lstCandidateAttachment =
CandidateAttachmentManager.GetByfkCandidateId(CandidateId);
I think it is because since I am using session.save and then trying to read the tabel contents I am unable to execute the query and table is locked till I commit my session. Between the beginTransaction and commit, the table associated with the object is locked. How can I achieve this? Any Ideas?
Update:
I read up on some of the post. It looks like I need to set isolation level for the transaction. But even after adding it doesn't seem to work. Here is how I tried to inplement it:
using (ITransaction tranx = session.BeginTransaction(IsolationLevel.ReadUncommitted))
{
saveDocument();
}
something I don't understand in your code is where you get your nHibernate session.
Indeed you use
new ManagerFactory().GetCandidateAttachmentManager();
and
using (ICandidateAttachmentManager CandidateAttachmentManager = new ManagerFactory().GetCandidateAttachmentManager())
so your ManagerFactory class provides you the ISession ?
then you do:
CandidateAttachment attach = new CandidateAttachment();
attach = checkCV();
but
checkCV() returns either a null or a string ?
Finally you should never do
Save()
but instead
SaveOrUpdate()
Hope that helps you resolving your issue.
Feel free to give more details

EntityFramework6 with WPF update

I have a EF6 data context that I'm manually binding to a form with the method below.
private void GetJob(int i)
{
var context = new APIntegrationEntities();
var jb = context.Jobs.Find(i);
//tJobName.AppendText(jb.JobName.ToString());
tId.Text = jb.Id.ToString();
tJobName.Text = jb.JobName;
tSourceQuery.Text = jb.SourceQuery;
tAPI.Text = jb.API;
tConnectionString.Text = jb.ConnectionString;
tSheetName.Text = jb.SheetName;
tVersion.Text = jb.VersionName;
}
I'm trying to update with the following :
private void bSave_Click(object sender, RoutedEventArgs e)
{
var context = new APIntegrationEntities();
var jb = context.Jobs.Find(Int32.Parse(tId.Text));
jb.JobName = tJobName.Text;
jb.SheetName = tSheetName.Text;
jb.SourceQuery = tSourceQuery.Text;
jb.ConnectionString = tConnectionString.Text;
jb.VersionName = tVersion.Text;
jb.Id = Int32.Parse(tId.Text);
jb.API = null;
context.SaveChanges();
}
But I get an exception :
System.Data.Entity.Validation.DbEntityValidationException was unhandled
HResult=-2146232032
Message=Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
Source=EntityFramework
Am I using the EF correctly? Is there a better way to bind the context to the form and process the updates?
You are using EF technically correctly but not very good from design point of view.
Exception that you have got means that you are trying to pass in job entity some illegal from database point of view data (for example DateTime that doesn't fit in datetime DB type, null in non-null column, string with length that exceeds maxlength etc.).
So you need to see exception details and figure out what particular property causes a problem and correct the the data you are passing in it.

Unable to save data to Entity Model Database using saveChanges() method

I am trying to save data to my database. What I want is that when the button is pressed, data is saved to the database permanently. I've done tests where code is saved while the application is running. The saved data is viewable. But when I terminate the application, the data is not present when I view the data for that table in visual studio. I've provided the code that I am using for testing.
private void btn_otrFun_Click(object sender, EventArgs e)
{
tblCheese cheese = new tblCheese();
string cheesename = "TestCheese";
cheese.CheeseName = cheesename;
cheese.CheeseGroup = 1;
cheeseEntity.tblCheese.AddObject(cheese);
cheeseEntity.SaveChanges();
}
Here is where I am getting the context form. It is instantiated at the beginnning of the form.
private CheeseWorld_DatabaseEntities cheeseEntity = new CheeseWorld_DatabaseEntities(); //instanciate new database entities
And further I am using this snippet to retrieve data from the the database to dynamically created buttons.
var cheeselist = cheeseEntity.ExecuteStoreQuery<tblCheese>("Select * FROM tblCheese WHERE cheeseGroup = 1", null).ToList();
Hope these further details help. If more are required, let me know.
You've departed from the normal pattern we usually use for this... maybe try putting it back to something like this... (I don't see where you are getting the context)
using (var context = new cheeseEntity()) {
tblCheese cheese = new tblCheese();
cheese.CheeseName = "TestCheese";
cheese.CheeseGroup = 1;
context.tblCheese.Add(cheese);
context.SaveChanges();
}
This is covered in the documentation: http://msdn.microsoft.com/en-us/data/jj593489
(Pay attention to the bottom where it shows how to trace the generated SQL)
NOTE: I am using Add instead of AddObject.

The EntityKey property can only be set when the current value of the property is null

i'm trying to execute an EF update in the following manner but continue to receive this error:
The EntityKey property can only be set when the current value of the property is null.
using (hydraEntities db = new hydraEntities())
{
YouUser = db.youusers.Include("address").Include("entity").Include("youusercontacts.contact").Include("youuserlogins").Include("youusernotes.note").Include("youusernotes.youuser.entity").Where( yu => yu.YOUUserId.Equals(YOUUserId)).First();
}
YouUser.entity.FirstName = txtFirstName.Text;
YouUser.entity.LastName = txtLastName.Text;
YouUser.address.AddressLine1 = txtAddressLine1.Text;
YouUser.address.AddressLine2 = txtAddressLine2.Text;
YouUser.address.City = txtCity.Text;
YouUser.address.State = ddlState.SelectedValue;
YouUser.address.Zipcode = txtZipcode.Text;
using (hydraEntities db = new hydraEntities())
{
db.youusers.AddObject(YouUser);
db.ObjectStateManager.ChangeObjectState(YouUser, System.Data.EntityState.Modified);
db.SaveChanges();
}
Would greatly appreciate any insight on how I can fix this and execute the statement above.
Don't use AddObject in this scenario. It is for inserting a new entity but you are updating existing one. Use Attach instead:
using (hydraEntities db = new hydraEntities())
{
db.youusers.Attach(YouUser);
db.ObjectStateManager.ChangeObjectState(YouUser, System.Data.EntityState.Modified);
db.SaveChanges();
}
In my scenario I was adding objects several times at once through different threads. I had to lock the Model Container object when doing this, to make sure only one object would be processed at once.

Categories

Resources