I have a problem running an insert query via C# OleDbCommand to an Access backend table. The SQL runs fine if you copy it and run it directly in Access, and it works fine for other data prior to hitting this particular entry.
I have tried altering the data, with no success. The source for this is an XML file. The XML data is being loaded correctly.
The command that is failing is the dbCommand.ExecuteNonQuery() with the error "Syntax error in INSERT INTO statement".
dbCommand = new OleDbCommand(string.Format(INSERT_RECURRING, tableName, fieldList, valueList), dbCon);
dbCommand.ExecuteNonQuery();
The SQL that is trying to run and failing is below. Note that table and field names are generated from an XML source file, hence the capitalisation and underscoring.
INSERT INTO LIST_CONTACTSGP (RID, CONTACT_TYPE, SURNAME_OR_FAMILY_NAME, GIVEN_NAMES, ORGANISATION, ADDRESS_GP, PHONE, MOBILE, WORK, FAX, EMAIL, COMMENTS) VALUES ('1-8HZAZN', 'Daughter, Other Emergency Contact', 'Smith', 'Ms Jenny', '', '', '49123456', '0416123456', '', '', '', '');
As I mentioned earlier, this SQL runs without fail from within Access, and other insert commands work fine (on other tables) prior to this failure. I strip out all SQL Special characters that may cause issues.
Any help would be greatly appreciated.
As requested, copy of the Stack Trace:
System.Data.OleDb.OleDbException was unhandled
Message=Syntax error in INSERT INTO statement.
Source=Microsoft Office Access Database Engine
ErrorCode=-2147217900
StackTrace:
at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr)
at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method)
at System.Data.OleDb.OleDbCommand.ExecuteNonQuery()
at CCAPXMLImport.CXIDatabase.insertRepeatedSection(Dictionary`2 ReferralData, String ReferralID) in C:\SMNS-local\Development\TeleHealth\CCAPXMLImport\CCAPXMLImport\CCAPXMLImport\CXIDatabase.cs:line 279
at CCAPXMLImport.frmMain.btnBrowse_Click(Object sender, EventArgs e) in C:\SMNS-local\Development\TeleHealth\CCAPXMLImport\CCAPXMLImport\CCAPXMLImport\frmMain.cs:line 131
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at CCAPXMLImport.Program.Main() in C:\SMNS-local\Development\TeleHealth\CCAPXMLImport\CCAPXMLImport\CCAPXMLImport\Program.cs:line 18
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
OK, I have an answer (thanks to ralf.w). Big thanks also go to AVD and Remou for for taking the time to help with this issue.
The column names needed to be encapsulated in square brackets. Despite working fine with other tables and directly in Access, when sending it through the OleDbCommand, one (or more) of the column names must have been causing an issue.
So the SQL Code should be:
string sql="INSERT INTO LIST_CONTACTSGP ([RID], [CONTACT_TYPE], [SURNAME_OR_FAMILY_NAME],
[GIVEN_NAMES], [ORGANISATION], [ADDRESS_GP], [PHONE], [MOBILE], [WORK], [FAX], [EMAIL],
[COMMENTS]) VALUES (#RID, #CONTACT_TYPE, #SURNAME_OR_FAMILY_NAME,
#GIVEN_NAMES, #ORGANISATION, #ADDRESS_GP, #PHONE, #MOBILE, #WORK, #FAX,
#EMAIL, #COMMENTS)";
Use parameters instead of string concatenation.
string sql="INSERT INTO LIST_CONTACTSGP (RID, CONTACT_TYPE, SURNAME_OR_FAMILY_NAME,
GIVEN_NAMES, ORGANISATION, ADDRESS_GP, PHONE, MOBILE, WORK, FAX, EMAIL,
COMMENTS) VALUES (#RID, #CONTACT_TYPE, #SURNAME_OR_FAMILY_NAME,
#GIVEN_NAMES, #ORGANISATION, #ADDRESS_GP, #PHONE, #MOBILE, #WORK, #FAX,
#EMAIL, #COMMENTS)";
using(OleDbCommand dbCommand = new OleDbCommand(sql,conn))
{
dbCommand.Parameters.Add("#RID",OleDbType.VarChar,20).Value="10";
dbCommand.Parameters.Add("#CONTACT_TYPE",OleDbType.VarChar,20).Value="Somethig";
.....
conn.Open();
dbCommand.ExecuteNonQuery();
conn.Close();
}
Related
I am creating a new sheet in Smartsheet via the API in Visual Studio 2015 C#.
I have followed the code/API Guide from Smartsheet but i get an error at run time when the code fires.
The error is as follows:
Smartsheet.Api.ResourceNotFoundException was unhandled
HResult=-2146233088
Message=Not Found
Source=smartsheet-csharp-sdk
StackTrace:
at Smartsheet.Api.Internal.AbstractResources.HandleError(HttpResponse response)
at Smartsheet.Api.Internal.AbstractResources.CreateResource[T](String path, Type objectClass, T object)
at Smartsheet.Api.Internal.FolderSheetResourcesImpl.CreateSheet(Int64 folderId, Sheet sheet)
at Aviva_Order_Systems.avivaorders.button1_Click(Object sender, EventArgs e) in C:\Dropbox\AL DB\Dropbox\Aviva\Order Project\Aviva Order Systems\avivaorders.cs:line 372
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at Aviva_Order_Systems.Program.Main() in C:\Dropbox\AL DB\Dropbox\Aviva\Order Project\Aviva Order Systems\Program.cs:line 18
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
"
This section of the code is what is being highlight when i attempt to debug the error.
Sheet newSheet = ssproj.FolderResources.SheetResources.CreateSheet(
#####, // long folderId
new Sheet
{
Name = "OrderProfile",
Columns = new Column[] { CCnum, CCName, Project, Supplier, SEQ }
}
);
Note i have changed the #### on purpose. It is giving the error here:
Sheet newSheet = ssproj.FolderResources.SheetResources.CreateSheet(
#####, // long folderId
new Sheet
{
Name = "OrderProfile",
Columns = new Column[] { CCnum, CCName, Project, Supplier, SEQ }
}
);
Any ideas on what is causing this? I have tried searching
Looks like you're trying to create the sheet in the specified folder. Based on the error you're getting, I'd suspect that the folder ID that you're specifying isn't valid.
To troubleshoot, you can verify whether the folder ID is valid by trying to execute a Get Folder request with that ID. If the ID is valid, the Get Folder request will succeed; if it's invalid, the request will fail. The following C# code example attempts to retrieve folder with ID = 7116448184199044.
Folder folder = smartsheet.FolderResources.GetFolder(
7116448184199044, // long folderId
null // IEnumerable<FolderInclusion> include
);
UPDATE (in response to your comment)
If you want to create the sheet in a folder and that folder happens to be located within a shared workspace, the API call you're using (Create Sheet in Folder) should work. If you're getting the "resource not found" error in response to this API request, then either the folder ID you're specifying is invalid OR the account that owns the API access token you're using to issue the API request doesn't have access to that folder/workspace. As described previously, you can verify that the folder ID is valid (and that the account that owns the API access token does have access to the folder) by confirming that you're able to successfully issue a Get Folder API request for that folder.
If you want to create the sheet at the root of the shared workspace (i.e., not inside a folder, but rather, at the root level of the workspace), you'll need to use the Create Sheet in Workspace API request to do so (specifying the ID of the workspace). The account that owns the API access token used to issue the API request must have access to the workspace in order for this call to succeed.
I am currently working on a project in which I need to use FP-Growth algorithm. I know Weka is a handy tool for it. However, I am using C# for coding (due to some other libraries I need). So, I converted weka.jar to weka.dll using IKVM.NET. Below is a code snippet that i have written:
FPGrowth FPMiner = new FPGrowth();
FPMiner.buildAssociations(dataset);
AssociationRules rules = FPMiner.getAssociationRules();
List<AssociationRule> rule = rules.getRules();
This gives me an error as:
Cannot implicitly convert type 'java.util.List' to
'System.Collections.Generic.List'.
An explicit conversion exists (are you missing a cast?)
So, I added a cast to the last line as:
List<AssociationRule> rule = (System.Collections.Generic.List<AssociationRule>)rules.getRules();
The error goes away but I get an exception when I run my code, saying:
System.InvalidCastException was unhandled Message=Unable to cast
object of type 'java.util.ArrayList' to type
System.Collections.Generic.List`1[weka.associations.AssociationRule]'.
Source=WindowsFormsApplication1
The stacktrace goes as:
StackTrace:
at DetectGroup.Form1.GenerateARFF() in C:\Users\user\Documents\Visual Studio 2010\Projects\DetectGroup\DetectGroup\Form1.cs:line 279
at DetectGroup.Form1.findNearestNeighbours() in C:\Users\user\Documents\Visual Studio 2010\Projects\DetectGroup\DetectGroup\Form1.cs:line 236
at DetectGroup.Form1.findSelectedTraj() in C:\Users\user\Documents\Visual Studio 2010\Projects\DetectGroup\DetectGroup\Form1.cs:line 165
at DetectGroup.Form1.button2_Click(Object sender, EventArgs e) in C:\Users\user\Documents\Visual Studio 2010\Projects\DetectGroup\DetectGroup\Form1.cs:line 404
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at DetectGroup.Program.Main() in C:\Users\user\Documents\Visual Studio 2010\Projects\DetectGroup\DetectGroup\Program.cs:line 18
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart() InnerException:
I am unable to figure out what to do now. I have tried searching stuff but haven't yet got the solution. I understand that the error is because getRules() returns java.util.List while I am trying to use it as System.Collections.Generic.List. What can I do to avoid it? Any help would be great!
Also, is there any data mining library (like Weka) available in C#?
Thank you!
I am answering my own question. I used this link to solve the problem I was facing. Thanks #SecretSquirrel(see the comments) and #Jon Iles (see the answer I've linked).
This is my first attempt trying to access db files from the server. If run the program locally there are no problems
I stored ms access files on the server and I trying to run the program from my laptop and I am recieving the following error....
System.Data.OleDb.OleDbException was unhandled is not a valid path. Make sure that the path
name is spelled correctly and that you are connected to the server on which the file resides.
My connection string looks something like this...
myCon = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=H:\name-SERVER\SHAREDFILES\FileRDB.mdb; Jet OLEDB:System Database=system.mdw");
There has username and password for the server. Should I include this in the connection string?
Stacktrace looks like this...
System.Data.OleDb.OleDbException was unhandled
is not a valid path. Make sure that the path name is spelled correctly and that you are connected to the server on which the file resides.
Source=Microsoft JET Database Engine
ErrorCode=-2147467259
StackTrace:
at System.Data.OleDb.OleDbConnectionInternal..ctor(OleDbConnectionString constr, OleDbConnection connection)
at System.Data.OleDb.OleDbConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup)
at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
at System.Data.OleDb.OleDbConnection.Open()
at MALHRManagementSystem.FrmLogin.btnLogin_Click(Object sender, EventArgs e) in C:\Users\username\Desktop\Project\foldername\foldername\foldername\Form.cs:line 40
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at somefilename.Program.Main() in C:\Users\username\Desktop\Project\foldername\foldername\foldername\Program.cs:line 18
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
Please can someone advise me how do I correct this problem.
Thanks in advance
I am not sure what tag I should use for this thread but please correct it if I am wrong here.
db is MS-Access 2003 and visual studio 2010
This is working now. To have a mapped network drive on vista/ Windows 7. Right click on My Computer > Map Network Drive > Select a drive > Click on Browse button . A menu appears as Browse For Folder -- Select a shared network folder. Then choose the network name and the folder. Once you have done that Click OK. That is all you have to do. Here are some useful links on howto if anyone is interested...
here
here
Vista
Caveat: I am new to C# and SQL (less than 2 months with C# and 6 months with SQL)
I have been working on this for a few days, and I am beginning to think I am asking the impossible.
I have two local databases. The first is a Temp database that receives data from a third party. This data is in XML format and does have duplicate records in it.
I insert the data into the Temp database and then would like to use INSERT INTO.. to move the unique records into the Final database.
I have created and tested the insert into sql and it works with no problems. Here is an example:
INSERT INTO Final.dbo.R_DATA
(C1, C2,..)
SELECT distinct C1, C2, ...
FROM Temp.dbo.R_DATA
WHERE NOT EXISTS(Select *
FROM Final.dbo.R_DATA
WHERE (R_DATA.C1=Final.dbo.R_DATA.C1))
This works. I have even tried creating a Synonym for Final.dbo.R_DATA, and replaced that in the query - again in SQL Express it also works.
I have also set both queries (with and without the Synonym, as stored procedures, and again they both work from within SQL Express.
I then try to run the same query from C#- using the following.
string sqlConnStr = #"DataSource=.\SQLEXPRESS;AttachDbFilename=W:\SQL\**Temp.mdf;Integrated Security=True;Connect Timeout=120;User Instance=True";
FileInfo SQLfile = new FileInfo(#"W:\SQL\MOVETEST.sql");
MOVETEST is the sql script I am trying - I converted the above query into a procedure and then placed the procedure in the sql
string script = SQLfile.OpenText().ReadToEnd();
SqlConnection connection = new SqlConnection(sqlConnStr);
connection.Open();
Server server = new Server(new ServerConnection(connection));
I am running this from a form - for testing it is on a button click but I would like it to be part of a longer procedure when / if I get it working. This is for me to see that the connection is open
StatusMessage.AppendText(connection.ServerVersion + " " + connection.State);
server.ConnectionContext.ExecuteNonQuery(script);
connection.Close();
It is at the server.ConnectionContect.ExecuteNonQuery(script); that the error happens - no matter what I try I get an Invalid Object error. I am thinking that there is no way to insert data from a table in one db to another, or am I missing something.
I think I could make this work by:
extract distinct rows from the Temp.R_DATA to a new tempR_DATA
table in that Temp db.
use bulkcopy to move the whole TempR_DATA
table to the dbo.FINAL
connect to the dbo.Final and run a query
there to insert from the FINAL.dbo.temp.R_DATA into FINAL.dbo.R_DATA
(using where not exists).
But I would realy like to avoid all of those read and writes, as something tells me it would be slow.
So what am I overlooking?
Any and all comments are welcome, I have a feeling that this is an issue of concept (how I am trying to do this) rather than syntax etc.
Conrad asked about the exact error:
System.Data.SqlClient.SqlException was unhandled Message=Invalid object name '**Final.dbo.RELEASE_DATA'. Source=.Net SqlClient Data Provider ErrorCode=-2146232060 Class=16 LineNumber=3 Number=208 Procedure=MoveRELEASE_DATA Server=\\.\pipe\37E36041-6FB1-4D\tsql\query State=1 StackTrace:
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at DataLoader.Imports.button2_Click(Object sender, EventArgs e) in c:\mydocs\visual studio 2010\Projects\PathFinder\PathFinder\Imports.cs:line 363
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at DataLoader.Program.Main() in c:\mydocs\visual studio 2010\Projects\PathFinder\PathFinder\Program.cs:line 18
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.Runtime.Hosting.ManifestRunner.Run(Boolean checkAptModel)
at System.Runtime.Hosting.ManifestRunner.ExecuteAsAssembly()
at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext, String[] activationCustomData)
at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext)
at System.Activator.CreateInstance(ActivationContext activationContext)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart() InnerException:
Here is the error message - same - Invalid Object, I get this whenever I am trying to do the insert across databases.
Thank you.
This code should work:
using (SqlConnection connection = new SqlConnection("DataSource=..."))
using (SqlComamnd command = connection.CreateCommand())
{
command.CommandText = "INSERT INTO ...";
connection.Open();
int i = command.ExecuteNonQuery(); // number of rows inserted
}
Also I recommend to wrap the query within a stored procedure.
I am doing college project. In that, they want a bonafide certificate. For that, I planned to pass TextBox string to report.
I googled for passing parameter in a winform. Then I got this step by step process. I implement that.
Step:
1: In Visual Studio 2010, open your
.rdlc file, and open “Report Data”
window (If you can not see this
window, go to View menu to open it);
2: Right click the “Parameters” node,
and add a new Parameter, ie: named it
“content“;
3: In your .rdlc file, add a textbox,
named it tbContent, and set its filed
express to :
=Parameters!content.Value
4: Go to your Form file which include
your reporterview control, and add the
following code:
this.reportViewer1.LocalReport.ReportEmbeddedResource
= “TestReport.Report1.rdlc”;
ReportParameter rp = new ReportParameter(“content”,
this.textBox1.Text);
this.reportViewer1.LocalReport.SetParameters(new
ReportParameter[] { rp });
this.reportViewer1.RefreshReport();
5: then you can pass the parameter
from the TextBox on the form to .rdlc
file;
I added using Microsoft.Reporting.WinForms; assembly reference.
this.reportViewer1.LocalReport.ReportEmbeddedResource = "Report1.rdlc";
ReportParameter rp = new ReportParameter("content", this.textBox1.Text);
this.reportViewer1.LocalReport.SetParameters(new ReportParameter[] { rp });
this.reportViewer1.RefreshReport();
But it throws the exception:
Local processing Exception was
unhandled at
this.reportViewer1.LocalReport.SetParameters(new
ReportParameter[] { rp });
line.
Here's the full error from the clipboard:
Microsoft.Reporting.WinForms.LocalProcessingException was unhandled
Message=An error occurred during local report processing.
Source=Microsoft.ReportViewer.WinForms
StackTrace:
at Microsoft.Reporting.WinForms.LocalReport.EnsureExecutionSession()
at Microsoft.Reporting.WinForms.LocalReport.SetParameters(IEnumerable`1 parameters)
at Report.Form1.Form1_Load(Object sender, EventArgs e) in D:\Jagadeeswaran\Project\Report\Report\Form1.cs:line 38
at System.Windows.Forms.Form.OnLoad(EventArgs e)
at System.Windows.Forms.Form.OnCreateControl()
at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
at System.Windows.Forms.Control.CreateControl()
at System.Windows.Forms.Control.WmShowWindow(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
at System.Windows.Forms.Form.WmShowWindow(Message& m)
at System.Windows.Forms.Form.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.SafeNativeMethods.ShowWindow(HandleRef hWnd, Int32 nCmdShow)
at System.Windows.Forms.Control.SetVisibleCore(Boolean value)
at System.Windows.Forms.Form.SetVisibleCore(Boolean value)
at System.Windows.Forms.Control.set_Visible(Boolean value)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at Report.Program.Main() in D:\Jagadeeswaran\Project\Report\Report\Program.cs:line 18
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.ApplicationException
Message=The report definition for report 'D:\Jagadeeswaran\Project\Report\Report\bin\Debug\~/Report1.rdlc' has not been specified
Source=Microsoft.ReportViewer.Common
StackTrace:
at Microsoft.Reporting.PreviewStore.GetCompiledReport(CatalogItemContextBase context, Boolean rebuild, Byte[]& reportDefinition, ControlSnapshot& snapshot)
at Microsoft.Reporting.LocalService.GetCompiledReport(CatalogItemContextBase itemContext, Boolean rebuild, ControlSnapshot& snapshot)
at Microsoft.Reporting.WinForms.LocalReport.EnsureExecutionSession()
InnerException: System.IO.DirectoryNotFoundException
Message=Could not find a part of the path 'D:\Jagadeeswaran\Project\Report\Report\bin\Debug\~\Report1.rdlc'.
Source=mscorlib
StackTrace:
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
at Microsoft.ReportingServices.StandalonePreviewStore.GetReportDefinition(ReportID reportId)
at Microsoft.Reporting.PreviewStore.GetCompiledReport(CatalogItemContextBase context, Boolean rebuild, Byte[]& reportDefinition, ControlSnapshot& snapshot)
InnerException:
Set this:
this.reportViewer1.ProcessingMode =
Microsoft.Reporting.WinForms.ProcessingMode.Local;
And change this:
this.reportViewer1.LocalReport.ReportEmbeddedResource = "Report1.rdlc"
to
this.reportViewer1.LocalReport.ReportPath = "Report1.rdlc";
Just in case that this would be the case, I had the same problem after I reorganized my project folders, thus changing the report file path. All I had to do is re-selecting the report in the ReportViewer's Choose Report ComboBox accessible from its upper-right corner.
also double check that you are spelling your rdlc filename correctly. For example, my report file was ReportName.rdlc but I had typed in this.reportViewer1.LocalReport.ReportPath = "ReportsName.rdlc";
You can use embedded just fine, just don't forget to include the name space in the RDLC path. The assembly namespace is required, as well as any possible sub namespaces you might have as the full namespace path to the report.
reportViewer1.LocalReport.ReportEmbeddedResource = "assemblyname.Report1.rdlc"
or
reportViewer1.LocalReport.ReportEmbeddedResource = "assemblyname.subnamespace.Report1.rdlc"
I have just run Install-Package Microsoft.SqlServer.Types in "NuGet Package Manager Console" and everything is working well.