How to retrieve multiple spaces from a string - c#

I have this method:
public static string ReplaceVarReferences(string input,char open, char close)
{
string inner = "";
for (int i = 0; i < input.Length; i++)
{
if (input[i] == open)
{
i++;
string varInner = "";
while (input[i] != close)
{
varInner += input[i];
i++;
}
inner += GetVariable(varInner);
}
else
{
inner += input[i];
}
}
return inner;
}
and this memory allocation and retrieval methods:
public static Dictionary<string, string> memory = new Dictionary<string, string>();
public static string GetVariable(string key)
{
if (memory.ContainsKey(key))
{
return memory[key];
}
else
{
return key;
}
}
public static void SetVariable(string key, string value)
{
if (memory.ContainsKey(key))
{
memory[key] = value;
}
else
{
memory.Add(key, value);
}
}
I want to to return a string with the 'ReplaceVarReferences' method and return a string with multiple spaces like this:
this code is from my interpreter and not real code.
var a = hello world;
print(variable a = {a})
the 'ReplaceVarReferences' method should be able to return this with multiple spaces:
"variable a = hello world"
but instead, it returns:
"variable a = hello world"
how can I fix this?

Ok so I looked at the wrong place I have another method that had the problem:
public static string GetNested(string Open, string Close, List<string> t, ref int i)
{
string inner = "";
int nested = 0;
while (true)
{
if (i < t.Count - 1)
{
i++;
if (string.IsNullOrWhiteSpace(t[i]))
{
for (int x = 0; x < t[i].Length; x++)
{
inner += " ";
}
}
else if (t[i] == Close)
{
nested--;
if (nested > 0)
{
inner += t[i];
}
}
else if (t[i] == Open)
{
if (nested > 0)
{
inner += t[i];
}
nested++;
}
else
{
inner += t[i];
}
if (nested == 0)
{
break;
}
}
}
return inner;
}
i did not include:
if (string.IsNullOrWhiteSpace(t[i]))
{
for (int x = 0; x < t[i].Length; x++)
{
inner += " ";
}
}
and it resulted in the spaces being dumped when retrieving the nested string.

Related

In what context does "ConsoleInput" miss? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
using System;
namespace suma_cifrelor_unui_nr
{
class Program
{
static void Main(string[] args)
{
int n;
int suma = 0;
Console.Write("Introdu numarul ");
Console.Write("\n");
n = int.Parse(ConsoleInput.ReadToWhiteSpace(true));
while (n > 0)
{
suma = suma + n % 10;
n = n / 10;
}
Console.Write("Suma cifrelor este ==");
Console.Write(suma);
}
}
}
When I m trying to run this code the following error pops up :
"The name 'ConsoleInput' does not exist in the current context"
enter image description here
As expected ConsoleInput is a helper class so I did some google search,
And that's land me to convert code from c++ to c# and i found that words "with the 'ConsoleInput' helper class added by our converter", so try to check google before ask next time.
internal static class ConsoleInput
{
private static bool goodLastRead = false;
internal static bool LastReadWasGood
{
get
{
return goodLastRead;
}
}
internal static string ReadToWhiteSpace(bool skipLeadingWhiteSpace)
{
string input = "";
char nextChar;
while (char.IsWhiteSpace(nextChar = (char)System.Console.Read()))
{
//accumulate leading white space if skipLeadingWhiteSpace is false:
if (!skipLeadingWhiteSpace)
input += nextChar;
}
//the first non white space character:
input += nextChar;
//accumulate characters until white space is reached:
while (!char.IsWhiteSpace(nextChar = (char)System.Console.Read()))
{
input += nextChar;
}
goodLastRead = input.Length > 0;
return input;
}
internal static string ScanfRead(string unwantedSequence = null, int maxFieldLength = -1)
{
string input = "";
char nextChar;
if (unwantedSequence != null)
{
nextChar = '\0';
for (int charIndex = 0; charIndex < unwantedSequence.Length; charIndex++)
{
if (char.IsWhiteSpace(unwantedSequence[charIndex]))
{
//ignore all subsequent white space:
while (char.IsWhiteSpace(nextChar = (char)System.Console.Read()))
{
}
}
else
{
//ensure each character matches the expected character in the sequence:
nextChar = (char)System.Console.Read();
if (nextChar != unwantedSequence[charIndex])
return null;
}
}
input = nextChar.ToString();
if (maxFieldLength == 1)
return input;
}
while (!char.IsWhiteSpace(nextChar = (char)System.Console.Read()))
{
input += nextChar;
if (maxFieldLength == input.Length)
return input;
}
return input;
}
}
using System;
namespace suma_cifrelor_unui_nr
{
internal static class ConsoleInput
{
static void Main(string[] args)
{
int n;
int suma = 0;
Console.Write("Introdu numarul ");
Console.Write("\n");
n = int.Parse(ConsoleInput.ReadToWhiteSpace(true));
while (n > 0)
{
suma = suma + n % 10;
n = n / 10;
}
Console.Write("Suma cifrelor este ==");
Console.Write(suma);
}
private static ReadOnlySpan<char> ReadToWhiteSpace(bool v)
{
throw new NotImplementedException();
}
}
}

Read Data from a CSV file

I am looking to store values from a CSV file with two Columns, I have the following class ReadFromCSVhandling the reading of the CSV file but I am having difficulty using this list to display the contents once a button is clicked. The code I have to read the CSV file is as follows;
namespace ELMFS
{
public class ReadFromCSV
{
static void ReadCSV(string[] args)
{
List<TextSpeak> TxtSpk = File.ReadAllLines(#"C:\textwords.csv")
.Skip(1)
.Select(t => TextSpeak.FromCsv(t))
.ToList();
}
}
public class TextSpeak
{
string Abreviated;
string Expanded;
public static TextSpeak FromCsv(string csvLine)
{
string[] TxtSpk = csvLine.Split(',');
TextSpeak textSpeak = new TextSpeak();
textSpeak.Abreviated = TxtSpk[0];
textSpeak.Expanded = TxtSpk[1];
return textSpeak;
}
}
}
I am trying to display the textSpeak.Abreviated in a message box but cannot seem to access it from the WPF window.
How do I use this list in other windows within the application?
any advice would be appreciated!
Thanks in advance!
First, ReadCSV method should return the generated List object (or you cannot use the list anywhere else).
Second, TextSpeak class should have properties so that you can access its member variables outside the class.
I.e. something like this should work:
namespace ELMFS
{
public class ReadFromCSV
{
public static List<TextSpeak> ReadCSV(string[] args)
{
List<TextSpeak> TxtSpk = File.ReadAllLines(#"C:\textwords.csv")
.Skip(1)
.Select(t => TextSpeak.FromCsv(t))
.ToList();
return TxtSpk;
}
}
public class TextSpeak
{
public string Abreviated { get; private set; }
public string Expanded { get; private set; }
public static TextSpeak FromCsv(string csvLine)
{
string[] TxtSpk = csvLine.Split(',');
TextSpeak textSpeak = new TextSpeak();
textSpeak.Abreviated = TxtSpk[0];
textSpeak.Expanded = TxtSpk[1];
return textSpeak;
}
}
}
private void Display(int count)
{
textBox1.Text = "";
for (int i = 0; i <= count ; i++)
{
textBox1.Text += ((dataGridView1.Rows[i].Cells[1].Value).ToString()) + (dataGridView1.Rows[i].Cells[2].Value.ToString()) + Environment.NewLine;
}
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
// your code here
string CSVFilePathName =Path.GetDirectoryName(Application.ExecutablePath).Replace(#"\bin\Debug", #"\NewFolder1\TEST.csv");
string[] Lines = File.ReadAllLines(CSVFilePathName);
string[] Fields;
Fields = Lines[0].Split(new char[] { ',' });
int Cols = Fields.GetLength(0);
DataTable dt = new DataTable();
//1st row must be column names; force lower case to ensure matching later on.
for (int i = 0; i < Cols; i++)
dt.Columns.Add(Fields[i].ToLower(), typeof(string));
DataRow Row;
for (int i = 1; i < Lines.GetLength(0); i++)
{
Fields = Lines[i].Split(new char[] { ',' });
Row = dt.NewRow();
for (int f = 0; f < Cols; f++)
Row[f] = Fields[f];
dt.Rows.Add(Row);
}
dataGridView1.DataSource = dt;
int count = 0;
if (dataGridView1.RowCount > 0)
{
count = dataGridView1.Rows.Count;
}
buttons = new Button[count];
for (int i = 0; i <count; i++)
{
buttons[i] = new Button();
buttons[i].Name = "buttons_Click" + i.ToString();
buttons[i].Text = "Click";
buttons[i].Click += new EventHandler(buttons_Click);
this.Controls.Add(buttons[i]);
buttons[i].Visible = false;
}
buttons[0].Visible = true;
// buttons[1].Visible = true;
}
catch (Exception ex)
{
MessageBox.Show("Error is " + ex.ToString());
throw;
}
}
private void buttons_Click(object sender, EventArgs e)
{
int count = dataGridView1.Rows.Count-1;
if(c <= count)
{
if (buttons[c].Name == "buttons_Click" + c.ToString())
{
buttons[c].Visible = false;
int j = c;
Display(j);
if (c != count)
{
c = c + 1;
buttons[c].Visible = true;
}
}
}
if (c == count)
{
buttons[0].Visible = true;
}
}
}
}

What C# template engine that has clean separation between HTML and control code?

What C# template engine
that uses 'pure' HTML having only text and markers
sans any control flow like if, while, loop or expressions,
separating html from control code ?
Below is the example phone book list code,
expressing how this should be done:
string html=#"
<html><head><title>#title</title></head>
<body>
<table>
<tr>
<td> id</td> <td> name</td> <td> sex</td> <td>phones</td>
</tr><!--#contacts:-->
<tr>
<td>#id</td> <td>#name</td> <td>#sex</td>
<td>
<!--#phones:-->#phone <br/>
<!--:#phones-->
</td>
</tr><!--:#contacts-->
</table>
</body>
</html>";
var contacts = from c in db.contacts select c;
Marker m = new Marker(html);
Filler t = m.Mark("title");
t.Set("Phone book");
Filler c = m.Mark("contacts", "id,name,sex");
// **foreach** expressed in code, not in html
foreach(var contact in contacts) {
int id = contact.id;
c.Add(id, contact.name, contact.sex);
Filler p = c.Mark("phones", "phone");
var phones = from ph in db.phones
where ph.id == id
select new {ph.phone};
if (phones.Any()) {
foreach(var ph in phones) {
p.Add(ph);
}
} else {
fp.Clear();
}
}
Console.Out.WriteLine(m.Get());
Use this code:
Templet.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace templaten.com.Templaten
{
public class tRange
{
public int head, toe;
public tRange(int _head, int _toe)
{
head = _head;
toe = _toe;
}
}
public enum AType
{
VALUE = 0,
NAME = 1,
OPEN = 2,
CLOSE = 3,
GROUP = 4
}
public class Atom
{
private AType kin;
private string tag;
private object data;
private List<Atom> bag;
public Atom(string _tag = "",
AType _kin = AType.VALUE,
object _data = null)
{
tag = _tag;
if (String.IsNullOrEmpty(_tag))
_kin = AType.GROUP;
kin = _kin;
if (_kin == AType.GROUP)
bag = new List<Atom>();
else
bag = null;
data = _data;
}
public AType Kin
{
get { return kin; }
}
public string Tag
{
get { return tag; }
set { tag = value; }
}
public List<Atom> Bag
{
get { return bag; }
}
public object Data
{
get { return data; }
set { data = value; }
}
public int Add(string _tag = "",
AType _kin = AType.VALUE,
object _data = null)
{
if (bag != null)
{
bag.Add(new Atom(_tag, _kin, _data));
return bag.Count - 1;
}
else
{
return -1;
}
}
}
public class Templet
{
private string content;
string namepat = "\\w+";
string justName = "(\\w+)";
string namePre = "#";
string namePost = "";
string comment0 = "\\<!--\\s*";
string comment1 = "\\s*--\\>";
private Atom tokens; // parsed contents
private Dictionary<string, int> iNames; // name index
private Dictionary<string, tRange> iGroups; // groups index
private Atom buffer; // output buffer
private Dictionary<string, int> _iname; // output name index
private Dictionary<string, tRange> _igroup; // output index
public Templet(string Content = null)
{
Init(Content);
}
private int[] mark(string[] names, string group)
{
if (names == null || names.Length < 1) return null;
tRange t = new tRange(0, buffer.Bag.Count - 1);
if (group != null)
{
if (!_igroup.ContainsKey(group)) return null;
t = _igroup[group];
}
int[] marks = new int[names.Length];
for (int i = 0; i < marks.Length; i++)
marks[i] = -1;
for (int i = t.head; i <= t.toe; i++)
{
if (buffer.Bag[i].Kin == AType.NAME)
{
for (int j = 0; j < names.Length; j++)
{
if (String.Compare(
names[j],
buffer.Bag[i].Tag,
true) == 0)
{
marks[j] = i;
break;
}
}
}
}
return marks;
}
public Filler Mark(string group, string names)
{
Filler f = new Filler(this, names);
f.di = mark(f.names, group);
f.Group = group;
tRange t = null;
if (_igroup.ContainsKey(group)) t = _igroup[group];
f.Range = t;
return f;
}
public Filler Mark(string names)
{
Filler f = new Filler(this, names);
f.di = mark(f.names, null);
f.Group = "";
f.Range = null;
return f;
}
public void Set(int[] locations, object[] x)
{
int j = Math.Min(x.Length, locations.Length);
for (int i = 0; i < j; i++)
{
int l = locations[i];
if ((l >= 0) && (buffer.Bag[l] != null))
buffer.Bag[l].Data = x[i];
}
}
public void New(string group, int seq = 0)
{
// place new group copied from old group just below it
if (!( iGroups.ContainsKey(group)
&& _igroup.ContainsKey(group)
&& seq > 0)) return;
tRange newT = null;
tRange t = iGroups[group];
int beginRange = _igroup[group].toe + 1;
for (int i = t.head; i <= t.toe; i++)
{
buffer.Bag.Insert(beginRange,
new Atom(tokens.Bag[i].Tag,
tokens.Bag[i].Kin,
tokens.Bag[i].Data));
beginRange++;
}
newT = new tRange(t.toe + 1, t.toe + (t.toe - t.head + 1));
// rename past group
string pastGroup = group + "_" + seq;
t = _igroup[group];
buffer.Bag[t.head].Tag = pastGroup;
buffer.Bag[t.toe].Tag = pastGroup;
_igroup[pastGroup] = t;
// change group indexes
_igroup[group] = newT;
}
public void ReMark(Filler f, string group)
{
if (!_igroup.ContainsKey(group)) return;
Map(buffer, _iname, _igroup);
f.di = mark(f.names, group);
f.Range = _igroup[group];
}
private static void Indexing(string aname,
AType kin,
int i,
Dictionary<string, int> dd,
Dictionary<string, tRange> gg)
{
switch (kin)
{
case AType.NAME: // index all names
dd[aname] = i;
break;
case AType.OPEN: // index all groups
if (!gg.ContainsKey(aname))
gg[aname] = new tRange(i, -1);
else
gg[aname].head = i;
break;
case AType.CLOSE:
if (!gg.ContainsKey(aname))
gg[aname] = new tRange(-1, i);
else
gg[aname].toe = i;
break;
default:
break;
}
}
private static void Map(Atom oo,
Dictionary<string, int> dd,
Dictionary<string, tRange> gg)
{
for (int i = 0; i < oo.Bag.Count; i++)
{
string aname = oo.Bag[i].Tag;
Indexing(oo.Bag[i].Tag, oo.Bag[i].Kin, i, dd, gg);
}
}
public void Init(string Content = null)
{
content = Content;
tokens = new Atom("", AType.GROUP);
iNames = new Dictionary<string, int>();
iGroups = new Dictionary<string, tRange>();
// parse content into tokens
string namePattern = namePre + namepat + namePost;
string patterns =
"(?<var>" + namePattern + ")|" +
"(?<head>" + comment0 + namePattern + ":" + comment1 + ")|" +
"(?<toe>" + comment0 + ":" + namePattern + comment1 + ")";
Regex jn = new Regex(justName, RegexOptions.Compiled);
Regex r = new Regex(patterns, RegexOptions.Compiled);
MatchCollection ms = r.Matches(content);
int pre = 0;
foreach (Match m in ms)
{
tokens.Add(content.Substring(pre, m.Index - pre));
int idx = -1;
if (m.Groups.Count >= 3)
{
string aname = "";
MatchCollection x = jn.Matches(m.Value);
if (x.Count > 0 && x[0].Groups.Count > 1)
aname = x[0].Groups[1].ToString();
AType t = AType.VALUE;
if (m.Groups[1].Length > 0) t = AType.NAME;
if (m.Groups[2].Length > 0) t = AType.OPEN;
if (m.Groups[3].Length > 0) t = AType.CLOSE;
if (aname.Length > 0)
{
tokens.Add(aname, t);
idx = tokens.Bag.Count - 1;
}
Indexing(aname, t, idx, iNames, iGroups);
}
pre = m.Index + m.Length;
}
if (pre < content.Length)
tokens.Add(content.Substring(pre, content.Length - pre));
// copy tokens into buffer
buffer = new Atom("", AType.GROUP);
for (int i = 0; i < tokens.Bag.Count; i++)
buffer.Add(tokens.Bag[i].Tag, tokens.Bag[i].Kin);
// initialize index of output names
_iname = new Dictionary<string, int>();
foreach (string k in iNames.Keys)
_iname[k] = iNames[k];
// initialize index of output groups
_igroup = new Dictionary<string, tRange>();
foreach (string k in iGroups.Keys)
{
tRange t = iGroups[k];
_igroup[k] = new tRange(t.head, t.toe);
}
}
public string Get()
{
StringBuilder sb = new StringBuilder("");
for (int i = 0; i < buffer.Bag.Count; i++)
{
switch (buffer.Bag[i].Kin)
{
case AType.VALUE:
sb.Append(buffer.Bag[i].Tag);
break;
case AType.NAME:
sb.Append(buffer.Bag[i].Data);
break;
case AType.OPEN:
case AType.CLOSE:
break;
default: break;
}
}
return sb.ToString();
}
}
public class Filler
{
private Templet t = null;
public int[] di;
public string[] names;
public string Group { get; set; }
public tRange Range { get; set; }
private int seq = 0;
public Filler(Templet tl, string markers = null)
{
t = tl;
if (markers != null)
names = markers.Split(new char[] { ',' },
StringSplitOptions.RemoveEmptyEntries);
else
names = null;
}
public void init(int length)
{
di = new int[length];
for (int i = 0; i < length; i++)
di[i] = -1;
seq = 0;
Group = "";
Range = null;
}
// clear contents inside marked object or group
public void Clear()
{
object[] x = new object[di.Length];
for (int i = 0; i < di.Length; i++)
x[i] = null;
t.Set(di, x);
}
// set value for marked object,
// or add row to group and set value to columns
public void Set(params object[] x)
{
t.Set(di, x);
}
public void Add(params object[] x)
{
if (Group.Length > 0)
{
t.New(Group, seq);
++seq;
t.ReMark(this, Group);
}
t.Set(di, x);
}
}
}
Testing program
Program.cs
Templet m = new Templet(html);
Filler f= m.Mark("title");
f.Set("Phone book");
Filler fcontacts = m.Mark("contacts", "id,name,sex,phone");
fcontacts.Add(1, "Akhmad", "M", "123456");
fcontacts.Add(2, "Barry", "M", "234567");
fcontacts.Add(1, "Charles", "M", "345678");
Console.Out.WriteLine(m.Get());
Still can't do nested loop- yet.
Just use ASP.NET. Whether you use webforms or MVC, it's super easy to have C# in your .cs files, and HTML in your .aspx files.
As with anything in programming, it's 99% up to you to do things right. Flexible UI engines aren't going to enforce that you follow good coding practices.
In principle most any template engine you choose can separate HTML from control logic with the proper architecture. using an MVC (Or MVVM) pattern, if you construct your model in such a way that the controller contains the if/then logic instead of the view you can eliminate it from the view.
That said, the syntax you use is very close to Razor syntax which is easily available for ASP.NET MVC through NuGet packages.
I totally hear you. I built SharpFusion, which has some other stuff in it but if you look for the template.cs file you will see the handler that parses a HTML file and simply replaces out tokens with values that you've made in c#.
Because no XML parsing is done like ASP.NET the framework loads much faster than even an MVC site.
Another alternative is ServiceStack.

convert Javascript function to c#

I want to convert following javascript function to c#
can anyone help?
function parseCoordinate(coordinate,type,format,spaced) {
coordinate = coordinate.toString();
coordinate = coordinate.replace(/(^\s+|\s+$)/g,''); // remove white space
var neg = 0; if (coordinate.match(/(^-|[WS])/i)) { neg = 1; }
if (coordinate.match(/[EW]/i) && !type) { type = 'lon'; }
if (coordinate.match(/[NS]/i) && !type) { type = 'lat'; }
coordinate = coordinate.replace(/[NESW\-]/gi,' ');
if (!coordinate.match(/[0-9]/i)) {
return '';
}
parts = coordinate.match(/([0-9\.\-]+)[^0-9\.]*([0-9\.]+)?[^0-9\.]*([0-9\.]+)?/);
if (!parts || parts[1] == null) {
return '';
} else {
n = parseFloat(parts[1]);
if (parts[2]) { n = n + parseFloat(parts[2])/60; }
if (parts[3]) { n = n + parseFloat(parts[3])/3600; }
if (neg && n >= 0) { n = 0 - n; }
if (format == 'dmm') {
if (spaced) {
n = Degrees_to_DMM(n,type,' ');
} else {
n = Degrees_to_DMM(n,type);
}
} else if (format == 'dms') {
if (spaced) {
n = Degrees_to_DMS(n,type,' ');
} else {
n = Degrees_to_DMS(n,type,'');
}
} else {
n = Math.round(10000000 * n) / 10000000;
if (n == Math.floor(n)) { n = n + '.0'; }
}
return comma2point(n);
}
}
Check out Regex on MSDN or have a quick look on google for Regex C#
if (coordinate.match(/(^-|[WS])/i)) { neg = 1; }
would become:
using System.Text.RegularExpressions;
Regex myRegex = new Regex("/(^-|[WS])/i)");
if (coordinate.IsMatch(myRegex))
{
neg=1;
}
If it will always be like your above example 'N27 53.4891' then you could store it as a string. If the above latitude is in 2 parts ('N27' and 53.4891) and you need to access them seperately then you could have a custom Coordinate class, e.g.
public class coordinate
{
public string otherPart {get; set;} // N27
public float coordPart {get; set;} // 53.4891
}
You can then override the .toString() method to get 'N27 53.4891'.
Regex myPattern =new Regex("/(^-|[WS])/i)");
if(myPattern.isMatch(coordinate))
{ neg = 1; }
see if this works

Using HttpUtility.HtmlDecode method with .NET Compact Framework?

A project using .NET Compact Framework does not allow use System.Web library.
How can I do to HTMLDecode a string using .NET Compact Framework?
I didn't found any class that do that.
If you decompile the .NET Framework source you can get the methods you need. I did it for you, so you can copy and paste the two classes below:
internal class HtmlEntities
{
// Fields
private static string[] _entitiesList = new string[] {
"\"-quot", "&-amp", "<-lt", ">-gt", "\x00a0-nbsp", "\x00a1-iexcl", "\x00a2-cent", "\x00a3-pound", "\x00a4-curren", "\x00a5-yen", "\x00a6-brvbar", "\x00a7-sect", "\x00a8-uml", "\x00a9-copy", "\x00aa-ordf", "\x00ab-laquo",
"\x00ac-not", "\x00ad-shy", "\x00ae-reg", "\x00af-macr", "\x00b0-deg", "\x00b1-plusmn", "\x00b2-sup2", "\x00b3-sup3", "\x00b4-acute", "\x00b5-micro", "\x00b6-para", "\x00b7-middot", "\x00b8-cedil", "\x00b9-sup1", "\x00ba-ordm", "\x00bb-raquo",
"\x00bc-frac14", "\x00bd-frac12", "\x00be-frac34", "\x00bf-iquest", "\x00c0-Agrave", "\x00c1-Aacute", "\x00c2-Acirc", "\x00c3-Atilde", "\x00c4-Auml", "\x00c5-Aring", "\x00c6-AElig", "\x00c7-Ccedil", "\x00c8-Egrave", "\x00c9-Eacute", "\x00ca-Ecirc", "\x00cb-Euml",
"\x00cc-Igrave", "\x00cd-Iacute", "\x00ce-Icirc", "\x00cf-Iuml", "\x00d0-ETH", "\x00d1-Ntilde", "\x00d2-Ograve", "\x00d3-Oacute", "\x00d4-Ocirc", "\x00d5-Otilde", "\x00d6-Ouml", "\x00d7-times", "\x00d8-Oslash", "\x00d9-Ugrave", "\x00da-Uacute", "\x00db-Ucirc",
"\x00dc-Uuml", "\x00dd-Yacute", "\x00de-THORN", "\x00df-szlig", "\x00e0-agrave", "\x00e1-aacute", "\x00e2-acirc", "\x00e3-atilde", "\x00e4-auml", "\x00e5-aring", "\x00e6-aelig", "\x00e7-ccedil", "\x00e8-egrave", "\x00e9-eacute", "\x00ea-ecirc", "\x00eb-euml",
"\x00ec-igrave", "\x00ed-iacute", "\x00ee-icirc", "\x00ef-iuml", "\x00f0-eth", "\x00f1-ntilde", "\x00f2-ograve", "\x00f3-oacute", "\x00f4-ocirc", "\x00f5-otilde", "\x00f6-ouml", "\x00f7-divide", "\x00f8-oslash", "\x00f9-ugrave", "\x00fa-uacute", "\x00fb-ucirc",
"\x00fc-uuml", "\x00fd-yacute", "\x00fe-thorn", "\x00ff-yuml", "Œ-OElig", "œ-oelig", "Š-Scaron", "š-scaron", "Ÿ-Yuml", "ƒ-fnof", "ˆ-circ", "˜-tilde", "Α-Alpha", "Β-Beta", "Γ-Gamma", "Δ-Delta",
"Ε-Epsilon", "Ζ-Zeta", "Η-Eta", "Θ-Theta", "Ι-Iota", "Κ-Kappa", "Λ-Lambda", "Μ-Mu", "Ν-Nu", "Ξ-Xi", "Ο-Omicron", "Π-Pi", "Ρ-Rho", "Σ-Sigma", "Τ-Tau", "Υ-Upsilon",
"Φ-Phi", "Χ-Chi", "Ψ-Psi", "Ω-Omega", "α-alpha", "β-beta", "γ-gamma", "δ-delta", "ε-epsilon", "ζ-zeta", "η-eta", "θ-theta", "ι-iota", "κ-kappa", "λ-lambda", "μ-mu",
"ν-nu", "ξ-xi", "ο-omicron", "π-pi", "ρ-rho", "ς-sigmaf", "σ-sigma", "τ-tau", "υ-upsilon", "φ-phi", "χ-chi", "ψ-psi", "ω-omega", "ϑ-thetasym", "ϒ-upsih", "ϖ-piv",
" -ensp", " -emsp", " -thinsp", "‌-zwnj", "‍-zwj", "‎-lrm", "‏-rlm", "–-ndash", "—-mdash", "‘-lsquo", "’-rsquo", "‚-sbquo", "“-ldquo", "”-rdquo", "„-bdquo", "†-dagger",
"‡-Dagger", "•-bull", "…-hellip", "‰-permil", "′-prime", "″-Prime", "‹-lsaquo", "›-rsaquo", "‾-oline", "⁄-frasl", "€-euro", "ℑ-image", "℘-weierp", "ℜ-real", "™-trade", "ℵ-alefsym",
"←-larr", "↑-uarr", "→-rarr", "↓-darr", "↔-harr", "↵-crarr", "⇐-lArr", "⇑-uArr", "⇒-rArr", "⇓-dArr", "⇔-hArr", "∀-forall", "∂-part", "∃-exist", "∅-empty", "∇-nabla",
"∈-isin", "∉-notin", "∋-ni", "∏-prod", "∑-sum", "−-minus", "∗-lowast", "√-radic", "∝-prop", "∞-infin", "∠-ang", "∧-and", "∨-or", "∩-cap", "∪-cup", "∫-int",
"∴-there4", "∼-sim", "≅-cong", "≈-asymp", "≠-ne", "≡-equiv", "≤-le", "≥-ge", "⊂-sub", "⊃-sup", "⊄-nsub", "⊆-sube", "⊇-supe", "⊕-oplus", "⊗-otimes", "⊥-perp",
};
private static Hashtable _entitiesLookupTable;
private static object _lookupLockObject = new object();
internal static char Lookup(string entity)
{
if (_entitiesLookupTable == null)
{
lock (_lookupLockObject)
{
if (_entitiesLookupTable == null)
{
Hashtable hashtable = new Hashtable();
foreach (string str in _entitiesList)
{
hashtable[str.Substring(2)] = str[0];
}
_entitiesLookupTable = hashtable;
}
}
}
object obj2 = _entitiesLookupTable[entity];
if (obj2 != null)
{
return (char)obj2;
}
return '\0';
}
}
public sealed class HttpUtility
{
private static char[] s_entityEndingChars = new char[] { ';', '&' };
public static string HtmlDecode(string s)
{
if (s == null)
{
return null;
}
if (s.IndexOf('&') < 0)
{
return s;
}
StringBuilder sb = new StringBuilder();
StringWriter output = new StringWriter(sb);
HtmlDecode(s, output);
return sb.ToString();
}
public static void HtmlDecode(string s, TextWriter output)
{
if (s != null)
{
if (s.IndexOf('&') < 0)
{
output.Write(s);
}
else
{
int length = s.Length;
for (int i = 0; i < length; i++)
{
char ch = s[i];
if (ch == '&')
{
int num3 = s.IndexOfAny(s_entityEndingChars, i + 1);
if ((num3 > 0) && (s[num3] == ';'))
{
string entity = s.Substring(i + 1, (num3 - i) - 1);
if ((entity.Length > 1) && (entity[0] == '#'))
{
try
{
if ((entity[1] == 'x') || (entity[1] == 'X'))
{
ch = (char)int.Parse(entity.Substring(2), NumberStyles.AllowHexSpecifier);
}
else
{
ch = (char)int.Parse(entity.Substring(1));
}
i = num3;
}
catch (FormatException)
{
i++;
}
catch (ArgumentException)
{
i++;
}
}
else
{
i = num3;
char ch2 = HtmlEntities.Lookup(entity);
if (ch2 != '\0')
{
ch = ch2;
}
else
{
output.Write('&');
output.Write(entity);
output.Write(';');
goto Label_0103;
}
}
}
}
output.Write(ch);
Label_0103: ;
}
}
}
}
}
You could always port the code from Mono, sample VB code or sample Java code found with a simple web search.
I've used reflector in the past to find just the methods I need from the framework that aren't included and compile them directly into my compact.net project.

Categories

Resources