I have character arrays seperated into multiple groups, my code uses a character from every group, so once character in a group is processed it will go to the next. I want to remove a group when it's considered empty. (or alternative if you can help fix the code so it skips empty groups)
In the form, there are checkboxes which add the specific characters to their specified group, you have the option to add those characters of choice or not, which I also have a user include input textbox if they want to add their personal characters, but in a case of a char group being empty I get an exception most likely due to the group having no characters.
Exception:
"System.IndexOutOfRangeException: 'Index was outside the bounds of the
array."
For
"result[i] = charGroups[nextGroupIdx][nextCharIdx];"
char[][] charGroups = new char[][]
{
CapitalCharacterSet.ToCharArray(),
LowercaseCharacterSet.ToCharArray(),
NumbersCharacterSet.ToCharArray(),
IncludeCharacterSet.ToCharArray(),
SpecialCharacterSet.ToCharArray()
};
FULL CODE:
char[][] charGroups = new char[][]
{
CapitalCharacterSet.ToCharArray(),
LowercaseCharacterSet.ToCharArray(),
NumbersCharacterSet.ToCharArray(),
IncludeCharacterSet.ToCharArray(),
SpecialCharacterSet.ToCharArray()
};
int[] charsLeftInGroup = new int[charGroups.Length];
for (int i = 0; i < charsLeftInGroup.Length; i++)
charsLeftInGroup[i] = charGroups[i].Length;
int[] leftGroupsOrder = new int[charGroups.Length];
for (int i = 0; i < leftGroupsOrder.Length; i++)
leftGroupsOrder[i] = i;
byte[] randomBytes = new byte[4];
RNGCryptoServiceProvider rng = new();
rng.GetBytes(randomBytes);
int seed = BitConverter.ToInt32(randomBytes, 0);
Random random = new(seed);
char[] result = null;
result = new char[length.Value];
int nextCharIdx;
int nextGroupIdx;
int nextLeftGroupsOrderIdx;
int lastCharIdx;
int lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;
for (int i = 0; i < result.Length; i++)
{
if (lastLeftGroupsOrderIdx == 0)
nextLeftGroupsOrderIdx = 0;
else
nextLeftGroupsOrderIdx = random.Next(0, lastLeftGroupsOrderIdx);
nextGroupIdx = leftGroupsOrder[nextLeftGroupsOrderIdx];
lastCharIdx = charsLeftInGroup[nextGroupIdx] - 1;
if (lastCharIdx == 0)
nextCharIdx = 0;
else
nextCharIdx = random.Next(0, lastCharIdx + 1);
try
{
result[i] = charGroups[nextGroupIdx][nextCharIdx];
}
catch
{
if (lastCharIdx == 0)
nextCharIdx = 0;
else
nextCharIdx = random.Next(0, lastCharIdx + 1);
}
if (lastCharIdx == 0)
charsLeftInGroup[nextGroupIdx] = charGroups[nextGroupIdx].Length;
else
{
if (lastCharIdx != nextCharIdx)
{
char temp = charGroups[nextGroupIdx][lastCharIdx];
charGroups[nextGroupIdx][lastCharIdx] =
charGroups[nextGroupIdx][nextCharIdx];
charGroups[nextGroupIdx][nextCharIdx] = temp;
}
charsLeftInGroup[nextGroupIdx]--;
}
if (lastLeftGroupsOrderIdx == 0)
lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;
else
if (lastLeftGroupsOrderIdx != nextLeftGroupsOrderIdx)
{
int temp = leftGroupsOrder[lastLeftGroupsOrderIdx];
leftGroupsOrder[lastLeftGroupsOrderIdx] =
leftGroupsOrder[nextLeftGroupsOrderIdx];
leftGroupsOrder[nextLeftGroupsOrderIdx] = temp;
}
lastLeftGroupsOrderIdx--;
}
}
I have a list of clauses in my database and a listview in my custom pane in VSTO.
When I select or drag and drop a list item, it gets copied twice. I found this answer.
Listview ItemSelectionChanged fires twice?
But I dont have a isSelected method for my EventArgs e.
Below is my code, please help me out, I want the data/text to be copied only once.
private void clauseList_SelectedIndexChanged(object sender, EventArgs e)
{
ListView.SelectedListViewItemCollection col = clauseList.SelectedItems;
string temp = clauseList.FocusedItem.Text;
clauseList.DoDragDrop(temp, DragDropEffects.Move);
Microsoft.Office.Interop.Word.Selection currentSelection = Globals.ThisAddIn.Application.Selection;
Microsoft.Office.Interop.Word.Range range = currentSelection.Range;
currentSelection.TypeText(temp);
currentSelection.TypeParagraph();
clslst(select);
}
public void clslst(object s)
{
DataAccess data = new DataAccess();
List<ClauseDetails> details = new List<ClauseDetails>();
details.AddRange(data.ClausesRelated(s));
string FromtextFromDoc;
FromtextFromDoc = Globals.ThisAddIn.Application.Selection.Text;
Microsoft.Office.Interop.Word.Document docs = Globals.ThisAddIn.Application.ActiveDocument;
List<string> clslist = new List<string>();
string aa = "";
int f = 0;
string tempindex = "";
foreach (Paragraph paragraph in docs.Paragraphs)
{
Style style = paragraph.get_Style() as Style;
string styleName = style.NameLocal;
//var sty = style.Font;
//fontstyle = sty.Name;
//fontsize = sty.Size;
if (styleName.Equals("Heading 1"))
{
f += 1;
if (f == 2)
{
tempindex = aa;
f = 0;
clslist.Add(tempindex);
aa = "";
}
}
if (f > 0)
{
aa += paragraph.Range.Text;
}
}
clslist.Add(aa);
List<string> ClausesNotPresent = new List<string>();
List<string> ClausesPresent = new List<string>();
for (int i = 0; i < clslist.Count; i++)
{
for (int j = 0; j < details.Count; j++)
{
if (clslist[i].Contains(details[j].clausetitle) || clslist[i].Contains(details[j].clause))
{
ClausesPresent.Add(details[j].clausetitle + "\n" + details[j].clause);
}
}
}
List<string> test = new List<string>();
for (int z = 0; z < details.Count; z++)
{
test.Add(details[z].clausetitle + "\n" + details[z].clause);
}
if (ClausesPresent.Count < details.Count)
{
ClausesNotPresent.AddRange(test.Except(ClausesPresent));
}
for(int m=0;m<ClausesNotPresent.Count;m++)
{
ClausesNotPresent[m] = "\n"+ ClausesNotPresent[m];
}
clauseList.Clear();
for (int i = 0; i < ClausesNotPresent.Count; i++)
{
clauseList.Items.Add(ClausesNotPresent[i]);
}
}
My input is:
something1#email.com.;;
something2#email.eu,./
something3#email.org..
something4#email.netcdsfsd
What I want is to get rid of all characters after my "domains"(stored in array).
So output should be:
something1#email.com
something2#email.eu
something3#email.org
something4#email.net
My code is:
string[] domains = richTextBox_domains.Text.Split(';');
char[] specialchars = ".!#$%^&*()-_=+[]{}\\|;:'\",.<>/?".ToCharArray();
for (int x = 0; x < domains.Length; x++)
{
for (int y = 0; y < specialchars.Length; y++)
{
string check = domains[x] + specialchars[y];
string aftertmp = "." + after.Substring(after.IndexOf('.') + 1);
if (aftertmp == check)
after = after.Replace(check, domains[x]);
}
}
It's working but not always and only for one character at the end.
I will be glad for help
use regex to check email id and than store it in different array
var regex1 = new Regex("(([-a-zA-Z0-9])|([-a-zA-Z0-9]{1,256}[#%._\+~#=][-a-zA-Z0-9])){1,10}\.[-a-zA-Z0-9]{1,10}\b",RegexOptions.IgnoreCase);
string[] domains = richTextBox_domains.Text.Split(';');
List<string> l = new List<string>();
for (int x = 0; x < domains.Length; x++)
{
var results = regex1.Matches(domains[x]);
foreach (Match match in results)
{
l.Add(match.Groups[1].Value);
MessageBox.Show(match.Groups[1].Value);
}
}
string[] s = l.ToArray();// new array
hope this helps
This works fine
string[] s = { ".com",".net",".edu",".eu" };
string[] domain = new string[]
{
"something1#email.com.;;",
"something2#email.eu,./",
"something3#email.org..",
"something4#email.netcdsfsd"
};
string result = "";
for (int m = 0; m < domain.Length; m++)
{
for (int i = 0; i < s.Length; i++)
{
if (domain[m].IndexOf(s[i]) != -1)
{
result = domain[m].Substring(0, domain[m].IndexOf(s[i])) + s[i];
MessageBox.Show(result);
}
}
}
}
I really need a solution for the next scenario(I've been searching for hours and beating about the bushes to find a smooth solution, but none worked):
I have a winform that:
parse a text file
generate some folders using random words from that file
My code so far:
int value;
string path = null;
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
if (fbd.ShowDialog(this) == DialogResult.OK)
{
path = fbd.SelectedPath;
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
value = Convert.ToInt32(textBox1.Text);//store the value from the textbox in variable "value"
}
private void button2_Click(object sender, EventArgs e)
{
if (path != null && Directory.Exists(path))
for (int i = 0; i < value; i++)
{
Random rnd = new Random();
string tick1 = rnd.Next(0, 10).ToString();
var lines = File.ReadAllLines(#"M:\\dictionar.txt");
var r = new Random(DateTime.Now.Millisecond);
var randomLineNumber = r.Next(0, lines.Length - 1);
var line = lines[randomLineNumber];
StringBuilder b = new StringBuilder();
for (int j = 0; j < line.Length; j++)
{
char c = line[j];
if (rnd.Next(2) == 0)
{
c = Char.ToUpper(c);
}
b.Append(c);
if (j % 3 == 2)
{
b.Append(rnd.Next(10));
}
}
line = b.ToString();
Directory.CreateDirectory(Path.Combine(path, string.Format("{0}", line.Insert(2, tick1).Insert(4, tick1).Insert(6, tick1))));
}
}
Is there a way to use ToUpper() method as line.Insert() one so that I can get random upper letters? More, is there a better way of randomizing those index positions form line.Insert() (I'm asking this because when it's generating the folders name: the indexes are the same: e.g pe8rs8on8al and just after that the index changes.)?
I want to achieve the following:
if I have the next words in the .txt file:
personal
football
programming
computer
I would like the folder names to look like:
Pe3rs9oN1al
fO8ot5Ba6lL
You can loop through the characters in the string and build a new string depending on random values:
StringBuilder b = new StringBuilder();
for (int i = 0; i < line.Length; i++ ) {
char c = line[i];
if (rnd.Next(2) == 0) {
c = Char.ToUpper(c);
}
b.Append(c);
if (i % 2 == 1) {
b.Append(rnd.Next(10));
}
}
line = b.ToString();
Note: You shouldn't create Random objects in the loop. You should create a single Random object before the loop and use for all random numbers that you need. Creating instances too close in time will make them return the same sequences of random numbers. Also, you don't need to seed the random generator from the clock, the constructor without parameters does that automatically:
Random rnd = new Random();
So, the code in the method would be:
if (path != null && Directory.Exists(path))
Random rnd = new Random();
for (int i = 0; i < value; i++)
{
var lines = File.ReadAllLines(#"M:\\dictionar.txt");
var randomLineNumber = rnd.Next(0, lines.Length);
var line = lines[randomLineNumber];
StringBuilder b = new StringBuilder();
for (int j = 0; j < line.Length; j++)
{
char c = line[j];
if (rnd.Next(2) == 0)
{
c = Char.ToUpper(c);
}
b.Append(c);
if (j % 2 == 1)
{
b.Append(rnd.Next(10));
}
}
line = b.ToString();
Directory.CreateDirectory(Path.Combine(path, line));
}
}
Note the rnd.Next(0, lines.Length) to pick a random line. The upper limit for the random number is not inclusive, so if you use rnd.Next(0, lines.Length - 1) it will never pick the last line.
That's because you are specifying only tick1 in the same loop. If you want to change this, add additional ticks to your code as below:
string tick1 = rnd.Next(0, 10).ToString();
string tick2 = rnd.Next(0, 10).ToString();
string tick3 = rnd.Next(0, 10).ToString();
Then use those in your formatting of the string:
Directory.CreateDirectory(Path.Combine(path, string.Format("{0}", line.Insert(2, tick1).Insert(4, tick2).Insert(6, tick3))))
Like Guffa said you should not use Random in a loop, in all preference you should only instanciate one of it, but I think you could use it like this
public static class StringRandomize
{
static readonly Random rnd = new Random();
static char[] permmitedCharacters { get; set; }
static StringRandomize()
{
List<char> Chars= new List<char>();
for (int i = 48; i < 48+10; i++)
{
Chars.Add((char)i);
}
for (int i = 65; i < 65+26; i++)
{
Chars.Add((char)i);
}
permmitedCharacters = Chars.ToArray();
}
public static string Randomize(string input, double RandomizePercent = 30)
{
StringBuilder result = new StringBuilder();
int index = 0;
while (index < input.Length)
{
if (rnd.Next(0, 100) <= RandomizePercent)
{
if (rnd.Next(0, 100) <= RandomizePercent)
{
result.Append(GenerateCaracter());
}
else
{
if (rnd.Next(0, 100) > 50)
{
result.Append(input.ToLower()[index]);
}
else
{
result.Append(input.ToUpper()[index]);
}
index++;
}
}
else
{
result.Append(input[index]);
index++;
}
}
return result.ToString();
}
private static char GenerateCaracter()
{
return permmitedCharacters[rnd.Next(0, permmitedCharacters.Length)];
}
}
private static void GenerateRandomDirectories(string path, int value)
{
//I'm supposing value is the number of lines that you want
var lines = File.ReadAllLines(#"M:\\dictionar.txt");
Random rnd = new Random();
if (path != null && Directory.Exists(path))
{
for (int i = 0; i < value; i++)
{
Directory.CreateDirectory(path + "\\" + StringRandomize.Randomize(lines[rnd.Next(0,lines.Length)]));
}
}
}
"pers3o7Nal"
"foOtBaLl"
Got like this
public Form1()
{
InitializeComponent();
string content = "";
using (FileStream fs = new FileStream("D:\\names.txt", FileMode.Open, FileAccess.Read))
using (StreamReader sr = new StreamReader(fs))
content = sr.ReadToEnd();
string[] names = content.Split(new string[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
string path = "D:\\RandDirs";
if (!Directory.Exists(path))Directory.CreateDirectory(path) ;
for (int i = 0; i < 50; i++) Directory.CreateDirectory(path + "\\" + getRandomName(names));
}
Random randName = new Random();
Random insertingNumber = new Random();
Random randUpper = new Random();
Random randInsertNumber = new Random();
string getRandomName(string[] names)
{
string name = names[randName.Next(names.Length)];
name = name.Replace(" ", "");
string result = "";
for (int i = 0; i < name.Length; i++)
result += (randUpper.Next(0, 9) <= 5 ? name[i].ToString().ToLower() : name[i].ToString().ToUpper())
+ (((i + 1) % 2 == 0) ? insertingNumber.Next(0, 9).ToString() : "");
return result;
}
as per your needs, i've changed from randomly inserting numbers to inserting number every 2 characters.
Using Microsoft.Office.Interop.Word DLL i want to find the particular Paragraph and repeat that paragraph in the document below the old paragraph. Here i'm able to to extract the paragraph from the selected document using given string (or) text.
Below is the code block:
private string[] ReadFileContent(Document doc, string Key)
{
Word::Application WordApp;
WordApp = new Word.Application();
List<string> SelectedParagraphs = new List<string>();
string parac = string.Empty;
for (int j = 1; j <= doc.Paragraphs.Count; j++) //numeration of paragraphs starts from 1
{
Microsoft.Office.Interop.Word.Paragraph para = doc.Content.Paragraphs[j];
int cSent = para.Range.Sentences.Count;
string a;
for (int l = 1; l <= cSent; l++)
{
Microsoft.Office.Interop.Word.Range sent = para.Range.Sentences[l];
a = sent.Text.ToString();
if (a.IndexOf(Key)>-1)
{
parac = parac+ "," + j.ToString();
}
}
}
parac = parac.TrimStart(',');
string[] ParaArray = parac.Split(',');
string[] Result = new string[ParaArray.Count()];
for (int m = 0; m < ParaArray.Count(); m++)
{
int i = 0;
//StringBuilder sb = new StringBuilder();
Microsoft.Office.Interop.Word.Paragraphs DocPar = doc.Paragraphs;
// Count number of paragraphs in the file
long parCount = DocPar.Count;
// Step through the paragraphs
int paraGraphNum = Convert.ToInt32(ParaArray[m]);
while (i < parCount)
{
i++;
if (i == paraGraphNum)
{
// sb.Append(DocPar[i].Range.Text);
Result[m] = DocPar[i].Range.Text;
break;
}
}
}
return Result;
}