Using Linq with SQLite: Table recognized but "Results View" gives error - c#

I'm trying to work with SQLITE in .
However I've faced a weird problem :
// Start of code
connection = new SQLiteConnection(myConnectionString);
connection.Open();
myDataContext = new Main(connection, new SqliteVendor());
// End of code
Examing 'myDataContext' after execution (with debugger), I see it has the type 'Main' (as should be :)) and also has as members,
the names of the tables I've defind in DB (so far - so good...), but...
Trying open one table (which has(!) records), and then trying to open the "ResultView" member of that table, I'm facing the string
"SQLite error\n No such table: main:XXXX"
(XXXX is the table name...)
(I've came to examine the structure because when I've tried to fetch records by linq command - I've got an exception.)
Do you have any idea what can cause this behavior?
Thanks,
Rivka

Ok, I've found the source of it...
(actually found it several hours after I've published the question...)
I'm working with visual studio and my DB file name is part of the project.
Since I've changed the (name and content...) of th db filename, i've forgot to mark
it "Copy Always"... That has caused the problem.
Please mark that as solved...

Related

Error even after changing datatype in both dataset and SQL Server Management Studio

I have a database and then a dataset in C# Visual Studio. In the database there is a table with a column called CardType. This was created by someone before me. And the value in this column is always 40. So he created it of type double.
I was told now that now the value has to be changed to SAR40 and not just 40. So now it is a string. So when I changed the value to SAR40 obviously there will be error when trying to add SAR40 to a column of type double. So first I went to SQL Server Management Studio and changed the type to nvarchar there. Then I come back to Visual Studio and changed the type of datatype of CardType to System.String.
Then when I run the program I still get an error
Parameter value could not be converted from string to double.
FormatException: The input string is in the wrong format.
How the program works is there are a bunch of small sections to fill data and each of the data goes into the database. Data like cardtype, hardwarerevision etc. And from this it will form a workrow.
workRow["CardType"] = type.Text;
workRow["Hardwarerevision"] = hw.Text;
and then finally add to the database using these two lines
//add new data row
ds.UNIO_CPU.Rows.Add(workRow);
//write data to database
DataGridAdapter_CPU.Update(workRow);
So why do I still get an error?
I try to run the program with just 40 and the program is showing no error. It works fine. How is that possible. Because I changed both in the SQL Server Management Studio and dataset in Visual Studio to string type. So here it should show error. But it is not showing error. Whereas I try to enter SAR40 then it is showing error that you cant convert string to double. What could be the error reason? Kindly help me. Thank you.
It is not clear what are the nature of the objects from your post. Also, it is not obvious where exception happens. From your sample, is it OK on string
ds.UNIO_CPU.Rows.Add(workRow);
And fails on
DataGridAdapter_CPU.Update(workRow);
Right?
And can you provide more details about DataGridAdapter_CPU?
In addition, DataSet contains DataTable with its own structure, did you check it?

2013 C# connection to PowerPivot DataModel

This article Connecting to PowerPivot with C# is the closest to my question but it seems that it is out of date. I attempted the methods they showed in the answer but the example
ThisWorkbook.Connections["PowerPivot Data"].OLEDBConnection.ADOConnection
Does not return the connection information, rather an exception.
But I was able to access the PP Data Model using:
ThisAddIn.Current.Application.ActiveWorkbook.Connections[1]. ModelTables[1].ModelTableColumns[1].Name`
But the object only allows you to look at the column names in the model. I wasn't able to get the connection information or anything.
ThisAddIn.Current.Application.ActiveWorkbook.Connections[1].ModelConnection.ADOConnection`
causes an exception and so does:
ThisAddIn.Current.Application.ActiveWorkbook.Connections[1].OLEDBConnection.ADOConnection
MY QUESTIONS
Have I made a mistake in my code?
Is there another method to connect to the datamodel that I haven't listed above?
Is it possible to read the records in the datamodel? (I was able to read column names)
Thank you for your time!
string ConnString = "Provider=MSOLAP;Data Source=$Embedded$;
Locale Identifier=1033;Location=" + ThisAddIn.Current.Application.ActiveWorkbook.FullName + ";SQLQueryMode=DataKeys";
Microsoft.AnalysisServices.Server OlapServer = new Microsoft.AnalysisServices.Server();
OlapServer.Connect(ConnString);

Sequence contains no elements... Thing is, I know it should

Background:
Using C# in the ASP.Net code-behind to call a SQL stored procedure via LINQ-to-Entities.
Also, please note that I am a complete newbie to all of this.
Problem:
I'm calling a stored procedure to get the max_length of a column in my database.
It keeps returning "Sequence Contains No Elements" when utilizing .First() and (alternately) the default when using .FirstOrDefault().
The problem is, I know it should be returning the number "4500" as I've run the query in SQL to see what should be there.
Any ideas on why it would be doing this?
I've searched high and low, but I can't find anyone else who has had this problem where they know it should be returning a value.
Code:
short? `shorty = db.sp_GetMaxLength("ApplicantEssay").First();`
The result of the SQL query used in the stored procedure:
Thanks so much for any assistance you can provide!!
Edit:
The only other code involved is the ADO.Net Entity auto-generated code.
At least, it's the only other code that the program steps through when I tried to examine what was going on.
I had a hard time looking at the return and trying to figure it out, but obviously it's returning nothing):
public virtual ObjectResult<Nullable<short>> sp_GetMaxLength(string cOLUMN_NAME)
{
var cOLUMN_NAMEParameter = cOLUMN_NAME != null ?
new ObjectParameter("COLUMN_NAME", cOLUMN_NAME) :
new ObjectParameter("COLUMN_NAME", typeof(string));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<Nullable<short>>("sp_GetMaxLength", cOLUMN_NAMEParameter);
}
Edit #2: I guess I should close this question out.
I messed around with some stuff in sql, then put it back to what I had in the first place and re-executed the stored procedure. Following that, I deleted the Entity Model, reset web.config to its original state pre-model, closed Visual studio, re-opened Visual Studio, and then re-added an ADO.Net Entity Model to the project. I then re-ran the code, stepped through it, and then all of a sudden, "4500" popped up as the returned value.
I am completely flummoxed, since all the code is exactly the same without changes, but I guess that's the power of scrapping and re-starting??? No other explanation, though I hate when it's as simple as that. :-(
Thanks to all who commented. :-)

RavenDB namespace change on document object throws "Unable to cast object" Error

So I am just trying to get RavenDB up and running and I have struggled with several issues but finally got it working. I was able to successfully insert and pull records for display.
However, I decided to move the class I was using to generate documents from to another spot which cause a namespace change. I ran ran everything and I can still insert documents to Raven. But when I try to pull them for display purposes I get the following error:
Unable to cast object of type 'Library.Logging.RewardProviderLog' to type 'Admin.ViewModels.ImportMonitorViewModel'.
So after going through all of the other posts I could find online it seems that the issue has something to do with the Raven-Clr-Type that essentially tracks the namespace information of the object you are saving as a document.
Ok. So I went in and deleted all the documents I created since I am still just testing and trying to get things running. I even went ahead and blew away the index and recreated it. I ran my process of inserting a new log. But I still get the same error message when I try to pull them and display them.
Note: ViewModels.ImportMonitorViewModel and Library.Logging.RewardProviderLog are identical. They contain the exact same properties.
Update
Index (named ImportMonitorLogs):
from doc in docs.RewardProviderLogs
select new {doc.status, doc.newItemsCount, doc.additionalInfo, doc.lastRun};
Query:
DocumentStore RavenDBStore = new Raven.Client.Document.DocumentStore { Url = "myurl" };
RavenDBStore.DefaultDatabase = "yei-logs";
RavenDBStore.Initialize();Raven.Client.Indexes.IndexCreation.CreateIndexes(System.Reflection.Assembly.GetCallingAssembly(), RavenDBStore);
using(var session = RavenDBStore.OpenSession())
{
model = (from log in session.Query<ViewModels.ImportMonitorViewModel>("ImportMonitorLogs")
orderby log.lastRun descending
select log).ToList();
}
Putting aside the rename and what might have worked before, the error matches the query you are attempting. You are indexing documents of type RewardProviderLog, and retrieving them directly as type ImportMonitorViewModel.
You say all of the properties are the same in both classes, but that alone won't get RavenDB to duck-type them for you. You have to be a little more explicit. This will probably work:
model = (from log in session.Query<RewardProviderLog>("ImportMonitorLogs")
orderby log.lastRun descending
select log).As<ViewModels.ImportMonitorViewModel>().ToList();
Or if you want slightly cleaner syntax (IMHO), this is equivalent:
model = session.Query<RewardProviderLog>("ImportMonitorLogs")
.OrderByDescending(x=> x.lastRun)
.As<ViewModels.ImportMonitorViewModel>()
.ToList();
The key here is that you are querying based on the type that matches the entity your index is returning, and that you use the As method to duck-type it into your view model. (This is the same thing as OfType<T>, and you can read more in the docs here).
If you want to get a bit fancier and project different fields or project from the index directly, you can look at AsProjection in the docs here.
If you're still scratching your head as to why this worked before, I can see that it might have worked if your viewmodel an entity were named the same thing - even if they were from different namespaces. They would still have the same Raven-Entity-Name metadata value.

DataTableReader is invalid for current DataTable 'TempTable' [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm getting the following error whenever my code creates a DataTableReader from a valid DataTable Object:
"DataTableReader is invalid for current DataTable 'TempTable'."
The thing is, if I reboot my machine, it works fine for an undetermined amount of time, then dies with the above. The code that throws this error could have been working fine for hours and then: bang. you get this error.
It's not limited to one line either; it's every single location that a DataTableReader is used. Also, this error does NOT occur on the production web server - ever.
This has been driving me nuts for the best part of a week, and I've failed to find anything on Google that could help (as I'm pretty positive this isn't a coding issue).
Some technical info:
DEV Box:
Vista 32bit (with all current windows updates)
Visual Studio 2008 v9.0.30729.1 SP
dotNet Framework 3.5 SP1
SQL Server:
Microsoft SQL Server 2005 Standard Edition- 9.00.4035.00 (X64)
Windows 2003 64bit (with all current windows updates)
Web Server:
Windows 2003 64bit (with all current windows updates)
Any help, ideas, or advice would be greatly appreciated!
UPDATE 1:
Ok - Have tried the following now with no success:
1: Rebooted
2: SFC / ScanNow
3: Changed SQL Servers
4: Tried a different method that uses DataTableReaders
5: Cleaned solution
The only thing I did find that worked was copy & pasting the code
from the main Visual studio instance, into another which had a simple console app.
This then worked as expected (queried database and got results into a dataTable, created a datatablereader on that table, then queried hasrows before calling .Read()...
All of which worked.
I am struggling to see what could cause this, as there are NO code faults - i'm 100% certain, as it runs perfectly when published to the webserver.
I think using the while(reader.read()) may solve your problem.
if (myReader.HasRows)
while (myReader.Read())
Console.WriteLine("\t{0}\t{1}", myReader.GetInt32(0), myReader.GetString(1));
else
Console.WriteLine("No rows returned.");
myReader.Close();
UPDATE:
Also from msdn:
The HasRows property returns information about the current result set. If the DataTableReader contains multiple result sets, you can examine the value of the HasRows property immediately after you call the NextResult method in order to determine whether the new result set contains rows.
Use the HasRows property to avoid the requirement to call the Read method of the DataTableReader if there are no rows within the current result set.
DataTableReader.HasRows Property
Had the same problem and got rid of it after clearing the variables in the watch window.
Clearing the watch window & doing rebuilds worked for me. However, because I had to remember to frequently rebuild, I eventually just renamed it also. (prior to renaming, adding additional watch variables on an object could cause previous watch variables on that object to become invalid -- even without progressing through the code, ie staying on the same line)
Wrap usage of DataTableReader (and all IDisposables) with using.
OK.. Further down in the code, I have the following code:
using (DataTableReader tr = dtCustomers.CreateDataReader())
{
....
}
If I change this to read:
using (DataTableReader tr2 = dtCustomers.CreateDataReader())
{
....
}
Then, and remember this bit of code is much later down in the same procedure, BOTH bits of code work without fault!
So, this doesn't work:
using (DataTableReader tr = dt.CreateDataReader())
{
...
}
....
using (DataTableReader tr = dt.CreateDataReader())
{
...
}
But this does:
using (DataTableReader tr = dt.CreateDataReader())
{
...
}
....
using (DataTableReader tr2 = dt.CreateDataReader())
{
...
}
I don't understand why this way works, but it does and as I've not had another answer, I'll be going with this.
If you know why this works, and why the original doesn't, please can you enlighten me? :)
Just thought I would post on here in case it's helps someone else. I tried a number of things and in the end i simply changed the name of the datareader and it worked, kind of similar to here. i dont know why for sure but i think it might be because the datareader (originally) wasnt being closed, so maybe after a few times debugging, there was lots of "stuff" in memory with a certain name attached and it said "no more!". still, i could be talking bullpies. my advice, change the name of your datareader variable and make sure you close it after you use it
Seems like a bug on getting the tableReader... i have code that has been working for ears and if i change another method sometimes i get that errro... some times it's solved just recompiling (rebuild), another times i reinstalled the .NET framework or use the option repair of it... i am starting to put try catch sections to use the reader if the system "wants" to givme the reader and the DataTable if not.
Greetings.

Categories