OpenQA.Selenium.ElementNotInteractableException : Cannot click on element - c#

public PriceChangeRequestStatus SelectPcrFrom(String[] fromdate)
{
wrapper.Click(imgPcrFrom);
String year, day, month;
day = fromdate[0];
month = fromdate[1];
year = fromdate[2];
//for (int index = 0; index <= 1; index++)
wrapper.Click(lnkPcrFrom);
wrapper.Click(lnkPcrFrom);
Thread.Sleep(4000);
driver.FindElement(By.XPath("//div[contains(text(),'" + year + "')]")).Click();
Thread.Sleep(4000);
driver.FindElement(By.XPath("//div[contains(text(),'" + findMonth(month).Substring(0, 3) + "')]")).Click();
Thread.Sleep(2000);
driver.FindElement(By.XPath("//div[contains(#title,'" + findMonth(month) + " " + day + ", " + year + "')]")).Click();
Thread.Sleep(2000);
return this;
}
public PriceChangeRequestStatus SelectPcrTo(String[] todate)
{
wrapper.Click(imgPcrTo);
wrapper.Click(lnkPcrTo);
wrapper.Click(lnkPcrTo);
String year, day, month;
day = todate[0];
month = todate[1];
year = todate[2];
Thread.Sleep(4000);
// By Sunayana
//IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
//js.ExecuteScript("document.getElementsByClassName('ajax__calendar_year')");
// End
//// IReadOnlyList<IWebElement> yearClick = wrapper.GetElements("xpath:=.//div[#class='ajax__calendar_year']");
//IList<IWebElement> yearClick = driver.FindElements(By.XPath(".//div[#class='ajax__calendar_year']"));
//Console.WriteLine(yearClick.Count);
//for (int index = 1; index-1 <= yearClick.Count; index++)
//{
// int i=0;
// Console.WriteLine(index);
// i=index;
// if (yearClick[i].GetAttribute("innerHTML").Equals(year))
// {
// yearClick[i].Click();
// Console.WriteLine("I am here");
// }
// else {
// Console.WriteLine("Sorry");
// }
//}
Thread.Sleep(4000);
//var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
//try
//{
// wait.Until(ExpectedConditions.ElementToBeClickable(By.XPath("//div[contains(text(),'" + year + "')]"))).Click();
//}
//catch (WebDriverTimeoutException)
//{
// Console.WriteLine("Logout button was not visible!");
//}
IWebElement clickyear = driver.FindElement(By.XPath("//div[contains(text(),'" +year+ "')]"));
clickyear.Click();
//Actions action = new Actions(driver);
//action.MoveToElement(clickyear).Click().Build().Perform();
Thread.Sleep(4000);
driver.FindElement(By.XPath("//div[contains(text(),'" + findMonth(month).Substring(0, 3) + "')]")).Click();
Thread.Sleep(2000);
driver.FindElement(By.XPath("//div[contains(#title,'" + findMonth(month) + " " + day + ", " + year + "')]")).Click();
Thread.Sleep(2000);
return this;
}
public String findMonth(String month)
{
String CorrectMonth = "";
switch (month) {
case "01":
CorrectMonth = "January";
break;
case "02":
CorrectMonth = "February";
break;
case "03":
CorrectMonth = "March";
break;
case "04":
CorrectMonth = "April";
break;
case "05":
CorrectMonth = "May";
break;
case "06":
CorrectMonth = "June";
break;
case "07":
CorrectMonth = "July";
break;
case "08":
CorrectMonth = "August";
break;
case "09":
CorrectMonth = "September";
break;
case "10":
CorrectMonth = "October";
break;
case "11":
CorrectMonth = "November";
break;
case "12":
CorrectMonth = "December";
break;
}
return CorrectMonth;
}
Edited the code and tried running the script. The logic written for SELECTPCRFROM is working fine but the same logic is not working for SELECTPCRTO. tried many others solutions but still SELECTPCRTO is nor working as expected Please help me on this. The executed code is displaying error message provided in the title

Most of the datepickers gets identified by xpath but when you try perform an operation on them then they would give you an error. Instead try going the javascript way.
Java -
document.evaluate(PATH, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
Similary you can use it in C#
Refer the answer here - link

Related

How to draw a path by using longitiude and latitude in Windows Form Application c#?

I can collect longitude and latitude info from GNGGA data get from GPS/GNSS board, but I can't draw a path according to longitude and latitude information.
For example you can see in picture;
In pıcture there is a also direction.For the first step direction is not important. I just want to draw it wiht points or lines without direction(if it is possible).To be trust, I tried to draw in chart and picture box but I couldn't achieve it.
Have you got any ideas about it?
Here is my code; gBoylam=longitude, gEnlem=lattitude, gYukseklik=altitude
gParca=NMEA.Split(new char[] { ',' });
switch (gParca[0])
{
//Global Positioning System Fix data
case "$GNGGA":
gParca[2] = gParca[2].Replace('.', ',');
gParca[4] = gParca[4].Replace('.', ',');
if (gParca[3]=="N")
{
gKG = "North";
}
else if(gParca[3]=="S")
{
gKG = "South";
}
if (gParca[5]=="E")
{
gDB = "East";
}
else if(gParca[5]=="W")
{
gDB = "West";
}
switch (gParca[6])
{
case "0": gKilitlenme = "Invalid"; break;
case "1": gKilitlenme = "GPS fix (SPS)"; break;
case "2": gKilitlenme = "DGPS fix"; break;
case "3": gKilitlenme = "PPS fix"; break;
case "4": gKilitlenme = "RTK fix"; break;
case "5": gKilitlenme = "RTK float"; break;
case "6": gKilitlenme = "Estimated"; break;
case "7": gKilitlenme = "Manuel Input"; break;
case "8": gKilitlenme = "Simulation"; break;
default: gKilitlenme = "Unknown"; break;
}
gEnlem = gParca[2];
gBoylam = gParca[4];
gUydular = gParca[7];
gYukseklik = gParca[9] + " " + gParca[10];
// gVeriTipi = "GPS Data Fix";
gSaat = gParca[1].Substring(0, 2) + ":" + gParca[1].Substring(2, 2) + " " +
gParca[1].Substring(4, 2) + " (UTF)";
gYataySapma = gParca[8];
GPSData(NMEA);
break;
default:
break;
}
txtbxLongitude.Text = gBoylam + " " + gDB;
txtbxLatitude.Text = gEnlem + " " + gKG;
txtbxAltitude.Text = gYukseklik;
txtbxFixQuality.Text = gKilitlenme;
txtbxSatellites.Text = gUydular;
txtbxTime.Text = gSaat;

How to call a C# Class from a C# Form

This is my class:
using System;
using System.Collections.Generic;
using System.Text;
namespace Num2Wrd
{
public class NumberToEnglish
{
public String changeNumericToWords(double numb)
{
String num = numb.ToString();
return changeToWords(num, false);
}
public String changeCurrencyToWords(String numb)
{
return changeToWords(numb, true);
}
public String changeNumericToWords(String numb)
{
return changeToWords(numb, false);
}
public String changeCurrencyToWords(double numb)
{
return changeToWords(numb.ToString(), true);
}
private String changeToWords(String numb, bool isCurrency)
{
String val = "", wholeNo = numb, points = "", andStr = "", pointStr = "";
String endStr = (isCurrency) ? ("Only") : ("");
try
{
int decimalPlace = numb.IndexOf(".");
if (decimalPlace > 0)
{
wholeNo = numb.Substring(0, decimalPlace);
points = numb.Substring(decimalPlace + 1);
if (Convert.ToInt32(points) > 0)
{
andStr = (isCurrency) ? ("and") : ("point");// just to separate whole numbers from points/Rupees
endStr = (isCurrency) ? ("Rupees " + endStr) : ("");
pointStr = translateRupees(points);
}
}
val = String.Format("{0} {1}{2} {3}", translateWholeNumber(wholeNo).Trim(), andStr, pointStr, endStr);
}
catch
{
;
}
return val;
}
private String translateWholeNumber(String number)
{
string word = "";
try
{
bool beginsZero = false;//tests for 0XX
bool isDone = false;//test if already translated
double dblAmt = (Convert.ToDouble(number));
//if ((dblAmt > 0) && number.StartsWith("0"))
if (dblAmt > 0)
{//test for zero or digit zero in a nuemric
beginsZero = number.StartsWith("0");
int numDigits = number.Length;
int pos = 0;//store digit grouping
String place = "";//digit grouping name:hundres,thousand,etc...
switch (numDigits)
{
case 1://ones' range
word = ones(number);
isDone = true;
break;
case 2://tens' range
word = tens(number);
isDone = true;
break;
case 3://hundreds' range
pos = (numDigits % 3) + 1;
place = " Hundred ";
break;
case 4://thousands' range
case 5:
case 6:
pos = (numDigits % 4) + 1;
place = " Thousand ";
break;
case 7://millions' range
case 8:
case 9:
pos = (numDigits % 7) + 1;
place = " Million ";
break;
case 10://Billions's range
pos = (numDigits % 10) + 1;
place = " Billion ";
break;
//add extra case options for anything above Billion...
default:
isDone = true;
break;
}
if (!isDone)
{//if transalation is not done, continue...(Recursion comes in now!!)
word = translateWholeNumber(number.Substring(0, pos)) + place + translateWholeNumber(number.Substring(pos));
//check for trailing zeros
if (beginsZero) word = " and " + word.Trim();
}
//ignore digit grouping names
if (word.Trim().Equals(place.Trim())) word = "";
}
}
catch
{
;
}
return word.Trim();
}
private String tens(String digit)
{
int digt = Convert.ToInt32(digit);
String name = null;
switch (digt)
{
case 10:
name = "Ten";
break;
case 11:
name = "Eleven";
break;
case 12:
name = "Twelve";
break;
case 13:
name = "Thirteen";
break;
case 14:
name = "Fourteen";
break;
case 15:
name = "Fifteen";
break;
case 16:
name = "Sixteen";
break;
case 17:
name = "Seventeen";
break;
case 18:
name = "Eighteen";
break;
case 19:
name = "Nineteen";
break;
case 20:
name = "Twenty";
break;
case 30:
name = "Thirty";
break;
case 40:
name = "Fourty";
break;
case 50:
name = "Fifty";
break;
case 60:
name = "Sixty";
break;
case 70:
name = "Seventy";
break;
case 80:
name = "Eighty";
break;
case 90:
name = "Ninety";
break;
default:
if (digt > 0)
{
name = tens(digit.Substring(0, 1) + "0") + " " + ones(digit.Substring(1));
}
break;
}
return name;
}
private String ones(String digit)
{
int digt = Convert.ToInt32(digit);
String name = "";
switch (digt)
{
case 1:
name = "One";
break;
case 2:
name = "Two";
break;
case 3:
name = "Three";
break;
case 4:
name = "Four";
break;
case 5:
name = "Five";
break;
case 6:
name = "Six";
break;
case 7:
name = "Seven";
break;
case 8:
name = "Eight";
break;
case 9:
name = "Nine";
break;
}
return name;
}
private String translateRupees(String Rupees)
{
String cts = "", digit = "", engOne = "";
for (int i = 0; i < Rupees.Length; i++)
{
digit = Rupees[i].ToString();
if (digit.Equals("0"))
{
engOne = "Zero";
}
else
{
engOne = ones(digit);
}
cts += " " + engOne;
}
return cts;
}
}
}
Form contains two Textboxes (textBox1 and textBox2) and a Button(button1).
I want to type an amount in numbers in textBox1 and click on the button. The amount entered in numbers in textBox1 has to be converted to text and appear in textbox2. Functions to convert are in above C# class file. I am a new student. Can anyone help me in solving this problem.
You have to create an object for 'NumberToEnglish' Class and use it in Form1.cs this way
public partial class Form1 : Form
{
NumberToEnglish neObj = new NumberToEnglish();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
textBox2.Text = neObj.changeCurrencyToWords(Convert.ToDouble(textBox1.Text));
}
}
public partial class Form1 : Form
{
NumberToEnglish Obj = new NumberToEnglish();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
textBox2.Text = Obj.changeCurrencyToWords(textBox1.Text);//As your method accept a string..
}
}

Display Numbers to words in textbox or lable in asp.net,C#?

<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True" OnTextChanged="TextBox1_TextChanged"></asp:TextBox><br />
<br />
<asp:TextBox ID="TextBox2" runat="server" Height="100px" TextMode="MultiLine" Width="600px"></asp:TextBox>
</div>
</form>
And my code behind code is:
public String changeToWords(String numb)
{
String val = "", wholeNo = numb, points = "", andStr = "", pointStr = "";
String endStr = ("");
try
{
int decimalPlace = numb.IndexOf(".");
if (decimalPlace > 0)
{
wholeNo = numb.Substring(0, decimalPlace);
points = numb.Substring(decimalPlace + 1);
if (Convert.ToInt32(points) > 0)
{
andStr = ("point");// just to separate whole numbers from points/Rupees
}
}
val = String.Format("{0} {1}{2} {3}", translateWholeNumber(wholeNo).Trim(), andStr, pointStr, endStr);
}
catch
{
;
}
return val;
}
private String translateWholeNumber(String number)
{
string word = "";
try
{
bool beginsZero = false;//tests for 0XX
bool isDone = false;//test if already translated
double dblAmt = (Convert.ToDouble(number));
//if ((dblAmt > 0) && number.StartsWith("0"))
if (dblAmt > 0)
{//test for zero or digit zero in a nuemric
beginsZero = number.StartsWith("0");
int numDigits = number.Length;
int pos = 0;//store digit grouping
String place = "";//digit grouping name:hundres,thousand,etc...
switch (numDigits)
{
case 1://ones' range
word = ones(number);
isDone = true;
break;
case 2://tens' range
word = tens(number);
isDone = true;
break;
case 3://hundreds' range
pos = (numDigits % 3) + 1;
place = " Hundred ";
break;
case 4://thousands' range
case 5:
case 6:
pos = (numDigits % 4) + 1;
place = " Thousand ";
break;
case 7://millions' range
case 8:
case 9:
pos = (numDigits % 7) + 1;
place = " Million ";
break;
case 10://Billions's range
pos = (numDigits % 10) + 1;
place = " Billion ";
break;
//add extra case options for anything above Billion...
default:
isDone = true;
break;
}
if (!isDone)
{//if transalation is not done, continue...(Recursion comes in now!!)
word = translateWholeNumber(number.Substring(0, pos)) + place + translateWholeNumber(number.Substring(pos));
//check for trailing zeros
if (beginsZero) word = " and " + word.Trim();
}
//ignore digit grouping names
if (word.Trim().Equals(place.Trim())) word = "";
}
}
catch
{
;
}
return word.Trim();
}
private String tens(String digit)
{
int digt = Convert.ToInt32(digit);
String name = null;
switch (digt)
{
case 10:
name = "Ten";
break;
case 11:
name = "Eleven";
break;
case 12:
name = "Twelve";
break;
case 13:
name = "Thirteen";
break;
case 14:
name = "Fourteen";
break;
case 15:
name = "Fifteen";
break;
case 16:
name = "Sixteen";
break;
case 17:
name = "Seventeen";
break;
case 18:
name = "Eighteen";
break;
case 19:
name = "Nineteen";
break;
case 20:
name = "Twenty";
break;
case 30:
name = "Thirty";
break;
case 40:
name = "Fourty";
break;
case 50:
name = "Fifty";
break;
case 60:
name = "Sixty";
break;
case 70:
name = "Seventy";
break;
case 80:
name = "Eighty";
break;
case 90:
name = "Ninety";
break;
default:
if (digt > 0)
{
name = tens(digit.Substring(0, 1) + "0") + " " + ones(digit.Substring(1));
}
break;
}
return name;
}
private String ones(String digit)
{
int digt = Convert.ToInt32(digit);
String name = "";
switch (digt)
{
case 1:
name = "One";
break;
case 2:
name = "Two";
break;
case 3:
name = "Three";
break;
case 4:
name = "Four";
break;
case 5:
name = "Five";
break;
case 6:
name = "Six";
break;
case 7:
name = "Seven";
break;
case 8:
name = "Eight";
break;
case 9:
name = "Nine";
break;
}
return name;
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
TextBox2.Text = changeToWords(TextBox1.Text);
}
it is working properly but what i want is when i am typeing in textbox it automatically shows in another textbox and I want to show numbers to words in lakhs also.... please help me

Convert a complicated txt file into a csv file using c#

I have absolutely no idea what to do with this but here is a snippet of the file that I'm trying to convert:
"September
3Beef
Lamb Chops
4Fish
Not Fish
5Mac and Cheese
PB & J"
The csv file is supposed to print the date what comes after in quotes, so the above should look like:
Tuesday September Third 2013 "Beef" "Lamb Chops"
Wednesday September Fourth 2013 "Fish" "Not Fish"
Thursday September Fifth 2013 "Mac and Cheese" "PB&J"
Here is what I have so far:
StreamReader reader = new StreamReader(#"..\..\Lunches.txt");
while (!reader.EndOfStream)
{
string currentLine = reader.ReadLine();
}
StreamWriter writer = new StreamWriter(#"..\..\Lunches.csv");
// date.ToString("ddddd yyyyy mm MMMMMM");
string delimiter = ",";
Here is the code
private void Form1_Load(object sender, EventArgs e)
{
string sayka = "August\n\n" +
"31Beef\n" +
"Lamb Chops\n" +
"24Fish\n" +
"Not Fish\n" +
"15Mac and Cheese\n" +
"PB & J\n";
MessageBox.Show(makeCSV(sayka));
}
string getMonthName(int val)
{
switch (val)
{
case 1: return "JANUARY";
case 2: return "FEBRUARY";
case 3: return "MARCH";
case 4: return "APRIL";
case 5: return "MAY";
case 6: return "JUNE";
case 7: return "JULY";
case 8: return "AUGUST";
case 9: return "SEPTEMBER";
case 10: return "OCTOBER";
case 11: return "NOVEMBER";
case 12: return "DECEMBER";
default: return null;
}
}
string getDayName(int val)
{
switch (val)
{
case 1: return "First";
case 2: return "Second";
case 3: return "Third";
case 4: return "Fourth";
case 5: return "Fifth";
case 6: return "Sixth";
case 7: return "Seventh";
case 8: return "Eighth";
case 9: return "Nineth";
case 10: return "Tenth";
case 11: return "Eleventh";
case 12: return "Twelth";
case 13: return "Thirteenth";
case 14: return "Fouteenth";
case 15: return "Fifteenth";
case 16: return "Sixteenth";
case 17: return "Seventeenth";
case 18: return "Eighteenth";
case 19: return "Nineteenth";
case 20: return "Twentieth";
default: return "";
}
}
string getDayName2(int val)
{
if (val == 30) return "Thirtieth";
else if (val > 30) return "Thirty " + getDayName(val % 30);
else if (val > 20) return "Twenty " + getDayName(val % 20);
else return getDayName(val);
}
string makeCSV(string val)
{
string res = "";
string[] ss = val.Split('\n');
int curMonth = 0;
for (int i = 0; i < ss.Length; i++)
{
if (ss[i].Trim() != "")
{
bool isInt = false;
try
{
int intA = Convert.ToInt32(ss[i][0].ToString());
isInt = true;
}
catch { }
if (isInt)
{
bool isDoubleInt = false;
try
{
int intB = Convert.ToInt32(ss[i][1].ToString());
isDoubleInt = true;
}
catch { }
int date = 0;
if (isDoubleInt) date = Convert.ToInt32(ss[i].Remove(2));
else date = Convert.ToInt32(ss[i][0].ToString());
DateTime dt = new DateTime(DateTime.Now.Year, curMonth, date);
string itemName = "";
if (isDoubleInt) itemName = ss[i].Substring(2);
else itemName = ss[i].Substring(1);
string itemName2 = ss[i + 1];
res += dt.DayOfWeek + " " + getMonthName(dt.Month) + " " + getDayName2(dt.Day) + " \"" + itemName + "\"" + " \"" + itemName2 + "\"\n";
}
else
{
for (int j = 1; j < 13; j++)
if (ss[i].ToUpper().StartsWith(getMonthName(j)))
{
curMonth = j;
break;
}
}
}
}
return res;
}
}
From the filestream either use StreamReader.readToEnd(), get the string and use the function, Or if the file is big then use it line by line..
Rate if this helps..
This is going to be a bit complicated. I left out some things for you to do.
String[] months = { "January", "February", "March", ....};
Date processDate = new Date();
while (!reader.EndOfStream)
{
string currentLine = reader.ReadLine();
// skip this line if blank
if (String.IsNullOrEmpty(currentLine)) continue;
if (months.Contains(currentLine)) {
// we have a new starting month.
// reset the process date
Int32 month = DateTime.ParseExact(currentLine.Trim(), "MMMM", CultureInfo.CurrentCulture).Month;
date = Convert.ToDate(month.ToString() + "/01/2013");
continue;
}
// here's where the real fun begins:
// you have to pull out the first two characters and test if one or both are digits.
// This will give you the day. Put that into your date variable.
Int32 day = 0;
char[] arr = currentLine.ToCharArray(0, currentLine.Length);
if (Char.IsDigit(arr[1])) {
// first two characters are numbers
day = Convert.ToInt32(currentLine.Substring(0,2));
currentLine = currentLine.Remove(0,2);
} else {
// only the first character is a number
day = Convert.ToInt32(currentLine.Substring(0,1));
currentLine = currentLine.Remove(0,1);
}
// set the new date
date = new DateTime(date.Year, date.Month, day, 0, 0, 0);
// If we can assume that ALL lines are broken into two parts then we can do the following:
String secondLine = reader.ReadLine();
currentLine = String.Format("{0} {1}", currentLine, secondLine);
// At this point you have the month, day, and the entire line.
// write it to your lunch stream or store in a StringBuilder
}

Faster than String.Replace()

Is there any other method that is faster than doing like this?
private void EscapeStringSequence(ref string data)
{
data = data.Replace("\\", "\\\\"); // Backslash
data = data.Replace("\r", "\\r"); // Carriage return
data = data.Replace("\n", "\\n"); // New Line
data = data.Replace("\a", "\\a"); // Vertical tab
data = data.Replace("\b", "\\b"); // Backspace
data = data.Replace("\f", "\\f"); // Formfeed
data = data.Replace("\t", "\\t"); // Horizontal tab
data = data.Replace("\v", "\\v"); // Vertical tab
data = data.Replace("\"", "\\\""); // Double quotation mark
data = data.Replace("'", "\\'"); // Single quotation mark
}
-- Edited (Add explanation) --
Q1: Is there a reason why you need to speed it up? Is it causing a huge problem?
This part is used in this project: http://mysqlbackuprestore.codeplex.com/
I'm going to loop lots of various length of strings into this function repeatly. The whole process takes around 6-15 seconds to finished for millions of rows. There are other part get involve too. I'm trying to speed up every part.
Q2: How slow is it now?
OK, I'll capture the exact time used and post it here. I'll come back later. (will post the result tomorrow)
Update 29-06-2012
I have run test. This is the result:
Speed Test: String.Replace() - measured in miliseconds
Test 1: 26749.7531 ms
Test 2: 27063.438 ms
Test 3: 27753.8884 ms
Average: 27189.0265 ms
Speed: 100%
Speed Test: Foreach Char and Append - measured in miliseconds
Test 1: 8468.4547 ms
Test 2: 8348.8527 ms
Test 3: 8353.6476 ms
Average: 8390.3183 ms
Speed: 224% < faster
===================================
Update - Next Test (Another round)
===================================
------
Test Replace String Speed.
Test 1: 26535.6466
Test 2: 26379.6464
Test 3: 26379.6463
Average: 26431.6464333333
Speed: 100%
------
Test Foreach Char String Append.
Test 1: 8502.015
Test 2: 8517.6149
Test 3: 8595.6151
Average: 8538.415
Speed: 309.56%
------
Test Foreach Char String Append (Fix StringBuilder Length).
Test 1: 8314.8146
Test 2: 8330.4147
Test 3: 8346.0146
Average: 8330.41463333333
Speed: 317.29%
Conclusion:
Using Foreach Char Loop and Append is faster than String.Replace().
Thanks you very much guys.
--------
Below are the codes that I used to run the test: (edited)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.Write("Press any key to continue...");
Console.ReadKey();
Console.Write("\r\nProcess started.");
Test();
Console.WriteLine("Done.");
Console.Read();
}
public static Random random = new Random((int)DateTime.Now.Ticks);
public static string RandomString(int size)
{
StringBuilder sb = new StringBuilder();
char ch;
for (int i = 0; i < size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
sb.Append(ch);
}
return sb.ToString();
}
public static void Test()
{
string text = "\\_\r\n\a\b\f\t\v\"'" + RandomString(2000) + "\\_\r\n\a\b\f\t\v\"'" + RandomString(2000);
List<TimeSpan> lstTimeUsed = new List<TimeSpan>();
int target = 100000;
for (int i = 0; i < 3; i++)
{
DateTime startTime = DateTime.Now;
for (int j = 0; j < target; j++)
{
if (j.ToString().EndsWith("000"))
{
Console.Clear();
Console.WriteLine("Test " + i.ToString());
Console.WriteLine(j.ToString() + " of " + target.ToString());
}
string data = text;
data = data.Replace("\\", "\\\\"); // Backslash
data = data.Replace("\r", "\\r"); // Carriage return
data = data.Replace("\n", "\\n"); // New Line
data = data.Replace("\a", "\\a"); // Vertical tab
data = data.Replace("\b", "\\b"); // Backspace
data = data.Replace("\f", "\\f"); // Formfeed
data = data.Replace("\t", "\\t"); // Horizontal tab
data = data.Replace("\v", "\\v"); // Vertical tab
data = data.Replace("\"", "\\\""); // Double quotation mark
data = data.Replace("'", "\\'"); // Single quotation mark
}
DateTime endTime = DateTime.Now;
TimeSpan ts = endTime - startTime;
lstTimeUsed.Add(ts);
}
double t1 = lstTimeUsed[0].TotalMilliseconds;
double t2 = lstTimeUsed[1].TotalMilliseconds;
double t3 = lstTimeUsed[2].TotalMilliseconds;
double tOri = (t1 + t2 + t3) / 3;
System.IO.TextWriter tw = new System.IO.StreamWriter("D:\\test.txt", true);
tw.WriteLine("------");
tw.WriteLine("Test Replace String Speed. Test Time: " + DateTime.Now.ToString());
tw.WriteLine("Test 1: " + t1.ToString());
tw.WriteLine("Test 2: " + t2.ToString());
tw.WriteLine("Test 3: " + t3.ToString());
tw.WriteLine("Average: " + tOri.ToString());
tw.WriteLine("Speed: 100%");
tw.Close();
lstTimeUsed = new List<TimeSpan>();
for (int i = 0; i < 3; i++)
{
DateTime startTime = DateTime.Now;
for (int j = 0; j < target; j++)
{
if (j.ToString().EndsWith("000"))
{
Console.Clear();
Console.WriteLine("Test " + i.ToString());
Console.WriteLine(j.ToString() + " of " + target.ToString());
}
string data = text;
var builder = new StringBuilder();
foreach (var ch in data)
{
switch (ch)
{
case '\\':
case '\r':
case '\n':
case '\a':
case '\b':
case '\f':
case '\t':
case '\v':
case '\"':
case '\'':
builder.Append('\\');
break;
default:
break;
}
builder.Append(ch);
}
}
DateTime endTime = DateTime.Now;
TimeSpan ts = endTime - startTime;
lstTimeUsed.Add(ts);
}
t1 = lstTimeUsed[0].TotalMilliseconds;
t2 = lstTimeUsed[1].TotalMilliseconds;
t3 = lstTimeUsed[2].TotalMilliseconds;
tw = new System.IO.StreamWriter("D:\\test.txt", true);
tw.WriteLine("------");
tw.WriteLine("Test Foreach Char String Append. Test Time: " + DateTime.Now.ToString());
tw.WriteLine("Test 1: " + t1.ToString());
tw.WriteLine("Test 2: " + t2.ToString());
tw.WriteLine("Test 3: " + t3.ToString());
tw.WriteLine("Average: " + ((t1 + t2 + t3) / 3).ToString());
tw.WriteLine("Speed: " + ((tOri) / ((t1 + t2 + t3) / 3) * 100).ToString("0.00") + "%");
tw.Close();
lstTimeUsed = new List<TimeSpan>();
for (int i = 0; i < 3; i++)
{
DateTime startTime = DateTime.Now;
for (int j = 0; j < target; j++)
{
if (j.ToString().EndsWith("000"))
{
Console.Clear();
Console.WriteLine("Test " + i.ToString());
Console.WriteLine(j.ToString() + " of " + target.ToString());
}
string data = text;
var builder = new StringBuilder(data.Length + 20);
foreach (var ch in data)
{
switch (ch)
{
case '\\':
case '\r':
case '\n':
case '\a':
case '\b':
case '\f':
case '\t':
case '\v':
case '\"':
case '\'':
builder.Append('\\');
break;
default:
break;
}
builder.Append(ch);
}
}
DateTime endTime = DateTime.Now;
TimeSpan ts = endTime - startTime;
lstTimeUsed.Add(ts);
}
t1 = lstTimeUsed[0].TotalMilliseconds;
t2 = lstTimeUsed[1].TotalMilliseconds;
t3 = lstTimeUsed[2].TotalMilliseconds;
tw = new System.IO.StreamWriter("D:\\test.txt", true);
tw.WriteLine("------");
tw.WriteLine("Test Foreach Char String Append (Fix StringBuilder Length). Test Time: " + DateTime.Now.ToString());
tw.WriteLine("Test 1: " + t1.ToString());
tw.WriteLine("Test 2: " + t2.ToString());
tw.WriteLine("Test 3: " + t3.ToString());
tw.WriteLine("Average: " + ((t1 + t2 + t3) / 3).ToString());
tw.WriteLine("Speed: " + ((tOri) / ((t1 + t2 + t3) / 3) * 100).ToString("0.00") + "%");
tw.Close();
}
}
}
var builder = new StringBuilder(data.Length + 20);
foreach (var ch in data)
{
switch (ch)
{
case '\\':
case '\r':
...
builder.Append('\\');
break;
}
builder.Append(ch);
}
return builder.ToString();
Try using a series of StringBuilder calls.

Categories