I'm trying to implement a stopwatch method in my soap program. The method will start the stopwatch and stop the stopwatch once the program has loaded and I want to display the time elapsed between starting and stopping on the asmx page.
below is my code that im trying to implement the stop watch method on:
public class WebService1 : System.Web.Services.WebService
{
static private Authenticator auth = new Authenticator();
Stopwatch sw = new Stopwatch();
[WebMethod]
public string Authenticate(string username, string password)
{
sw.Start();
if (string.IsNullOrWhiteSpace(username) && string.IsNullOrWhiteSpace(password))
{
return "Please enter a username and password";
}
if (string.IsNullOrWhiteSpace(username))
{
return "Please enter your username!";
}
if (string.IsNullOrWhiteSpace(password))
{
return "Please enter your password!";
}
//Assigning the username and password variables to a bool called isvalid
bool isvalid = auth.authenticated(username, password);
{
if (isvalid)//Not using == because im not comparing
{
return "Authenticated!";
}
else
{
return "Not Authenticated!";
}
}
sw.Stop();
long time = sw.ElapsedMilliseconds;
return time.ToString();
// long time = sw.ElapsedMilliseconds;
// return time.ToString();
}
}
}
My question is - Is it possible to do what I am asking and if so is what I have so far correct because it won't work! (Yes I know .asmx is legacy)
Your code isn't being hit after the return statement is hit. You just have to set your message to a variable and return it at the end of the method you're calling.
To my understanding, return is where your method call is halted. No further processing occurs.
How to return the elapsed time is up to you. You can pass a long variable byref in the function, return an object from the method, XML, a string with a specific structure that you can break apart afterwards (something like "value to return|elapsed time"), etc.