Best vb.net questions in November 2011

Binary Shift Differences between VB.NET and C#

9 votes

I just found an interesting problem between translating some data:

VB.NET: CByte(4) << 8 Returns 4

But C#: (byte)4 << 8 Returns 1024

Namely, why does VB.NET: (CByte(4) << 8).GetType() return type {Name = "Byte" FullName = "System.Byte"}

Yet C#: ((byte)4 << 8).GetType() returns type {Name = "Int32" FullName = "System.Int32"}

Is there a reason why these two treat the binary shift the same? Following from that, is there any way to make the C# bit shift perform the same as VB.NET (to make VB.NET perform like C# you just do CInt(_____) << 8)?

According to http://msdn.microsoft.com/en-us/library/a1sway8w.aspx byte does not have << defined on it for C# (only int, uint, long and ulong. This means that it will use an implciit conversion to a type that it can use so it converts it to int before doing the bit shift.

http://msdn.microsoft.com/en-us/library/7haw1dex.aspx says that VB defines the operation on Bytes. To prevent overflow it applies a mask to your shift to bring it within an appropriate range so it is actually in this case shifting by nothing at all.

As to why C# doesn't define shifting on bytes I can't tell you.

To actually make it behave the same for other datatypes you need to just mask your shift number by 7 for bytes or 15 for shorts (see second link for info).

IsNumeric returns true for strings containing a D character

7 votes

I had a strange error in a VB6 app this morning and it all stems from the fact that IsNumeric is not working as I expected. Can someone shed some light on why? To me this seems like a bug.

This code displays 4.15877E+62 in a message box:

Dim strMessage As String
strMessage = "0415877D57"
If IsNumeric(strMessage) Then
    MsgBox CDbl(strMessage)
Else
    MsgBox "not numeric"
End If

I am guessing that the runtime engine is incorrectly thinking that the D is in fact an E? I think this is a bug though as the exact same code in VB.NET outputs not numeric Is this a known issue with IsNumeric?

If you check the VB6 docs:

Note Floating-point values can be expressed as mmmEeee or mmmDeee, in which mmm is the mantissa and eee is the exponent (a power of 10). The highest positive value of a Single data type is 3.402823E+38, or 3.4 times 10 to the 38th power; the highest positive value of a Double data type is 1.79769313486232D+308, or about 1.8 times 10 to the 308th power. Using D to separate the mantissa and exponent in a numeric literal causes the value to be treated as a Double data type. Likewise, using E in the same fashion treats the value as a Single data type.

Create VB6 application using a class in a DLL, then swap out that DLL after build?

6 votes

so my question is relatively simple, can I create VB6 application that references a class in a dll, and then substitute that dll for another at runtime?

Now my intial guess is... no chance in VB6.

So my thoughts turned to a VB.net interop dll. Could I do it in here, and then call the interop dll from the VB?

Again, my guess would be no.... but I'd be happy if someone knew differently.

The only thing that I think would actually work would be DI in .Net, but I'm limited to .net 2, or 3.5 at a big push, so I dont know if that is possible.

So for the background....

I have a dll that a specific site uses, but we dont want to ship that out to everyone. Instead, we want to build a clone dll which just has the interfaces setup so that the VB6 build will complete. When it gets to the site that needs it, they want to replace the dummy dll, and drop in their version instead.

Note: We do use RegFreeCOM when its gets installed, so I do have the manifest files that I could play around with if needed.

Any ideas would be much appreciated.

Nick

Its a COM dll so its not statically linked to the VB6 exe, so long as the clsids and interface ids are the same in the type library for both DLLs, you can swap them around as you see fit. (If its a VB6 dll this is trivial to do with the 'binary compatibility' build option)

Attaching console to running ASP.NET app

5 votes

Let’s say I have a library, in which I added a few Console.WriteLine(..) statements to help me out during the implementation and see what’s going on when I use the library in a Console App.

Now I want to use the same library in an ASP.NET app. Ideally I would be able to log on to the production webserver, and somehow start a command prompt and attach it to the website and see the messages in real time as they occur. How do I do that?

I'm not sure it works with ASP.Net, but you can use Trace.WriteLine instead of Console.WriteLine and then use DebugView to view the traces as they happen.

Splitting a String into Pairs

5 votes

How would I go on splitting a string into pairs of letter in VB?

for example: abcdefgh

split into: ab cd ef gh

I'll throw my hat in the ring:

Dim test As String = "abcdefgh"
Dim results As New List(Of String)

For i As Integer = 0 To test.Length - 1 Step 2
  If i + 1 < test.Length Then
    results.Add(test.Substring(i, 2))
  Else
    results.Add(test.Substring(i))
  End If
Next

MessageBox.Show(String.Join(" ", results.ToArray))

linq ambiguity on where and select

5 votes

Today I ran into an issue with LINQ to objects (not SQL) that popped up due to a typo. I had a .Select one place and a .Where in another place. I was expecting same result but they are showing different numbers. Assume somelist has 10 elements with all elements having qty = 0

//returns 10 - basically count of all rows. I am expecting 0
 somelist.Select(p => p.qty > 0).Count() 

//returns 0 - the correct count
 somelist.Where(p => p.qty > 0).Count() 

if both select and where return IEnumerable<T> then why the ambiguity? Thank you.

Select is a projection, so what you get is the expression p.qty > 0 evaluated for each element in somelist. i.e. lots of true/false values (the same number as your original list). So when you do Count on it, you get the same number. If you look the select will return IEnumerable<bool> (because the type of p.qty > 0 is a bool).

Where filters the results so count runs on the filtered list, and give you the expected results. The type of this is an IEnumerable<TypeOfElementInOriginalList>.

Note you can also do: somelist.Count(p => p.qty > 0) because Count has an overload that accepts a predicate to filter by.

GetProperty method is case sensitive for VB?

5 votes

I was debugging one of the applications I work on and came across an interesting issue. For those unfamiliar with VB.NET, variable names are case insensitive. Therefore,

Dim foo As Integer
FOO = 5
System.Console.WriteLine(foO)

will compile and output a value of 5.

Anyways, the code I was working on was attempting to get a value from a property via reflection like so:

Dim value As Object = theObject.GetType().GetProperty("foo", BindingFlags.Public Or BindingFlags.Instance).GetValue(theObject, Nothing)

The code threw a NullReferenceException on this line. After doing some debugging, I noticed it is the GetProperty method that is returning Nothing, so GetValue is bombing. Looking at the class for theObject, it has a public property with the name "Foo", not "foo" (notice the difference in casing). Apparently, since I was searching for lowercase foo, it could not find the property at all via reflection.

Thinking this was some weird fluke, I created a quick and dirty sandbox app to test this finding:

Option Strict On
Option Explicit On

Imports System.Reflection

Module Module1

    Sub Main()
        Dim test As New TestClass
        Dim propNames As New List(Of String)(New String() {"testprop", "testProp", "Testprop", "TestProp"})

        'Sanity Check
        System.Console.WriteLine(test.testprop)
        System.Console.WriteLine(test.testProp)
        System.Console.WriteLine(test.Testprop)
        System.Console.WriteLine(test.TestProp)

        For Each propName As String In propNames
            Dim propInfo As PropertyInfo = test.GetType().GetProperty(propName, BindingFlags.Public Or BindingFlags.Instance)
            If propInfo Is Nothing Then
                System.Console.WriteLine("Uh oh! We don't have PropertyInfo for {0}", propName)
            Else
                System.Console.WriteLine("Alright, we have PropertyInfo for {0} and its value is: {1}", propName, propInfo.GetValue(test, Nothing))
            End If
        Next
    End Sub

    Public Class TestClass
        Private _testProp As String = "I got it!"
        Public Property TestProp() As String
            Get
                Return _testProp
            End Get
            Set(ByVal value As String)
                _testProp = value
            End Set
        End Property
    End Class

End Module

Much to my surprise, the output was as follows:

I got it!
I got it!
I got it!
I got it!
Uh oh! We don't have PropertyInfo for testprop
Uh oh! We don't have PropertyInfo for testProp
Uh oh! We don't have PropertyInfo for Testprop
Alright, we have PropertyInfo for TestProp and its value is: I got it!

TL;DR

Variable names in VB.NET are typically case insensitive. The GetProperty method on Type seems to be case sensitive when it comes to the property name. Is there a way to call this method "VB.NET style" and ignore case? Or am I SOL here and need to apply a C# mentality and worry about casing?

Variable names in VB.NET are typically case insensitive.

That's a trick done by the compiler. The CLR itself is case-sensitive. Since reflection has nothing to do with the compiler, case-sensitivity applies.

Is there a way to call this method "VB.NET style" and ignore case?

Yes. Specify in your BindingFlags to IgnoreCase:

Dim propInfo As PropertyInfo = test.GetType().GetProperty(propName, BindingFlags.Public Or BindingFlags.Instance Or BindingFlags.IgnoreCase)

Why do we need connection strings?

5 votes

When we connect to a database in ASP.NET you must specify the appropriate connection string. However most other instances where data is to be specified is done within an object.

For example why couldn't we have connection objects such as:

var connection = new connectionObject(){
   DataSource = "myServerAddress",
   IntialCatalog = "myDataBase",
   UserId = "myUsername",
   Password = "myPassword"
}

which is far better than some key/value string:

Data Source=myServerAddress;Initial Catalog=myDataBase;UserId=myUsername;Password=myPassword;

The only reason I can think of is to allow storage in web.config, but there would be nothing stopping us storing the individual values in there anyway.

I'm sure there are good reasons, but what are they?

Legacy, tradition but above all : flexibility.

Try to write (or just imagine) the connectionConfig object that could handle all the MS-SQL, Oracle and (nested) ODBC configurations. And that's only a few of the databases supporting .NET.

Also, the main purpose of such an object would be to be serialized in a (somewhat) human-readable form.

So XML is an alternative, a fixed (set of) objects is not.

4 votes

Consider this example:

Private Sub Button_Click(
    sender As Button, e As RoutedEventArgs) Handles btn.Click

  sender.IsEnabled = False

  Thread.Sleep(5000)

  sender.IsEnabled = True
End Sub

In my scenario the Button_Click is a command delegate in the VM, and the Thread.Sleep is some long-running process (about 2-10 seconds).

I want, that when the user calls the command, it should immediately update the UI disabling the button so the user cannot execute it while it's running, then execute that operation, then, when operation completed, unblock the button.

I tried wrapping the middle line like the following:

Dispatcher.BeginInvoke(Sub() Thread.Sleep(5000))

But it didn't do the job.
What's the best way to do it?

Instead of creating a thread of your own you can also use the BackgroundWorker Control. By calling the Method "RunWorkerAsync" the DoWork Event get's called in another Thread.

By Calling the Method "CancelAsync" form your UI thread you can set the Backgroundworker to "Cancellation Pending" (Property of the Control "CancellationPending" is then true). In your long running background thread you can check for that property (e.g. if you have a loop: exit the loop as soon as CancellationPending is true). This is a quite nice feature to safely abort the thread.

In addition with the Backgroundworker you can also report the progress of the thread (e.g. for use in a ProgressBar)

Example:

Public Class Form1

   Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load

      '** Set to true if you want the ReportProgress Event
      BackgroundWorker1.WorkerReportsProgress = True
      BackgroundWorker1.WorkerSupportsCancellation = True
   End Sub

   Private Sub BackgroundWorker1_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork

      Dim i As Integer
      Dim n As Integer = 100
      Dim iLastPerc As Integer


      While Not BackgroundWorker1.CancellationPending AndAlso i < n

         '** Do your time consuming actions here
         Threading.Thread.Sleep(500)

         If Math.Floor((i / n) * 100) > iLastPerc Then
            '** If the Progress has changed. Report
            iLastPerc = CInt(Math.Floor((i / n) * 100))
            BackgroundWorker1.ReportProgress(iLastPerc)
         End If

         i += 1
      End While

   End Sub

   Private Sub btnStart_Click(sender As System.Object, e As System.EventArgs) Handles btnStart.Click

      '** Run the Backgroundworker
      BackgroundWorker1.RunWorkerAsync()

   End Sub

   Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged

      '** Update the ProgressBar
      ProgressBar1.Value = e.ProgressPercentage

   End Sub

   Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted

      '** Worker is done. Check for Exceptions or evaluate the Result Object if you like

   End Sub

   Private Sub btnCancel_Click(sender As System.Object, e As System.EventArgs) Handles btnCancel.Click

      '** Cancel the worker
      BackgroundWorker1.CancelAsync()

      MsgBox("Finished!")

   End Sub
End Class

In reference to your question the code should be:

Private Sub btn_Click(sender As Button, e As RoutedEventArgs) Handles btn.Click
  sender.IsEnabled = False
  Using bw As New BackgroundWorker()
    AddHandler bw.DoWork, Sub(s, ea) Thread.Sleep(5000)
    AddHandler bw.RunWorkerCompleted, Sub(s, ea) sender.IsEnabled = True
    bw.RunWorkerAsync()
  End Using
End Sub

How to dynamically generate textbox and collect data entered by user?

4 votes

I will appreciate answers in VB or C#

we use a database to create Data Collection forms with dynamic items

enter image description here

I used this code to generate labels and textboxes from a table in database (when the user hits the button "load CRF")

enter image description here

 Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim CRFgrid As New GridView
    CRFgrid.DataSource = CRFds
    CRFgrid.DataBind()

    Dim ItemCount As Integer = CRFgrid.Rows.Count
            Session("Itemcount") = CRFgrid.Rows.Count

    For I = 0 To (ItemCount - 1)
        Dim itemname As String = CRFgrid.Rows(0 + I).Cells(1).Text.ToString
        Session("Item") = "Item" + (I + 1).ToString
        Dim ItemNamelabel As New Label
        Dim ItemNameBox As New TextBox

        ItemNamelabel.ID = "L" + (I + 1).ToString
        Session("FU" + I.ToString) = ItemNamelabel.ID.ToString
        ItemNameBox.ID = "T" + (I + 1).ToString

        ItemNamelabel.Text = "<br />" + (Session("Item").ToString) + " " + itemname + " " + "<br />"

        Me.Form.Controls.Add(ItemNamelabel)
        Me.Form.Controls.Add(ItemNameBox)



    Next
End Sub

when the data collection form is loaded, the page looks like this

enter image description here

and the "view page source" shows

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>

 </title></head>
<body>
<form method="post" action="Default.aspx" id="form1">
<div class="aspNetHidden">
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE"     value="/wEPDwUKLTI0NTA5MDI3NGRkUb8sl0uZpLbvUN/GSmHgjYxS9xqGR7rmcMBR3Ufhz4w=" />
</div>

<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWCQLf7PXOCQKM54rGBgK7q7GGCALF9vKRBQLs7+btDALs7+LtDALs797tDALs79rtDALs79btDDHrb+Vhkcph8brtCJP9//5IH57FFoImey2PApARP+k1" />

<input type="submit" name="Button1" value="LoadCRF" id="Button1" style="width:85px;" />
<br />
<br />
<input type="submit" name="Button2" value="InsertData" id="Button2" style="width:85px;" />
<br />
<br />

MRN
<input name="MRNtxt" type="text" id="MRNtxt" />
<br />
<br />
<span id="L1"><br />Item1 Diagnosis <br /></span><input name="T1" type="text" id="T1" /><span id="L2"><br />Item2 Treatment Protocol <br /></span><input name="T2" type="text" id="T2" /><span id="L3"><br />Item3 Initial CSF <br /></span><input name="T3" type="text" id="T3" /><span id="L4"><br />Item4 Location <br /></span><input name="T4" type="text" id="T4" /><span id="L5"><br />Item5 Consultant <br /></span><input name="T5" type="text" id="T5" /></form>

once the user fills the form and click insert, i want to save entered text into a other tabel in the database using this code. it does not work. can u tell me where my mistake is?

Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click


    Dim mydb As New OleDbConnection
    mydb =
    New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source= |datadirectory|openclinica.mdb;Persist Security Info=True")
    mydb.Open()
    Dim Y As Integer = Session("Itemcount")
    For M = 1 To Y

        Session("FUt") = "L" + M.ToString
        Session("FUDt") = "T" + M.ToString

        Dim sqlstring = "INSERT INTO [Followup] ([MRN], [FU], [FUData]) VALUES (@MRNtxt, @" + Session("FUt") + ", @" + Session("FUDt") + ");"
        Dim mydbcommand As New OleDbCommand(sqlstring, mydb)
        mydbcommand.Parameters.Add("@MRNtxt", OleDbType.VarChar).Value = MRNtxt.Text
        mydbcommand.Parameters.Add("@" + Session("FUt"), OleDbType.VarChar).Value = Session("FUt").Text
        mydbcommand.Parameters.Add("@" + Session("FUDt"), OleDbType.VarChar).Value = Session("FUDt").Text
        mydbcommand.ExecuteNonQuery()

    Next

    mydb.Close()
End Sub

the error message looks like this when i click "insert"

enter image description here

I tried a lot and found this solution

Imports System.Data.OleDb

Partial Class _Default
Inherits System.Web.UI.Page

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

End Sub

Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click


    Dim mydb As New OleDbConnection
    mydb =
    New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source= |datadirectory|openclinica.mdb;Persist Security Info=True")
    mydb.Open()
    Dim part2 As Integer = Session("Itemcount")



    For Each C As Control In PlaceHolder1.Controls

        If TypeOf (C) Is TextBox Then

            Dim sqlstring = "insert into [followup] ([mrn], [fu], [fudata]) values (@mrntxt, @mylabel" + ", @mydata);"
            Dim mydbcommand As New OleDbCommand(sqlstring, mydb)
            mydbcommand.Parameters.Add("@mrntxt", OleDbType.VarChar).Value = MRNtxt.Text
            mydbcommand.Parameters.Add("@mylabel", OleDbType.VarChar).Value = C.ID
            mydbcommand.Parameters.Add("@mydata", OleDbType.VarChar).Value = CType(C, TextBox).Text
            mydbcommand.ExecuteNonQuery()
        End If
    Next

    mydb.Close()
End Sub




Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    InitializeCRF()
End Sub

Private Sub InitializeCRF()
    Dim CRFgrid As New GridView
    CRFgrid.DataSource = CRFds
    CRFgrid.DataBind()

    Dim ItemCount As Integer = CRFgrid.Rows.Count
    'Response.Write(ItemCount.ToString)
    Session("Itemcount") = CRFgrid.Rows.Count

    For I = 0 To (ItemCount - 1)
        Dim itemname As String = CRFgrid.Rows(0 + I).Cells(1).Text.ToString
        Session("Item") = "Item" + (I + 1).ToString
        Dim ItemNamelabel As New Label
        Dim ItemNameBox As New TextBox

        ItemNameBox.ID = itemname

        ItemNamelabel.Text = "<br/>" & itemname

        PlaceHolder1.Controls.Add(ItemNamelabel)
        PlaceHolder1.Controls.Add(ItemNameBox)


        ' Response.Write(itemname)
        ' Response.Write(", ")
    Next

End Sub
End Class

turning off automatic stop on exception in vb.net

4 votes

My coworker's installation of visual studio 2008 breaks every time there's an exception, mine doesn't.

We've been looking for how to stop his from doing this but haven't had any luck. The only difference is that mine was initialized for C# while his was initialized for VB.

Other than reinstalling and choosing the option that says "Optimise for C#" when VS2008 sets up the environment for the first time, does anyone know how to fix this?

Thanks.

In the Debug menu, choose "Exceptions..." and you can decide when the debugger breaks for each kind of exception - whether it's immediately, or only if it's unhandled, or neither.

See the MSDN section on exception handling with debugging for more information.

Meaning of Right$(string, 3)

4 votes

I was reading through some source code and came across what looks like a call to a function:

Right$(string, 3)

I can understand this is just simple string manipulation, but what is the meaning of the $ symbol?

$ has no meaning in context of Right function. In ancient VB Right$ was a function in new VB it is Right but you can also use Right$ (for backward compatibility)

Right$("hasan", 3) and Right("hasan", 3) are same in VB.NET

It is merely a convention used to name String related functions.

Late Binding Magic under VB.NET converted to C#

4 votes

I should convert some code from VB to C#. Given following lines of VB work (I think only because option is not set to strict):

Dim someProp As SomeType
Try
    someProp = CType(SomeInstance, Object).SomeProp 
    ' ...

Due to late binding, this code is possible under VB. Of course, following won't work under C#:

SomeType someProp;
try
{
    someProp = ((object)SomeInstance).SomeProp;
    // ...

How could I formulate something similar under C#?

Thx for any tipps sl3dg3

If you're using C# 4.0:

SomeType someProp;
try
{
    someProp = ((dynamic)SomeInstance).SomeProp;
    // ...

c# equivalent to vb.net handles button1.click, button2.click

4 votes

In vb.net I can do

private sub button_click(sender, e) handles Button1.Click, Button2.Click etc...
do something...
end sub

is there a method for this in c# .net ? I have roughly 16 buttons that all call the same function, just pass the text of the button to the function. I would rather not have 16 private void button_clicks calling one function.

Not sure how to do this though (not familiar with c# to much.)

thanks

Button1.Click += button_click;
Button2.Click += button_click;

What is the VB.NET equivalent of this C# Razor syntax?

4 votes

In the MVC 3 book by Steven Sanderson on p185 at the bottom, the following expression is used to render the paging links.

@Html.PageLinks(Model.Paginginfo, x=> Url.Action("List", new {page = x}))

What is the VB.NET equivalent? I am stuck on the x url lambda bit.

In VB.NET the lambda should be equivalent to this:

Function(x) Url.Action("List", New With { .Page = x })

You can refer to MSDN for more information about VB.NET's:

Is using thread local storage safe for this operation?

3 votes

I have a ASP.NET web application that allows end users to upload a file. Once the file is on the server, I spawn a thread to process the file. The thread is passed data regarding the specific operation (UserId, file path, various options, etc.). Most of the data is passed around via objects and method parameters but UserId needs to be available more globally so I put it in thread-local storage.

The thread is lengthy but it just processes the file and aborts. Is my use of the named data slot safe in this circumstance? If UserA uploads a file then UserB uploads a file while the first file is still processing, is it possible that the thread for UserA will also be delegated to handle UserB, thus producing a conflict for the named slot? (i.e. The slot gets overwritten with UserB's id and the rest of the operation of UserA's file is linked to the wrong User, UserB).

Public Class FileUploadProcess
    Public UserId as String

    Public Sub ExecuteAsync()
        Dim t As New Thread(New ThreadStart(AddressOf ProcessFile))
        t.Start()
    End Sub

    Protected Sub ProcessFile()
        Dim slot As LocalDataStoreSlot = Thread.GetNamedDataSlot("UserId")
        Thread.SetData(slot, UserId)

        'lengthy operation to process file

        Thread.FreeNamedDataSlot("UserId")
        Thread.CurrentThread.Abort()
    End Sub
End Class

Note that I am not asking if the LocalNamedDataStore slots are thread-safe. By definition, I know that they are.

In this case your use of thread local storage is safe. No two threads will ever share the same local storage (hence it's thread local). So there is no chance that two concurrent requests will stomp on the others data.

Couple of other comments though

  • Do avoid the use of Thread.Abort. It's a very dangerous operation and truthfully not needed here. The thread will end the statement afterwards.
  • A better approach would be to create a class which contains the background operation that has the UserId as a local field. Each request gets a new class instance. This is a much easier way to pass the data around to the background tasks

Could .NET be parsed and evaluated at runtime

3 votes

I thought it would be fun if I could write vb.net or c# code at runtime and the interpreter would automatically parse it like python does it, so I made a little program, which would do something similar. Basically it looks like this:

InputArgs = Console.ReadLine()
ParseInput(InputArgs.Split(" "))

Private Sub ParseInput(Args as List(Of String), Optional TempArgs as List(Of String))
Dim arg as string = Args(0)
If arg = ".." then
 ...
elseif arg = ".." then
 ...
end if
End Sub

I know it's not a good system, but it show's the basics. So my question is: Is it possible to make vb.net or c# like python - interpreted at runtime?

This already exists in a fair number of shapes and forms:

Mono.CSharp

Mono has the Mono.CSharp assembly, which you can reference to do whatever CSharp.exe (A C# 'interpreter' or interactive shell, if you will) can do:

void ReadEvalPrintLoopWith (ReadLiner readline)
{
    string expr = null;
    while (!InteractiveBase.QuitRequested){
            string input = readline (expr == null);
            if (input == null)
                return;

            if (input == "")
                continue;

            expr = expr == null ? input : expr + "\n" + input;

            expr = Evaluate (expr);
    } 
}

Needless to say this works on MS.Net too (of course, that's the point about portable .Net).

Full sources here on github - just as the rest of Mono, in fact.

DLR

Several DLR languages have been implemented, including but not limited to

It will allow you to evaluate python/ruby code on the fly in the .NET framework.

Roslyn

Microsoft has published Roslyn as a CTP (preview). It can basically do the same stuff as the Mono REPL (first item), and (much) more. But it is a preview still.