Reading first 3 numbers in a 13 digit control number in c# - c#

I have a program that generates a control number. Control number contains 13 numbers. The first 3 numbers is generated if the user is a maritime education, it is 100, but if the user is a general education, it is 101, then the following 5 numbers is a random numbers. Then the last 5 digits is the ID number of the user.
Code :
Random rand = new Random();
int startingDigits;
if (CmbEducation.SelectedItem.Equals("Maritime Education"))
{
startingDigits = 100;
string IdNumber = TxtIDnum.Text;
string controlNumber = string.Format("{0}{1}{2}",
startingDigits, rand.Next(10000, 99999).ToString(), IdNumber);
TxtControlNum.Text = controlNumber;
}
else if (CmbEducation.SelectedItem.Equals("General Education"))
{
startingDigits = 101;
string IdNumber = TxtIDnum.Text;
string controlNumber = string.Format("{0}{1}{2}",
startingDigits, rand.Next(10000, 99999).ToString(), IdNumber);
TxtControlNum.Text = controlNumber;
}
My problem is, I want to make an if..else condition. but i want to read the first 3 numbers of the control number how do i do it? Thanks :)
edited :
I am using the control number in another form now for password. So i want to read the first 3 numbers to get if the user is a marine education or a general education.
Now, I am in another form, i just copied the text from the login page where the password is the control number to the textbox in another form. so how do i read first 3 numbers inside a textbox?

Not sure if I'm reading your question correctly, but if all you need is to read the first three digits, just do:
var start = new String(controlNumber.Take(3).ToArray());
or
var start = controlNumber.Substring(0,3);
It's not clear what you mean by "read inside a textbox". Do you want to read them from a textbox? Then try:
TextboxName.Text.Substring(0,3);
If you want to place them in a textbox, use:
TextboxName.Text = controlNumber.Substring(0,3);
Update: I'll give this one more try. This should be self-explanatory, assuming you've got start as above:
if (start.Equals("100"))
{
// Do something
}
else if (start.Equals("101"))
{
// Do something else
}
else
{
// ...take a nap?
}

var controlNumberPrefix = myTextBox.Text.Substring(0, 3);
switch (controlNumberPrefix)
{
case "100":/* Maritime education - do something */ ; break;
case "101":/* Gen education - do something */ ; break;
}
or
var controlNumberPrefix = myTextBox.Text.Substring(0, 3);
if(controlNumberPrefix == "100")
// Do something
else if (controlNumberPrefix =="101")
// Do something
Edit:
Its the same thing with textbox. Just use the Text property of the textbox.

Related

display user input from do while loop C#

I have some code below that is almost finished, but the last thing I want to do is for the console app to display the number they have gotten from the user
EX: if user input 1, 3, 5
the console will display
The number you have inserted are:
One
Three
Five
Is it possible to do that ?
Thanks
static void Main (string []args)
{
string again;
do
{
Console.Clear();
Console.WriteLine("Insert Random number");
int number = int.Parse(Console.ReadLine());
Console.WriteLine("Would you like to Insert another number ?(Enter Y for yes /Enter any other key to exit)");
again = Console.ReadLine();
} while (again == "Y");
Console.WriteLine("The number you have inserted are: ");
Console.ReadKey();
}
First, you need a place to keep all the numbers you collected. Given this code, you may be expected to use an array, but real code is more likely to use a generic List<int>. Declare it near the beginning of the Main method like this:
List<int> numbers = new List<int>();
Add each number to it after Parse()-ing like this:
numbers.Add(number);
Then, in between the final WriteLine() and ReadKey() calls, you need to loop through the collected numbers:
int i = 0;
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine($"{i+1}. {numbers[i]}");
}
What you won't be able to do in a simple way is convert the digit 1 to the text value One. There's nothing built into C# or .Net to do that part for you. Since this code looks like a learning exercise, I'll leave you to attempt that part on your own.

Use libphonenumber to validate mobile phone number without knowing the country

I have a list (string) of phone numbers from any country.
for example:
var items = new List<string> { "+989302794433", "009891234599882", "+391234567890", "00336615551212"};
at first, I think that every country code length is exactly two number, for example(33: France, 39: Italy, 98: Iran , ...).
using libphonenumber library, you must be pass the regCode for parsing. and because of (in my scenario) I get the list of string(mobile number), then I must be separate country code from number.
foreach (var item in items)
{
int countryCode = 0;
var number = "";
if (item.StartsWith("+"))
{
countryCode = int.Parse(item.Substring(1, 2));
number = item.Substring(3);
}
else if (item.StartsWith("00"))
{
countryCode = int.Parse(item.Substring(2, 2));
number = item.Substring(4);
}
var regCode = phoneUtil.GetRegionCodeForCountryCode(countryCode);
var numberWithRegCode = phoneUtil.Parse(number, regCode);
if (!phoneUtil.IsValidNumber(numberWithRegCode)) continue;
//else ...
}
this code fine worked just for country codes that their length is two numbers!
but after a little time , I knew that some country code length is one number( for example, US: 1) and even three number!.
now, is exists any way using libphonenumber library (or other solutions) to solve this issue?
thanks a lot
The libphonenumber library can find country codes by itself as long as the number starts with a +. So, just replace double zeros at the beginning of a number with a plus. And then let the library decide whether the number is valid on its own.
libphonenumber will on its own know which is the country code following the plus sign (it internally has a list of all the codes) and then apply the rules according to the correct country to decide whether the number is valid.
bool IsValidNumber(string aNumber)
{
bool result = false;
aNumber = aNumber.Trim();
if (aNumber.StartsWith("00"))
{
// Replace 00 at beginning with +
aNumber = "+" + aNumber.Remove(0, 2);
}
try
{
result = PhoneNumberUtil.Instance.Parse(aNumber, "").IsValidNumber;
}
catch
{
// Exception means is no valid number
}
return result;
}
You can use date ftom this package https://www.npmjs.com/package/dialcodes

checking if the user input has changed from the previous input

Hi I am new to programming
I have a masked textbox into which a user inputs an account number, then I have a label which displays the number of users or rather display the number of times the account number has been changed. I.e. as each account number is being entered the customer count should increase.
I don't have an example code because I do not even know where to start
Please show me how to code this, I am using a form in Visual Studio
have it add the input to a list or array, and then you can run a check to see if the array/list contains that input already. If so, do not add the input again, if it does not, then add the input. You can then tell how many customers you have by the size of the list.
If you are taking in the users input as a string do a String Comparison or if you're doing strictly a numerical account number and am taking it in as an int then simply see if the numbers are different
For strings use:
result = input1.Equals(input2, StringComparison.OrdinalIgnoreCase);
For ints just use an If statement to test:
if(input1 != input2) {
Console.WriteLine("Input has changed")
else
Console.WriteLine("Input has not changed");
}
I'm guessing the user has to push a button after the user has entered the password? If so, we can easily track this. First we make a global int variable like so: private int userCount = 0;
Then we add an event to our button:
private void btnAccountNumber_Click(object sender, EventArgs e)
{
userCount = userCount + 1;
displayLabel.Text = userCount.ToString() + " Customers";
maskedTextBox.Clear();
}
So in this button we add our customer that just clicked on our button to the total of users.
Next we show that number in the label you created. And finally we clear the maskedTextBox of userInput so the next customer can use it.

Advice on this method that works with chars

Recently I've been told to change one validation towards a database to a new database in a C# application. Instead of the old database I would be using the new one.
The problem is that I can't run the app. I need to publish it so the guys that uses it give me their feedback.
So I decided to share this part of the code that I added.
Not changed, but added. This is something new and a potential thing that can go wrong.
Hopefully someone with more experience will tell me how much my code sucks or if it looks OK.
Thing is... the old database has an int value in a column and the new one has a nvarchar(5).
So I made this to convert the old one in a new one.
string ConvertIDToReg(string kairosID)
{
double n;
if (!Double.TryParse(Convert.ToString(kairosID),
System.Globalization.NumberStyles.Any,
System.Globalization.NumberFormatInfo.InvariantInfo, out n))
{
return "0";
}
char[] regID = kairosID.ToCharArray();
if (regID.Length > 4)
{
return "0";
}
if (reg.Length == 3)
{
regID[4] = regID[3];
regID[3] = regID[2];
regID[2] = regID[1];
regID[1] = regID[0];
regID[0] = "0";
}
return regID.ToString();
}
This is how it should work:
The old ID is something like "1234" but the new one is a 5 char max ID with a 0 in the beginning like "01234" (if the 5th number is not occupied). So basically I want to be able to put a 0 in the beginning if there isn't a 5th number.
If the number exceeds the 5 digits I want to return a 0 as the whole string (this will be handled later)
If the number is not a number (i.e "123ABC") return a 0 all the same.
Should this compile or even work?
What about efficiency? This will run several times. Any help to make this faster will do.
No, this won't compile. You misspelled your second regID (forgot the 'ID'), and are assigning a string to a char at regID[0] = "0";
Change that and it will compile, then blow up when you run it, when regID.Length= 3, because you're trying to access index 3 and 4, which it clearly will not have.
This should do what you're wanting:
string ConvertIDToReg(string kairosID)
{
if (kairosID.Length > 4 || kairosID.Any(c => !char.IsDigit(c)))
return "0";
return kairosID.PadLeft(5, '0');
}
if it's longer than 4 characters or if any character is not a digit, return a zero as a string ("0"). Else return the ID padded to 5 digits. About as simple as i can make it I think. No need to parse it as an int even.
This code should work:
private string ConvertIntToChar(string numValue)
{
int result = 0;
if (int.TryParse(numValue, out result) == false || numValue.Length > 4)
{
return "0";
}
return numValue.PadLeft(5, '0');
}
If value is not of 4 characters then it will add number of "0" required to make the string length equal to 5.
If the string is always some form of an integer i would approach the problem as such. and you wanted to keep every thing else the same. the "D5" tells the ToString method to 0 pad the string so that it is always 5 digits but retains the same numerical value.
string ConvertIDToReg(string kairosID)
{
int id;
if (!Int32.TryParse(kairosID, out id) || id > 9999)
{
return "0";
}
return id.ToString("D5");
}

Sorting and summation over a set of words gives incorrect result

I am having trouble with Project Euler's Problem 22
Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.
For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714.
What is the total of all the name scores in the file?
So far this is the first Euler problem I haven't been able to solve on my own, and I don't get what I'm doing wrong here. I'm coming up short by 1532 with this solution.
This is my code:
using (WebClient client = new WebClient())
{
try
{
tempString = client
.DownloadString("http://projecteuler.net/project/resources/p022_names.txt")
.Replace("\"", "");
}
catch (Exception)
{
MessageBox.Show("Error, check your internet connection!");
}
}
string[] names = tempString.Split(',');
Array.Sort(names);
int total = 0;
for (int i = 0; i < names.Length; i++)
{
int namescore = 0;
foreach (char c in names[i]) { namescore += (int)c - 64; }
total += namescore * (i + 1);
}
return total.ToString();
I think it might be a C# specific bug or quirk ?
As you noted, you cannot set the CurrentCulture, therefore set DefaultThreadCurrentCulture.
When I use
CultureInfo.DefaultThreadCurrentCulture = CultureInfo.GetCultureInfo("hr-HR");
before any action, I get the same result you have. So, obviously, you should use
CultureInfo.DefaultThreadCurrentCulture = CultureInfo.GetCultureInfo("en-US");
to achieve the expected output (other than mentioned in the comments it's not enough to do this in the ToString() method, cause it also affects sorting).
Okay, let's check step by step an try to find inconsistencies. I have the correct answer.
Initial data:
names.Length == 5163
names.Count(w=>!Regex.IsMatch(w,"^[A-Z]+$")) == 0
names.Sum(w=>w.Length) == 30959
Partial sums (after N elements):
500: 7139561
2500: 187773540
5000: 811204450
UPDATE:
I have one idea: Sort is locale-specific! Try Sort(StringComparison.Ordinal).
UPDATE2:
To switch culture, set thread culture or AppDomain culture to, say, CultureInfo("en-US").

Categories