Checking if a user inputed string is in an array - c#

So this is more than just checking if a user input string in an array because if the string is actually in the array and the bool returns true I want it to write some custom text.
{
static void Main(string[] args)
{
string[] name= {"Bob","Bob2","Bob3","Bob4"};
bool exists = name.Contains(string userName= Console.ReadLine());
if (exists == true)
Console.WriteLine("Hi " + userName);
Console.ReadLine();
}
}
I know I can't run the code like this but I'm looking for a similar way to run it but I'm not sure how to store user input and still have the bool check if the user inuputed string is in the string array.

you almost had it, just move the userName assignment up to its own line:
static void Main(string[] args)
{
string[] name = { "Bob", "Bob2", "Bob3", "Bob4" };
string userName = Console.ReadLine();
bool exists = name.Contains(userName);
if (exists == true)
Console.WriteLine("Hi " + userName);
Console.ReadLine();
}
here is the output:

Just declare your input variable outside of te Contains check:
static void Main(string[] args)
{
string[] name= {"Bob","Bob2","Bob3","Bob4"};
string userName = Console.ReadLine();
bool exists = name.Contains(userName);
if (exists == true)
Console.WriteLine("Hi " + userName);
Console.ReadLine();
}

I came up with this...
import java.util.Scanner;
public class inp {
public static void main (String args[]) {
String[] name = new String[] {
"Ben",
"Sam"
};
int max = name.length;
int current = 0;
boolean is = false;
System.out.println("What name tho?");
Scanner inp = new Scanner(System.in);
String nameInq = inp.next();
while(is == false && current<max) {
if(name[current].equals(nameInq)) {
is = true;
}else {
current++;
}
}
if(is) {
System.out.println("They are in the list");
}else {
System.out.println("nah");
}
}
}
Not quite as efficent but gets the job done.

Related

How can I make an auto injection detector in c#?

I want to make an auto injection scanner in any given website and I have to use c#.
I tried some things that I found online and none of them worked for me, until i find selenium but i keep getting this error message: "OpenQA.Selenium.ElementNotInteractableException: 'element not interactable", and I have no idea why.
I didn't find anything helpful online and I think the problem may be with selenium.
I tried to find SQL, JS and BASH injections, but the script fails when i try to interact with an input. I am using OWASP juice shop to test my code.
This is my code:
static int _crntTypeOfInjection;
const int ESQL = 0, EJS = 1, EBASH = 2;
static public bool IsImportantInput(string type)
{
bool valid = false;
string[] importantTypes = new string[] { "text", "email", "password", "search", "url" };
foreach (string check in importantTypes)
{
if (type == check)
{
return true;
}
}
return false;
}
public static string getCrntInjection()
{
switch (_crntTypeOfInjection)
{
case ESQL:
return "\' OR 1=1;--";
break;
case EBASH:
return "; echo Test";
break;
case EJS:
return "<img src=\"http:\\\\url.to.file.which\\not.exist\" onerror=alert(\"JS injection success\");>";
break;
}
return "defult";
}
static public bool AttackSuccessful(string normalPage, string InjectedPage, string MainUrl, string afterClickUrl)
{
if (afterClickUrl != MainUrl || InjectedPage.Contains("Internal Server Error") || InjectedPage.Contains("JS injection success") || InjectedPage.Contains("Test"))
{
return true;
}
return false;
}
static public void Injection(string url)
{
string InjectedPage = "", NormalPage = "", AfterClickUrl = "";
var driver = new ChromeDriver("C:\\Users\\nirya\\");
driver.Url = url;
Console.WriteLine(driver.PageSource);
Actions a = new Actions(driver);
foreach (var button in driver.FindElements(By.CssSelector("button")))
{
// INJECTED PAGE
a.MoveByOffset(0, 0).Click().Perform();
foreach (IWebElement input in driver.FindElements(By.TagName("input")))
{
Console.WriteLine(input.Text);
Console.WriteLine(input.TagName);
try
{
if (IsImportantInput(input.GetAttribute("type")))
{
input.Click(); // *** HERE IS THE PROBLEM ***
input.Clear();
input.SendKeys(getCrntInjection());
}
}
catch (NoSuchElementException)
{
continue;
}
}
button.Click();
InjectedPage = driver.PageSource;
AfterClickUrl = driver.Url;
driver.Navigate().Back();
// NORMAL PAGE
a.MoveByOffset(0, 0).Click().Perform();
foreach (IWebElement input in driver.FindElements(By.CssSelector("input")))
{
try
{
if (IsImportantInput(input.GetAttribute("type")))
{
input.Clear();
input.SendKeys("normal");
}
}
catch (NoSuchElementException)
{
continue;
}
}
button.Click();
NormalPage = driver.PageSource;
driver.Navigate().Back();
if (AttackSuccessful(NormalPage, InjectedPage, url, AfterClickUrl))
{
// add to database
}
}
}
static void Main(string[] args)
{
Injection("http://localhost:3000/#/login");
}
Is there a problem with my code? Or is there another library that i can use instead?

How to Display the details of a single person from a text file onto the console in C# from a PhoneBook for example?

static void AddContact()
{
string path = #"C:\Users\...\Desktop\Projekte\C# Übungen\ContactList/contacts.txt";
string name, address;
int phoneNumber;
bool addingContact = true;
string response;
List<string> ContactList = File.ReadAllLines(path).ToList();
while(addingContact)
{
System.Console.Write("Name: ");
name = Console.ReadLine();
System.Console.Write("Nummer: ");
phoneNumber = int.Parse(Console.ReadLine());
System.Console.Write("Adresse: ");
address = Console.ReadLine();
ContactList.Add($"Name: {name}");
ContactList.Add($"Nummer: {phoneNumber}");
ContactList.Add($"Adresse: {address} \n---------------------------------");
foreach (var contact in ContactList)
{
File.WriteAllLines(path, ContactList);
}
Console.Clear();
System.Console.WriteLine("Contact added successfully! Would you like to Add another Contact? (y)(n)");
response = Console.ReadLine().ToLower();
if(response == "y")
{
Console.Clear();
}
else
{
addingContact = false;
}
}
Console.WriteLine("Good bye!");
}
static void ShowContact()
{
string path = #"C:\Users\...\Desktop\Projekte\C# Übungen\ContactList/contacts.txt";
string response;
System.Console.WriteLine("Would you like to see all contacts (0) or a specific one (1)?");
response = Console.ReadLine();
switch (response)
{
case "0":
File.ReadAllLines(path);
break;
case "1":
System.Console.WriteLine("Type the name of the user: ");
string username = Console.ReadLine();
File.ReadAllLines(path)
break;
}
}
Thats everything. In the switch Statement at case 1 is where the problem is. I want it to look something like this if the user types John for example:
Name: John
Number: 233
Address: lolol 23
I already tried out something but i stopped in the middle of writing it because i realized that i dont actually know how to code that so i made my way over to stackoverflow to ask for help, thanks. Please be polite and i know that this code isnt the best, im a beginner.
Edit: I just found out that ShowContacts doesnt work at all
Edit 2: Fixed it with a foreach loop and List
List<string> contacts = File.ReadAllLines(path).ToList();
System.Console.WriteLine("Would you like to see all contacts (0) or a specific one (1)?");
response = Console.ReadLine();
switch (response)
{
case "0":
foreach (var contact in contacts)
{
Console.WriteLine(contact);
}
break;
}
Okay, if each item is broken down by three values consider chunking the data by three than iterate the results.
Change the Debug.WriteLine to Console.WriteLine below for your code.
Extension method for chunking
public static class ListExtensions
{
public static List<List<T>> ChunkBy<T>(this List<T> source, int chunkSize)
=> source
.Select((value, index) => new { Index = index, Value = value })
.GroupBy(x => x.Index / chunkSize)
.Select(grp => grp.Select(v => v.Value).ToList())
.ToList();
}
File contents
John
111
John's address
Mary
222
Mary's address
Bill
333
Bill's address
Code to first assert data is divisible by three than read the data, no assertion of data types or if null values are performed.
var contents = File.ReadAllLines("TextFile1.txt");
if (contents.Length % 3 == 0)
{
var results = contents.ToList().ChunkBy(3);
foreach (var list in results)
{
Debug.WriteLine($" Name: {list[0]}");
Debug.WriteLine($" Number: {list[1]}");
Debug.WriteLine($"Address: {list[2]}");
}
}
else
{
Debug.WriteLine("Malformed");
}
Edit: placed into a method
private static void ViewAllContacts()
{
var fileName = "TextFile1.txt";
if (File.Exists(fileName))
{
var contents = File.ReadAllLines(fileName);
if (contents.Length % 3 == 0)
{
var results = contents.ToList().ChunkBy(3);
foreach (var list in results)
{
Debug.WriteLine($" Name: {list[0]}");
Debug.WriteLine($" Number: {list[1]}");
Debug.WriteLine($"Address: {list[2]}");
}
}
else
{
Debug.WriteLine("Malformed");
}
}
else
{
Debug.WriteLine($"{fileName} not found");
}
}
Save your contact to json format, like this:
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.IO;
namespace JsonTester
{
// Open Package Manager Console:
// Tools >> Nuget Package Manager >> Package Manager Console
//
// Install libraries through Package Manager Console:
// PM > Install-Package System.Text.Json -Version 6.0.1
internal class Program
{
static List<Contact> contactList = new List<Contact>();
static readonly string MY_CONTACT = #"D:\MyContact.txt";
class Contact {
public string Name { get; set; }
public string Number { get; set; }
public string Address { get; set; }
}
static void EnterContact() {
var contact = new Contact();
Console.WriteLine("Name: ");
contact.Name = Console.ReadLine();
Console.WriteLine("Number: ");
contact.Number = Console.ReadLine();
Console.WriteLine("Address: ");
contact.Address = Console.ReadLine();
contactList.Add(contact);
}
static void SaveContact() {
if (contactList.Count > 0) {
foreach (Contact contact in contactList) {
String strContactJson = JsonSerializer.Serialize(contact);
File.AppendAllText(MY_CONTACT, strContactJson + "\n");
}
}
}
static void ReadContact()
{
try
{
Console.WriteLine("Read contact list:\n");
String[] strContactJsonArr = File.ReadAllLines(MY_CONTACT);
if (strContactJsonArr.Length > 0)
{
foreach (String s in strContactJsonArr)
{
Contact contact = JsonSerializer.Deserialize<Contact>(s);
if (contact != null)
{
Console.WriteLine("Name: " + contact.Name);
Console.WriteLine("Number: " + contact.Number);
Console.WriteLine("Address: " + contact.Address);
Console.WriteLine("");
}
}
Console.WriteLine("Found {0} contacts\n\n", strContactJsonArr.Length);
}
}
catch (Exception) {
Console.WriteLine("Contact list is empty\n");
}
}
static bool SearchContact(String name)
{
try
{
String[] strContactJsonArr = File.ReadAllLines(MY_CONTACT);
if (strContactJsonArr.Length > 0)
{
foreach (String s in strContactJsonArr)
{
Contact contact = JsonSerializer.Deserialize<Contact>(s);
if (contact != null)
{
if (contact.Name.Equals(name)) {
Console.WriteLine("");
Console.WriteLine("Name: " + contact.Name);
Console.WriteLine("Number: " + contact.Number);
Console.WriteLine("Address: " + contact.Address);
Console.WriteLine("");
return true;
}
}
}
}
}
catch (Exception)
{
}
return false;
}
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("- Press S for search contact.\n- Press N for new contact.\n- Press R for read contact list.\n");
ConsoleKeyInfo key = Console.ReadKey(true);
if (key.KeyChar == 's' || key.KeyChar == 'S')
{
Console.WriteLine("Searching contact.");
Console.Write("Enter name: ");
String name = Console.ReadLine();
bool isFounded = SearchContact(name);
if (isFounded)
{
Console.WriteLine("Contact is found\n");
}
else
{
Console.WriteLine("Contact isn't found!\n");
}
}
else if (key.KeyChar == 'n' || key.KeyChar == 'N')
{
EnterContact();
SaveContact();
}
else if (key.KeyChar == 'r' || key.KeyChar == 'R') {
ReadContact();
}
}
}
}
}
Console Output:
MyContact.txt (contact save in JSON format):

C# Multi threading not starting worker/job?

For some reason my threads are ignoring my job, it looks like anyone have any sort of idea why it is doing this? Help is very welcome and extremely appreciated, thank you. What this program is, is a ProxyChecker, because i've bought a bunch and will continue to do so of proxies with different user/passes etc, however some have expired
static List<String> user = new List<String>();
static List<String> pass = new List<String>();
static List<String> ips = new List<String>();
static Random rnd = new Random();
static void Main(string[] args)
{
int threads = 4;
loadips();
Console.WriteLine("Enter the amount of threads to run (4 default):");
threads = Int32.Parse(Console.ReadLine());
Console.WriteLine("Starting on " + threads + " threads...");
for (int i = 0; i < threads; i++)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(CheckProxy), i);
}
//Console.ReadLine();
}
public class MyIP
{
public string IP { get; set; }
public bool AcceptsConnection { get; set; }
}
private static void CheckProxy(object state)
{
var u = user[0];
var p = pass[0];
var l = new List<MyIP>();
Parallel.ForEach(l.ToArray(), (item) =>
{
string ip = getip();
try
{
using (var client = new ProxyClient(ip, u, p))
{
Console.WriteLine(ip, user, pass);
client.Connect();
item.AcceptsConnection = client.IsConnected;
}
}
catch
{
l.Remove(item);
}
});
foreach (var item in l)
{
if (item.AcceptsConnection == true)
{
WriteToFile(user[0], pass[0]);
}
Console.WriteLine(item.IP + " is " + (item.AcceptsConnection) + " accepts connections" + " doesn not accept connections");
}
}
private static void loadips()
{
using (TextReader tr = new StreamReader("ips.txt"))
{
string line = null;
while ((line = tr.ReadLine()) != null)
{
ips.Add(line);
}
}
}
You didn't understand my code example... You should add the IP's to the list l, instead of a getip() method... So lose the getip() method
private static void CheckProxy(object state)
{
var u = user[0];
var p = pass[0];
var l = new List<MyIP>();
l.Add(new MyIP { IP = "192.168.1.1" });
l.Add(new MyIP { IP = "192.168.1.2" });
l.Add(new MyIP { IP = "192.168.1.3" });
Parallel.ForEach(l.ToArray(), (ip_item) =>
{
try
{
using (var client = new ProxyClient(ip_item, u, p))
{
Console.WriteLine(ip_item, user, pass);
client.Connect();
item.AcceptsConnection = client.IsConnected;
}
}
catch
{
lock(l)
l.Remove(item);
}
});
foreach (var item in l)
{
if (item.AcceptsConnection == true)
{
WriteToFile(user[0], pass[0]);
}
Console.WriteLine(item.IP + " is " + (item.AcceptsConnection) + " accepts connections" + " doesn not accept connections");
}
}

how get customer first name and last name

I'm wondering how to change this code to get first name and last name. My friend and I develop this code but I need to alter this code. There is Customer class as well where I set their properties. So looking for suggestion to alter this:
//Getting No: Of Customers for user wish to enter data.
do
{
needToGetInputFromUser = false;
Console.WriteLine("Please enter customer name");
customerName = Console.ReadLine();
if (customerName.Length < 5 || customerName.Length > 20)
{
Console.WriteLine("Invalid name length, must be between 5 and 20 characters");
Console.WriteLine("Please try again.");
Console.WriteLine(" ");
needToGetInputFromUser = true;
}
else
{
isUserEnteredValidInputData = true;
}
} while (needToGetInputFromUser);
//Getting Account number
My approach is slightly different from everyone else's, Where I ask for first name first, then last name. Here is the Customer class:
class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName { get { return FirstName + " " + LastName; } }
}
Basically I create a Customer object then set the FirstName and LastName based on user input individually like so:
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var customer = new Customer();
customer.FirstName = GetStringValueFromConsole("Customer First Name");
customer.LastName = GetStringValueFromConsole("Customer Last Name");
Console.WriteLine("New Customers name: " + customer.FullName);
Console.WriteLine("Finished");
Console.ReadLine();
}
private static string GetStringValueFromConsole(string valueToAskFor)
{
var needToGetInputFromUser = false;
var stringValue = string.Empty;
do
{
Console.WriteLine("Please enter " + valueToAskFor);
stringValue = Console.ReadLine();
if (stringValue.Length < 5 || stringValue.Length > 20)
{
Console.WriteLine("Invalid \"" + valueToAskFor + "\", must be between 5 and 20 characters");
Console.WriteLine("Please try again.");
Console.WriteLine(" ");
needToGetInputFromUser = true;
}
else
{
needToGetInputFromUser = false;
}
} while (needToGetInputFromUser);
return stringValue;
}
}
}
List<Customer> ListOfCustomer = new List<Customer> ();
do
{
needToGetInputFromUser = false;
Console.WriteLine("Please enter customer name");
customerName = Console.ReadLine();
if (customerName.Length < 5 || customerName.Length > 20)
{
Console.WriteLine("Invalid name length, must be between 5 and 20 characters");
Console.WriteLine("Please try again.");
Console.WriteLine(" ");
needToGetInputFromUser = true;
}
else
{
Customer c = new Customer();
c.Name = customerName;
ListOfCustomer.Add(c);
isUserEnteredValidInputData = true;
}
} while (needToGetInputFromUser);
int CustomerCount = ListOfCustomer.Count;
I assume you get a string like:
Brian Mains
And you want to split by the " " between Brian and Mains, storing it in first/last name in the Customer object right? I think you are trying to do something like:
Customer c = new Customer();
if (customerName.Contains(" ")) {
var terms = customerName.Split(' ');
if (terms.Length == 2) {
c.FirstName = terms[0];
c.LastName = terms[1];
}
else {
//TBD
}
}

Checking string with custom format in c#

I'm creating a command system for my application but i don't know how to make c# recognize a pattern in my string.
Example:
add(variable1, variable2)
How to make c# recognize addUser(...) and do some stuff?
I'm currently using string contains but if user type add()()()()() or add((((((, it still work!
Please help!
sorry about my english!
This may not be perfect, but might give you some ideas :)
static void Main(string[] args)
{
string example_input = "xxxxx Add(user1, user2) xxxxxx";
string myArgs = getBetween2(example_input, "Add(", ")"); //myArgs = "user1, user2"
if (myArgs != "EMPTY")
{
myArgs = myArgs.Replace(" ", ""); // remove spaces... myArgs = "user1,user2"
string[] userArray = myArgs.Split(',');
foreach (string user in userArray)
{
Console.WriteLine(user);
//Your code here
}
}
Console.ReadKey(); //pause
}
static string getBetween2(string strSource, string strStart, string strEnd)
{
try
{
int Start, End;
if (strSource.Contains(strStart) && strSource.Contains(strEnd))
{
Start = strSource.IndexOf(strStart, 0) + strStart.Length;
End = strSource.IndexOf(strEnd, Start);
return strSource.Substring(Start, End - Start);
}
else
{
return "EMPTY";
}
}
catch
{
return "EMPTY";
}
}

Categories

Resources