NotImplementedException in Silverlight and IronPython - wpf

i'm hosting IronPython Scripts in one Silverlight Application and i want to run the script and get one System.Windows.Controls.TextBlock object.
so i use this ironPython code:
import clr
clr.AddReferenceByName("System.Windows.Controls, Version=2.0.5.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")
from System.Windows.Controls import *
tb = TextBlock()
i'm being able to add the reference, but, when i import System.Windows.Controls i get a System.NotImplementedException.
The same happens if i try with "import wpf"
i'm using Silverlight 4 and IronPython 2.7.1 beta2
and this is the code to run the script:
Dim engine = IronPython.Hosting.Python.CreateEngine
Dim scope = engine.CreateScope()
Dim source = engine.CreateScriptSourceFromString(CodeTB.Text)
source.Execute(scope)
ResultLB.Items.Add(scope.GetVariable("hello"))
If scope.ContainsVariable("tb") Then
GuiStack.Children.Add(scope.GetVariable("tb"))
End If
Here is the Stack Trace of the exception:
en Microsoft.Scripting.PlatformAdaptationLayer.FileExists(String path)
en IronPython.Runtime.Importer.LoadModuleFromSource(CodeContext context, String name, String path)
en IronPython.Runtime.Importer.LoadPackageFromSource(CodeContext context, String name, String path)
en IronPython.Runtime.Importer.LoadFromDisk(CodeContext context, String name, String fullName, String str)
en IronPython.Runtime.Importer.ImportFromPathHook(CodeContext context, String name, String fullName, List path, Func`5 defaultLoader)
en IronPython.Runtime.Importer.ImportFromPath(CodeContext context, String name, String fullName, List path)
en IronPython.Runtime.Importer.ImportTopAbsolute(CodeContext context, String name)
en IronPython.Runtime.Importer.ImportModule(CodeContext context, Object globals, String modName, Boolean bottom, Int32 level)
en IronPython.Modules.Builtin.__import__(CodeContext context, String name, Object globals, Object locals, Object fromlist, Int32 level)
en Microsoft.Scripting.Interpreter.FuncCallInstruction`7.Run(InterpretedFrame frame)
en Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
en Microsoft.Scripting.Interpreter.LightLambda.Run7[T0,T1,T2,T3,T4,T5,T6,TRet](T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6)
en IronPython.Runtime.Importer.ImportLightThrow(CodeContext context, String fullName, PythonTuple from, Int32 level)
en IronPython.Runtime.Importer.Import(CodeContext context, String fullName, PythonTuple from, Int32 level)
en IronPython.Runtime.Operations.PythonOps.ImportStar(CodeContext context, String fullName, Int32 level)
en Microsoft.Scripting.Interpreter.ActionCallInstruction`3.Run(InterpretedFrame frame)
en Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
en Microsoft.Scripting.Interpreter.LightLambda.Run2[T0,T1,TRet](T0 arg0, T1 arg1)
en IronPython.Compiler.PythonScriptCode.RunWorker(CodeContext ctx)
en IronPython.Compiler.PythonScriptCode.Run(Scope scope)
en IronPython.Compiler.RuntimeScriptCode.InvokeTarget(Scope scope)
en IronPython.Compiler.RuntimeScriptCode.Run(Scope scope)
en Microsoft.Scripting.SourceUnit.Execute(Scope scope, ErrorSink errorSink)
en Microsoft.Scripting.SourceUnit.Execute(Scope scope)
en Microsoft.Scripting.Hosting.ScriptSource.Execute(ScriptScope scope)
en TestApp2.MainPage.ExecuteButton_Click(Object sender, RoutedEventArgs e)
en System.Windows.Controls.Primitives.ButtonBase.OnClick()
en System.Windows.Controls.Button.OnClick()
en System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
en System.Windows.Controls.Control.OnMouseLeftButtonUp(Control ctrl, EventArgs e)
en MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, Int32 actualArgsTypeIndex, String eventName)
And here is the all the source code
Thankyou for everything :)

It should work without any AddReference:
import clr
from System.Windows.Controls import TextBlock
tb = TextBlock()

Thank You, Lukas, the article was very helpful, now the problem is fixed.
Here's my new source code
Dim setup As ScriptRuntimeSetup = Python.CreateRuntimeSetup(Nothing)
setup.HostType = GetType(Microsoft.Scripting.Silverlight.BrowserScriptHost)
Dim runtime As New ScriptRuntime(setup)
Dim engine = IronPython.Hosting.Python.GetEngine(runtime)
Dim scope = engine.CreateScope()
Dim uri As New Uri("System.Windows.Controls.dll", UriKind.Relative)
Dim sri As StreamResourceInfo = Application.GetResourceStream(uri)
Dim ap As New AssemblyPart
Dim asm As Assembly = ap.Load(sri.Stream)
runtime.LoadAssembly(asm)
Dim assamblies As String() = {"mscorlib", "System", "System.Windows", "System.Windows.Browser", "System.Net"}
For Each item In assamblies
runtime.LoadAssembly(runtime.Host.PlatformAdaptationLayer.LoadAssembly(item))
Next
Dim source = engine.CreateScriptSourceFromString(CodeTB.Text, Microsoft.Scripting.SourceCodeKind.Statements)
source.Execute(scope)
ResultLB.Items.Add(scope.GetVariable("hello"))
If scope.ContainsVariable("tb") Then
GuiStack.Children.Add(scope.GetVariable("tb"))
End If

Related

When executing code, I receive a System.InvalidOperationException: 'ExecuteReader:Connection property has not been initialized.' Error [duplicate]

This question already has answers here:
ExecuteNonQuery: Connection property has not been initialized.
(7 answers)
ExecuteNonQuery. connection property has not been initialized
(2 answers)
ExecuteReader: Connection property has not been initialized
(2 answers)
"ExecuteReader:Connection Property has not been initialized."
(4 answers)
Closed 6 months ago.
I am fairly new to VB and I am in the process of developing a program that can pull information from a specific database and display the information in a generated XML file.
Whenever the export button is clicked and processed, I receive the System.InvaildOperationExecption error specified above.
I will post an example of my code below, but for security purposes some information has to be left out as it is sensitive. I can say with the utmost certainty that this connection information is entered correctly. I will place stars in place of the sensitive information.
I feel I have correctly declared my variables properly in order for this to correctly connect to the database to pull information, but I still receive this error to no avail.
I will appreciate any advice given on this as I am fairly new to coding and utilizing Microsoft SQL database connections.
Below is my code.
Public Sub MakeExportButton_Click(sender As Object, e As EventArgs) Handles MakeExportButton.Click
Dim daDaysSince As Integer = 0
Dim itemNumber As Integer
Dim gotAtLeastOne As String = "N"
Dim MDBConnectString = "Persist Security Info=False;User ID=***;Password=******;Initial Catalog=***_****;Data Source=***.***.*.***;"
Dim dt As New DataTable("Customer")
dt.Columns.Add("Index")
dt.Columns.Add("CustomerNumber")
dt.Columns.Add("CustomerName")
Dim drow As DataRow
Dim cn As New SqlConnection
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
Dim daRowInfo As String
daRowInfo = ""
Dim DaysSincetemp As Integer = 0
DaysSincetemp = daDaysSince * -5
'Default yesterday, but can change time period.
'Dim yesterday As Date = Now.AddDays(-5)
Dim Daysbefore As Date = Now.AddDays(DaysSincetemp)
cn = New SqlConnection(MDBConnectString)
cmd = New SqlCommand("SELECT " &
"TM_Customer.CustomerNumber, " &
"TM_Customer.CustomerName ")
cn.Open()
dr = cmd.ExecuteReader
Dim today As Date = Now
Dim DasDate As Date
Dim ErrorDescription As String = ""
Dim IndexNumber As Integer = 0
While dr.Read
DasDate = dr("LastModifiedDatetime")
If DasDate >= Daysbefore Then
Dim DasErrorCode As String = ""
If IsDBNull(dr("ErrorFlag")) Then
DasErrorCode = "None"
Else
DasErrorCode = dr("ErrorFlag")
End If
IndexNumber = IndexNumber + 1
gotAtLeastOne = "Y"
itemNumber = itemNumber + 1
drow = dt.NewRow
drow("Index") = IndexNumber
drow("CustomerNumber") = dr("CustomerNumber")
drow("CustomerName") = dr("CustomerName")
dt.Rows.Add(drow)
daRowInfo = drow("Index") & ") *** Customer" & drow("Customer") & "-"
End If
End While
cn.Close()
If gotAtLeastOne = "Y" Then
dt.WriteXml("c:/temp/********_" + GetNowDateAndTime() + ".xml")
End If
End Sub
Here are error details posted as well.
System.InvalidOperationException
HResult=0x80131509
Message=ExecuteReader: Connection property has not been initialized.
Source=System.Data.SqlClient
StackTrace:
at System.Data.SqlClient.SqlCommand.ValidateCommand(Boolean async, String method)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.SqlClient.SqlCommand.ExecuteReader()
at *****_*_*******.Form1.MakeExportButton_Click(Object sender, EventArgs e) in C:\Users\****** ********\source\repos\***** * *******\***** * *******\Form1.vb:line 87
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.Callback(IntPtr hWnd, WM msg, IntPtr wparam, IntPtr lparam)

SQLBulkCopy with type mismatch exception and Datetime complaints about

I want to BULK Insert in a table with different types and a auto-increment column. The problem is, that i get the messagte it is not possible to convert from Int32 to Datetime.
This is my table Structure, the id is an auto-increment identity column.
in the first Method of this section, i create the DataTable with the types (is System.DateTime correct?). The second method in this section is the SQLBulkCopy.
public DataTable makeTherapyStatusTransitionTable()
// Create a new DataTable named NewProducts.
{
DataTable tstTable = new DataTable("therapystatustransition");
DataColumn therapy = new DataColumn();
therapy.DataType = System.Type.GetType("System.Int32");
therapy.ColumnName = "therapy";
tstTable.Columns.Add(therapy);
DataColumn minutes = new DataColumn();
minutes.DataType = System.Type.GetType("System.String");
minutes.ColumnName = "minutes";
tstTable.Columns.Add(minutes);
DataColumn seconds = new DataColumn();
seconds.DataType = System.Type.GetType("System.String");
seconds.ColumnName = "seconds";
tstTable.Columns.Add(seconds);
DataColumn time = new DataColumn();
time.DataType = System.Type.GetType("System.DateTime");
time.ColumnName = "time";
tstTable.Columns.Add(time);
DataColumn from_phase = new DataColumn();
from_phase.DataType = System.Type.GetType("System.Int32");
from_phase.ColumnName = "from_phase";
tstTable.Columns.Add(from_phase);
DataColumn to_phase = new DataColumn();
to_phase.DataType = System.Type.GetType("System.Int32");
to_phase.ColumnName = "to_phase";
tstTable.Columns.Add(to_phase);
return tstTable;
}
public string bulkTableTo(DataTable dataTable, string tabellenname)
{
// get your connection string
string connString = MyConfigurationManager.prdSqlServerString;
// connect to SQL
using (SqlConnection connection = new SqlConnection(connString))
{
// make sure to enable triggers
// more on triggers in next post
SqlBulkCopy bulkCopy = new SqlBulkCopy
(
connection,
SqlBulkCopyOptions.Default,
null
);
// set the destination table name
bulkCopy.DestinationTableName = tabellenname;
connection.Open();
// write the data in the "dataTable"
try
{
bulkCopy.WriteToServer(dataTable);
}
catch (Exception e)
{
return "Es ist ein Fehler aufgetreten. " +
"Stellen Sie sicher dass der Timeout im SQL Server " +
"auf unendlich steht und AutoClose für die Verbindung " +
"nicht aktiviert wurde. " + e.Message;
}
connection.Close();
}
// reset
dataTable.Clear();
return "ok";
}
The datatable is filled in a loop with this:
string[] phasenInfo = inputLine.Split(new Char[] { ' ' });
//string[] phasenRow = new string[] { Int32.Parse(therapy_id), phasenInfo[0], phasenInfo[1], UnixTimeStampToDateTime(Double.Parse(phasenInfo[2])).ToString(), phasenInfo[3], phasenInfo[4] };
DataRow row = historyTable.NewRow();
row["therapy"] = Int32.Parse(therapy_id);
row["minutes"] = phasenInfo[0];
row["seconds"] = phasenInfo[1];
row["time"] = UnixTimeStampToDateTime(Double.Parse(phasenInfo[2]));
row["from_phase"] = Int32.Parse(phasenInfo[3]);
row["to_phase"] = Int32.Parse(phasenInfo[4]);
historyTable.Rows.Add(row);
This is the errormessage i got:
{System.InvalidOperationException: Der angegebene Wert vom Typ Int32 aus der Datenquelle kann nicht in Typ datetime der angegebenen Zielspalte konvertiert werden. ---> System.InvalidCastException: Parameterwert konnte nicht von Int32 in DateTime umgewandelt werden. ---> System.InvalidCastException: Ungültige Umwandlung von "Int32" in "DateTime".
bei System.Int32.System.IConvertible.ToDateTime(IFormatProvider provider)
bei System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)
bei System.Data.SqlClient.SqlParameter.CoerceValue(Object value, MetaType destinationType, Boolean& coercedToDataFeed, Boolean& typeChanged, Boolean allowStreaming)
--- Ende der internen Ausnahmestapelüberwachung ---
bei System.Data.SqlClient.SqlParameter.CoerceValue(Object value, MetaType destinationType, Boolean& coercedToDataFeed, Boolean& typeChanged, Boolean allowStreaming)
bei System.Data.SqlClient.SqlBulkCopy.ConvertValue(Object value, _SqlMetaData metadata, Boolean isNull, Boolean& isSqlType, Boolean& coercedToDataFeed)
--- Ende der internen Ausnahmestapelüberwachung ---
bei System.Data.SqlClient.SqlBulkCopy.ConvertValue(Object value, _SqlMetaData metadata, Boolean isNull, Boolean& isSqlType, Boolean& coercedToDataFeed)
bei System.Data.SqlClient.SqlBulkCopy.ReadWriteColumnValueAsync(Int32 col)
bei System.Data.SqlClient.SqlBulkCopy.CopyColumnsAsync(Int32 col, TaskCompletionSource`1 source)
bei System.Data.SqlClient.SqlBulkCopy.CopyRowsAsync(Int32 rowsSoFar, Int32 totalRows, CancellationToken cts, TaskCompletionSource`1 source)
bei System.Data.SqlClient.SqlBulkCopy.CopyBatchesAsyncContinued(BulkCopySimpleResultSet internalResults, String updateBulkCommandText, CancellationToken cts, TaskCompletionSource`1 source)
bei System.Data.SqlClient.SqlBulkCopy.CopyBatchesAsync(BulkCopySimpleResultSet internalResults, String updateBulkCommandText, CancellationToken cts, TaskCompletionSource`1 source)
bei System.Data.SqlClient.SqlBulkCopy.WriteToServerInternalRestContinuedAsync(BulkCopySimpleResultSet internalResults, CancellationToken cts, TaskCompletionSource`1 source)
bei System.Data.SqlClient.SqlBulkCopy.WriteToServerInternalRestAsync(CancellationToken cts, TaskCompletionSource`1 source)
bei System.Data.SqlClient.SqlBulkCopy.WriteToServerInternalAsync(CancellationToken ctoken)
bei System.Data.SqlClient.SqlBulkCopy.WriteRowSourceToServerAsync(Int32 columnCount, CancellationToken ctoken)
bei System.Data.SqlClient.SqlBulkCopy.WriteToServer(DataTable table, DataRowState rowState)
bei System.Data.SqlClient.SqlBulkCopy.WriteToServer(DataTable table)
bei TrendfileProcessorLib.Services.TrendService.bulkTableTo(DataTable dataTable, String tabellenname) in c:\dev\Visual Studio Projects\TrendReader\TrendfileProcessorLib\Services\TrendService.cs:Zeile 77.}

System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near ')'

I have been trying to debug a piece of code and I have been thus far very unsuccessful in doing this.
I keep on getting this error
System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near ')'
and I can't seem to see where the error is.
The code is below, having looked at various answers on this site and looked at the examples. The situation is that I am writing a program that accesses a database and is able to add and save data to that database. It is located on a server - though this is on my laptop.
I have written, re-written and copied the connection string to ensure there are no mistakes in it and even dropped a copy of the string into word and compared it to the one that is in the coding itself but to no avail.
public partial class AddingClients : Form
{
public AddingClients()
{
InitializeComponent();
}
String CompanyName2;
String ClientName2;
String CompanyAddress12;
String CompanyAddress22;
String CompanyAddress32;
String CompanyTown2;
String CompanyPostCode2;
String TelephoneNumber2;
String CompanyEMail2;
String CompanyNotes2;
String ClientReference2;
public SqlConnection con;
public void connection()
{
String connectionstr = #"Data Source=ACER\PATTESTSERVER;Initial Catalog=PatTest;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;";
con = new SqlConnection(connectionstr);
con.Open();
}
private void Finish_Click(object sender, EventArgs e)
{
ClientReference2 = Id.Text;
CompanyName2 = CompanyName.Text;
ClientName2 = ClientName.Text;
CompanyAddress12 = CompanyAddress1.Text;
CompanyAddress22 = CompanyAddress2.Text;
CompanyAddress32 = CompanyAddress3.Text;
CompanyTown2 = CompanyTown.Text;
CompanyPostCode2 = CompanyPostCode.Text;
TelephoneNumber2 = TelephoneNumber.Text;
CompanyEMail2 = CompanyEMail.Text;
CompanyNotes2 = CompanyNotes.Text;
String connectionstr = #"Data Source=ACER\PATTESTSERVER;Initial Catalog=PatTest;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;";
con = new SqlConnection(connectionstr);
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO ClientTable(Id, ClientName, CompanyName, CompanyAddress1, CompanyAddress2, CompanyAddress3, CompanyTown, CompanyPostCode, TelephoneNumber, CompanyEMail, CompanyNotes,) VALUES(#parameter1, #parameter2, #parameter3, #parameter4, #parameter5, #parameter6, #parameter7, #parameter8, #parameter9, #parameter10, #parameter11,)", con);
cmd.Parameters.AddWithValue("#parameter1", ClientReference2);
cmd.Parameters.AddWithValue("#parameter2", ClientName2);
cmd.Parameters.AddWithValue("#parameter3", CompanyName2);
cmd.Parameters.AddWithValue("#parameter4", CompanyAddress12);
cmd.Parameters.AddWithValue("#parameter5", CompanyAddress22);
cmd.Parameters.AddWithValue("#parameter6", CompanyAddress32);
cmd.Parameters.AddWithValue("#parameter7", CompanyTown2);
cmd.Parameters.AddWithValue("#parameter8", CompanyPostCode2);
cmd.Parameters.AddWithValue("#parameter9", TelephoneNumber2);
cmd.Parameters.AddWithValue("#parameter10", CompanyEMail2);
cmd.Parameters.AddWithValue("#parameter11", CompanyNotes2);
cmd.ExecuteNonQuery();
//this method moves to the next screen.
this.Hide();
Asset M1 = new Asset();
M1.Show();
}
private void SaveandNext_Click(object sender, EventArgs e){
ClientReference2 = Id.Text;
CompanyName2 = CompanyName.Text;
ClientName2 = ClientName.Text;
CompanyAddress12 = CompanyAddress1.Text;
CompanyAddress22 = CompanyAddress2.Text;
CompanyAddress32 = CompanyAddress3.Text;
CompanyTown2 = CompanyTown.Text;
CompanyPostCode2 = CompanyPostCode.Text;
TelephoneNumber2 = TelephoneNumber.Text;
CompanyEMail2 = CompanyEMail.Text;
CompanyNotes2 = CompanyNotes.Text;
String connectionstr = #"Data Source=ACER\PATTESTSERVER;Initial Catalog=PatTest;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;";
con = new SqlConnection(connectionstr);
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO ClientTable(Id, ClientName, CompanyName, CompanyAddress1, CompanyAddress2, CompanyAddress3, CompanyTown, CompanyPostCode, TelephoneNumber, CompanyEMail, CompanyNotes,) VALUES(#parameter1, #parameter2, #parameter3, #parameter4, #parameter5, #parameter6, #parameter7, #parameter8, #parameter9, #parameter10, #parameter11,)", con);
cmd.Parameters.AddWithValue("#parameter1", ClientReference2);
cmd.Parameters.AddWithValue("#parameter2", ClientName2);
cmd.Parameters.AddWithValue("#parameter3", CompanyName2);
cmd.Parameters.AddWithValue("#parameter4", CompanyAddress12);
cmd.Parameters.AddWithValue("#parameter5", CompanyAddress22);
cmd.Parameters.AddWithValue("#parameter6", CompanyAddress32);
cmd.Parameters.AddWithValue("#parameter7", CompanyTown2);
cmd.Parameters.AddWithValue("#parameter8", CompanyPostCode2);
cmd.Parameters.AddWithValue("#parameter9", TelephoneNumber2);
cmd.Parameters.AddWithValue("#parameter10", CompanyEMail2);
cmd.Parameters.AddWithValue("#parameter11", CompanyNotes2);
cmd.ExecuteNonQuery();
this.Hide();
AddingClients M1 = new AddingClients();
M1.Show();//Saves the current data then goes to the next record to be tested.
You have an extra comma before the closing ) in your column list and VALUES sections:
SqlCommand cmd = new SqlCommand("INSERT INTO ClientTable(Id, ClientName, CompanyName, CompanyAddress1, CompanyAddress2, CompanyAddress3, CompanyTown, CompanyPostCode, TelephoneNumber, CompanyEMail,
CompanyNotes,)
****
VALUES(#parameter1, #parameter2, #parameter3, #parameter4, #parameter5, #parameter6, #parameter7, #parameter8, #parameter9, #parameter10,
#parameter11,)", con);
****
Remove that and you should be fine

vb.net syntax error in UPDATE statement. Code attached

Hi I am trying to UPDATE an access database with VB.net and am getting a Syntax Error. Everything else in my program works except this!
Error:
System.Data.OleDb.OleDbException was unhandled ErrorCode=-2147217900
HResult=-2147217900 Message=Syntax error in UPDATE statement.
Source=Microsoft Office Access Database Engine 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
WindowsApplication3.Form2.AddAddButton_Click(Object sender, EventArgs
e) in C:\Users\Andrew\Documents\Visual Studio
2013\Projects\WindowsApplication3\WindowsApplication3\Form2.vb:line 83
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(ApplicationContext context) at
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
at
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
at
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[]
commandLine) at WindowsApplication3.My.MyApplication.Main(String[]
Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81 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:
Code:
Private Sub AddAddButton_Click(sender As Object, e As EventArgs) Handles AddAddButton.Click
Dim conn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\*****************************;Jet OLEDB:Database Password=*********;")
Dim insertsql As String
Try
insertsql = "UPDATE RepairOrders SET ROOther = #Other, ROJobType = #Type, SET ROJobTime = #Time, SET RODelPicDate = #DelPic WHERE RONo = #JobNo"
Dim cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand(insertsql, conn)
cmd.Parameters.AddWithValue("#Other", AddOtherText.Text)
cmd.Parameters.AddWithValue("#Type", AddTypeCombo.SelectedValue)
If AddTimeCombo.Text = "AM" Then
cmd.Parameters.AddWithValue("#Time", Convert.ToInt32("1"))
Else
cmd.Parameters.AddWithValue("#Time", Convert.ToInt32("2"))
End If
cmd.Parameters.AddWithValue("#Time", Convert.ToInt32(AddTimeCombo.SelectedValue))
cmd.Parameters.AddWithValue("#DelPic", AddDatePick.Value.Date.ToString)
cmd.Parameters.AddWithValue("#JobNo", Convert.ToInt32(AddJobText.Text))
conn.Open()
cmd.ExecuteNonQuery()
MessageBox.Show("Booking Added!")
conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
I have hidden some sensitive information in the code. Please help me identify this issue. Thankyou :)
You have multiple SET in your query. Change it to
insertsql = "UPDATE RepairOrders SET ROOther = #Other,
ROJobType = #Type, ROJobTime = #Time, RODelPicDate = #DelPic WHERE RONo = #JobNo"

How to Read each row values from datagrid in Silverlight?

How to Read each row values from datagrid in Silverlight ?
i have this error
System.NullReferenceException was unhandled by user code
Message=La référence d'objet n'est pas définie à une instance d'un objet.
StackTrace:
à BusinessApplication4.Home.button4_Click(Object sender, RoutedEventArgs e)
à System.Windows.Controls.Primitives.ButtonBase.OnClick()
à System.Windows.Controls.Button.OnClick()
à System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
à System.Windows.Controls.Control.OnMouseLeftButtonUp(Control ctrl, EventArgs e)
à MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, Int32 actualArgsTypeIndex, String eventName)
InnerException:
foreach (var dgcol in dataGrid2.ItemsSource)
This happens because you didn't specify an ItemsSource. Try iterating through the Items instead.

Resources