I'm using this proximity card scanner software to read my card for testing. They provide an SDK but it covers everything except desktop scanners, even though their software is able to read it fine. I noticed their software was coded in .NET and I was able to decompile it using JetBrains dotPeek. I'm very close to what I'm needing. I was able to fix the decompiled code except for these 3 lines. I'm unfamiliar with how to handle the encoding:
string[] array = ((IEnumerable<string>) ConfigurationManager.AppSettings.AllKeys).Where<string>((Func<string, bool>) (stg => stg.StartsWith(\uE0001.\uE000(27359)))).ToArray<string>();
string str = ((IEnumerable<string>) ConfigurationManager.AppSettings.AllKeys).Any<string>((Func<string, bool>) (stg => stg == \uE0001.\uE000(28615))) ? ConfigurationManager.AppSettings[\uE0001.\uE000(28615)] : directoryName;
assyTypeKey = index2.Replace(\uE0001.\uE000(28428), \uE0001.\uE000(28439));
I know they're Unicode characters but it's looking very foreign to me with that declaration next to it in parentheses. I'm not sure how to handle this.
Here's one of the functions. I know it's ugly but it's decompiled:
public static void LoadSubServices()
{
//SubServicesManager._logger.Info((object) \uE0001.\uE000(28243));
string[] array = ((IEnumerable<string>) ConfigurationManager.AppSettings.AllKeys).Where<string>((Func<string, bool>) (stg => stg.StartsWith(\uE0001.\uE000(27359)))).ToArray<string>();
label_2:
int num1 = 1;
while (true)
{
switch (num1)
{
case 0:
//SubServicesManager._logger.Error((object) \uE0001.\uE000(28270));
num1 = 2;
continue;
case 1:
if (array.Length == 0)
{
num1 = 0;
continue;
}
goto label_7;
case 2:
goto label_31;
default:
goto label_2;
}
}
label_7:
string directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName);
//SubServicesManager._logger.InfoFormat(\uE0001.\uE000(28582), (object) directoryName);
string str = ((IEnumerable<string>) ConfigurationManager.AppSettings.AllKeys).Any<string>((Func<string, bool>) (stg => stg == \uE0001.\uE000(28615))) ? ConfigurationManager.AppSettings[\uE0001.\uE000(28615)] : directoryName;
label_9:
int num2 = 1;
while (true)
{
switch (num2)
{
case 0:
//SubServicesManager._logger.ErrorFormat(\uE0001.\uE000(28621), (object) str);
num2 = 2;
continue;
case 1:
if (!Directory.Exists(str))
{
num2 = 0;
continue;
}
goto label_14;
case 2:
goto label_6;
default:
goto label_9;
}
}
label_6:
return;
label_14:
label_33:
for (int index1 = 0; index1 < array.Length; ++index1)
{
label_17:
int num3 = 2;
string appSetting1 = null;
string appSetting2 = null;
ILoadableServer loadableServer = null;
string index2 = null;
string assyTypeKey = null;
while (true)
{
switch (num3)
{
case 0:
//SubServicesManager._logger.InfoFormat(\uE0001.\uE000(28419), (object) appSetting1);
num3 = 1;
continue;
case 1:
loadableServer = SubServicesManager.LoadSubServiceAssembly(appSetting1, str, appSetting2);
num3 = 5;
continue;
case 2:
index2 = array[index1];
num3 = 3;
continue;
case 3:
assyTypeKey = index2.Replace(\uE0001.\uE000(28428), \uE0001.\uE000(28439));
num3 = 6;
continue;
case 4:
//SubServicesManager._logger.ErrorFormat(\uE0001.\uE000(28442), (object) appSetting1);
num3 = 9;
continue;
case 5:
if (loadableServer == null)
{
num3 = 4;
continue;
}
goto label_29;
case 6:
appSetting2 = ConfigurationManager.AppSettings[index2];
num3 = 7;
continue;
case 7:
if (((IEnumerable<string>) ConfigurationManager.AppSettings.AllKeys).Any<string>((Func<string, bool>) (stg => stg == assyTypeKey)))
{
num3 = 8;
continue;
}
goto label_30;
case 8:
appSetting1 = ConfigurationManager.AppSettings[assyTypeKey];
num3 = 0;
continue;
case 9:
goto label_33;
default:
goto label_17;
}
}
label_29:
SubServicesManager._loadableServices.Add(loadableServer);
//SubServicesManager._logger.InfoFormat(\uE0001.\uE000(28496));
continue;
label_30:
return;
//SubServicesManager._logger.WarnFormat(\uE0001.\uE000(28525), (object) index2, (object) appSetting2);
}
return;
label_31:;
}
Related
I have a switch statement that assigns a value to an array of two dimensions depending on the case. The problem is that sometimes the cases are skipped and the default case is called. There seems to be no pattern to the functioning of the switch (sometimes works and sometimes goes to default).
I have tried changing the type of the value that I am giving to the switch from float to string because, in other questions that I saw before, the problem was the data type.
I also checked that the value that I was giving to the switch was one of the cases and I debug.log the "code"(variable of the value that I am giving to my switch) and it is always one of the cases.
I even changed the switch statement to a chain of if-else statements to see if I wrote the switch wrong but that didn't help.
The following code is a function that is generating the "code" that is given to the switch function that goes to default.
private void NodeEnumeration()
{
//for each node in _mapArray
for(int i = 0; i < _mapSize; i++)
{
for(int e = 0; e < _mapSize; e++)
{
//if node value is not 0
if(_mapArray[i, e] != 0)
{
float code = 0f;
//Left
if(e != 0)
{
_surroundingNodesPositions[0].x = e - 1;
_surroundingNodesPositions[0].y = i;
if(_mapArray[(int)_surroundingNodesPositions[0].y, (int)_surroundingNodesPositions[0].x] > 0)
{
code += 1f;
}
}
//Up
if(i != 0)
{
_surroundingNodesPositions[1].x = e;
_surroundingNodesPositions[1].y = i - 1;
if(_mapArray[(int)_surroundingNodesPositions[1].y, (int)_surroundingNodesPositions[1].x] > 0)
{
code += 0.1f;
}
}
//Right
if(e != _mapSize - 1)
{
_surroundingNodesPositions[2].x = e + 1;
_surroundingNodesPositions[2].y = i;
if(_mapArray[(int)_surroundingNodesPositions[2].y, (int)_surroundingNodesPositions[2].x] > 0)
{
code += 0.01f;
}
}
//Down
if(i != _mapSize - 1)
{
_surroundingNodesPositions[3].x = e;
_surroundingNodesPositions[3].y = i + 1;
if(_mapArray[(int)_surroundingNodesPositions[3].y, (int)_surroundingNodesPositions[3].x] > 0)
{
code += 0.001f;
}
}
AssignValue(i, e, code);//! Here is the problem
}
}
}
}
private void AssignValue(int i, int e, float code)
{
switch(code)
{
case 1.111f:
_mapArray[i, e] = 1;
break;
case 1.110f:
_mapArray[i, e] = 2;
break;
case 1.101f:
_mapArray[i, e] = 3;
break;
case 1.100f:
_mapArray[i, e] = 4;
break;
case 1.011f:
_mapArray[i, e] = 5;
break;
case 1.010f:
_mapArray[i, e] = 6;
break;
case 1.001f:
_mapArray[i, e] = 7;
break;
case 1.000f:
_mapArray[i, e] = 8;
break;
case 0.111f:
_mapArray[i, e] = 9;
break;
case 0.110f:
_mapArray[i, e] = 10;
break;
case 0.101f:
_mapArray[i, e] = 11;
break;
case 0.100f:
_mapArray[i, e] = 12;
break;
case 0.011f:
_mapArray[i, e] = 13;
break;
case 0.010f:
_mapArray[i, e] = 14;
break;
case 0.001f:
_mapArray[i, e] = 15;
break;
case 0.000f:
_mapArray[i, e] = 16;
break;
default:
Debug.LogError("MapGenerator::NodeEnumeration()::AssignValue() no value can be assigned | code: " + code);
Debug.Log("height: " + i + " width: " + e);
break;
}
}
The problem that you're dealing with is a result of floating point (im)precision. Read through the answer here, as it explains it a lot better that I could do.
TLDR: you can't rely on decimal math to be precise, even simple equations such as 0.1f + 0.2f != 0.3f. In most cases, you should just use integer math, or epsilons for judging if two floating point values are equal:
private static float EPSILON = 0.0005f;
public static bool AreApproximatelyEqual(float a, float b)
{
return Mathf.Abs(a - b) < EPSILON;
}
However, in your case specifically, we can do a LOT better than just using floating point epsilons, or even integer math. Using boolean math is the best way to go about this, with a concept called "flags".
Notice how the final value assigned into the _mapArray is always equal to 16 - value (when removing the decimal point, and converting the value to binary). Example: 1.111f = 0b1111 in binary, = 15 in decimal. 16-15 = 1, your intended value.
Since this holds true for all of your cases, we can set each bit within the using the OR operation:
0100
|= 0010
---------
0110
The final implementation then would look something like this:
private void NodeEnumeration()
{
//for each node in _mapArray
for(int i = 0; i < _mapSize; i++)
{
for(int e = 0; e < _mapSize; e++)
{
//if node value is not 0
if(_mapArray[i, e] != 0)
{
int code = 0; //change our code to be an integer. we could go all the way down to a byte, if you wanted.
//Left
if(e != 0)
{
_surroundingNodesPositions[0].x = e - 1;
_surroundingNodesPositions[0].y = i;
if(_mapArray[(int)_surroundingNodesPositions[0].y, (int)_surroundingNodesPositions[0].x] > 0)
{
code |= 0b1000; //set the 4th bit in this case. Equivalent to += 8
}
}
//Up
if(i != 0)
{
_surroundingNodesPositions[1].x = e;
_surroundingNodesPositions[1].y = i - 1;
if(_mapArray[(int)_surroundingNodesPositions[1].y, (int)_surroundingNodesPositions[1].x] > 0)
{
code |= 0b0100; //set the 3rd bit in this case. Equivalent to += 4
}
}
//Right
if(e != _mapSize - 1)
{
_surroundingNodesPositions[2].x = e + 1;
_surroundingNodesPositions[2].y = i;
if(_mapArray[(int)_surroundingNodesPositions[2].y, (int)_surroundingNodesPositions[2].x] > 0)
{
code |= 0b0010; //set the 2nd bit in this case. Equivalent to += 2
}
}
//Down
if(i != _mapSize - 1)
{
_surroundingNodesPositions[3].x = e;
_surroundingNodesPositions[3].y = i + 1;
if(_mapArray[(int)_surroundingNodesPositions[3].y, (int)_surroundingNodesPositions[3].x] > 0)
{
code |= 0b0001; //Set the 1st bit in this case. Equivalent to += 1
}
}
_mapArray[i, e] = 16 - flags;
}
}
}
}
so as the title says my C# code is not running/debugging even though i have 0 errors being shown.
I begin the debugging and all that happens is the console screen flashes quickly then exits with 0 errors. Even the .exe in the bin\debug folder does the exact same. All i'm receiving is a wall of text in the output section.
Algorithms.vshost.exe' (CLR v4.0.30319: Algorithms.vshost.exe): Loaded C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\Accessibility\v4.0_4.0.0.0__b03f5f7f11d50a3a\Accessibility.dll. Symbols loaded.
The thread 0x12b8 has exited with code 0 (0x0).
The thread 0x289c has exited with code 0 (0x0).
The program [15012] Algorithms.vshost.exe has exited with code 0 (0x0).
I hope this is understandable enough! I would appreciate any help, thanks!
Code as requested by some! I hope it's helpful! I appreciate all the answers and help so far!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AlgorithmsResit
{
class Program
{
private static void Main(string[] args)
{ }
public static void AlgorithmSortInt(int[] array)
{
int j = array.Length - 1;
int x, i, temp;
for (x = 1; x <= j; ++x)
{
temp = array[x];
for (i = x - 1; i >= 0; --i)
{
if (temp < array[i]) array[i + 1] = array[i];
else break;
}
array[1 + 1] = temp;
}
}
public static void AlgorithmSortDouble(double[] array)
{
int j = array.Length - 1;
int x, i;
double temp;
for (x = 1; x <= j; ++x)
{
temp = array[x];
for (i = x - 1; i >= 0; --i)
{
if (temp < array[i]) array[i + 1] = array[i];
else break;
}
array[i + 1] = temp;
}
}
public static void AlgorithmDateTime(DateTime[] array)
{
int j = array.Length - 1;
int x, i;
DateTime temp;
for (x = 1; x <= j; ++x)
{
temp = array[x];
for (i = x - 1; i >= 0; --i)
{
if (temp < array[i]) array[i + 1] = array[i];
else break;
}
array[i + 1] = temp;
}
}
public static void StringToSort(string[] array)
{
int x = array.Length - 1;
for (int j = 0; j < x; j++)
{
for (int i = x; i > j; i--)
{
if (((IComparable)array[i - 1]).CompareTo(array[i]) > 0)
{
var temp = array[i - 1];
array[i - 1] = array[i];
array[i] = temp;
}
}
}
}
static void main(string[] args)
{
string[] Day1 = System.IO.File.ReadAllLines(#"TextFiles/Day_1.txt");
List<int> Day1List = new List<int>();
foreach (string Day in Day1)
{
int Days = Convert.ToInt32(Day);
Day1List.Add(Days);
}
int[] Day1Arr = Day1List.ToArray();
string[] Depth1 = System.IO.File.ReadAllLines(#"TextFiles/Depth_1.txt");
List<double> Depth1List = new List<double>();
foreach (string Depth in Depth1)
{
double Depths = Convert.ToDouble(Depth);
Depth1List.Add(Depths);
}
double[] Depth1Arr = Depth1List.ToArray();
string[] IRISID1 = System.IO.File.ReadAllLines(#"TextFiles/IRIS_ID_1.txt");
List<int> Iris1List = new List<int>();
foreach (string IRIS in IRISID1)
{
int Iris = Convert.ToInt32(IRIS);
Iris1List.Add(Iris);
}
int[] Iris1Arr = Iris1List.ToArray();
string[] Latitude1 = System.IO.File.ReadAllLines(#"TextFiles/Latitude_1.txt");
List<double> Latitude1List = new List<double>();
foreach (string Lat in Latitude1)
{
double Latitude = Convert.ToDouble(Latitude1);
Latitude1List.Add(Latitude);
}
double[] Latitude1Arr = Latitude1List.ToArray();
string[] Longitude1 = System.IO.File.ReadAllLines(#"TextFiles/Longitude_1.txt");
List<double> Longitude1List = new List<double>();
foreach (string Longitude in Longitude1)
{
double Longitudes = Convert.ToDouble(Longitude1);
Longitude1List.Add(Longitudes);
}
double[] Longitude1Arr = Longitude1List.ToArray();
string[] Magnitude1 = System.IO.File.ReadAllLines(#"TextFiles/Magnitude_1.txt");
List<Double> Magnitude1List = new List<Double>();
foreach (string Magnitude in Magnitude1)
{
double Magnitudes = Convert.ToDouble(Magnitude1);
Magnitude1List.Add(Magnitudes);
}
double[] Magnitude1Arr = Magnitude1List.ToArray();
string[] Month1 = System.IO.File.ReadAllLines(#"TextFiles/Month_1.txt");
string[] Region1 = System.IO.File.ReadAllLines(#"TextFiles/Region_1.txt");
string[] Time1 = System.IO.File.ReadAllLines(#"TextFiles/Time_1.txt");
List<DateTime> Time1List = new List<DateTime>();
foreach (string Time in Time1)
{
DateTime Times = Convert.ToDateTime(Time);
Time1List.Add(Times);
}
DateTime[] Time1Arr = Time1List.ToArray();
string[] Timestamp1 = System.IO.File.ReadAllLines(#"TextFiles/Timestamp_1.txt");
List<int> Timestamp1List = new List<int>();
foreach (string Timestamp in Timestamp1)
{
int Timestamps = Convert.ToInt32(Timestamp);
Timestamp1List.Add(Timestamps);
}
int[] Timestamp1Arr = Timestamp1List.ToArray();
string[] Year1 = System.IO.File.ReadAllLines(#"TextFiles/Year_1.txt");
List<int> Year1List = new List<int>();
foreach (String Date in Year1)
{
int Dates = Convert.ToInt32(Date);
Year1List.Add(Dates);
}
int[] Year1Arr = Year1List.ToArray();
string UserArrayChoice, AscOrDescChoice;
int ArrayChoice;
int count = 0;
do
{
count++;
Console.Write("{0} ", Day1Arr[count]);
Console.Write("{0} ", Depth1[count]);
Console.Write("{0} ", IRISID1[count]);
Console.Write("{0} ", Latitude1Arr[count]);
Console.Write("{0} ", Longitude1Arr[count]);
Console.Write("{0} ", Magnitude1Arr[count]);
Console.Write("{0} ", Month1[count]);
Console.Write("{0} ", Region1[count]);
Console.Write("{0} ", Time1Arr[count]);
Console.Write("{0} ", Timestamp1Arr[count]);
Console.Write("{0}", Year1Arr[count]);
Console.Write("\n");
} while (count < Year1Arr.Length - 1);
Console.WriteLine("Enter the number of the file you would like to sort... \n1 ) Day_1.txt\n2 ) Depth_1.txt\n3 ) IRIS_ID_.txt\n4 ) Latitude_1.txt\n5 ) Longitude_1.txt\n6 ) Magnitude_1.txt\n7 ) Month_1.txt\n8 ) Region_1.txt\n9 ) Time_1.txt\n10 ) Timestamp_1.txt\n11 ) Year_1.txt\n12");
UserArrayChoice = Console.ReadLine();
ArrayChoice = Convert.ToInt32(UserArrayChoice);
switch (UserArrayChoice)
{
case "1":
UserArrayChoice = "Day_1.txt";
break;
case "2":
UserArrayChoice = "Depth_1.txt";
break;
case "3":
UserArrayChoice = "IRIS_ID_1.txt";
break;
case "4":
UserArrayChoice = "Latitude_1.txt";
break;
case "5":
UserArrayChoice = "Longitude_1.txt";
break;
case "6":
UserArrayChoice = "Magnitude_1.txt";
break;
case "7":
UserArrayChoice = "Month_1.txt";
break;
case "8":
UserArrayChoice = "Region_1.txt";
break;
case "9":
UserArrayChoice = "Time_1.txt";
break;
case "10":
UserArrayChoice = "Timestamp_1.txt";
break;
case "11":
UserArrayChoice = "Year_1.txt";
break;
default:
break;
}
Console.WriteLine("---------------------------------------------------------------------------");
Console.WriteLine("{0} Has been selected, would you like to sort by Ascending or Descending? ", UserArrayChoice);
Console.WriteLine("---------------------------------------------------------------------------");
AscOrDescChoice = Console.ReadLine();
if (AscOrDescChoice == "Ascending" | AscOrDescChoice == "ascending")
{
Console.WriteLine("---------------------------------");
Console.WriteLine("{0} Will sort in Ascending order!", UserArrayChoice);
Console.WriteLine("---------------------------------");
switch (ArrayChoice)
{
case 1:
AlgorithmSortInt(Day1Arr);
foreach (int temp in Day1Arr)
{
Console.WriteLine("{0} ", temp);
}
break;
case 2:
AlgorithmSortDouble(Depth1Arr);
foreach (double temp in Depth1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
case 3:
AlgorithmSortInt(Iris1Arr);
foreach (int temp in Iris1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
case 4:
AlgorithmSortDouble(Latitude1Arr);
foreach (double temp in Latitude1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
case 5:
AlgorithmSortDouble(Longitude1Arr);
foreach (double temp in Longitude1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
case 6:
AlgorithmSortDouble(Magnitude1Arr);
foreach (double temp in Magnitude1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
case 7:
StringToSort(Month1);
foreach (string temp in Month1)
{
Console.WriteLine("{0}", temp);
}
break;
case 8:
StringToSort(Region1);
foreach (string temp in Region1)
{
Console.WriteLine("{0}", temp);
}
break;
case 9:
AlgorithmDateTime(Time1Arr);
foreach (DateTime temp in Time1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
case 10:
AlgorithmSortInt(Timestamp1Arr);
foreach (int temp in Timestamp1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
case 11:
AlgorithmSortInt(Year1Arr);
foreach (int temp in Year1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
}
}
else if (AscOrDescChoice == "Descending" | AscOrDescChoice == "descending")
{
Console.WriteLine("----------------------------------");
Console.WriteLine("{0} Will sort in Descending order!", UserArrayChoice);
Console.WriteLine("----------------------------------");
switch (ArrayChoice)
{
case 1:
AlgorithmSortInt(Day1Arr);
Array.Reverse(Day1Arr);
foreach (int temp in Day1Arr)
{
Console.WriteLine("{0} ", temp);
}
break;
case 2:
AlgorithmSortDouble(Depth1Arr);
Array.Reverse(Depth1Arr);
foreach (double temp in Depth1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
case 3:
AlgorithmSortInt(Iris1Arr);
Array.Reverse(Iris1Arr);
foreach (int temp in Iris1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
case 4:
AlgorithmSortDouble(Latitude1Arr);
Array.Reverse(Latitude1Arr);
foreach (double temp in Latitude1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
case 5:
AlgorithmSortDouble(Longitude1Arr);
Array.Reverse(Longitude1Arr);
foreach (double temp in Longitude1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
case 6:
AlgorithmSortDouble(Magnitude1Arr);
Array.Reverse(Magnitude1Arr);
foreach (double temp in Magnitude1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
case 7:
StringToSort(Month1);
Array.Reverse(Month1);
foreach (string temp in Month1)
{
Console.WriteLine("{0}", temp);
}
break;
case 8:
StringToSort(Region1);
Array.Reverse(Region1);
foreach (string temp in Region1)
{
Console.WriteLine("{0}", temp);
}
break;
case 9:
AlgorithmDateTime(Time1Arr);
Array.Reverse(Time1Arr);
foreach (DateTime temp in Time1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
case 10:
AlgorithmSortInt(Timestamp1Arr);
Array.Reverse(Timestamp1Arr);
foreach (int temp in Timestamp1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
case 11:
AlgorithmSortInt(Year1Arr);
Array.Reverse(Year1Arr);
foreach (int temp in Year1Arr)
{
Console.WriteLine("{0}", temp);
}
break;
}
}
else
{
Console.WriteLine("-------------------");
Console.WriteLine("Incorrect Response!");
Console.WriteLine("-------------------");
}
Console.WriteLine("Enter the number of the file you would like to search... \n1 ) Day_1.txt\n2 ) Depth_1.txt\n3 ) IRIS_ID_1\n4 ) Latitude_1\n5 ) Longitude_1\n6 ) Magnitude_1\n7 ) Month_1\n8 ) Region_1\n9 ) Time_1\n10 ) Timestamp_1\n11 ) Year_1\n12");
UserArrayChoice = Console.ReadLine();
ArrayChoice = Convert.ToInt32(UserArrayChoice);
switch (UserArrayChoice)
{
case "1":
UserArrayChoice = "Day_1.txt";
break;
case "2":
UserArrayChoice = "Depth_1.txt";
break;
case "3":
UserArrayChoice = "IRIS_ID_1.txt";
break;
case "4":
UserArrayChoice = "Latitude_1.txt";
break;
case "5":
UserArrayChoice = "Longitude_1.txt";
break;
case "6":
UserArrayChoice = "Magnitude_1.txt";
break;
case "7":
UserArrayChoice = "Month_1.txt";
break;
case "8":
UserArrayChoice = "Region_1.txt";
break;
case "9":
UserArrayChoice = "Time_1.txt";
break;
case "10":
UserArrayChoice = "Timestamp_1.txt";
break;
case "11":
UserArrayChoice = "Year_1.txt";
break;
default:
break;
}
Console.WriteLine("--------------------------------------------------------------------");
Console.WriteLine("{0} has been selected! Please enter what you would like to search - ", UserArrayChoice);
Console.WriteLine("--------------------------------------------------------------------");
string SearchTemp = Console.ReadLine();
bool Found = false;
int counter = 0;
switch (ArrayChoice)
{
case 1:
int SearchDay = Convert.ToInt32(SearchTemp);
for (int x = 0; x < Day1Arr.Length; x++)
{
if (SearchDay == Day1Arr[x])
{
Found = true;
}
}
if (Found == true) { Console.WriteLine("Successful! :-)"); }
else { Console.WriteLine("Unsuccessful! Sorry :-("); }
break;
case 2:
double DepthSearch = Convert.ToDouble(SearchTemp);
for (int x = 0; x < Depth1Arr.Length; x++)
{
if (DepthSearch == Depth1Arr[x])
{
Found = true;
}
}
if (Found == true) { Console.WriteLine("Successful!:-)"); }
else { Console.WriteLine("Unsuccessful! Sorry :-("); }
break;
case 3:
int SearchIris = Convert.ToInt32(SearchTemp);
for (int x = 0; x < Iris1Arr.Length; x++)
{
if (SearchIris == Iris1Arr[x])
{
Found = true;
}
}
if (Found == true) { Console.WriteLine("Successful! :-)"); }
else { Console.WriteLine("Unsuccessful! Sorry :-("); }
break;
case 4:
double SearchLatitude = Convert.ToDouble(SearchTemp);
for (int x = 0; x < Latitude1Arr.Length; x++)
{
if (SearchLatitude == Latitude1Arr[x])
{
Found = true;
}
}
if (Found == true) { Console.WriteLine("Successful! :-)"); }
else { Console.WriteLine("Unsuccessful! Sorry :-("); }
break;
case 5:
double SearchLong = Convert.ToDouble(SearchTemp);
for (int x = 0; x < Longitude1Arr.Length; x++)
{
if (SearchLong == Longitude1Arr[x])
{
Found = true;
}
}
if (Found == true) { Console.WriteLine("Successful! :-)"); }
else { Console.WriteLine("Unsuccessful! Sorry :-("); }
break;
case 6:
double SearchMag = Convert.ToDouble(SearchTemp);
for (int x = 0; x < Magnitude1Arr.Length; x++)
{
if (SearchMag == Magnitude1Arr[x])
{
Found = true;
}
}
if (Found == true) { Console.WriteLine("Successful! :-)"); }
else { Console.WriteLine("Unsuccessful! Sorry :-("); }
break;
case 7:
foreach (var Months in Month1)
{
if (Months.Contains(SearchTemp))
{
count++;
Found = true;
Console.Write("{0} ", Day1Arr[counter]);
Console.Write("{0} ", Depth1Arr[counter]);
Console.Write("{0} ", Iris1Arr[counter]);
Console.Write("{0} ", Latitude1Arr[counter]);
Console.Write("{0} ", Longitude1Arr[counter]);
Console.Write("{0} ", Magnitude1Arr[counter]);
Console.Write("{0} ", Month1[counter]);
Console.Write("{0} ", Region1[counter]);
Console.Write("{0} ", Time1Arr[counter]);
Console.Write("{0} ", Timestamp1Arr[counter]);
Console.Write("{0} ", Year1Arr[counter]);
Console.Write("\n");
}
}
if (Found == true) { Console.WriteLine("Successful! :-)"); }
else { Console.WriteLine("Unsuccessful! Sorry :-("); }
break;
case 8:
foreach (var Regions in Region1)
{
if (Regions.Contains(SearchTemp))
{
Found = true;
}
}
if (Found == true) { Console.WriteLine("Successful! :-)"); }
else { Console.WriteLine("Unsuccessful! Sorry :-("); }
break;
case 9:
DateTime SearchDate = Convert.ToDateTime(SearchTemp);
for (int x = 0; x < Time1Arr.Length; x++)
{
if (SearchDate == Time1Arr[x])
{
Found = true;
}
}
if (Found == true) { Console.WriteLine("Successful! :-)"); }
else { Console.WriteLine("Unsuccessful! Sorry :-("); }
break;
case 10:
int SearchTimestamp = Convert.ToInt32(SearchTemp);
for (int x = 0; x < Timestamp1Arr.Length; x++)
{
if (SearchTimestamp == Timestamp1Arr[x])
{
Found = true;
}
}
if (Found == true) { Console.WriteLine("Successful! :-)"); }
else { Console.WriteLine("Unsuccessful! Sorry :-("); }
break;
case 11:
int SearchYear = Convert.ToInt32(SearchTemp);
for (int x = 0; x < Year1Arr.Length; x++)
{
{
Found = true;
}
}
if (Found == true) { Console.WriteLine("Successful! :-)"); }
else { Console.WriteLine("Unsuccessful! Sorry :-("); }
break;
}
}
}
}
What I know that it is just debugging message. You can switch that off by right clicking into the output window and uncheck the thread ended message.
http://msdn.microsoft.com/en-us/library/bs4c1wda.aspx
(1)Please add a breakpoint in your app, and then debug it again.
Like this thread:
Keeping console window open when debugging.
(2)If you run it with “start without debugging”, it would not be closed. You could also add Console.ReadLine()in your app like this thread.
(3)If you just debug your app and get this messages, please also enable the Exceptions settings under Debugger->Windows menu, and make sure that no Exception.
there is a project for Windows application that I'm still working on and is about a set of card deck. The application utilizes 52 cards which consist of 4 suits and 13 face values such as 2 of Clubs, Jack of Hearts, and so forth. The part that I'm working is that I also have to use five pictureboxes to display each random card so I click on a "Deal" button. I'm aware that I would have to use a "Random" keyword along with using a for-loop to do the shuffle.
Therefore, I'm not too sure how would I display each picturebox with different random cards and display each card's name accordingly.
Beneath of this contain screenshots of what the windows application looks like and my code for the project.
List<PlayingCard> cardDeckList = new List<PlayingCard>();
private void buttonDeal_Click(object sender, EventArgs e)
{
int integer = 0;
Random picRandom = new Random();
int n = 0;
integer = picRandom.Next(0, imageListCards.Images.Count);
for( n = 0; n < cardDeckList.Count; n++)
{
pictureBox_Card1.Image = cardDeckList[integer].CardImage;
pictureBox_Card2.Image = cardDeckList[integer].CardImage;
pictureBox_Card3.Image = cardDeckList[integer].CardImage;
pictureBox_Card4.Image = cardDeckList[integer].CardImage;
pictureBox_Card5.Image = cardDeckList[integer].CardImage;
}
listBoxOutput.Items.Add(cardDeckList[integer].ToString());
}
private void FormShuffleCardDeck_Load(object sender, EventArgs e)
{
try
{
string[] suitList = { "Clubs", "Diamonds", "Hearts", "Spades" };
string[] faceList = new string[13];
List<int> pointValues = new List<int>();
pointValues.Add(2);
pointValues.Add(3);
pointValues.Add(4);
pointValues.Add(5);
pointValues.Add(6);
pointValues.Add(7);
pointValues.Add(8);
pointValues.Add(9);
pointValues.Add(10);
pointValues.Add(10);
pointValues.Add(11);
string suit = "";
string face = "";
int counter = 0;
int i = 0;
int k = 0;
for (i = 0; i < 4; i++)
{
suit = i.ToString();
switch (suit)
{
case "0":
suit = "Clubs";
break;
case "1":
suit = "Diamonds";
break;
case "2":
suit = "Hearts";
break;
case "3":
suit = "Spades";
break;
}
for (k = 0; k < 13; k++)
{
face = k.ToString();
switch (k)
{
case 0:
face = "2";
break;
case 1:
face = "3";
break;
case 2:
face = "4";
break;
case 3:
face = "5";
break;
case 4:
face = "6";
break;
case 5:
face = "7";
break;
case 6:
face = "8";
break;
case 7:
face = "9";
break;
case 8:
face = "10";
break;
case 9:
face = "Ace";
break;
case 10:
face = "King";
break;
case 11:
face = "Jack";
break;
case 12:
face = "Queen";
break;
}
cardDeckList.Add(new PlayingCard(suit, face, imageListCards.Images[counter],2));
counter++;
}
}
//for (int l = 0; l < cardDeckList.Count; l++)
//{
// listBoxOutput.Items.Add(cardDeckList[l].ToString());
// //MessageBox.Show(cardDeckList.Count.ToString());
//}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Windows App Program
I'm not sure how your PlayingCard class is coded, but it seems like a large portion of your problems stem from its design. Take this implementation for example:
PlayingCard Class
public class PlayingCard : IComparable<PlayingCard>
{
private int value;
private int suit;
private Bitmap cardImage;
public int Value => value;
public string ValueName => ValueToName(value);
public int Suit => suit;
public string SuitName => SuitToName(suit);
public Bitmap CardImage => cardImage;
public PlayingCard(int value, int suit, Bitmap cardImage)
{
this.value = value;
this.suit = suit;
this.cardImage = cardImage;
}
private string ValueToName(int n)
{
switch (n)
{
case 0:
return "Ace";
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
return (n+1).ToString();
case 10:
return "Jack";
case 11:
return "Queen";
case 12:
return "King";
default:
throw new ArgumentException("Unrecognized card value.");
}
}
private string SuitToName(int s)
{
switch (s)
{
case 0:
return "Clubs";
case 1:
return "Diamonds";
case 2:
return "Spades";
case 3:
return "Hearts";
default:
throw new ArgumentException("Unrecognized card suit");
}
}
public int CompareTo(PlayingCard other)
{
int result = this.Suit.CompareTo(other.Suit);
if (result != 0)
return result;
return this.Value.CompareTo(other.Value);
}
public override string ToString()
{
return String.Format("{0} of {1}", ValueName, SuitName);
}
}
It has all the comparison and value conversion coded within it, so you don't have to worry about creating highly specialized methods to do extraneous conversions. You can use it in a deck like so:
Array Implementation
// How to initialize deck
PlayingCard[] deck = Enumerable.Range(0, 52)
.Select(x => new PlayingCard(x % 13, x / 13, imageListCards[x]))
.ToArray();
// How to shuffle deck
Random r = new Random();
Array.Sort(deck, (a, b) => r.Next(0, 2) == 0 ? -1 : 1);
// How to reset deck
Array.Sort(deck);
// How to display top five cards
pictureBox_Card1.Image = deck[0].CardImage;
pictureBox_Card2.Image = deck[1].CardImage;
pictureBox_Card3.Image = deck[2].CardImage;
pictureBox_Card4.Image = deck[3].CardImage;
pictureBox_Card5.Image = deck[4].CardImage;
List Implementation
// How to initialize deck
List<PlayingCard> deck = Enumerable.Range(0, 52)
.Select(x => new PlayingCard(x % 13, x / 13, imageListCards[x]))
.ToList();
// How to shuffle deck
Random r = new Random();
deck.Sort((a, b) => r.Next(0, 2) == 0 ? -1 : 1);
// How to reset deck
deck.Sort();
// How to display top five cards
pictureBox_Card1.Image = deck[0].CardImage;
pictureBox_Card2.Image = deck[1].CardImage;
pictureBox_Card3.Image = deck[2].CardImage;
pictureBox_Card4.Image = deck[3].CardImage;
pictureBox_Card5.Image = deck[4].CardImage;
EDIT:
Manual Shuffling
If you want to do a shuffle manually, there's a simple algorithm called the Fisher-Yates Shuffle that will do the trick:
private static Random r = new Random();
static void Shuffle<T>(T[] array)
{
for (int i = 0; i < array.Length; i++)
{
int idx = r.Next(i, array.Length);
T temp = array[idx];
array[idx] = array[i];
array[i] = temp;
}
}
(List Implementation)
private static Random r = new Random();
static void Shuffle<T>(List<T> list)
{
for (int i = 0; i < list.Count; i++)
{
int idx = r.Next(i, list.Count);
T temp = list[idx];
list[idx] = list[i];
list[i] = temp;
}
}
I have some months read into an array from an external text file and I need to convert the months to an array that holds the value equivalent of the months e.g. January = 1, February = 2 etc. So that they can then be put through Quicksort.
public static void Main(string[] args)
{
//Read external files into arrays.
string[] Month = File.ReadLines(#"Month.txt").ToArray();
string[] Year = File.ReadLines(#"Year.txt").ToArray();
//Convert arrays from string to double to be used in sort.
double[] YearSort = Array.ConvertAll(Year, double.Parse);
int UserInput1;
//Create new array that will hold selected array to be used in sort.
double[] data = new double[1022];
//Prompt user to select action.
Console.WriteLine("Press 1 to Sort by month or 2 to sort by year.");
UserInput1 = Convert.ToInt32(Console.ReadLine());
if(UserInput1 == 1)
{
Array.Copy(Month,data,1022);
QuickSort(data);
for (int i = 0; i < 1022; i++)
Console.WriteLine(data[i]);
Console.WriteLine();
}
else if (UserInput1 == 2)
{
Array.Copy(YearSort,data,1022);
QuickSort(data);
for (int i = 0; i < 1022; i++)
Console.WriteLine(data[i]);
Console.WriteLine();
}
else
{
Console.WriteLine("Please try again and select a valid option");
}
}
static int MonthToDouble( string Month )
{
int NewMonth = 0;
switch(Month)
{
case "January":
case "january":
NewMonth = 1;
break;
case "February":
case "february":
NewMonth = 2;
break;
case "March":
case "march":
NewMonth = 3;
break;
case "April":
case "april":
NewMonth = 4;
break;
case "May":
case "may":
NewMonth = 5;
break;
case "June":
case "june":
NewMonth = 6;
break;
case "July":
case "july":
NewMonth = 7;
break;
case "August":
case "august":
NewMonth = 8;
break;
case "September":
case "september":
NewMonth = 9;
break;
case "October":
case "october":
NewMonth = 10;
break;
case "November":
case "november":
NewMonth = 11;
break;
case "December":
case "december":
NewMonth = 12;
break;
}
return NewMonth;
}
static string DoubleToMonth(double Month)
{
string NewMonth = "";
switch ((int)Month)
{
case 1:
NewMonth = "January";
break;
case 2:
NewMonth = "February";
break;
case 3:
NewMonth = "March";
break;
case 4:
NewMonth = "April";
break;
case 5:
NewMonth = "May";
break;
case 6:
NewMonth = "June";
break;
case 7:
NewMonth = "July";
break;
case 8:
NewMonth = "August";
break;
case 9:
NewMonth = "September";
break;
case 10:
NewMonth = "October";
break;
case 11:
NewMonth = "November";
break;
case 12:
NewMonth = "December";
break;
}
return NewMonth;
}
//QuickSort for double data values are in ascending order.
public static void QuickSort(double[] data)
{
Quick_Sort(data, 0, data.Length - 1);
}
public static void Quick_Sort(double[] data, int left, int right)
{
int i, j;
double pivot, temp;
i = left;
j = right;
pivot = data[(left + right) / 2];
do
{
while ((data[i] < pivot) && (i < right)) i++;
while ((pivot < data[j]) && (j > left)) j--;
if (i <= j)
{
temp = data[i];
data[i] = data[j];
data[j] = temp;
i++;
j--;
}
} while (i <= j);
if (left < j) Quick_Sort(data, left, j);
if (i < right) Quick_Sort(data, i, right);
}
}
A DateTime object's Month property gives you the integer value of the month starting at 1 like you need. So you can use DateTime.ParseExact() to parse the string into a full DateTime object then grab the Month property:
int monthNumber = DateTime.ParseExact("January", "MMMM", CultureInfo.CurrentCulture).Month;
You just need to replace "January" with your month strings, and leave "MMMM"which is the Custom Format String for "The full name of the month".
All the above code does is simplify your MonthToDouble() method, which you are not even using for some reason (also it should return a double, not an int). Contrary to your title, you already have a method to "Convert months to number equivalent", you just aren't using it.
So, I assume the only thing you are missing is to replace this:
Array.Copy(Month,data,1022);
QuickSort(data);
With this:
double[] monthsAsDoubles = new double[Month.Length];
for (int i = 0; i < monthsAsDoubles.Length; i++)
{
monthsAsDoubles[i] = MonthToDouble(Month[i]);
}
QuickSort(monthsAsDoubles);
Also change the return value of MonthToDouble() from int to double (cast if you need to).
Edit: On second thought, Quantic's answer is simpler. I'll just leave this here as an alternative.
Your code can be simplified a lot by using the DateTimeFormatInfo.MonthNames property, along with a case-insensitive string comparison. This also has the advantage of being much easier to port to use different languages for the month names.
Here is a snippet:
using System;
using System.Globalization;
using System.Linq;
using System.Collections.Generic;
public class Test
{
public static void Main()
{
var InputMonths = new List<string> { "January","march","sepTEmber","smarch" };
var MonthNames = new DateTimeFormatInfo().MonthNames.ToList();
var InputMonthNumbers = new List<int>();
foreach (var m in InputMonths)
{
//Find index of the month name, ignoring case
//Note if the input month name is invalid, FindIndex will return 0
int month_num = 1 + MonthNames.FindIndex(name => name.Equals(m, StringComparison.OrdinalIgnoreCase));
if (month_num > 0)
{
InputMonthNumbers.Add(month_num);
}
}
foreach (var n in InputMonthNumbers)
{
Console.WriteLine(n.ToString());
}
}
}
output:
1
3
9
Are there any classes/functions available to be used for easy JSON escaping? I'd rather not have to write my own.
I use System.Web.HttpUtility.JavaScriptStringEncode
string quoted = HttpUtility.JavaScriptStringEncode(input);
For those using the very popular Json.Net project from Newtonsoft the task is trivial:
using Newtonsoft.Json;
....
var s = JsonConvert.ToString(#"a\b");
Console.WriteLine(s);
....
This code prints:
"a\\b"
That is, the resulting string value contains the quotes as well as the escaped backslash.
Building on the answer by Dejan, what you can do is import System.Web.Helpers .NET Framework assembly, then use the following function:
static string EscapeForJson(string s) {
string quoted = System.Web.Helpers.Json.Encode(s);
return quoted.Substring(1, quoted.Length - 2);
}
The Substring call is required, since Encode automatically surrounds strings with double quotes.
Yep, just add the following function to your Utils class or something:
public static string cleanForJSON(string s)
{
if (s == null || s.Length == 0) {
return "";
}
char c = '\0';
int i;
int len = s.Length;
StringBuilder sb = new StringBuilder(len + 4);
String t;
for (i = 0; i < len; i += 1) {
c = s[i];
switch (c) {
case '\\':
case '"':
sb.Append('\\');
sb.Append(c);
break;
case '/':
sb.Append('\\');
sb.Append(c);
break;
case '\b':
sb.Append("\\b");
break;
case '\t':
sb.Append("\\t");
break;
case '\n':
sb.Append("\\n");
break;
case '\f':
sb.Append("\\f");
break;
case '\r':
sb.Append("\\r");
break;
default:
if (c < ' ') {
t = "000" + String.Format("X", c);
sb.Append("\\u" + t.Substring(t.Length - 4));
} else {
sb.Append(c);
}
break;
}
}
return sb.ToString();
}
I have used following code to escape the string value for json.
You need to add your '"' to the output of the following code:
public static string EscapeStringValue(string value)
{
const char BACK_SLASH = '\\';
const char SLASH = '/';
const char DBL_QUOTE = '"';
var output = new StringBuilder(value.Length);
foreach (char c in value)
{
switch (c)
{
case SLASH:
output.AppendFormat("{0}{1}", BACK_SLASH, SLASH);
break;
case BACK_SLASH:
output.AppendFormat("{0}{0}", BACK_SLASH);
break;
case DBL_QUOTE:
output.AppendFormat("{0}{1}",BACK_SLASH,DBL_QUOTE);
break;
default:
output.Append(c);
break;
}
}
return output.ToString();
}
In .Net Core 3+ and .Net 5+:
string escapedJsonString = JsonEncodedText.Encode(jsonString);
The methods offered here are faulty.
Why venture that far when you could just use System.Web.HttpUtility.JavaScriptEncode ?
If you're on a lower framework, you can just copy paste it from mono
Courtesy of the mono-project #
https://github.com/mono/mono/blob/master/mcs/class/System.Web/System.Web/HttpUtility.cs
public static string JavaScriptStringEncode(string value, bool addDoubleQuotes)
{
if (string.IsNullOrEmpty(value))
return addDoubleQuotes ? "\"\"" : string.Empty;
int len = value.Length;
bool needEncode = false;
char c;
for (int i = 0; i < len; i++)
{
c = value[i];
if (c >= 0 && c <= 31 || c == 34 || c == 39 || c == 60 || c == 62 || c == 92)
{
needEncode = true;
break;
}
}
if (!needEncode)
return addDoubleQuotes ? "\"" + value + "\"" : value;
var sb = new System.Text.StringBuilder();
if (addDoubleQuotes)
sb.Append('"');
for (int i = 0; i < len; i++)
{
c = value[i];
if (c >= 0 && c <= 7 || c == 11 || c >= 14 && c <= 31 || c == 39 || c == 60 || c == 62)
sb.AppendFormat("\\u{0:x4}", (int)c);
else switch ((int)c)
{
case 8:
sb.Append("\\b");
break;
case 9:
sb.Append("\\t");
break;
case 10:
sb.Append("\\n");
break;
case 12:
sb.Append("\\f");
break;
case 13:
sb.Append("\\r");
break;
case 34:
sb.Append("\\\"");
break;
case 92:
sb.Append("\\\\");
break;
default:
sb.Append(c);
break;
}
}
if (addDoubleQuotes)
sb.Append('"');
return sb.ToString();
}
This can be compacted into
// https://github.com/mono/mono/blob/master/mcs/class/System.Json/System.Json/JsonValue.cs
public class SimpleJSON
{
private static bool NeedEscape(string src, int i)
{
char c = src[i];
return c < 32 || c == '"' || c == '\\'
// Broken lead surrogate
|| (c >= '\uD800' && c <= '\uDBFF' &&
(i == src.Length - 1 || src[i + 1] < '\uDC00' || src[i + 1] > '\uDFFF'))
// Broken tail surrogate
|| (c >= '\uDC00' && c <= '\uDFFF' &&
(i == 0 || src[i - 1] < '\uD800' || src[i - 1] > '\uDBFF'))
// To produce valid JavaScript
|| c == '\u2028' || c == '\u2029'
// Escape "</" for <script> tags
|| (c == '/' && i > 0 && src[i - 1] == '<');
}
public static string EscapeString(string src)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
int start = 0;
for (int i = 0; i < src.Length; i++)
if (NeedEscape(src, i))
{
sb.Append(src, start, i - start);
switch (src[i])
{
case '\b': sb.Append("\\b"); break;
case '\f': sb.Append("\\f"); break;
case '\n': sb.Append("\\n"); break;
case '\r': sb.Append("\\r"); break;
case '\t': sb.Append("\\t"); break;
case '\"': sb.Append("\\\""); break;
case '\\': sb.Append("\\\\"); break;
case '/': sb.Append("\\/"); break;
default:
sb.Append("\\u");
sb.Append(((int)src[i]).ToString("x04"));
break;
}
start = i + 1;
}
sb.Append(src, start, src.Length - start);
return sb.ToString();
}
}
I ran speed tests on some of these answers for a long string and a short string. Clive Paterson's code won by a good bit, presumably because the others are taking into account serialization options. Here are my results:
Apple Banana
System.Web.HttpUtility.JavaScriptStringEncode: 140ms
System.Web.Helpers.Json.Encode: 326ms
Newtonsoft.Json.JsonConvert.ToString: 230ms
Clive Paterson: 108ms
\\some\long\path\with\lots\of\things\to\escape\some\long\path\t\with\lots\of\n\things\to\escape\some\long\path\with\lots\of\"things\to\escape\some\long\path\with\lots"\of\things\to\escape
System.Web.HttpUtility.JavaScriptStringEncode: 2849ms
System.Web.Helpers.Json.Encode: 3300ms
Newtonsoft.Json.JsonConvert.ToString: 2827ms
Clive Paterson: 1173ms
And here is the test code:
public static void Main(string[] args)
{
var testStr1 = "Apple Banana";
var testStr2 = #"\\some\long\path\with\lots\of\things\to\escape\some\long\path\t\with\lots\of\n\things\to\escape\some\long\path\with\lots\of\""things\to\escape\some\long\path\with\lots""\of\things\to\escape";
foreach (var testStr in new[] { testStr1, testStr2 })
{
var results = new Dictionary<string,List<long>>();
for (var n = 0; n < 10; n++)
{
var count = 1000 * 1000;
var sw = Stopwatch.StartNew();
for (var i = 0; i < count; i++)
{
var s = System.Web.HttpUtility.JavaScriptStringEncode(testStr);
}
var t = sw.ElapsedMilliseconds;
results.GetOrCreate("System.Web.HttpUtility.JavaScriptStringEncode").Add(t);
sw = Stopwatch.StartNew();
for (var i = 0; i < count; i++)
{
var s = System.Web.Helpers.Json.Encode(testStr);
}
t = sw.ElapsedMilliseconds;
results.GetOrCreate("System.Web.Helpers.Json.Encode").Add(t);
sw = Stopwatch.StartNew();
for (var i = 0; i < count; i++)
{
var s = Newtonsoft.Json.JsonConvert.ToString(testStr);
}
t = sw.ElapsedMilliseconds;
results.GetOrCreate("Newtonsoft.Json.JsonConvert.ToString").Add(t);
sw = Stopwatch.StartNew();
for (var i = 0; i < count; i++)
{
var s = cleanForJSON(testStr);
}
t = sw.ElapsedMilliseconds;
results.GetOrCreate("Clive Paterson").Add(t);
}
Console.WriteLine(testStr);
foreach (var result in results)
{
Console.WriteLine(result.Key + ": " + Math.Round(result.Value.Skip(1).Average()) + "ms");
}
Console.WriteLine();
}
Console.ReadLine();
}
I would also recommend using the JSON.NET library mentioned, but if you have to escape unicode characters (e.g. \uXXXX format) in the resulting JSON string, you may have to do it yourself. Take a look at Converting Unicode strings to escaped ascii string for an example.
I nice one-liner, used JsonConvert as others have but added substring to remove the added quotes and backslash.
var escapedJsonString = JsonConvert.ToString(JsonString).Substring(1, JsonString.Length - 2);
What about System.Web.Helpers.Json.Encode(...) (see http://msdn.microsoft.com/en-us/library/system.web.helpers.json.encode(v=vs.111).aspx)?
String.Format("X", c);
That just outputs: X
Try this instead:
string t = ((int)c).ToString("X");
sb.Append("\\u" + t.PadLeft(4, '0'));
There's a Json library at Codeplex
I chose to use System.Web.Script.Serialization.JavaScriptSerializer.
I have a small static helper class defined as follows:
internal static partial class Serialization
{
static JavaScriptSerializer serializer;
static Serialization()
{
serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = Int32.MaxValue;
}
public static string ToJSON<T>(T obj)
{
return serializer.Serialize(obj);
}
public static T FromJSON<T>(string data)
{
if (Common.IsEmpty(data))
return default(T);
else
return serializer.Deserialize<T>(data);
}
}
To serialize anything I just call Serialization.ToJSON(itemToSerialize)
To deserialize I just call Serialization.FromJSON<T>(jsonValueOfTypeT)