[Visual C#]
public ICommand MyCommand
{
get
{
if (this.myCommand == null)
{
this.myCommand = new RelayCommand(this.ShowMyCommand);
}
return this.myCommand;
}
}
private void ShowMyCommand(object param)
{
...
}
This code works fine, but when I convert it to Visual Basic:
[Visual Basic]
Private _myCommand As RelayCommand
Public ReadOnly Property MyCommand As ICommand
Get
If Me._myCommand Is Nothing Then
Me._myCommand = New RelayCommand(Me.ShowMyCommand)
End If
Return Me._myCommand
End Get
End Property
Private Sub ShowMyCommand(ByVal param As Object)
...
End Sub
I get the error:
Error 3 Argument not specified for
parameter 'param' of 'Private Sub
ShowMyCommand(param As Object)'.
Any ideas? I am just doing blind conversion so I don't understand what the project does, I am just converting it.
I am a bit on thin ice when it comes to VB, but according to what I know, you need to prefix the method name with the keyword AddressOf in order for it to be usable as a method group for the event.
The following line:
Me._myCommand = New RelayCommand(Me.ShowMyCommand)
Needs to be written as:
Me._myCommand = New RelayCommand(AddressOf Me.ShowMyCommand)
The error message is because the compiler is trying to compile a call to the method, and is thus missing the argument to its parameter.
Related
to create functionallity in my project I need to convert this C# sample to vb.net
I can only connect (Read/Write) to the backend using this API.
to get the details of a customer from a database:
Customer.BeginFetch(CustomerId, AfterFetchingCustomer);
private void AfterFetchingCustomer(object sender, DataPortalResult<Customer> dataPortalResult)
{
Invoke((Action)(() =>
{
_customer = dataPortalResult.Object;
txtShortName.Text = _customer.ShortName;
}));
}
//This is from the API in C#
public static void BeginFetch(string customerId, EventHandler<DataPortalResult<Customer>> callback, AdministrationContext context = null);
I tried:
Dim Debb Debiteur.CustomerId = "DE16000"
Customer.BeginFetch(Debiteur, AfterFetchingCustomer)
End Sub
Private Sub AfterFetchingCustomer(sender As Object, e As DataPortalResult(Of Customer))
End Sub
''This is from the API in VB:
Public Shared Sub BeginFetch(customerId As String, callback As EventHandler(Of DataPortalResult(Of Customer)), Optional context As AdministrationContext = Nothing)
But still get the errors:
Argument not specified for parameter sender ...
Argument not specified for parameter e ...
How can i get this code validated?
So I can continue to work on this program.
Thanks in advance!
This question already has answers here:
VB.NET equivalent to C# var keyword [duplicate]
(4 answers)
Closed 8 years ago.
I'm looking at trying to implement a mediator helper class to facilitate the transfer of information between viewmodels.
Starting with the following in c#
static public class Mediator
{
static IDictionary<string, List<Action<object>>> pl_dict = new Dictionary<string, List<Action<object>>>();
static public void Register(string token, Action<object> callback)
{
if (!pl_dict.ContainsKey(token))
{
var list = new List<Action<object>>();
list.Add(callback);
pl_dict.Add(token, list);
}
else
{
bool found = false;
foreach (var item in pl_dict[token])
if (item.Method.ToString() == callback.Method.ToString())
found = true;
if (!found)
pl_dict[token].Add(callback);
}
}
static public void Unregister(string token, Action<object> callback)
{
if (pl_dict.ContainsKey(token))
pl_dict[token].Remove(callback);
}
static public void NotifyColleagues(string token, object args)
{
if (pl_dict.ContainsKey(token))
foreach (var callback in pl_dict[token])
callback(args);
}
}
I end up with the following in vb (courtesy of telerik's online converter
Public NotInheritable Class Mediator
Private Sub New()
End Sub
Shared pl_dict As IDictionary(Of String, List(Of Action(Of Object))) = New Dictionary(Of String, List(Of Action(Of Object)))()
Public Shared Sub Register(token As String, callback As Action(Of Object))
If Not pl_dict.ContainsKey(token) Then
Dim list = New List(Of Action(Of Object))()
list.Add(callback)
pl_dict.Add(token, list)
Else
Dim found As Boolean = False
For Each item As var In pl_dict(token)
If item.Method.ToString() = callback.Method.ToString() Then
found = True
End If
Next
If Not found Then
pl_dict(token).Add(callback)
End If
End If
End Sub
Public Shared Sub Unregister(token As String, callback As Action(Of Object))
If pl_dict.ContainsKey(token) Then
pl_dict(token).Remove(callback)
End If
End Sub
Public Shared Sub NotifyColleagues(token As String, args As Object)
If pl_dict.ContainsKey(token) Then
For Each callback As var In pl_dict(token)
callback(args)
Next
End If
End Sub
End Class
The compiler doesn't like the two For Each <...> As var statements. I'm assuming that this is linq c# style which has always been very difficult to translate with ease. This one has me ostensibly because I'm still trying to fathom out the whole principle anyway. Can anyone suggest a proper construct for the two lines in question.
Thanks
In VB, the equivalent of var is to simply declare the variable without specifying the type, for instance:
For Each callback In pl_dict(token)
callback(args)
Next
However, in order for that to work, you need to have Option Infer On. Alternatively, you could just specify the type of the iterator variable as whatever it actually is (in this case, Action(Of Object)), like this:
For Each callback As Action(Of Object) In pl_dict(token)
callback(args)
Next
This is the way properties are defined in C# language.
In C# unlike in PHP, class properties are not simple variables and when you set or get their values, accessor functions are called. So you can lock a property from being changed after initialization. In php it seems without function name followed by parentheses you can't call such value. Is there any similar concept in PHP for that?
Not yet, but "maybe" in future versions of PHP.
RFC: https://wiki.php.net/rfc/propertygetsetsyntax
Magic _get/_set and "overloading", are various cases of code smell.
It's possible to have get and set methods in PHP using the __get and __set magic methods (though the implementation is different from C#)
class A {
protected $test_int;
function __construct() {
$this->test_int = 2;
}
function __get($prop) {
if ($prop == 'test_int') {
echo 'test_int get method<br>';
return $this->test_int;
}
}
function __set($prop, $val) {
if ($prop == 'test_int') {
echo 'test_int set method<br>';
//$this->test_int = $val;
}
}
}
$obj = new A();
$obj->test_int = 3; //Will echo 'test_int set method'
echo $obj->test_int; //Will echo 'test_int get method' and then the value of test_int.
If you want to "lock" a property's value, simply do:
function __set($prop, $val) {
if ($prop == 'test_int') {
//Do nothing
}
}
I don't understand what you are meaning.
But if you'r talking about getters and setters, you can simply declare your var as private and make a public method to get the value.
private $lol;
public getlol(){
return $this->lol;
}
But if you'r talking about contants you need try it:
define("MAXSIZE", 100);
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 using Microsoft WebTest and want to be able to do something similar to NUnit's Assert.Fail(). The best i have come up with is to throw new webTestException() but this shows in the test results as an Error rather than a Failure.
Other than reflecting on the WebTest to set a private member variable to indicate the failure, is there something I've missed?
EDIT: I have also used the Assert.Fail() method, but this still shows up as an error rather than a failure when used from within WebTest, and the Outcome property is read-only (has no public setter).
EDIT: well now I'm really stumped. I used reflection to set the Outcome property to Failed but the test still passes!
Here's the code that sets the Oucome to failed:
public static class WebTestExtensions
{
public static void Fail(this WebTest test)
{
var method = test.GetType().GetMethod("set_Outcome", BindingFlags.NonPublic | BindingFlags.Instance);
method.Invoke(test, new object[] {Outcome.Fail});
}
}
and here's the code that I'm trying to fail:
public override IEnumerator<WebTestRequest> GetRequestEnumerator()
{
this.Fail();
yield return new WebTestRequest("http://google.com");
}
Outcome is getting set to Oucome.Fail but apparently the WebTest framework doesn't really use this to determine test pass/fail results.
Set the Outcome property to Fail:
Outcome = Outcome.Fail;
There's also an Assert.Fail() in the Microsoft.VisualStudio.QualityTools.UnitTestFramework assembly.
The Outcome property will set the public at vsts 2010 :-)
You make a test always fail by adding a validation rule that always fails. For example, you could write a fail validation rule like this:
public class FailValidationRule : ValidationRule
{
public override void Validate(object sender, ValidationEventArgs e)
{
e.IsValid = false;
}
}
Then attach the new validation rule you your webtest's ValidateResponse event, like so:
public class CodedWebTest : WebTest
{
public override IEnumerator<WebTestRequest> GetRequestEnumerator()
{
WebTestRequest request1 = new WebTestRequest("http://www.google.com");
FailValidationRule failValidation = new FailValidationRule();
request1.ValidateResponse += new EventHandler<ValidationEventArgs>(failValidation.Validate);
yield return request1;
}
}
A solution that would work in declarative tests (as well as coded) is:
write a Validation Rule that fails when a certain Context Parameter (e.g. 'FAIL') is present in the Context
when you want to trigger the failure, set the Context Parameter and call WebTest.Stop()
add the Validation Rule as a WebTest-level rule (not request-level) so that it runs on all requests
I think that's as concise as it can be done.
First off, I'm working with VB.net, but I also tried to set the outcome to fail before finding out it does not work (which brought me here).
I finally managed to do it by just throwing an exception :
Public Overrides Sub PostRequest(ByVal sender As Object, ByVal e As PostRequestEventArgs)
If YourTest = True Then
Throw New WebTestException("My test Failed")
End If
MyBase.PostRequest(sender, e)
End Sub
I know this topic is old but I hope it helps someone anyway :)
Set the value of Outcome in the PostWebTest event handler.