No overload for method 'run' takes 1 arguments - c#

I'm creating an operating system in COSMOS when I was running into this little problem.
else if (HOLOOS.seperate(MyGlobals.input, 5) == "login")
{
if (MyGlobals.input == "login")
{
Console.Write(Commands.login.usage);
}
else
{
var arg = HOLOOS.rseperate(MyGlobals.input, 6, (MyGlobals.input.Length - 1));
arg = HOLOOS.GatherArgs(arg);
login.run(arg);
}
}
This is the login class.. I guess something is wrong with the public static void run?
class login
{
public static string CurrentUser;
public static void run(string EnteredUser, string EnteredPassword, string User1CorrectName, string User1CorrectCode, string User2CorrectName = "", string User2CorrectCode = "")
{
string EnteredHashedPassword = BashUtils.Encrypt(EnteredPassword);
//Check if the user name is
if (EnteredUser == User1CorrectName)
{
//If the user name entered is jacob, then check if the password is OK
if (EnteredHashedPassword == BashUtils.Encrypt(User1CorrectCode))
{
//If password is okay than login
Console.Write("You have sucessfully logged in as " + User1CorrectName);
CurrentUser = User1CorrectName;
cd.Path = "D:\\" + User1CorrectName + "\\";
}
//If the password is not OK then say so
else
{
Console.Write("Not correct password for " + User2CorrectName);
}
}

You are passing one argument in this line:
login.run(arg);
to the method run()
when the signature of the method is this:
public static void run(string EnteredUser, string EnteredPassword, string User1CorrectName, string User1CorrectCode, string User2CorrectName = "", string User2CorrectCode = "")
As you can see, the first 4 parameters are mandatory, so you should pass them to the function. Or modified run's signature.
The last 2 parameters have a default value, the empty string "". So, you could not pass those values if you don't need them (this will be assigned with the default value if you don't pass it as an argument).
Read this documentation for parameters and default values MSDN for a complete description with many examples.
I would definitely go with named parameters in that case, but this is just an opinion. Read the docs, if you don't understand something just ask.

Related

Visual Studio Load Test redirect URL from Siteminder

I have a security application called Siteminder. It creates unique URLS for every authentication. HTTPS://SITE/idp/**RANDOMURLSTRING**/resumeSAML20/idp/startSSO.ping
How can i capture the Unique URL and have the test continue to login.
A webtest assumes the next URL in the process. It does not support[Or I don't know how] a unique redirect to a random URL. Does anyone know of a way to handle this case?
EDIT:
My Solution -- Replace the SessionID with {{SessionID}} in all the URLS and use this extraction rule
public class ExtractSiteMinderCustomUrl : ExtractionRule
{
public string SiteMinderSessionID { get; private set; }
// The Extract method. The parameter e contains the web performance test context.
//---------------------------------------------------------------------
public override void Extract(object sender, ExtractionEventArgs e)
{
//look for anchor tags with URLS
Regex regex = new Regex("<a\\s+(?:[^>]*?\\s+)?href=\"([^\"]+\\?[^\"]+)\"");
MatchCollection match = regex.Matches(e.Response.BodyString);
if (match.Count > 0)
{
foreach (Match ItemMatch in match)
{
if (ItemMatch.ToString().Contains("/idp/"))
{
//start and ends string from the sitemindersession is in the link on the page
e.WebTest.Context.Add(this.ContextParameterName, GetStringBetween(ItemMatch.ToString(), "/idp/", "/resume"));
e.Success = true;
return;
}
}
e.Success = false;
e.Message = String.Format(CultureInfo.CurrentCulture, "Not Found in Link : /idp/");
}
else
{
e.Success = false;
e.Message = String.Format(CultureInfo.CurrentCulture, "No href tags found");
}
}
public static string GetStringBetween(string token, string first, string second)
{
if (!token.Contains(first)) return "";
var afterFirst = token.Split(new[] { first }, StringSplitOptions.None)[1];
if (!afterFirst.Contains(second)) return "";
var result = afterFirst.Split(new[] { second }, StringSplitOptions.None)[0];
return result;
}
}
The simple answer is to have use extraction rule that gets the **RANDOMURLSTRING** then change the URLs in the requests to be, for example, HTTPS://SITE/idp/{{TheRandomString}}/resumeSAML20/idp/startSSO.ping where TheRandomString is the context parameter that holds the extracted value. Note the doubled curly braces ({{ and }}) around the context parameter.
Suppose a value returned by the first redirection needs to be captured but a normal web test would redirect again and so the response is not seen by the extraction rules. In this case need to handle the redirect explicitly. Set the Follow redirects property of the initial request to false then add extraction rule(s) to gather the wanted values. Add a new request after the initial request and use the extracted values in it as necessary. It is possible to extract the entire redirected url and set the Url field to the extracted value.

C#: What is the reason of not detecting if testcase failed

I am trying to detect if my testcase failed that it should do some process which I have mentioned it in my code below. I am successfully able to detect when my testcase passed.
I have added my code. My code here does is to navigate to google homepage if it passed then I should get a txt file with a "[MethodName] - Passed.txt" with a text in it Passed. Same for fail.
[Test]
public void Initialize()
{
PropertiesCollection.driver = new TWebDriver();
LoginPageObject objLogin = new LoginPageObject();
string pathfile = #"file location";
string sheetName = "Login";
var excelFile = new ExcelQueryFactory(pathfile);
var abc = from a in excelFile.Worksheet(sheetName).AsEnumerable()
where a["ID"] == "3"
select a;
foreach (var a in abc)
{
PropertiesCollection.driver.Navigate().GoToUrl(a["URL"]);
}
foreach (var a in abc)
{
objLogin.Login(a["uname"], a["paswd"]);
}
StackFrame stackFrame = new StackFrame();
MethodBase methodBase = stackFrame.GetMethod();
string Name = methodBase.Name;
GetFiles(Name);
}
public void GetFiles(string testcase)
{
if ((TestContext.CurrentContext.Result.Status == TestStatus.Failed) || (TestContext.CurrentContext.Result.State == TestState.Failure) || (TestContext.CurrentContext.Result.State == TestState.Ignored) || (TestContext.CurrentContext.Result.State == TestState.Error))
{
string destpath = (#"destination location");
File.WriteAllText(Path.Combine(destpath, testcase + " - Failed" + ".txt"), "Failed");
}
else
{
string destpath = (#"destination location");
File.WriteAllText(Path.Combine(destpath, testcase + " - Passed" + ".txt"), "Passed");
}
}
Here, only else condition is identified but not with if condition.
Question: Can anyone identify what part I am missing for fail test case.
Note:
Please forgive me if I have not explained properly. If you donot understand please ask question.
For each part is actually an error. If there is an error it should create a txt file as per my code in GetFiles(string testcase) which I am unable to do so.
I am using Nunit to identify whether my test case passed or fail. So if testcase passes or fails a text is created mentioning that to keep a record of my failed test case.
Appreciate your help.
If a test fails, the [Test] method is terminated, and the rest of the method never run. So, if your test were to fail mid-way through, GetFiles() would never be called.
You probably mean to run GetFiles() as a [TearDown] to achieve what you're trying to do.
As an aside, I'd recommend doing:
TestContext.CurrentContext.Result.Status != TestStatus.Success
rather than you current if - as you seem to have found already, there are many different varieties of failure!
It looks like you have a typo. Your if statement can never be true as written. You want an 'or' instead of an 'and'
if ((TestContext.CurrentContext.Result.Status == TestStatus.Failed) ||
(TestContext.CurrentContext.Result.State == TestState.Failure) ||
(TestContext.CurrentContext.Result.State == TestState.Ignored) || // <-- typo?
(TestContext.CurrentContext.Result.State == TestState.Error))
{

How to read and create new user by every 4th line

So, I read a text file. It looks like this:
TEACHER - TEACHER/STUDENT
adamsmith - ID
Adam Smith - Name
B1u2d3a4 - Password
STUDENT
marywilson
Mary Wilson
s1Zeged
TEACHER
sz12gee3
George Johnson
George1234
STUDENT
sophieb
Sophie Black
SophieB12
And so on, there are all the users.
The user class:
class User
{
private string myID;
private string myName;
private string myPW;
private bool isTeacher;
public string ID
{
get
{
return myID;
}
set
{
myID = value;
}
}
public string Name
{
get
{
return myName;
}
set
{
myName = value;
}
}
public string PW
{
get
{
return myPW;
}
set
{
PW = value;
}
}
public bool teacher
{
get
{
return teacher;
}
set
{
isTeacher = value;
}
}
public override string ToString()
{
return myName;
}
}
The Form1_Load method:
private void Form1_Load(object sender, EventArgs e)
{
List<User> users = new List<User>();
string line;
using (StreamReader sr = new StreamReader("danet.txt"))
{
while ((line=sr.ReadLine())!=null)
{
User user = new User();
user.ID=line;
user.Name=sr.ReadLine();
user.PW=sr.ReadLine();
if(sr.ReadLine=="TEACHER")
{
teacher=true;
}
else
{
teacher=false;
}
users.Add(user);
}
}
}
I want to read the text and store the informations. By this method I get 4 times more user than I should. I was thinking of using for and a couple of things, but I didn't get to a solution.
New answer
Your reader assumes the every fourth line is the user-id, it is not, the absolute first line is a STUDENT/TEACHER line. Either this is a typo, or you have to change your format.
Your PW property will cause a StackOverflowException,
public string PW
{
get
{
return myPW;
}
set
{
PW = value;
}
}
Change the setter to myPW = value;, or just convert them to auto-properties.
Your teacher property has the same error, but on the getter.
You have also missed the () on one of your ReadLine's, but let's just assume this is a typo.
Not using a text-file, but just a string so I'm using a StringReader instead, but it's the same concept.
string stuff =
#"adamsmith
Adam Smith
B1u2d3a4
STUDENT
marywilson
Mary Wilson
s1Zeged
TEACHER
sz12gee3
George Johnson
George1234
STUDENT
sophieb
Sophie Black
SophieB12
STUDENT";
public void Main(string[] args)
{
string line;
var users = new List<User>();
using (var sr = new StringReader(stuff))
{
while ((line = sr.ReadLine()) != null)
{
User user = new User();
user.ID = line;
user.Name = sr.ReadLine();
user.PW = sr.ReadLine();
user.teacher = sr.ReadLine() == "TEACHER";
users.Add(user);
}
}
}
Old answer
There is nothing inherently erroneous with you code. But since you have not provided an actual example of what your "danet.txt" looks like, one must assume the error lies within the data itself.
Your "parser" (if you want to call it that) is not forgiving, i.e. if there is an empty line in your source file or if you just mess up one line (say forget putting in a password or ID) then everything would get offset – but as far as your "parser" is concerned, nothing is wrong.
By default formats which depend on "line positions" or "line offset" are prone to break, especially if the file itself is created by hand versus being auto-generated.
Why not use a denoted format instead? Such as XML, JSON or even just INI. C# can handle either of these, either built in or by external libraries (see the links).
There will never be any way for your "line-by-line" parser to not break if the user makes a faulty input, that is unless you have very strict formats for IDs, names, passwords and "student/teachers". and then validate them, using regular expressions (or similar). But that would defeat the purpose of a simple "line-by-line" format. And by then, you might as well go with a more "complex" format.
while ((line=sr.ReadLine())!=null)
{
User user = new User();
for (int i = 0; i < 4; i++)
{
switch (i)
{
case 1:
user.ID = line;
break;
case 2:
user.Name=sr.ReadLine();
break;
....
}
}
}

command line variable/string

My code looks something like this, but I have shortened it a little.
public static void mainvoid()
{
string line = Console.ReadLine().ToLower();
if (line == "restart")
{
Console.Clear();
Main();
}
if (line == "enter a value: ")
{
string value = console.ReadLine();
console.writeline("Your value is {0}", value);
mainvoid();
}
if (line == "my name")
{
Console.WriteLine("Your name is {0}", ConsoleApplication1.Properties.Settings.Default.name);
mainvoid();
}
I want my program to pick up a command (witch I have done) and some of them have values/strings after them E.g.
By the way I am using c# 2010
I want my command to look like this
My name is Daniel
and so the string/value = Daniel
or
name = billy
so the string/value = billy
So I want it to pick it up via console.readline(); and pick out that it is changing the name and after that will be the name in which it will be changed to.
But I don't know how to make the last bit the value/string that I can also use.
Please leave a comment if you can help me :)
You probably need to come up with your own syntax.
For e.g i have chosen a syntax like below
<Command Name>:Parameters
ChangeName:Daniel
Then have a enum to define your commands
enum Command
{
ChangeName
}
//Now we can parse the command and take a required action
//Split the string
String[] inputs= Console.ReadLine().Split(":");//"ChangeName:Bob"
//Generate the enumeration type from the input command
var cmd = (Command) Enum.Parse(typeof(Command), inputs[0] , false);
if(cmd == Command.ChangeName)
{
//Process the parameters in inputs[1]
}
I can see that there are two issues here, one is extracting the persons name from the "my name is xyz" command, the other is saving that value for later in the program.
Because of the way you've structured your mainmethod, and the fact that it calls itself (this is called recursion), it cannot share any variables from one call to the next. This makes it impossible to store the persons name. You could eliminate the recursion by instead creating a loop in the mainmethod
static public void Main()
{
string currentLine;
do
{
currentLine = Console.ReadLine();
}
while (!currentLine.Equals("exit"))
}
This will continuously allow the user to enter commands, and the program will terminate when the user enters "exit".
Now onto the problem of storing the users name, you can simply remove the "my name is" part of the sentence to get the users name...
static public void Main()
{
string username = "Matthew";
string currentLine;
do
{
currentLine = Console.ReadLine();
if (currentLine.Equals("restart"))
{
Console.Clear();
}
if (currentLine.StartsWith("my name is"))
{
username = currentLine.Replace("my name is ", "");
}
if (currentLine.Equals("my name"))
{
Console.WriteLine("Your name is {0}", username);
}
}
while (!currentLine.Equals("exit"))
}
I hope that gets you moving!
If you don't want to pick up command by Console.ReadLine() pick it with Console.ReadKey(true). Your text won't change.
Here is example:
ConsoleKeyInfo ck = Console.ReadKey(true);
if(ck.Key == Keys.Space){
//do something
}
I didn't understand you well, but I'll try guess :)
If you want to retrive the name, you may write like this:
Console.Write("Your name is ");
string name = Console.ReadLine();

How to get the source file name and the line number of a type member?

Considering that the debug data file is available (PDB) and by using either System.Reflection or another similar framework such as Mono.Cecil, how to retrieve programmatically the source file name and the line number where a type or a member of a type is declared.
For example, let's say you have compiled this file into an assembly:
C:\MyProject\Foo.cs
1: public class Foo
2: {
3: public string SayHello()
4: {
5: return "Hello";
6: }
7: }
How to do something like:
MethodInfo methodInfo = typeof(Foo).GetMethod("SayHello");
string sourceFileName = methodInfo.GetSourceFile(); // ?? Does not exist!
int sourceLineNumber = methodInfo.GetLineNumber(); // ?? Does not exist!
sourceFileName would contain "C:\MyProject\Foo.cs" and sourceLineNumber be equal to 3.
Update: System.Diagnostics.StackFrame is indeed able to get that information, but only in the scope of current executing call stack. It means that the method must be invoked first. I would like to get the same info, but without invoking the type member.
Up to date method:
private static void Log(string text,
[CallerFilePath] string file = "",
[CallerMemberName] string member = "",
[CallerLineNumber] int line = 0)
{
Console.WriteLine("{0}_{1}({2}): {3}", Path.GetFileName(file), member, line, text);
}
New Framework API which populates arguments (marked with special attributes) at runtime,
see more in my answer to this SO question
Using one of the methods explained above, inside the constructor of an attribute, you can provide the source location of everything, that may have an attribute - for instance a class. See the following attribute class:
sealed class ProvideSourceLocation : Attribute
{
public readonly string File;
public readonly string Member;
public readonly int Line;
public ProvideSourceLocation
(
[CallerFilePath] string file = "",
[CallerMemberName] string member = "",
[CallerLineNumber] int line = 0)
{
File = file;
Member = member;
Line = line;
}
public override string ToString() { return File + "(" + Line + "):" + Member; }
}
[ProvideSourceLocation]
class Test
{
...
}
The you can write for instance:
Console.WriteLine(typeof(Test).GetCustomAttribute<ProvideSourceLocation>(true));
Output will be:
a:\develop\HWClassLibrary.cs\src\Tester\Program.cs(65):
you might find some help with these links:
Getting file and line numbers without deploying the PDB files
also found this following post
"Hi Mark,
The following will give you the line number of your code (in the
source file):
Dim CurrentStack As System.Diagnostics.StackTrace
MsgBox (CurrentStack.GetFrame(0).GetFileLineNumber)
In case you're interested, you can find out about the routine that you're
in, as well as all its callers.
Public Function MeAndMyCaller As String
Dim CurrentStack As New System.Diagnostics.StackTrace
Dim Myself As String = CurrentStack.GetFrame(0).GetMethod.Name
Dim MyCaller As String = CurrentStack.GetFrame(1).GetMethod.Name
Return "In " & Myself & vbCrLf & "Called by " & MyCaller
End Function
This can be very handy if you want a generalised error routine because it
can get the name of the caller (which would be where the error occurred).
Regards,
Fergus
MVP [Windows Start button, Shutdown dialogue]
"

Categories