Dictionary(Of String, String) Cannot Evaluate Expression - asp.net

When calling a Sub to populate a System.Collections.Generic.Dictionary with keys and values from a DictionaryEntry(), upon examining the Dictionary in Debug mode every property has a red circle with an X and contains the text "Unable to evaluate expression." It appears to be working, it will even complain if I try to add two entries with the same Key/Value pair. No keys or values are present either, even though my test string (valuesString) is populated.
I am calling the Sub from the ItemInserted event of a FormView (.Net Framework 4, Visual Studio 2013 Webforms Application)
Protected Sub PopulateDictionary(myValues As DictionaryEntry())
Dim de As DictionaryEntry
Dim valuesString As String = String.Empty
Dim myDictionary As New Dictionary(Of String, String)
For Each de In myValues
'This works - the string is populated with key/value pairs
valuesString &= "Key=" & de.Key.ToString() & ", " & _
"Value=" & de.Value.ToString() & "<br/>"
'This doesn't - just get the red circle with an X
myDictionary.Add(de.Key.ToString(), de.Value.ToString())
Next
End Sub
What is going on here? I have restarted Visual Studio with no luck.

odd that this works with the "<br/>". it looks like it's missing the closing quote. (and maybe ToString() is not needed?)
valuesString &= "Key=" & de.Key.ToString() & ", " & _
"Value=" & de.Value.ToString() & "<br/>"
it looks like this:
myDictionary.Add(de.Key.ToString(), de.Value.ToString())
just needs to be:
myDictionary.Add(valuesString)
or (not sure...):
myDictionary.Add(DictionaryEntry())

Related

vb.net string concat adds vbCrlf literal to the string

I am trying to build a string that includes a newline character and is getting the weirdest result. This string is going to be stored in a SQL database to be later used as part of an email. My code is the following:
Dim strBody As String = "Andy," & Environment.NewLine
When I inspect the value of strBody during a debugging session, it is the following:
"Andy," & vbCrlf
I am obviously expecting is to be more like:
"Andy,"
Knowing that what is after the , is a hidden character.
Ultimately, the problem is... when I include strBody as part of my SQL insert statement, it literally shows up as the following within my SQL insert statement:
'Andy," & vbCrLf & "'
I was using this code yesterday and it worked fine. I am using similar code within another function of the same asp.net project and it works fine. I have tried using + instead of &, I have tried to use vbCrLf instead of Environment.NewLine, I have tried using stringbuilder, I have tried using string.concat. All with the same results where the & vbCrLf is included in strBody.
Is there a setting that I accidentally changed?
I know this is a weird one... Any help is greatly appreciated.
This is only Visual Studio showing you that there is new line character (vbCrLf or Environment.NewLine). If you use that string anywhere, it will be stored correctly.
I believe you will need to use some combination of Char(10) and Char(13):
Dim strBody As String = "'Andy,'" & " + CHAR(13)+CHAR(10) + "
There is a discussion about these and other methods on this thread.
You can do like this if you just need to insert Environment.NewLine inside database.
Dim a As String = """ & Environment.NewLine & """
Dim strBody As String = String.Format("Andy,{0}", a)
'"Andy," & Environment.NewLine & ""

Asp.net string creation gives operator "&" error VB

I have a SQL string in Asp.net web page, with vb code behind.
It was working fine before but for unknown reason I start now getting the following error:
Error: Sys.WebForms.PageRequestManagerServerErrorException: Operator '&' is not defined for string "UPDATE db.usersdata SET `SH" and type 'TextBox'.
UPDATE: SH is a string ('SAVE' or 'HIDE')
UPDATE: I am using MySQL database on the background.
Protected Sub savehide_SelectedIndexChanged(sender As Object, e As EventArgs)
Dim SQLstring As String = ""
Dim SH As String
SH = saveorhide.SelectedItem.Value
' the following line is where the error occurs
SQLstring = "UPDATE `db`.`usersdata` SET `SH`='" & SH & "' WHERE `PIC` = '" & Session("UserId") & "'"
Session("SH") = SH
SQLNonQuery_mysql(SQLstring)
CLEARALL()
displaydata()
End Sub
I have spent hours but I cannot find the reason for this, specially when before it was working fine.
This code runs when a dropdownlist field is changed.
The thing it also started to happen to other dropdownlist and SQL string creation code...So it is failing in various VB places now (as I said before it wasn't)
I am wondering if there is a bug or some weird reason why this error is coming out now (and not before) and what would be the solution.
According to the error message, either SH is a TextBox or Session("UserId") is a TextBox.
Since you already showed the declaration of SH, the only suspect remaining is the Session("UserId").
Can you show how you are setting the Session("UserId") value?
My best guess is that you are doing this:
Session("UserId") = TextBox1
you should change it to:
Session("UserId") = TextBox1.Text
(replace TextBox1 with name of your TextBox)

Math operators as dynamic variables

I have no idea how I'm going to accomplish this BUT someway, somehow I have to perform calculations dynamically in ASP/VB.NET (Possibly SQL Server). Something like this:
Dim var1, var2 as Integer
Dim Optr as string
var1 = 15
var2 = 25
Optr = +
MyResult(var1, var2, Optr)
...and MyResult should equal 40. How can I do this? Anyone have any ideas? Thanks!
The only way I can think of is a switch case which deals with all possible operators.
If you want to implement something more complicated(with operator presedence) you can use the Shunting Yard Algorithm
I don't have the code specifics, but you if have your vars and operations concatenated as a single string you could parse the string and compile it, given you the proper result.
Check this SO questions and answers here, they discuss a very similar problem (if not the exact same)
I like Paul Sasik's example for a purely .net solution, but another alternative would be to make use of the VBScript engine that's part of windows.
For example (you'll need to add a reference to the COM MSScript control)
Static sc As MSScriptControl.ScriptControl
'---- init the script control once
If sc Is Nothing Then
sc = New MSScriptControl.ScriptControl
sc.Language = "VBScript"
sc.AllowUI = False
End If
Try
Return sc.Eval(Expr)
Catch ex As Exception
'Deal with any error conditions here
End Try
Where Expr is any expression you might want to evaluate.
Granted, this leverages VBScript support, which you might want to avoid, but, depending on your audience, they might be more comfortable with that than .net coding
To allow for arbitrarily complex calculations you could take advantage of .NET's on-fly-compilation features. Here's an article for starters.
For your particular implementation you would construct a calculation string from your input like this:
Dim toCalc as string = var1 & " " & Optr & " " & var2
...and use a process where the calculation would get injected into a dynamically created class that would look something like this: (working console sample based on the CP article)
Imports System.CodeDom.Compiler
Imports System.Reflection
Module Module1
Sub Main()
Dim var1 As Integer = 50
Dim var2 As Integer = 65
Dim Optr As String = "+"
Dim equation As String = var1 & " " & Optr & " " & var2
Dim nl As String = System.Environment.NewLine
Dim dynClass As String = ""
dynClass &= "public class DynamicClass" & nl
dynClass &= " public shared function Calc() as double" & nl
dynClass &= " return " & equation & nl
dynClass &= " end function" & nl
dynClass &= "end class" & nl
Try
Dim params As New CompilerParameters
params.ReferencedAssemblies.AddRange(New String() {"Microsoft.VisualBasic.dll"})
Dim mAssembly As Assembly = New VBCodeProvider().CreateCompiler. _
CompileAssemblyFromSource(params, dynClass).CompiledAssembly
Console.WriteLine("Calculating: " & equation)
Console.WriteLine("SUCCESS! Result: " & mAssembly. _
GetType("DynamicClass"). _
InvokeMember("Calc", _
BindingFlags.InvokeMethod Or _
BindingFlags.Public Or _
BindingFlags.Static, _
Nothing, Nothing, Nothing).ToString())
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Sub
End Module

ASP.NET Replacing Line Break with HTML br not working

Hi
I am trying to submit some information into a database using an ASP.NET multiline textbox.
I have the following code:
Dim noteContent As String = Replace(txtNoteContent.InnerText.ToString(), vbCrLf, "<br />")
Shop.Job.Notes.addNote(Request.QueryString("JobID"), ddlNoteFrom.SelectedValue, ddlNoteTo.SelectedValue, noteContent)
The addNote's function code is:
Public Shared Sub addNote(ByVal JobID As Integer, ByVal NoteFrom As Integer, ByVal NoteTo As Object, ByVal NoteContent As String)
Dim newNote As New Job_Note
newNote.Date = DateTime.Now()
newNote.JobID = JobID
newNote.NoteByStaffID = NoteFrom
If Not NoteTo = Nothing Then
newNote.NoteToStaffID = CInt(NoteTo)
End If
newNote.NoteContent = NoteContent
Try
db.Job_Notes.InsertOnSubmit(newNote)
db.SubmitChanges()
Catch ex As Exception
End Try
End Sub
When it submit's the compiler does not seem to detect that line breaks have been entered into the textbox. I have debugged and stepped through the code, and sure enough, it just ignores the line breaks. If I try and replace another character instead of a line break, it works fine.
It doesn't seem to be anything to do with my function, the LINQ insert or anything like that, it simply just doesn't detect the line breaks. I have tried VbCr, and also chr(13) but they do not work either.
Can someone help me? I have been trying ad searching for over an hour trying to sort this.
Thanks
When you do your replace, you should check for VbCrLf (Windows Line Break), VbLf (Unix Line Break) and VbCr (Mac Line Break). If memory serves correct, the standard newline in a HTML textarea element is "\n" (aka VbLf), so you might just get away with replacing VbCrLf with VbLf in your code, but personally I always check for them all just to be safe.
Example
Dim htmlBreakElement As String = "<br />"
Dim noteContent As String = txtNoteContent.Text _
.Replace(vbCrLf, htmlBreakElement) _
.Replace(vbLf, htmlBreakElement) _
.Replace(vbCr, htmlBreakElement)
Shop.Job.Notes.addNote(Request.QueryString("JobID"), ddlNoteFrom.SelectedValue, ddlNoteTo.SelectedValue, noteContent)

add client script to asp.net page dynamically

I want to add javascript to asp.net page dynamically.
can anybody point me towards working example?
i know it can be done by using Page.ClientScript.RegisterClientScriptBlock
but i have no idea to use it.
MSDN
This is the MSDN link
if (!this.Page.ClientScript.IsClientScriptBlockRegistered(typeof(Page), "Utils"))
{
string UtilsScript = ResourceHelper.GetEmbeddedAssemblyResource("Utils.js");
this.Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Utils", UtilsScript, true);
}
I added the above example to help,
Here we test if the script is already registered (using the type an dkey we register against) get the script as a string from an embedded resource, then register (the last parameter of true tells the code to render Script tags).
hope this helps
P
An example to move the value of a Drop Down List to text field. The ID parameters are the Object.ClientID properties for the drop down list and text box.
Private Sub RegisterClientDropDownToTextBox(ByVal functionName As String, ByVal dropDownId As String, ByVal textBoxId As String)
Dim javascriptFunction As String = "function " & functionName & "() {" & _
"document.getElementById('" & textBoxId & "').value = document.getElementById('" & dropDownId & "').value;" & _
"}"
Dim javascriptWireEvent As String = "document.getElementById('" & dropDownId & "').onclick = " & functionName & ";"
Me.ClientScript.RegisterClientScriptBlock(Me.GetType(), functionName & "_ScriptBlock", javascriptFunction, True)
Me.ClientScript.RegisterStartupScript(Me.GetType(), functionName & "_Startup", javascriptWireEvent, True)
End Sub

Resources