Using HttpUtility.HtmlDecode method with .NET Compact Framework? - c#
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.
Related
How to retrieve multiple spaces from a string
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.
Character counting with a Linked List
I am trying to Design a program that reads an ASCII text file one byte at a time and outputs the frequency count of how many times each character appears. The output does not need to be sorted. The character frequency objects need to be processed and stored using a Linked List. I know that my character frequency class is okay, however I cannot figure out how to count the characters. This is the code I have so far, but my counts end up as 0. LinkedList<CharacterFrequency> list = new LinkedList<CharacterFrequency>(); CharacterFrequency cf = new CharacterFrequency(); StreamReader file = new StreamReader(#"input.txt"); var ch = -1; while ((ch = file.Read ()) !=-1) { LinkedListNode<CharacterFrequency> node; node = list.Find(cf); if (list.Any()) { cf.Increment(); } if (node != null) { list.AddLast(cf); } } Console.WriteLine(cf.ToString()); file.Close(); //and here is my character frequency class; class CharacterFrequency { private Char m_char; private int m_count; public CharacterFrequency() { m_char = '\0'; m_count = 0; } public CharacterFrequency(Char ch) { m_char = ch; m_count = 0; } public CharacterFrequency(Char ch, int count) { m_char = ch; m_count = count; } public CharacterFrequency(CharacterFrequency cf) { m_char = cf.Character; m_count = cf.Count; } public Char Character { get { return m_char; } set { m_char = value; } } public int Count { get { return m_count; } set { if (m_count > value) m_count = value; } } public void Increment() { m_count++; } public override string ToString() { return String.Format("{0}({1}) {2}", m_char, (int)m_char, m_count); } public override int GetHashCode() { return (int)m_char; } public override bool Equals(object obj) { if (obj == null) return false; if (obj == this) return true; if (!(obj.GetType() == GetType())) return false; CharacterFrequency rhs = (CharacterFrequency)obj; return this.Character == rhs.Character; } } Updated code (I have not been able to work through the issue with the increment method yet): class Program { static void Main(string[] args) { int ch; const int Input_File = 0; const int Output_File = 1; StreamReader reader = null; StreamWriter writer = null; //linked list declaration LinkedList<CharacterFrequency> list = new LinkedList<CharacterFrequency>(); //read the characters from the input file reader = new StreamReader(File.OpenRead(args[Input_File])); while ((ch = reader.Read ()) !=-1)//casts to integer { CharacterFrequency cf = LinkedList<CharacterFrequency>list(ch); //attempt to create linked list from character frequency BIG ISSUES HERE! LinkedListNode<CharacterFrequency> node; //attempt to create node node = list.Find(cf); // find method if (node != null) //increment if found { node.Value.Increment(); } else //add if not found { list.AddLast(cf); } } reader.Close(); //write outputfile writer = new StreamWriter(File.OpenWrite(args[Output_File])); foreach (CharacterFrequency cf in list) writer.WriteLine(cf.ToString()); writer.Close(); } } }
I suspect the problem is here : if (list.Any()) { cf.Increment(); } I think it should be (You may need to adjust it more): if(node != null) { node.getData().increment(); } else { list.AddLast(cf); } There's also a problem with the fact that you don't use ch . At the beggining of the loop, you should recreate a LinkedListNode<CharacterFrequency> cf from the char you've read, or the code won't work . EDIT: You can't declare a variable more than once, so simply take it outside the loop CharacterFrequency cf; while ((ch = reader.Read ()) !=-1)//casts to integer { cf = LinkedList<CharacterFrequency>list(ch); ....
Split a comma delimited string with nested children in parentheses
I have a string formatted something like this: "a, b(c,d(e,f),g),h, i(j, k, l)" where each letter represents one or more words. I need to split this string up in to a list of objects: public class Item { public string Name { get; set; } public IEnumerable<Item> Children { get; set; } public Ingredient() { Children = new List<Item>(); } } The desired result represented in an outline format: a b 2.1. c 2.2. d 2.2.1. e 2.2.2. f 2.3. g h i 4.1. j 4.2. k 4.2. l What would be the most efficient way to do so?
You can use a recursive algorithm to parse your string like this: static IEnumerable<Item> Parse(string source) { var root = new Item() { Name = "Root", Children = new List<Item>() }; AddChildrenTo(root, source); return root.Children; } static int AddChildrenTo(Item item, string source) { Item node = null; var word = new List<char>(); for (int i = 0; i < source.Length; i++) { var c = source[i]; if (new[] { ',', '(', ')' }.Contains(c)) { if (word.Count > 0) { node = new Item { Name = new string(word.ToArray()), Children = new List<Item>() }; (item.Children as List<Item>).Add(node); word.Clear(); } if (c == '(') { i += AddChildrenTo(node, source.Substring(i + 1)) + 1; } else if (c == ')') { return i; } } else if (char.IsLetter(c)) // add other valid characters to if condition { word.Add(c); } } return source.Length; } Then you can simply call Parse() (For better demonstration I've changed the letters (a, b, ..) in your string to words (ark, book, ...)): string source = "ark,book(cook,door(euro,fun),good),hello,ink(jack,kill,loop)"; var res = Parse(source); Please note that for a very large string recursive approach wouldn't be the best solution. And for simplicity I didn't do the error checkings.
You can use a stack like this: static public List<Item> Parse(string str) { Stack<Item> stack = new Stack<Item>(); Item root = new Item(); stack.Push(root); foreach (char c in str) { if (char.IsLetter(c)) { Item item = new Item(); item.Name = c.ToString(); stack.Peek().Children.Add(item); stack.Push(item); } else if (c == ')' || c == ',') { stack.Pop(); } } return root.Children; } Please note that the Children property needs to be a List like this: public class Item { public string Name { get; set; } public List<Item> Children { get; set; } public Item() { Children = new List<Item>(); } }
If you don't care about unbalanced bracket type: static string[] SplitString(string input) { bool nSingleQuote = false; bool nDubbleQuote = false; int nBracket = 0; int start = 0; List<String> result = new List<String>(); for (int i = 0; i < input.Length; i++) { char c = input[i]; if (c == '\'') { if(!nDubbleQuote) nSingleQuote = !nSingleQuote; } else if (c == '"') { if(!nSingleQuote) nDubbleQuote = !nDubbleQuote; } if (!nSingleQuote && !nDubbleQuote) { if (c == ',') { if (nBracket == 0) { result.Add(input.Substring(start, i - start).Trim()); start = i + 1; } } else if (c == '(' || c == '[' || c == '{') { nBracket++; } else if (c == ')' || c == ']' || c == '}') { nBracket--; if (nBracket < 0) throw new Exception("Unbalanced parenthesis, square bracket or curly bracket at offset #" + i); } } } if (nBracket > 0) throw new Exception("Missing closing parenthesis, square bracket or curly bracket"); if (nSingleQuote || nDubbleQuote) throw new Exception("Missing end quotation mark"); result.Add(input.Substring(start).Trim()); return result.ToArray(); }
XML - System.Xml.XmlException - hexadecimal value 0x06
I get this error. Later I searched and found out the reason of illegal characters in my XML and its solution. But I don't have the access to edit any of these files. My job is to read and fetch the tag value, attribute value and similar stuff. SO I can't replace the binary characters with escapes like '\x01' with . Also I tried to include CheckCharacters =false in XMLreader settings. It doesn't take this. Still it is throwing the same error. Is it not possible to fix in XMLreader? I read about XMLtextReader. It can skip the exception. But already I have coded for all my features using XMLreader. It would be good if I can find a solution for this. Otherwise I would have to change all my code. My code: private void button1_Click(object sender, EventArgs e) { int i = 0; var filenames = System.IO.Directory .EnumerateFiles(textBox1.Text, "*.xml", System.IO.SearchOption.AllDirectories) .Select(System.IO.Path.GetFullPath); foreach (var f in filenames) { var resolver = new XmlUrlOverrideResolver(); resolver.DtdFileMap[#"X1.DTD"] = #"\\location\X1.DTD"; resolver.DtdFileMap[#"R2.DTD"] = #"\\location\X2.DTD"; resolver.DtdFileMap[#"R5.DTD"] = #"\\location\R5.DTD"; XmlReaderSettings settings = new XmlReaderSettings(); settings.DtdProcessing = DtdProcessing.Parse; settings.XmlResolver = resolver; XmlReader doc = XmlReader.Create(f, settings); while (doc.Read()) { if ((doc.NodeType == XmlNodeType.Element) && (doc.Name == "ap")) { if (doc.HasAttributes) { String fin = doc.GetAttribute("ap"); if (fin == "no") { String[] array = new String[10000]; array[i] = (f); File.AppendAllText(#"\\location\NAPP.txt", array[i] + Environment.NewLine); i++; } else { String[] abs = new String[10000]; abs[i] = (f); File.AppendAllText(#"\\location\APP.txt", abs[i] + Environment.NewLine); i++; } } } } } MessageBox.Show("Done"); }
This is a very simple example of character "filter" that will replae the 0x06 character with a space: public class MyStreamReader : StreamReader { public MyStreamReader(string path) : base(path) { } public override int Read(char[] buffer, int index, int count) { int res = base.Read(buffer, index, count); for (int i = 0; i < res; i++) { if (buffer[i] == 0x06) { buffer[i] = ' '; } } return res; } } You use it this way: using (var sr = new MyStreamReader(f)) { var doc = XmlReader.Create(sr, settings); Note that it's very simple because it's replacing a character (the 0x06) with another character of the same "length" (the space). If you wanted to replace a character with a "sequence" of characters (to escape it), it would get more complex (not impossible, 30 minutes of work difficult) (I have checked and it seems the XmlTextReader only uses that method and not the Read() method) As always, when a programmer tells you 30 minutes, it means 0 minutes or 2 hours :-) This is the "more complex" ReplacingStreamReader: /// <summary> /// Only the Read methods are supported! /// </summary> public class ReplacingStreamReader : StreamReader { public ReplacingStreamReader(string path) : base(path) { } public Func<char, string> ReplaceWith { get; set; } protected char[] RemainingChars { get; set; } protected int RemainingCharsIndex { get; set; } public override int Read() { int ch; if (RemainingChars != null) { ch = RemainingChars[RemainingCharsIndex]; RemainingCharsIndex++; if (RemainingCharsIndex == RemainingChars.Length) { RemainingCharsIndex = 0; RemainingChars = null; } } else { ch = base.Read(); if (ch != -1) { string replace = ReplaceWith((char)ch); if (replace == null) { // Do nothing } else if (replace.Length == 1) { ch = replace[0]; } else { ch = replace[0]; RemainingChars = replace.ToCharArray(1, replace.Length - 1); RemainingCharsIndex = 0; } } } return ch; } public override int Read(char[] buffer, int index, int count) { int res = 0; // We leave error handling to the StreamReader :-) // We handle only "working" parameters if (RemainingChars != null && buffer != null && index >= 0 && count > 0 && index + count <= buffer.Length) { int remainingCharsCount = RemainingChars.Length - RemainingCharsIndex; res = Math.Min(remainingCharsCount, count); Array.Copy(RemainingChars, RemainingCharsIndex, buffer, index, res); RemainingCharsIndex += res; if (RemainingCharsIndex == RemainingChars.Length) { RemainingCharsIndex = 0; RemainingChars = null; } if (res == count) { return res; } index += res; count -= res; } while (true) { List<char> sb = null; int res2 = base.Read(buffer, index, count); if (res2 == 0 || ReplaceWith == null) { return res; } int j = 0; for (int i = 0; i < res2; i++) { char ch = buffer[index + i]; string replace = ReplaceWith(ch); if (sb != null) { if (replace == null) { sb.Add(ch); } else { sb.AddRange(replace); } } else if (replace == null) { buffer[j] = ch; j++; } else if (replace.Length == 1) { buffer[j] = replace[0]; j++; } else if (replace.Length == 0) { // We do not advance } else { sb = new List<char>(); sb.AddRange(replace); } } res2 = j; if (sb != null) { int res3 = Math.Min(sb.Count, count - res2); sb.CopyTo(0, buffer, index + res2, res3); if (res3 < sb.Count) { RemainingChars = new char[sb.Count - res3]; RemainingCharsIndex = 0; sb.CopyTo(res3, RemainingChars, 0, RemainingChars.Length); } res += res3; } else { res2 = j; // Can't happen if sb != null (at least a character must // have been added) if (res2 == 0) { continue; } } res += res2; return res; } } } Use it like: using (var sr = new ReplacingStreamReader(f)) { sr.ReplaceWith = x => { return x == 0x6 ? " " : null; // return x == '.' ? " " : null; // Replace all . with }; var doc = XmlReader.Create(sr, settings); Be aware that the ReplacingStreamReader doesn't "know" which part of the xml it is modifying, so rarely a "blind" replace is ok :-) Other than this limitation, you can replace any character with any string (null in the ReplaceWith means "keep the current character", equivalent to x.ToString() in the example given. Returning string.Empty is valid, means remove the current character). The class is quite interesting: it keeps a char[] RemainingChars with the chars that have been read (and filtered by ReplaceWith) but that haven't been returned by a Read() method because the passed buffer was too much small (the ReplaceWith method could "enlarge" the read string, making it too much big for the buffer!). Note that sb is a List<char> instead of a StringBuilder. Probably using one or the other would be nearly equivalent, code-wise.
You could first read the content into a string replace (escape) the content, and then load it into a XmlReader: foreach (var f in filenames) { string text; using (StreamReader s = new StreamReader(f,Encoding.UTF8)) { text = s.ReadToEnd(); } text = text.Replace("\x01",#""); //replace the content //load some settings var resolver = new XmlUrlOverrideResolver(); resolver.DtdFileMap[#"X1.DTD"] = #"\\location\X1.DTD"; resolver.DtdFileMap[#"R2.DTD"] = #"\\location\X2.DTD"; resolver.DtdFileMap[#"R5.DTD"] = #"\\location\R5.DTD"; XmlReaderSettings settings = new XmlReaderSettings(); settings.DtdProcessing = DtdProcessing.Parse; settings.XmlResolver = resolver; XmlReader doc = XmlReader.Create(text, settings); //perform processing task //... }
ASP.NET: Implementing ISessionIDManager for cookieless sessions?
Question: I'm writing a custom session provider. So far it works excellently. I decided I wanted to add a customized ISessionIDManager, to control the session id. It already works fine for cookie sessions. But when I swich to cookieless, like this: <sessionState mode="Custom" customProvider="custom_provider" cookieless="true" timeout="1" sessionIDManagerType="Samples.AspNet.Session.MySessionIDManager" sqlConnectionString="Data Source=localhost;Initial Catalog=TestDB;User Id=SomeUser;Password=SomePassword;" sqlCommandTimeout="10" > <!-- timeout in minutes--> <providers> <add name="custom_provider" type="Test.WebSession.CustomSessionStoreProvider" /> </providers> </sessionState> Then it redirects to: http://localhost:52897/(77bb065f-d2e9-4cfc-8117-8b89a40e00d8)/default.aspx and this throws HTTP 404. I understand why, as there is no such folder. But when you use the default session manager (the one that ships with asp.net), and switch to cookieless, the URL looks like this: http://localhost:52897/(S(sq2abm453wnasg45pvboee45))/DisplaySessionValues.aspx and there is no HTTP 404... I tried adding the (S and ) to my session-id in brackets in the url, but that didn't help. What am I missing ? using System; using System.Configuration; using System.Web.Configuration; using System.Web; using System.Web.SessionState; // http://allantech.blogspot.com/2011/04/cookieless-session-state-in-aspnet.html // http://forums.asp.net/t/1082784.aspx/1 // http://stackoverflow.com/questions/4612310/implementing-a-custom-sessionidmanager // http://msdn.microsoft.com/en-us/library/system.web.sessionstate.isessionidmanager.aspx // http://msdn.microsoft.com/en-us/library/system.web.sessionstate.isessionidmanager(v=vs.80).aspx namespace Samples.AspNet.Session { // Samples.AspNet.Session.MySessionIDManager public class MySessionIDManager : IHttpModule, ISessionIDManager { protected SessionStateSection pConfig = null; internal const string HeaderName = "AspFilterSessionId"; protected void InitializeModule() { // Obtain session-state configuration settings. if (pConfig == null) { Configuration cfg = WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath); pConfig = (SessionStateSection)cfg.GetSection("system.web/sessionState"); } // End if (pConfig == null) } // // IHttpModule Members // // // IHttpModule.Init // public void Init(HttpApplication app) { //InitializeModule(); } // End Sub Init // // IHttpModule.Dispose // public void Dispose() { } // End Sub Dispose // // ISessionIDManager Members // // // ISessionIDManager.Initialize // public void Initialize() { InitializeModule(); } // End Sub Initialize // // ISessionIDManager.InitializeRequest // public bool InitializeRequest( HttpContext context, bool suppressAutoDetectRedirect, out bool supportSessionIDReissue ) { if (pConfig.Cookieless == HttpCookieMode.UseCookies) { supportSessionIDReissue = false; return false; } else { supportSessionIDReissue = true; return context.Response.IsRequestBeingRedirected; } } // End Function InitializeRequest // // ISessionIDManager.GetSessionID // public string GetSessionID(HttpContext context) { string id = null; if (pConfig.Cookieless == HttpCookieMode.UseUri) { string tmp = context.Request.Headers[HeaderName]; if (tmp != null) id = HttpUtility.UrlDecode(id); // Retrieve the SessionID from the URI. } else { if (context.Request.Cookies.Count > 0) { id = context.Request.Cookies[pConfig.CookieName].Value; id = HttpUtility.UrlDecode(id); } } // Verify that the retrieved SessionID is valid. If not, return null. if (!Validate(id)) id = null; return id; } // End Function GetSessionID // // ISessionIDManager.CreateSessionID // public string CreateSessionID(HttpContext context) { return System.Guid.NewGuid().ToString(); } // End Function CreateSessionID // // ISessionIDManager.RemoveSessionID // public void RemoveSessionID(HttpContext context) { context.Response.Cookies.Remove(pConfig.CookieName); } // End Sub RemoveSessionID public static string InsertSessionId(string id, string path) { string dir = GetDirectory(path); if (!dir.EndsWith("/")) dir += "/"; string appvpath = HttpRuntime.AppDomainAppVirtualPath; if (!appvpath.EndsWith("/")) appvpath += "/"; if (path.StartsWith(appvpath)) path = path.Substring(appvpath.Length); if (path[0] == '/') path = path.Length > 1 ? path.Substring(1) : ""; // //http://localhost:52897/(S(sq2abm453wnasg45pvboee45))/DisplaySessionValues.aspx return Canonic(appvpath + "(" + id + ")/" + path); //return Canonic(appvpath + "(S(" + id + "))/" + path); } public static bool IsRooted(string path) { if (path == null || path.Length == 0) return true; char c = path[0]; if (c == '/' || c == '\\') return true; return false; } public static string Canonic(string path) { char[] path_sep = { '\\', '/' }; bool isRooted = IsRooted(path); bool endsWithSlash = path.EndsWith("/"); string[] parts = path.Split(path_sep); int end = parts.Length; int dest = 0; for (int i = 0; i < end; i++) { string current = parts[i]; if (current.Length == 0) continue; if (current == ".") continue; if (current == "..") { dest--; continue; } if (dest < 0) if (!isRooted) throw new HttpException("Invalid path."); else dest = 0; parts[dest++] = current; } if (dest < 0) throw new HttpException("Invalid path."); if (dest == 0) return "/"; string str = String.Join("/", parts, 0, dest); str = RemoveDoubleSlashes(str); if (isRooted) str = "/" + str; if (endsWithSlash) str = str + "/"; return str; } public static string GetDirectory(string url) { url = url.Replace('\\', '/'); int last = url.LastIndexOf('/'); if (last > 0) { if (last < url.Length) last++; return RemoveDoubleSlashes(url.Substring(0, last)); } return "/"; } public static string RemoveDoubleSlashes (string input) { // MS VirtualPathUtility removes duplicate '/' int index = -1; for (int i = 1; i < input.Length; i++) if (input [i] == '/' && input [i - 1] == '/') { index = i - 1; break; } if (index == -1) // common case optimization return input; System.Text.StringBuilder sb = new System.Text.StringBuilder(input.Length); sb.Append (input, 0, index); for (int i = index; i < input.Length; i++) { if (input [i] == '/') { int next = i + 1; if (next < input.Length && input [next] == '/') continue; sb.Append ('/'); } else { sb.Append (input [i]); } } return sb.ToString (); } // http://www.dotnetfunda.com/articles/article1531-how-to-add-custom-headers-into-readonly-httprequest-object-using-httpmodule-.aspx public void SetHeader(string strHeaderName, string strValue) { //get a reference System.Collections.Specialized.NameValueCollection headers = HttpContext.Current.Request.Headers; //get a type Type t = headers.GetType(); //get the property System.Reflection.PropertyInfo prop = t.GetProperty( "IsReadOnly", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.IgnoreCase | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.FlattenHierarchy | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.FlattenHierarchy ); //unset readonly prop.SetValue(headers, false, null); // Set Read-Only to false //add a header //HttpContext.Current.Request.Headers.Add(strHeaderName, strValue); //headers.Add(strHeaderName, strValue); t.InvokeMember("BaseAdd", System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance, null, headers, new object[] { strHeaderName, new System.Collections.ArrayList { strValue } } ); prop.SetValue(headers, true, null); // Reset Read-Only to true // Victory ! //string strCheckHeaders = string.Join(Environment.NewLine, HttpContext.Current.Request.Headers.AllKeys); } // // ISessionIDManager.SaveSessionID // public void SaveSessionID(HttpContext context, string id, out bool redirected, out bool cookieAdded) { if (!Validate(id)) throw new HttpException("Invalid session ID"); Type t = base.GetType(); redirected = false; cookieAdded = false; if (pConfig.Cookieless == HttpCookieMode.UseUri) { // Add the SessionID to the URI. Set the redirected variable as appropriate. //context.Request.Headers.Add(HeaderName, id); //context.Request.Headers.Set(HeaderName, id); SetHeader(HeaderName, id); cookieAdded = false; redirected = true; UriBuilder newUri = new UriBuilder(context.Request.Url); newUri.Path = InsertSessionId(id, context.Request.FilePath); //http://localhost:52897/(S(sq2abm453wnasg45pvboee45))/DisplaySessionValues.aspx context.Response.Redirect(newUri.Uri.PathAndQuery, false); context.ApplicationInstance.CompleteRequest(); // Important ! return; } else { context.Response.Cookies.Add(new HttpCookie(pConfig.CookieName, id)); cookieAdded = true; } } // End Sub SaveSessionID // // ISessionIDManager.Validate // public bool Validate(string id) { try { Guid testGuid = new Guid(id); if (id == testGuid.ToString()) return true; } catch { } return false; } // End Function Validate } // End Class MySessionIDManager : IHttpModule, ISessionIDManager } // End Namespace Samples.AspNet.Session
Creating a custom session id manager from scratch seems like a lot of work. What about inheriting from System.Web.SessionState.SessionIDManager class and overriding the CreateSessionID method? public class MySessionIDManager : SessionIDManager, ISessionIDManager { public override string CreateSessionID(HttpContext context) { return System.Guid.NewGuid().ToString("N"); } }
When all else fails, crack open the .NET implementation with Reflector or ILSpy and see what they are doing different.