Insert data to SQL Server Compact database - sql

I work on a VB.NET project, and I have a button that I want to insert data to my table with. So this is the code of this button :
Public Class Form21
Dim connexion As New SqlCeConnection("Data Source=D:\Cours\Projets\Stge\WindowsApplication1\WindowsApplication1\datababse.sdf")
Dim cmd As New SqlCeCommand
Dim libelle As String = TextBox1.Text
Dim prix As Double = Double.Parse(TextBox2.Text)
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
cmd.Connection = connexion
cmd.CommandText = "INSERT into Produit_fini values(#libelle,#prix)"
cmd.Parameters.AddWithValue("#libelle", libelle)
cmd.Parameters.AddWithValue("#prix", prix)
connexion.Open()
cmd.ExecuteNonQuery()
connexion.Close()
End Sub
End Class
The problem now, is that when I want to open the window where the button is figured, I get an error on this line :
Form21.ShowDialog()
The error says that I cannot open the window. Are there any errors in my button's code? Please help.
Thank you
Here is the error detail :
L'exception System.InvalidOperationException n'a pas été gérée
Message=Une erreur s'est produite lors de la création du formulaire. Pour plus d'informations, consultez Exception.InnerException. L'erreur est : La référence d'objet n'est pas définie à une instance d'un objet.
Source=database
StackTrace:
à database.My.MyProject.MyForms.Create_Instance_[T](T Instance) dans 17d14f5c-a337-4978-8281-53493378c1071.vb:ligne 190
à database.My.MyProject.MyForms.get_Form21()
à database.Form1.إضافةمنتوججديدToolStripMenuItem_Click(Object sender, EventArgs e) dans D:\Cours\Projets\ferran\WindowsApplication1\WindowsApplication1\Form1.vb:ligne 130
à System.Windows.Forms.ToolStripItem.RaiseEvent(Object key, EventArgs e)
à System.Windows.Forms.ToolStripMenuItem.OnClick(EventArgs e)
à System.Windows.Forms.ToolStripItem.HandleClick(EventArgs e)
à System.Windows.Forms.ToolStripItem.HandleMouseUp(MouseEventArgs e)
à System.Windows.Forms.ToolStripItem.FireEventInteractive(EventArgs e, ToolStripItemEventType met)
à System.Windows.Forms.ToolStripItem.FireEvent(EventArgs e, ToolStripItemEventType met)
à System.Windows.Forms.ToolStrip.OnMouseUp(MouseEventArgs mea)
à System.Windows.Forms.ToolStripDropDown.OnMouseUp(MouseEventArgs mea)
à System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
à System.Windows.Forms.Control.WndProc(Message& m)
à System.Windows.Forms.ScrollableControl.WndProc(Message& m)
à System.Windows.Forms.ToolStrip.WndProc(Message& m)
à System.Windows.Forms.ToolStripDropDown.WndProc(Message& m)
à System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
à System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
à System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
à System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
à System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
à System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
à System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
à System.Windows.Forms.Application.Run(ApplicationContext context)
à Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
à Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
à Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
à database.My.MyApplication.Main(String[] Args) dans 17d14f5c-a337-4978-8281-53493378c1071.vb:ligne 81
à System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
à System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
à Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
à System.Threading.ThreadHelper.ThreadStart_Context(Object state)
à System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
à System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
à System.Threading.ThreadHelper.ThreadStart()
InnerException: System.NullReferenceException
Message=La référence d'objet n'est pas définie à une instance d'un objet.
Source=database
StackTrace:
à database.Form21..ctor() dans D:\Cours\Projets\Stge\WindowsApplication1\WindowsApplication1\Form21.vb:ligne 7

Public Class Form21
Dim connexion As New SqlCeConnection("Data Source...")
Dim cmd As New SqlCeCommand
Dim libelle As String = TextBox1.Text
Dim prix As Double = Double.Parse(TextBox2.Text)
If these are form level declares as they appear to be you cannot reference controls (TextBox1 and TextBox2) before they are initialized. Change to:
Dim libelle As String = ""
Dim prix As Double =
Then in Form Load (when the TBs exist):
libelle = TextBox1.Text
prix = Double.Parse(TextBox2.Text)

Related

How to convert Stream to Image?

I have a WCF service and I send img by parameter in Stream, and I want save the image that I sent in file in my server, in this case is localhost.
Can you help me?
Public Function UploadStream(ByVal stream As Stream) As Byte() Implements IService1.UploadStream
Dim buffer As Byte() = New Byte(9999) {}
Dim bytesRead As Integer, totalBytesRead As Integer = 0
Do
bytesRead = stream.Read(buffer, 0, buffer.Length)
totalBytesRead += bytesRead
Loop While bytesRead > 0
Dim imagememorystream As MemoryStream = New MemoryStream(buffer)
Dim imgFromStream As Image = Image.FromStream(imagememorystream)
Return buffer
End Function
If I remove this code: Dim imagememorystream As MemoryStream = New MemoryStream(buffer)
Dim imgFromStream As Image = Image.FromStream(imagememorystream),
the function returns the bytearray, when I add him the WCF service doesn't work.
Erro do Pedido
O servidor encontrou um erro ao processar o pedido. A mensagem de exceção é 'O parâmetro não é válido.'. Consulte os registos do servidor para obter mais detalhes. O rastreio da pilha de exceções é:
em System.Drawing.Image.FromStream(Stream stream, Boolean useEmbeddedColorManagement, Boolean validateImageData)
em WcfService2.Service1.UploadStream(Stream stream)
em C:\Users\d-sil\source\repos\WcfService2\WcfService2\Service1.svc.vb:line 40
em SyncInvokeUploadStream(Object , Object[] , Object[] )
em System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
em System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
em System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
em System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage11(MessageRpc& rpc)
em System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)
i don't know much about vb but i did the same thing in c#. at first you need to return Stream instead of byte array and the simply return the image like this:
var Image = new MemoryStream(image) { Position = 0 };
WebOperationContext.Current.OutgoingResponse.ContentType = "image/*";
return Image;

Error with validation DigitalPersona SDK Excepción from HRESULT: 0xFFFFFFE3 (SDK Error = -29)

I am verifying the trace I receive from a SQL Server DB, the Data type is varbinary (MAX) but I receive this exception and I have no idea what it may be, I leave you the code of the query where I bring the data and the method it processes
Exception:
Exception From HRESULT: 0xFFFFFFE3
Log from the exception (This be in spanish):
Consulte el final de este mensaje para obtener más detalles sobre cómo invocar a la depuración
Just-In-Time (JIT) en lugar de a este cuadro de diálogo.
************** Texto de la excepción **************
DPFP.Error.SDKException: Event Handler has generated an Exception ---> System.Runtime.InteropServices.COMException: Excepción de HRESULT: 0xFFFFFFE3
en DPFP.Verification.Verification.MC_verifyFeaturesEx(SafeHandle mcContext, Int32 templateSize, Byte[] templatePt, Int32 featureSetSize, Byte[] featureSet, Int32 reserved0, IntPtr reserved1, IntPtr reserved2, IntPtr reserved3, Double& achievedFar)
en DPFP.Verification.Verification.Verify(FeatureSet FeatureSet, Template Template, Int32 FARRequested)
en DPFP.Verification.Verification.Verify(FeatureSet FeatureSet, Template Template, Result& Result)
en VerifyEnrollerApp.VerifyFinger.Process(Sample Sample) en c:\users\desarrollo 02\documents\visual studio 2012\Projects\VerifyEnrollerApp\VerifyEnrollerApp\Form1.vb:línea 322
en VerifyEnrollerApp.VerifyFinger.OnComplete(Object Capture, String ReaderSerialNumber, Sample Sample) en c:\users\desarrollo 02\documents\visual studio 2012\Projects\VerifyEnrollerApp\VerifyEnrollerApp\Form1.vb:línea 246
en DPFP.Capture.Capture.MessageReceived(Message& m)
--- Fin del seguimiento de la pila de la excepción interna ---
en DPFP.Capture.Capture.MessageReceived(Message& m)
en DPFP.Capture.Capture.MessageEvents.MessageWindow.WndProc(Message& m)
************** Ensamblados cargados **************
mscorlib
Versión del ensamblado: 4.0.0.0
Versión Win32: 4.6.1087.0 built by: NETFXREL4STAGE
Código base: file:///C:/Windows/Microsoft.NET/Framework/v4.0.30319/mscorlib.dll
----------------------------------------
Microsoft.VisualStudio.HostingProcess.Utilities
Versión del ensamblado: 11.0.0.0
Versión Win32: 11.0.50727.1
Código base: file:///C:/Windows/assembly/GAC_MSIL/Microsoft.VisualStudio.HostingProcess.Utilities/11.0.0.0__b03f5f7f11d50a3a/Microsoft.VisualStudio.HostingProcess.Utilities.dll
----------------------------------------
System.Windows.Forms
Versión del ensamblado: 4.0.0.0
Versión Win32: 4.6.1087.0 built by: NETFXREL4STAGE
Código base: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Windows.Forms/v4.0_4.0.0.0__b77a5c561934e089/System.Windows.Forms.dll
----------------------------------------
Select to the DataBase
Private Template As DPFP.Template
Public Function CargarHuella()
Dim conexion As New SqlConnection(Cadena_Conexion)
Dim a As Byte()
Dim Result As String = ""
Dim sql As String
Try
conexion.Open()
sql = "SELECT H_1 FROM HUELLAS WHERE H_Nit_ID = '11' AND H_TypeDocument_ID = '1' AND H_Document_ID = '1032494911'"
Dim cmd As New SqlCommand(sql, conexion)
Dim reader As SqlDataReader = cmd.ExecuteReader()
If reader.Read Then
a = reader.GetValue(0)
End If
reader.Close()
cmd.Dispose()
conexion.Dispose()
Dim str As New MemoryStream
str = New MemoryStream(a) 'Convertirmos los bites en Memory
Dim template As New DPFP.Template(str) 'Volvemos el Memory en Template para verificar
CargarTemplate(template)
Result = "Exito"
Catch ex As Exception
Result = "Error: " & ex.ToString
End Try
Return Result
End Function
Protected Sub CargarTemplate(ByVal template As DPFP.Template)
If Me.TXTMensajes.InvokeRequired Then
Dim d As New AddTemplateCallBack(AddressOf CargarTemplate)
Me.Invoke(d, New Object() {template})
Else
Me.Template = template
End If
End Sub
Verification Process
Private Verificator As DPFP.Verification.Verification
Protected Sub ProcessSample(ByVal Sample As DPFP.Sample)
DibujarMapa(Sample)
Dim caracteristicas As DPFP.FeatureSet = ExtraerCaracteristicas(Sample, DPFP.Processing.DataPurpose.Enrollment)
If (Not caracteristicas Is Nothing) Then
' Comparamos las caracteristicas de la huella tomada con las del template que tenemos
Dim result As DPFP.Verification.Verification.Result = New DPFP.Verification.Verification.Result()
Verificator.Verify(caracteristicas, Template, result) '<----HERE IS WHERE THE EXCEPTION IS SHOW
If result.Verified Then
SendMensaje("Ok", "Ok", 3)
Else
SendMensaje("KO", "KO", 1)
End If
End If
End Sub
What may be failing, or what am I failing?
PD: Sorry for my bad english :(
SOLUTION
Ok I solved it in the following way, I'll explain it first.
Apparently I had to instantiate as a new object the features that are extracted, I crawled with a try-catch to get the error code issued by the SDK on the failed process, the error is the -29 and in the documentation explain that it is when there is a Error in the features and can not be converted correctly I leave the code with the correction, it works perfectly for me.
''' <summary>
''' Todo el proceso que se encarga de validar la captura de la huella
''' </summary>
''' <param name="Sample"></param>
''' <remarks></remarks>
Protected Sub ProcessSample(ByVal Sample As DPFP.Sample)
Try
DibujarMapa(Sample)
Dim caracteristicas As DPFP.FeatureSet = New DPFP.FeatureSet '<---- I added this line and ready, it was fixed
caracteristicas = ExtraerCaracteristicas(Sample, DPFP.Processing.DataPurpose.Verification)
If (Not caracteristicas Is Nothing) Then
' Comparamos las caracteristicas de la huella tomada con las del template que tenemos
Dim result As DPFP.Verification.Verification.Result = New DPFP.Verification.Verification.Result()
CodesErrors.GetTypeCode()
Verificator.Verify(caracteristicas, Template, result)
If result.Verified Then
Huella = True
UpdateCalidad("Mensaje: " & vbCrLf & vbCrLf & "Huella verificada")
SendMensaje("Ok", "Ok...", 3)
Else
Huella = False
UpdateCalidad("Mensaje: " & vbCrLf & vbCrLf & "Huella no coincide")
SendMensaje("KO", "KO...", 1)
End If
End If
Catch ex As Exception
If ex.HResult = -29 Then '<-- This is the error code from de SDK exception
SendMensaje("Lo sentimos, ocurrió un error durante la validación de la huella." & vbCrLf & vbCrLf & "• Message: 'Invalid Feature Set Type'" & vbCrLf & "• Exception Code: " & ex.HResult, "Disculpenos :( - Error Número (" & ex.HResult & ")", 1)
Else
SendMensaje("• Exception Message: " & ex.Message & vbCrLf & vbCrLf & "• Exception Code: " & ex.HResult, "Error al Verificar", 1)
End If
End Try
End Sub

convert Date column to string / label if NOT IsDBNull

I am trying (much too long) to convert a DateTime column to a label.Text.
Various errors:
What am I missing?
drExpDatesRow = dtAllCompanies.Select("CompanyID = " + CompanyID.ToString())
Dim ls_ExpiresDateString As String
If (Not IsDBNull(drExpDatesRow("Expdate"))) Then
Date.TryParse(drExpDatesRow("Expdate").ToString(), ls_ExpiresDateString)
'ls_ExpiresDateString = ldt_ExpiresDate.ToString("MM/dd/yyyy")
lbl_ExpireDate.Text = ls_ExpiresDateString.ToString()
Else
lbl_ExpireDate.Text = ""
End If
System.InvalidCastException was unhandled Message=Conversion from
string "Expdate" to type 'Integer' is not valid.
Source=Microsoft.VisualBasic StackTrace:
at Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(String
Value)
at zzz.winCompanyInfo.CompanyInfo_Load(Object sender, EventArgs e) in C:\inetpub\zzz.vb:line 638
at System.Windows.Forms.Form.OnLoad(EventArgs e)
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.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) InnerException:
System.FormatException
Message=Input string was not in a correct format.
Source=Microsoft.VisualBasic
StackTrace:
at Microsoft.VisualBasic.CompilerServices.Conversions.ParseDouble(String
Value, NumberFormatInfo NumberFormat)
at Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(String
Value)
InnerException:
UPDATE** Added DataRow logic
When using TryParse use the same data type.
Dim drExpDatesRow = (From dr As DataRow In dtAllCompanies.Rows
Where dr("CompanyId").ToString =
CompanyID.ToString).FirstOrDefault
Dim ls_ExpiresDate As Date ' Date not String
If (Not drExpDatesRow Is Nothing) Then
If Date.TryParse(drExpDatesRow("Expdate").ToString(), ls_ExpiresDate)
lbl_ExpireDate.Text = ls_ExpiresDate.ToString()
End If
Else
lbl_ExpireDate.Text = ""
End If
You had multiple issues in your code. This one should take care of things for good
drExpDatesRow = dtAllCompanies.Select("CompanyID = " + CompanyID.ToString()) ' returns array
lbl_ExpireDate.Text = ""
If drExpDatesRow.Length > 0 Then
If (Not IsDBNull(drExpDatesRow(0)("Expdate"))) Then
Dim myDate As DateTime
Dim res As Boolean = Date.TryParse(drExpDatesRow("Expdate"), myDate)
If res Then lbl_ExpireDate.Text = MyDate.ToString("<format>")
End If
End If

Replace a text with all alphabet VB.NET

I just stopped by this error
System.NullReferenceException was unhandled HResult=-2147467261
Message=Object reference not set to an instance of an object.
Source=System.Windows.Forms StackTrace:
at System.Windows.Forms.RichTextBox.StreamIn(String str, Int32 flags)
at System.Windows.Forms.RichTextBox.set_SelectedText(String value)
at Novania_JAV_Viewer_EncDec.Form1.Button1_Click(Object sender, EventArgs ef) in c:\users\toshiba\documents\visual studio
2010\Projects\Novania JAV Viewer EncDec\Novania JAV Viewer
EncDec\Form1.vb:line 91
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 Novania_JAV_Viewer_EncDec.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:
and this is my whole code, I am trying to replace all alphabet in one word, and it needs to replace one by one, and one by one variable.
the error is located here ("title") word
Do Until RichTextBox1.Find("titelz") = -1
RichTextBox1.Find("titelz")
RichTextBox1.SelectedText = titel
and this is my whole form class code
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
RichTextBox1.LoadFile("template.rtf")
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal ef As System.EventArgs) Handles Button1.Click
Dim A As String
Replace(TextBox1.Text, "A", "5TY5")
Console.WriteLine(A)
Dim B As String
Replace(A, "B", "WEE")
Console.WriteLine(B)
Dim C As String
Replace(B, "C", "23RW")
Console.WriteLine(C)
Dim D As String
Replace(C, "D", "RW4R")
Console.WriteLine(D)
Dim E As String
Replace(D, "E", "DFS")
Console.WriteLine(E)
Dim F As String
Replace(E, "F", "R5")
Console.WriteLine(F)
Dim G As String
Replace(F, "G", "QWEDQ")
Console.WriteLine(G)
Dim H As String
Replace(G, "H", "ZDCZ")
Console.WriteLine(H)
Dim I As String
Replace(H, "I", "VGHN")
Console.WriteLine(I)
Dim J As String
Replace(I, "J", "ZSC")
Console.WriteLine(J)
Dim K As String
Replace(J, "K", "ZSD")
Console.WriteLine(K)
Dim L As String
Replace(K, "L", "WER")
Console.WriteLine(L)
Dim M As String
Replace(L, "M", "GN")
Console.WriteLine(M)
Dim N As String
Replace(M, "N", "xfv")
Console.WriteLine(N)
Dim O As String
Replace(N, "O", "DAASAD")
Console.WriteLine(O)
Dim P As String
Replace(O, "P", "WET")
Console.WriteLine(P)
Dim Q As String
Replace(P, "Q", "DFCV")
Console.WriteLine(Q)
Dim R As String
Replace(Q, "R", "ADSDA")
Console.WriteLine(R)
Dim S As String
Replace(R, "S", "SGFDG")
Console.WriteLine(S)
Dim T As String
Replace(S, "T", "SFSFD")
Console.WriteLine(T)
Dim U As String
Replace(T, "U", "AWDAD")
Console.WriteLine(U)
Dim V As String
Replace(U, "V", "RERE")
Console.WriteLine(V)
Dim W As String
Replace(V, "W", "GBGDBB")
Console.WriteLine(W)
Dim X As String
Replace(W, "X", " AWDAW ")
Console.WriteLine(X)
Dim Y As String
Replace(X, "Y", "AWDEAVA")
Console.WriteLine(Y)
Dim Z As String
Replace(Y, "Z", "AWEDWADW")
Console.WriteLine(Z)
Dim titel As String = Z
Do Until RichTextBox1.Find("titelz") = -1
RichTextBox1.Find("titelz")
RichTextBox1.SelectedText = titel
Loop
RichTextBox2.Text = RichTextBox1.Text
RichTextBox1.Clear()
RichTextBox1.LoadFile("template.rtf")
End Sub
End Class
In order to do the replace, I'd try the following code...
It uses a Dictionary type variable. They are used in .NET quite a lot as some sort of associative array.
' First, create dictionary that you can loop through.
' This variable is created on form level (so only once)
' and contains all the "words" as key-value pairs.
' So you can search for key and replace with value.
Dim replaceDictionary As New Dictionary(Of String, String) From {{"A", "5TY5"}, _
{"B", "WEE"}, _
{"C", "23RW"}, _
{"D", "RW4R"}, _
{"E", "DFS"}, _
{"F", "R5"}, _
{"G", "QWEDQ"}, _
{"H", "ZDCZ"}, _
{"I", "VGHN"}, _
{"J", "ZSC"}, _
{"K", "ZSD"}, _
{"L", "WER"}, _
{"M", "GN"}, _
{"N", "xfv"}, _
{"O", "DAASAD"}, _
{"P", "WET"}, _
{"Q", "DFCV"}, _
{"R", "ADSDA"}, _
{"S", "SGFDG"}, _
{"T", "SFSFD"}, _
{"U", "AWDAD"}, _
{"V", "RERE"}, _
{"W", "GBGDBB"}, _
{"X", " AWDAW "}, _
{"Y", "AWDEAVA"}, _
{"Z", "AWEDWADW"}
}
Private Sub btnReplace_Click(sender As System.Object, e As System.EventArgs) Handles btnReplace.Click
' Declare temporary variable to store text
Dim tmpText As String = txtTitel.Text
' Loop through dictionary
For Each replaceItem In replaceDictionary
' Replace key ("A" etc.) with value ("5TY5" etc.)
' and store in temporary variable
tmpText = Replace(tmpText, replaceItem.Key, replaceItem.Value)
Next
'Display text
txtTitel.Text = tmpText
End Sub
Now for your "find" part... nothing like "titelz" is going to be changed with above code (only caps), so if it was in there, it stays in there.
So I have no idea what to do with that...
Edit
For the record: this goes for a long line of replaces... Once you've replaced all the A's in your string, the T from "5TY5" will also be replaced.
If you don't want this, you'll have to split the original text into characters and start checking them one by one.
Checking title string one letter at a time
There are a few changes to above code:
Dictionary is now of type (Char, String) instead of 2 strings.
The title is stored in a seperate variable in order to keep working with the orignal title text.
Instead of looping through the dictionary, you loop through the title text one letter at a time.
The code is documented with comments and should be pretty self-explanatory.
Good luck!
' First, create dictionary that you can loop through.
' This variable is created on form level (so only once)
' and contains all the "words" as key-value pairs.
' So you can search for key and replace with value.
Dim replaceDictionary As New Dictionary(Of Char, String) From {{"A", "5TY5"}, _
{"B", "WEE"}, _
{"C", "23RW"}, _
{"D", "RW4R"}, _
{"E", "DFS"}, _
{"F", "R5"}, _
{"G", "QWEDQ"}, _
{"H", "ZDCZ"}, _
{"I", "VGHN"}, _
{"J", "ZSC"}, _
{"K", "ZSD"}, _
{"L", "WER"}, _
{"M", "GN"}, _
{"N", "xfv"}, _
{"O", "DAASAD"}, _
{"P", "WET"}, _
{"Q", "DFCV"}, _
{"R", "ADSDA"}, _
{"S", "SGFDG"}, _
{"T", "SFSFD"}, _
{"U", "AWDAD"}, _
{"V", "RERE"}, _
{"W", "GBGDBB"}, _
{"X", " AWDAW "}, _
{"Y", "AWDEAVA"}, _
{"Z", "AWEDWADW"}
}
Private Sub btnReplace_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReplace.Click
' Declare temporary variable to store text
Dim tmpTitle As String = txtTitel.Text
Dim tmpText As String = ""
Dim tmpLetter As Char
' Loop through title string
Dim i As Integer = 0
Do While (i < tmpTitle.Length)
' Increase counter
i += 1
' Save next letter in tmpLetter
tmpLetter = Mid(tmpTitle, i, 1)
' Check for key in dictionary
If replaceDictionary.ContainsKey(tmpLetter) Then
' When found, append associated value to tmpText
tmpText &= replaceDictionary(tmpLetter)
Else
' Not found: use letter from title string
tmpText &= CStr(tmpLetter)
End If
Loop
'Display text
txtTitel.Text = tmpText
End Sub

LINQ compiled query won't execute - ArgumentNulException was unhandled

I'm testing the Compiled Queries for the first time.
My current query is:
Shared compiledLatestDate As Func(Of RackJobbingDataDataContext, ArtikelInfoParameters, List(Of VerdelingPlanning)) = _
CompiledQuery.Compile(Of RackJobbingDataDataContext, ArtikelInfoParameters, List(Of VerdelingPlanning))( _
Function(db As RackJobbingDataDataContext, param As ArtikelInfoParameters) _
(From verdplan As VerdelingPlanning In db.VerdelingPlannings _
Join artPlan As ArtikelPlanning In db.ArtikelPlannings _
On artPlan.VerdelingPlanningID Equals verdplan.VerdelingPlanningID _
Join levDet As LeveringDetail In db.LeveringDetails _
On levDet.ArtikelPlanningID Equals artPlan.ArtikelPlanningID _
Join lev As Levering In db.Leverings _
On lev.LeveringID Equals levDet.LeveringID _
Where artPlan.ArtikelID.Equals(param.artId) _
And lev.WinkelID.Equals(param.winkId) _
And Not levDet.PlanningAantal.Equals(Nothing) _
And levDet.PlanningAantal <> 0 _
And verdplan.Datum < param.datumVerdeling _
Order By verdplan.Datum Descending _
Select levDet))
But i receive an ArgumentNulException was unhandled.
It was advised for LINQ queries to add an object with the required parameters, so this is the class:
Public Class ArtikelInfoParameters
Private _wkId As Guid
Private _artId As Guid
Private _datumVerdeling As DateTime
Public Sub New(ByVal artId As Guid, ByVal winkId As Guid, ByVal datumVerdeling As DateTime)
_artId = artId
_wkId = winkId
_datumVerdeling = datumVerdeling
End Sub
Public Property artId As Guid
Get
Return _artId
End Get
Set(ByVal value As Guid)
_artId = value
End Set
End Property
Public Property winkId As Guid
Get
Return _wkId
End Get
Set(ByVal value As Guid)
_wkId = value
End Set
End Property
Public Property datumVerdeling As DateTime
Get
Return _datumVerdeling
End Get
Set(ByVal value As DateTime)
_datumVerdeling = value
End Set
End Property
End Class
And for the sake of being complete, this is the error i'm receiving.
bij System.Data.Linq.SqlClient.SqlJoin.set_Left(SqlSource value)
bij System.Data.Linq.SqlClient.SqlMultiplexer.Visitor.VisitMultiset(SqlSubSelect sms)
bij System.Data.Linq.SqlClient.SqlVisitor.VisitSubSelect(SqlSubSelect ss)
bij System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode node)
bij System.Data.Linq.SqlClient.SqlVisitor.VisitExpression(SqlExpression exp)
bij System.Data.Linq.SqlClient.SqlMultiplexer.Visitor.VisitSelect(SqlSelect select)
bij System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode node)
bij System.Data.Linq.SqlClient.SqlProvider.BuildQuery(ResultShape resultShape, Type resultType, SqlNode node, ReadOnlyCollection`1 parentParameters, SqlNodeAnnotations annotations)
bij System.Data.Linq.SqlClient.SqlProvider.BuildQuery(Expression query, SqlNodeAnnotations annotations)
bij System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Compile(Expression query)
bij System.Data.Linq.CompiledQuery.ExecuteQuery(DataContext context, Object[] args)
bij System.Data.Linq.CompiledQuery.Invoke[TArg0,TArg1,TResult](TArg0 arg0, TArg1 arg1)
bij RackJobbing.UI.ucArtikelInfo.getLatestDate(Guid artikelId) in D:\EasySolutions\TFS\Provoost\Development\RackJobbing\RackJobbing.UI\Snelinvoer\Verdeling\ucArtikelInfo.vb:regel 69
bij RackJobbing.UI.ucArtikelInfo.UpdateInfo() in D:\EasySolutions\TFS\Provoost\Development\RackJobbing\RackJobbing.UI\Snelinvoer\Verdeling\ucArtikelInfo.vb:regel 111
bij RackJobbing.UI.frmPrePlanning.UcVerdeling1_ArtikelWinkelChanged() in D:\EasySolutions\TFS\Provoost\Development\RackJobbing\RackJobbing.UI\Snelinvoer\Verdeling\frmPrePlanning.vb:regel 280
bij RackJobbing.UI.ucVerdeling.grdVerdeling_EnterCell(Object sender, EventArgs e) in D:\EasySolutions\TFS\Provoost\Development\RackJobbing\RackJobbing.UI\Snelinvoer\Verdeling\ucVerdeling.vb:regel 339
bij C1.Win.C1FlexGrid.C1FlexGridBase.OnEnterCell(EventArgs e)
bij C1.Win.C1FlexGrid.C1FlexGridBase.a9()
bij C1.Win.C1FlexGrid.C1FlexGridBase.OnGridChanged(Object sender, GridChangedEventArgs e)
bij C1.Win.C1FlexGrid.C1FlexGrid.OnGridChanged(Object sender, GridChangedEventArgs e)
bij C1.Win.C1FlexGrid.t.bc(GridChangedTypeEnum A_0, Int32 A_1, Int32 A_2, Int32 A_3, Int32 A_4)
bij C1.Win.C1FlexGrid.t.bn(GridChangedTypeEnum A_0)
bij C1.Win.C1FlexGrid.p.n(C1FlexGridBase A_0, CellRange A_1, Boolean A_2)
bij C1.Win.C1FlexGrid.C1FlexGridBase.Select(CellRange rg, Boolean show)
bij C1.Win.C1FlexGrid.ab.o(MouseEventArgs A_0)
bij C1.Win.C1FlexGrid.ab.l(MouseEventArgs A_0)
bij C1.Win.C1FlexGrid.C1FlexGridBase.OnMouseDown(MouseEventArgs e)
bij System.Windows.Forms.Control.WmMouseDown(Message& m, MouseButtons button, Int32 clicks)
bij System.Windows.Forms.Control.WndProc(Message& m)
bij C1.Win.C1FlexGrid.Util.BaseControls.ScrollableControl.WndProc(Message& m)
bij System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
bij System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
bij System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
bij System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
bij System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
bij System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
bij System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
bij System.Windows.Forms.Application.Run(ApplicationContext context)
bij Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
bij Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
bij Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
bij RackJobbing.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:regel 81
bij System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
bij System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
bij Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
bij System.Threading.ThreadHelper.ThreadStart_Context(Object state)
bij System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
bij System.Threading.ThreadHelper.ThreadStart()
I'd appreciate any help in solving my problem , because i really can't seem to find the solution :(
Unlike SQL, the ON clause's left and right sides have different scope visibility.
You need to put variables that were in scope before the JOIN on the left side of the ON clause, and variables that are newly in scope from the JOIN on the right side.
Here I have switched the variables in ON clauses.
From verdplan As VerdelingPlanning In db.VerdelingPlannings _
Join artPlan As ArtikelPlanning In db.ArtikelPlannings _
On verdplan.VerdelingPlanningID Equals artPlan.VerdelingPlanningID _
Join levDet As LeveringDetail In db.LeveringDetails _
On artPlan.ArtikelPlanningID Equals levDet.ArtikelPlanningID _
Join lev As Levering In db.Leverings _
On levDet.LeveringID Equals lev.LeveringID _
Solution:
Public Shared CompiledLatestDate As Func(Of RackJobbingDataDataContext, ArtikelInfoParameters, IQueryable(Of VerdelingPlanning)) = _
CompiledQuery.Compile(Function(db As RackJobbingDataDataContext, artInfo As ArtikelInfoParameters) _
From verdplan As VerdelingPlanning In db.VerdelingPlannings _
Join artPlan As ArtikelPlanning In db.ArtikelPlannings _
On verdplan.VerdelingPlanningID Equals artPlan.VerdelingPlanningID _
Join levDet As LeveringDetail In db.LeveringDetails _
On artPlan.ArtikelPlanningID Equals levDet.ArtikelPlanningID _
Join lev As Levering In db.Leverings _
On levDet.LeveringID Equals lev.LeveringID _
Where artPlan.ArtikelID.Equals(artInfo.artId) _
And lev.WinkelID.Equals(artInfo.winkId) _
And Not levDet.PlanningAantal.Equals(Nothing) _
And levDet.PlanningAantal <> 0 _
And verdplan.Datum < artInfo.datumVerdeling _
Order By verdplan.Datum Descending _
Select verdplan)
Solved almost all of my problems, even though i sometimes get a NullReferenceException when there is no value in the collection (it doesn't always give an error, so i'm still looking into that).