I'm trying to translate this C# code to VB.net
var messages = animalmgr.ReadFile(thefilename);
//Getting method from manager
if (messages != null)
{
messages.ToList().ForEach(msg => Resultlst.Items.Add(msg));
}
I tried it like this:
Dim message = animalmgr.ReadFile(thefilename)
If (Not (message) Is Nothing) Then
'I don't know how the code below are supposed to be
message.ToList.ForEach(() => { }, Resultlst.Items.Add(msg))
End If
I would appreciate if anyone could help me out. Thanks.
VB lambda functions are a bit different. Here is how it looks in VB.Net:
message.ToList().ForEach(Sub(msg) Resultlst.Items.Add(msg))
Related
I've been all over trying to find an answer to this, but every answer I found seemed to differ quiet a bit from what I really am looking for.
I need to check to make sure that two ASP Textboxes have been filled in before running a C# function that will do work on the text boxes.
Currently, I am using codebehind to check, but it is sloppy and has to postback to work.
So I have:
<td>Start Date (mm/dd/yyyy):</td><td><asp:TextBox ID="startDate" runat="server"></asp:TextBox></td>
<ajax:CalendarExtender ID="ce1" runat="server" TargetControlID="startDate"></ajax:CalendarExtender>
<td>End Date (mm/dd/yyyy):</td><td><asp:TextBox ID="endDate"></asp:TextBox></td>
<ajax:CalendarExtender ID="ce2" runat="server" TargetControlID="endDate"></ajax:CalendarExtender>
So I need a JS function to check if both field are empty, before using AJAX to run a C# program. I'm new to ASP and JS but this problem came through and figured it would be a (sort of) easy fix.
I would assume something like:
function checkDates(startid, endid) {
var s = document.getElementById(startid);
var e = document.getElementById(endid);
if( s != '' && e != ''){
//Use ajax to run C# function
}}
should work. But I can't seem to find any examples close to it to get an idea of what I need to do when working ASP and not just HTML.
Any input is greatly appreciated! (I tried to be as clear as possible, getting tunnel vision..)
You are almost there
function checkDates(startid, endid) {
var s = document.getElementById(startid);
var e = document.getElementById(endid);
if( s.value != '' && e.value != ''){
//Use ajax to run C# function
}
}
You should also need to check on the server side to ensure that the parameters being supplied are not null or empty.
This should work for you. I built an object to help keep things organized. Get the elements using the ClientID and store the reference in an object.
Whatever you're binding the handler to just needs to call Page.Handlers.CheckDates();
var Page =
{
Members:
{
startDate: document.getElementById('<%=startDate.ClientID %>'),
endDate: document.getElementById('<%=endDate.ClientID %>')
},
Handlers:
{
CheckDates: function ()
{
if (Page.Members.startDate.value.length > 0 && Page.Members.endDate.value.length > 0)
{
Page.Ajax.ValidateDates();
}
}
},
Ajax:
{
ValidateDates: function ()
{
//Put you ajax code here
}
}
}
In addition to Kami's answer I believe asp.net automatically prepends a tag to all asp.net controls to distinguish them. If you haven't changed it yourself I believe the default is "ct100_". So if you're using jQuery and aren't use an ajax call to get the ClientID the selector would look something like "#ct100_idname".
http://www.asp.net/web-forms/tutorials/master-pages/control-id-naming-in-content-pages-cs
Edit:
You can also use an inline server call to get the ID of a asp.net control
http://weblogs.asp.net/asptest/archive/2009/01/06/asp-net-4-0-clientid-overview.aspx
Using VS 2010, VB.NET, HTTPClient, .NET 4.0, and Windows Forms.
I am trying to get a windows application to consume JSON coming from a Web API that I have created. Web API works great and I can view the results from a browser. Found this article that I have been trying to get working only using VB.NET instead of C#.
http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-wpf-application
The critical part of the code is this function:
private void GetProducts(object sender, RoutedEventArgs e)
{
btnGetProducts.IsEnabled = false;
client.GetAsync("api/products/2").ContinueWith((t) =>
{
if (t.IsFaulted)
{
MessageBox.Show(t.Exception.Message);
btnGetProducts.IsEnabled = true;
}
else
{
var response = t.Result;
if (response.IsSuccessStatusCode)
{
response.Content.ReadAsAsync<IEnumerable<Product>>().
ContinueWith(t2 =>
{
if (t2.IsFaulted)
{
MessageBox.Show(t2.Exception.Message);
btnGetProducts.IsEnabled = true;
}
else
{
var products = t2.Result;
_products.CopyFrom(products);
btnGetProducts.IsEnabled = true;
}
}, TaskScheduler.FromCurrentSynchronizationContext());
}
}
}, TaskScheduler.FromCurrentSynchronizationContext());
}
I have tried to convert this to VB.NET but I am having issues with the t.Result saying "'Result' is not a member of 'System.Threading.Tasks.Task'."
Here is my attempt to convert it to VB.NET:
Private Sub GetProducts(sender As Object, e As RoutedEventArgs)
btnGetProducts.IsEnabled = False
client.GetAsync("api/products/2") _
.ContinueWith(Of HttpResponseMessage) _
(Function(t)
If t.IsFaulted Then
MessageBox.Show(t.Exception.Message)
btnGetProducts.IsEnabled = True
Else
'***************************************************************
Dim response = t.Result 'This is the line that is giving me grief. Error Msg: 'Result' is not a member of 'System.Threading.Tasks.Task'.
'***************************************************************
If response.IsSuccessStatusCode Then
response.Content.ReadAsAsync(Of IEnumerable(Of SendNotice)).ContinueWith _
(Function(t2)
If t2.IsFaulted Then
MessageBox.Show(t2.Exception.Message)
btnGetProducts.IsEnabled = True
Else
Dim products = t2.Result
_lstSN.CopyFrom(products)
btnGetProducts.IsEnabled = True
End If
End Function, TaskScheduler.FromCurrentSynchronizationContext())
End If
End If
End Function, TaskScheduler.FromCurrentSynchronizationContext())
End Sub
Any idea why I am getting this error and what am I missing in my code to allow me to catch the returning JSON data?
Thanks!
This is because VB.NET type inference is not great in Visual Studio 2010. You'll need to give the compiler a bit of extra help by specifying the actual type returned by your client.GetAsync(), like so:
client _
.GetAsync("api/products/2") _
.ContinueWith( _
Sub(t As Task(Of HttpResponseMessage))
...
End Sub, _
TaskScheduler.FromCurrentSynchronizationContext())
Note: I've changed your Function to Sub because I didn't see any Return statements.
Try this:
client.GetAsync("api/products/2") _
.ContinueWith(Sub(t)
If t.IsFaulted Then
.
.
.
Try changing your lambda from a Function to a Sub.
I found some code online. It is in C# and I am trying to port it to vb.net. I need some help with calling the evaluator function from within the Log subroutine. In C#, evaluator does not appear to expect any parameters when it gets called in Log. However, VB keeps asking for the Match parameter. What is the magic and how should I get it to work in VB.NET? Thanks.
private string evaluator(Match match)
{
Pri pri = new Pri(match.Groups[1].Value);
return pri.ToString()+" ";
}
private void Log(EndPoint endPoint, string strReceived)
{
...
string strMessage = string.Format("{0} : {1}",
endPoint, m_regex.Replace(strReceived, evaluator));
...
}
The C# version is using the (string, MatchEvaluator) overload of Regex.Replace(), and using the implicit conversion of the method name to the MatchEvaluator delegate type. See the MSDN documentation on that overload.
On the MSDN page, this is how they call it:
Dim result As String = rx.Replace(text, AddressOf RegExSample.CapText)
So make sure to use the AddressOf keyword.
I'm seeing some strange behaviour when making a change to the following VB.net code. This is the original sourcecode:
Private Function ValidateSelectedId(ByVal purposeId As String) As Boolean
Dim possiblePurposes As New InfoCollector.Purpose
Dim isPurposeValid As Boolean = False
'Any of the following purposes (but only these)
'should be considered valid
Select Case UCase(purposeId)
Case UCase(possiblePurposes.FirstPurpose), _
UCase(possiblePurposes.SecondPurpose), _
UCase(possiblePurposes.ThirdPurpose), _
UCase(possiblePurposes.FourthPurpose)
isPurposeValid = True
Case Else
isPurposeValid = False
End Select
Return isPurposeValid
End Function
This is the new version. The only change is the addition of a fifth valid purpose:
Private Function ValidateSelectedId(ByVal purposeId As String) As Boolean
Dim possiblePurposes As New InfoCollector.Purpose
Dim isPurposeValid As Boolean = False
Select Case UCase(purposeId)
Case UCase(possiblePurposes.FirstPurpose), _
UCase(possiblePurposes.SecondPurpose), _
UCase(possiblePurposes.ThirdPurpose), _
UCase(possiblePurposes.FourthPurpose), _
UCase(possiblePurposes.FifthPurpose)
isPurposeValid = True
Case Else
isPurposeValid = False
End Select
Return isPurposeValid
End Function
I compiled this new version on my local PC and tested the functionality, and it worked fine. After checking this into our central code repository, and building it on the server however, the usage failed (it appeared to be ignoring the new purpose). While trying to figure out what is missing, I decompiled the .DLL found on the server, and this is what it gave me (Note: I've changed the variable names and reformatted slightly):
Private Function ValidateSelectedId(ByVal purposeId As String) As Boolean
Dim ValidateSelectedId As Boolean
Dim possiblePurposes As Purpose = New Purpose()
Dim isPurposeValid As Boolean = False
Dim str As String = Strings.UCase(purposeId)
If (Operators.CompareString(str, Strings.UCase(possiblePurposes.FirstPurpose), False) <> 0) Then
If (Operators.CompareString(str, Strings.UCase(possiblePurposes.SecondPurpose), False) <> 0
AndAlso (Operators.CompareString(str, Strings.UCase(possiblePurposes.ThirdPurpose), False) = 0
OrElse Operators.CompareString(str, Strings.UCase(possiblePurposes.FourthPurpose), False) <> 0)) Then
If (Operators.CompareString(str, Strings.UCase(possiblePurposes.FifthPurpose), False) = 0) Then
Return True
End If
isPurposeValid = False
End If
End If
Return isPurposeValid
End Function
I also tried decompiling this into C#, which might be a little easier to read for some of us:
private bool ValidateSelectedId(string purposeId)
{
bool ValidateSelectedId;
Purpose possiblePurposes = new Purpose();
bool isPurposeValid = false;
string str = Strings.UCase(purposeId);
if (Operators.CompareString(str, Strings.UCase(possiblePurposes.FirstPurpose), false) != 0)
{
if (Operators.CompareString(str, Strings.UCase(possiblePurposes.SecondPurpose), false) != 0
&& (Operators.CompareString(str, Strings.UCase(possiblePurposes.ThirdPurpose), false) == 0
|| Operators.CompareString(str, Strings.UCase(possiblePurposes.FourthPurpose), false) != 0))
{
if (Operators.CompareString(str, Strings.UCase(possiblePurposes.FifthPurpose), false) == 0)
{
return true;
}
isPurposeValid = false;
}
}
return isPurposeValid;
}
This however, seems to be doing something like the inverse of what I wanted, and not at all what the original source code is saying!
I can't see how the original source code could have been compiled to this. Could there be something wrong with my decompiler (I'm using Just Decompile from Telerik)? If so, how come the logic works on my local PC, but not on the server?
Could there actually be some kind of bug in the compile-process? Or am I being a complete Id**t, and simply misunderstanding the logic in the decompiled code?
Any relevant theories to explain this will be greatly appreciated.
Silly me.
I eventually discovered the reason this did not work on the server: There was another related bug which had been fixed locally, but not on the server.
Silly decompiler.
I was confused by the result from the decompiler, which was obviously messed up. I've used JustDecompile many times before, but never run across a problem like this. Apparently, it is unable to decompile the code from the above method in any reasonable fashion.
My assumptions are that some form of optimization is done during compilation, which JustDecompile has trouble understanding and displaying properly.
I just wanted to verify that my changes had been published to the server. Instead I was sent on a wild goose chase for a phantom bug. Lesson learned: Use the decompiler when needed, but do not automatically trust everything it tells you.
I have some c# code that uses the Microsoft Scripting Control to evaluate some expressions:
using MSScriptControl; // references msscript.ocx
ScriptControlClass sc = new ScriptControlClass();
sc.Language = "VBScript";
sc.AllowUI = true;
try
{
Console.WriteLine(sc.Eval(txtEx.Text).ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
(txtEx is a simple text field)
Numerical expressions: "6+4", "cos(34)", "abs(-99)", "round(1.234, 2)" etc. are fine
Boolean expressions: "true or false", "1=2" are fine
But how can I evaluate a simple 'if'? I have tried "if(true, 2, 3)", "iif(true, 2, 3)", "if (true) then 2 else 3" and "if (true) then 2 else 3 endif"
Can anybody please help me to evaluate simple conditional expressions? Any help much appreciated!
RH
Try wrapping your IF-expression in a function
Function test
if (true) then
return true
else
return false
end if
End function
Add the function to the control and then use Run
Result = ScriptControl.Run("Test")
(the code above is not tested, but something along that way should work)
Check out this link for some more info
http://support.microsoft.com/kb/184740
using MSScriptControl; // references msscript.ocx
ScriptControlClass sc = new ScriptControlClass();
sc.Language = "VBScript";
sc.AllowUI = true;
// VBScript engine doesn’t have IIf function
// Adding wraper IIF function to script control.
// This IIF function will work just as VB6 IIf function.
sc.AddCode(#"Function IIF(Expression,TruePart,FalsePart)
If Expression Then
IIF=TruePart
Else
IIF=FalsePart
End IF
End Function");
try
{
//define x,y variable with value
sc.AddCode(#"x=5
y=6");
//test our IIF
Console.WriteLine(sc.Eval("IIF(x>y,x,y)").ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
You should consider using the expression evaluation engine that is part of Windows Workflow Foundation. Both the evaluator and the designer for it can be used separately from WF.
if (true) then return 2 else return 3
Thanks for the tips! After a bit more experimenting, based on Brummo's help, this seems to work:
txtEx contains this text:
function test
if (1=1) then
test = true
else
test = false
end if
end function
then
sc.AddCode(txtEx.Text);
and
object[] myParams = { };
Console.WriteLine(sc.Run("Test", ref myParams).ToString());
This isn't ideal, since I really wanted to evaluate an expression, without building, loading and evaluating a function. (I am surprised IIF doesn't work for simple one line if evaluation).