context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/* * MindTouch Dream - a distributed REST framework * Copyright (C) 2006-2011 MindTouch, Inc. * www.mindtouch.com oss@mindtouch.com * * For community documentation and downloads visit wiki.developer.mindtouch.com; * please review the licensing section. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Xml; namespace MindTouch.Xml { /// <summary> /// Provides a facility for comparing <see cref="XDoc"/> instances. /// </summary> public static class XDocDiff { //--- Constants --- private const string DELETED = "del"; private const string INSERTED = "ins"; private const int MAX_SAME_COUNTER = 3; //--- Types --- /// <summary> /// Provides a xml node token. /// </summary> public class Token { //--- Class Methods --- /// <summary> /// Compare two Token to determine whether they represent the same value. /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool Equal(Token left, Token right) { return (left.Type == right.Type) && (left.Value == right.Value); } //--- Fields --- /// <summary> /// Type of node. /// </summary> public readonly XmlNodeType Type; /// <summary> /// String value of Xml node. /// </summary> public readonly string Value; /// <summary> /// Unique key to identify token by. /// </summary> public readonly object Key; //--- Constructors --- /// <summary> /// Create a new node token. /// </summary> /// <param name="type">Type of node.</param> /// <param name="value">String value of node.</param> /// <param name="key">Unique key to identify token by.</param> public Token(XmlNodeType type, string value, object key) { this.Type = type; this.Value = value; this.Key = key; } //--- Methods --- /// <summary> /// Return a string representation of the the Token's value. /// </summary> /// <returns>A string instance.</returns> public override string ToString() { return Type + "(" + Value + ")"; } } //--- Class Methods --- /// <summary> /// Diff two documents. /// </summary> /// <param name="left">Left hand document.</param> /// <param name="right">Right hand document.</param> /// <param name="maxsize">Maximum size of the difference response.</param> /// <returns>Array of difference tuples.</returns> public static Tuplet<ArrayDiffKind, Token>[] Diff(XDoc left, XDoc right, int maxsize) { if(left == null) { throw new ArgumentNullException("left"); } if(right == null) { throw new ArgumentNullException("right"); } return Diff(Tokenize(left), Tokenize(right), maxsize); } /// <summary> /// Diff two token sets. /// </summary> /// <param name="left">Left hand token set.</param> /// <param name="right">Right hand token set.</param> /// <param name="maxsize">Maximum size of the difference response.</param> /// <returns>Array of difference tuples.</returns> public static Tuplet<ArrayDiffKind, Token>[] Diff(Token[] left, Token[] right, int maxsize) { if(left == null) { throw new ArgumentNullException("left"); } if(right == null) { throw new ArgumentNullException("right"); } return ArrayUtil.Diff(left, right, maxsize, Token.Equal); } /// <summary> /// Perform a three-way merge of documents. /// </summary> /// <param name="original">Original document.</param> /// <param name="left">Left hand modification of document.</param> /// <param name="right">Right hand modification of document.</param> /// <param name="maxsize">Maximum size of the difference response.</param> /// <param name="priority">Merge priority.</param> /// <param name="conflict">Output of conflict flag.</param> /// <returns>Merged document.</returns> public static XDoc Merge(XDoc original, XDoc left, XDoc right, int maxsize, ArrayMergeDiffPriority priority, out bool conflict) { if(original == null) { throw new ArgumentNullException("original"); } if(left == null) { throw new ArgumentNullException("left"); } if(right == null) { throw new ArgumentNullException("right"); } return Merge(Tokenize(original), Tokenize(left), Tokenize(right), maxsize, priority, out conflict); } /// <summary> /// Perform a three-way merge between token sets resulting in a document. /// </summary> /// <param name="original">Original Token set.</param> /// <param name="left">Left hand token set.</param> /// <param name="right">Right hand token set.</param> /// <param name="maxsize">Maximum size of the difference response.</param> /// <param name="priority">Merge priority.</param> /// <param name="conflict">Output of conflict flag.</param> /// <returns>Merged document.</returns> public static XDoc Merge(Token[] original, Token[] left, Token[] right, int maxsize, ArrayMergeDiffPriority priority, out bool conflict) { if(original == null) { throw new ArgumentNullException("original"); } if(left == null) { throw new ArgumentNullException("left"); } if(right == null) { throw new ArgumentNullException("right"); } // create left diff Tuplet<ArrayDiffKind, Token>[] leftDiff = Diff(original, left, maxsize); if(leftDiff == null) { conflict = false; return null; } // create right diff Tuplet<ArrayDiffKind, Token>[] rightDiff = Diff(original, right, maxsize); if(rightDiff == null) { conflict = false; return null; } // merge changes Tuplet<ArrayDiffKind, Token>[] mergeDiff = ArrayUtil.MergeDiff(leftDiff, rightDiff, priority, Token.Equal, x => x.Key, out conflict); return Detokenize(mergeDiff); } /// <summary> /// Create a highlight document from a set of differences. /// </summary> /// <param name="diff">Difference set.</param> /// <returns>Highlight document.</returns> public static XDoc Highlight(Tuplet<ArrayDiffKind, Token>[] diff) { XDoc combined; List<Tuplet<string, string, string>> invisibleChanges; XDoc before; XDoc after; Highlight(diff, out combined, out invisibleChanges, out before, out after); return combined; } /// <summary> /// Create before, after and combined highlight documents for a set of differences. /// </summary> /// <param name="diff">Difference set.</param> /// <param name="combined">Output of combined highlight document.</param> /// <param name="combinedInvisible">Output of the combined invisible differences.</param> /// <param name="before">Output of before difference highlight document.</param> /// <param name="after">Output of after difference highlight document.</param> public static void Highlight(Tuplet<ArrayDiffKind, Token>[] diff, out XDoc combined, out List<Tuplet<string, string, string>> combinedInvisible /* tuple(xpath, before, after) */, out XDoc before, out XDoc after) { if(diff == null) { throw new ArgumentNullException("diff"); } List<Tuplet<ArrayDiffKind, Token>> combinedChanges = new List<Tuplet<ArrayDiffKind, Token>>(diff.Length); combinedInvisible = new List<Tuplet<string, string, string>>(); List<Tuplet<ArrayDiffKind, Token>> beforeChanges = new List<Tuplet<ArrayDiffKind, Token>>(diff.Length); List<Tuplet<ArrayDiffKind, Token>> afterChanges = new List<Tuplet<ArrayDiffKind, Token>>(diff.Length); bool changedElement = false; Stack<List<string>> path = new Stack<List<string>>(); Dictionary<string, Tuplet<string, string, string>> invisibleChangesLookup = new Dictionary<string, Tuplet<string, string, string>>(); path.Push(new List<string>()); for(int i = 0; i < diff.Length; ++i) { Tuplet<ArrayDiffKind, Token> item = diff[i]; Token token = item.Item2; switch(item.Item1) { case ArrayDiffKind.Added: switch(token.Type) { case XmlNodeType.Text: if((token.Value.Length > 0) && !char.IsWhiteSpace(token.Value[0])) { Highlight_InlineTextChanges(diff, i, combinedChanges, beforeChanges, afterChanges, out i); // adjust iterator since it will be immediately increased again --i; continue; } break; case XmlNodeType.Attribute: if(!changedElement) { string[] parts = token.Value.Split(new char[] { '=' }, 2); string xpath = ComputeXPath(path, "@" + parts[0]); Tuplet<string, string, string> beforeAfter; if(invisibleChangesLookup.TryGetValue(xpath, out beforeAfter)) { beforeAfter.Item3 = parts[1]; } else { beforeAfter = new Tuplet<string, string, string>(xpath, null, parts[1]); combinedInvisible.Add(beforeAfter); invisibleChangesLookup[xpath] = beforeAfter; } } break; case XmlNodeType.Element: // NOTE (steveb): this check shouldn't be needed, but just in case, it's better to have a wrong path than an exception! if(path.Count > 0) { path.Peek().Add(token.Value); } path.Push(new List<string>()); changedElement = true; break; case XmlNodeType.None: // NOTE (steveb): this check shouldn't be needed, but just in case, it's better to have a wrong path than an exception! if(path.Count > 0) { path.Pop(); } break; } item = new Tuplet<ArrayDiffKind, Token>(ArrayDiffKind.Same, token); afterChanges.Add(item); combinedChanges.Add(item); break; case ArrayDiffKind.Removed: switch(token.Type) { case XmlNodeType.Text: if((token.Value.Length > 0) && !char.IsWhiteSpace(token.Value[0])) { Highlight_InlineTextChanges(diff, i, combinedChanges, beforeChanges, afterChanges, out i); // adjust iterator since it will be immediately increased again --i; continue; } else { // keep whitespace text combinedChanges.Add(new Tuplet<ArrayDiffKind, Token>(ArrayDiffKind.Same, token)); } break; case XmlNodeType.Attribute: if(!changedElement) { string[] parts = token.Value.Split(new char[] { '=' }, 2); string xpath = ComputeXPath(path, "@" + parts[0]); Tuplet<string, string, string> beforeAfter; if(invisibleChangesLookup.TryGetValue(xpath, out beforeAfter)) { beforeAfter.Item2 = parts[1]; } else { beforeAfter = new Tuplet<string, string, string>(xpath, parts[1], null); combinedInvisible.Add(beforeAfter); invisibleChangesLookup[xpath] = beforeAfter; } } break; case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: // keep whitespace text combinedChanges.Add(new Tuplet<ArrayDiffKind, Token>(ArrayDiffKind.Same, token)); break; case XmlNodeType.Element: changedElement = true; break; } beforeChanges.Add(new Tuplet<ArrayDiffKind, Token>(ArrayDiffKind.Same, token)); break; case ArrayDiffKind.Same: switch(token.Type) { case XmlNodeType.Element: changedElement = false; // NOTE (steveb): this check shouldn't be needed, but just in case, it's better to have a wrong path than an exception! if(path.Count > 0) { path.Peek().Add(token.Value); } path.Push(new List<string>()); break; case XmlNodeType.None: // NOTE (steveb): this check shouldn't be needed, but just in case, it's better to have a wrong path than an exception! if(path.Count > 0) { path.Pop(); } break; } combinedChanges.Add(item); beforeChanges.Add(item); afterChanges.Add(item); break; case ArrayDiffKind.AddedLeft: case ArrayDiffKind.AddedRight: case ArrayDiffKind.RemovedLeft: case ArrayDiffKind.RemovedRight: // TODO (steveb): process conflicting changes throw new NotImplementedException("cannot highlight changes for a diff with conflicts"); } } before = Detokenize(beforeChanges.ToArray()); after = Detokenize(afterChanges.ToArray()); combined = Detokenize(combinedChanges.ToArray()); } private static void Highlight_InlineTextChanges(Tuplet<ArrayDiffKind, Token>[] diff, int index, List<Tuplet<ArrayDiffKind, Token>> combinedChanges, List<Tuplet<ArrayDiffKind, Token>> beforeChanges, List<Tuplet<ArrayDiffKind, Token>> afterChanges, out int next) { int lastAdded = index; int lastRemoved = index; int firstAdded = -1; int firstRemoved = -1; Tuplet<ArrayDiffKind, Token> item; // determine how long the chain of intermingled changes is for(int i = index, sameCounter = 0; (i < diff.Length) && ((diff[i].Item2.Type == XmlNodeType.Text) || (diff[i].Item2.Type == XmlNodeType.Whitespace) || diff[i].Item2.Type == XmlNodeType.SignificantWhitespace) && (sameCounter <= MAX_SAME_COUNTER); ++i) { item = diff[i]; Token token = item.Item2; if((token.Value.Length > 0) && !char.IsWhiteSpace(token.Value[0])) { if(item.Item1 == ArrayDiffKind.Added) { sameCounter = 0; if(firstAdded == -1) { firstAdded = i; } lastAdded = i; } else if(item.Item1 == ArrayDiffKind.Removed) { sameCounter = 0; if(firstRemoved == -1) { firstRemoved = i; } lastRemoved = i; } else { // we count the number of non-changed elements to break-up long runs with no changes ++sameCounter; } } } // set index of next element next = Math.Max(lastAdded, lastRemoved) + 1; // check if any text was added if(firstAdded != -1) { // add all unchanged text before the first added text for(int i = index; i < firstAdded; ++i) { if(diff[i].Item1 == ArrayDiffKind.Same) { item = new Tuplet<ArrayDiffKind, Token>(ArrayDiffKind.Same, diff[i].Item2); combinedChanges.Add(item); afterChanges.Add(item); } } // add all text nodes that were added in a row object key = new object(); item = new Tuplet<ArrayDiffKind, Token>(ArrayDiffKind.Same, new Token(XmlNodeType.Element, INSERTED, key)); combinedChanges.Add(item); afterChanges.Add(item); item = new Tuplet<ArrayDiffKind, Token>(ArrayDiffKind.Same, new Token(XmlNodeType.EndElement, string.Empty, null)); combinedChanges.Add(item); afterChanges.Add(item); for(int i = firstAdded; i <= lastAdded; ++i) { if(diff[i].Item1 != ArrayDiffKind.Removed) { item = new Tuplet<ArrayDiffKind, Token>(ArrayDiffKind.Same, diff[i].Item2); combinedChanges.Add(item); afterChanges.Add(item); } } item = new Tuplet<ArrayDiffKind, Token>(ArrayDiffKind.Same, new Token(XmlNodeType.None, INSERTED, key)); combinedChanges.Add(item); afterChanges.Add(item); // add all unchanged text after the last added text for(int i = lastAdded + 1; i < next; ++i) { if(diff[i].Item1 == ArrayDiffKind.Same) { item = new Tuplet<ArrayDiffKind, Token>(ArrayDiffKind.Same, diff[i].Item2); combinedChanges.Add(item); afterChanges.Add(item); } } } else { // add all unchanged text before the first added text for(int i = index; i < next; ++i) { if(diff[i].Item1 == ArrayDiffKind.Same) { item = new Tuplet<ArrayDiffKind, Token>(ArrayDiffKind.Same, diff[i].Item2); combinedChanges.Add(item); afterChanges.Add(item); } } } // check if any text was removed if(firstRemoved != -1) { // add all unchanged text before the first removed text for(int i = index; i < firstRemoved; ++i) { if(diff[i].Item1 == ArrayDiffKind.Same) { item = new Tuplet<ArrayDiffKind, Token>(ArrayDiffKind.Same, diff[i].Item2); if((item.Item2.Value.Length > 0) && !char.IsWhiteSpace(item.Item2.Value[0])) { combinedChanges.Add(item); } beforeChanges.Add(item); } } // add all text nodes that were removed in a row object key = new object(); item = new Tuplet<ArrayDiffKind, Token>(ArrayDiffKind.Same, new Token(XmlNodeType.Element, DELETED, key)); combinedChanges.Add(item); beforeChanges.Add(item); item = new Tuplet<ArrayDiffKind, Token>(ArrayDiffKind.Same, new Token(XmlNodeType.EndElement, string.Empty, null)); combinedChanges.Add(item); beforeChanges.Add(item); for(int i = firstRemoved; i <= lastRemoved; ++i) { if(diff[i].Item1 != ArrayDiffKind.Added) { item = new Tuplet<ArrayDiffKind, Token>(ArrayDiffKind.Same, diff[i].Item2); combinedChanges.Add(item); beforeChanges.Add(item); } } item = new Tuplet<ArrayDiffKind, Token>(ArrayDiffKind.Same, new Token(XmlNodeType.None, DELETED, key)); combinedChanges.Add(item); beforeChanges.Add(item); // add all unchanged text after the last removed text for(int i = lastRemoved + 1; i < next; ++i) { if(diff[i].Item1 == ArrayDiffKind.Same) { item = new Tuplet<ArrayDiffKind, Token>(ArrayDiffKind.Same, diff[i].Item2); combinedChanges.Add(item); beforeChanges.Add(item); } } } else { // add all unchanged text before the first removed text for(int i = index; i < next; ++i) { if(diff[i].Item1 == ArrayDiffKind.Same) { item = new Tuplet<ArrayDiffKind, Token>(ArrayDiffKind.Same, diff[i].Item2); if((item.Item2.Value.Length > 0) && !char.IsWhiteSpace(item.Item2.Value[0])) { combinedChanges.Add(item); } beforeChanges.Add(item); } } } } /// <summary> /// Create a document from a difference set. /// </summary> /// <param name="tokens">Difference set.</param> /// <returns>Detokenized document.</returns> public static XDoc Detokenize(Tuplet<ArrayDiffKind, Token>[] tokens) { XmlDocument doc = XDoc.NewXmlDocument(); Detokenize(tokens, 0, null, doc); return new XDoc(doc); } /// <summary> /// Convert a document to a token set. /// </summary> /// <param name="doc"></param> /// <returns>Set of tokens.</returns> public static Token[] Tokenize(XDoc doc) { if(doc.IsEmpty) { throw new ArgumentException("XML document is empty", "doc"); } List<Token> result = new List<Token>(); XmlNode start = doc.AsXmlNode; if(start is XmlDocument) { start = start.OwnerDocument.DocumentElement; } Tokenize(start, result); return result.ToArray(); } /// <summary> /// Write a difference set. /// </summary> /// <param name="diffset">Difference set.</param> /// <param name="writer">TextWriter to write the set to.</param> public static void Write(Tuplet<ArrayDiffKind, Token>[] diffset, TextWriter writer) { foreach(Tuplet<ArrayDiffKind, Token> entry in diffset) { switch(entry.Item1) { case ArrayDiffKind.Same: writer.WriteLine(" " + entry.Item2); break; case ArrayDiffKind.Removed: writer.WriteLine("-" + entry.Item2); break; case ArrayDiffKind.Added: writer.WriteLine("+" + entry.Item2); break; case ArrayDiffKind.AddedLeft: writer.WriteLine("+<" + entry.Item2); break; case ArrayDiffKind.AddedRight: writer.WriteLine("+>" + entry.Item2); break; case ArrayDiffKind.RemovedLeft: writer.WriteLine("-<" + entry.Item2); break; case ArrayDiffKind.RemovedRight: writer.WriteLine("->" + entry.Item2); break; } } } private static int Detokenize(Tuplet<ArrayDiffKind, Token>[] tokens, int index, XmlElement current, XmlDocument doc) { for(; index < tokens.Length; ++index) { Tuplet<ArrayDiffKind, Token> token = tokens[index]; switch(token.Item1) { case ArrayDiffKind.Same: case ArrayDiffKind.Added: switch(token.Item2.Type) { case XmlNodeType.CDATA: if(current == null) { throw new ArgumentNullException("current"); } current.AppendChild(doc.CreateCDataSection(token.Item2.Value)); break; case XmlNodeType.Comment: if(current == null) { throw new ArgumentNullException("current"); } current.AppendChild(doc.CreateComment(token.Item2.Value)); break; case XmlNodeType.SignificantWhitespace: if(current == null) { throw new ArgumentNullException("current"); } current.AppendChild(doc.CreateSignificantWhitespace(token.Item2.Value)); break; case XmlNodeType.Text: if(current == null) { throw new ArgumentNullException("current"); } current.AppendChild(doc.CreateTextNode(token.Item2.Value)); break; case XmlNodeType.Whitespace: if(current == null) { throw new ArgumentNullException("current"); } current.AppendChild(doc.CreateWhitespace(token.Item2.Value)); break; case XmlNodeType.Element: XmlElement next = doc.CreateElement(token.Item2.Value); if(current == null) { doc.AppendChild(next); } else { current.AppendChild(next); } index = Detokenize(tokens, index + 1, next, doc); break; case XmlNodeType.Attribute: if(current == null) { throw new ArgumentNullException("current"); } string[] parts = token.Item2.Value.Split(new char[] { '=' }, 2); current.SetAttribute(parts[0], parts[1]); break; case XmlNodeType.EndElement: // nothing to do break; case XmlNodeType.None: if(current == null) { throw new ArgumentNullException("current"); } // ensure we're closing the intended element if(token.Item2.Value != current.Name) { throw new InvalidOperationException(string.Format("mismatched element ending; found </{0}>, expected </{1}>", token.Item2.Value, current.Name)); } // we're done with this sequence return index; default: throw new InvalidOperationException("unhandled node type: " + token.Item2.Type); } break; case ArrayDiffKind.Removed: // ignore removed nodes break; default: throw new InvalidOperationException("invalid diff kind: " + token.Item1); } } if(current != null) { throw new InvalidOperationException("unexpected end of tokens"); } return index; } private static void Tokenize(XmlNode node, List<Token> tokens) { switch(node.NodeType) { case XmlNodeType.CDATA: case XmlNodeType.Comment: case XmlNodeType.SignificantWhitespace: case XmlNodeType.Whitespace: tokens.Add(new Token(node.NodeType, node.Value, null)); break; case XmlNodeType.Text: { // split text nodes string text = node.Value; int start = 0; int end = text.Length; while(start < end) { // check if first character is a whitespace int index = start + 1; if(char.IsWhiteSpace(text[start])) { // skip whitespace while((index < end) && char.IsWhiteSpace(text[index])) { ++index; } } else if(char.IsLetterOrDigit(text[start]) || (text[start] == '_')) { // skip alphanumeric, underscore (_), and dot (.)/comma (,) if preceded by a digit while(index < end) { char c = text[index]; if(char.IsLetterOrDigit(c) || (c == '_') || (((c == '.') || (c == ',')) && (index > start) && char.IsDigit(text[index-1]))) { ++index; } else { break; } } } else { // skip non-whitespace & non-alphanumeric while((index < end) && !char.IsWhiteSpace(text[index]) && !char.IsLetterOrDigit(text[index])) { ++index; } } if((start == 0) && (index == end)) { tokens.Add(new Token(XmlNodeType.Text, text, null)); } else { tokens.Add(new Token(XmlNodeType.Text, text.Substring(start, index - start), null)); } start = index; } } break; case XmlNodeType.Element: object key = new object(); tokens.Add(new Token(XmlNodeType.Element, node.Name, key)); // enumerate attribute in sorted order if(node.Attributes.Count > 0) { List<XmlAttribute> attributes = new List<XmlAttribute>(); foreach(XmlAttribute attribute in node.Attributes) { attributes.Add(attribute); } attributes.Sort(delegate(XmlAttribute left, XmlAttribute right) { return StringUtil.CompareInvariant(left.Name, right.Name); }); foreach(XmlAttribute attribute in attributes) { tokens.Add(new Token(XmlNodeType.Attribute, attribute.Name + "=" + attribute.Value, null)); } } tokens.Add(new Token(XmlNodeType.EndElement, string.Empty, null)); if(node.HasChildNodes) { foreach(XmlNode child in node.ChildNodes) { Tokenize(child, tokens); } } tokens.Add(new Token(XmlNodeType.None, node.Name, key)); break; } } private static string ComputeXPath(Stack<List<string>> path, string last) { StringBuilder result = new StringBuilder(); List<string>[] levels = path.ToArray(); Array.Reverse(levels); foreach(List<string> level in levels) { if(level.Count > 0) { string current = level[level.Count - 1]; int count = 1; for(int i = 0; i < level.Count - 1; ++i) { if(StringUtil.EqualsInvariant(current, level[i])) { ++count; } } result.Append('/').Append(current); if(count > 1) { result.Append('[').Append(count).Append(']'); } } } if(!string.IsNullOrEmpty(last)) { result.Append('/').Append(last); } return result.ToString(); } } /// <summary> /// Provides a utility for extracting and replacing words from an xml document. /// </summary> public class XDocWord { //--- Types --- /// <summary> /// Delegate for replacing and <see cref="XDocWord"/> instance in a document with a new XmlNode. /// </summary> /// <param name="doc">Parent document node of the word.</param> /// <param name="word">Word to replace.</param> /// <returns>Replacement Xml node.</returns> public delegate XmlNode ReplacementHandler(XmlDocument doc, XDocWord word); //--- Class Methods --- /// <summary> /// Create a word list from an <see cref="XDoc"/> instance. /// </summary> /// <param name="doc">Document to extract words from.</param> /// <returns>Array of word instances.</returns> public static XDocWord[] ConvertToWordList(XDoc doc) { List<XDocWord> result = new List<XDocWord>(); if(!doc.IsEmpty) { ConvertToWordList(doc.AsXmlNode, result); } return result.ToArray(); } /// <summary> /// Replace words in a document. /// </summary> /// <param name="wordlist">List of words to run replacement function for.</param> /// <param name="handler">Word replacement delegate.</param> public static void ReplaceText(XDocWord[] wordlist, ReplacementHandler handler) { if(wordlist == null) { throw new ArgumentNullException("wordlist"); } if(handler == null) { throw new ArgumentNullException("handler"); } // loop through words backwards for(int i = wordlist.Length - 1; i >= 0; --i) { XDocWord word = wordlist[i]; if(word.IsText) { XmlNode replacement = handler(word.Node.OwnerDocument, word); if(replacement != null) { // split the node XmlText node = (XmlText)word.Node; // split off the part after the text if(node.Value.Length > (word.Offset + word.Value.Length)) { node.SplitText(word.Offset + word.Value.Length); } // split off the part before the text if(word.Offset > 0) { node = node.SplitText(word.Offset); } // replace text with new result node.ParentNode.InsertAfter(replacement, node); node.ParentNode.RemoveChild(node); } } } } private static void ConvertElementToWord(XmlNode node, string[] attributes, List<XDocWord> words) { StringBuilder tag = new StringBuilder(); tag.Append("<"); tag.Append(node.Name); foreach(string attribute in attributes) { XmlAttribute attr = node.Attributes[attribute]; if(attr != null) { tag.AppendFormat(" {0}=\"{1}\"", attr.Name, attr.Value); } } tag.Append(">"); words.Add(new XDocWord(tag.ToString(), 0, node)); } private static void ConvertToWordList(XmlNode node, List<XDocWord> words) { switch(node.NodeType) { case XmlNodeType.Document: ConvertToWordList(((XmlDocument)node).DocumentElement, words); break; case XmlNodeType.Element: switch(node.Name) { case "img": ConvertElementToWord(node, new string[] { "src" }, words); break; default: if(node.HasChildNodes) { foreach(XmlNode child in node.ChildNodes) { ConvertToWordList(child, words); } } break; } break; case XmlNodeType.Text: { // split text nodes string text = node.Value; if((text.Length == 0) && (words.Count == 0)) { // NOTE (steveb): we add the empty text node at the beginning of each document as a reference point words.Add(new XDocWord(text, 0, node)); } else { int start = 0; int end = text.Length; while(start < end) { // check if first character is a whitespace int index = start + 1; if(char.IsWhiteSpace(text[start])) { // skip whitespace while((index < end) && char.IsWhiteSpace(text[index])) { ++index; } } else if(char.IsLetterOrDigit(text[start])) { // skip alphanumeric, underscore (_), and dot (.)/comma (,) if preceded by a digit while(index < end) { char c = text[index]; if(char.IsLetterOrDigit(c) || (c == '_') || (((c == '.') || (c == ',')) && (index > start) && char.IsDigit(text[index - 1]))) { ++index; } else { break; } } } else { // skip non-whitespace & non-alphanumeric while((index < end) && !char.IsWhiteSpace(text[index]) && !char.IsLetterOrDigit(text[index])) { ++index; } } // only add non-whitespace nodes if(!char.IsWhiteSpace(text[start])) { if((start == 0) && (index == end)) { words.Add(new XDocWord(text, 0, node)); } else { words.Add(new XDocWord(text.Substring(start, index - start), start, node)); } } start = index; } } } break; } } //--- Fields --- /// <summary> /// The word. /// </summary> public readonly string Value; /// <summary> /// Word count offset into document. /// </summary> public readonly int Offset; /// <summary> /// The Xml node containing the word. /// </summary> public readonly XmlNode Node; //--- Constructors --- private XDocWord(string value, int offset, XmlNode node) { this.Value = value; this.Offset = offset; this.Node = node; } //--- Properties --- /// <summary> /// <see langword="True"/> if the node is a text node. /// </summary> public bool IsText { get { return Node is XmlText; } } /// <summary> /// <see langword="True"/> if the parsed contents are an alphanumeric sequence. /// </summary> public bool IsWord { get { return IsText && (Value.Length > 0) && char.IsLetterOrDigit(Value[0]); } } /// <summary> /// XPath to the Node. /// </summary> public string Path { get { List<string> parents = new List<string>(); XmlNode current = Node; switch(Node.NodeType) { case XmlNodeType.Text: parents.Add("#"); current = Node.ParentNode; break; } for(; current != null; current = current.ParentNode) { parents.Add(current.Name); } parents.Reverse(); return string.Join("/", parents.ToArray()); } } //--- Methods --- /// <summary> /// Create a string represenation of the instance. /// </summary> /// <returns></returns> public override string ToString() { switch(Node.NodeType) { case XmlNodeType.Element: if(Value != null) { return Path + ": " + Value; } else { return Path + ": </ " + Node.Name + ">"; } case XmlNodeType.Text: return Path + ": '" + Value + "'"; default: throw new InvalidDataException("unknown node type"); } } } }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; namespace Microsoft.Zelig.Test { public class ValueSimpleTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; string testName = "ValueSimpleXX_"; int testNumber = 0; //////result |= Assert.CheckFailed( ValueSimple01_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( ValueSimple02_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( ValueSimple03_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( ValueSimple04_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( ValueSimple05_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( ValueSimple06_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( ValueSimple07_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( ValueSimple09_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueSimple11_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ValueSimple12_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( ValueSimple13_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( ValueSimple14_Test( ), testName, ++testNumber ); //////result |= Assert.CheckFailed( ValueSimple15_Test( ), testName, ++testNumber ); return result; } //ValueSimple Test methods //The following tests were ported from folder current\test\cases\client\CLR\Conformance\4_values\ValueSimple //01,02,03,04,05,06,07,09,11,12,13,14,15 //12 Failed //Test Case Calls //////[TestMethod] //////public TestResult ValueSimple01_Test() //////{ ////// Log.Comment(" Section 4.1"); ////// Log.Comment(" byte is an alias for System.Byte"); ////// if (ValueSimpleTestClass01.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult ValueSimple02_Test() //////{ ////// Log.Comment(" Section 4.1"); ////// Log.Comment(" char is an alias for System.Char"); ////// if (ValueSimpleTestClass02.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult ValueSimple03_Test() //////{ ////// Log.Comment(" Section 4.1"); ////// Log.Comment(" short is an alias for System.Int16"); ////// if (ValueSimpleTestClass03.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult ValueSimple04_Test() //////{ ////// Log.Comment(" Section 4.1"); ////// Log.Comment(" int is an alias for System.Int32"); ////// if (ValueSimpleTestClass04.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult ValueSimple05_Test() //////{ ////// Log.Comment(" Section 4.1"); ////// Log.Comment(" long is an alias for System.Int64"); ////// if (ValueSimpleTestClass05.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult ValueSimple06_Test() //////{ ////// Log.Comment(" Section 4.1"); ////// Log.Comment(" float is an alias for System.Single"); ////// if (ValueSimpleTestClass06.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult ValueSimple07_Test() //////{ ////// Log.Comment(" Section 4.1"); ////// Log.Comment(" double is an alias for System.Double"); ////// if (ValueSimpleTestClass07.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult ValueSimple09_Test() //////{ ////// Log.Comment(" Section 4.1"); ////// Log.Comment(" bool is an alias for System.Boolean"); ////// if (ValueSimpleTestClass09.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} [TestMethod] public TestResult ValueSimple11_Test() { Log.Comment(" Section 4.1"); Log.Comment(" A simple type and the structure type it aliases are completely indistinguishable."); Log.Comment(" In other words, writing the reserved work byte is exactly the same as writing "); Log.Comment(" System.Byte, and writing System.Int32 is exactly the same as writing the reserved"); Log.Comment(" word int."); if (ValueSimpleTestClass11.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ValueSimple12_Test() { Log.Comment(" Section 4.1"); Log.Comment(" Because a simple type aliases a struct type, every simple type has members."); if (ValueSimpleTestClass12.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //////[TestMethod] //////public TestResult ValueSimple13_Test() //////{ ////// Log.Comment(" Section 4.1"); ////// Log.Comment(" sbyte is an alias for System.SByte"); ////// if (ValueSimpleTestClass13.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult ValueSimple14_Test() //////{ ////// Log.Comment(" Section 4.1"); ////// Log.Comment(" ushort is an alias for System.UInt16"); ////// if (ValueSimpleTestClass14.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //////[TestMethod] //////public TestResult ValueSimple15_Test() //////{ ////// Log.Comment(" Section 4.1"); ////// Log.Comment(" uint is an alias for System.UInt32"); ////// if (ValueSimpleTestClass15.testMethod()) ////// { ////// return TestResult.Pass; ////// } ////// return TestResult.Fail; //////} //Compiled Test Cases //////public class ValueSimpleTestClass01 //////{ ////// public static bool testMethod() ////// { ////// byte b = 0; ////// if (b.GetType() == Type.GetType("System.Byte")) ////// { ////// return true; ////// } ////// else ////// { ////// return false; ////// } ////// } //////} //////public class ValueSimpleTestClass02 //////{ ////// public static bool testMethod() ////// { ////// char c = 'a'; ////// if (c.GetType() == Type.GetType("System.Char")) ////// { ////// return true; ////// } ////// else ////// { ////// return false; ////// } ////// } //////} //////public class ValueSimpleTestClass03 //////{ ////// public static bool testMethod() ////// { ////// short s = 0; ////// if (s.GetType() == Type.GetType("System.Int16")) ////// { ////// return true; ////// } ////// else ////// { ////// return false; ////// } ////// } //////} //////public class ValueSimpleTestClass04 //////{ ////// public static bool testMethod() ////// { ////// int i = 0; ////// if (i.GetType() == Type.GetType("System.Int32")) ////// { ////// return true; ////// } ////// else ////// { ////// return false; ////// } ////// } //////} //////public class ValueSimpleTestClass05 //////{ ////// public static bool testMethod() ////// { ////// long l = 0L; ////// if (l.GetType() == Type.GetType("System.Int64")) ////// { ////// return true; ////// } ////// else ////// { ////// return false; ////// } ////// } //////} //////public class ValueSimpleTestClass06 //////{ ////// public static bool testMethod() ////// { ////// float f = 0.0f; ////// if (f.GetType() == Type.GetType("System.Single")) ////// { ////// return true; ////// } ////// else ////// { ////// return false; ////// } ////// } //////} //////public class ValueSimpleTestClass07 //////{ ////// public static bool testMethod() ////// { ////// double d = 0.0d; ////// if (d.GetType() == Type.GetType("System.Double")) ////// { ////// return true; ////// } ////// else ////// { ////// return false; ////// } ////// } //////} //////public class ValueSimpleTestClass09 //////{ ////// public static bool testMethod() ////// { ////// bool b = true; ////// if (b.GetType() == Type.GetType("System.Boolean")) ////// { ////// return true; ////// } ////// else ////// { ////// return false; ////// } ////// } //////} public class ValueSimpleTestClass11 { public static bool testMethod() { System.Byte b = 2; System.Int32 i = 2; if ((b == 2) && (i == 2)) { return true; } else { return false; } } } public class ValueSimpleTestClass12 { public static bool testMethod() { bool RetVal = true; int i = int.MaxValue; if (i != Int32.MaxValue) { RetVal = false; } string s = i.ToString(); if (!s.Equals(Int32.MaxValue.ToString())) { RetVal = false; } i = 123; string t = 123.ToString(); if (!t.Equals(i.ToString())) { RetVal = false; } return RetVal; } } //////public class ValueSimpleTestClass13 //////{ ////// public static bool testMethod() ////// { ////// sbyte b = 0; ////// if (b.GetType() == Type.GetType("System.SByte")) ////// { ////// return true; ////// } ////// else ////// { ////// return false; ////// } ////// } //////} //////public class ValueSimpleTestClass14 //////{ ////// public static bool testMethod() ////// { ////// ushort s = 0; ////// if (s.GetType() == Type.GetType("System.UInt16")) ////// { ////// return true; ////// } ////// else ////// { ////// return false; ////// } ////// } //////} //////public class ValueSimpleTestClass15 //////{ ////// public static bool testMethod() ////// { ////// uint i = 0; ////// if (i.GetType() == Type.GetType("System.UInt32")) ////// { ////// return true; ////// } ////// else ////// { ////// return false; ////// } ////// } //////} } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using org.apache.zookeeper.client; using org.apache.jute; using org.apache.utils; using org.apache.zookeeper.proto; using ZooKeeperNetEx.utils; namespace org.apache.zookeeper { /** * This class manages the socket i/o for the client. ClientCnxn maintains a list * of available servers to connect to and "transparently" switches servers it is * connected to as needed. * */ internal sealed class ClientCnxn { private static readonly ILogProducer LOG = TypeLogger<ClientCnxn>.Instance; /* ZOOKEEPER-706: If a session has a large number of watches set then * attempting to re-establish those watches after a connection loss may * fail due to the SetWatches request exceeding the server's configured * jute.maxBuffer value. To avoid this we instead split the watch * re-establishement across multiple SetWatches calls. This constant * controls the size of each call. It is set to 128kB to be conservative * with respect to the server's 1MB default for jute.maxBuffer. */ private const int SET_WATCHES_MAX_LENGTH = 128 * 1024; private class AuthData { internal AuthData(string scheme, byte[] data) { this.scheme = scheme; this.data = data; } internal readonly string scheme; internal readonly byte[] data; } private List<AuthData> authInfo = new List<AuthData>(); /** * These are the packets that have been sent and are waiting for a response. */ internal readonly LinkedList<Packet> pendingQueue = new LinkedList<Packet>(); /** * These are the packets that need to be sent. */ internal readonly LinkedList<Packet> outgoingQueue = new LinkedList<Packet>(); private int connectTimeout { get { int timeout = negotiatedSessionTimeout.Value; if (timeout == 0) timeout = sessionTimeout; return timeout / hostProvider.size(); } } /** * The timeout in ms the client negotiated with the server. This is the * "real" timeout, not the timeout request by the client (which may have * been increased/decreased by the server which applies bounds to this * value. */ private readonly VolatileInt negotiatedSessionTimeout = new VolatileInt(0); private int readTimeout; private readonly int sessionTimeout; private readonly ZooKeeper zooKeeper; private readonly ClientWatchManager watcher; private long sessionId; private byte[] sessionPasswd; /** * If true, the connection is allowed to go to r-o mode. This field's value * is sent, besides other data, during session creation handshake. If the * server on the other side of the wire is partitioned it'll accept * read-only clients only. */ private readonly bool readOnly; public readonly string chrootPath; private Task sendTask; private Task eventTask; private readonly Timer timer; /** * Set to true when close is called. Latches the connection such that we * don't attempt to re-connect to the server if in the middle of closing the * connection (client sends session disconnect to server as part of close * operation) */ private readonly VolatileBool closing = new VolatileBool(false); /** * A set of ZooKeeper hosts this client could connect to. */ private readonly HostProvider hostProvider; // Is set to true when a connection to a r/w server is established for the // first time; never changed afterwards. // Is used to handle situations when client without sessionId connects to a // read-only server. Such client receives "fake" sessionId from read-only // server, but this sessionId is invalid for other servers. So when such // client finds a r/w server, it sends 0 instead of fake sessionId during // connection handshake and establishes new, valid session. // If this field is false (which implies we haven't seen r/w server before) // then non-zero sessionId is fake, otherwise it is valid. // internal readonly VolatileBool seenRwServerBefore = new VolatileBool(false); public long getSessionId() { return sessionId; } public byte[] getSessionPasswd() { return sessionPasswd; } public int getSessionTimeout() { return negotiatedSessionTimeout.Value; } public override string ToString() { StringBuilder sb = new StringBuilder(); EndPoint local = clientCnxnSocket.getLocalSocketAddress(); EndPoint remote = clientCnxnSocket.getRemoteSocketAddress(); sb .Append("sessionid:0x").Append(getSessionId().ToHexString()) .Append(" local:").Append(local) .Append(" remoteserver:").Append(remote) .Append(" lastZxid:").Append(lastZxid) .Append(" xid:").Append(xid) .Append(" sent:").Append(clientCnxnSocket.getSentCount()) .Append(" recv:").Append(clientCnxnSocket.getRecvCount()) //.Append(" queuedpkts:").Append(outgoingQueue.size()) //.Append(" pendingresp:").Append(pendingQueue.size()) .Append(" queuedevents:").Append(waitingEvents.size()); return sb.ToString(); } /** * This class allows us to pass the headers and the relevant records around. */ public sealed class Packet : TaskCompletionSource<bool> { internal readonly RequestHeader requestHeader; internal readonly ReplyHeader replyHeader; private readonly Record request; internal readonly Record response; internal ByteBuffer bb { get; private set; } /** Client's view of the path (may differ due to chroot) **/ internal string clientPath; /** Servers's view of the path (may differ due to chroot) **/ internal string serverPath; internal void SetFinished() { TrySetResult(true); } internal readonly ZooKeeper.WatchRegistration watchRegistration; private readonly bool readOnly; /** Convenience ctor */ internal Packet(RequestHeader requestHeader, ReplyHeader replyHeader, Record request, Record response, ZooKeeper.WatchRegistration watchRegistration) : this(requestHeader, replyHeader, request, response, watchRegistration, false) { } internal Packet(RequestHeader requestHeader, ReplyHeader replyHeader, Record request, Record response, ZooKeeper.WatchRegistration watchRegistration, bool readOnly):base(TaskCreationOptions.RunContinuationsAsynchronously) { this.requestHeader = requestHeader; this.replyHeader = replyHeader; this.request = request; this.response = response; this.readOnly = readOnly; this.watchRegistration = watchRegistration; } public void createBB() { try { MemoryStream ms = new MemoryStream(); BigEndianBinaryWriter writer = new BigEndianBinaryWriter(ms); BinaryOutputArchive boa = BinaryOutputArchive.getArchive(writer); boa.writeInt(-1, "len"); // We'll fill this in later if (requestHeader != null) { ((Record) requestHeader).serialize(boa, "header"); } if (request is ConnectRequest) { request.serialize(boa, "connect"); // append "am-I-allowed-to-be-readonly" flag boa.writeBool(readOnly, "readOnly"); } else if (request != null) { request.serialize(boa, "request"); } ms.Position = 0; bb = new ByteBuffer(ms); boa.writeInt(bb.limit() - 4, "len"); ms.Position = 0; } catch (Exception e) { LOG.warn("Ignoring unexpected exception", e); } } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append(" clientPath:").Append(clientPath); sb.Append(" serverPath:").Append(serverPath); sb.Append(" finished:").Append(Task.IsCompleted); sb.Append(" header::").Append(requestHeader); sb.Append("replyHeader::").Append(replyHeader); sb.Append(" request::").Append(request); sb.Append(" response::").Append(response); // jute toString is horrible, remove unnecessary newlines return sb.ToString().Replace(@"\r*\n+", " "); } } /** * Creates a connection object. The actual network connect doesn't get * established until needed. The start() instance method must be called * subsequent to construction. * * @param chrootPath - the chroot of this client. Should be removed from this Class in ZOOKEEPER-838 * @param hostProvider * the list of ZooKeeper servers to connect to * @param sessionTimeout * the timeout for connections. * @param zooKeeper * the zookeeper object that this connection is related to. * @param watcher watcher for this connection * @param clientCnxnSocket * the socket implementation used (e.g. NIO/Netty) * @param sessionId * session id if re-establishing session * @param sessionPasswd * session passwd if re-establishing session * @param canBeReadOnly * whether the connection is allowed to go to read-only mode in * case of partitioning * @throws IOException */ internal ClientCnxn(string chrootPath, HostProvider hostProvider, int sessionTimeout, ZooKeeper zooKeeper, ClientWatchManager watcher, long sessionId, byte[] sessionPasswd, bool canBeReadOnly) { this.zooKeeper = zooKeeper; this.watcher = watcher; this.sessionId = sessionId; this.sessionPasswd = sessionPasswd; this.sessionTimeout = sessionTimeout; this.hostProvider = hostProvider; this.chrootPath = chrootPath; readTimeout = sessionTimeout*2/3; readOnly = canBeReadOnly; clientCnxnSocket = new ClientCnxnSocketNIO(this); timer = new Timer(delegate { clientCnxnSocket.wakeupCnxn(); }, null, Timeout.Infinite, Timeout.Infinite); state.Value = (int) ZooKeeper.States.CONNECTING; } public void start() { sendTask = startSendTask(); eventTask = startEventTask(); } private static readonly WatcherSetEventPair eventOfDeath = new WatcherSetEventPair(null, null); private class WatcherSetEventPair { internal readonly HashSet<Watcher> watchers; internal readonly WatchedEvent @event; public WatcherSetEventPair(HashSet<Watcher> watchers, WatchedEvent @event) { this.watchers = watchers; this.@event = @event; } } private readonly AwaitableSignal waitingEventsSignal = new AwaitableSignal(); private readonly ConcurrentQueue<WatcherSetEventPair> waitingEvents=new ConcurrentQueue<WatcherSetEventPair>(); /** This is really the queued session state until the event * task actually processes the event and hands it to the watcher. But for all * But for all intents and purposes this is the state. */ private readonly VolatileInt sessionState = new VolatileInt((int) Watcher.Event.KeeperState.Disconnected); private void queueEvent(WatchedEvent @event) { if (@event.get_Type() == Watcher.Event.EventType.None && sessionState.Value == (int) @event.getState()) { return; } sessionState.Value = (int) @event.getState(); // materialize the watchers based on the event WatcherSetEventPair pair = new WatcherSetEventPair( watcher.materialize(@event.getState(), @event.get_Type(), @event.getPath()), @event); // queue the pair (watch set & event) for later processing waitingEvents.Enqueue(pair); waitingEventsSignal.TrySignal(); } private void queueEventOfDeath() { waitingEvents.Enqueue(eventOfDeath); waitingEventsSignal.TrySignal(); } private async Task startEventTask() { bool wasKilled = false; try { while (!(wasKilled && waitingEvents.IsEmpty)) { await waitingEventsSignal; waitingEventsSignal.Reset(); WatcherSetEventPair @event; while (waitingEvents.TryDequeue(out @event)) { if (@event == eventOfDeath) { wasKilled = true; } else { await processEvent(@event).ConfigureAwait(false); } } } } catch (Exception e) { LOG.warn("Exception occurred in EventTask", e); } LOG.info("EventTask shut down for session: 0x" + getSessionId().ToHexString()); } private static async Task processEvent(WatcherSetEventPair @event) { foreach (Watcher watcher in @event.watchers) { try { await watcher.process(@event.@event).ConfigureAwait(false); } catch (Exception t) { LOG.error("Error while calling watcher ", t); } } } private static void finishPacket(Packet p) { if (p.watchRegistration != null) { p.watchRegistration.register(p.replyHeader.getErr()); } p.SetFinished(); } private void conLossPacket(Packet p) { if (p.replyHeader == null) { return; } switch (getState()) { case ZooKeeper.States.AUTH_FAILED: p.replyHeader.setErr((int) KeeperException.Code.AUTHFAILED); break; case ZooKeeper.States.CLOSED: p.replyHeader.setErr((int) KeeperException.Code.SESSIONEXPIRED); break; default: p.replyHeader.setErr((int) KeeperException.Code.CONNECTIONLOSS); break; } //finishPacket(p); <-- moved outside since it should be called outside of a lock } private readonly VolatileLong lastZxid = new VolatileLong(0); private class SessionTimeoutException : IOException { public SessionTimeoutException(string msg) : base(msg) { } } private class SessionExpiredException : IOException { public SessionExpiredException(string msg) : base(msg) { } } private class RWServerFoundException : IOException { public RWServerFoundException(string msg) : base(msg) { } } public const int packetLen = 0xfffff; private long lastPingSentNs; private readonly ClientCnxnSocketNIO clientCnxnSocket; private readonly Random r = new Random(); private bool isFirstConnect = true; internal void readResponse(ByteBuffer incomingBuffer) { BigEndianBinaryReader bbis = new BigEndianBinaryReader(incomingBuffer.Stream); BinaryInputArchive bbia = BinaryInputArchive.getArchive(bbis); ReplyHeader replyHdr = new ReplyHeader(); ((Record) replyHdr).deserialize(bbia, "header"); if (replyHdr.getXid() == -2) { // -2 is the xid for pings if (LOG.isDebugEnabled()) { LOG.debug("Got ping response for sessionid: 0x" + sessionId.ToHexString() + " after " + ((TimeHelper.ElapsedNanoseconds - lastPingSentNs) / 1000000) + "ms"); } return; } if (replyHdr.getXid() == -4) { // -4 is the xid for AuthPacket if (replyHdr.getErr() == (int) KeeperException.Code.AUTHFAILED) { state.Value = (int) ZooKeeper.States.AUTH_FAILED; queueEvent(new WatchedEvent(Watcher.Event.EventType.None, Watcher.Event.KeeperState.AuthFailed, null)); } if (LOG.isDebugEnabled()) { LOG.debug("Got auth sessionid:0x" + sessionId.ToHexString()); } return; } if (replyHdr.getXid() == -1) { // -1 means notification if (LOG.isDebugEnabled()) { LOG.debug("Got notification sessionid:0x" + sessionId.ToHexString()); } WatcherEvent @event = new WatcherEvent(); ((Record) @event).deserialize(bbia, "response"); // convert from a server path to a client path if (chrootPath != null) { string serverPath = @event.getPath(); if (serverPath == chrootPath) { @event.setPath("/"); } else if (serverPath.Length > chrootPath.Length) { @event.setPath(serverPath.Substring(chrootPath.Length)); } else { LOG.warn("Got server path " + @event.getPath() + " which is too short for chroot path " + chrootPath); } } WatchedEvent we = new WatchedEvent(@event); if (LOG.isDebugEnabled()) { LOG.debug("Got " + we + " for sessionid 0x" + sessionId.ToHexString()); } queueEvent(we); return; } Packet packet; lock (pendingQueue) { if (pendingQueue.size() == 0) { throw new IOException("Nothing in the queue, but got " + replyHdr.getXid()); } packet = pendingQueue.First.Value; pendingQueue.RemoveFirst(); } /* * Since requests are processed in order, we better get a response * to the first request! */ try { if (packet.requestHeader.getXid() != replyHdr.getXid()) { packet.replyHeader.setErr((int) KeeperException.Code.CONNECTIONLOSS); throw new IOException("Xid out of order. Got Xid " + replyHdr.getXid() + " with err " + + replyHdr.getErr() + " expected Xid " + packet.requestHeader.getXid() + " for a packet with details: " + packet); } packet.replyHeader.setXid(replyHdr.getXid()); packet.replyHeader.setErr(replyHdr.getErr()); packet.replyHeader.setZxid(replyHdr.getZxid()); if (replyHdr.getZxid() > 0) { lastZxid.Value = replyHdr.getZxid(); } if (packet.response != null && replyHdr.getErr() == 0) { packet.response.deserialize(bbia, "response"); } if (LOG.isDebugEnabled()) { LOG.debug("Reading reply sessionid:0x" + sessionId.ToHexString() + ", packet:: " + packet); } } finally { finishPacket(packet); } } internal void primeConnection() { LOG.info("Socket connection established to " + clientCnxnSocket.getRemoteSocketAddress() + ", initiating session"); isFirstConnect = false; long sessId = (seenRwServerBefore.Value) ? sessionId : 0; ConnectRequest conReq = new ConnectRequest(0, lastZxid.Value, sessionTimeout, sessId, sessionPasswd); lock (outgoingQueue) { // We add backwards since we are pushing into the front // Only send if there's a pending watch // TODO: here we have the only remaining use of zooKeeper in // this class. It's to be eliminated! List<string> dataWatches = zooKeeper.getDataWatches(); List<string> existWatches = zooKeeper.getExistWatches(); List<string> childWatches = zooKeeper.getChildWatches(); long setWatchesLastZxid = lastZxid.Value; bool done = false; if (dataWatches.Count > 0 || existWatches.Count > 0 || childWatches.Count > 0) { using(var dataWatchesIter = prependChroot(dataWatches).GetEnumerator()) using(var existWatchesIter = prependChroot(existWatches).GetEnumerator()) using(var childWatchesIter = prependChroot(childWatches).GetEnumerator()) while (!done) { var dataWatchesBatch = new List<string>(); var existWatchesBatch = new List<string>(); var childWatchesBatch = new List<string>(); int batchLength = 0; // Note, we may exceed our max length by a bit when we add the last // watch in the batch. This isn't ideal, but it makes the code simpler. while (batchLength < SET_WATCHES_MAX_LENGTH) { string watch; if (dataWatchesIter.MoveNext()) { watch = dataWatchesIter.Current; dataWatchesBatch.Add(watch); } else if (existWatchesIter.MoveNext()) { watch = existWatchesIter.Current; existWatchesBatch.Add(watch); } else if (childWatchesIter.MoveNext()) { watch = childWatchesIter.Current; childWatchesBatch.Add(watch); } else { done = true; break; } batchLength += watch.Length; } SetWatches sw = new SetWatches(setWatchesLastZxid, dataWatchesBatch, existWatchesBatch, childWatchesBatch); RequestHeader h = new RequestHeader(); h.set_Type((int) ZooDefs.OpCode.setWatches); h.setXid(-8); Packet packet = new Packet(h, new ReplyHeader(), sw, null, null); outgoingQueue.AddFirst(packet); } } foreach (AuthData id in authInfo) { outgoingQueue.AddFirst(new Packet(new RequestHeader(-4, (int) ZooDefs.OpCode.auth), null, new AuthPacket(0, id.scheme, id.data), null, null)); } outgoingQueue.AddFirst(new Packet(null, null, conReq, null, null, readOnly)); } clientCnxnSocket.enableReadWriteOnly(); if (LOG.isDebugEnabled()) { LOG.debug("Session establishment request sent on " + clientCnxnSocket.getRemoteSocketAddress()); } } private List<string> prependChroot(List<string> paths) { if (chrootPath != null && paths.Count > 0) { for (int i = 0; i < paths.size(); ++i) { string clientPath = paths[i]; string serverPath; // handle clientPath = "/" if (clientPath.Length == 1) { serverPath = chrootPath; } else { serverPath = chrootPath + clientPath; } paths[i] = serverPath; } } return paths; } private void sendPing() { lastPingSentNs = TimeHelper.ElapsedNanoseconds; RequestHeader h = new RequestHeader(-2, (int) ZooDefs.OpCode.ping); queuePacket(h, null, null, null, null, null, null); } private ResolvedEndPoint rwServerAddress; private const int minPingRwTimeout = 100; private const int maxPingRwTimeout = 60000; private int pingRwTimeout = minPingRwTimeout; private void startConnect(ResolvedEndPoint addr) { state.Value = (int) ZooKeeper.States.CONNECTING; logStartConnect(addr); clientCnxnSocket.connect(addr); } private static void logStartConnect(ResolvedEndPoint addr) { string msg = "Opening socket connection to server " + addr; LOG.info(msg); } private const string RETRY_CONN_MSG = ", closing socket connection and attempting reconnect"; private async Task startSendTask() { try { clientCnxnSocket.introduce(sessionId); clientCnxnSocket.updateNow(); clientCnxnSocket.updateLastSendAndHeard(); int to; long lastPingRwServer = TimeHelper.ElapsedMiliseconds; const int MAX_SEND_PING_INTERVAL = 10000; //10 seconds ResolvedEndPoint serverAddress = null; while (getState().isAlive()) { try { if (!clientCnxnSocket.isConnected()) { if (!isFirstConnect) { await Task.Delay(r.Next(1000)).ConfigureAwait(false); } else { await hostProvider.next(1000).ConfigureAwait(false); } // don't re-establish connection if we are closing if (closing.Value || !getState().isAlive()) { break; } if (rwServerAddress != null) { serverAddress = rwServerAddress; rwServerAddress = null; } else { serverAddress = await hostProvider.next(1000).ConfigureAwait(false); } startConnect(serverAddress); clientCnxnSocket.updateLastSendAndHeard(); } if (getState().isConnected()) { to = readTimeout - clientCnxnSocket.getIdleRecv(); } else { to = connectTimeout - clientCnxnSocket.getIdleRecv(); } if (to <= 0) { string warnInfo; warnInfo = "Client session timed out, have not heard from server in " + clientCnxnSocket.getIdleRecv() + "ms" + " for sessionid 0x" + clientCnxnSocket.sessionId.ToHexString(); LOG.warn(warnInfo); throw new SessionTimeoutException(warnInfo); } if (getState().isConnected()) { // 1000(1 second) is to prevent race condition missing to send the second ping // also make sure not to send too many pings when readTimeout is small int timeToNextPing = readTimeout / 2 - clientCnxnSocket.getIdleSend() - ((clientCnxnSocket.getIdleSend() > 1000) ? 1000 : 0); // send a ping request either time is due or no packet sent out within MAX_SEND_PING_INTERVAL if (timeToNextPing <= 0 || clientCnxnSocket.getIdleSend() > MAX_SEND_PING_INTERVAL) { sendPing(); clientCnxnSocket.updateLastSend(); } else { if (timeToNextPing < to) { to = timeToNextPing; } } } // If we are in read-only mode, seek for read/write server if (getState() == ZooKeeper.States.CONNECTEDREADONLY) { long now = TimeHelper.ElapsedMiliseconds; int idlePingRwServer = (int) (now - lastPingRwServer); if (idlePingRwServer >= pingRwTimeout) { lastPingRwServer = now; idlePingRwServer = 0; pingRwTimeout = Math.Min(2*pingRwTimeout, maxPingRwTimeout); await pingRwServer().ConfigureAwait(false); } to = Math.Min(to, pingRwTimeout - idlePingRwServer); } if (to > 0 && !clientCnxnSocket.somethingIsPending.IsCompleted) { timer.Change(to, Timeout.Infinite); await clientCnxnSocket.somethingIsPending; timer.Change(Timeout.Infinite, Timeout.Infinite); } clientCnxnSocket.doTransport(); } catch (Exception e) { if (closing.Value) { if (LOG.isDebugEnabled()) { // closing so this is expected LOG.debug("An exception was thrown while closing send task for session 0x" + getSessionId().ToHexString(), e); } break; } // this is ugly, you have a better way speak up if (e is SessionExpiredException) { LOG.info("closing socket connection", e); } else if (e is SessionTimeoutException) { LOG.info(RETRY_CONN_MSG, e); } else if (e is EndOfStreamException) { LOG.info(RETRY_CONN_MSG, e); } else if (e is RWServerFoundException) { LOG.info(e); } else if (e is SocketException) { LOG.info(string.Format("Socket error occurred: {0}", serverAddress), e); } else { LOG.warn(string.Format("Session 0x{0} for server {1}, unexpected error{2}", getSessionId().ToHexString(), serverAddress, RETRY_CONN_MSG), e); } cleanup(); if (getState().isAlive()) { queueEvent(new WatchedEvent( Watcher.Event.EventType.None, Watcher.Event.KeeperState.Disconnected, null)); } clientCnxnSocket.updateNow(); clientCnxnSocket.updateLastSendAndHeard(); } } cleanup(); clientCnxnSocket.close(); if (getState().isAlive()) { queueEvent(new WatchedEvent(Watcher.Event.EventType.None, Watcher.Event.KeeperState.Disconnected, null)); } } catch(Exception e){ LOG.warn("Exception occurred in SendTask", e); } LOG.debug("SendTask exited loop for session: 0x" + getSessionId().ToHexString()); } private async Task pingRwServer() { string result = null; ResolvedEndPoint addr = await hostProvider.next(0).ConfigureAwait(false); LOG.info("Checking server " + addr + " for being r/w." + " Timeout " + pingRwTimeout); TcpClient sock = null; StreamReader br = null; try { sock = new TcpClient(); sock.LingerState = new LingerOption(false, 0); sock.SendTimeout = 1000; sock.NoDelay = true; await sock.ConnectAsync(addr.Address, addr.Port).ConfigureAwait(false); var networkStream = sock.GetStream(); await networkStream.WriteAsync("isro".UTF8getBytes(), 0, 4).ConfigureAwait(false); await networkStream.FlushAsync().ConfigureAwait(false); br = new StreamReader(networkStream); result = await br.ReadLineAsync().ConfigureAwait(false); } catch (Exception e) { var se = e.InnerException as SocketException; if (se != null && se.SocketErrorCode == SocketError.ConnectionRefused) { // ignore, this just means server is not up } else { // some unexpected error, warn about it LOG.warn("Exception while seeking for r/w server ", e); } } if (sock != null) { try { ((IDisposable) sock).Dispose(); } catch (Exception e) { LOG.warn("Unexpected exception", e); } } if (br != null) { try { br.Dispose(); } catch (Exception e) { LOG.warn("Unexpected exception", e); } } if ("rw" == result) { pingRwTimeout = minPingRwTimeout; // save the found address so that it's used during the next // connection attempt rwServerAddress = addr; throw new RWServerFoundException("Majority server found at " + addr); } } private void cleanup() { clientCnxnSocket.cleanup(); var connLostPackets = new List<Packet>(); lock (pendingQueue) { foreach (Packet p in pendingQueue) { conLossPacket(p); connLostPackets.Add(p); } pendingQueue.Clear(); } lock (outgoingQueue) { foreach (Packet p in outgoingQueue) { conLossPacket(p); connLostPackets.Add(p); } outgoingQueue.Clear(); } foreach (var conLostPacket in connLostPackets) { finishPacket(conLostPacket); } } /** * Callback invoked by the ClientCnxnSocket once a connection has been * established. * * @param _negotiatedSessionTimeout * @param _sessionId * @param _sessionPasswd * @param isRO * @throws IOException */ internal void onConnected(int _negotiatedSessionTimeout, long _sessionId, byte[] _sessionPasswd, bool isRO) { negotiatedSessionTimeout.Value = _negotiatedSessionTimeout; if (negotiatedSessionTimeout.Value <= 0) { state.Value = (int) ZooKeeper.States.CLOSED; queueEvent(new WatchedEvent( Watcher.Event.EventType.None, Watcher.Event.KeeperState.Expired, null)); queueEventOfDeath(); string warnInfo = "Unable to reconnect to ZooKeeper service, session 0x" + sessionId.ToHexString() + " has expired"; LOG.warn(warnInfo); throw new SessionExpiredException(warnInfo); } if (!readOnly && isRO) { LOG.error("Read/write client got connected to read-only server"); } readTimeout = negotiatedSessionTimeout.Value*2/3; hostProvider.onConnected(); sessionId = _sessionId; sessionPasswd = _sessionPasswd; state.Value = (int) (isRO ? ZooKeeper.States.CONNECTEDREADONLY : ZooKeeper.States.CONNECTED); seenRwServerBefore.Value |= !isRO; LOG.info("Session establishment complete on server " + clientCnxnSocket.getRemoteSocketAddress() + ", sessionid = 0x" + sessionId.ToHexString() + ", negotiated timeout = " + negotiatedSessionTimeout.Value + (isRO ? " (READ-ONLY mode)" : "")); Watcher.Event.KeeperState eventState = (isRO) ? Watcher.Event.KeeperState.ConnectedReadOnly : Watcher.Event.KeeperState.SyncConnected; queueEvent(new WatchedEvent( Watcher.Event.EventType.None, eventState, null)); } private void close() { state.Value = (int) ZooKeeper.States.CLOSED; clientCnxnSocket.wakeupCnxn(); } /** * Shutdown the send/event tasks. This method should not be called * directly - rather it should be called as part of close operation. This * method is primarily here to allow the tests to verify disconnection * behavior. */ private void disconnect() { if (LOG.isDebugEnabled()) { LOG.debug("Disconnecting client for session: 0x" + getSessionId().ToHexString()); } close(); queueEventOfDeath(); } private int isDisposed; /** * Close the connection, which includes; send session disconnect to the * server, shutdown the send/event tasks. * */ internal async Task closeAsync() { if (Interlocked.CompareExchange(ref isDisposed, 1, 0) == 0) { if (LOG.isDebugEnabled()) { LOG.debug("Closing client for session: 0x" + getSessionId().ToHexString()); } try { RequestHeader h = new RequestHeader(); h.set_Type((int) ZooDefs.OpCode.closeSession); await submitRequest(h, null, null, null).ConfigureAwait(false); } finally { disconnect(); } await sendTask.ConfigureAwait(false); await eventTask.ConfigureAwait(false); timer.Dispose(); } } private int xid = 1; private readonly VolatileInt state = new VolatileInt((int) ZooKeeper.States.NOT_CONNECTED); /* * getXid() is called externally by ClientCnxnNIO::doIO() when packets are * sent from the outgoingQueue to the server. Thus, getXid() must be public. */ public int getXid() { return Interlocked.Increment(ref xid); } public async Task<ReplyHeader> submitRequest(RequestHeader h, Record request, Record response, ZooKeeper.WatchRegistration watchRegistration) { ReplyHeader rep = new ReplyHeader(); Packet packet = queuePacket(h, rep, request, response, null, null, watchRegistration); await packet.Task.ConfigureAwait(false); return rep; } internal Packet queuePacket(RequestHeader h, ReplyHeader rep, Record request, Record response, string clientPath, string serverPath, ZooKeeper.WatchRegistration watchRegistration) { Packet packet; // Note that we do not generate the Xid for the packet yet. It is // generated later at send-time, by an implementation of // ClientCnxnSocket::doIO(), // where the packet is actually sent. bool isConnectionLostPacket = false; lock (outgoingQueue) { packet = new Packet(h, rep, request, response, watchRegistration); packet.clientPath = clientPath; packet.serverPath = serverPath; if (!getState().isAlive() || closing.Value) { conLossPacket(packet); isConnectionLostPacket = true; } else { // If the client is asking to close the session then // mark as closing if (h.get_Type() == (int) ZooDefs.OpCode.closeSession) { closing.Value = true; } outgoingQueue.AddLast(packet); } } if(isConnectionLostPacket) finishPacket(packet); clientCnxnSocket.wakeupCnxn(); return packet; } public void addAuthInfo(string scheme, byte[] auth) { if (!getState().isAlive()) { return; } List<AuthData> newAuthDataList = new List<AuthData>(authInfo) {new AuthData(scheme, auth)}; authInfo = newAuthDataList; queuePacket(new RequestHeader(-4, (int) ZooDefs.OpCode.auth), null, new AuthPacket(0, scheme, auth), null, null, null, null); } internal ZooKeeper.States getState() { return (ZooKeeper.States) state.Value; } } }
/* Copyright 2011 - 2022 Adrian Popescu Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Xml; using System.Xml.Serialization; using Newtonsoft.Json; using Redmine.Net.Api.Extensions; using Redmine.Net.Api.Internals; using Redmine.Net.Api.Serialization; namespace Redmine.Net.Api.Types { /// <summary> /// Availability 2.2 /// </summary> [DebuggerDisplay("{" + nameof(DebuggerDisplay) + ",nq}")] [XmlRoot(RedmineKeys.WIKI_PAGE)] public sealed class WikiPage : Identifiable<WikiPage> { #region Properties /// <summary> /// Gets the title. /// </summary> public string Title { get; internal set; } /// <summary> /// Gets or sets the text. /// </summary> public string Text { get; set; } /// <summary> /// Gets or sets the comments /// </summary> public string Comments { get; set; } /// <summary> /// Gets or sets the version /// </summary> public int Version { get; set; } /// <summary> /// Gets the author. /// </summary> public IdentifiableName Author { get; internal set; } /// <summary> /// Gets the created on. /// </summary> /// <value>The created on.</value> public DateTime? CreatedOn { get; internal set; } /// <summary> /// Gets or sets the updated on. /// </summary> /// <value>The updated on.</value> public DateTime? UpdatedOn { get; internal set; } /// <summary> /// Gets the attachments. /// </summary> /// <value> /// The attachments. /// </value> public IList<Attachment> Attachments { get; set; } /// <summary> /// Sets the uploads. /// </summary> /// <value> /// The uploads. /// </value> /// <remarks>Availability starting with redmine version 3.3</remarks> public IList<Upload> Uploads { get; set; } #endregion #region Implementation of IXmlSerializable /// <summary> /// /// </summary> /// <param name="reader"></param> public override void ReadXml(XmlReader reader) { reader.Read(); while (!reader.EOF) { if (reader.IsEmptyElement && !reader.HasAttributes) { reader.Read(); continue; } switch (reader.Name) { case RedmineKeys.ID: Id = reader.ReadElementContentAsInt(); break; case RedmineKeys.ATTACHMENTS: Attachments = reader.ReadElementContentAsCollection<Attachment>(); break; case RedmineKeys.AUTHOR: Author = new IdentifiableName(reader); break; case RedmineKeys.COMMENTS: Comments = reader.ReadElementContentAsString(); break; case RedmineKeys.CREATED_ON: CreatedOn = reader.ReadElementContentAsNullableDateTime(); break; case RedmineKeys.TEXT: Text = reader.ReadElementContentAsString(); break; case RedmineKeys.TITLE: Title = reader.ReadElementContentAsString(); break; case RedmineKeys.UPDATED_ON: UpdatedOn = reader.ReadElementContentAsNullableDateTime(); break; case RedmineKeys.VERSION: Version = reader.ReadElementContentAsInt(); break; default: reader.Read(); break; } } } /// <summary> /// /// </summary> /// <param name="writer"></param> public override void WriteXml(XmlWriter writer) { writer.WriteElementString(RedmineKeys.TEXT, Text); writer.WriteElementString(RedmineKeys.COMMENTS, Comments); writer.WriteValueOrEmpty<int>(RedmineKeys.VERSION, Version); writer.WriteArray(RedmineKeys.UPLOADS, Uploads); } #endregion #region Implementation of IJsonSerialization /// <summary> /// /// </summary> /// <param name="reader"></param> public override void ReadJson(JsonReader reader) { while (reader.Read()) { if (reader.TokenType == JsonToken.EndObject) { return; } if (reader.TokenType != JsonToken.PropertyName) { continue; } switch (reader.Value) { case RedmineKeys.ID: Id = reader.ReadAsInt(); break; case RedmineKeys.ATTACHMENTS: Attachments = reader.ReadAsCollection<Attachment>(); break; case RedmineKeys.AUTHOR: Author = new IdentifiableName(reader); break; case RedmineKeys.COMMENTS: Comments = reader.ReadAsString(); break; case RedmineKeys.CREATED_ON: CreatedOn = reader.ReadAsDateTime(); break; case RedmineKeys.TEXT: Text = reader.ReadAsString(); break; case RedmineKeys.TITLE: Title = reader.ReadAsString(); break; case RedmineKeys.UPDATED_ON: UpdatedOn = reader.ReadAsDateTime(); break; case RedmineKeys.VERSION: Version = reader.ReadAsInt(); break; default: reader.Read(); break; } } } /// <summary> /// /// </summary> /// <param name="writer"></param> public override void WriteJson(JsonWriter writer) { using (new JsonObject(writer, RedmineKeys.WIKI_PAGE)) { writer.WriteProperty(RedmineKeys.TEXT, Text); writer.WriteProperty(RedmineKeys.COMMENTS, Comments); writer.WriteValueOrEmpty<int>(RedmineKeys.VERSION, Version); writer.WriteArray(RedmineKeys.UPLOADS, Uploads); } } #endregion #region Implementation of IEquatable<WikiPage> /// <summary> /// /// </summary> /// <param name="other"></param> /// <returns></returns> public override bool Equals(WikiPage other) { if (other == null) return false; return Id == other.Id && Title == other.Title && Text == other.Text && Comments == other.Comments && Version == other.Version && Author == other.Author && CreatedOn == other.CreatedOn && UpdatedOn == other.UpdatedOn; } /// <summary> /// /// </summary> /// <returns></returns> public override int GetHashCode() { unchecked { var hashCode = base.GetHashCode(); hashCode = HashCodeHelper.GetHashCode(Title, hashCode); hashCode = HashCodeHelper.GetHashCode(Text, hashCode); hashCode = HashCodeHelper.GetHashCode(Comments, hashCode); hashCode = HashCodeHelper.GetHashCode(Version, hashCode); hashCode = HashCodeHelper.GetHashCode(Author, hashCode); hashCode = HashCodeHelper.GetHashCode(CreatedOn, hashCode); hashCode = HashCodeHelper.GetHashCode(UpdatedOn, hashCode); hashCode = HashCodeHelper.GetHashCode(Attachments, hashCode); return hashCode; } } #endregion /// <summary> /// /// </summary> /// <returns></returns> private string DebuggerDisplay => $@"[{nameof(WikiPage)}: {ToString()}, Title={Title}, Text={Text}, Comments={Comments}, Version={Version.ToString(CultureInfo.InvariantCulture)}, Author={Author}, CreatedOn={CreatedOn?.ToString("u", CultureInfo.InvariantCulture)}, UpdatedOn={UpdatedOn?.ToString("u", CultureInfo.InvariantCulture)}, Attachments={Attachments.Dump()}]"; } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if UNIX using System; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Resources; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Management.Automation.Internal; namespace System.Management.Automation.Tracing { /// <summary> /// Encapsulates the message resource and SysLog logging for an ETW event. /// The other half of the partial class is generated by EtwGen and contains a /// static dictionary containing the event id mapped to the associated event meta data /// and resource string reference. /// </summary> /// <remarks> /// This component logs ETW trace events to syslog. /// The log entries use the following common format /// (commitId:threadId:channelid) [context] payload /// Where: /// commitId: A hash code of the full git commit id string. /// threadid: The thread identifier of calling code. /// channelid: The identifier for the output channel. See PSChannel for values. /// context: Dependent on the type of log entry. /// payload: Dependent on the type of log entry. /// Note: /// commitId, threadId, and eventId are logged as HEX without a leading /// '0x'. /// /// 4 types of log entries are produced. /// NOTE: Where constant string are logged, the template places the string in /// double quotes. For example, the GitCommitId log entry uses "GitCommitId" /// for the context value. /// /// Note that the examples illustrate the output from SysLogProvider.Log, /// Data automatically prepended by syslog, such as timestamp, hostname, ident, /// and processid are not shown. /// /// GitCommitId /// This is the first log entry for a session. It provides a correlation /// between the full git commit id string and a hash code used for subsequent /// log entries. /// Context: "GitCommitId" /// Payload: string "Hash:" hashcode as HEX string. /// For official builds, the GitCommitID is the release tag. For other builds the commit id may include an SHA-1 hash at the /// end of the release tag. /// Example 1: Official release /// (19E1025:3:10) [GitCommitId] v6.0.0-beta.9 Hash:64D0C08D /// Example 2: Commit id with SHA-1 hash /// (19E1025:3:10) [GitCommitId] v6.0.0-beta.8-67-gca2630a3dea6420a3cd3914c84a74c1c45311f54 Hash:8EE3A3B3 /// /// Transfer /// A log entry to record a transfer event. /// Context: "Transfer" /// The playload is two, space separated string guids, the first being the /// parent activityid followed by the new activityid. /// Example: (19E1025:3:10) [Transfer] {de168a71-6bb9-47e4-8712-bc02506d98be} {ab0077f6-c042-4728-be76-f688cfb1b054} /// /// Activity /// A log entry for when activity is set. /// Context: "Activity" /// Payload: The string guid of the activity id. /// Example: (19E1025:3:10) [Activity] {ab0077f6-c042-4728-be76-f688cfb1b054} /// /// Event /// Application logging (Events) /// Context: EventId:taskname.opcodename.levelname /// Payload: The event's message text formatted with arguments from the caller. /// Example: (19E1025:3:10) [Perftrack_ConsoleStartupStart:PowershellConsoleStartup.WinStart.Informational] PowerShell console is starting up /// </remarks> internal class SysLogProvider { // Ensure the string pointer is not garbage collected. private static IntPtr _nativeSyslogIdent = IntPtr.Zero; private static readonly NativeMethods.SysLogPriority _facility = NativeMethods.SysLogPriority.Local0; private readonly byte _channelFilter; private readonly ulong _keywordFilter; private readonly byte _levelFilter; /// <summary> /// Initializes a new instance of this class. /// </summary> /// <param name="applicationId">The log identity name used to identify the application in syslog.</param> /// <param name="level">The trace level to enable.</param> /// <param name="keywords">The keywords to enable.</param> /// <param name="channels">The output channels to enable.</param> public SysLogProvider(string applicationId, PSLevel level, PSKeyword keywords, PSChannel channels) { // NOTE: This string needs to remain valid for the life of the process since the underlying API keeps // a reference to it. // FUTURE: If logging is redesigned, make these details static or a singleton since there should only be one // instance active. _nativeSyslogIdent = Marshal.StringToHGlobalAnsi(applicationId); NativeMethods.OpenLog(_nativeSyslogIdent, _facility); _keywordFilter = (ulong)keywords; _levelFilter = (byte)level; _channelFilter = (byte)channels; if ((_channelFilter & (ulong)PSChannel.Operational) != 0) { _keywordFilter |= (ulong)PSKeyword.UseAlwaysOperational; } if ((_channelFilter & (ulong)PSChannel.Analytic) != 0) { _keywordFilter |= (ulong)PSKeyword.UseAlwaysAnalytic; } } /// <summary> /// Defines a thread local StringBuilder for building log messages. /// </summary> /// <remarks> /// NOTE: do not access this field directly, use the MessageBuilder /// property to ensure correct thread initialization; otherwise, a null reference can occur. /// </remarks> [ThreadStatic] private static StringBuilder t_messageBuilder; private static StringBuilder MessageBuilder { get { if (t_messageBuilder == null) { // NOTE: Thread static fields must be explicitly initialized for each thread. t_messageBuilder = new StringBuilder(200); } return t_messageBuilder; } } /// <summary> /// Defines a activity id for the current thread. /// </summary> /// <remarks> /// NOTE: do not access this field directly, use the Activity property /// to ensure correct thread initialization. /// </remarks> [ThreadStatic] private static Guid? t_activity; private static Guid Activity { get { if (!t_activity.HasValue) { // NOTE: Thread static fields must be explicitly initialized for each thread. t_activity = Guid.NewGuid(); } return t_activity.Value; } set { t_activity = value; } } /// <summary> /// Gets the value indicating if the specified level and keywords are enabled for logging. /// </summary> /// <param name="level">The PSLevel to check.</param> /// <param name="keywords">The PSKeyword to check.</param> /// <returns>True if the specified level and keywords are enabled for logging.</returns> internal bool IsEnabled(PSLevel level, PSKeyword keywords) { return ((ulong)keywords & _keywordFilter) != 0 && ((int)level <= _levelFilter); } // NOTE: There are a number of places where PowerShell code sends analytic events // to the operational channel. This is a side-effect of the custom wrappers that // use flags that are not consistent with the event definition. // To ensure filtering of analytic events is consistent, both keyword and channel // filtering is performed to suppress analytic events. private bool ShouldLog(PSLevel level, PSKeyword keywords, PSChannel channel) { return (_channelFilter & (ulong)channel) != 0 && IsEnabled(level, keywords); } #region resource manager private static global::System.Resources.ResourceManager _resourceManager; private static global::System.Globalization.CultureInfo _resourceCulture; private static global::System.Resources.ResourceManager ResourceManager { get { if (_resourceManager is null) { _resourceManager = new global::System.Resources.ResourceManager("System.Management.Automation.resources.EventResource", typeof(EventResource).Assembly); } return _resourceManager; } } /// <summary> /// Overrides the current threads CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return _resourceCulture; } set { _resourceCulture = value; } } private static string GetResourceString(string resourceName) { string value = ResourceManager.GetString(resourceName, Culture); if (string.IsNullOrEmpty(value)) { value = string.Format(CultureInfo.InvariantCulture, "Unknown resource: {0}", resourceName); Diagnostics.Assert(false, value); } return value; } #endregion resource manager /// <summary> /// Gets the EventMessage for a given event. /// </summary> /// <param name="sb">The StringBuilder to append.</param> /// <param name="eventId">The id of the event to retrieve.</param> /// <param name="args">An array of zero or more payload objects.</param> private static void GetEventMessage(StringBuilder sb, PSEventId eventId, params object[] args ) { int parameterCount; string resourceName = EventResource.GetMessage((int)eventId, out parameterCount); if (resourceName == null) { // If an event id was specified that is not found in the event resource lookup table, // use a placeholder message that includes the event id. resourceName = EventResource.GetMissingEventMessage(out parameterCount); Diagnostics.Assert(false, sb.ToString()); args = new object[] {eventId}; } string resourceValue = GetResourceString(resourceName); if (parameterCount > 0) { sb.AppendFormat(resourceValue, args); } else { sb.Append(resourceValue); } } #region logging // maps a LogLevel to an associated SysLogPriority. private static readonly NativeMethods.SysLogPriority[] _levels = { NativeMethods.SysLogPriority.Info, NativeMethods.SysLogPriority.Critical, NativeMethods.SysLogPriority.Error, NativeMethods.SysLogPriority.Warning, NativeMethods.SysLogPriority.Info, NativeMethods.SysLogPriority.Info }; /// <summary> /// Logs a activity transfer. /// </summary> /// <param name="parentActivityId">The parent activity id.</param> public void LogTransfer(Guid parentActivityId) { // NOTE: always log int threadId = Environment.CurrentManagedThreadId; string message = string.Format(CultureInfo.InvariantCulture, "({0}:{1:X}:{2:X}) [Transfer]:{3} {4}", PSVersionInfo.GitCommitId, threadId, PSChannel.Operational, parentActivityId.ToString("B"), Activity.ToString("B")); NativeMethods.SysLog(NativeMethods.SysLogPriority.Info, message); } /// <summary> /// Logs the activity identifier for the current thread. /// </summary> /// <param name="activity">The Guid activity identifier.</param> public void SetActivity(Guid activity) { int threadId = Environment.CurrentManagedThreadId; Activity = activity; // NOTE: always log string message = string.Format(CultureInfo.InvariantCulture, "({0:X}:{1:X}:{2:X}) [Activity] {3}", PSVersionInfo.GitCommitId, threadId, PSChannel.Operational, activity.ToString("B")); NativeMethods.SysLog(NativeMethods.SysLogPriority.Info, message); } /// <summary> /// Writes a log entry. /// </summary> /// <param name="eventId">The event id of the log entry.</param> /// <param name="channel">The channel to log.</param> /// <param name="task">The task for the log entry.</param> /// <param name="opcode">The operation for the log entry.</param> /// <param name="level">The logging level.</param> /// <param name="keyword">The keyword(s) for the event.</param> /// <param name="args">The payload for the log message.</param> public void Log(PSEventId eventId, PSChannel channel, PSTask task, PSOpcode opcode, PSLevel level, PSKeyword keyword, params object[] args) { if (ShouldLog(level, keyword, channel)) { int threadId = Environment.CurrentManagedThreadId; StringBuilder sb = MessageBuilder; sb.Clear(); // add the message preamble sb.AppendFormat(CultureInfo.InvariantCulture, "({0}:{1:X}:{2:X}) [{3:G}:{4:G}.{5:G}.{6:G}] ", PSVersionInfo.GitCommitId, threadId, channel, eventId, task, opcode, level); // add the message GetEventMessage(sb, eventId, args); NativeMethods.SysLogPriority priority; if ((int)level <= _levels.Length) { priority = _levels[(int)level]; } else { priority = NativeMethods.SysLogPriority.Info; } // log it. NativeMethods.SysLog(priority, sb.ToString()); } } #endregion logging } internal enum LogLevel : uint { Always = 0, Critical = 1, Error = 2, Warning = 3, Information = 4, Verbose = 5 } internal static class NativeMethods { private const string libpslnative = "libpsl-native"; /// <summary> /// Write a message to the system logger, which in turn writes the message to the system console, log files, etc. /// See man 3 syslog for more info. /// </summary> /// <param name="priority"> /// The OR of a priority and facility in the SysLogPriority enum indicating the the priority and facility of the log entry. /// </param> /// <param name="message">The message to put in the log entry.</param> [DllImport(libpslnative, CharSet = CharSet.Ansi, EntryPoint = "Native_SysLog")] internal static extern void SysLog(SysLogPriority priority, string message); [DllImport(libpslnative, CharSet = CharSet.Ansi, EntryPoint = "Native_OpenLog")] internal static extern void OpenLog(IntPtr ident, SysLogPriority facility); [DllImport(libpslnative, EntryPoint = "Native_CloseLog")] internal static extern void CloseLog(); [Flags] internal enum SysLogPriority : uint { // Priorities enum values. /// <summary> /// System is unusable. /// </summary> Emergency = 0, /// <summary> /// Action must be taken immediately. /// </summary> Alert = 1, /// <summary> /// Critical conditions. /// </summary> Critical = 2, /// <summary> /// Error conditions. /// </summary> Error = 3, /// <summary> /// Warning conditions. /// </summary> Warning = 4, /// <summary> /// Normal but significant condition. /// </summary> Notice = 5, /// <summary> /// Informational. /// </summary> Info = 6, /// <summary> /// Debug-level messages. /// </summary> Debug = 7, // Facility enum values. /// <summary> /// Kernel messages. /// </summary> Kernel = (0 << 3), /// <summary> /// Random user-level messages. /// </summary> User = (1 << 3), /// <summary> /// Mail system. /// </summary> Mail = (2 << 3), /// <summary> /// System daemons. /// </summary> Daemon = (3 << 3), /// <summary> /// Authorization messages. /// </summary> Authorization = (4 << 3), /// <summary> /// Messages generated internally by syslogd. /// </summary> Syslog = (5 << 3), /// <summary> /// Line printer subsystem. /// </summary> Lpr = (6 << 3), /// <summary> /// Network news subsystem. /// </summary> News = (7 << 3), /// <summary> /// UUCP subsystem. /// </summary> Uucp = (8 << 3), /// <summary> /// Clock daemon. /// </summary> Cron = (9 << 3), /// <summary> /// Security/authorization messages (private) /// </summary> Authpriv = (10 << 3), /// <summary> /// FTP daemon. /// </summary> Ftp = (11 << 3), // Reserved for system use /// <summary> /// Reserved for local use. /// </summary> Local0 = (16 << 3), /// <summary> /// Reserved for local use. /// </summary> Local1 = (17 << 3), /// <summary> /// Reserved for local use. /// </summary> Local2 = (18 << 3), /// <summary> /// Reserved for local use. /// </summary> Local3 = (19 << 3), /// <summary> /// Reserved for local use. /// </summary> Local4 = (20 << 3), /// <summary> /// Reserved for local use. /// </summary> Local5 = (21 << 3), /// <summary> /// Reserved for local use. /// </summary> Local6 = (22 << 3), /// <summary> /// Reserved for local use. /// </summary> Local7 = (23 << 3), } } } #endif // UNIX
using System; using System.Globalization; using System.Text; namespace FileHelpers { /// <summary> /// Class that provides static methods that returns a default /// <see cref="ConverterBase">Converter</see> to the basic types. /// </summary> /// <remarks> /// Used by the <see cref="FileHelpers.FieldConverterAttribute"/>. /// </remarks> internal static class ConvertHelpers { private const string DefaultDecimalSep = "."; #region " CreateCulture " /// <summary> /// Return culture information for with comma decimal separator or comma decimal separator /// </summary> /// <param name="decimalSep">Decimal separator string</param> /// <returns>Cultural information based on separator</returns> private static CultureInfo CreateCulture(string decimalSep) { var ci = new CultureInfo(CultureInfo.CurrentCulture.LCID); if (decimalSep == ".") { ci.NumberFormat.NumberDecimalSeparator = "."; ci.NumberFormat.NumberGroupSeparator = ","; } else if (decimalSep == ",") { ci.NumberFormat.NumberDecimalSeparator = ","; ci.NumberFormat.NumberGroupSeparator = "."; } else throw new BadUsageException("You can only use '.' or ',' as decimal or group separators"); return ci; } #endregion #region " GetDefaultConverter " /// <summary> /// Check the type of the field and then return a converter for that particular type /// </summary> /// <param name="fieldName">Field name to check</param> /// <param name="fieldType">Type of the field to check</param> /// <returns>Converter for this particular field</returns> internal static ConverterBase GetDefaultConverter(string fieldName, Type fieldType) { if (fieldType.IsArray) { if (fieldType.GetArrayRank() != 1) { throw new BadUsageException("The array field: '" + fieldName + "' has more than one dimension and is not supported by the library."); } fieldType = fieldType.GetElementType(); if (fieldType.IsArray) { throw new BadUsageException("The array field: '" + fieldName + "' is a jagged array and is not supported by the library."); } } if (fieldType.IsValueType && fieldType.IsGenericType && fieldType.GetGenericTypeDefinition() == typeof (Nullable<>)) fieldType = fieldType.GetGenericArguments()[0]; // Try to assign a default Converter if (fieldType == typeof (string)) return null; if (fieldType == typeof (Int16)) return new Int16Converter(); if (fieldType == typeof (Int32)) return new Int32Converter(); if (fieldType == typeof (Int64)) return new Int64Converter(); if (fieldType == typeof (SByte)) return new SByteConverter(); if (fieldType == typeof (UInt16)) return new UInt16Converter(); if (fieldType == typeof (UInt32)) return new UInt32Converter(); if (fieldType == typeof (UInt64)) return new UInt64Converter(); if (fieldType == typeof (byte)) return new ByteConverter(); if (fieldType == typeof (decimal)) return new DecimalConverter(); if (fieldType == typeof (double)) return new DoubleConverter(); if (fieldType == typeof (Single)) return new SingleConverter(); if (fieldType == typeof (DateTime)) return new DateTimeConverter(); if (fieldType == typeof (bool)) return new BooleanConverter(); // Added by Alexander Obolonkov 2007.11.08 (the next three) if (fieldType == typeof (char)) return new CharConverter(); if (fieldType == typeof (Guid)) return new GuidConverter(); if (fieldType.IsEnum) return new EnumConverter(fieldType); throw new BadUsageException("The field: '" + fieldName + "' has the type: " + fieldType.Name + " that is not a system type, so this field need a CustomConverter ( Please Check the docs for more Info)."); } #endregion /// <summary> /// Convert a numeric value with separators into a value /// </summary> internal abstract class CultureConverter : ConverterBase { /// <summary> /// Culture information based on the separator /// </summary> protected CultureInfo mCulture; /// <summary> /// Type fo field being converted /// </summary> protected Type mType; /// <summary> /// Convert to a type given a decimal separator /// </summary> /// <param name="T">type we are converting</param> /// <param name="decimalSep">Separator</param> protected CultureConverter(Type T, string decimalSep) { mCulture = CreateCulture(decimalSep); mType = T; } /// <summary> /// Convert the field to a string representation /// </summary> /// <param name="from">Object to convert</param> /// <returns>string representation</returns> public override sealed string FieldToString(object from) { if (from == null) return string.Empty; return ((IConvertible) from).ToString(mCulture); } /// <summary> /// Convert a string to the object type /// </summary> /// <param name="from">String to convert</param> /// <returns>Object converted to</returns> public override sealed object StringToField(string from) { return ParseString(from); } /// <summary> /// Convert a string into the return object required /// </summary> /// <param name="from">Value to convert (string)</param> /// <returns>Converted object</returns> protected abstract object ParseString(string from); } /// <summary> /// COnvert a string into a byte value /// </summary> internal sealed class ByteConverter : CultureConverter { /// <summary> /// Convert a string to a byte value using the default decimal separator /// </summary> public ByteConverter() : this(DefaultDecimalSep) {} /// <summary> /// Convert a string to a byte /// </summary> /// <param name="decimalSep">decimal separator to use '.' or ','</param> public ByteConverter(string decimalSep) : base(typeof (Byte), decimalSep) {} /// <summary> /// Convert a string to a byte value /// </summary> /// <param name="from">string to parse</param> /// <returns>byte value</returns> protected override object ParseString(string from) { byte res; if (!byte.TryParse(StringHelper.RemoveBlanks(from), NumberStyles.Number, mCulture, out res)) throw new ConvertException(from, mType); return res; } } /// <summary> /// Convert a string to a short integer /// </summary> internal sealed class UInt16Converter : CultureConverter { /// <summary> /// Convert a number to a short integer /// </summary> public UInt16Converter() : this(DefaultDecimalSep) {} /// <summary> /// Convert a number to a short integer /// </summary> /// <param name="decimalSep">Decimal separator</param> public UInt16Converter(string decimalSep) : base(typeof (UInt16), decimalSep) {} /// <summary> /// Parse a string to a short integer /// </summary> /// <param name="from">string representing short integer</param> /// <returns>short integer value</returns> protected override object ParseString(string from) { ushort res; if ( !UInt16.TryParse(StringHelper.RemoveBlanks(from), NumberStyles.Number | NumberStyles.AllowExponent, mCulture, out res)) throw new ConvertException(from, mType); return res; } } /// <summary> /// Unsigned integer converter /// </summary> internal sealed class UInt32Converter : CultureConverter { /// <summary> /// Unsigned integer converter /// </summary> public UInt32Converter() : this(DefaultDecimalSep) {} /// <summary> /// Unsigned integer converter with a decimal separator /// </summary> /// <param name="decimalSep">dot or comma for to separate decimal</param> public UInt32Converter(string decimalSep) : base(typeof (UInt32), decimalSep) {} /// <summary> /// Convert a string to a unsigned integer value /// </summary> /// <param name="from">String value to parse</param> /// <returns>Unsigned integer object</returns> protected override object ParseString(string from) { uint res; if ( !UInt32.TryParse(StringHelper.RemoveBlanks(from), NumberStyles.Number | NumberStyles.AllowExponent, mCulture, out res)) throw new ConvertException(from, mType); return res; } } /// <summary> /// Unsigned long converter /// </summary> internal sealed class UInt64Converter : CultureConverter { /// <summary> /// Unsigned long converter /// </summary> public UInt64Converter() : this(DefaultDecimalSep) {} /// <summary> /// Unsigned long with decimal separator /// </summary> /// <param name="decimalSep">dot or comma for separator</param> public UInt64Converter(string decimalSep) : base(typeof (UInt64), decimalSep) {} /// <summary> /// Convert a string to an unsigned integer long /// </summary> /// <param name="from">String value to convert</param> /// <returns>Unsigned long value</returns> protected override object ParseString(string from) { ulong res; if ( !UInt64.TryParse(StringHelper.RemoveBlanks(from), NumberStyles.Number | NumberStyles.AllowExponent, mCulture, out res)) throw new ConvertException(from, mType); return res; } } #region " Int16, Int32, Int64 Converters " #region " Convert Classes " /// <summary> /// Signed byte converter (8 bit signed integer) /// </summary> internal sealed class SByteConverter : CultureConverter { /// <summary> /// Signed byte converter (8 bit signed integer) /// </summary> public SByteConverter() : this(DefaultDecimalSep) {} /// <summary> /// Signed byte converter (8 bit signed integer) /// </summary> /// <param name="decimalSep">dot or comma for separator</param> public SByteConverter(string decimalSep) : base(typeof (SByte), decimalSep) {} /// <summary> /// Convert a string to an signed byte /// </summary> /// <param name="from">String value to convert</param> /// <returns>Signed byte value</returns> protected override object ParseString(string from) { sbyte res; if (!SByte.TryParse(StringHelper.RemoveBlanks(from), NumberStyles.Number, mCulture, out res)) throw new ConvertException(from, mType); return res; } } /// <summary> /// Convert a value to a short integer /// </summary> internal sealed class Int16Converter : CultureConverter { /// <summary> /// Convert a value to a short integer /// </summary> public Int16Converter() : this(DefaultDecimalSep) {} /// <summary> /// Convert a value to a short integer /// </summary> /// <param name="decimalSep">dot or comma for separator</param> public Int16Converter(string decimalSep) : base(typeof (short), decimalSep) {} /// <summary> /// Convert a string to an short integer /// </summary> /// <param name="from">String value to convert</param> /// <returns>Short signed value</returns> protected override object ParseString(string from) { short res; if ( !short.TryParse(StringHelper.RemoveBlanks(from), NumberStyles.Number | NumberStyles.AllowExponent, mCulture, out res)) throw new ConvertException(from, mType); return res; } } /// <summary> /// Convert a value to a integer /// </summary> internal sealed class Int32Converter : CultureConverter { /// <summary> /// Convert a value to a integer /// </summary> public Int32Converter() : this(DefaultDecimalSep) {} /// <summary> /// Convert a value to a integer /// </summary> /// <param name="decimalSep">dot or comma for separator</param> public Int32Converter(string decimalSep) : base(typeof (int), decimalSep) {} /// <summary> /// Convert a string to an integer /// </summary> /// <param name="from">String value to convert</param> /// <returns>integer value</returns> protected override object ParseString(string from) { int res; if ( !int.TryParse(StringHelper.RemoveBlanks(from), NumberStyles.Number | NumberStyles.AllowExponent, mCulture, out res)) throw new ConvertException(from, mType); return res; } } /// <summary> /// Convert a value to a long integer /// </summary> internal sealed class Int64Converter : CultureConverter { /// <summary> /// Convert a value to a long integer /// </summary> public Int64Converter() : this(DefaultDecimalSep) {} /// <summary> /// Convert a value to a long integer /// </summary> /// <param name="decimalSep">dot or comma for separator</param> public Int64Converter(string decimalSep) : base(typeof (long), decimalSep) {} /// <summary> /// Convert a string to an integer long /// </summary> /// <param name="from">String value to convert</param> /// <returns>Long value</returns> protected override object ParseString(string from) { long res; if ( !long.TryParse(StringHelper.RemoveBlanks(from), NumberStyles.Number | NumberStyles.AllowExponent, mCulture, out res)) throw new ConvertException(from, mType); return res; } } #endregion #endregion #region " Single, Double, DecimalConverters " #region " Convert Classes " /// <summary> /// Convert a value to a decimal value /// </summary> internal sealed class DecimalConverter : CultureConverter { /// <summary> /// Convert a value to a decimal value /// </summary> public DecimalConverter() : this(DefaultDecimalSep) {} /// <summary> /// Convert a value to a decimal value /// </summary> /// <param name="decimalSep">dot or comma for separator</param> public DecimalConverter(string decimalSep) : base(typeof (decimal), decimalSep) {} /// <summary> /// Convert a string to a decimal /// </summary> /// <param name="from">String value to convert</param> /// <returns>decimal value</returns> protected override object ParseString(string from) { decimal res; if ( !decimal.TryParse(StringHelper.RemoveBlanks(from), NumberStyles.Number | NumberStyles.AllowExponent, mCulture, out res)) throw new ConvertException(from, mType); return res; } } /// <summary> /// Convert a value to a single floating point /// </summary> internal sealed class SingleConverter : CultureConverter { /// <summary> /// Convert a value to a single floating point /// </summary> public SingleConverter() : this(DefaultDecimalSep) {} /// <summary> /// Convert a value to a single floating point /// </summary> /// <param name="decimalSep">dot or comma for separator</param> public SingleConverter(string decimalSep) : base(typeof (Single), decimalSep) {} /// <summary> /// Convert a string to an single precision floating point /// </summary> /// <param name="from">String value to convert</param> /// <returns>Single floating point value</returns> protected override object ParseString(string from) { float res; if ( !Single.TryParse(StringHelper.RemoveBlanks(from), NumberStyles.Number | NumberStyles.AllowExponent, mCulture, out res)) throw new ConvertException(from, mType); return res; } } /// <summary> /// Convert a value to a single floating point /// </summary> internal sealed class DoubleConverter : CultureConverter { /// <summary> /// Convert a value to a floating point /// </summary> public DoubleConverter() : this(DefaultDecimalSep) {} /// <summary> /// Convert a value to a floating point /// </summary> /// <param name="decimalSep">dot or comma for separator</param> public DoubleConverter(string decimalSep) : base(typeof (Double), decimalSep) {} /// <summary> /// Convert a string to an floating point /// </summary> /// <param name="from">String value to convert</param> /// <returns>Floating point value</returns> protected override object ParseString(string from) { double res; if ( !Double.TryParse(StringHelper.RemoveBlanks(from), NumberStyles.Number | NumberStyles.AllowExponent, mCulture, out res)) throw new ConvertException(from, mType); return res; } } /// <summary> /// This Class is specialized version of the Double Converter /// The main difference being that it can handle % sign at the end of the number /// It gives a value which is basically number / 100. /// </summary> /// <remarks>Edited : Shreyas Narasimhan (17 March 2010) </remarks> internal sealed class PercentDoubleConverter : CultureConverter { /// <summary> /// Convert a value to a floating point from a percentage /// </summary> public PercentDoubleConverter() : this(DefaultDecimalSep) {} /// <summary> /// Convert a value to a floating point from a percentage /// </summary> /// <param name="decimalSep">dot or comma for separator</param> public PercentDoubleConverter(string decimalSep) : base(typeof (Double), decimalSep) {} /// <summary> /// Convert a string to an floating point from percentage /// </summary> /// <param name="from">String value to convert</param> /// <returns>floating point value</returns> protected override object ParseString(string from) { double res; var blanksRemoved = StringHelper.RemoveBlanks(from); if (blanksRemoved.EndsWith("%")) { if ( !Double.TryParse(blanksRemoved, NumberStyles.Number | NumberStyles.AllowExponent, mCulture, out res)) throw new ConvertException(from, mType); return res/100.0; } else { if ( !Double.TryParse(blanksRemoved, NumberStyles.Number | NumberStyles.AllowExponent, mCulture, out res)) throw new ConvertException(from, mType); return res; } } } #endregion #endregion #region " Date Converters " #region " Convert Classes " /// <summary> /// Convert a value to a date time value /// </summary> internal sealed class DateTimeConverter : ConverterBase { private readonly string mFormat; private readonly CultureInfo mCulture; /// <summary> /// Convert a value to a date time value /// </summary> public DateTimeConverter() : this(DefaultDateTimeFormat) {} /// <summary> /// Convert a value to a date time value /// </summary> /// <param name="format">date format see .Net documentation</param> public DateTimeConverter(string format) :this(format, null) { } /// <summary> /// Convert a value to a date time value /// </summary> /// <param name="format">date format see .Net documentation</param> /// <param name="culture">The culture used to parse the Dates</param> public DateTimeConverter(string format, string culture) { if (string.IsNullOrEmpty(format)) throw new BadUsageException("The format of the DateTime Converter cannot be null or empty."); try { DateTime.Now.ToString(format); } catch { throw new BadUsageException("The format: '" + format + " is invalid for the DateTime Converter."); } mFormat = format; if (culture != null) mCulture = CultureInfo.GetCultureInfo(culture); } /// <summary> /// Convert a string to a date time value /// </summary> /// <param name="from">String value to convert</param> /// <returns>DateTime value</returns> public override object StringToField(string from) { if (from == null) from = string.Empty; DateTime val; if (!DateTime.TryParseExact(from.Trim(), mFormat, mCulture, DateTimeStyles.None, out val)) { string extra; if (from.Length > mFormat.Length) extra = " There are more chars in the Input String than in the Format string: '" + mFormat + "'"; else if (from.Length < mFormat.Length) extra = " There are less chars in the Input String than in the Format string: '" + mFormat + "'"; else extra = " Using the format: '" + mFormat + "'"; throw new ConvertException(from, typeof (DateTime), extra); } return val; } /// <summary> /// Convert a date time value to a string /// </summary> /// <param name="from">DateTime value to convert</param> /// <returns>string DateTime value</returns> public override string FieldToString(object from) { if (from == null) return string.Empty; return Convert.ToDateTime(from).ToString(mFormat, mCulture); } } #endregion #region " Convert Classes " /// <summary> /// Convert a value to a date time value /// </summary> internal sealed class DateTimeMultiFormatConverter : ConverterBase { private readonly string[] mFormats; /// <summary> /// Convert a value to a date time value using multiple formats /// </summary> public DateTimeMultiFormatConverter(string format1, string format2) : this(new[] {format1, format2}) {} /// <summary> /// Convert a value to a date time value using multiple formats /// </summary> public DateTimeMultiFormatConverter(string format1, string format2, string format3) : this(new[] {format1, format2, format3}) {} /// <summary> /// Convert a date time value to a string /// </summary> /// <param name="formats">list of formats to try</param> private DateTimeMultiFormatConverter(string[] formats) { for (int i = 0; i < formats.Length; i++) { if (formats[i] == null || formats[i] == String.Empty) throw new BadUsageException("The format of the DateTime Converter can be null or empty."); try { DateTime.Now.ToString(formats[i]); } catch { throw new BadUsageException("The format: '" + formats[i] + " is invalid for the DateTime Converter."); } } mFormats = formats; } /// <summary> /// Convert a date time value to a string /// </summary> /// <param name="from">DateTime value to convert</param> /// <returns>string DateTime value</returns> public override object StringToField(string from) { if (from == null) from = string.Empty; DateTime val; if (!DateTime.TryParseExact(from.Trim(), mFormats, null, DateTimeStyles.None, out val)) { string extra = " does not match any of the given formats: " + CreateFormats(); throw new ConvertException(from, typeof (DateTime), extra); } return val; } /// <summary> /// Create a list of formats to pass to the DateTime tryparse function /// </summary> /// <returns>string DateTime value</returns> private string CreateFormats() { var sb = new StringBuilder(); for (int i = 0; i < mFormats.Length; i++) { if (i == 0) sb.Append("'" + mFormats[i] + "'"); else sb.Append(", '" + mFormats[i] + "'"); } return sb.ToString(); } /// <summary> /// Convert a date time value to a string (uses first format for output /// </summary> /// <param name="from">DateTime value to convert</param> /// <returns>string DateTime value</returns> public override string FieldToString(object from) { if (from == null) return string.Empty; return Convert.ToDateTime(from).ToString(mFormats[0]); } } #endregion #endregion #region " Boolean Converters " #region " Convert Classes " /// <summary> /// Convert an input value to a boolean, allows for true false values /// </summary> internal sealed class BooleanConverter : ConverterBase { private readonly string mTrueString = null; private readonly string mFalseString = null; private readonly string mTrueStringLower = null; private readonly string mFalseStringLower = null; /// <summary> /// Simple boolean converter /// </summary> public BooleanConverter() {} /// <summary> /// Boolean converter with true false values /// </summary> /// <param name="trueStr">True string</param> /// <param name="falseStr">False string</param> public BooleanConverter(string trueStr, string falseStr) { mTrueString = trueStr; mFalseString = falseStr; mTrueStringLower = trueStr.ToLower(); mFalseStringLower = falseStr.ToLower(); } /// <summary> /// convert a string to a boolean value /// </summary> /// <param name="from">string to convert</param> /// <returns>boolean value</returns> public override object StringToField(string from) { object val; string testTo = from.ToLower(); if (mTrueString == null) { testTo = testTo.Trim(); switch (testTo) { case "true": case "1": case "y": case "t": val = true; break; case "false": case "0": case "n": case "f": // I don't think that this case is possible without overriding the CustomNullHandling // and it is possible that defaulting empty fields to be false is not correct case "": val = false; break; default: throw new ConvertException(from, typeof (bool), "The string: " + from + " can't be recognized as boolean using default true/false values."); } } else { // Most of the time the strings should match exactly. To improve performance // we skip the trim if the exact match is true if (testTo == mTrueStringLower) val = true; else if (testTo == mFalseStringLower) val = false; else { testTo = testTo.Trim(); if (testTo == mTrueStringLower) val = true; else if (testTo == mFalseStringLower) val = false; else { throw new ConvertException(from, typeof (bool), "The string: " + from + " can't be recognized as boolean using the true/false values: " + mTrueString + "/" + mFalseString); } } } return val; } /// <summary> /// Convert to a true false string /// </summary> /// <param name="from"></param> /// <returns></returns> public override string FieldToString(object from) { bool b = Convert.ToBoolean(from); if (b) { if (mTrueString == null) return "True"; else return mTrueString; } else if (mFalseString == null) return "False"; else return mFalseString; } } #endregion #endregion #region " GUID, Char, String Converters " #region " Convert Classes " /// <summary> /// Allow characters to be converted to upper and lower case automatically. /// </summary> internal sealed class CharConverter : ConverterBase { /// <summary> /// whether we upper or lower case the character on input /// </summary> private enum CharFormat { /// <summary> /// Don't change the case /// </summary> NoChange = 0, /// <summary> /// Change to lower case /// </summary> Lower, /// <summary> /// change to upper case /// </summary> Upper, } /// <summary> /// default to not upper or lower case /// </summary> private readonly CharFormat mFormat = CharFormat.NoChange; /// <summary> /// Create a single character converter that does not upper or lower case result /// </summary> public CharConverter() : this("") // default, no upper or lower case conversion {} /// <summary> /// Single character converter that optionally makes it upper (X) or lower case (x) /// </summary> /// <param name="format"> empty string for no upper or lower, x for lower case, X for Upper case</param> public CharConverter(string format) { switch (format.Trim()) { case "x": case "lower": mFormat = CharFormat.Lower; break; case "X": case "upper": mFormat = CharFormat.Upper; break; case "": mFormat = CharFormat.NoChange; break; default: throw new BadUsageException( "The format of the Char Converter must be \"\", \"x\" or \"lower\" for lower case, \"X\" or \"upper\" for upper case"); } } /// <summary> /// Extract the first character with optional upper or lower case /// </summary> /// <param name="from">String contents</param> /// <returns>Character (may be upper or lower case)</returns> public override object StringToField(string from) { if (string.IsNullOrEmpty(from)) return Char.MinValue; try { switch (mFormat) { case CharFormat.NoChange: return from[0]; case CharFormat.Lower: return char.ToLower(from[0]); case CharFormat.Upper: return char.ToUpper(from[0]); default: throw new ConvertException(from, typeof (Char), "Unknown char convert flag " + mFormat.ToString()); } } catch { throw new ConvertException(from, typeof (Char), "Upper or lower case of input string failed"); } } /// <summary> /// Convert from a character to a string for output /// </summary> /// <param name="from">Character to convert from</param> /// <returns>String containing the character</returns> public override string FieldToString(object from) { switch (mFormat) { case CharFormat.NoChange: return Convert.ToChar(from).ToString(); case CharFormat.Lower: return char.ToLower(Convert.ToChar(from)).ToString(); case CharFormat.Upper: return char.ToUpper(Convert.ToChar(from)).ToString(); default: throw new ConvertException("", typeof (Char), "Unknown char convert flag " + mFormat.ToString()); } } } /// <summary> /// Convert a GUID to and from a field value /// </summary> internal sealed class GuidConverter : ConverterBase { /// <summary> /// D or N or B or P (default is D: see Guid.ToString(string format)) /// </summary> private readonly string mFormat; /// <summary> /// Create a GUID converter with the default format code "D" /// </summary> public GuidConverter() : this("D") // D or N or B or P (default is D: see Guid.ToString(string format)) {} /// <summary> /// Create a GUID converter with formats as defined for GUID /// N, D, B or P /// </summary> /// <param name="format">Format code for GUID</param> public GuidConverter(string format) { if (String.IsNullOrEmpty(format)) format = "D"; format = format.Trim().ToUpper(); if (!(format == "N" || format == "D" || format == "B" || format == "P")) throw new BadUsageException("The format of the Guid Converter must be N, D, B or P."); mFormat = format; } /// <summary> /// Convert a GUID string to a GUID object for the record object /// </summary> /// <param name="from">String representation of the GUID</param> /// <returns>GUID object or GUID empty</returns> public override object StringToField(string from) { if (String.IsNullOrEmpty(from)) return Guid.Empty; try { return new Guid(from); } catch { throw new ConvertException(from, typeof (Guid)); } } /// <summary> /// Output GUID as a string field /// </summary> /// <param name="from">Guid object</param> /// <returns>GUID as a string depending on format</returns> public override string FieldToString(object from) { if (from == null) return String.Empty; return ((Guid) from).ToString(mFormat); } } //// Added by Alexander Obolonkov 2007.11.08 //internal sealed class StringConverter : ConverterBase //{ // string mFormat; // public StringConverter() // : this(null) // { // } // public StringConverter(string format) // { // //throw new BadUsageException("The format of the String Converter can be null or empty."); // if (String.IsNullOrEmpty(format)) // mFormat = null; // else // { // mFormat = format; // try // { // string tmp = String.Format(format, "Any String"); // } // catch // { // throw new BadUsageException( // String.Format("The format: '{0}' is invalid for the String Converter.", format)); // } // } // } // public override object StringToField(string from) // { // if (from == null) // return string.Empty; // if (from.Length == 0) // return string.Empty; // try // { // if (mFormat == null) // return from; // else // return String.Format(mFormat, from); // //if (m_intMaxLength > 0) // // strRet = strRet.Substring(0, m_intMaxLength); // } // catch // { // throw new ConvertException(from, typeof(String), "TODO Extra Info"); // } // } // public override string FieldToString(object from) // { // if (from == null) // return string.Empty; // else // return String.Format(mFormat, from); // } //} #endregion #endregion } }
namespace PcapDotNet.Packets.IpV4 { /// <summary> /// Indicates the next level IPv4 protocol used in the pyaload of the IPv4 datagram. /// </summary> public enum IpV4Protocol : byte { /// <summary> /// IPv6 Hop-by-Hop Option RFC 2460 /// </summary> IpV6HopByHopOption = 0x00, /// <summary> /// Internet Control Message Protocol RFC 792 /// </summary> InternetControlMessageProtocol = 0x01, /// <summary> /// Internet Group Management Protocol RFC 1112 /// </summary> InternetGroupManagementProtocol = 0x02, /// <summary> /// Gateway-to-Gateway Protocol RFC 823 /// </summary> GatewayToGateway = 0x03, /// <summary> /// IP in IP (encapsulation) RFC 2003 /// </summary> Ip = 0x04, /// <summary> /// Internet Stream Protocol RFC 1190, RFC 1819 /// </summary> Stream = 0x05, /// <summary> /// Transmission Control Protocol RFC 793 /// </summary> Tcp = 0x06, /// <summary> /// CBT /// </summary> Cbt = 0x07, /// <summary> /// Exterior Gateway Protocol RFC 888 /// </summary> ExteriorGatewayProtocol = 0x08, /// <summary> /// Interior Gateway Protocol (any private interior gateway (used by Cisco for their IGRP)) /// </summary> InteriorGatewayProtocol = 0x09, /// <summary> /// BBN RCC Monitoring /// </summary> BbnRccMonitoring = 0x0A, /// <summary> /// Network Voice Protocol RFC 741 /// </summary> NetworkVoice = 0x0B, /// <summary> /// Xerox PUP /// </summary> Pup = 0x0C, /// <summary> /// ARGUS /// </summary> Argus = 0x0D, /// <summary> /// EMCON /// </summary> Emcon = 0x0E, /// <summary> /// Cross Net Debugger IEN 158 /// </summary> CrossNetDebugger = 0x0F, /// <summary> /// Chaos /// </summary> Chaos = 0x10, /// <summary> /// User Datagram Protocol RFC 768 /// </summary> Udp = 0x11, /// <summary> /// Multiplexing IEN 90 /// </summary> Multiplexing = 0x12, /// <summary> /// DCN Measurement Subsystems /// </summary> DcnMeasurement = 0x13, /// <summary> /// Host Monitoring Protocol RFC 869 /// </summary> HostMonitoringProtocol = 0x14, /// <summary> /// Packet Radio Measurement /// </summary> PacketRadioMeasurement = 0x15, /// <summary> /// XEROX NS IDP /// </summary> XeroxNsInternetDatagramProtocol = 0x16, /// <summary> /// Trunk-1 /// </summary> Trunk1 = 0x17, /// <summary> /// Trunk-2 /// </summary> Trunk2 = 0x18, /// <summary> /// Leaf-1 /// </summary> Leaf1 = 0x19, /// <summary> /// Leaf-2 /// </summary> Leaf2 = 0x1A, /// <summary> /// Reliable Datagram Protocol RFC 908 /// </summary> ReliableDatagramProtocol = 0x1B, /// <summary> /// Internet Reliable Transaction Protocol RFC 938 /// </summary> InternetReliableTransactionProtocol = 0x1C, /// <summary> /// ISO Transport Protocol Class 4 RFC 905 /// </summary> IsoTransportProtocolClass4 = 0x1D, /// <summary> /// Bulk Data Transfer Protocol RFC 998 /// </summary> BulkDataTransferProtocol = 0x1E, /// <summary> /// MFE Network Services Protocol /// </summary> MagneticFusionEnergyNetworkServicesProtocol = 0x1F, /// <summary> /// MERIT Internodal Protocol /// </summary> MeritInternodalProtocol = 0x20, /// <summary> /// Datagram Congestion Control Protocol RFC 4340 /// </summary> DatagramCongestionControlProtocol = 0x21, /// <summary> /// Third Party Connect Protocol /// </summary> ThirdPartyConnect = 0x22, /// <summary> /// Inter-Domain Policy Routing Protocol RFC 1479 /// </summary> InterDomainPolicyRoutingProtocol = 0x23, /// <summary> /// Xpress Transport Protocol /// </summary> XpressTransportProtocol = 0x24, /// <summary> /// Datagram Delivery Protocol /// </summary> DatagramDeliveryProtocol = 0x25, /// <summary> /// IDPR Control Message Transport Protocol /// </summary> InterDomainPolicyRoutingProtocolControlMessageTransportProtocol = 0x26, /// <summary> /// TP++ Transport Protocol /// </summary> TransportProtocolPlusPlus = 0x27, /// <summary> /// IL Transport Protocol /// </summary> Il = 0x28, /// <summary> /// IPv6 RFC 2460 /// </summary> IpV6 = 0x29, /// <summary> /// Source Demand Routing Protocol /// </summary> SourceDemandRoutingProtocol = 0x2A, /// <summary> /// Routing Header for IPv6 RFC 2460 /// </summary> IpV6Route = 0x2B, /// <summary> /// Fragment Header for IPv6 RFC 2460 /// </summary> FragmentHeaderForIpV6 = 0x2C, /// <summary> /// Inter-Domain Routing Protocol /// </summary> InterDomainRoutingProtocol = 0x2D, /// <summary> /// Resource Reservation Protocol /// </summary> Rsvp = 0x2E, /// <summary> /// Generic Routing Encapsulation /// </summary> Gre = 0x2F, /// <summary> /// Mobile Host Routing Protocol /// </summary> MobileHostRoutingProtocol = 0x30, /// <summary> /// BNA /// </summary> Bna = 0x31, /// <summary> /// Encapsulating Security Payload RFC 2406 /// </summary> Esp = 0x32, /// <summary> /// Authentication Header RFC 2402 /// </summary> AuthenticationHeader = 0x33, /// <summary> /// Integrated Net Layer Security Protocol TUBA /// </summary> IntegratedNetLayerSecurityProtocol = 0x34, /// <summary> /// IP with Encryption /// </summary> Swipe = 0x35, /// <summary> /// NBMA Address Resolution Protocol RFC 1735 /// </summary> NArp = 0x36, /// <summary> /// IP Mobility (Min Encap) RFC 2004 /// </summary> Mobile = 0x37, /// <summary> /// Transport Layer Security Protocol (using Kryptonet key management) /// </summary> TransportLayerSecurityProtocol = 0x38, /// <summary> /// Simple Key-Management for Internet Protocol RFC 2356 /// </summary> Skip = 0x39, /// <summary> /// ICMP for IPv6 RFC 2460 /// </summary> InternetControlMessageProtocolForIpV6 = 0x3A, /// <summary> /// No Next Header for IPv6 RFC 2460 /// </summary> NoNextHeaderForIpV6 = 0x3B, /// <summary> /// Destination Options for IPv6 RFC 2460 /// </summary> IpV6Opts = 0x3C, /// <summary> /// Any host internal protocol /// </summary> AnyHostInternal = 0x3D, /// <summary> /// CFTP /// </summary> Cftp = 0x3E, /// <summary> /// Any local network /// </summary> AnyLocalNetwork = 0x3F, /// <summary> /// SATNET and Backroom EXPAK /// </summary> SatnetAndBackroomExpak = 0x40, /// <summary> /// Kryptolan /// </summary> Kryptolan = 0x41, /// <summary> /// MIT Remote Virtual Disk Protocol /// </summary> RemoteVirtualDiskProtocol = 0x42, /// <summary> /// Internet Pluribus Packet Core /// </summary> InternetPluribusPacketCore = 0x43, /// <summary> /// Any distributed file system /// </summary> AnyDistributedFileSystem = 0x44, /// <summary> /// SATNET Monitoring /// </summary> SatMon = 0x45, /// <summary> /// VISA Protocol /// </summary> Visa = 0x46, /// <summary> /// Internet Packet Core Utility /// </summary> InternetPacketCoreUtility = 0x47, /// <summary> /// Computer Protocol Network Executive /// </summary> ComputerProtocolNetworkExecutive = 0x48, /// <summary> /// Computer Protocol Heart Beat /// </summary> ComputerProtocolHeartbeat = 0x49, /// <summary> /// Wang Span Network /// </summary> WangSpanNetwork = 0x4A, /// <summary> /// Packet Video Protocol /// </summary> PacketVideoProtocol = 0x4B, /// <summary> /// Backroom SATNET Monitoring /// </summary> BackroomSatMon = 0x4C, /// <summary> /// SUN ND PROTOCOL-Temporary /// </summary> SunNd = 0x4D, /// <summary> /// WIDEBAND Monitoring /// </summary> WidebandMonitoring = 0x4E, /// <summary> /// WIDEBAND EXPAK /// </summary> WidebandExpak = 0x4F, /// <summary> /// International Organization for Standardization Internet Protocol /// </summary> IsoIp = 0x50, /// <summary> /// Versatile Message Transaction Protocol RFC 1045 /// </summary> VersatileMessageTransactionProtocol = 0x51, /// <summary> /// Secure Versatile Message Transaction Protocol RFC 1045 /// </summary> SecureVersatileMessageTransactionProtocol = 0x52, /// <summary> /// VINES /// </summary> Vines = 0x53, /// <summary> /// TTP /// </summary> Ttp = 0x54, /// <summary> /// NSFNET-IGP /// </summary> NationalScienceFoundationNetworkInteriorGatewayProtocol = 0x55, /// <summary> /// Dissimilar Gateway Protocol /// </summary> DissimilarGatewayProtocol = 0x56, /// <summary> /// TCF /// </summary> Tcf = 0x57, /// <summary> /// Enhanced Interior Gateway Routing Protocol /// </summary> EnhancedInteriorGatewayRoutingProtocol = 0x58, /// <summary> /// Open Shortest Path First RFC 1583 /// </summary> OpenShortestPathFirst = 0x59, /// <summary> /// Sprite RPC Protocol /// </summary> SpriteRpc = 0x5A, /// <summary> /// Locus Address Resolution Protocol /// </summary> LArp = 0x5B, /// <summary> /// Multicast Transport Protocol /// </summary> MulticastTransportProtocol = 0x5C, /// <summary> /// AX.25 /// </summary> Ax25 = 0x5D, /// <summary> /// IP-within-IP Encapsulation Protocol /// </summary> IpIp = 0x5E, /// <summary> /// Mobile Internetworking Control Protocol /// </summary> MobileInternetworkingControlProtocol = 0x5F, /// <summary> /// Semaphore Communications Sec. Pro /// </summary> SemaphoreCommunicationsSecondProtocol = 0x60, /// <summary> /// Ethernet-within-IP Encapsulation RFC 3378 /// </summary> EtherIp = 0x61, /// <summary> /// Encapsulation Header RFC 1241 /// </summary> EncapsulationHeader = 0x62, /// <summary> /// Any private encryption scheme /// </summary> AnyPrivateEncryptionScheme = 0x63, /// <summary> /// GMTP /// </summary> Gmtp = 0x64, /// <summary> /// Ipsilon Flow Management Protocol /// </summary> IpsilonFlowManagementProtocol = 0x65, /// <summary> /// PNNI over IP /// </summary> PrivateNetworkToNetworkInterface = 0x66, /// <summary> /// Protocol Independent Multicast /// </summary> Pin = 0x67, /// <summary> /// ARIS /// </summary> Aris = 0x68, /// <summary> /// SCPS (Space Communications Protocol Standards) /// </summary> SpaceCommunicationsProtocolStandards = 0x69, /// <summary> /// QNX /// </summary> Qnx = 0x6A, /// <summary> /// Active Networks /// </summary> ActiveNetworks = 0x6B, /// <summary> /// IP Payload Compression Protocol RFC 3173 /// </summary> IpComp = 0x6C, /// <summary> /// Sitara Networks Protocol /// </summary> SitaraNetworksProtocol = 0x6D, /// <summary> /// Compaq Peer Protocol /// </summary> CompaqPeer = 0x6E, /// <summary> /// IPX in IP /// </summary> InternetworkPacketExchangeInIp = 0x6F, /// <summary> /// Virtual Router Redundancy Protocol, Common Address Redundancy Protocol (not IANA assigned) VRRP:RFC 3768 /// </summary> VirtualRouterRedundancyProtocol = 0x70, /// <summary> /// PGM Reliable Transport Protocol RFC 3208 /// </summary> PragmaticGeneralMulticastTransportProtocol = 0x71, /// <summary> /// Any 0-hop protocol /// </summary> Any0HopProtocol = 0x72, /// <summary> /// Layer Two Tunneling Protocol /// </summary> LayerTwoTunnelingProtocol = 0x73, /// <summary> /// D-II Data Exchange (DDX) /// </summary> DiiDataExchange = 0x74, /// <summary> /// Interactive Agent Transfer Protocol /// </summary> InteractiveAgentTransferProtocol = 0x75, /// <summary> /// Schedule Transfer Protocol /// </summary> ScheduleTransferProtocol = 0x76, /// <summary> /// SpectraLink Radio Protocol /// </summary> SpectraLinkRadioProtocol = 0x77, /// <summary> /// UTI /// </summary> Uti = 0x78, /// <summary> /// Simple Message Protocol /// </summary> SimpleMessageProtocol = 0x79, /// <summary> /// SM /// </summary> Sm = 0x7A, /// <summary> /// Performance Transparency Protocol /// </summary> PerformanceTransparencyProtocol = 0x7B, /// <summary> /// IS-IS over IPv4 /// </summary> IsIsOverIpV4 = 0x7C, /// <summary> /// /// </summary> Fire = 0x7D, /// <summary> /// Combat Radio Transport Protocol /// </summary> CombatRadioTransportProtocol = 0x7E, /// <summary> /// Combat Radio User Datagram /// </summary> CombatRadioUserDatagram = 0x7F, /// <summary> /// /// </summary> ServiceSpecificConnectionOrientedProtocolInAMultilinkAndConnectionlessEnvironment = 0x80, /// <summary> /// /// </summary> Iplt = 0x81, /// <summary> /// Secure Packet Shield /// </summary> SecurePacketShield = 0x82, /// <summary> /// Private IP Encapsulation within IP Expired I-D draft-petri-mobileip-pipe-00.txt /// </summary> Pipe = 0x83, /// <summary> /// Stream Control Transmission Protocol /// </summary> StreamControlTransmissionProtocol = 0x84, /// <summary> /// Fibre Channel /// </summary> FibreChannel = 0x85, /// <summary> /// RSVP-E2E-IGNORE RFC 3175 /// </summary> RsvpE2EIgnore = 0x86, /// <summary> /// Mobility Header RFC 3775 /// </summary> MobilityHeader = 0x87, /// <summary> /// UDP Lite RFC 3828 /// </summary> UdpLite = 0x88, /// <summary> /// MPLS-in-IP RFC 4023 /// </summary> MultiprotocolLabelSwitchingInIp = 0x89, /// <summary> /// MANET Protocols I-D draft-ietf-manet-iana-07.txt /// </summary> MobileAdHocNetwork = 0x8A, /// <summary> /// Host Identity Protocol RFC 5201 /// </summary> Hip = 0x8B } }
// // Copyright 2012, Xamarin Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Net; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using System.Linq; using System.Text; using System.Threading; using Xamarin.Auth; using Xamarin.Utilities; using System.Json; namespace Xamarin.Auth { /// <summary> /// An HTTP web request that provides a convenient way to make authenticated /// requests using account objects obtained from an authenticator. /// </summary> #if XAMARIN_AUTH_INTERNAL internal class Request #else public class Request #endif { HttpWebRequest request; /// <summary> /// The HTTP method. /// </summary> public string Method { get; protected set; } /// <summary> /// The URL of the resource to request. /// </summary> public Uri Url { get; protected set; } /// <summary> /// The parameters of the request. These will be added to the query string of the /// URL for GET requests, encoded as form a parameters for POSTs, and added as /// multipart values if the request uses <see cref="Multiparts"/>. /// </summary> public IDictionary<string, string> Parameters { get; internal set; } /// <summary> /// The account that will be used to authenticate this request. /// </summary> public virtual ISalesforceUser Account { get; set; } /// <summary> /// Initializes a new instance of the <see cref="Xamarin.Auth.Request"/> class. /// </summary> /// <param name='method'> /// The HTTP method. /// </param> /// <param name='url'> /// The URL. /// </param> /// <param name='parameters'> /// Parameters that will pre-populate the <see cref="Parameters"/> property or null. /// </param> /// <param name='account'> /// The account used to authenticate this request. /// </param> public Request (string method, Uri url, IDictionary<string, string> parameters = null, ISalesforceUser account = null) { Method = method; Url = url; Parameters = parameters == null ? new Dictionary<string, string> () : new Dictionary<string, string> (parameters); Account = account; } /// <summary> /// A single part of a multipart request. /// </summary> protected class Part { /// <summary> /// The data. /// </summary> public Stream Data; /// <summary> /// The optional textual representation of the <see cref="Data"/>. /// </summary> public string TextData; /// <summary> /// The name. /// </summary> public string Name; /// <summary> /// The MIME type. /// </summary> public string MimeType; /// <summary> /// The filename of this part if it represents a file. /// </summary> public string Filename; } /// <summary> /// The parts of a multipart request. /// </summary> protected readonly List<Part> Multiparts = new List<Part> (); /// <summary> /// Adds a part to the request. Doing so will make this request be sent as multipart/form-data. /// </summary> /// <param name='name'> /// Name of the part. /// </param> /// <param name='data'> /// Text value of the part. /// </param> public void AddMultipartData (string name, string data) { Multiparts.Add (new Part { TextData = data, Data = new MemoryStream (Encoding.UTF8.GetBytes (data)), Name = name, MimeType = "", Filename = "", }); } /// <summary> /// Adds a part to the request. Doing so will make this request be sent as multipart/form-data. /// </summary> /// <param name='name'> /// Name of the part. /// </param> /// <param name='data'> /// Data used when transmitting this part. /// </param> /// <param name='mimeType'> /// The MIME type of this part. /// </param> /// <param name='filename'> /// The filename of this part if it represents a file. /// </param> public virtual void AddMultipartData (string name, Stream data, string mimeType = "", string filename = "") { Multiparts.Add (new Part { Data = data, Name = name, MimeType = mimeType, Filename = filename, }); } /// <summary> /// Gets the response. /// </summary> /// <returns> /// The response. /// </returns> public virtual Task<Response> GetResponseAsync () { return GetResponseAsync (CancellationToken.None); } /// <summary> /// Gets the response. /// </summary> /// <remarks> /// Service implementors should override this method to modify the PreparedWebRequest /// to authenticate it. /// </remarks> /// <returns> /// The response. /// </returns> public virtual Task<Response> GetResponseAsync (CancellationToken cancellationToken) { var request = GetPreparedWebRequest (); // // Disable 100-Continue: http://blogs.msdn.com/b/shitals/archive/2008/12/27/9254245.aspx // if (Method == "POST") { ServicePointManager.Expect100Continue = false; } if (Multiparts.Count > 0) { var boundary = "---------------------------" + new Random ().Next (); request.ContentType = "multipart/form-data; boundary=" + boundary; return Task.Factory .FromAsync<Stream> (request.BeginGetRequestStream, request.EndGetRequestStream, null) .ContinueWith (reqStreamtask => { using (reqStreamtask.Result) { WriteMultipartFormData (boundary, reqStreamtask.Result); } return Task.Factory .FromAsync<WebResponse> (request.BeginGetResponse, request.EndGetResponse, null) .ContinueWith (resTask => { return new Response ((HttpWebResponse)resTask.Result); }, cancellationToken); }, cancellationToken).Unwrap(); } else if ((Method == "POST" || Method == "PATCH") && Parameters.Count > 0) { var body = new JsonObject (Parameters.Select(k => new KeyValuePair<string,JsonValue>(k.Key, new JsonPrimitive(k.Value))).ToArray()).ToString(); var bodyData = System.Text.Encoding.UTF8.GetBytes (body); request.ContentLength = bodyData.Length; request.ContentType = "application/json"; return Task.Factory .FromAsync<Stream> (request.BeginGetRequestStream, request.EndGetRequestStream, null) .ContinueWith (reqStreamTask => { using (reqStreamTask.Result) { reqStreamTask.Result.Write (bodyData, 0, bodyData.Length); } return Task.Factory .FromAsync<WebResponse> (request.BeginGetResponse, request.EndGetResponse, null) .ContinueWith (resTask => { return new Response ((HttpWebResponse)resTask.Result); }, cancellationToken); }, cancellationToken).Unwrap(); } else { return Task.Factory .FromAsync<WebResponse> (request.BeginGetResponse, request.EndGetResponse, null) .ContinueWith (resTask => { return new Response ((HttpWebResponse)resTask.Result); }, cancellationToken); } } void WriteMultipartFormData (string boundary, Stream s) { var boundaryBytes = Encoding.ASCII.GetBytes ("--" + boundary); foreach (var p in Multiparts) { s.Write (boundaryBytes, 0, boundaryBytes.Length); s.Write (CrLf, 0, CrLf.Length); // // Content-Disposition // var header = "Content-Disposition: form-data; name=\"" + p.Name + "\""; if (!string.IsNullOrEmpty (p.Filename)) { header += "; filename=\"" + p.Filename + "\""; } var headerBytes = Encoding.ASCII.GetBytes (header); s.Write (headerBytes, 0, headerBytes.Length); s.Write (CrLf, 0, CrLf.Length); // // Content-Type // if (!string.IsNullOrEmpty (p.MimeType)) { header = "Content-Type: " + p.MimeType; headerBytes = Encoding.ASCII.GetBytes (header); s.Write (headerBytes, 0, headerBytes.Length); s.Write (CrLf, 0, CrLf.Length); } // // End Header // s.Write (CrLf, 0, CrLf.Length); // // Data // p.Data.CopyTo (s); s.Write (CrLf, 0, CrLf.Length); } // // End // s.Write (boundaryBytes, 0, boundaryBytes.Length); s.Write (DashDash, 0, DashDash.Length); s.Write (CrLf, 0, CrLf.Length); } static readonly byte[] CrLf = new byte[] { (byte)'\r', (byte)'\n' }; static readonly byte[] DashDash = new byte[] { (byte)'-', (byte)'-' }; /// <summary> /// Gets the prepared URL. /// </summary> /// <remarks> /// Service implementors should override this function and add any needed parameters /// from the Account to the URL before it is used to get the response. /// </remarks> /// <returns> /// The prepared URL. /// </returns> protected virtual Uri GetPreparedUrl () { var url = Url.AbsoluteUri; if (Parameters.Count > 0 && Method != "POST") { var head = Url.AbsoluteUri.Contains ('?') ? "&" : "?"; foreach (var p in Parameters) { url += head; url += Uri.EscapeDataString (p.Key); url += "="; url += p.Value == null ? String.Empty : Uri.EscapeDataString (p.Value); head = "&"; } } return new Uri (url); } /// <summary> /// Returns the <see cref="T:System.Net.HttpWebRequest"/> that will be used for this <see cref="T:Xamarin.Auth.Request"/>. All properties /// should be set to their correct values before accessing this object. /// </summary> /// <remarks> /// Service implementors should modify the returned request to add whatever /// authentication data is needed before getting the response. /// </remarks> /// <returns> /// The prepared HTTP web request. /// </returns> protected virtual HttpWebRequest GetPreparedWebRequest () { if (request == null) { request = (HttpWebRequest)WebRequest.Create (GetPreparedUrl ()); request.Method = Method; request.Headers.Set(HttpRequestHeader.Authorization, "Bearer " + Account.Properties["access_token"]); } if (request.CookieContainer == null && Account != null) { request.CookieContainer = Account.Cookies; } return request; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using System.Threading.Tasks; using BudgetAnalyser.Engine.Budget; using JetBrains.Annotations; namespace BudgetAnalyser.Engine.Statement { /// <summary> /// A collection of bank statement transactions that have been imported. /// </summary> /// <seealso cref="INotifyPropertyChanged" /> /// <seealso cref="IDataChangeDetection" /> /// <seealso cref="IDisposable" /> [SuppressMessage("Microsoft.Design", "CA1063:ImplementIDisposableCorrectly", Justification = "There are no native resources to clean up. Unnecessary complexity.")] public class StatementModel : INotifyPropertyChanged, IDataChangeDetection, IDisposable { private readonly ILogger logger; /// <summary> /// A hash to show when critical state of the statement model has changed. Includes child objects ie Transactions. /// The hash does not persist between Application Loads. /// </summary> private Guid changeHash; private GlobalFilterCriteria currentFilter; // Track whether Dispose has been called. private bool disposed; private List<Transaction> doNotUseAllTransactions; private int doNotUseDurationInMonths; private IEnumerable<Transaction> doNotUseTransactions; private IEnumerable<IGrouping<int, Transaction>> duplicates; private int fullDuration; internal StatementModel() { throw new NotSupportedException("This constructor is only used for producing mappers by reflection."); } /// <summary> /// Initializes a new instance of the <see cref="StatementModel" /> class. /// </summary> /// <param name="logger">The logger.</param> /// <exception cref="System.ArgumentNullException"></exception> [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "Reviewed, ok here. Required for binding")] public StatementModel([NotNull] ILogger logger) { if (logger == null) { throw new ArgumentNullException(nameof(logger)); } this.logger = logger; this.changeHash = Guid.NewGuid(); AllTransactions = new List<Transaction>(); Transactions = new List<Transaction>(); } /// <summary> /// Occurs when a property value changes. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Gets all transactions ignoring any filters. /// </summary> public IEnumerable<Transaction> AllTransactions { get { return this.doNotUseAllTransactions; } private set { this.doNotUseAllTransactions = value.ToList(); OnPropertyChanged(); } } /// <summary> /// Gets the duration in months of the current <see cref="Transactions" /> collection. /// </summary> public int DurationInMonths { get { return this.doNotUseDurationInMonths; } private set { this.doNotUseDurationInMonths = value; OnPropertyChanged(); } } /// <summary> /// Gets a value indicating whether this <see cref="StatementModel" /> has an active filtered. /// </summary> public bool Filtered { get; private set; } /// <summary> /// Gets the last imported date and time. /// </summary> public DateTime LastImport { get; internal set; } /// <summary> /// Gets or sets the storage key. This could be the filename for the statement's persistence, or a database unique id. /// </summary> public string StorageKey { get; set; } /// <summary> /// Gets the filtered transactions. /// </summary> public IEnumerable<Transaction> Transactions { get { return this.doNotUseTransactions; } private set { this.doNotUseTransactions = value; this.changeHash = Guid.NewGuid(); OnPropertyChanged(); } } /// <summary> /// Calcuates a hash that represents a data state for the current instance. When the data state changes the hash will /// change. /// </summary> public long SignificantDataChangeHash() { ThrowIfDisposed(); return BitConverter.ToInt64(this.changeHash.ToByteArray(), 8); } /// <summary> /// Implement IDisposable. /// Do not make this method virtual. /// A derived class should not be able to override this method /// </summary> public void Dispose() { Dispose(true); // Take this instance off the Finalization queue // to prevent finalization code for this object // from executing a second time. GC.SuppressFinalize(this); } /// <summary> /// Calculates the duration in months from the beginning of the period to the end. /// </summary> /// <param name="criteria"> /// The criteria that is currently applied to the Statement. Pass in null to use first and last /// statement dates. /// </param> /// <param name="transactions">The list of transactions to use to determine duration.</param> public static int CalculateDuration(GlobalFilterCriteria criteria, IEnumerable<Transaction> transactions) { List<Transaction> list = transactions.ToList(); DateTime minDate = DateTime.MaxValue, maxDate = DateTime.MinValue; if (criteria != null && !criteria.Cleared) { if (criteria.BeginDate != null) { minDate = criteria.BeginDate.Value; Debug.Assert(criteria.EndDate != null); maxDate = criteria.EndDate.Value; } } else { minDate = list.Min(t => t.Date); maxDate = list.Max(t => t.Date); } return minDate.DurationInMonths(maxDate); } /// <summary> /// Allows derivatives to customise dispose logic. /// </summary> protected virtual void Dispose(bool disposing) { // Check to see if Dispose has already been called. if (!this.disposed) { UnsubscribeToTransactionChangedEvents(); } this.disposed = true; } /// <summary> /// Called when a property is changed. /// </summary> /// <param name="propertyName">Name of the property.</param> [NotifyPropertyChangedInvocator] protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { ThrowIfDisposed(); var handler = PropertyChanged; handler?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } internal virtual void Filter(GlobalFilterCriteria criteria) { ThrowIfDisposed(); if (criteria == null) { this.changeHash = Guid.NewGuid(); Transactions = AllTransactions.ToList(); DurationInMonths = this.fullDuration; Filtered = false; return; } if (criteria.BeginDate > criteria.EndDate) { throw new ArgumentException("End date must be after the begin date."); } this.currentFilter = criteria; this.changeHash = Guid.NewGuid(); if (criteria.Cleared) { Transactions = AllTransactions.ToList(); DurationInMonths = this.fullDuration; Filtered = false; return; } IEnumerable<Transaction> query = BaseFilterQuery(criteria); Transactions = query.ToList(); DurationInMonths = CalculateDuration(criteria, Transactions); this.duplicates = null; Filtered = true; } /// <summary> /// Used internally by the importers to load transactions into the statement model. /// </summary> /// <param name="transactions">The transactions to load.</param> /// <returns>Returns this instance, to allow chaining.</returns> internal virtual StatementModel LoadTransactions(IEnumerable<Transaction> transactions) { ThrowIfDisposed(); UnsubscribeToTransactionChangedEvents(); this.changeHash = Guid.NewGuid(); List<Transaction> listOfTransactions; if (transactions == null) { listOfTransactions = new List<Transaction>(); } else { listOfTransactions = transactions.OrderBy(t => t.Date).ToList(); } Transactions = listOfTransactions; AllTransactions = Transactions; if (listOfTransactions.Any()) { UpdateDuration(); } this.duplicates = null; OnPropertyChanged(nameof(Transactions)); SubscribeToTransactionChangedEvents(); return this; } /// <summary> /// Merges the provided model with this one and returns a new combined model. This model or the supplied one are not /// changed. /// </summary> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Ok here. This methods creates the instance for use elsewhere.")] internal virtual StatementModel Merge([NotNull] StatementModel additionalModel) { ThrowIfDisposed(); if (additionalModel == null) { throw new ArgumentNullException(nameof(additionalModel)); } var combinedModel = new StatementModel(this.logger) { LastImport = additionalModel.LastImport, StorageKey = StorageKey }; List<Transaction> mergedTransactions = AllTransactions.ToList().Merge(additionalModel.AllTransactions).ToList(); combinedModel.LoadTransactions(mergedTransactions); return combinedModel; } internal void ReassignFixedProjectTransactions([NotNull] FixedBudgetProjectBucket bucket, [NotNull] BudgetBucket reassignmentBucket) { ThrowIfDisposed(); if (bucket == null) { throw new ArgumentNullException(nameof(bucket)); } if (reassignmentBucket == null) { throw new ArgumentNullException(nameof(reassignmentBucket)); } foreach (var transaction in AllTransactions.Where(t => t.BudgetBucket == bucket)) { transaction.BudgetBucket = reassignmentBucket; } } internal virtual void RemoveTransaction([NotNull] Transaction transaction) { ThrowIfDisposed(); if (transaction == null) { throw new ArgumentNullException(nameof(transaction)); } transaction.PropertyChanged -= OnTransactionPropertyChanged; this.changeHash = Guid.NewGuid(); this.doNotUseAllTransactions.Remove(transaction); Filter(this.currentFilter); } internal virtual void SplitTransaction( [NotNull] Transaction originalTransaction, decimal splinterAmount1, decimal splinterAmount2, [NotNull] BudgetBucket splinterBucket1, [NotNull] BudgetBucket splinterBucket2) { ThrowIfDisposed(); if (originalTransaction == null) { throw new ArgumentNullException(nameof(originalTransaction)); } if (splinterBucket1 == null) { throw new ArgumentNullException(nameof(splinterBucket1)); } if (splinterBucket2 == null) { throw new ArgumentNullException(nameof(splinterBucket2)); } var splinterTransaction1 = originalTransaction.Clone(); var splinterTransaction2 = originalTransaction.Clone(); splinterTransaction1.Amount = splinterAmount1; splinterTransaction2.Amount = splinterAmount2; splinterTransaction1.BudgetBucket = splinterBucket1; splinterTransaction2.BudgetBucket = splinterBucket2; if (splinterAmount1 + splinterAmount2 != originalTransaction.Amount) { throw new ArgumentException("The two new amounts do not add up to the original transaction value."); } RemoveTransaction(originalTransaction); this.changeHash = Guid.NewGuid(); if (AllTransactions == null) { AllTransactions = new List<Transaction>(); } List<Transaction> mergedTransactions = AllTransactions.ToList().Merge(new[] { splinterTransaction1, splinterTransaction2 }).ToList(); AllTransactions = mergedTransactions; splinterTransaction1.PropertyChanged += OnTransactionPropertyChanged; splinterTransaction2.PropertyChanged += OnTransactionPropertyChanged; this.duplicates = null; UpdateDuration(); Filter(this.currentFilter); } internal IEnumerable<IGrouping<int, Transaction>> ValidateAgainstDuplicates() { ThrowIfDisposed(); if (this.duplicates != null) { return this.duplicates; // Reset by Merging Transations, Load Transactions, or by reloading the statement model. } List<IGrouping<int, Transaction>> query = Transactions.GroupBy(t => t.GetEqualityHashCode(), t => t) .Where(group => group.Count() > 1) .AsParallel() .ToList(); this.logger.LogWarning(l => l.Format("{0} Duplicates detected.", query.Sum(group => group.Count()))); query.ForEach( duplicate => { foreach (var txn in duplicate) { txn.IsSuspectedDuplicate = true; } }); this.duplicates = query; return this.duplicates; } private IEnumerable<Transaction> BaseFilterQuery(GlobalFilterCriteria criteria) { if (criteria.Cleared) { return AllTransactions.ToList(); } IEnumerable<Transaction> query = AllTransactions; if (criteria.BeginDate != null) { query = AllTransactions.Where(t => t.Date >= criteria.BeginDate.Value); } if (criteria.EndDate != null) { query = query.Where(t => t.Date <= criteria.EndDate.Value); } return query; } private void OnTransactionPropertyChanged(object sender, PropertyChangedEventArgs propertyChangedEventArgs) { switch (propertyChangedEventArgs.PropertyName) { case nameof(Transaction.Amount): case nameof(Transaction.BudgetBucket): case nameof(Transaction.Date): this.changeHash = Guid.NewGuid(); break; } } private void SubscribeToTransactionChangedEvents() { if (AllTransactions == null) { return; } Parallel.ForEach(AllTransactions, transaction => { transaction.PropertyChanged += OnTransactionPropertyChanged; }); } private void ThrowIfDisposed() { if (this.disposed) { throw new ObjectDisposedException(nameof(StatementModel)); } } private void UnsubscribeToTransactionChangedEvents() { if (AllTransactions == null || AllTransactions.None()) { return; } Parallel.ForEach(AllTransactions, transaction => { transaction.PropertyChanged -= OnTransactionPropertyChanged; }); } private void UpdateDuration() { this.fullDuration = CalculateDuration(new GlobalFilterCriteria(), AllTransactions); DurationInMonths = CalculateDuration(null, Transactions); } /// <summary> /// Finalizes an instance of the <see cref="StatementModel" /> class. /// This destructor will run only if the Dispose method does not get called. /// Do not provide destructors in types derived from this class. /// </summary> ~StatementModel() { // Do not re-create Dispose clean-up code here. Dispose(false); } } }
using System; using System.Runtime.InteropServices; namespace VulkanCore.Nvx { /// <summary> /// Provides NVIDIA specific extension methods for the <see cref="CommandBuffer"/> class. /// </summary> public static unsafe class CommandBufferExtensions { /// <summary> /// Performs the generation of commands on the device. /// </summary> /// <param name="commandBuffer"> /// The primary command buffer in which the generation process takes space. /// </param> /// <param name="processCommandsInfo"> /// The structure containing parameters affecting the processing of commands. /// </param> public static void CmdProcessCommandsNvx(this CommandBuffer commandBuffer, CmdProcessCommandsInfoNvx processCommandsInfo) { fixed (IndirectCommandsTokenNvx* tokensPtr = processCommandsInfo.IndirectCommandsTokens) { processCommandsInfo.ToNative(out CmdProcessCommandsInfoNvx.Native nativeProcessCommandsInfo, tokensPtr); vkCmdProcessCommandsNVX(commandBuffer)(commandBuffer, &nativeProcessCommandsInfo); } } /// <summary> /// Perform a reservation of command buffer space. /// <para> /// The <paramref name="commandBuffer"/> must not have had a prior space reservation since /// its creation or the last reset. /// </para> /// <para> /// The state of the <paramref name="commandBuffer"/> must be legal to execute all commands /// within the sequence provided by the <see /// cref="CmdProcessCommandsInfoNvx.IndirectCommandsLayout"/> member. /// </para> /// </summary> /// <param name="commandBuffer"> /// The secondary command buffer in which the space for device-generated commands is reserved. /// </param> /// <param name="reserveSpaceInfo"> /// The structure containing parameters affecting the reservation of command buffer space. /// </param> public static void CmdReserveSpaceForCommandsNvx(this CommandBuffer commandBuffer, CmdReserveSpaceForCommandsInfoNvx reserveSpaceInfo) { reserveSpaceInfo.Prepare(); vkCmdReserveSpaceForCommandsNVX(commandBuffer)(commandBuffer, &reserveSpaceInfo); } private delegate void vkCmdProcessCommandsNVXDelegate(IntPtr commandBuffer, CmdProcessCommandsInfoNvx.Native* processCommandsInfo); private static vkCmdProcessCommandsNVXDelegate vkCmdProcessCommandsNVX(CommandBuffer commandBuffer) => GetProc<vkCmdProcessCommandsNVXDelegate>(commandBuffer, nameof(vkCmdProcessCommandsNVX)); private delegate void vkCmdReserveSpaceForCommandsNVXDelegate(IntPtr commandBuffer, CmdReserveSpaceForCommandsInfoNvx* reserveSpaceInfo); private static vkCmdReserveSpaceForCommandsNVXDelegate vkCmdReserveSpaceForCommandsNVX(CommandBuffer commandBuffer) => GetProc<vkCmdReserveSpaceForCommandsNVXDelegate>(commandBuffer, nameof(vkCmdReserveSpaceForCommandsNVX)); private static TDelegate GetProc<TDelegate>(CommandBuffer commandBuffer, string name) where TDelegate : class => commandBuffer.Parent.Parent.GetProc<TDelegate>(name); } /// <summary> /// Structure specifying parameters for the generation of commands. /// </summary> public unsafe struct CmdProcessCommandsInfoNvx { /// <summary> /// The <see cref="ObjectTableNvx"/> to be used for the generation process. Only registered /// objects at the time <see cref="CommandBufferExtensions.CmdReserveSpaceForCommandsNvx"/> /// is called, will be taken into account for the reservation. /// </summary> public long ObjectTable; /// <summary> /// The <see cref="IndirectCommandsLayoutNvx"/> that provides the command sequence to generate. /// </summary> public long IndirectCommandsLayout; /// <summary> /// Provides an array of <see cref="IndirectCommandsTokenNvx"/> that reference the input data /// for each token command. /// </summary> public IndirectCommandsTokenNvx[] IndirectCommandsTokens; /// <summary> /// The maximum number of sequences for which command buffer space will be reserved. If <see /// cref="SequencesCountBuffer"/> is 0, this is also the actual number of sequences generated. /// </summary> public int MaxSequencesCount; /// <summary> /// Can be the secondary <see cref="CommandBuffer"/> in which the commands should be /// recorded. If <see cref="TargetCommandBuffer"/> is <see cref="IntPtr.Zero"/> an implicit /// reservation as well as execution takes place on the processing <see cref="CommandBuffer"/>. /// </summary> public IntPtr TargetCommandBuffer; /// <summary> /// Can be <see cref="Buffer"/> from which the actual amount of sequences is sourced from as /// <see cref="int"/> value. /// </summary> public long SequencesCountBuffer; /// <summary> /// The byte offset into <see cref="SequencesCountBuffer"/> where the count value is stored. /// </summary> public long SequencesCountOffset; /// <summary> /// Must be set if <see cref="IndirectCommandsLayout"/>'s <see /// cref="IndirectCommandsLayoutUsagesNvx.IndexedSequences"/> bit is set and provides the /// used sequence indices as <see cref="int"/> array. Otherwise it must be 0. /// </summary> public long SequencesIndexBuffer; /// <summary> /// The byte offset into <see cref="SequencesIndexBuffer"/> where the index values start. /// </summary> public long SequencesIndexOffset; /// <summary> /// Initializes a new instance of the <see cref="CmdProcessCommandsInfoNvx"/> structure. /// </summary> /// <param name="objectTable"> /// The <see cref="ObjectTableNvx"/> to be used for the generation process. Only registered /// objects at the time <see cref="CommandBufferExtensions.CmdReserveSpaceForCommandsNvx"/> /// is called, will be taken into account for the reservation. /// </param> /// <param name="indirectCommandsLayout"> /// The <see cref="IndirectCommandsLayoutNvx"/> that provides the command sequence to generate. /// </param> /// <param name="indirectCommandsTokens"> /// Provides an array of <see cref="IndirectCommandsTokenNvx"/> that reference the input data /// for each token command. /// </param> /// <param name="maxSequencesCount"> /// The maximum number of sequences for which command buffer space will be reserved. If <see /// cref="SequencesCountBuffer"/> is 0, this is also the actual number of sequences generated. /// </param> /// <param name="targetCommandBuffer"> /// Can be the secondary <see cref="CommandBuffer"/> in which the commands should be /// recorded. If <c>null</c> an implicit reservation as well as execution takes place on the /// processing <see cref="CommandBuffer"/>. /// </param> /// <param name="sequencesCountBuffer"> /// Can be <see cref="Buffer"/> from which the actual amount of sequences is sourced from as /// <see cref="int"/> value. /// </param> /// <param name="sequencesCountOffset"> /// The byte offset into <see cref="SequencesCountBuffer"/> where the count value is stored. /// </param> /// <param name="sequencesIndexBuffer"> /// Must be set if <see cref="IndirectCommandsLayout"/>'s <see /// cref="IndirectCommandsLayoutUsagesNvx.IndexedSequences"/> bit is set and provides the /// used sequence indices as <see cref="int"/> array. Otherwise it must be 0. /// </param> /// <param name="sequencesIndexOffset"> /// The byte offset into <see cref="SequencesIndexBuffer"/> where the index values start. /// </param> public CmdProcessCommandsInfoNvx(ObjectTableNvx objectTable, IndirectCommandsLayoutNvx indirectCommandsLayout, IndirectCommandsTokenNvx[] indirectCommandsTokens, int maxSequencesCount = 0, CommandBuffer targetCommandBuffer = null, Buffer sequencesCountBuffer = null, long sequencesCountOffset = 0, Buffer sequencesIndexBuffer = null, long sequencesIndexOffset = 0) { ObjectTable = objectTable; IndirectCommandsLayout = indirectCommandsLayout; IndirectCommandsTokens = indirectCommandsTokens; MaxSequencesCount = maxSequencesCount; TargetCommandBuffer = targetCommandBuffer; SequencesCountBuffer = sequencesCountBuffer; SequencesCountOffset = sequencesCountOffset; SequencesIndexBuffer = sequencesIndexBuffer; SequencesIndexOffset = sequencesIndexOffset; } [StructLayout(LayoutKind.Sequential)] internal struct Native { public StructureType Type; public IntPtr Next; public long ObjectTable; public long IndirectCommandsLayout; public int IndirectCommandsTokenCount; public IndirectCommandsTokenNvx* IndirectCommandsTokens; public int MaxSequencesCount; public IntPtr TargetCommandBuffer; public long SequencesCountBuffer; public long SequencesCountOffset; public long SequencesIndexBuffer; public long SequencesIndexOffset; } internal void ToNative(out Native native, IndirectCommandsTokenNvx* indirectCommandsTokens) { native.Type = StructureType.CmdProcessCommandsInfoNvx; native.Next = IntPtr.Zero; native.ObjectTable = ObjectTable; native.IndirectCommandsLayout = IndirectCommandsLayout; native.IndirectCommandsTokenCount = IndirectCommandsTokens?.Length ?? 0; native.IndirectCommandsTokens = indirectCommandsTokens; native.MaxSequencesCount = MaxSequencesCount; native.TargetCommandBuffer = TargetCommandBuffer; native.SequencesCountBuffer = SequencesCountBuffer; native.SequencesCountOffset = SequencesCountOffset; native.SequencesIndexBuffer = SequencesIndexBuffer; native.SequencesIndexOffset = SequencesIndexOffset; } } /// <summary> /// Structure specifying parameters for the reservation of command buffer space. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct IndirectCommandsTokenNvx { /// <summary> /// Specifies the token command type. /// </summary> public IndirectCommandsTokenTypeNvx TokenType; /// <summary> /// Specifies the <see cref="VulkanCore.Buffer"/> storing the functional arguments for each /// squence. These argumetns can be written by the device. /// </summary> public long Buffer; /// <summary> /// Specified an offset into <see cref="Buffer"/> where the arguments start. /// </summary> public long Offset; /// <summary> /// Initializes a new instance of the <see cref="IndirectCommandsTokenNvx"/> structure. /// </summary> /// <param name="tokenType">Specifies the token command type.</param> /// <param name="buffer"> /// Specifies the <see cref="VulkanCore.Buffer"/> storing the functional arguments for each /// squence. These argumetns can be written by the device. /// </param> /// <param name="offset"> /// Specified an offset into <see cref="Buffer"/> where the arguments start. /// </param> public IndirectCommandsTokenNvx(IndirectCommandsTokenTypeNvx tokenType, Buffer buffer, long offset = 0) { TokenType = tokenType; Buffer = buffer; Offset = offset; } } /// <summary> /// Structure specifying parameters for the reservation of command buffer space. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct CmdReserveSpaceForCommandsInfoNvx { internal StructureType Type; internal IntPtr Next; /// <summary> /// The <see cref="ObjectTableNvx"/> to be used for the generation process. Only registered /// objects at the time <see cref="CommandBufferExtensions.CmdReserveSpaceForCommandsNvx"/> /// is called, will be taken into account for the reservation. /// </summary> public long ObjectTable; /// <summary> /// The <see cref="IndirectCommandsLayoutNvx"/> that must also be used at generation time. /// </summary> public long IndirectCommandsLayout; /// <summary> /// The maximum number of sequences for which command buffer space will be reserved. /// </summary> public int MaxSequencesCount; /// <summary> /// Initializes a new instance of the <see cref="CmdReserveSpaceForCommandsInfoNvx"/> structure. /// </summary> /// <param name="objectTable"> /// The <see cref="ObjectTableNvx"/> to be used for the generation process. Only registered /// objects at the time <see cref="CommandBufferExtensions.CmdReserveSpaceForCommandsNvx"/> /// is called, will be taken into account for the reservation. /// </param> /// <param name="indirectCommandsLayout"> /// The <see cref="IndirectCommandsLayoutNvx"/> that must also be used at generation time. /// </param> /// <param name="maxSequencesCount"> /// The maximum number of sequences for which command buffer space will be reserved. /// </param> public CmdReserveSpaceForCommandsInfoNvx(ObjectTableNvx objectTable, IndirectCommandsLayoutNvx indirectCommandsLayout, int maxSequencesCount) { Type = StructureType.CmdReserveSpaceForCommandsInfoNvx; Next = IntPtr.Zero; ObjectTable = objectTable; IndirectCommandsLayout = indirectCommandsLayout; MaxSequencesCount = maxSequencesCount; } internal void Prepare() { Type = StructureType.CmdReserveSpaceForCommandsInfoNvx; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.CompilerServices; namespace System.Numerics { // This file contains the definitions for all of the JIT intrinsic methods and properties that are recognized by the current x64 JIT compiler. // The implementation defined here is used in any circumstance where the JIT fails to recognize these members as intrinsic. // The JIT recognizes these methods and properties by name and signature: if either is changed, the JIT will no longer recognize the member. // Some methods declared here are not strictly intrinsic, but delegate to an intrinsic method. For example, only one overload of CopyTo() public partial struct Vector2 { /// <summary> /// The X component of the vector. /// </summary> public float X; /// <summary> /// The Y component of the vector. /// </summary> public float Y; #region Constructors /// <summary> /// Constructs a vector whose elements are all the single specified value. /// </summary> /// <param name="value">The element to fill the vector with.</param> [Intrinsic] public Vector2(float value) : this(value, value) { } /// <summary> /// Constructs a vector with the given individual elements. /// </summary> /// <param name="x">The X component.</param> /// <param name="y">The Y component.</param> [Intrinsic] public Vector2(float x, float y) { X = x; Y = y; } #endregion Constructors #region Public Instance Methods /// <summary> /// Copies the contents of the vector into the given array. /// </summary> /// <param name="array">The destination array.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void CopyTo(float[] array) { CopyTo(array, 0); } /// <summary> /// Copies the contents of the vector into the given array, starting from the given index. /// </summary> /// <exception cref="ArgumentNullException">If array is null.</exception> /// <exception cref="RankException">If array is multidimensional.</exception> /// <exception cref="ArgumentOutOfRangeException">If index is greater than end of the array or index is less than zero.</exception> /// <exception cref="ArgumentException">If number of elements in source vector is greater than those available in destination array /// or if there are not enough elements to copy.</exception> public void CopyTo(float[] array, int index) { if (array == null) { // Match the JIT's exception type here. For perf, a NullReference is thrown instead of an ArgumentNull. throw new NullReferenceException(SR.Arg_NullArgumentNullRef); } if (index < 0 || index >= array.Length) { throw new ArgumentOutOfRangeException(nameof(index), SR.Format(SR.Arg_ArgumentOutOfRangeException, index)); } if ((array.Length - index) < 2) { throw new ArgumentException(SR.Format(SR.Arg_ElementsInSourceIsGreaterThanDestination, index)); } array[index] = X; array[index + 1] = Y; } /// <summary> /// Returns a boolean indicating whether the given Vector2 is equal to this Vector2 instance. /// </summary> /// <param name="other">The Vector2 to compare this instance to.</param> /// <returns>True if the other Vector2 is equal to this instance; False otherwise.</returns> [Intrinsic] public bool Equals(Vector2 other) { return this.X == other.X && this.Y == other.Y; } #endregion Public Instance Methods #region Public Static Methods /// <summary> /// Returns the dot product of two vectors. /// </summary> /// <param name="value1">The first vector.</param> /// <param name="value2">The second vector.</param> /// <returns>The dot product.</returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Dot(Vector2 value1, Vector2 value2) { return value1.X * value2.X + value1.Y * value2.Y; } /// <summary> /// Returns a vector whose elements are the minimum of each of the pairs of elements in the two source vectors. /// </summary> /// <param name="value1">The first source vector.</param> /// <param name="value2">The second source vector.</param> /// <returns>The minimized vector.</returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Min(Vector2 value1, Vector2 value2) { return new Vector2( (value1.X < value2.X) ? value1.X : value2.X, (value1.Y < value2.Y) ? value1.Y : value2.Y); } /// <summary> /// Returns a vector whose elements are the maximum of each of the pairs of elements in the two source vectors /// </summary> /// <param name="value1">The first source vector</param> /// <param name="value2">The second source vector</param> /// <returns>The maximized vector</returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Max(Vector2 value1, Vector2 value2) { return new Vector2( (value1.X > value2.X) ? value1.X : value2.X, (value1.Y > value2.Y) ? value1.Y : value2.Y); } /// <summary> /// Returns a vector whose elements are the absolute values of each of the source vector's elements. /// </summary> /// <param name="value">The source vector.</param> /// <returns>The absolute value vector.</returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Abs(Vector2 value) { return new Vector2(MathF.Abs(value.X), MathF.Abs(value.Y)); } /// <summary> /// Returns a vector whose elements are the square root of each of the source vector's elements. /// </summary> /// <param name="value">The source vector.</param> /// <returns>The square root vector.</returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 SquareRoot(Vector2 value) { return new Vector2(MathF.Sqrt(value.X), MathF.Sqrt(value.Y)); } #endregion Public Static Methods #region Public Static Operators /// <summary> /// Adds two vectors together. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The summed vector.</returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 operator +(Vector2 left, Vector2 right) { return new Vector2(left.X + right.X, left.Y + right.Y); } /// <summary> /// Subtracts the second vector from the first. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The difference vector.</returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 operator -(Vector2 left, Vector2 right) { return new Vector2(left.X - right.X, left.Y - right.Y); } /// <summary> /// Multiplies two vectors together. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The product vector.</returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 operator *(Vector2 left, Vector2 right) { return new Vector2(left.X * right.X, left.Y * right.Y); } /// <summary> /// Multiplies a vector by the given scalar. /// </summary> /// <param name="left">The scalar value.</param> /// <param name="right">The source vector.</param> /// <returns>The scaled vector.</returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 operator *(float left, Vector2 right) { return new Vector2(left, left) * right; } /// <summary> /// Multiplies a vector by the given scalar. /// </summary> /// <param name="left">The source vector.</param> /// <param name="right">The scalar value.</param> /// <returns>The scaled vector.</returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 operator *(Vector2 left, float right) { return left * new Vector2(right, right); } /// <summary> /// Divides the first vector by the second. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The vector resulting from the division.</returns> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 operator /(Vector2 left, Vector2 right) { return new Vector2(left.X / right.X, left.Y / right.Y); } /// <summary> /// Divides the vector by the given scalar. /// </summary> /// <param name="value1">The source vector.</param> /// <param name="value2">The scalar value.</param> /// <returns>The result of the division.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 operator /(Vector2 value1, float value2) { return value1 / new Vector2(value2); } /// <summary> /// Negates a given vector. /// </summary> /// <param name="value">The source vector.</param> /// <returns>The negated vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 operator -(Vector2 value) { return Zero - value; } /// <summary> /// Returns a boolean indicating whether the two given vectors are equal. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>True if the vectors are equal; False otherwise.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(Vector2 left, Vector2 right) { return left.Equals(right); } /// <summary> /// Returns a boolean indicating whether the two given vectors are not equal. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>True if the vectors are not equal; False if they are equal.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(Vector2 left, Vector2 right) { return !(left == right); } #endregion Public Static Operators } }
using UnityEngine; using System.Text; using System.Collections.Generic; using System.Runtime.InteropServices; //----------------------------------------------------------------------------- // Copyright 2012-2015 RenderHeads Ltd. All rights reserverd. //----------------------------------------------------------------------------- public class AVProWindowsMediaPlugin { public enum VideoFrameFormat { RAW_BGRA32, YUV_422_YUY2, YUV_422_UYVY, YUV_422_YVYU, YUV_422_HDYC, YUV_420_NV12=7, Hap_RGB=9, // Standard quality 24-bit RGB, using DXT1 compression Hap_RGBA, // Standard quality 32-bit RGBA, using DXT5 compression Hap_RGB_HQ, // High quality 24-bit, using DXT5 compression with YCoCg color-space trick } // Used by GL.IssuePluginEvent public const int PluginID = 0xFA10000; public enum PluginEvent { UpdateAllTextures = 0, } ////////////////////////////////////////////////////////////////////////// // Initialisation [DllImport("AVProWindowsMedia")] public static extern bool Init(); [DllImport("AVProWindowsMedia")] public static extern void Deinit(); [DllImport("AVProWindowsMedia")] public static extern void SetUnityFeatures(bool supportExternalTextures); [DllImport("AVProWindowsMedia")] public static extern float GetPluginVersion(); // Open and Close handle [DllImport("AVProWindowsMedia")] public static extern int GetInstanceHandle(); [DllImport("AVProWindowsMedia")] public static extern void FreeInstanceHandle(int handle); ////////////////////////////////////////////////////////////////////////// // Loading [DllImport("AVProWindowsMedia")] public static extern bool LoadMovie(int handle, System.IntPtr filename, bool playFromMemory, bool allowNativeFormat, bool useAudioDelay, bool useAudioMixer, bool useDisplaySync); [DllImport("AVProWindowsMedia")] public static extern bool LoadMovieFromMemory(int handle, System.IntPtr moviePointer, long movieLength, bool allowNativeFormat, bool useAudioDelay, bool useAudioMixer, bool useDisplaySync); ////////////////////////////////////////////////////////////////////////// // Get Properties [DllImport("AVProWindowsMedia")] public static extern int GetWidth(int handle); [DllImport("AVProWindowsMedia")] public static extern int GetHeight(int handle); [DllImport("AVProWindowsMedia")] public static extern float GetFrameRate(int handle); [DllImport("AVProWindowsMedia")] public static extern long GetFrameDuration(int handle); [DllImport("AVProWindowsMedia")] public static extern int GetFormat(int handle); [DllImport("AVProWindowsMedia")] public static extern float GetDurationSeconds(int handle); [DllImport("AVProWindowsMedia")] public static extern uint GetDurationFrames(int handle); [DllImport("AVProWindowsMedia")] public static extern bool IsOrientedTopDown(int handle); ////////////////////////////////////////////////////////////////////////// // Playback [DllImport("AVProWindowsMedia")] public static extern void Play(int handle); [DllImport("AVProWindowsMedia")] public static extern void Pause(int handle); [DllImport("AVProWindowsMedia")] public static extern void Stop(int handle); ////////////////////////////////////////////////////////////////////////// // Seeking & Position [DllImport("AVProWindowsMedia")] public static extern void SeekUnit(int handle, float position); [DllImport("AVProWindowsMedia")] public static extern void SeekSeconds(int handle, float position); [DllImport("AVProWindowsMedia")] public static extern void SeekFrames(int handle, uint position); [DllImport("AVProWindowsMedia")] public static extern float GetCurrentPositionSeconds(int handle); [DllImport("AVProWindowsMedia")] public static extern uint GetCurrentPositionFrames(int handle); ////////////////////////////////////////////////////////////////////////// // Get Current State [DllImport("AVProWindowsMedia")] public static extern bool IsLooping(int handle); [DllImport("AVProWindowsMedia")] public static extern float GetPlaybackRate(int handle); [DllImport("AVProWindowsMedia")] public static extern float GetAudioBalance(int handle); [DllImport("AVProWindowsMedia")] public static extern bool IsFinishedPlaying(int handle); ////////////////////////////////////////////////////////////////////////// // Set Current State [DllImport("AVProWindowsMedia")] public static extern void SetVolume(int handle, float volume); [DllImport("AVProWindowsMedia")] public static extern void SetLooping(int handle, bool loop); [DllImport("AVProWindowsMedia")] public static extern void SetDisplayFrameRange(int handle, int min, int max); [DllImport("AVProWindowsMedia")] public static extern void SetPlaybackRate(int handle, float rate); [DllImport("AVProWindowsMedia")] public static extern void SetAudioBalance(int handle, float balance); [DllImport("AVProWindowsMedia")] public static extern void SetAudioChannelMatrix(int handle, float[] values, int numValues); [DllImport("AVProWindowsMedia")] public static extern void SetAudioDelay(int handle, int ms); ////////////////////////////////////////////////////////////////////////// // Update [DllImport("AVProWindowsMedia")] public static extern bool Update(int handle); ////////////////////////////////////////////////////////////////////////// // Frame Update [DllImport("AVProWindowsMedia")] public static extern bool IsNextFrameReadyForGrab(int handle); [DllImport("AVProWindowsMedia")] public static extern int GetLastFrameUploaded(int handle); [DllImport("AVProWindowsMedia")] public static extern bool UpdateTextureGL(int handle, int textureID, ref int frameNumber); [DllImport("AVProWindowsMedia")] public static extern bool GetFramePixels(int handle, System.IntPtr data, int bufferWidth, int bufferHeight, ref int frameNumber); [DllImport("AVProWindowsMedia")] public static extern bool SetTexturePointer(int handle, System.IntPtr data); [DllImport("AVProWindowsMedia")] public static extern System.IntPtr GetTexturePointer(int handle); ////////////////////////////////////////////////////////////////////////// // Live Stats [DllImport("AVProWindowsMedia")] public static extern float GetCaptureFrameRate(int handle); ////////////////////////////////////////////////////////////////////////// // Internal Frame Buffering [DllImport("AVProWindowsMedia")] public static extern void SetFrameBufferSize(int handle, int read, int write); [DllImport("AVProWindowsMedia")] public static extern long GetLastFrameBufferedTime(int handle); [DllImport("AVProWindowsMedia")] public static extern System.IntPtr GetLastFrameBuffered(int handle); [DllImport("AVProWindowsMedia")] public static extern System.IntPtr GetFrameFromBufferAtTime(int handle, long time); ////////////////////////////////////////////////////////////////////////// // Debugging [DllImport("AVProWindowsMedia")] public static extern int GetNumFrameBuffers(int handle); [DllImport("AVProWindowsMedia")] public static extern void GetFrameBufferTimes(int handle, System.IntPtr dest, int destSizeBytes); [DllImport("AVProWindowsMedia")] public static extern void FlushFrameBuffers(int handle); [DllImport("AVProWindowsMedia")] public static extern int GetLastBufferUploaded(int handle); //----------------------------------------------------------------------------- }
/* * XmlCharacterData.cs - Implementation of the * "System.Xml.XmlCharacterData" class. * * Copyright (C) 2002 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Xml { using System; using System.Text; #if ECMA_COMPAT internal #else public #endif abstract class XmlCharacterData : XmlLinkedNode { // Internal state. May be either "String" or "StringBuilder". private Object data; // Constructors. internal XmlCharacterData(XmlNode parent, String data) : base(parent) { this.data = data; } protected internal XmlCharacterData(String data, XmlDocument doc) : base(doc) { this.data = data; } // Get or set the data in this node. public virtual String Data { get { return GetString(); } set { XmlNodeChangedEventArgs args; args = EmitBefore(XmlNodeChangedAction.Change); data = value; EmitAfter(args); } } // Get or set the inner text for this node. public override String InnerText { get { return Value; } set { Value = value; } } // Get the length of the character data. public virtual int Length { get { if(data == null) { return 0; } else if(data is StringBuilder) { return ((StringBuilder)data).Length; } else { return ((String)data).Length; } } } // Get or set the value of this node. public override String Value { get { return Data; } set { Data = value; } } // Get the underlying data as a string builder. private StringBuilder GetBuilder() { StringBuilder builder; if(data == null) { builder = new StringBuilder(); } else if(data is StringBuilder) { return (StringBuilder)data; } else { builder = new StringBuilder((String)data); } data = builder; return builder; } // Get the underlying data as a string. private String GetString() { if(data == null) { return String.Empty; } else if(data is StringBuilder) { data = ((StringBuilder)data).ToString(); return (String)data; } else { return (String)data; } } // Append data to this node. public virtual void AppendData(String strData) { XmlNodeChangedEventArgs args; args = EmitBefore(XmlNodeChangedAction.Change); GetBuilder().Append(strData); EmitAfter(args); } // Delete data from this node. public virtual void DeleteData(int offset, int count) { // Clamp the range to the actual data bounds. int length = Length; if(offset < 0) { count += offset; offset = 0; } else if(offset >= length) { offset = length; count = 0; } if((length - offset) < count) { count = length - offset; } if(count < 0) { count = 0; } // Delete the character range. XmlNodeChangedEventArgs args; args = EmitBefore(XmlNodeChangedAction.Change); GetBuilder().Remove(offset, count); EmitAfter(args); } // Insert data into this node. public virtual void InsertData(int offset, String strData) { XmlNodeChangedEventArgs args; args = EmitBefore(XmlNodeChangedAction.Change); GetBuilder().Insert(offset, strData); EmitAfter(args); } // Replace the data at a particular position within this node. public virtual void ReplaceData(int offset, int count, String strData) { // Clamp the range to the actual data bounds. int length = Length; if(offset < 0) { count += offset; offset = 0; } else if(offset >= length) { offset = length; count = 0; } if((length - offset) < count) { count = length - offset; } if(count < 0) { count = 0; } // Replace the range with the supplied string. XmlNodeChangedEventArgs args; args = EmitBefore(XmlNodeChangedAction.Change); GetBuilder().Remove(offset, count); GetBuilder().Insert(offset, strData); EmitAfter(args); } // Retrieve a substring. public virtual String Substring(int offset, int count) { // Clamp the range to the actual data bounds. int length = Length; if(offset < 0) { count += offset; offset = 0; } else if(offset >= length) { offset = length; count = 0; } if((length - offset) < count) { count = length - offset; } if(count < 0) { count = 0; } // Get the substring. return GetString().Substring(offset, count); } }; // class XmlCharacterData }; // namespace System.Xml
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; #if !NETCF_1_0 using System.Collections; #endif using log4net.Core; namespace log4net.Util { /// <summary> /// Implementation of Stack for the <see cref="log4net.ThreadContext"/> /// </summary> /// <remarks> /// <para> /// Implementation of Stack for the <see cref="log4net.ThreadContext"/> /// </para> /// </remarks> /// <author>Nicko Cadell</author> public sealed class ThreadContextStack : IFixingRequired { #region Private Static Fields /// <summary> /// The stack store. /// </summary> private Stack m_stack = new Stack(); #endregion Private Static Fields #region Public Instance Constructors /// <summary> /// Internal constructor /// </summary> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="ThreadContextStack" /> class. /// </para> /// </remarks> internal ThreadContextStack() { } #endregion Public Instance Constructors #region Public Properties /// <summary> /// The number of messages in the stack /// </summary> /// <value> /// The current number of messages in the stack /// </value> /// <remarks> /// <para> /// The current number of messages in the stack. That is /// the number of times <see cref="Push"/> has been called /// minus the number of times <see cref="Pop"/> has been called. /// </para> /// </remarks> public int Count { get { return m_stack.Count; } } #endregion // Public Properties #region Public Methods /// <summary> /// Clears all the contextual information held in this stack. /// </summary> /// <remarks> /// <para> /// Clears all the contextual information held in this stack. /// Only call this if you think that this tread is being reused after /// a previous call execution which may not have completed correctly. /// You do not need to use this method if you always guarantee to call /// the <see cref="IDisposable.Dispose"/> method of the <see cref="IDisposable"/> /// returned from <see cref="Push"/> even in exceptional circumstances, /// for example by using the <c>using(log4net.ThreadContext.Stacks["NDC"].Push("Stack_Message"))</c> /// syntax. /// </para> /// </remarks> public void Clear() { m_stack.Clear(); } /// <summary> /// Removes the top context from this stack. /// </summary> /// <returns>The message in the context that was removed from the top of this stack.</returns> /// <remarks> /// <para> /// Remove the top context from this stack, and return /// it to the caller. If this stack is empty then an /// empty string (not <see langword="null"/>) is returned. /// </para> /// </remarks> public string Pop() { Stack stack = m_stack; if (stack.Count > 0) { return ((StackFrame)(stack.Pop())).Message; } return ""; } /// <summary> /// Pushes a new context message into this stack. /// </summary> /// <param name="message">The new context message.</param> /// <returns> /// An <see cref="IDisposable"/> that can be used to clean up the context stack. /// </returns> /// <remarks> /// <para> /// Pushes a new context onto this stack. An <see cref="IDisposable"/> /// is returned that can be used to clean up this stack. This /// can be easily combined with the <c>using</c> keyword to scope the /// context. /// </para> /// </remarks> /// <example>Simple example of using the <c>Push</c> method with the <c>using</c> keyword. /// <code lang="C#"> /// using(log4net.ThreadContext.Stacks["NDC"].Push("Stack_Message")) /// { /// log.Warn("This should have an ThreadContext Stack message"); /// } /// </code> /// </example> public IDisposable Push(string message) { Stack stack = m_stack; stack.Push(new StackFrame(message, (stack.Count>0) ? (StackFrame)stack.Peek() : null)); return new AutoPopStackFrame(stack, stack.Count - 1); } #endregion Public Methods #region Internal Methods /// <summary> /// Gets the current context information for this stack. /// </summary> /// <returns>The current context information.</returns> internal string GetFullMessage() { Stack stack = m_stack; if (stack.Count > 0) { return ((StackFrame)(stack.Peek())).FullMessage; } return null; } /// <summary> /// Gets and sets the internal stack used by this <see cref="ThreadContextStack"/> /// </summary> /// <value>The internal storage stack</value> /// <remarks> /// <para> /// This property is provided only to support backward compatability /// of the <see cref="NDC"/>. Tytpically the internal stack should not /// be modified. /// </para> /// </remarks> internal Stack InternalStack { get { return m_stack; } set { m_stack = value; } } #endregion Internal Methods /// <summary> /// Gets the current context information for this stack. /// </summary> /// <returns>Gets the current context information</returns> /// <remarks> /// <para> /// Gets the current context information for this stack. /// </para> /// </remarks> public override string ToString() { return GetFullMessage(); } /// <summary> /// Get a portable version of this object /// </summary> /// <returns>the portable instance of this object</returns> /// <remarks> /// <para> /// Get a cross thread portable version of this object /// </para> /// </remarks> object IFixingRequired.GetFixedObject() { return GetFullMessage(); } /// <summary> /// Inner class used to represent a single context frame in the stack. /// </summary> /// <remarks> /// <para> /// Inner class used to represent a single context frame in the stack. /// </para> /// </remarks> private sealed class StackFrame { #region Private Instance Fields private readonly string m_message; private readonly StackFrame m_parent; private string m_fullMessage = null; #endregion #region Internal Instance Constructors /// <summary> /// Constructor /// </summary> /// <param name="message">The message for this context.</param> /// <param name="parent">The parent context in the chain.</param> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="StackFrame" /> class /// with the specified message and parent context. /// </para> /// </remarks> internal StackFrame(string message, StackFrame parent) { m_message = message; m_parent = parent; if (parent == null) { m_fullMessage = message; } } #endregion Internal Instance Constructors #region Internal Instance Properties /// <summary> /// Get the message. /// </summary> /// <value>The message.</value> /// <remarks> /// <para> /// Get the message. /// </para> /// </remarks> internal string Message { get { return m_message; } } /// <summary> /// Gets the full text of the context down to the root level. /// </summary> /// <value> /// The full text of the context down to the root level. /// </value> /// <remarks> /// <para> /// Gets the full text of the context down to the root level. /// </para> /// </remarks> internal string FullMessage { get { if (m_fullMessage == null && m_parent != null) { m_fullMessage = string.Concat(m_parent.FullMessage, " ", m_message); } return m_fullMessage; } } #endregion Internal Instance Properties } /// <summary> /// Struct returned from the <see cref="ThreadContextStack.Push"/> method. /// </summary> /// <remarks> /// <para> /// This struct implements the <see cref="IDisposable"/> and is designed to be used /// with the <see langword="using"/> pattern to remove the stack frame at the end of the scope. /// </para> /// </remarks> private struct AutoPopStackFrame : IDisposable { #region Private Instance Fields /// <summary> /// The ThreadContextStack internal stack /// </summary> private Stack m_frameStack; /// <summary> /// The depth to trim the stack to when this instance is disposed /// </summary> private int m_frameDepth; #endregion Private Instance Fields #region Internal Instance Constructors /// <summary> /// Constructor /// </summary> /// <param name="frameStack">The internal stack used by the ThreadContextStack.</param> /// <param name="frameDepth">The depth to return the stack to when this object is disposed.</param> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="AutoPopStackFrame" /> class with /// the specified stack and return depth. /// </para> /// </remarks> internal AutoPopStackFrame(Stack frameStack, int frameDepth) { m_frameStack = frameStack; m_frameDepth = frameDepth; } #endregion Internal Instance Constructors #region Implementation of IDisposable /// <summary> /// Returns the stack to the correct depth. /// </summary> /// <remarks> /// <para> /// Returns the stack to the correct depth. /// </para> /// </remarks> public void Dispose() { if (m_frameDepth >= 0 && m_frameStack != null) { while(m_frameStack.Count > m_frameDepth) { m_frameStack.Pop(); } } } #endregion Implementation of IDisposable } #if NETCF_1_0 /// <summary> /// Subclass of <see cref="System.Collections.Stack"/> to /// provide missing methods. /// </summary> /// <remarks> /// <para> /// The Compact Framework version of the <see cref="System.Collections.Stack"/> /// class is missing the <c>Clear</c> and <c>Clone</c> methods. /// This subclass adds implementations of those missing methods. /// </para> /// </remarks> public class Stack : System.Collections.Stack { /// <summary> /// Clears the stack of all elements. /// </summary> /// <remarks> /// <para> /// Clears the stack of all elements. /// </para> /// </remarks> public void Clear() { while(Count > 0) { Pop(); } } /// <summary> /// Makes a shallow copy of the stack's elements. /// </summary> /// <returns>A new stack that has a shallow copy of the stack's elements.</returns> /// <remarks> /// <para> /// Makes a shallow copy of the stack's elements. /// </para> /// </remarks> public Stack Clone() { Stack res = new Stack(); object[] items = ToArray(); foreach(object item in items) { res.Push(item); } return res; } } #endif } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class SpawnPoolsDict : IEnumerable, IDictionary<string, SpawnPool>, ICollection<KeyValuePair<string, SpawnPool>>, IEnumerable<KeyValuePair<string, SpawnPool>> { private Dictionary<string, SpawnPool> _pools = new Dictionary<string, SpawnPool>(); bool ICollection<KeyValuePair<string, SpawnPool>>.IsReadOnly { get { return true; } } public int Count { get { return this._pools.Count; } } public SpawnPool this[string key] { get { SpawnPool result; try { result = this._pools[key]; } catch (KeyNotFoundException) { string message = string.Format("A Pool with the name '{0}' not found. \nPools={1}", key, this.ToString()); throw new KeyNotFoundException(message); } return result; } set { string message = "Cannot set PoolManager.Pools[key] directly. SpawnPools add themselves to PoolManager.Pools when created, so there is no need to set them explicitly. Create pools using PoolManager.Pools.Create() or add a SpawnPool component to a GameObject."; throw new NotImplementedException(message); } } public ICollection<string> Keys { get { string message = "If you need this, please request it."; throw new NotImplementedException(message); } } public ICollection<SpawnPool> Values { get { string message = "If you need this, please request it."; throw new NotImplementedException(message); } } private bool IsReadOnly { get { return true; } } void ICollection<KeyValuePair<string, SpawnPool>>.CopyTo(KeyValuePair<string, SpawnPool>[] array, int arrayIndex) { string message = "PoolManager.Pools cannot be copied"; throw new NotImplementedException(message); } IEnumerator IEnumerable.GetEnumerator() { return this._pools.GetEnumerator(); } public SpawnPool Create(string poolName) { GameObject gameObject = new GameObject(poolName + "Pool"); return gameObject.AddComponent<SpawnPool>(); } public SpawnPool Create(string poolName, GameObject owner) { if (!this.assertValidPoolName(poolName)) { return null; } string name = owner.gameObject.name; SpawnPool result; try { owner.gameObject.name = poolName; result = owner.AddComponent<SpawnPool>(); } finally { owner.gameObject.name = name; } return result; } private bool assertValidPoolName(string poolName) { string text = poolName.Replace("Pool", string.Empty); if (text != poolName) { string message = string.Format("'{0}' has the word 'Pool' in it. This word is reserved for GameObject defaul naming. The pool name has been changed to '{1}'", poolName, text); if (CachePoolManager.bDebug) { Debug.LogWarning(message); } poolName = text; } if (this.ContainsKey(poolName)) { if (CachePoolManager.bDebug) { Debug.Log(string.Format("A pool with the name '{0}' already exists", poolName)); } return false; } return true; } public override string ToString() { string[] array = new string[this._pools.Count]; this._pools.Keys.CopyTo(array, 0); return string.Format("[{0}]", string.Join(", ", array)); } public bool Destroy(string poolName) { SpawnPool spawnPool; if (!this._pools.TryGetValue(poolName, out spawnPool)) { if (CachePoolManager.bDebug) { LogSystem.LogWarning(new object[] { string.Format("PoolManager: Unable to destroy '{0}'. Not in PoolManager", poolName) }); } return false; } DelegateProxy.GameDestory(spawnPool.gameObject); return true; } public void DestroyAll() { foreach (KeyValuePair<string, SpawnPool> current in this._pools) { DelegateProxy.GameDestory(current.Value); } } internal void Add(SpawnPool spawnPool) { if (this.ContainsKey(spawnPool.poolName)) { if (CachePoolManager.bDebug) { LogSystem.LogWarning(new object[] { string.Format("A pool with the name '{0}' already exists. This should only happen if a SpawnPool with this name is added to a scene twice.", spawnPool.poolName) }); } return; } this._pools.Add(spawnPool.poolName, spawnPool); } public void Add(string key, SpawnPool value) { string message = "SpawnPools add themselves to PoolManager.Pools when created, so there is no need to Add() them explicitly. Create pools using PoolManager.Pools.Create() or add a SpawnPool component to a GameObject."; throw new NotImplementedException(message); } internal bool Remove(SpawnPool spawnPool) { if (!this.ContainsKey(spawnPool.poolName)) { if (CachePoolManager.bDebug) { LogSystem.LogWarning(new object[] { string.Format("PoolManager: Unable to remove '{0}'. Pool not in PoolManager", spawnPool.poolName) }); } return false; } this._pools.Remove(spawnPool.poolName); return true; } public bool Remove(string poolName) { string message = "SpawnPools can only be destroyed, not removed and kept alive outside of PoolManager. There are only 2 legal ways to destroy a SpawnPool: DestroyTime the GameObject directly, if you have a reference, or use PoolManager.DestroyTime(string poolName)."; throw new NotImplementedException(message); } public bool ContainsKey(string poolName) { return this._pools.ContainsKey(poolName); } public bool TryGetValue(string poolName, out SpawnPool spawnPool) { return this._pools.TryGetValue(poolName, out spawnPool); } public bool Contains(KeyValuePair<string, SpawnPool> item) { string message = "Use PoolManager.Pools.Contains(string poolName) instead."; throw new NotImplementedException(message); } public void Add(KeyValuePair<string, SpawnPool> item) { string message = "SpawnPools add themselves to PoolManager.Pools when created, so there is no need to Add() them explicitly. Create pools using PoolManager.Pools.Create() or add a SpawnPool component to a GameObject."; throw new NotImplementedException(message); } public void Clear() { string message = "Use PoolManager.Pools.DestroyAll() instead."; throw new NotImplementedException(message); } private void CopyTo(KeyValuePair<string, SpawnPool>[] array, int arrayIndex) { string message = "PoolManager.Pools cannot be copied"; throw new NotImplementedException(message); } public bool Remove(KeyValuePair<string, SpawnPool> item) { string message = "SpawnPools can only be destroyed, not removed and kept alive outside of PoolManager. There are only 2 legal ways to destroy a SpawnPool: DestroyTime the GameObject directly, if you have a reference, or use PoolManager.DestroyTime(string poolName)."; throw new NotImplementedException(message); } public IEnumerator<KeyValuePair<string, SpawnPool>> GetEnumerator() { return this._pools.GetEnumerator(); } }
using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; #if NETFRAMEWORK using Microsoft.Win32; #endif using System.Text.RegularExpressions; namespace YAF.Lucene.Net.Util { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// Some useful constants. /// </summary> public static class Constants // LUCENENET specific - made static because all members are static and constructor in Lucene was private { // LUCENENET NOTE: IMPORTANT - this line must be placed before RUNTIME_VERSION so it can be parsed. private static readonly Regex VERSION = new Regex(@"(\d+\.\d+(?:\.\d+)?(?:\.\d+)?)", RegexOptions.Compiled); // LUCENENET specific - renamed JAVA_VERSION to RUNTIME_VERSION and moved below OS constants because loading is dependent upon OS /// <summary> /// NOTE: This was JAVA_VENDOR in Lucene /// </summary> public static readonly string RUNTIME_VENDOR = "Microsoft"; // AppSettings.Get("java.vendor", ""); //public static readonly string JVM_VENDOR = GetEnvironmentVariable("java.vm.vendor", ""); //public static readonly string JVM_VERSION = GetEnvironmentVariable("java.vm.version", ""); //public static readonly string JVM_NAME = GetEnvironmentVariable("java.vm.name", ""); /// <summary> /// The value of <see cref="RuntimeInformation.OSDescription"/>, excluding the version number.</summary> public static readonly string OS_NAME = VERSION.Replace(RuntimeInformation.OSDescription, string.Empty).Trim(); /// <summary> /// True iff running on Linux. </summary> public static readonly bool LINUX = RuntimeInformation.IsOSPlatform(OSPlatform.Linux); /// <summary> /// True iff running on Windows. </summary> public static readonly bool WINDOWS = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); /// <summary> /// True iff running on SunOS. </summary> public static readonly bool SUN_OS = RuntimeInformation.IsOSPlatform(OSPlatform.Create("SunOS")); /// <summary> /// True iff running on Mac OS X </summary> public static readonly bool MAC_OS_X = RuntimeInformation.IsOSPlatform(OSPlatform.OSX); /// <summary> /// True iff running on FreeBSD </summary> public static readonly bool FREE_BSD = RuntimeInformation.IsOSPlatform(OSPlatform.Create("FreeBSD")); // Possible Values: X86, X64, Arm, Arm64 public static readonly string OS_ARCH = RuntimeInformation.OSArchitecture.ToString(); public static readonly string OS_VERSION = ExtractString(RuntimeInformation.OSDescription, VERSION); #if NETFRAMEWORK /// <summary> /// The value of the currently installed .NET Framework version on Windows or <see cref="Environment.Version"/> on other operating systems. /// <para/> /// NOTE: This was JAVA_VERSION in Lucene /// </summary> #else /// <summary> /// The value of the version parsed from <see cref="RuntimeInformation.FrameworkDescription"/>. /// <para/> /// NOTE: This was JAVA_VERSION in Lucene /// </summary> #endif public static readonly string RUNTIME_VERSION = LoadRuntimeVersion(); [MethodImpl(MethodImplOptions.AggressiveInlining)] private static string LoadRuntimeVersion() // LUCENENET: Avoid static constructors (see https://github.com/apache/lucenenet/pull/224#issuecomment-469284006) { #if NETFRAMEWORK return WINDOWS ? GetFramework45PlusFromRegistry() : Environment.Version.ToString(); #else return ExtractString(RuntimeInformation.FrameworkDescription, VERSION); #endif } // LUCENENET: Removed JRE fields /// <summary> /// NOTE: This was JRE_IS_64BIT in Lucene /// </summary> public static readonly bool RUNTIME_IS_64BIT = LoadRuntimeIs64Bit(); // LUCENENET NOTE: We still need this constant to indicate 64 bit runtime. [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool LoadRuntimeIs64Bit() // LUCENENET: Avoid static constructors (see https://github.com/apache/lucenenet/pull/224#issuecomment-469284006) { // LUCENENET NOTE: In Java, the check is for sun.misc.Unsafe.addressSize, // which is the pointer size of the current environment. We don't need to // fallback to the OS bitness in .NET because this property is reliable and // doesn't throw exceptions. if (IntPtr.Size == 8) return true;// 64 bit machine else // if (IntPtr.Size == 4) return false;// 32 bit machine } // this method prevents inlining the final version constant in compiled classes, // see: http://www.javaworld.com/community/node/3400 [MethodImpl(MethodImplOptions.AggressiveInlining)] private static string Ident(string s) { return s.ToString(); } // We should never change index format with minor versions, so it should always be x.y or x.y.0.z for alpha/beta versions! /// <summary> /// this is the internal Lucene version, recorded into each segment. /// NOTE: we track per-segment version as a <see cref="string"/> with the <c>"X.Y"</c> format /// (no minor version), e.g. <c>"4.0", "3.1", "3.0"</c>. /// <para/>Alpha and Beta versions will have numbers like <c>"X.Y.0.Z"</c>, /// anything else is not allowed. This is done to prevent people from /// using indexes created with ALPHA/BETA versions with the released version. /// </summary> public static readonly string LUCENE_MAIN_VERSION = Ident("4.8"); // LUCENENET NOTE: This version is automatically updated by the // build script, so there is no need to change it here (although // it might make sense to change it when a major/minor/patch // port to Lucene is done). /// <summary> /// This is the Lucene version for display purposes. /// </summary> public static readonly string LUCENE_VERSION = "4.8.0"; /// <summary> /// Returns a LUCENE_MAIN_VERSION without any ALPHA/BETA qualifier /// Used by test only! /// </summary> internal static string MainVersionWithoutAlphaBeta { get { string[] parts = MAIN_VERSION_WITHOUT_ALPHA_BETA.Split(LUCENE_MAIN_VERSION); if (parts.Length == 4 && "0".Equals(parts[2], StringComparison.Ordinal)) { return parts[0] + "." + parts[1]; } return LUCENE_MAIN_VERSION; } } private static readonly Regex MAIN_VERSION_WITHOUT_ALPHA_BETA = new Regex("\\.", RegexOptions.Compiled); #if NETFRAMEWORK // Gets the .NET Framework Version (if at least 4.5) // Reference: https://docs.microsoft.com/en-us/dotnet/framework/migration-guide/how-to-determine-which-versions-are-installed private static string GetFramework45PlusFromRegistry() { const string subkey = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\"; // As an alternative, if you know the computers you will query are running .NET Framework 4.5 // or later, you can use: using RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(subkey); object releaseValue; if (ndpKey != null && (releaseValue = ndpKey.GetValue("Release")) != null) { return CheckFor45PlusVersion((int)releaseValue); } else { // Fall back to Environment.Version (probably wrong, but this is our best guess if the registry check fails) return Environment.Version.ToString(); //Console.WriteLine(".NET Framework Version 4.5 or later is not detected."); } } // Checking the version using >= will enable forward compatibility. private static string CheckFor45PlusVersion(int releaseKey) { if (releaseKey >= 460799) return "4.8"; if (releaseKey >= 460798) return "4.7"; if (releaseKey >= 394802) return "4.6.2"; if (releaseKey >= 394254) { return "4.6.1"; } if (releaseKey >= 393295) { return "4.6"; } if ((releaseKey >= 379893)) { return "4.5.2"; } if ((releaseKey >= 378675)) { return "4.5.1"; } if ((releaseKey >= 378389)) { return "4.5"; } // This code should never execute. A non-null release key should mean // that 4.5 or later is installed. return "No 4.5 or later version detected"; } #endif /// <summary> /// Extracts the first group matched with the regex as a new string. /// </summary> /// <param name="input">The string to examine</param> /// <param name="pattern">A regex object to use to extract the string</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] private static string ExtractString(string input, Regex pattern) { Match m = pattern.Match(input); return (m.Groups.Count > 1) ? m.Groups[1].Value : string.Empty; } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Windows; using Microsoft.PythonTools.Infrastructure; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.Win32; namespace Microsoft.PythonTools.Profiling { sealed class ProfiledProcess : IDisposable { private readonly string _exe, _args, _dir; private readonly ProcessorArchitecture _arch; private readonly Process _process; private readonly PythonToolsService _pyService; public ProfiledProcess(PythonToolsService pyService, string exe, string args, string dir, Dictionary<string, string> envVars) { var arch = NativeMethods.GetBinaryType(exe); if (arch != ProcessorArchitecture.X86 && arch != ProcessorArchitecture.Amd64) { throw new InvalidOperationException(Strings.UnsupportedArchitecture.FormatUI(arch)); } dir = PathUtils.TrimEndSeparator(dir); if (string.IsNullOrEmpty(dir)) { dir = "."; } _pyService = pyService; _exe = exe; _args = args; _dir = dir; _arch = arch; ProcessStartInfo processInfo; string pythonInstallDir = Path.GetDirectoryName(PythonToolsInstallPath.GetFile("VsPyProf.dll", typeof(ProfiledProcess).Assembly)); string dll = _arch == ProcessorArchitecture.Amd64 ? "VsPyProf.dll" : "VsPyProfX86.dll"; string arguments = string.Join(" ", ProcessOutput.QuoteSingleArgument(Path.Combine(pythonInstallDir, "proflaun.py")), ProcessOutput.QuoteSingleArgument(Path.Combine(pythonInstallDir, dll)), ProcessOutput.QuoteSingleArgument(dir), _args ); processInfo = new ProcessStartInfo(_exe, arguments); if (_pyService.DebuggerOptions.WaitOnNormalExit) { processInfo.EnvironmentVariables["VSPYPROF_WAIT_ON_NORMAL_EXIT"] = "1"; } if (_pyService.DebuggerOptions.WaitOnAbnormalExit) { processInfo.EnvironmentVariables["VSPYPROF_WAIT_ON_ABNORMAL_EXIT"] = "1"; } processInfo.CreateNoWindow = false; processInfo.UseShellExecute = false; processInfo.RedirectStandardOutput = false; processInfo.WorkingDirectory = _dir; if (envVars != null) { foreach (var keyValue in envVars) { processInfo.EnvironmentVariables[keyValue.Key] = keyValue.Value; } } _process = new Process(); _process.StartInfo = processInfo; } public void Dispose() { _process.Dispose(); } public void StartProfiling(string filename) { StartPerfMon(filename); _process.EnableRaisingEvents = true; _process.Exited += (sender, args) => { try { // Exited event is fired on a random thread pool thread, we need to handle exceptions. StopPerfMon(); } catch (InvalidOperationException e) { MessageBox.Show(Strings.UnableToStopPerfMon.FormatUI(e.Message), Strings.ProductTitle); } var procExited = ProcessExited; if (procExited != null) { procExited(this, EventArgs.Empty); } }; _process.Start(); } public event EventHandler ProcessExited; private void StartPerfMon(string filename) { string perfToolsPath = GetPerfToolsPath(); string perfMonPath = Path.Combine(perfToolsPath, "VSPerfMon.exe"); if (!File.Exists(perfMonPath)) { throw new InvalidOperationException(Strings.CannotLocatePerformanceTools); } var psi = new ProcessStartInfo(perfMonPath, "/trace /output:" + ProcessOutput.QuoteSingleArgument(filename)); psi.CreateNoWindow = true; psi.UseShellExecute = false; psi.RedirectStandardError = true; psi.RedirectStandardOutput = true; Process.Start(psi).Dispose(); string perfCmdPath = Path.Combine(perfToolsPath, "VSPerfCmd.exe"); using (var p = ProcessOutput.RunHiddenAndCapture(perfCmdPath, "/waitstart")) { p.Wait(); if (p.ExitCode != 0) { throw new InvalidOperationException(Strings.StartPerfCmdError.FormatUI( string.Join(Environment.NewLine, p.StandardOutputLines), string.Join(Environment.NewLine, p.StandardErrorLines) )); } } } private void StopPerfMon() { string perfToolsPath = GetPerfToolsPath(); string perfMonPath = Path.Combine(perfToolsPath, "VSPerfCmd.exe"); using (var p = ProcessOutput.RunHiddenAndCapture(perfMonPath, "/shutdown")) { p.Wait(); if (p.ExitCode != 0) { throw new InvalidOperationException(Strings.StopPerfMonError.FormatUI( string.Join(Environment.NewLine, p.StandardOutputLines), string.Join(Environment.NewLine, p.StandardErrorLines) )); } } } private string GetPerfToolsPath() { using (var baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32)) { if (baseKey == null) { throw new InvalidOperationException(Strings.CannotOpenSystemRegistry); } using (var key = baseKey.OpenSubKey(@"Software\Microsoft\VisualStudio\VSPerf")) { var path = key?.GetValue("CollectionToolsDir") as string; if (!string.IsNullOrEmpty(path)) { if (_arch == ProcessorArchitecture.Amd64) { path = PathUtils.GetAbsoluteDirectoryPath(path, "x64"); } if (Directory.Exists(path)) { return path; } } } using (var key = baseKey.OpenSubKey(@"SOFTWARE\Microsoft\VisualStudio\RemoteTools\{0}\DiagnosticsHub".FormatInvariant(AssemblyVersionInfo.VSVersion))) { var path = PathUtils.GetParent(key?.GetValue("VSPerfPath") as string); if (!string.IsNullOrEmpty(path)) { if (_arch == ProcessorArchitecture.Amd64) { path = PathUtils.GetAbsoluteDirectoryPath(path, "x64"); } if (Directory.Exists(path)) { return path; } } } } Debug.Fail("Registry search for Perfomance Tools failed - falling back on old path"); string shFolder; if (!_pyService.Site.TryGetShellProperty(__VSSPROPID.VSSPROPID_InstallDirectory, out shFolder)) { throw new InvalidOperationException(Strings.CannotFindShellFolder); } try { shFolder = Path.GetDirectoryName(Path.GetDirectoryName(shFolder)); } catch (ArgumentException) { throw new InvalidOperationException(Strings.CannotFindShellFolder); } string perfToolsPath; if (_arch == ProcessorArchitecture.Amd64) { perfToolsPath = @"Team Tools\Performance Tools\x64"; } else { perfToolsPath = @"Team Tools\Performance Tools\"; } perfToolsPath = Path.Combine(shFolder, perfToolsPath); return perfToolsPath; } internal void StopProfiling() { _process.Kill(); } } }
#if !UNIX using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Management.Automation; using System.ComponentModel; using System.Runtime.InteropServices; using System.Globalization; using System.Diagnostics.CodeAnalysis; namespace Microsoft.PowerShell.Commands { /// <summary> /// A cmdlet to retrieve time zone information. /// </summary> [Cmdlet(VerbsCommon.Get, "TimeZone", DefaultParameterSetName = "Name", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=799468")] [Alias("gtz")] public class GetTimeZoneCommand : PSCmdlet { #region Parameters /// <summary> /// A list of the local time zone ids that the cmdlet should look up. /// </summary> [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "Id")] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] Id { get; set; } /// <summary> /// Specifies that the cmdlet should produce a collection of the /// TimeZoneInfo objects that are available on the system. /// </summary> [Parameter(Mandatory = true, ParameterSetName = "ListAvailable")] public SwitchParameter ListAvailable { get; set; } /// <summary> /// A list of the local time zone names that the cmdlet should look up. /// </summary> [Parameter(Position = 0, ValueFromPipeline = true, ParameterSetName = "Name")] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] Name { get; set; } #endregion Parameters /// <summary> /// Implementation of the ProcessRecord method for Get-TimeZone /// </summary> protected override void ProcessRecord() { // make sure we've got the latest time zone settings TimeZoneHelper.ClearCachedData(); if (this.ParameterSetName.Equals("ListAvailable", StringComparison.OrdinalIgnoreCase)) { // output the list of all available time zones WriteObject(TimeZoneInfo.GetSystemTimeZones(), true); } else if (this.ParameterSetName.Equals("Id", StringComparison.OrdinalIgnoreCase)) { // lookup each time zone id foreach (string tzid in Id) { try { WriteObject(TimeZoneInfo.FindSystemTimeZoneById(tzid)); } #if CORECLR // TimeZoneNotFoundException is thrown by TimeZoneInfo, but not // publicly visible (so can't be caught), so for now we're catching // the parent exception time. This should be removed once the more // specific exception is available. catch (Exception e) #else catch (TimeZoneNotFoundException e) #endif { WriteError(new ErrorRecord(e, TimeZoneHelper.TimeZoneNotFoundError, ErrorCategory.InvalidArgument, "Id")); } } } else // ParameterSetName == "Name" { if (null != Name) { // lookup each time zone name (or wildcard pattern) foreach (string tzname in Name) { TimeZoneInfo[] timeZones = TimeZoneHelper.LookupSystemTimeZoneInfoByName(tzname); if (0 < timeZones.Length) { // manually process each object in the array, so if there is only a single // entry then the returned type is TimeZoneInfo and not TimeZoneInfo[], and // it can be pipelined to Set-TimeZone more easily foreach (TimeZoneInfo timeZone in timeZones) { WriteObject(timeZone); } } else { string message = string.Format(CultureInfo.InvariantCulture, TimeZoneResources.TimeZoneNameNotFound, tzname); #if CORECLR // Because .NET Core does not currently expose the TimeZoneNotFoundException // we need to throw the more generic parent exception class for the time being. // This should be removed once the correct exception class is available. Exception e = new Exception(message); #else Exception e = new TimeZoneNotFoundException(message); #endif WriteError(new ErrorRecord(e, TimeZoneHelper.TimeZoneNotFoundError, ErrorCategory.InvalidArgument, "Name")); } } } else { // return the current system local time zone WriteObject(TimeZoneInfo.Local); } } } } /// <summary> /// A cmdlet to set the system's local time zone. /// </summary> [Cmdlet(VerbsCommon.Set, "TimeZone", SupportsShouldProcess = true, DefaultParameterSetName = "Name", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=799469")] [Alias("stz")] public class SetTimeZoneCommand : PSCmdlet { #region string constants private const string TimeZoneTarget = "Local System"; #endregion string constants #region Parameters /// <summary> /// The name of the local time zone that the system should use. /// </summary> [Parameter(Mandatory = true, ParameterSetName = "Id", ValueFromPipelineByPropertyName = true)] public string Id { get; set; } /// <summary> /// A TimeZoneInfo object identifying the local time zone that the system should use. /// </summary> [Parameter(Mandatory = true, Position = 0, ParameterSetName = "InputObject", ValueFromPipeline = true)] public TimeZoneInfo InputObject { get; set; } /// <summary> /// The name of the local time zone that the system should use. /// </summary> [Parameter(Mandatory = true, Position = 0, ParameterSetName = "Name")] public string Name { get; set; } /// <summary> /// Request return of the new local time zone as a TimeZoneInfo object /// </summary> [Parameter] public SwitchParameter PassThru { get; set; } #endregion Parameters /// <summary> /// Implementation of the ProcessRecord method for Get-TimeZone /// </summary> [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly", Justification = "Since Name is not a parameter of this method, it confuses FXCop. It is the appropriate value for the exception.")] protected override void ProcessRecord() { // make sure we've got fresh data, in case the requested time zone was added // to the system (registry) after our process was started TimeZoneHelper.ClearCachedData(); // acquire a TimeZoneInfo if one wasn't supplied. if (this.ParameterSetName.Equals("Id", StringComparison.OrdinalIgnoreCase)) { try { InputObject = TimeZoneInfo.FindSystemTimeZoneById(Id); } #if CORECLR // TimeZoneNotFoundException is thrown by TimeZoneInfo, but not // publicly visible (so can't be caught), so for now we're catching // the parent exception time. This should be removed once the more // specific exception is available. catch (Exception e) #else catch (TimeZoneNotFoundException e) #endif { ThrowTerminatingError(new ErrorRecord( e, TimeZoneHelper.TimeZoneNotFoundError, ErrorCategory.InvalidArgument, "Id")); } } else if (this.ParameterSetName.Equals("Name", StringComparison.OrdinalIgnoreCase)) { // lookup the time zone name and make sure we have one (and only one) match TimeZoneInfo[] timeZones = TimeZoneHelper.LookupSystemTimeZoneInfoByName(Name); if (0 == timeZones.Length) { string message = string.Format(CultureInfo.InvariantCulture, TimeZoneResources.TimeZoneNameNotFound, Name); #if CORECLR // Because .NET Core does not currently expose the TimeZoneNotFoundException // we need to throw the more generic parent exception class for the time being. // This should be removed once the correct exception class is available. Exception e = new Exception(message); #else Exception e = new TimeZoneNotFoundException(message); #endif ThrowTerminatingError(new ErrorRecord(e, TimeZoneHelper.TimeZoneNotFoundError, ErrorCategory.InvalidArgument, "Name")); } else if (1 < timeZones.Length) { string message = string.Format(CultureInfo.InvariantCulture, TimeZoneResources.MultipleMatchingTimeZones, Name); ThrowTerminatingError(new ErrorRecord( new PSArgumentException(message, "Name"), TimeZoneHelper.MultipleMatchingTimeZonesError, ErrorCategory.InvalidArgument, "Name")); } else { InputObject = timeZones[0]; } } else // ParameterSetName == "InputObject" { try { // a TimeZoneInfo object was supplied, so use it to make sure we can find // a backing system time zone, otherwise it's an error condition InputObject = TimeZoneInfo.FindSystemTimeZoneById(InputObject.Id); } #if CORECLR // TimeZoneNotFoundException is thrown by TimeZoneInfo, but not // publicly visible (so can't be caught), so for now we're catching // the parent exception time. This should be removed once the more // specific exception is available. catch (Exception e) #else catch (TimeZoneNotFoundException e) #endif { ThrowTerminatingError(new ErrorRecord( e, TimeZoneHelper.TimeZoneNotFoundError, ErrorCategory.InvalidArgument, "InputObject")); } } if (ShouldProcess(TimeZoneTarget)) { bool acquireAccess = false; try { // check to see if permission to set the time zone is already enabled for this process if (!HasAccess) { // acquire permissions to set the timezone SetAccessToken(true); acquireAccess = true; } } catch (Win32Exception e) { ThrowTerminatingError(new ErrorRecord(e, TimeZoneHelper.InsufficientPermissionsError, ErrorCategory.PermissionDenied, null)); } try { // construct and populate a new DYNAMIC_TIME_ZONE_INFORMATION structure NativeMethods.DYNAMIC_TIME_ZONE_INFORMATION dtzi = new NativeMethods.DYNAMIC_TIME_ZONE_INFORMATION(); dtzi.Bias -= (int)InputObject.BaseUtcOffset.TotalMinutes; dtzi.StandardName = InputObject.StandardName; dtzi.DaylightName = InputObject.DaylightName; dtzi.TimeZoneKeyName = InputObject.Id; // Request time zone transition information for the current year NativeMethods.TIME_ZONE_INFORMATION tzi = new NativeMethods.TIME_ZONE_INFORMATION(); if (!NativeMethods.GetTimeZoneInformationForYear((ushort)DateTime.Now.Year, ref dtzi, ref tzi)) { ThrowWin32Error(); } // copy over the transition times dtzi.StandardBias = tzi.StandardBias; dtzi.StandardDate = tzi.StandardDate; dtzi.DaylightBias = tzi.DaylightBias; dtzi.DaylightDate = tzi.DaylightDate; // set the new local time zone for the system if (!NativeMethods.SetDynamicTimeZoneInformation(ref dtzi)) { ThrowWin32Error(); } #if !CORECLR // broadcast a WM_SETTINGCHANGE notification message to all top-level windows so that they // know to update their notion of the current system time (and time zone) if applicable int result = 0; NativeMethods.SendMessageTimeout((IntPtr)NativeMethods.HWND_BROADCAST, NativeMethods.WM_SETTINGCHANGE, (IntPtr)0, "intl", NativeMethods.SMTO_ABORTIFHUNG, 5000, ref result); #endif // clear the time zone data or this PowerShell session // will not recognize the new time zone settings TimeZoneHelper.ClearCachedData(); if (PassThru.IsPresent) { // return the TimeZoneInfo object for the (new) current local time zone WriteObject(TimeZoneInfo.Local); } } catch (Win32Exception e) { ThrowTerminatingError(new ErrorRecord(e, TimeZoneHelper.SetTimeZoneFailedError, ErrorCategory.FromStdErr, null)); } finally { if (acquireAccess) { // reset the permissions SetAccessToken(false); } } } else { if (PassThru.IsPresent) { // show the user the time zone settings that would have been used. WriteObject(InputObject); } } } #region Helper functions /// <summary> /// True if the current process has access to change the time zone setting. /// </summary> protected bool HasAccess { get { bool hasAccess = false; // open the access token for the current process IntPtr hToken = IntPtr.Zero; IntPtr hProcess = NativeMethods.GetCurrentProcess(); if (!NativeMethods.OpenProcessToken(hProcess, NativeMethods.TOKEN_ADJUST_PRIVILEGES | NativeMethods.TOKEN_QUERY, ref hToken)) { ThrowWin32Error(); } try { // setup the privileges being checked NativeMethods.PRIVILEGE_SET ps = new NativeMethods.PRIVILEGE_SET() { PrivilegeCount = 1, Control = 1, Luid = 0, Attributes = NativeMethods.SE_PRIVILEGE_ENABLED, }; // lookup the Luid of the SeTimeZonePrivilege if (!NativeMethods.LookupPrivilegeValue(null, NativeMethods.SE_TIME_ZONE_NAME, ref ps.Luid)) { ThrowWin32Error(); } // set the privilege for the open access token if (!NativeMethods.PrivilegeCheck(hToken, ref ps, ref hasAccess)) { ThrowWin32Error(); } } finally { NativeMethods.CloseHandle(hToken); } return (hasAccess); } } /// <summary> /// Set the SeTimeZonePrivilege, which controls access to the SetDynamicTimeZoneInformation API /// </summary> /// <param name="enable">Set to true to enable (or false to disable) the privilege.</param> protected void SetAccessToken(bool enable) { // open the access token for the current process IntPtr hToken = IntPtr.Zero; IntPtr hProcess = NativeMethods.GetCurrentProcess(); if (!NativeMethods.OpenProcessToken(hProcess, NativeMethods.TOKEN_ADJUST_PRIVILEGES | NativeMethods.TOKEN_QUERY, ref hToken)) { ThrowWin32Error(); } try { // setup the privileges being requested NativeMethods.TOKEN_PRIVILEGES tp = new NativeMethods.TOKEN_PRIVILEGES() { PrivilegeCount = 1, Luid = 0, Attributes = (enable ? NativeMethods.SE_PRIVILEGE_ENABLED : 0), }; // lookup the Luid of the SeTimeZonePrivilege if (!NativeMethods.LookupPrivilegeValue(null, NativeMethods.SE_TIME_ZONE_NAME, ref tp.Luid)) { ThrowWin32Error(); } // set the privilege for the open access token if (!NativeMethods.AdjustTokenPrivileges(hToken, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero)) { ThrowWin32Error(); } } finally { NativeMethods.CloseHandle(hToken); } } /// <summary> /// Get the Win32 error code from GetLastError and throw an exception. /// </summary> protected void ThrowWin32Error() { int error = Marshal.GetLastWin32Error(); throw new Win32Exception(error); } #endregion Helper functions #region Win32 interop helper internal class NativeMethods { /// <summary> /// Private constructor to prevent instantiation /// </summary> private NativeMethods() { } #region Native DLL locations #if CORECLR private const string SetDynamicTimeZoneApiDllName = "api-ms-win-core-timezone-l1-1-0.dll"; private const string GetTimeZoneInformationForYearApiDllName = "api-ms-win-core-timezone-l1-1-0.dll"; private const string GetCurrentProcessApiDllName = "api-ms-win-downlevel-kernel32-l1-1-0.dll"; private const string OpenProcessTokenApiDllName = "api-ms-win-downlevel-advapi32-l1-1-1.dll"; private const string LookupPrivilegeTokenApiDllName = "api-ms-win-downlevel-advapi32-l4-1-0.dll"; private const string PrivilegeCheckApiDllName = "api-ms-win-downlevel-advapi32-l1-1-1.dll"; private const string AdjustTokenPrivilegesApiDllName = "api-ms-win-downlevel-advapi32-l1-1-1.dll"; private const string CloseHandleApiDllName = "api-ms-win-downlevel-kernel32-l1-1-0.dll"; private const string SendMessageTimeoutApiDllName = "ext-ms-win-rtcore-ntuser-window-ext-l1-1-0.dll"; #else private const string SetDynamicTimeZoneApiDllName = "kernel32.dll"; private const string GetTimeZoneInformationForYearApiDllName = "kernel32.dll"; private const string GetCurrentProcessApiDllName = "kernel32.dll"; private const string OpenProcessTokenApiDllName = "advapi32.dll"; private const string LookupPrivilegeTokenApiDllName = "advapi32.dll"; private const string PrivilegeCheckApiDllName = "advapi32.dll"; private const string AdjustTokenPrivilegesApiDllName = "advapi32.dll"; private const string CloseHandleApiDllName = "kernel32.dll"; private const string SendMessageTimeoutApiDllName = "user32.dll"; #endif #endregion Native DLL locations #region Win32 SetDynamicTimeZoneInformation imports /// <summary> /// Used to marshal win32 SystemTime structure to managed code layer /// </summary> [StructLayout(LayoutKind.Sequential)] public struct SystemTime { /// <summary> /// The year. /// </summary> [MarshalAs(UnmanagedType.U2)] public short Year; /// <summary> /// The month. /// </summary> [MarshalAs(UnmanagedType.U2)] public short Month; /// <summary> /// The day of the week. /// </summary> [MarshalAs(UnmanagedType.U2)] public short DayOfWeek; /// <summary> /// The day of the month. /// </summary> [MarshalAs(UnmanagedType.U2)] public short Day; /// <summary> /// The hour. /// </summary> [MarshalAs(UnmanagedType.U2)] public short Hour; /// <summary> /// The minute. /// </summary> [MarshalAs(UnmanagedType.U2)] public short Minute; /// <summary> /// The second. /// </summary> [MarshalAs(UnmanagedType.U2)] public short Second; /// <summary> /// The millisecond. /// </summary> [MarshalAs(UnmanagedType.U2)] public short Milliseconds; } /// <summary> /// Used to marshal win32 DYNAMIC_TIME_ZONE_INFORMATION structure to managed code layer /// </summary> [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct DYNAMIC_TIME_ZONE_INFORMATION { /// <summary> /// The current bias for local time translation on this computer, in minutes. /// </summary> [MarshalAs(UnmanagedType.I4)] public int Bias; /// <summary> /// A description for standard time. /// </summary> [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)] public string StandardName; /// <summary> /// A SystemTime structure that contains a date and local time when the transition from daylight saving time to standard time occurs on this operating system. /// </summary> public SystemTime StandardDate; /// <summary> /// The bias value to be used during local time translations that occur during standard time. /// </summary> [MarshalAs(UnmanagedType.I4)] public int StandardBias; /// <summary> /// A description for daylight saving time (DST). /// </summary> [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)] public string DaylightName; /// <summary> /// A SystemTime structure that contains a date and local time when the transition from standard time to daylight saving time occurs on this operating system. /// </summary> public SystemTime DaylightDate; /// <summary> /// The bias value to be used during local time translations that occur during daylight saving time. /// </summary> [MarshalAs(UnmanagedType.I4)] public int DaylightBias; /// <summary> /// The name of the time zone registry key on the local computer. /// </summary> [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x80)] public string TimeZoneKeyName; /// <summary> /// Indicates whether dynamic daylight saving time is disabled. /// </summary> [MarshalAs(UnmanagedType.U1)] public bool DynamicDaylightTimeDisabled; } /// <summary> /// Used to marshal win32 TIME_ZONE_INFORMATION structure to managed code layer /// </summary> [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct TIME_ZONE_INFORMATION { /// <summary> /// The current bias for local time translation on this computer, in minutes. /// </summary> [MarshalAs(UnmanagedType.I4)] public int Bias; /// <summary> /// A description for standard time. /// </summary> [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)] public string StandardName; /// <summary> /// A SystemTime structure that contains a date and local time when the transition from daylight saving time to standard time occurs on this operating system. /// </summary> public SystemTime StandardDate; /// <summary> /// The bias value to be used during local time translations that occur during standard time. /// </summary> [MarshalAs(UnmanagedType.I4)] public int StandardBias; /// <summary> /// A description for daylight saving time (DST). /// </summary> [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)] public string DaylightName; /// <summary> /// A SystemTime structure that contains a date and local time when the transition from standard time to daylight saving time occurs on this operating system. /// </summary> public SystemTime DaylightDate; /// <summary> /// The bias value to be used during local time translations that occur during daylight saving time. /// </summary> [MarshalAs(UnmanagedType.I4)] public int DaylightBias; } /// <summary> /// PInvoke SetDynamicTimeZoneInformation API /// </summary> /// <param name="lpTimeZoneInformation">A DYNAMIC_TIME_ZONE_INFORMATION structure representing the desired local time zone.</param> /// <returns></returns> [DllImport(SetDynamicTimeZoneApiDllName, SetLastError = true)] public static extern bool SetDynamicTimeZoneInformation([In] ref DYNAMIC_TIME_ZONE_INFORMATION lpTimeZoneInformation); [DllImport(GetTimeZoneInformationForYearApiDllName, SetLastError = true)] public static extern bool GetTimeZoneInformationForYear([In] ushort wYear, [In] ref DYNAMIC_TIME_ZONE_INFORMATION pdtzi, ref TIME_ZONE_INFORMATION ptzi); #endregion Win32 SetDynamicTimeZoneInformation imports #region Win32 AdjustTokenPrivilege imports /// <summary> /// Definition of TOKEN_QUERY constant from Win32 API /// </summary> public const int TOKEN_QUERY = 0x00000008; /// <summary> /// Definition of TOKEN_ADJUST_PRIVILEGES constant from Win32 API /// </summary> public const int TOKEN_ADJUST_PRIVILEGES = 0x00000020; /// <summary> /// Definition of SE_PRIVILEGE_ENABLED constant from Win32 API /// </summary> public const int SE_PRIVILEGE_ENABLED = 0x00000002; /// <summary> /// Definition of SE_TIME_ZONE_NAME constant from Win32 API /// </summary> public const string SE_TIME_ZONE_NAME = "SeTimeZonePrivilege"; //http://msdn.microsoft.com/en-us/library/bb530716(VS.85).aspx /// <summary> /// PInvoke GetCurrentProcess API /// </summary> /// <returns></returns> [DllImport(GetCurrentProcessApiDllName, ExactSpelling = true)] public static extern IntPtr GetCurrentProcess(); /// <summary> /// PInvoke OpenProcessToken API /// </summary> /// <param name="ProcessHandle"></param> /// <param name="DesiredAccess"></param> /// <param name="TokenHandle"></param> /// <returns></returns> [DllImport(OpenProcessTokenApiDllName, SetLastError = true, CharSet = CharSet.Unicode, BestFitMapping = false)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool OpenProcessToken(IntPtr ProcessHandle, int DesiredAccess, ref IntPtr TokenHandle); /// <summary> /// PInvoke LookupPrivilegeValue API /// </summary> /// <param name="lpSystemName"></param> /// <param name="lpName"></param> /// <param name="lpLuid"></param> /// <returns></returns> [DllImport(LookupPrivilegeTokenApiDllName, SetLastError = true, CharSet = CharSet.Unicode, BestFitMapping = false)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool LookupPrivilegeValue(string lpSystemName, string lpName, ref long lpLuid); /// <summary> /// PInvoke PrivilegeCheck API /// </summary> /// <param name="ClientToken"></param> /// <param name="RequiredPrivileges"></param> /// <param name="pfResult"></param> /// <returns></returns> [DllImport(PrivilegeCheckApiDllName, SetLastError = true, CharSet = CharSet.Unicode, BestFitMapping = false)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool PrivilegeCheck(IntPtr ClientToken, ref PRIVILEGE_SET RequiredPrivileges, ref bool pfResult); /// <summary> /// PInvoke AdjustTokenPrivilege API /// </summary> /// <param name="TokenHandle"></param> /// <param name="DisableAllPrivilegs"></param> /// <param name="NewState"></param> /// <param name="BufferLength"></param> /// <param name="PreviousState"></param> /// <param name="ReturnLength"></param> /// <returns></returns> [DllImport(AdjustTokenPrivilegesApiDllName, SetLastError = true, CharSet = CharSet.Unicode, BestFitMapping = false)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool AdjustTokenPrivileges(IntPtr TokenHandle, bool DisableAllPrivilegs, ref TOKEN_PRIVILEGES NewState, int BufferLength, IntPtr PreviousState, IntPtr ReturnLength); /// <summary> /// PInvoke CloseHandle API /// </summary> /// <param name="hObject"></param> /// <returns></returns> [DllImport(CloseHandleApiDllName, ExactSpelling = true, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool CloseHandle(IntPtr hObject); /// <summary> /// Used to marshal win32 PRIVILEGE_SET structure to managed code layer /// </summary> [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct PRIVILEGE_SET { public int PrivilegeCount; public int Control; public long Luid; public int Attributes; } /// <summary> /// Used to marshal win32 TOKEN_PRIVILEGES structure to managed code layer /// </summary> [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct TOKEN_PRIVILEGES { public int PrivilegeCount; public long Luid; public int Attributes; } #endregion Win32 AdjustTokenPrivilege imports #region Win32 SendMessage imports /// <summary> /// Definition of WM_SETTINGCHANGE constant from Win32 API /// </summary> public const int WM_SETTINGCHANGE = 0x001A; /// <summary> /// Definition of HWND_BROADCAST constant from Win32 API /// </summary> public const int HWND_BROADCAST = (-1); /// <summary> /// Definition of SMTO_ABORTIFHUNG constant from Win32 API /// </summary> public const int SMTO_ABORTIFHUNG = 0x0002; /// <summary> /// PInvoke SendMessageTimeout API /// </summary> /// <param name="hWnd"></param> /// <param name="Msg"></param> /// <param name="wParam"></param> /// <param name="lParam"></param> /// <param name="fuFlags"></param> /// <param name="uTimeout"></param> /// <param name="lpdwResult"></param> /// <returns></returns> [DllImport(SendMessageTimeoutApiDllName, SetLastError = true, CharSet = CharSet.Unicode)] public static extern IntPtr SendMessageTimeout(IntPtr hWnd, int Msg, IntPtr wParam, string lParam, int fuFlags, int uTimeout, ref int lpdwResult); #endregion Win32 SendMessage imports } #endregion Win32 interop helper } /// <summary> /// static Helper class for working with system time zones. /// </summary> internal static class TimeZoneHelper { #region Error Ids internal const string TimeZoneNotFoundError = "TimeZoneNotFound"; internal const string MultipleMatchingTimeZonesError = "MultipleMatchingTimeZones"; internal const string InsufficientPermissionsError = "InsufficientPermissions"; internal const string SetTimeZoneFailedError = "SetTimeZoneFailed"; #endregion Error Ids /// <summary> /// Clear the cached TimeZoneInfo data. Note that since TimeZoneInfo.ClearCachedData /// does not exist in .NET Core there is an alternative mechanism (which doesn't seem /// to affect clearing out the cache under the full desktop version of .NET) /// </summary> internal static void ClearCachedData() { #if CORECLR // NOTE: .NET Core does not expose the ClearCachedData method, but executing // the specific ConvertTime request below should have the same effect. TimeZoneInfo.ConvertTime(new DateTime(0), TimeZoneInfo.Local); #else TimeZoneInfo.ClearCachedData(); #endif } /// <summary> /// Find the system time zone by checking first against StandardName and then, /// if no matches were found, against the DaylightName. /// </summary> /// <param name="name">The name (or wildcard pattern) of the system time zone to find.</param> /// <returns>A TimeZoneInfo object array containing information about the specified system time zones.</returns> internal static TimeZoneInfo[] LookupSystemTimeZoneInfoByName(string name) { WildcardPattern namePattern = new WildcardPattern(name, WildcardOptions.IgnoreCase); List<TimeZoneInfo> tzi = new List<TimeZoneInfo>(); // get the available system time zones ReadOnlyCollection<TimeZoneInfo> zones = TimeZoneInfo.GetSystemTimeZones(); // check against the standard and daylight names for each TimeZoneInfo foreach (TimeZoneInfo zone in zones) { if (namePattern.IsMatch(zone.StandardName) || namePattern.IsMatch(zone.DaylightName)) { tzi.Add(zone); } } return (tzi.ToArray()); } } } #endif
using System.Text.RegularExpressions; namespace SideBySide; public class ConnectSync : IClassFixture<DatabaseFixture> { public ConnectSync(DatabaseFixture database) { m_database = database; } [SkippableFact(Baseline = "https://bugs.mysql.com/bug.php?id=106242")] public void ConnectBadHost() { var csb = new MySqlConnectionStringBuilder { Server = "invalid.example.com", }; using var connection = new MySqlConnection(csb.ConnectionString); Assert.Equal(ConnectionState.Closed, connection.State); var ex = Assert.Throws<MySqlException>(connection.Open); #if !BASELINE Assert.True(ex.IsTransient); #endif Assert.Equal((int) MySqlErrorCode.UnableToConnectToHost, ex.Number); Assert.Equal((int) MySqlErrorCode.UnableToConnectToHost, ex.Data["Server Error Code"]); Assert.Equal(ConnectionState.Closed, connection.State); } [SkippableFact(Baseline = "https://bugs.mysql.com/bug.php?id=106242")] public void ConnectBadPort() { var csb = new MySqlConnectionStringBuilder { Server = "localhost", Port = 65000, }; using var connection = new MySqlConnection(csb.ConnectionString); Assert.Equal(ConnectionState.Closed, connection.State); Assert.Throws<MySqlException>(() => connection.Open()); Assert.Equal(ConnectionState.Closed, connection.State); } [Fact] public void ConnectInvalidPort() { var csb = new MySqlConnectionStringBuilder { Server = "localhost", Port = 1000000, }; using var connection = new MySqlConnection(csb.ConnectionString); Assert.Throws<MySqlException>(() => connection.Open()); } [Fact] public void ConnectBadDatabase() { var csb = AppConfig.CreateConnectionStringBuilder(); csb.Database = "wrong_database"; using var connection = new MySqlConnection(csb.ConnectionString); var ex = Assert.Throws<MySqlException>(connection.Open); #if !BASELINE // https://bugs.mysql.com/bug.php?id=78426 if (AppConfig.SupportedFeatures.HasFlag(ServerFeatures.ErrorCodes) || ex.ErrorCode != default) Assert.Equal(MySqlErrorCode.UnknownDatabase, ex.ErrorCode); #endif Assert.Equal(ConnectionState.Closed, connection.State); } [Fact] public void ConnectBadPassword() { var csb = AppConfig.CreateConnectionStringBuilder(); csb.Password = "wrong"; using var connection = new MySqlConnection(csb.ConnectionString); var ex = Assert.Throws<MySqlException>(connection.Open); #if !BASELINE // https://bugs.mysql.com/bug.php?id=78426 if (AppConfig.SupportedFeatures.HasFlag(ServerFeatures.ErrorCodes) || ex.ErrorCode != default) Assert.Equal(MySqlErrorCode.AccessDenied, ex.ErrorCode); #endif Assert.Equal(ConnectionState.Closed, connection.State); } #if !BASELINE [Theory] [InlineData("server=mysqld.sock;Protocol=Unix;LoadBalance=Failover")] [InlineData("server=pipename;Protocol=Pipe;LoadBalance=Failover")] public void LoadBalanceNotSupported(string connectionString) { using var connection = new MySqlConnection(connectionString); Assert.Throws<NotSupportedException>(() => connection.Open()); } #endif [Fact] public void NonExistentPipe() { var csb = new MySqlConnectionStringBuilder { PipeName = "nonexistingpipe", ConnectionProtocol = MySqlConnectionProtocol.NamedPipe, Server = ".", ConnectionTimeout = 1 }; var sw = Stopwatch.StartNew(); using var connection = new MySqlConnection(csb.ConnectionString); Assert.Throws<MySqlException>(connection.Open); #if !BASELINE TestUtilities.AssertDuration(sw, 900, 500); #else TestUtilities.AssertDuration(sw, 0, 500); #endif } [Theory] [InlineData(false, false)] [InlineData(true, false)] [InlineData(false, true)] [InlineData(true, true)] public void PersistSecurityInfo(bool persistSecurityInfo, bool closeConnection) { var csb = AppConfig.CreateConnectionStringBuilder(); csb.PersistSecurityInfo = persistSecurityInfo; var connectionStringWithoutPassword = Regex.Replace(csb.ConnectionString, @"(?i)password='?" + Regex.Escape(csb.Password) + "'?;?", ""); using var connection = new MySqlConnection(csb.ConnectionString); Assert.Equal(csb.ConnectionString, connection.ConnectionString); connection.Open(); if (persistSecurityInfo) Assert.Equal(csb.ConnectionString, connection.ConnectionString); else Assert.Equal(connectionStringWithoutPassword, connection.ConnectionString); if (closeConnection) { connection.Close(); if (persistSecurityInfo) Assert.Equal(csb.ConnectionString, connection.ConnectionString); else Assert.Equal(connectionStringWithoutPassword, connection.ConnectionString); } } [Fact] public void State() { using var connection = new MySqlConnection(m_database.Connection.ConnectionString); Assert.Equal(ConnectionState.Closed, connection.State); connection.Open(); Assert.Equal(ConnectionState.Open, connection.State); connection.Close(); Assert.Equal(ConnectionState.Closed, connection.State); connection.Open(); Assert.Equal(ConnectionState.Open, connection.State); } [Fact] public void DataSource() { using (var connection = new MySqlConnection()) { Assert.Equal("", connection.DataSource); } using (var connection = new MySqlConnection(m_database.Connection.ConnectionString)) { Assert.NotNull(connection.DataSource); } } [SkippableFact(ConfigSettings.TcpConnection, Baseline = "https://bugs.mysql.com/bug.php?id=81650")] public void ConnectMultipleHostNames() { var csb = AppConfig.CreateConnectionStringBuilder(); csb.Server = "invalid.example.net," + csb.Server; using var connection = new MySqlConnection(csb.ConnectionString); Assert.Equal(ConnectionState.Closed, connection.State); connection.Open(); Assert.Equal(ConnectionState.Open, connection.State); } [SkippableFact(ConfigSettings.PasswordlessUser)] public void ConnectNoPassword() { var csb = AppConfig.CreateConnectionStringBuilder(); csb.UserID = AppConfig.PasswordlessUser; csb.Password = ""; csb.Database = ""; using var connection = new MySqlConnection(csb.ConnectionString); Assert.Equal(ConnectionState.Closed, connection.State); connection.Open(); Assert.Equal(ConnectionState.Open, connection.State); } [SkippableFact(ConfigSettings.PasswordlessUser)] public void ConnectionPoolNoPassword() { var csb = AppConfig.CreateConnectionStringBuilder(); csb.UserID = AppConfig.PasswordlessUser; csb.Password = ""; csb.Database = ""; csb.Pooling = true; csb.MinimumPoolSize = 0; csb.MaximumPoolSize = 5; for (int i = 0; i < 3; i++) { using var connection = new MySqlConnection(csb.ConnectionString); Assert.Equal(ConnectionState.Closed, connection.State); connection.Open(); Assert.Equal(ConnectionState.Open, connection.State); } } [SkippableFact(ServerFeatures.Timeout)] public void ConnectTimeout() { var csb = new MySqlConnectionStringBuilder { Server = "www.mysql.com", Pooling = false, ConnectionTimeout = 3, }; using var connection = new MySqlConnection(csb.ConnectionString); var stopwatch = Stopwatch.StartNew(); Assert.Throws<MySqlException>(() => connection.Open()); stopwatch.Stop(); TestUtilities.AssertDuration(stopwatch, 2900, 1500); } #if !BASELINE [Fact] public void UsePasswordProvider() { var csb = AppConfig.CreateConnectionStringBuilder(); var password = csb.Password; csb.Password = null; using var connection = new MySqlConnection(csb.ConnectionString); MySqlConnection.ClearPool(connection); var wasCalled = false; connection.ProvidePasswordCallback = x => { Assert.Equal(csb.Server, x.Server); Assert.Equal((int) csb.Port, x.Port); Assert.Equal(csb.UserID, x.UserId); Assert.Equal(csb.Database, x.Database); wasCalled = true; return password; }; connection.Open(); Assert.True(wasCalled); } [Fact] public void UsePasswordProviderPasswordTakesPrecedence() { var csb = AppConfig.CreateConnectionStringBuilder(); var password = csb.Password; using var connection = new MySqlConnection(csb.ConnectionString); MySqlConnection.ClearPool(connection); var wasCalled = false; connection.ProvidePasswordCallback = _ => { wasCalled = true; return password; }; connection.Open(); Assert.False(wasCalled); } [Fact] public void UsePasswordProviderWithBadPassword() { var csb = AppConfig.CreateConnectionStringBuilder(); var password = csb.Password; csb.Password = null; using var connection = new MySqlConnection(csb.ConnectionString); MySqlConnection.ClearPool(connection); connection.ProvidePasswordCallback = _ => $"wrong_{password}"; var ex = Assert.Throws<MySqlException>(() => connection.Open()); Assert.Equal(MySqlErrorCode.AccessDenied, ex.ErrorCode); } [Fact] public void UsePasswordProviderWithException() { var csb = AppConfig.CreateConnectionStringBuilder(); var password = csb.Password; csb.Password = null; csb.ConnectionTimeout = 60; using var connection = new MySqlConnection(csb.ConnectionString); MySqlConnection.ClearPool(connection); var innerException = new NotSupportedException(); connection.ProvidePasswordCallback = _ => throw innerException; var ex = Assert.Throws<MySqlException>(() => connection.Open()); Assert.Equal(MySqlErrorCode.ProvidePasswordCallbackFailed, ex.ErrorCode); Assert.Same(innerException, ex.InnerException); } [Fact] public void UsePasswordProviderClone() { var csb = AppConfig.CreateConnectionStringBuilder(); var password = csb.Password; csb.Password = null; using var connection = new MySqlConnection(csb.ConnectionString); MySqlConnection.ClearPool(connection); connection.ProvidePasswordCallback = _ => password; using var clonedConnection = connection.Clone(); clonedConnection.Open(); Assert.Equal(ConnectionState.Closed, connection.State); Assert.Equal(ConnectionState.Open, clonedConnection.State); } [SkippableFact(ServerFeatures.ResetConnection)] public void UsePasswordProviderWithMinimumPoolSize() { var csb = AppConfig.CreateConnectionStringBuilder(); var password = csb.Password; csb.Password = null; csb.MinimumPoolSize = 3; csb.MaximumPoolSize = 102; using var connection = new MySqlConnection(csb.ConnectionString); MySqlConnection.ClearPool(connection); var invocationCount = 0; connection.ProvidePasswordCallback = _ => { invocationCount++; return password; }; connection.Open(); Assert.Equal((int) csb.MinimumPoolSize, invocationCount); } #endif [Fact] public void ConnectionDatabase() { var csb = AppConfig.CreateConnectionStringBuilder(); using var connection = new MySqlConnection(csb.ConnectionString); Assert.Equal(csb.Database, connection.Database); connection.Open(); Assert.Equal(csb.Database, connection.Database); Assert.Equal(csb.Database, QueryCurrentDatabase(connection)); } [SkippableFact(ConfigSettings.SecondaryDatabase)] public void ChangeDatabase() { var csb = AppConfig.CreateConnectionStringBuilder(); using var connection = new MySqlConnection(csb.ConnectionString); connection.Open(); Assert.Equal(csb.Database, connection.Database); Assert.Equal(csb.Database, QueryCurrentDatabase(connection)); connection.ChangeDatabase(AppConfig.SecondaryDatabase); Assert.Equal(AppConfig.SecondaryDatabase, connection.Database); Assert.Equal(AppConfig.SecondaryDatabase, QueryCurrentDatabase(connection)); } [SkippableFact(ConfigSettings.SecondaryDatabase)] public void ChangeDatabaseNotOpen() { var csb = AppConfig.CreateConnectionStringBuilder(); using var connection = new MySqlConnection(csb.ConnectionString); Assert.Throws<InvalidOperationException>(() => connection.ChangeDatabase(AppConfig.SecondaryDatabase)); } [SkippableFact(ConfigSettings.SecondaryDatabase)] public void ChangeDatabaseNull() { var csb = AppConfig.CreateConnectionStringBuilder(); using var connection = new MySqlConnection(csb.ConnectionString); Assert.Throws<ArgumentException>(() => connection.ChangeDatabase(null)); Assert.Throws<ArgumentException>(() => connection.ChangeDatabase("")); } [SkippableFact(ConfigSettings.SecondaryDatabase)] public void ChangeDatabaseInvalidName() { var csb = AppConfig.CreateConnectionStringBuilder(); using var connection = new MySqlConnection(csb.ConnectionString); connection.Open(); Assert.Throws<MySqlException>(() => connection.ChangeDatabase($"not_a_real_database_1234")); Assert.Equal(ConnectionState.Open, connection.State); Assert.Equal(csb.Database, connection.Database); Assert.Equal(csb.Database, QueryCurrentDatabase(connection)); } [SkippableFact(ConfigSettings.SecondaryDatabase)] public void ChangeDatabaseConnectionPooling() { var csb = AppConfig.CreateConnectionStringBuilder(); csb.Pooling = true; csb.MinimumPoolSize = 0; csb.MaximumPoolSize = 6; for (int i = 0; i < csb.MaximumPoolSize * 2; i++) { using var connection = new MySqlConnection(csb.ConnectionString); connection.Open(); Assert.Equal(csb.Database, connection.Database); Assert.Equal(csb.Database, QueryCurrentDatabase(connection)); connection.ChangeDatabase(AppConfig.SecondaryDatabase); Assert.Equal(AppConfig.SecondaryDatabase, connection.Database); Assert.Equal(AppConfig.SecondaryDatabase, QueryCurrentDatabase(connection)); } } [SkippableFact(ServerFeatures.SessionTrack, ConfigSettings.SecondaryDatabase, Baseline = "https://bugs.mysql.com/bug.php?id=89085")] public void UseDatabase() { var csb = AppConfig.CreateConnectionStringBuilder(); using var connection = new MySqlConnection(csb.ConnectionString); connection.Open(); Assert.Equal(csb.Database, connection.Database); Assert.Equal(csb.Database, QueryCurrentDatabase(connection)); using (var cmd = connection.CreateCommand()) { cmd.CommandText = $"USE {AppConfig.SecondaryDatabase};"; cmd.ExecuteNonQuery(); } Assert.Equal(AppConfig.SecondaryDatabase, connection.Database); Assert.Equal(AppConfig.SecondaryDatabase, QueryCurrentDatabase(connection)); } [SkippableFact(ConfigSettings.SecondaryDatabase)] public void ChangeDatabaseInTransaction() { var csb = AppConfig.CreateConnectionStringBuilder(); using var connection = new MySqlConnection(csb.ConnectionString); connection.Open(); connection.Execute($@"drop table if exists changedb1; create table changedb1(value int not null); drop table if exists `{AppConfig.SecondaryDatabase}`.changedb2; create table `{AppConfig.SecondaryDatabase}`.changedb2(value int not null);"); using var transaction = connection.BeginTransaction(); #if !BASELINE Assert.Equal(transaction, connection.CurrentTransaction); #endif using (var command = new MySqlCommand("SELECT 'abc';", connection, transaction)) Assert.Equal("abc", command.ExecuteScalar()); using (var command = new MySqlCommand("INSERT INTO changedb1(value) values(1),(2);", connection, transaction)) command.ExecuteNonQuery(); connection.ChangeDatabase(AppConfig.SecondaryDatabase); #if !BASELINE Assert.Equal(transaction, connection.CurrentTransaction); #endif using (var command = new MySqlCommand("SELECT 'abc';", connection, transaction)) Assert.Equal("abc", command.ExecuteScalar()); using (var command = new MySqlCommand("INSERT INTO changedb2(value) values(3),(4);", connection, transaction)) command.ExecuteNonQuery(); transaction.Commit(); using var connection2 = new MySqlConnection(csb.ConnectionString); connection2.Open(); var values = connection2.Query<int>($@"SELECT value FROM changedb1 UNION SELECT value FROM `{AppConfig.SecondaryDatabase}`.changedb2", connection2).OrderBy(x => x).ToList(); Assert.Equal(new[] { 1, 2, 3, 4 }, values); } private static string QueryCurrentDatabase(MySqlConnection connection) { using var cmd = connection.CreateCommand(); cmd.CommandText = "SELECT DATABASE()"; return (string) cmd.ExecuteScalar(); } [SkippableFact(ConfigSettings.SecondaryDatabase)] public void ChangeConnectionStringWhenOpen() { var csb = AppConfig.CreateConnectionStringBuilder(); using var connection = new MySqlConnection(csb.ConnectionString); connection.Open(); Assert.Equal(csb.Database, connection.Database); csb.Database = AppConfig.SecondaryDatabase; #if BASELINE Assert.Throws<MySqlException>(() => #else Assert.Throws<InvalidOperationException>(() => #endif { connection.ConnectionString = csb.ConnectionString; }); } [SkippableFact(ConfigSettings.SecondaryDatabase)] public void ChangeConnectionStringAfterClose() { var csb = AppConfig.CreateConnectionStringBuilder(); using var connection = new MySqlConnection(csb.ConnectionString); connection.Open(); Assert.Equal(csb.Database, connection.Database); connection.Close(); csb.Database = AppConfig.SecondaryDatabase; connection.ConnectionString = csb.ConnectionString; connection.Open(); Assert.Equal(csb.Database, connection.Database); connection.Close(); } [SkippableFact(ServerFeatures.Sha256Password, ConfigSettings.RequiresSsl)] public void Sha256WithSecureConnection() { var csb = AppConfig.CreateSha256ConnectionStringBuilder(); using var connection = new MySqlConnection(csb.ConnectionString); connection.Open(); } [SkippableFact(ServerFeatures.Sha256Password)] public void Sha256WithoutSecureConnection() { var csb = AppConfig.CreateSha256ConnectionStringBuilder(); csb.SslMode = MySqlSslMode.None; csb.AllowPublicKeyRetrieval = true; using var connection = new MySqlConnection(csb.ConnectionString); #if NET45 Assert.Throws<NotImplementedException>(() => connection.Open()); #else if (AppConfig.SupportedFeatures.HasFlag(ServerFeatures.RsaEncryption)) connection.Open(); else Assert.Throws<MySqlException>(() => connection.Open()); #endif } [Fact] public void PingNoConnection() { using var connection = new MySqlConnection(); Assert.False(connection.Ping()); } [Fact] public void PingBeforeConnecting() { using var connection = new MySqlConnection(AppConfig.ConnectionString); Assert.False(connection.Ping()); } [Fact] public void PingConnection() { using var connection = new MySqlConnection(AppConfig.ConnectionString); connection.Open(); Assert.True(connection.Ping()); } [SkippableFact(ServerFeatures.UnixDomainSocket)] public void UnixDomainSocket() { var csb = AppConfig.CreateConnectionStringBuilder(); csb.Server = AppConfig.SocketPath; csb.ConnectionProtocol = MySqlConnectionProtocol.Unix; using var connection = new MySqlConnection(csb.ConnectionString); connection.Open(); Assert.Equal(ConnectionState.Open, connection.State); } readonly DatabaseFixture m_database; }
using System; using System.Collections.Generic; using UnityEditor.AnimatedValues; using UnityEditor.Rendering; using UnityEngine; namespace UnityEditor.Experimental.Rendering.HDPipeline { [Flags] public enum FoldoutOption { None = 0, Indent = 1 << 0, Boxed = 1 << 2, SubFoldout = 1 << 3, NoSpaceAtEnd = 1 << 4 } [Flags] public enum GroupOption { None = 0, Indent = 1 << 0 } /// <summary> /// Utility class to draw inspectors /// </summary> /// <typeparam name="TData">Type of class containing data needed to draw inspector</typeparam> public static class CoreEditorDrawer<TData> { /// <summary> Abstraction that have the Draw hability </summary> public interface IDrawer { void Draw(TData p, Editor owner); } public delegate bool Enabler(TData data, Editor owner); public delegate void SwitchEnabler(TData data, Editor owner); public delegate T2Data DataSelect<T2Data>(TData data, Editor owner); public delegate void ActionDrawer(TData data, Editor owner); /// <summary> Equivalent to EditorGUILayout.Space that can be put in a drawer group </summary> public static readonly IDrawer space = Group((data, owner) => EditorGUILayout.Space()); /// <summary> Use it when IDrawer required but no operation should be done </summary> public static readonly IDrawer noop = Group((data, owner) => { }); /// <summary> /// Conditioned drawer that will only be drawn if its enabler function is null or return true /// </summary> /// <param name="enabler">Enable the drawing if null or return true</param> /// <param name="contentDrawers">The content of the group</param> public static IDrawer Conditional(Enabler enabler, params IDrawer[] contentDrawers) { return new ConditionalDrawerInternal(enabler, contentDrawers.Draw); } /// <summary> /// Conditioned drawer that will only be drawn if its enabler function is null or return true /// </summary> /// <param name="enabler">Enable the drawing if null or return true</param> /// <param name="contentDrawers">The content of the group</param> public static IDrawer Conditional(Enabler enabler, params ActionDrawer[] contentDrawers) { return new ConditionalDrawerInternal(enabler, contentDrawers); } class ConditionalDrawerInternal : IDrawer { ActionDrawer[] actionDrawers { get; set; } Enabler m_Enabler; public ConditionalDrawerInternal(Enabler enabler = null, params ActionDrawer[] actionDrawers) { this.actionDrawers = actionDrawers; m_Enabler = enabler; } void IDrawer.Draw(TData data, Editor owner) { if (m_Enabler != null && !m_Enabler(data, owner)) return; for (var i = 0; i < actionDrawers.Length; i++) actionDrawers[i](data, owner); } } /// <summary> /// Group of drawing function for inspector. /// They will be drawn one after the other. /// </summary> /// <param name="contentDrawers">The content of the group</param> public static IDrawer Group(params IDrawer[] contentDrawers) { return new GroupDrawerInternal(-1f, GroupOption.None, contentDrawers.Draw); } /// <summary> /// Group of drawing function for inspector. /// They will be drawn one after the other. /// </summary> /// <param name="contentDrawers">The content of the group</param> public static IDrawer Group(params ActionDrawer[] contentDrawers) { return new GroupDrawerInternal(-1f, GroupOption.None, contentDrawers); } /// <summary> Group of drawing function for inspector with a set width for labels </summary> /// <param name="labelWidth">Width used for all labels in the group</param> /// <param name="contentDrawers">The content of the group</param> public static IDrawer Group(float labelWidth, params IDrawer[] contentDrawers) { return new GroupDrawerInternal(labelWidth, GroupOption.None, contentDrawers.Draw); } /// <summary> Group of drawing function for inspector with a set width for labels </summary> /// <param name="labelWidth">Width used for all labels in the group</param> /// <param name="contentDrawers">The content of the group</param> public static IDrawer Group(float labelWidth, params ActionDrawer[] contentDrawers) { return new GroupDrawerInternal(labelWidth, GroupOption.None, contentDrawers); } /// <summary> /// Group of drawing function for inspector. /// They will be drawn one after the other. /// </summary> /// <param name="options">Allow to add indentation on this group</param> /// <param name="contentDrawers">The content of the group</param> public static IDrawer Group(GroupOption options, params IDrawer[] contentDrawers) { return new GroupDrawerInternal(-1f, options, contentDrawers.Draw); } /// <summary> /// Group of drawing function for inspector. /// They will be drawn one after the other. /// </summary> /// <param name="options">Allow to add indentation on this group</param> /// <param name="contentDrawers">The content of the group</param> public static IDrawer Group(GroupOption options, params ActionDrawer[] contentDrawers) { return new GroupDrawerInternal(-1f, options, contentDrawers); } /// <summary> Group of drawing function for inspector with a set width for labels </summary> /// <param name="labelWidth">Width used for all labels in the group</param> /// <param name="options">Allow to add indentation on this group</param> /// <param name="contentDrawers">The content of the group</param> public static IDrawer Group(float labelWidth, GroupOption options, params IDrawer[] contentDrawers) { return new GroupDrawerInternal(labelWidth, options, contentDrawers.Draw); } /// <summary> Group of drawing function for inspector with a set width for labels </summary> /// <param name="labelWidth">Width used for all labels in the group</param> /// <param name="options">Allow to add indentation on this group</param> /// <param name="contentDrawers">The content of the group</param> public static IDrawer Group(float labelWidth, GroupOption options, params ActionDrawer[] contentDrawers) { return new GroupDrawerInternal(labelWidth, options, contentDrawers); } class GroupDrawerInternal : IDrawer { ActionDrawer[] actionDrawers { get; set; } float m_LabelWidth; bool isIndented; public GroupDrawerInternal(float labelWidth = -1f, GroupOption options = GroupOption.None, params ActionDrawer[] actionDrawers) { this.actionDrawers = actionDrawers; m_LabelWidth = labelWidth; isIndented = (options & GroupOption.Indent) != 0; } void IDrawer.Draw(TData data, Editor owner) { if (isIndented) ++EditorGUI.indentLevel; var currentLabelWidth = EditorGUIUtility.labelWidth; if (m_LabelWidth >= 0f) { EditorGUIUtility.labelWidth = m_LabelWidth; } for (var i = 0; i < actionDrawers.Length; i++) actionDrawers[i](data, owner); if (m_LabelWidth >= 0f) { EditorGUIUtility.labelWidth = currentLabelWidth; } if (isIndented) --EditorGUI.indentLevel; } } /// <summary> Create an IDrawer based on an other data container </summary> /// <param name="dataSelect">The data new source for the inner drawers</param> /// <param name="otherDrawers">Inner drawers drawed with given data sources</param> /// <returns></returns> public static IDrawer Select<T2Data>( DataSelect<T2Data> dataSelect, params CoreEditorDrawer<T2Data>.IDrawer[] otherDrawers) { return new SelectDrawerInternal<T2Data>(dataSelect, otherDrawers.Draw); } /// <summary> Create an IDrawer based on an other data container </summary> /// <param name="dataSelect">The data new source for the inner drawers</param> /// <param name="otherDrawers">Inner drawers drawed with given data sources</param> /// <returns></returns> public static IDrawer Select<T2Data>( DataSelect<T2Data> dataSelect, params CoreEditorDrawer<T2Data>.ActionDrawer[] otherDrawers) { return new SelectDrawerInternal<T2Data>(dataSelect, otherDrawers); } class SelectDrawerInternal<T2Data> : IDrawer { DataSelect<T2Data> m_DataSelect; CoreEditorDrawer<T2Data>.ActionDrawer[] m_SourceDrawers; public SelectDrawerInternal(DataSelect<T2Data> dataSelect, params CoreEditorDrawer<T2Data>.ActionDrawer[] otherDrawers) { m_SourceDrawers = otherDrawers; m_DataSelect = dataSelect; } void IDrawer.Draw(TData data, Editor o) { var p2 = m_DataSelect(data, o); for (var i = 0; i < m_SourceDrawers.Length; i++) m_SourceDrawers[i](p2, o); } } /// <summary> /// Create an IDrawer foldout header using an ExpandedState. /// The default option is Indent in this version. /// </summary> /// <param name="title">Title wanted for this foldout header</param> /// <param name="mask">Bit mask (enum) used to define the boolean saving the state in ExpandedState</param> /// <param name="state">The ExpandedState describing the component</param> /// <param name="contentDrawers">The content of the foldout header</param> public static IDrawer FoldoutGroup<TEnum, TState>(string title, TEnum mask, ExpandedState<TEnum, TState> state, params IDrawer[] contentDrawers) where TEnum : struct, IConvertible { return FoldoutGroup(title, mask, state, contentDrawers.Draw); } /// <summary> /// Create an IDrawer foldout header using an ExpandedState. /// The default option is Indent in this version. /// </summary> /// <param name="title">Title wanted for this foldout header</param> /// <param name="mask">Bit mask (enum) used to define the boolean saving the state in ExpandedState</param> /// <param name="state">The ExpandedState describing the component</param> /// <param name="contentDrawers">The content of the foldout header</param> public static IDrawer FoldoutGroup<TEnum, TState>(string title, TEnum mask, ExpandedState<TEnum, TState> state, params ActionDrawer[] contentDrawers) where TEnum : struct, IConvertible { return FoldoutGroup(EditorGUIUtility.TrTextContent(title), mask, state, contentDrawers); } /// <summary> Create an IDrawer foldout header using an ExpandedState </summary> /// <param name="title">Title wanted for this foldout header</param> /// <param name="mask">Bit mask (enum) used to define the boolean saving the state in ExpandedState</param> /// <param name="state">The ExpandedState describing the component</param> /// <param name="contentDrawers">The content of the foldout header</param> public static IDrawer FoldoutGroup<TEnum, TState>(string title, TEnum mask, ExpandedState<TEnum, TState> state, FoldoutOption options, params IDrawer[] contentDrawers) where TEnum : struct, IConvertible { return FoldoutGroup(title, mask, state, options, contentDrawers.Draw); } /// <summary> Create an IDrawer foldout header using an ExpandedState </summary> /// <param name="title">Title wanted for this foldout header</param> /// <param name="mask">Bit mask (enum) used to define the boolean saving the state in ExpandedState</param> /// <param name="state">The ExpandedState describing the component</param> /// <param name="contentDrawers">The content of the foldout header</param> public static IDrawer FoldoutGroup<TEnum, TState>(string title, TEnum mask, ExpandedState<TEnum, TState> state, FoldoutOption options, params ActionDrawer[] contentDrawers) where TEnum : struct, IConvertible { return FoldoutGroup(EditorGUIUtility.TrTextContent(title), mask, state, options, contentDrawers); } /// <summary> /// Create an IDrawer foldout header using an ExpandedState. /// The default option is Indent in this version. /// </summary> /// <param name="title">Title wanted for this foldout header</param> /// <param name="mask">Bit mask (enum) used to define the boolean saving the state in ExpandedState</param> /// <param name="state">The ExpandedState describing the component</param> /// <param name="contentDrawers">The content of the foldout header</param> public static IDrawer FoldoutGroup<TEnum, TState>(GUIContent title, TEnum mask, ExpandedState<TEnum, TState> state, params IDrawer[] contentDrawers) where TEnum : struct, IConvertible { return FoldoutGroup(title, mask, state, contentDrawers.Draw); } /// <summary> /// Create an IDrawer foldout header using an ExpandedState. /// The default option is Indent in this version. /// </summary> /// <param name="title">Title wanted for this foldout header</param> /// <param name="mask">Bit mask (enum) used to define the boolean saving the state in ExpandedState</param> /// <param name="state">The ExpandedState describing the component</param> /// <param name="contentDrawers">The content of the foldout header</param> public static IDrawer FoldoutGroup<TEnum, TState>(GUIContent title, TEnum mask, ExpandedState<TEnum, TState> state, params ActionDrawer[] contentDrawers) where TEnum : struct, IConvertible { return FoldoutGroup(title, mask, state, FoldoutOption.Indent, contentDrawers); } /// <summary> Create an IDrawer foldout header using an ExpandedState </summary> /// <param name="title">Title wanted for this foldout header</param> /// <param name="mask">Bit mask (enum) used to define the boolean saving the state in ExpandedState</param> /// <param name="state">The ExpandedState describing the component</param> /// <param name="contentDrawers">The content of the foldout header</param> public static IDrawer FoldoutGroup<TEnum, TState>(GUIContent title, TEnum mask, ExpandedState<TEnum, TState> state, FoldoutOption options, params IDrawer[] contentDrawers) where TEnum : struct, IConvertible { return FoldoutGroup(title, mask, state, options, contentDrawers.Draw); } /// <summary> Create an IDrawer foldout header using an ExpandedState </summary> /// <param name="title">Title wanted for this foldout header</param> /// <param name="mask">Bit mask (enum) used to define the boolean saving the state in ExpandedState</param> /// <param name="state">The ExpandedState describing the component</param> /// <param name="contentDrawers">The content of the foldout header</param> public static IDrawer FoldoutGroup<TEnum, TState>(GUIContent title, TEnum mask, ExpandedState<TEnum, TState> state, FoldoutOption options, params ActionDrawer[] contentDrawers) where TEnum : struct, IConvertible { return FoldoutGroup(title, mask, state, options, null, null, contentDrawers); } // This one is private as we do not want to have unhandled advanced switch. Change it if necessary. static IDrawer FoldoutGroup<TEnum, TState>(GUIContent title, TEnum mask, ExpandedState<TEnum, TState> state, FoldoutOption options, Enabler isAdvanced, SwitchEnabler switchAdvanced, params ActionDrawer[] contentDrawers) where TEnum : struct, IConvertible { return Group((data, owner) => { bool isBoxed = (options & FoldoutOption.Boxed) != 0; bool isIndented = (options & FoldoutOption.Indent) != 0; bool isSubFoldout = (options & FoldoutOption.SubFoldout) != 0; bool noSpaceAtEnd = (options & FoldoutOption.NoSpaceAtEnd) != 0; bool expended = state[mask]; bool newExpended = expended; if (isSubFoldout) { newExpended = CoreEditorUtils.DrawSubHeaderFoldout(title, expended, isBoxed, isAdvanced == null ? (Func<bool>)null : () => isAdvanced(data, owner), switchAdvanced == null ? (Action)null : () => switchAdvanced(data, owner)); } else { CoreEditorUtils.DrawSplitter(isBoxed); newExpended = CoreEditorUtils.DrawHeaderFoldout(title, expended, isBoxed, isAdvanced == null ? (Func<bool>)null : () => isAdvanced(data, owner), switchAdvanced == null ? (Action)null : () => switchAdvanced(data, owner)); } if (newExpended ^ expended) state[mask] = newExpended; if (newExpended) { if (isIndented) ++EditorGUI.indentLevel; for (var i = 0; i < contentDrawers.Length; i++) contentDrawers[i](data, owner); if (isIndented) --EditorGUI.indentLevel; if (!noSpaceAtEnd) EditorGUILayout.Space(); } }); } /// <summary> Helper to draw a foldout with an advanced switch on it. </summary> /// <param name="title">Title wanted for this foldout header</param> /// <param name="mask">Bit mask (enum) used to define the boolean saving the state in ExpandedState</param> /// <param name="state">The ExpandedState describing the component</param> /// <param name="isAdvanced"> Delegate allowing to check if advanced mode is active. </param> /// <param name="switchAdvanced"> Delegate to know what to do when advance is switched. </param> /// <param name="normalContent"> The content of the foldout header always visible if expended. </param> /// <param name="advancedContent"> The content of the foldout header only visible if advanced mode is active and if foldout is expended. </param> public static IDrawer AdvancedFoldoutGroup<TEnum, TState>(GUIContent foldoutTitle, TEnum foldoutMask, ExpandedState<TEnum, TState> foldoutState, Enabler isAdvanced, SwitchEnabler switchAdvanced, IDrawer normalContent, IDrawer advancedContent, FoldoutOption options = FoldoutOption.Indent) where TEnum : struct, IConvertible { return AdvancedFoldoutGroup(foldoutTitle, foldoutMask, foldoutState, isAdvanced, switchAdvanced, normalContent.Draw, advancedContent.Draw, options); } /// <summary> Helper to draw a foldout with an advanced switch on it. </summary> /// <param name="title">Title wanted for this foldout header</param> /// <param name="mask">Bit mask (enum) used to define the boolean saving the state in ExpandedState</param> /// <param name="state">The ExpandedState describing the component</param> /// <param name="isAdvanced"> Delegate allowing to check if advanced mode is active. </param> /// <param name="switchAdvanced"> Delegate to know what to do when advance is switched. </param> /// <param name="normalContent"> The content of the foldout header always visible if expended. </param> /// <param name="advancedContent"> The content of the foldout header only visible if advanced mode is active and if foldout is expended. </param> public static IDrawer AdvancedFoldoutGroup<TEnum, TState>(GUIContent foldoutTitle, TEnum foldoutMask, ExpandedState<TEnum, TState> foldoutState, Enabler isAdvanced, SwitchEnabler switchAdvanced, ActionDrawer normalContent, IDrawer advancedContent, FoldoutOption options = FoldoutOption.Indent) where TEnum : struct, IConvertible { return AdvancedFoldoutGroup(foldoutTitle, foldoutMask, foldoutState, isAdvanced, switchAdvanced, normalContent, advancedContent.Draw, options); } /// <summary> Helper to draw a foldout with an advanced switch on it. </summary> /// <param name="title">Title wanted for this foldout header</param> /// <param name="mask">Bit mask (enum) used to define the boolean saving the state in ExpandedState</param> /// <param name="state">The ExpandedState describing the component</param> /// <param name="isAdvanced"> Delegate allowing to check if advanced mode is active. </param> /// <param name="switchAdvanced"> Delegate to know what to do when advance is switched. </param> /// <param name="normalContent"> The content of the foldout header always visible if expended. </param> /// <param name="advancedContent"> The content of the foldout header only visible if advanced mode is active and if foldout is expended. </param> public static IDrawer AdvancedFoldoutGroup<TEnum, TState>(GUIContent foldoutTitle, TEnum foldoutMask, ExpandedState<TEnum, TState> foldoutState, Enabler isAdvanced, SwitchEnabler switchAdvanced, IDrawer normalContent, ActionDrawer advancedContent, FoldoutOption options = FoldoutOption.Indent) where TEnum : struct, IConvertible { return AdvancedFoldoutGroup(foldoutTitle, foldoutMask, foldoutState, isAdvanced, switchAdvanced, normalContent.Draw, advancedContent, options); } /// <summary> Helper to draw a foldout with an advanced switch on it. </summary> /// <param name="title">Title wanted for this foldout header</param> /// <param name="mask">Bit mask (enum) used to define the boolean saving the state in ExpandedState</param> /// <param name="state">The ExpandedState describing the component</param> /// <param name="isAdvanced"> Delegate allowing to check if advanced mode is active. </param> /// <param name="switchAdvanced"> Delegate to know what to do when advance is switched. </param> /// <param name="normalContent"> The content of the foldout header always visible if expended. </param> /// <param name="advancedContent"> The content of the foldout header only visible if advanced mode is active and if foldout is expended. </param> public static IDrawer AdvancedFoldoutGroup<TEnum, TState>(GUIContent foldoutTitle, TEnum foldoutMask, ExpandedState<TEnum, TState> foldoutState, Enabler isAdvanced, SwitchEnabler switchAdvanced, ActionDrawer normalContent, ActionDrawer advancedContent, FoldoutOption options = FoldoutOption.Indent) where TEnum : struct, IConvertible { return FoldoutGroup(foldoutTitle, foldoutMask, foldoutState, options, isAdvanced, switchAdvanced, normalContent, Conditional((serialized, owner) => isAdvanced(serialized, owner) && foldoutState[foldoutMask], advancedContent).Draw ); } } public static class CoreEditorDrawersExtensions { /// <summary> Concatenate a collection of IDrawer as a unique IDrawer </summary> public static void Draw<TData>(this IEnumerable<CoreEditorDrawer<TData>.IDrawer> drawers, TData data, Editor owner) { foreach (var drawer in drawers) drawer.Draw(data, owner); } } }
// --------------------------------------------------------------------------- // <copyright file="IsamDatabase.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // --------------------------------------------------------------------------- // --------------------------------------------------------------------- // <summary> // </summary> // --------------------------------------------------------------------- namespace Microsoft.Database.Isam { using System; using Microsoft.Isam.Esent.Interop; /// <summary> /// A Database is a file used by the ISAM to store data. It is organized /// into tables which are in turn comprised of columns and indices and /// contain data in the form of records. The database's schema can be /// enumerated and manipulated by this object. Also, the database's /// tables can be opened for access by this object. /// </summary> public class IsamDatabase : DatabaseCommon, IDisposable { /// <summary> /// The dbid /// </summary> private readonly JET_DBID dbid; /// <summary> /// The table collection /// </summary> private TableCollection tableCollection = null; /// <summary> /// The cleanup /// </summary> private bool cleanup = false; /// <summary> /// The disposed /// </summary> private bool disposed = false; /// <summary> /// Initializes a new instance of the <see cref="IsamDatabase"/> class. /// </summary> /// <param name="isamSession">The session.</param> /// <param name="databaseName">Name of the database.</param> internal IsamDatabase(IsamSession isamSession, string databaseName) : base(isamSession) { lock (isamSession) { Api.JetOpenDatabase(isamSession.Sesid, databaseName, null, out this.dbid, OpenDatabaseGrbit.None); this.cleanup = true; this.tableCollection = new TableCollection(this); } } /// <summary> /// Finalizes an instance of the IsamDatabase class /// </summary> ~IsamDatabase() { this.Dispose(false); } /// <summary> /// Gets a collection of tables in the database. /// </summary> /// <returns>a collection of tables in the database</returns> public override TableCollection Tables { get { this.CheckDisposed(); return this.tableCollection; } } /// <summary> /// Gets the dbid. /// </summary> /// <value> /// The dbid. /// </value> internal JET_DBID Dbid { get { return this.dbid; } } /// <summary> /// Gets or sets a value indicating whether [disposed]. /// </summary> /// <value> /// <c>true</c> if [disposed]; otherwise, <c>false</c>. /// </value> internal override bool Disposed { get { return this.disposed || this.IsamSession.Disposed; } set { this.disposed = value; } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public new void Dispose() { lock (this) { this.Dispose(true); } GC.SuppressFinalize(this); } /// <summary> /// Creates a single table with the specified definition in the database /// </summary> /// <param name="tableDefinition">The table definition.</param> public override void CreateTable(TableDefinition tableDefinition) { lock (this.IsamSession) { this.CheckDisposed(); using (IsamTransaction trx = new IsamTransaction(this.IsamSession)) { // FUTURE-2013/11/15-martinc: Consider using JetCreateTableColumnIndex(). It would be // a bit faster because it's only a single managed/native transition. // Hard-code the initial space and density. JET_TABLEID tableid; Api.JetCreateTable(this.IsamSession.Sesid, this.dbid, tableDefinition.Name, 16, 90, out tableid); foreach (ColumnDefinition columnDefinition in tableDefinition.Columns) { JET_COLUMNDEF columndef = new JET_COLUMNDEF(); columndef.coltyp = IsamDatabase.ColtypFromColumnDefinition(columnDefinition); columndef.cp = JET_CP.Unicode; columndef.cbMax = columnDefinition.MaxLength; columndef.grbit = Converter.ColumndefGrbitFromColumnFlags(columnDefinition.Flags); byte[] defaultValueBytes = Converter.BytesFromObject( columndef.coltyp, false /*ASCII */, columnDefinition.DefaultValue); JET_COLUMNID columnid; int defaultValueLength = (defaultValueBytes == null) ? 0 : defaultValueBytes.Length; Api.JetAddColumn( this.IsamSession.Sesid, tableid, columnDefinition.Name, columndef, defaultValueBytes, defaultValueLength, out columnid); } foreach (IndexDefinition indexDefinition in tableDefinition.Indices) { JET_INDEXCREATE[] indexcreates = new JET_INDEXCREATE[1]; indexcreates[0] = new JET_INDEXCREATE(); indexcreates[0].szIndexName = indexDefinition.Name; indexcreates[0].szKey = IsamDatabase.IndexKeyFromIndexDefinition(indexDefinition); indexcreates[0].cbKey = indexcreates[0].szKey.Length; indexcreates[0].grbit = IsamDatabase.GrbitFromIndexDefinition(indexDefinition); indexcreates[0].ulDensity = indexDefinition.Density; indexcreates[0].pidxUnicode = new JET_UNICODEINDEX(); indexcreates[0].pidxUnicode.lcid = indexDefinition.CultureInfo.LCID; indexcreates[0].pidxUnicode.dwMapFlags = (uint)Converter.UnicodeFlagsFromCompareOptions(indexDefinition.CompareOptions); indexcreates[0].rgconditionalcolumn = IsamDatabase.ConditionalColumnsFromIndexDefinition(indexDefinition); indexcreates[0].cConditionalColumn = indexcreates[0].rgconditionalcolumn.Length; indexcreates[0].cbKeyMost = indexDefinition.MaxKeyLength; Api.JetCreateIndex2(this.IsamSession.Sesid, tableid, indexcreates, indexcreates.Length); } // The initially-created tableid is opened exclusively. Api.JetCloseTable(this.IsamSession.Sesid, tableid); trx.Commit(); DatabaseCommon.SchemaUpdateID++; } } } /// <summary> /// Deletes a single table in the database. /// </summary> /// <param name="tableName">The name of the table to be deleted.</param> /// <remarks> /// It is currently not possible to delete a table that is being used /// by a Cursor. All such Cursors must be disposed before the /// table can be successfully deleted. /// </remarks> public override void DropTable(string tableName) { lock (this.IsamSession) { this.CheckDisposed(); Api.JetDeleteTable(this.IsamSession.Sesid, this.dbid, tableName); DatabaseCommon.SchemaUpdateID++; } } /// <summary> /// Determines if a given table exists in the database /// </summary> /// <param name="tableName">The name of the table to evaluate for existence.</param> /// <returns> /// true if the table was found, false otherwise /// </returns> public override bool Exists(string tableName) { this.CheckDisposed(); return this.Tables.Contains(tableName); } /// <summary> /// Opens a cursor over the specified table. /// </summary> /// <param name="tableName">the name of the table to be opened</param> /// <param name="exclusive">when true, the table will be opened for exclusive access</param> /// <returns>a cursor over the specified table in this database</returns> public Cursor OpenCursor(string tableName, bool exclusive) { lock (this.IsamSession) { this.CheckDisposed(); OpenTableGrbit grbit = exclusive ? OpenTableGrbit.DenyRead : OpenTableGrbit.None; return new Cursor(this.IsamSession, this, tableName, grbit); } } /// <summary> /// Opens a cursor over the specified table. /// </summary> /// <param name="tableName">the name of the table to be opened</param> /// <returns>a cursor over the specified table in this database</returns> public override Cursor OpenCursor(string tableName) { lock (this.IsamSession) { this.CheckDisposed(); return this.OpenCursor(tableName, false); } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> void IDisposable.Dispose() { this.Dispose(); } /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { lock (this.IsamSession) { if (!this.Disposed) { if (this.cleanup) { Api.JetCloseDatabase(this.IsamSession.Sesid, this.dbid, CloseDatabaseGrbit.None); base.Dispose(disposing); this.cleanup = false; } this.Disposed = true; } } } /// <summary> /// Checks the disposed. /// </summary> /// <exception cref="System.ObjectDisposedException"> /// Thrown when the object is already disposed. /// </exception> private void CheckDisposed() { lock (this.IsamSession) { if (this.Disposed) { throw new ObjectDisposedException(this.GetType().Name); } } } } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using DotSpatial.Data; using DotSpatial.Serialization; namespace DotSpatial.Symbology { /// <summary> /// Symbolizer for polygon features. /// </summary> public class PolygonSymbolizer : FeatureSymbolizer, IPolygonSymbolizer { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="PolygonSymbolizer"/> class. /// </summary> public PolygonSymbolizer() { Patterns = new CopyList<IPattern> { new SimplePattern() }; } /// <summary> /// Initializes a new instance of the <see cref="PolygonSymbolizer"/> class. /// </summary> /// <param name="fillColor">The color to use as a fill color.</param> public PolygonSymbolizer(Color fillColor) { Patterns = new CopyList<IPattern> { new SimplePattern(fillColor) }; } /// <summary> /// Initializes a new instance of the <see cref="PolygonSymbolizer"/> class. /// </summary> /// <param name="fillColor">The fill color to use for the polygons.</param> /// <param name="outlineColor">The border color to use for the polygons.</param> public PolygonSymbolizer(Color fillColor, Color outlineColor) : this(fillColor, outlineColor, 1) { } /// <summary> /// Initializes a new instance of the <see cref="PolygonSymbolizer"/> class using a solid fill pattern. /// </summary> /// <param name="fillColor">The fill color to use for the polygons.</param> /// <param name="outlineColor">The border color to use for the polygons.</param> /// <param name="outlineWidth">The width of the outline to use fo.</param> public PolygonSymbolizer(Color fillColor, Color outlineColor, double outlineWidth) { Patterns = new CopyList<IPattern> { new SimplePattern(fillColor) }; OutlineSymbolizer = new LineSymbolizer(outlineColor, outlineWidth); } /// <summary> /// Initializes a new instance of the <see cref="PolygonSymbolizer"/> class using a Gradient Pattern with the specified colors and angle. /// </summary> /// <param name="startColor">The start color.</param> /// <param name="endColor">The end color.</param> /// <param name="angle">The direction of the gradient, measured in degrees clockwise from the x-axis.</param> /// <param name="style">Controls how the gradient is drawn.</param> public PolygonSymbolizer(Color startColor, Color endColor, double angle, GradientType style) { Patterns = new CopyList<IPattern> { new GradientPattern(startColor, endColor, angle, style) }; } /// <summary> /// Initializes a new instance of the <see cref="PolygonSymbolizer"/> class using a Gradient Pattern with the specified colors and angle. /// </summary> /// <param name="startColor">The start color.</param> /// <param name="endColor">The end color.</param> /// <param name="angle">The direction of the gradient, measured in degrees clockwise from the x-axis.</param> /// <param name="style">The type of gradient to use.</param> /// <param name="outlineColor">The color to use for the border symbolizer.</param> /// <param name="outlineWidth">The width of the line to use for the border symbolizer.</param> public PolygonSymbolizer(Color startColor, Color endColor, double angle, GradientType style, Color outlineColor, double outlineWidth) : this(startColor, endColor, angle, style) { OutlineSymbolizer = new LineSymbolizer(outlineColor, outlineWidth); } /// <summary> /// Initializes a new instance of the <see cref="PolygonSymbolizer"/> class using PicturePattern with the specified image. /// </summary> /// <param name="picture">The picture to draw.</param> /// <param name="wrap">The way to wrap the picture.</param> /// <param name="angle">The angle to rotate the image.</param> public PolygonSymbolizer(Image picture, WrapMode wrap, double angle) { Patterns = new CopyList<IPattern> { new PicturePattern(picture, wrap, angle) }; } /// <summary> /// Initializes a new instance of the <see cref="PolygonSymbolizer"/> class using PicturePattern with the specified image. /// </summary> /// <param name="picture">The picture to draw.</param> /// <param name="wrap">The way to wrap the picture.</param> /// <param name="angle">The angle to rotate the image.</param> /// <param name="outlineColor">The color to use for the border symbolizer.</param> /// <param name="outlineWidth">The width of the line to use for the border symbolizer.</param> public PolygonSymbolizer(Image picture, WrapMode wrap, double angle, Color outlineColor, double outlineWidth) : this(picture, wrap, angle) { OutlineSymbolizer = new LineSymbolizer(outlineColor, outlineWidth); } /// <summary> /// Initializes a new instance of the <see cref="PolygonSymbolizer"/> class using the patterns specified by the list or array of patterns. /// </summary> /// <param name="patterns">The patterns to add to this symbolizer.</param> public PolygonSymbolizer(IEnumerable<IPattern> patterns) { Patterns = new CopyList<IPattern>(); foreach (IPattern pattern in patterns) { Patterns.Add(pattern); } } /// <summary> /// Initializes a new instance of the <see cref="PolygonSymbolizer"/> class. /// </summary> /// <param name="selected">Boolean, true if this should use selection symbology.</param> public PolygonSymbolizer(bool selected) { Patterns = new CopyList<IPattern>(); if (selected) { Patterns.Add(new SimplePattern(Color.Transparent)); OutlineSymbolizer = new LineSymbolizer(Color.Cyan, 2); } else { Patterns.Add(new SimplePattern()); } } #endregion #region Properties /// <summary> /// Gets or sets the Symbolizer for the borders of this polygon as they appear on the top-most pattern. /// </summary> [ShallowCopy] [Serialize("OutlineSymbolizer")] public ILineSymbolizer OutlineSymbolizer { get { if (Patterns == null) return null; if (Patterns.Count == 0) return null; return Patterns[Patterns.Count - 1].Outline; } set { if (Patterns == null) return; if (Patterns.Count == 0) return; Patterns[Patterns.Count - 1].Outline = value; } } /// <summary> /// gets or sets the list of patterns to use for filling polygons. /// </summary> [Serialize("Patterns")] public IList<IPattern> Patterns { get; set; } #endregion #region Methods /// <summary> /// Draws the polygon symbology. /// </summary> /// <param name="g">The graphics device to draw to.</param> /// <param name="target">The target rectangle to draw symbology content to.</param> public override void Draw(Graphics g, Rectangle target) { GraphicsPath gp = new GraphicsPath(); gp.AddRectangle(target); foreach (IPattern pattern in Patterns) { pattern.Bounds = new RectangleF(target.X, target.Y, target.Width, target.Height); pattern.FillPath(g, gp); } foreach (IPattern pattern in Patterns) { pattern.Outline?.DrawPath(g, gp, 1); } gp.Dispose(); } /// <summary> /// Gets the fill color of the top-most pattern. /// </summary> /// <returns>The fill color.</returns> public Color GetFillColor() { if (Patterns == null) return Color.Empty; if (Patterns.Count == 0) return Color.Empty; return Patterns[Patterns.Count - 1].GetFillColor(); } /// <summary> /// This gets the largest width of all the strokes of the outlines of all the patterns. Setting this will /// forceably adjust the width of all the strokes of the outlines of all the patterns. /// </summary> /// <returns>The outline width.</returns> public double GetOutlineWidth() { if (Patterns == null) return 0; if (Patterns.Count == 0) return 0; double w = 0; foreach (IPattern pattern in Patterns) { double tempWidth = pattern.Outline.GetWidth(); if (tempWidth > w) w = tempWidth; } return w; } /// <summary> /// Sets the fill color of the top-most pattern. /// If the pattern is not a simple pattern, a simple pattern will be forced. /// </summary> /// <param name="color">The Color structure.</param> public void SetFillColor(Color color) { if (Patterns == null) return; if (Patterns.Count == 0) return; ISimplePattern sp = Patterns[Patterns.Count - 1] as ISimplePattern; if (sp == null) { sp = new SimplePattern(); Patterns[Patterns.Count - 1] = sp; } sp.FillColor = color; } /// <summary> /// Sets the outline, assuming that the symbolizer either supports outlines, or else by using a second symbol layer. /// </summary> /// <param name="outlineColor">The color of the outline.</param> /// <param name="width">The width of the outline in pixels.</param> public override void SetOutline(Color outlineColor, double width) { if (Patterns == null) return; if (Patterns.Count == 0) return; foreach (IPattern pattern in Patterns) { pattern.Outline.SetFillColor(outlineColor); pattern.Outline.SetWidth(width); pattern.UseOutline = true; } base.SetOutline(outlineColor, width); } /// <summary> /// Forces the specified width to be the width of every stroke outlining every pattern. /// </summary> /// <param name="width">The width to force as the outline width.</param> public void SetOutlineWidth(double width) { if (Patterns == null || Patterns.Count == 0) return; foreach (IPattern pattern in Patterns) { pattern.Outline.SetWidth(width); } } /// <summary> /// Occurs after the pattern list is set so that we can listen for when /// the outline symbolizer gets updated. /// </summary> protected virtual void OnHandlePatternEvents() { IChangeEventList<IPattern> patterns = Patterns as IChangeEventList<IPattern>; if (patterns != null) { patterns.ItemChanged += PatternsItemChanged; } } /// <summary> /// Occurs before the pattern list is set so that we can stop listening /// for messages from the old outline. /// </summary> protected virtual void OnIgnorePatternEvents() { IChangeEventList<IPattern> patterns = Patterns as IChangeEventList<IPattern>; if (patterns != null) { patterns.ItemChanged -= PatternsItemChanged; } } private void PatternsItemChanged(object sender, EventArgs e) { OnItemChanged(); } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Linq; using Xunit; #pragma warning disable 169, 649, 164 namespace System.Reflection.Tests { // Compare the results of RuntimeType and TypeInfo APIs results public class TypeInfoAPIsTest { private static BindingFlags s_declaredOnly = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance; private static Type s_runtimeType = typeof(PublicClass); private static TypeInfo s_typeInfo = s_runtimeType.GetTypeInfo(); [Fact] public void Test1() { VerifyResults("Name", s_runtimeType.Name, s_typeInfo.Name); } [Fact] public void Test2() { VerifyResults("FullName", s_runtimeType.FullName, s_typeInfo.FullName); } [Fact] public void Test3() { VerifyResults("GetDeclaredMethods", s_runtimeType.GetMethod("ProtectedMethod", s_declaredOnly), s_typeInfo.GetDeclaredMethods("ProtectedMethod").First()); } [Fact] public void Test4() { VerifyResults("GetDeclaredNestedType", s_runtimeType.GetNestedType("PublicNestedType", s_declaredOnly), s_typeInfo.GetDeclaredNestedType("PublicNestedType")); } [Fact] public void Test5() { VerifyResults("GetDeclaredProperty", s_runtimeType.GetProperty("PrivateProperty", s_declaredOnly), s_typeInfo.GetDeclaredProperty("PrivateProperty")); } [Fact] public void Test6() { VerifyResults("DeclaredFields", s_runtimeType.GetFields(s_declaredOnly), s_typeInfo.DeclaredFields); } [Fact] public void Test7() { VerifyResults("DeclaredMethods", s_runtimeType.GetMethods(s_declaredOnly), s_typeInfo.DeclaredMethods); } [Fact] public void Test8() { VerifyResults("DeclaredNestedTypes", s_runtimeType.GetNestedTypes(s_declaredOnly), s_typeInfo.DeclaredNestedTypes); } [Fact] public void Test9() { VerifyResults("DeclaredProperties", s_runtimeType.GetProperties(s_declaredOnly), s_typeInfo.DeclaredProperties); } [Fact] public void Test10() { VerifyResults("DeclaredEvents", s_runtimeType.GetEvents(s_declaredOnly), s_typeInfo.DeclaredEvents); } [Fact] public void Test11() { VerifyResults("DeclaredConstructors", s_runtimeType.GetConstructors(s_declaredOnly), s_typeInfo.DeclaredConstructors); } [Fact] public void Test12() { VerifyResults("GetEvents", s_runtimeType.GetEvents(), s_typeInfo.AsType().GetEvents()); } [Fact] public void Test13() { VerifyResults("GetFields", s_runtimeType.GetFields(), s_typeInfo.AsType().GetFields()); } [Fact] public void Test14() { VerifyResults("GetMethods", s_runtimeType.GetMethods(), s_typeInfo.AsType().GetMethods()); } [Fact] public void Test15() { BindingFlags all = BindingFlags.DeclaredOnly | BindingFlags.FlattenHierarchy | BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static; VerifyResults("GetNestedTypes", s_runtimeType.GetNestedTypes(all), s_typeInfo.AsType().GetNestedTypes(all)); } [Fact] public void Test16() { VerifyResults("GetProperties", s_runtimeType.GetProperties(), s_typeInfo.AsType().GetProperties()); } [Fact] public void Test17() { VerifyResults("GetType", s_runtimeType.GetType(), s_typeInfo.GetType()); } [Fact] public void Test18() { VerifyResults("IsAssignableFrom", true, s_runtimeType.IsAssignableFrom(s_typeInfo.AsType())); } [Fact] public void Test19() { VerifyResults("Equals", true, s_runtimeType.Equals(s_typeInfo)); } [Fact] public void Test20() { VerifyResults("IsClass", s_runtimeType.GetTypeInfo().IsClass, s_typeInfo.IsClass); } [Fact] public void Test21() { VerifyResults("IsPublic", s_runtimeType.GetTypeInfo().IsPublic, s_typeInfo.IsPublic); } [Fact] public void Test22() { VerifyResults("IsGenericType", s_runtimeType.GetTypeInfo().IsGenericType, s_typeInfo.IsGenericType); } [Fact] public void Test23() { VerifyResults("IsImport", s_runtimeType.GetTypeInfo().IsImport, s_typeInfo.IsImport); } [Fact] public void Test24() { VerifyResults("IsEnum", s_runtimeType.GetTypeInfo().IsEnum, s_typeInfo.IsEnum); } [Fact] public void Test25() { VerifyResults("IsGenericTypeDefinition ", s_runtimeType.GetTypeInfo().IsGenericTypeDefinition, s_typeInfo.IsGenericTypeDefinition); } private void VerifyResults(String testName, Object[] expected, IEnumerable<Object> actual) { // if (expected.Length != expected.Length) foreach (Object exObj in expected) { Boolean found = false; foreach (Object acObj in actual) { if (!exObj.ToString().Equals(acObj.ToString())) continue; found = true; break; } Assert.True(found); } } private void VerifyResults(String testName, Object expected, Object actual) { Assert.Equal(expected, actual); } } public class PublicClass { #region fields public int PublicField; protected int ProtectedField; private int _privateField; internal int InternalField; public static int PublicStaticField; protected static int ProtectedStaticField; private static int s_privateStaticField; internal static int InternalStaticField; #endregion #region constructors public PublicClass() { } protected PublicClass(int i) { } private PublicClass(int i, int j) { } internal PublicClass(int i, int j, int k) { } #endregion #region methods public void PublicMethod() { } protected void ProtectedMethod() { } private void PrivateMethod() { } internal void InternalMethod() { } public static void PublicStaticMethod() { } protected static void ProtectedStaticMethod() { } private static void PrivateStaticMethod() { } internal static void InternalStaticMethod() { } #endregion #region nested types public class PublicNestedType { } protected class ProtectedNestedType { } private class PrivateNestedType { } internal class InternalNestedType { } #endregion #region properties public int PublicProperty { get { return default(int); } set { } } protected int ProtectedProperty { get { return default(int); } set { } } private int PrivateProperty { get { return default(int); } set { } } internal int InternalProperty { get { return default(int); } set { } } #endregion } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the PnGrupoPrestacion class. /// </summary> [Serializable] public partial class PnGrupoPrestacionCollection : ActiveList<PnGrupoPrestacion, PnGrupoPrestacionCollection> { public PnGrupoPrestacionCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>PnGrupoPrestacionCollection</returns> public PnGrupoPrestacionCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { PnGrupoPrestacion o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the PN_grupo_prestacion table. /// </summary> [Serializable] public partial class PnGrupoPrestacion : ActiveRecord<PnGrupoPrestacion>, IActiveRecord { #region .ctors and Default Settings public PnGrupoPrestacion() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public PnGrupoPrestacion(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public PnGrupoPrestacion(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public PnGrupoPrestacion(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("PN_grupo_prestacion", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdCategoriaPrestacion = new TableSchema.TableColumn(schema); colvarIdCategoriaPrestacion.ColumnName = "id_categoria_prestacion"; colvarIdCategoriaPrestacion.DataType = DbType.Int32; colvarIdCategoriaPrestacion.MaxLength = 0; colvarIdCategoriaPrestacion.AutoIncrement = false; colvarIdCategoriaPrestacion.IsNullable = false; colvarIdCategoriaPrestacion.IsPrimaryKey = false; colvarIdCategoriaPrestacion.IsForeignKey = false; colvarIdCategoriaPrestacion.IsReadOnly = false; colvarIdCategoriaPrestacion.DefaultSetting = @""; colvarIdCategoriaPrestacion.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdCategoriaPrestacion); TableSchema.TableColumn colvarTema = new TableSchema.TableColumn(schema); colvarTema.ColumnName = "tema"; colvarTema.DataType = DbType.AnsiString; colvarTema.MaxLength = 255; colvarTema.AutoIncrement = false; colvarTema.IsNullable = true; colvarTema.IsPrimaryKey = false; colvarTema.IsForeignKey = false; colvarTema.IsReadOnly = false; colvarTema.DefaultSetting = @""; colvarTema.ForeignKeyTableName = ""; schema.Columns.Add(colvarTema); TableSchema.TableColumn colvarCategoria = new TableSchema.TableColumn(schema); colvarCategoria.ColumnName = "categoria"; colvarCategoria.DataType = DbType.AnsiString; colvarCategoria.MaxLength = 255; colvarCategoria.AutoIncrement = false; colvarCategoria.IsNullable = true; colvarCategoria.IsPrimaryKey = false; colvarCategoria.IsForeignKey = false; colvarCategoria.IsReadOnly = false; colvarCategoria.DefaultSetting = @""; colvarCategoria.ForeignKeyTableName = ""; schema.Columns.Add(colvarCategoria); TableSchema.TableColumn colvarCodigo = new TableSchema.TableColumn(schema); colvarCodigo.ColumnName = "codigo"; colvarCodigo.DataType = DbType.AnsiString; colvarCodigo.MaxLength = 255; colvarCodigo.AutoIncrement = false; colvarCodigo.IsNullable = true; colvarCodigo.IsPrimaryKey = false; colvarCodigo.IsForeignKey = false; colvarCodigo.IsReadOnly = false; colvarCodigo.DefaultSetting = @""; colvarCodigo.ForeignKeyTableName = ""; schema.Columns.Add(colvarCodigo); TableSchema.TableColumn colvarCategoriaPadre = new TableSchema.TableColumn(schema); colvarCategoriaPadre.ColumnName = "categoria_padre"; colvarCategoriaPadre.DataType = DbType.AnsiString; colvarCategoriaPadre.MaxLength = 255; colvarCategoriaPadre.AutoIncrement = false; colvarCategoriaPadre.IsNullable = true; colvarCategoriaPadre.IsPrimaryKey = false; colvarCategoriaPadre.IsForeignKey = false; colvarCategoriaPadre.IsReadOnly = false; colvarCategoriaPadre.DefaultSetting = @""; colvarCategoriaPadre.ForeignKeyTableName = ""; schema.Columns.Add(colvarCategoriaPadre); TableSchema.TableColumn colvarIdNomencladorDetalle = new TableSchema.TableColumn(schema); colvarIdNomencladorDetalle.ColumnName = "id_nomenclador_detalle"; colvarIdNomencladorDetalle.DataType = DbType.Int32; colvarIdNomencladorDetalle.MaxLength = 0; colvarIdNomencladorDetalle.AutoIncrement = false; colvarIdNomencladorDetalle.IsNullable = true; colvarIdNomencladorDetalle.IsPrimaryKey = false; colvarIdNomencladorDetalle.IsForeignKey = false; colvarIdNomencladorDetalle.IsReadOnly = false; colvarIdNomencladorDetalle.DefaultSetting = @""; colvarIdNomencladorDetalle.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdNomencladorDetalle); TableSchema.TableColumn colvarPrecio = new TableSchema.TableColumn(schema); colvarPrecio.ColumnName = "precio"; colvarPrecio.DataType = DbType.Decimal; colvarPrecio.MaxLength = 0; colvarPrecio.AutoIncrement = false; colvarPrecio.IsNullable = true; colvarPrecio.IsPrimaryKey = false; colvarPrecio.IsForeignKey = false; colvarPrecio.IsReadOnly = false; colvarPrecio.DefaultSetting = @""; colvarPrecio.ForeignKeyTableName = ""; schema.Columns.Add(colvarPrecio); TableSchema.TableColumn colvarNeo = new TableSchema.TableColumn(schema); colvarNeo.ColumnName = "neo"; colvarNeo.DataType = DbType.AnsiStringFixedLength; colvarNeo.MaxLength = 1; colvarNeo.AutoIncrement = false; colvarNeo.IsNullable = true; colvarNeo.IsPrimaryKey = false; colvarNeo.IsForeignKey = false; colvarNeo.IsReadOnly = false; colvarNeo.DefaultSetting = @"((0))"; colvarNeo.ForeignKeyTableName = ""; schema.Columns.Add(colvarNeo); TableSchema.TableColumn colvarCeroacinco = new TableSchema.TableColumn(schema); colvarCeroacinco.ColumnName = "ceroacinco"; colvarCeroacinco.DataType = DbType.AnsiStringFixedLength; colvarCeroacinco.MaxLength = 1; colvarCeroacinco.AutoIncrement = false; colvarCeroacinco.IsNullable = true; colvarCeroacinco.IsPrimaryKey = false; colvarCeroacinco.IsForeignKey = false; colvarCeroacinco.IsReadOnly = false; colvarCeroacinco.DefaultSetting = @"((0))"; colvarCeroacinco.ForeignKeyTableName = ""; schema.Columns.Add(colvarCeroacinco); TableSchema.TableColumn colvarIdGrupoPrestacion = new TableSchema.TableColumn(schema); colvarIdGrupoPrestacion.ColumnName = "id_grupo_prestacion"; colvarIdGrupoPrestacion.DataType = DbType.Int32; colvarIdGrupoPrestacion.MaxLength = 0; colvarIdGrupoPrestacion.AutoIncrement = true; colvarIdGrupoPrestacion.IsNullable = false; colvarIdGrupoPrestacion.IsPrimaryKey = true; colvarIdGrupoPrestacion.IsForeignKey = false; colvarIdGrupoPrestacion.IsReadOnly = false; colvarIdGrupoPrestacion.DefaultSetting = @""; colvarIdGrupoPrestacion.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdGrupoPrestacion); TableSchema.TableColumn colvarSeisanueve = new TableSchema.TableColumn(schema); colvarSeisanueve.ColumnName = "seisanueve"; colvarSeisanueve.DataType = DbType.AnsiStringFixedLength; colvarSeisanueve.MaxLength = 1; colvarSeisanueve.AutoIncrement = false; colvarSeisanueve.IsNullable = true; colvarSeisanueve.IsPrimaryKey = false; colvarSeisanueve.IsForeignKey = false; colvarSeisanueve.IsReadOnly = false; colvarSeisanueve.DefaultSetting = @"((0))"; colvarSeisanueve.ForeignKeyTableName = ""; schema.Columns.Add(colvarSeisanueve); TableSchema.TableColumn colvarAdol = new TableSchema.TableColumn(schema); colvarAdol.ColumnName = "adol"; colvarAdol.DataType = DbType.AnsiStringFixedLength; colvarAdol.MaxLength = 1; colvarAdol.AutoIncrement = false; colvarAdol.IsNullable = true; colvarAdol.IsPrimaryKey = false; colvarAdol.IsForeignKey = false; colvarAdol.IsReadOnly = false; colvarAdol.DefaultSetting = @"((0))"; colvarAdol.ForeignKeyTableName = ""; schema.Columns.Add(colvarAdol); TableSchema.TableColumn colvarAdulto = new TableSchema.TableColumn(schema); colvarAdulto.ColumnName = "adulto"; colvarAdulto.DataType = DbType.AnsiStringFixedLength; colvarAdulto.MaxLength = 1; colvarAdulto.AutoIncrement = false; colvarAdulto.IsNullable = true; colvarAdulto.IsPrimaryKey = false; colvarAdulto.IsForeignKey = false; colvarAdulto.IsReadOnly = false; colvarAdulto.DefaultSetting = @"((0))"; colvarAdulto.ForeignKeyTableName = ""; schema.Columns.Add(colvarAdulto); TableSchema.TableColumn colvarF = new TableSchema.TableColumn(schema); colvarF.ColumnName = "f"; colvarF.DataType = DbType.AnsiStringFixedLength; colvarF.MaxLength = 1; colvarF.AutoIncrement = false; colvarF.IsNullable = true; colvarF.IsPrimaryKey = false; colvarF.IsForeignKey = false; colvarF.IsReadOnly = false; colvarF.DefaultSetting = @"((0))"; colvarF.ForeignKeyTableName = ""; schema.Columns.Add(colvarF); TableSchema.TableColumn colvarM = new TableSchema.TableColumn(schema); colvarM.ColumnName = "m"; colvarM.DataType = DbType.AnsiStringFixedLength; colvarM.MaxLength = 1; colvarM.AutoIncrement = false; colvarM.IsNullable = true; colvarM.IsPrimaryKey = false; colvarM.IsForeignKey = false; colvarM.IsReadOnly = false; colvarM.DefaultSetting = @"((0))"; colvarM.ForeignKeyTableName = ""; schema.Columns.Add(colvarM); TableSchema.TableColumn colvarDiasUti = new TableSchema.TableColumn(schema); colvarDiasUti.ColumnName = "dias_uti"; colvarDiasUti.DataType = DbType.Int32; colvarDiasUti.MaxLength = 0; colvarDiasUti.AutoIncrement = false; colvarDiasUti.IsNullable = true; colvarDiasUti.IsPrimaryKey = false; colvarDiasUti.IsForeignKey = false; colvarDiasUti.IsReadOnly = false; colvarDiasUti.DefaultSetting = @""; colvarDiasUti.ForeignKeyTableName = ""; schema.Columns.Add(colvarDiasUti); TableSchema.TableColumn colvarDiasSala = new TableSchema.TableColumn(schema); colvarDiasSala.ColumnName = "dias_sala"; colvarDiasSala.DataType = DbType.Int32; colvarDiasSala.MaxLength = 0; colvarDiasSala.AutoIncrement = false; colvarDiasSala.IsNullable = true; colvarDiasSala.IsPrimaryKey = false; colvarDiasSala.IsForeignKey = false; colvarDiasSala.IsReadOnly = false; colvarDiasSala.DefaultSetting = @""; colvarDiasSala.ForeignKeyTableName = ""; schema.Columns.Add(colvarDiasSala); TableSchema.TableColumn colvarDiasTotal = new TableSchema.TableColumn(schema); colvarDiasTotal.ColumnName = "dias_total"; colvarDiasTotal.DataType = DbType.Int32; colvarDiasTotal.MaxLength = 0; colvarDiasTotal.AutoIncrement = false; colvarDiasTotal.IsNullable = true; colvarDiasTotal.IsPrimaryKey = false; colvarDiasTotal.IsForeignKey = false; colvarDiasTotal.IsReadOnly = false; colvarDiasTotal.DefaultSetting = @""; colvarDiasTotal.ForeignKeyTableName = ""; schema.Columns.Add(colvarDiasTotal); TableSchema.TableColumn colvarDiasMax = new TableSchema.TableColumn(schema); colvarDiasMax.ColumnName = "dias_max"; colvarDiasMax.DataType = DbType.Int32; colvarDiasMax.MaxLength = 0; colvarDiasMax.AutoIncrement = false; colvarDiasMax.IsNullable = true; colvarDiasMax.IsPrimaryKey = false; colvarDiasMax.IsForeignKey = false; colvarDiasMax.IsReadOnly = false; colvarDiasMax.DefaultSetting = @""; colvarDiasMax.ForeignKeyTableName = ""; schema.Columns.Add(colvarDiasMax); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("PN_grupo_prestacion",schema); } } #endregion #region Props [XmlAttribute("IdCategoriaPrestacion")] [Bindable(true)] public int IdCategoriaPrestacion { get { return GetColumnValue<int>(Columns.IdCategoriaPrestacion); } set { SetColumnValue(Columns.IdCategoriaPrestacion, value); } } [XmlAttribute("Tema")] [Bindable(true)] public string Tema { get { return GetColumnValue<string>(Columns.Tema); } set { SetColumnValue(Columns.Tema, value); } } [XmlAttribute("Categoria")] [Bindable(true)] public string Categoria { get { return GetColumnValue<string>(Columns.Categoria); } set { SetColumnValue(Columns.Categoria, value); } } [XmlAttribute("Codigo")] [Bindable(true)] public string Codigo { get { return GetColumnValue<string>(Columns.Codigo); } set { SetColumnValue(Columns.Codigo, value); } } [XmlAttribute("CategoriaPadre")] [Bindable(true)] public string CategoriaPadre { get { return GetColumnValue<string>(Columns.CategoriaPadre); } set { SetColumnValue(Columns.CategoriaPadre, value); } } [XmlAttribute("IdNomencladorDetalle")] [Bindable(true)] public int? IdNomencladorDetalle { get { return GetColumnValue<int?>(Columns.IdNomencladorDetalle); } set { SetColumnValue(Columns.IdNomencladorDetalle, value); } } [XmlAttribute("Precio")] [Bindable(true)] public decimal? Precio { get { return GetColumnValue<decimal?>(Columns.Precio); } set { SetColumnValue(Columns.Precio, value); } } [XmlAttribute("Neo")] [Bindable(true)] public string Neo { get { return GetColumnValue<string>(Columns.Neo); } set { SetColumnValue(Columns.Neo, value); } } [XmlAttribute("Ceroacinco")] [Bindable(true)] public string Ceroacinco { get { return GetColumnValue<string>(Columns.Ceroacinco); } set { SetColumnValue(Columns.Ceroacinco, value); } } [XmlAttribute("IdGrupoPrestacion")] [Bindable(true)] public int IdGrupoPrestacion { get { return GetColumnValue<int>(Columns.IdGrupoPrestacion); } set { SetColumnValue(Columns.IdGrupoPrestacion, value); } } [XmlAttribute("Seisanueve")] [Bindable(true)] public string Seisanueve { get { return GetColumnValue<string>(Columns.Seisanueve); } set { SetColumnValue(Columns.Seisanueve, value); } } [XmlAttribute("Adol")] [Bindable(true)] public string Adol { get { return GetColumnValue<string>(Columns.Adol); } set { SetColumnValue(Columns.Adol, value); } } [XmlAttribute("Adulto")] [Bindable(true)] public string Adulto { get { return GetColumnValue<string>(Columns.Adulto); } set { SetColumnValue(Columns.Adulto, value); } } [XmlAttribute("F")] [Bindable(true)] public string F { get { return GetColumnValue<string>(Columns.F); } set { SetColumnValue(Columns.F, value); } } [XmlAttribute("M")] [Bindable(true)] public string M { get { return GetColumnValue<string>(Columns.M); } set { SetColumnValue(Columns.M, value); } } [XmlAttribute("DiasUti")] [Bindable(true)] public int? DiasUti { get { return GetColumnValue<int?>(Columns.DiasUti); } set { SetColumnValue(Columns.DiasUti, value); } } [XmlAttribute("DiasSala")] [Bindable(true)] public int? DiasSala { get { return GetColumnValue<int?>(Columns.DiasSala); } set { SetColumnValue(Columns.DiasSala, value); } } [XmlAttribute("DiasTotal")] [Bindable(true)] public int? DiasTotal { get { return GetColumnValue<int?>(Columns.DiasTotal); } set { SetColumnValue(Columns.DiasTotal, value); } } [XmlAttribute("DiasMax")] [Bindable(true)] public int? DiasMax { get { return GetColumnValue<int?>(Columns.DiasMax); } set { SetColumnValue(Columns.DiasMax, value); } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int varIdCategoriaPrestacion,string varTema,string varCategoria,string varCodigo,string varCategoriaPadre,int? varIdNomencladorDetalle,decimal? varPrecio,string varNeo,string varCeroacinco,string varSeisanueve,string varAdol,string varAdulto,string varF,string varM,int? varDiasUti,int? varDiasSala,int? varDiasTotal,int? varDiasMax) { PnGrupoPrestacion item = new PnGrupoPrestacion(); item.IdCategoriaPrestacion = varIdCategoriaPrestacion; item.Tema = varTema; item.Categoria = varCategoria; item.Codigo = varCodigo; item.CategoriaPadre = varCategoriaPadre; item.IdNomencladorDetalle = varIdNomencladorDetalle; item.Precio = varPrecio; item.Neo = varNeo; item.Ceroacinco = varCeroacinco; item.Seisanueve = varSeisanueve; item.Adol = varAdol; item.Adulto = varAdulto; item.F = varF; item.M = varM; item.DiasUti = varDiasUti; item.DiasSala = varDiasSala; item.DiasTotal = varDiasTotal; item.DiasMax = varDiasMax; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdCategoriaPrestacion,string varTema,string varCategoria,string varCodigo,string varCategoriaPadre,int? varIdNomencladorDetalle,decimal? varPrecio,string varNeo,string varCeroacinco,int varIdGrupoPrestacion,string varSeisanueve,string varAdol,string varAdulto,string varF,string varM,int? varDiasUti,int? varDiasSala,int? varDiasTotal,int? varDiasMax) { PnGrupoPrestacion item = new PnGrupoPrestacion(); item.IdCategoriaPrestacion = varIdCategoriaPrestacion; item.Tema = varTema; item.Categoria = varCategoria; item.Codigo = varCodigo; item.CategoriaPadre = varCategoriaPadre; item.IdNomencladorDetalle = varIdNomencladorDetalle; item.Precio = varPrecio; item.Neo = varNeo; item.Ceroacinco = varCeroacinco; item.IdGrupoPrestacion = varIdGrupoPrestacion; item.Seisanueve = varSeisanueve; item.Adol = varAdol; item.Adulto = varAdulto; item.F = varF; item.M = varM; item.DiasUti = varDiasUti; item.DiasSala = varDiasSala; item.DiasTotal = varDiasTotal; item.DiasMax = varDiasMax; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdCategoriaPrestacionColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn TemaColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn CategoriaColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn CodigoColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn CategoriaPadreColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn IdNomencladorDetalleColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn PrecioColumn { get { return Schema.Columns[6]; } } public static TableSchema.TableColumn NeoColumn { get { return Schema.Columns[7]; } } public static TableSchema.TableColumn CeroacincoColumn { get { return Schema.Columns[8]; } } public static TableSchema.TableColumn IdGrupoPrestacionColumn { get { return Schema.Columns[9]; } } public static TableSchema.TableColumn SeisanueveColumn { get { return Schema.Columns[10]; } } public static TableSchema.TableColumn AdolColumn { get { return Schema.Columns[11]; } } public static TableSchema.TableColumn AdultoColumn { get { return Schema.Columns[12]; } } public static TableSchema.TableColumn FColumn { get { return Schema.Columns[13]; } } public static TableSchema.TableColumn MColumn { get { return Schema.Columns[14]; } } public static TableSchema.TableColumn DiasUtiColumn { get { return Schema.Columns[15]; } } public static TableSchema.TableColumn DiasSalaColumn { get { return Schema.Columns[16]; } } public static TableSchema.TableColumn DiasTotalColumn { get { return Schema.Columns[17]; } } public static TableSchema.TableColumn DiasMaxColumn { get { return Schema.Columns[18]; } } #endregion #region Columns Struct public struct Columns { public static string IdCategoriaPrestacion = @"id_categoria_prestacion"; public static string Tema = @"tema"; public static string Categoria = @"categoria"; public static string Codigo = @"codigo"; public static string CategoriaPadre = @"categoria_padre"; public static string IdNomencladorDetalle = @"id_nomenclador_detalle"; public static string Precio = @"precio"; public static string Neo = @"neo"; public static string Ceroacinco = @"ceroacinco"; public static string IdGrupoPrestacion = @"id_grupo_prestacion"; public static string Seisanueve = @"seisanueve"; public static string Adol = @"adol"; public static string Adulto = @"adulto"; public static string F = @"f"; public static string M = @"m"; public static string DiasUti = @"dias_uti"; public static string DiasSala = @"dias_sala"; public static string DiasTotal = @"dias_total"; public static string DiasMax = @"dias_max"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
// ScriptMetadata.cs // Script#/Libraries/CoreLib // This source code is subject to terms and conditions of the Apache License, Version 2.0. // using System; using System.ComponentModel; namespace System.Runtime.CompilerServices { /// <summary> /// This attribute can be placed on types in system script assemblies that should not /// be imported. It is only meant to be used within mscorlib.dll. /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event | AttributeTargets.Field, Inherited = false, AllowMultiple = false)] [NonScriptable] public sealed class NonScriptableAttribute : Attribute { } /// <summary> /// This attribute can be placed on types that should not be emitted into generated /// script, as they represent existing script or native types. All members without another naming attribute are considered to use [PreserveName]. /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Enum | AttributeTargets.Struct)] [NonScriptable] public sealed class ImportedAttribute : Attribute { /// <summary> /// Indicates that the type obeys the Saltarelle type system. If false (the default), the type is ignored in inheritance lists, casts to it is a no-op, and Object will be used if the type is used as a generic argument. /// The default is false. Requiring this to be set should be very uncommon. /// </summary> public bool ObeysTypeSystem { get; set; } /// <summary> /// Code used to check whether an object is of this type. Can use the placeholder {this} to reference the object being checked, as well as all type parameter for the type. /// </summary> public string TypeCheckCode { get; set; } } /// <summary> /// Marks an assembly as a script assembly that can be used with Script#. /// Additionally, each script must have a unique name that can be used as /// a dependency name. /// This name is also used to generate unique names for internal types defined /// within the assembly. The ScriptQualifier attribute can be used to provide a /// shorter name if needed. /// </summary> [AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = false)] [NonScriptable] public sealed class ScriptAssemblyAttribute : Attribute { public ScriptAssemblyAttribute(string name) { Name = name; } public string Name { get; private set; } } /// <summary> /// Provides a prefix to use when generating types internal to this assembly so that /// they can be unique within a given a script namespace. /// The specified prefix overrides the script name provided in the ScriptAssembly /// attribute. /// </summary> [AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = false)] [NonScriptable] public sealed class ScriptQualifierAttribute : Attribute { public ScriptQualifierAttribute(string prefix) { Prefix = prefix; } public string Prefix { get; private set; } } /// <summary> /// This attribute indicates that the namespace of type within a system assembly /// should be ignored at script generation time. It is useful for creating namespaces /// for the purpose of c# code that don't exist at runtime. /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Struct, Inherited = true, AllowMultiple = false)] [NonScriptable] public sealed class IgnoreNamespaceAttribute : Attribute { } /// <summary> /// Specifies the namespace that should be used in generated script. The script namespace /// is typically a short name, that is often shared across multiple assemblies. /// The developer is responsible for ensuring that public types across assemblies that share /// a script namespace are unique. /// For internal types, the ScriptQualifier attribute can be used to provide a short prefix /// to generate unique names. /// </summary> [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, AllowMultiple = false)] [NonScriptable] public sealed class ScriptNamespaceAttribute : Attribute { public ScriptNamespaceAttribute(string name) { Name = name; } public string Name { get; private set; } } /// <summary> /// This attribute can be placed on a static class that only contains static string /// fields representing a set of resource strings. /// </summary> [AttributeUsage(AttributeTargets.Class)] [NonScriptable] public sealed class ResourcesAttribute : Attribute { } /// <summary> /// This attribute turns methods on a static class as global methods in the generated /// script. Note that the class must be static, and must contain only methods. /// </summary> [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = true)] [NonScriptable] public sealed class GlobalMethodsAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)] [NonScriptable] public sealed class MixinAttribute : Attribute { public MixinAttribute(string expression) { Expression = expression; } public string Expression { get; private set; } } /// <summary> /// This attribute marks an enumeration type within a system assembly as as a set of /// names. Rather than the specific value, the name of the enumeration field is /// used as a string. /// </summary> [AttributeUsage(AttributeTargets.Enum, Inherited = false, AllowMultiple = false)] [NonScriptable] public sealed class NamedValuesAttribute : Attribute { } /// <summary> /// This attribute marks an enumeration type within a system assembly as as a set of /// numeric values. Rather than the enum field, the value of the enumeration field is /// used as a literal. /// </summary> [AttributeUsage(AttributeTargets.Enum, Inherited = false, AllowMultiple = false)] [NonScriptable] public sealed class NumericValuesAttribute : Attribute { } /// <summary> /// This attribute allows defining an alternate method signature that is not generated /// into script, but can be used for defining overloads to enable optional parameter semantics /// for a method. It must be applied on a method defined as extern, since an alternate signature /// method does not contain an actual method body. /// </summary> [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method, Inherited = true, AllowMultiple = false)] [NonScriptable] public sealed class AlternateSignatureAttribute : Attribute { } /// <summary> /// This attribute denotes a C# property that manifests like a field in the generated /// JavaScript (i.e. is not accessed via get/set methods). This is really meant only /// for use when defining OM corresponding to native objects exposed to script. /// </summary> [AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = false)] [NonScriptable] public sealed class IntrinsicPropertyAttribute : Attribute { } /// <summary> /// Allows specifying the name to use for a type or member in the generated script. Property and event accessors can use the placeholder {owner} to denote the name of their owning entity. /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Method | AttributeTargets.Event | AttributeTargets.Constructor, Inherited = false, AllowMultiple = false)] [NonScriptable] public sealed class ScriptNameAttribute : Attribute { public ScriptNameAttribute(string name) { Name = name; } public string Name { get; private set; } } /// <summary> /// This attribute allows suppressing the default behavior of converting /// member names to camel-cased equivalents in the generated JavaScript. /// </summary> [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event | AttributeTargets.Field, Inherited = true, AllowMultiple = false)] [NonScriptable] public sealed class PreserveCaseAttribute : Attribute { } /// <summary> /// This attribute allows suppressing the default behavior of converting /// member names of attached type to camel-cased equivalents in the generated JavaScript. /// When applied to an assembly, all types in the assembly are considered to have this /// attribute by default</summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Assembly, Inherited = true, AllowMultiple = false)] [NonScriptable] public sealed class PreserveMemberCaseAttribute : Attribute { public PreserveMemberCaseAttribute() { Preserve = true; } public PreserveMemberCaseAttribute(bool preserve) { Preserve = preserve; } public bool Preserve { get; private set; } } /// <summary> /// This attribute allows suppressing the default behavior of minimizing /// private type names and member names in the generated JavaScript. /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event | AttributeTargets.Field, Inherited = true, AllowMultiple = false)] [NonScriptable] public sealed class PreserveNameAttribute : Attribute { } /// <summary> /// This attribute allows public symbols inside an assembly to be minimized, in addition to non-public ones, when generating release scripts. /// </summary> [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)] [NonScriptable] public sealed class MinimizePublicNamesAttribute : Attribute { } /// <summary> /// This attribute allows specifying a script name for an imported method. /// The method is interpreted as a global method. As a result it this attribute /// only applies to static methods. /// </summary> // REVIEW: Eventually do we want to support this on properties/field and instance methods as well? [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = true, AllowMultiple = false)] [NonScriptable] public sealed class ScriptAliasAttribute : Attribute { public ScriptAliasAttribute(string alias) { Alias = alias; } public string Alias { get; private set; } } /// <summary> /// This attributes causes a method to not be invoked. The method must either be a static method with one argument (in case Foo.M(x) will become x), or an instance method with no arguments (in which x.M() will become x). /// Can also be applied to a constructor, in which case the constructor will not be called if used as an initializer (": base()" or ": this()"). /// </summary> [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = true, AllowMultiple = false)] [NonScriptable] public sealed class ScriptSkipAttribute : Attribute { } /// <summary> /// The method is implemented as inline code, eg Debugger.Break() => debugger. Can use the parameters {this} (for instance methods), as well as all typenames and argument names in braces (eg. {arg0}, {TArg0}). /// If a parameter name is preceeded by an @ sign, {@arg0}, that argument must be a literal string during invocation, and the supplied string will be inserted as an identifier into the script (eg '{this}.set_{@arg0}({arg1})' can transform the call 'c.F("MyProp", v)' to 'c.set_MyProp(v)'. /// If a parameter name is preceeded by an asterisk {*arg} that parameter must be a param array, and all invocations of the method must use the expanded invocation form. The entire array supplied for the parameter will be inserted into the call. Pretend that the parameter is a normal parameter, and commas will be inserted or omitted at the correct locations. /// The format string can also use identifiers starting with a dollar {$Namespace.Name} to construct type references. The name must be the fully qualified type name in this case. /// </summary> [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = true, AllowMultiple = false)] [NonScriptable] public sealed class InlineCodeAttribute : Attribute { public InlineCodeAttribute(string code) { Code = code; } public string Code { get; private set; } /// <summary> /// If set, a method with this name will be generated from the method source. /// </summary> public string GeneratedMethodName { get; set; } /// <summary> /// This code is used when the method is invoked non-virtually (eg. in a base.Method() call). /// </summary> public string NonVirtualCode { get; set; } /// <summary> /// This code is used when the method, which should be a method with a param array parameter, is invoked in non-expanded form. Optional, but can be used to support non-expanded invocation of a method that has a {*param} placeholder in its code. /// </summary> public string NonExpandedFormCode { get; set; } } /// <summary> /// This attribute specifies that a static method should be treated as an instance method on its first argument. This means that <c>MyClass.Method(x, a, b)</c> will be transformed to <c>x.Method(a, b)</c>. /// If no other name-preserving attribute is used on the member, it will be treated as if it were decorated with a [PreserveNameAttribute]. /// Useful for extension methods. /// </summary> [AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)] [NonScriptable] public sealed class InstanceMethodOnFirstArgumentAttribute : Attribute { } /// <summary> /// This attribute specifies that a generic type or method should have script generated as if it was a non-generic one. Any uses of the type arguments inside the method (eg. <c>typeof(T)</c>, or calling another generic method with T as a type argument) will cause runtime errors. /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Method, Inherited = true, AllowMultiple = false)] [NonScriptable] public sealed class IncludeGenericArgumentsAttribute : Attribute { public IncludeGenericArgumentsAttribute() { Include = true; } public IncludeGenericArgumentsAttribute(bool include) { Include = include; } public bool Include { get; private set; } } /// <summary> /// This enum defines the possibilities for default values for generic argument handling in an assembly. /// </summary> [NonScriptable] public enum GenericArgumentsDefault { /// <summary> /// Include generic arguments for all types that are not [Imported] /// </summary> IncludeExceptImported, /// <summary> /// Ignore generic arguments by default (this is the default) /// </summary> Ignore, /// <summary> /// Require an <see cref="IncludeGenericArgumentsAttribute"/> for all generic types/methods, excepts those that are imported, which will default to ignore their generic arguments. /// </summary> RequireExplicitSpecification, } /// <summary> /// This attribute indicates whether generic arguments for types and methods are included, but can always be overridden by specifying an <see cref="IncludeGenericArgumentsAttribute"/> on types or methods. /// </summary> [AttributeUsage(AttributeTargets.Assembly)] [NonScriptable] public sealed class IncludeGenericArgumentsDefaultAttribute : Attribute { public GenericArgumentsDefault TypeDefault { get; set; } public GenericArgumentsDefault MethodDefault { get; set; } } /// <summary> /// This attribute indicates that a user-defined operator should be compiled as if it were builtin (eg. op_Addition(a, b) => a + b). It can only be used on non-conversion operator methods. /// </summary> [AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)] [NonScriptable] public sealed class IntrinsicOperatorAttribute : Attribute { } /// <summary> /// This attribute can be applied to a method with a "params" parameter to make the param array be expanded in script (eg. given 'void F(int a, params int[] b)', the invocation 'F(1, 2, 3)' will be translated to 'F(1, [2, 3])' without this attribute, but 'F(1, 2, 3)' with this attribute. /// Methods with this attribute can only be invoked in the expanded form. /// </summary> [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Delegate, Inherited = true, AllowMultiple = false)] [NonScriptable] public sealed class ExpandParamsAttribute : Attribute { } /// <summary> /// Indicates that the Javascript 'this' should appear as the first argument to the delegate. /// </summary> [AttributeUsage(AttributeTargets.Delegate)] [NonScriptable] public sealed class BindThisToFirstParameterAttribute : Attribute { } /// <summary> /// If this attribute is applied to a constructor for a serializable type, it means that the constructor will not be called, but rather an object initializer will be created. Eg. 'new MyRecord(1, "X")' can become '{ a: 1, b: 'X' }'. /// All parameters must have a field or property with the same (case-insensitive) name, of the same type. /// This attribute is implicit on constructors of imported serializable types. /// </summary> [AttributeUsage(AttributeTargets.Constructor, Inherited = true, AllowMultiple = false)] [NonScriptable] public sealed class ObjectLiteralAttribute : Attribute { } /// <summary> /// This attribute can be specified on an assembly to specify additional compatibility options to help migrating from Script#. /// </summary> [AttributeUsage(AttributeTargets.Assembly)] [NonScriptable] public sealed class ScriptSharpCompatibilityAttribute : Attribute { /// <summary> /// If true, code will not be generated for casts of type '(MyClass)someValue'. Code will still be generated for 'someValue is MyClass' and 'someValue as MyClass'. /// </summary> public bool OmitDowncasts { get; set; } /// <summary> /// If true, code will not be generated to verify that a nullable value is not null before converting it to its underlying type. /// </summary> public bool OmitNullableChecks { get; set; } } /// <summary> /// If a constructor for a value type takes an instance of this type as a parameter, any attribute applied to that constructor will instead be applied to the default (undeclarable) constructor. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] [Imported] public sealed class DummyTypeUsedToAddAttributeToDefaultValueTypeConstructor { private DummyTypeUsedToAddAttributeToDefaultValueTypeConstructor() {} } /// <summary> /// Specifies that a type is defined in a module, which should be imported by a require() call. /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Assembly)] [NonScriptable] public sealed class ModuleNameAttribute : Attribute { public ModuleNameAttribute(string moduleName) { this.ModuleName = moduleName; } public string ModuleName { get; private set; } } /// <summary> /// When specified on an assembly, Javascript that adheres to the AMD pattern (require/define) will be generated. /// </summary> [AttributeUsage(AttributeTargets.Assembly)] [NonScriptable] public sealed class AsyncModuleAttribute : Attribute { } /// <summary> /// When specified on an assembly with an AsyncModule attribute, the module will require this additional dependency in its AMD declaration /// </summary> [AttributeUsage(AttributeTargets.Assembly, AllowMultiple=true)] [NonScriptable] public sealed class AdditionalDependencyAttribute : Attribute { public AdditionalDependencyAttribute(string moduleName) { ModuleName = moduleName; InstanceName = moduleName; } public AdditionalDependencyAttribute(string moduleName, string instanceName) { ModuleName = moduleName; InstanceName = instanceName; } public string ModuleName { get; private set; } public string InstanceName { get; set; } } /// <summary> /// Can be applied to a GetEnumerator() method to indicate that that array-style enumeration should be used. /// </summary> [AttributeUsage(AttributeTargets.Method)] [NonScriptable] public sealed class EnumerateAsArrayAttribute : Attribute { } /// <summary> /// Can be applied to a const field to indicate that the literal value of the constant should always be used instead of the symbolic field name. /// </summary> [AttributeUsage(AttributeTargets.Field)] [NonScriptable] public sealed class InlineConstantAttribute : Attribute { } /// <summary> /// Can be applied to a member to indicate that metadata for the member should (or should not) be included in the compiled script. By default members are reflectable if they have at least one scriptable attribute. The default reflectability can be changed with the [<see cref="DefaultMemberReflectabilityAttribute"/>]. /// </summary> [AttributeUsage(AttributeTargets.All)] [NonScriptable] public sealed class ReflectableAttribute : Attribute { public bool Reflectable { get; private set; } public ReflectableAttribute() { Reflectable = true; } public ReflectableAttribute(bool reflectable) { Reflectable = reflectable; } } /// <summary> /// This enum defines the possibilities for default member reflectability. /// </summary> [NonScriptable] public enum MemberReflectability { /// <summary> /// Members are not reflectable (unless they are decorated either with any script-usable attributes or a [ReflectableAttribute]) /// </summary> None, /// <summary> /// Public and protected members are reflectable, private/internal members are only reflectable if are decorated either with any script-usable attributes or a [ReflectableAttribute]. /// Members are reflectable even when their enclosing type is not publicly visible. /// </summary> PublicAndProtected, /// <summary> /// Public, protected and internal members are reflectable, private members are only reflectable if are decorated either with any script-usable attributes or a [ReflectableAttribute]. /// </summary> NonPrivate, /// <summary> /// All members are reflectable by default (can be overridden with [Reflectable(false)]). /// </summary> All } /// <summary> /// This attribute can be applied to an assembly or a type to indicate whether members are reflectable by default. /// </summary> [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Struct)] [NonScriptable] public sealed partial class DefaultMemberReflectabilityAttribute : #if PLUGIN Saltarelle.Compiler.PluginAttributeBase #else Attribute #endif { public MemberReflectability DefaultReflectability { get; private set; } public DefaultMemberReflectabilityAttribute(MemberReflectability defaultReflectability) { DefaultReflectability = defaultReflectability; } } /// <summary> /// Can be applied to a constant field to ensure that it will never be inlined, even in minified scripts. /// </summary> [AttributeUsage(AttributeTargets.Field)] [NonScriptable] public sealed class NoInlineAttribute : Attribute { } /// <summary> /// Can be applied to a user-defined value type (struct) to instruct the compiler that it can be mutated and therefore needs to be copied whenever .net would create a copy of a value type. /// </summary> [AttributeUsage(AttributeTargets.Struct)] [NonScriptable] public sealed class MutableAttribute : Attribute { } /// <summary> /// Can be applied to an attribute to indicate that its name when referenced in a plugin is different from its name in script. Only useful for plugin developers, and probably not for plugins either. The only use case I can think of is when you are modifying a framework attribute type (eg. SerializableAttribute). /// </summary> [AttributeUsage(AttributeTargets.Class)] [NonScriptable] [EditorBrowsable(EditorBrowsableState.Never)] public sealed class PluginNameAttribute : Attribute { public PluginNameAttribute(string fullName) { FullName = fullName; } public string FullName { get; private set; } } /// <summary> /// Can be applied to a (non-const) field or an automatically implemented property to specify custom code to create the value with which the member is being initialized. For events and properties, this attribute applies to the compiler-generated backing field. /// </summary> [AttributeUsage(AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Property)] [NonScriptable] public sealed class CustomInitializationAttribute : Attribute { /// <param name="code">JS code to initialize the field. Can use the placeholder {value} to represent the value with which the member is being initialized (as well as all other placeholders from <see cref="InlineCodeAttribute"/>). If null, the member will not be initialized.</param> public CustomInitializationAttribute(string code) { Code = code; } public string Code { get; set; } } /// <summary> /// Can be specified on a method or a constructor to indicate that no code should be generated for the member, but it has no effect on any usage of the member. /// </summary> [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor)] [NonScriptable] public sealed class DontGenerateAttribute : Attribute { } /// <summary> /// Can be specified on an automatically implemented event or property to denote the name of the backing field. The presense of this attribute will also cause the backing field to be initialized even if no code is generated for the accessors (eg. if they are [InlineCode]). /// </summary> [AttributeUsage(AttributeTargets.Property | AttributeTargets.Event)] [NonScriptable] public sealed class BackingFieldNameAttribute : Attribute { public BackingFieldNameAttribute(string name) { Name = name; } public string Name { get; private set; } } }
using System; using System.Collections; using System.Data; using System.Diagnostics; using System.Runtime.InteropServices; using ADOX; namespace Xsd2Db.Data { /// <summary> /// Summary description for JetDatabaseCreator. /// </summary> public abstract class AdoxDataSchemaAdapter : DataSchemaAdapter { /// <summary> /// /// </summary> internal static readonly Hashtable TypeMap; /// <summary> /// /// </summary> /// <param name="name"></param> protected abstract void DeleteCatalog(string name); /// <summary> /// /// </summary> /// <param name="name"></param> protected abstract void CreateCatalog(string name); /// <summary> /// /// </summary> /// <param name="name"></param> /// <returns></returns> protected abstract Catalog OpenCatalog(string name); /// <summary> /// /// </summary> static AdoxDataSchemaAdapter() { TypeMap = new Hashtable(); TypeMap[typeof (UInt64)] = DataTypeEnum.adUnsignedBigInt; TypeMap[typeof (Int64)] = DataTypeEnum.adBigInt; TypeMap[typeof (Boolean)] = DataTypeEnum.adBoolean; TypeMap[typeof (Char)] = DataTypeEnum.adWChar; TypeMap[typeof (DateTime)] = DataTypeEnum.adDate; TypeMap[typeof (Double)] = DataTypeEnum.adDouble; TypeMap[typeof (UInt32)] = DataTypeEnum.adUnsignedInt; TypeMap[typeof (Int32)] = DataTypeEnum.adInteger; TypeMap[typeof (Guid)] = DataTypeEnum.adGUID; TypeMap[typeof (UInt16)] = DataTypeEnum.adUnsignedSmallInt; TypeMap[typeof (Int16)] = DataTypeEnum.adSmallInt; TypeMap[typeof (Decimal)] = DataTypeEnum.adDecimal; TypeMap[typeof (Byte)] = DataTypeEnum.adTinyInt; TypeMap[typeof (String)] = DataTypeEnum.adWChar; TypeMap[typeof (TimeSpan)] = DataTypeEnum.adDBTime; TypeMap[typeof (Byte[])] = DataTypeEnum.adLongVarBinary; TypeMap[typeof (Char[])] = DataTypeEnum.adLongVarWChar; } /// <summary> /// Create a new database conforming to the passed schema. /// </summary> /// <param name="schema">a DataSet containing the schema</param> /// <param name="force">overwrite the database if it exists</param> public void Create( DataSet schema, bool force) { if (schema == null) { throw new ArgumentNullException("schema is null", "schema"); } string name = schema.DataSetName; if (name.Equals(String.Empty)) { throw new ArgumentException( "name of the schema (file name) not set", "schema.DataSetName"); } if (force) { DeleteCatalog(name); } CreateCatalog(name); Catalog catalog = null; try { //Hashtable map = new Hashtable(); catalog = OpenCatalog(name); foreach (DataTable srcTable in schema.Tables) { CreateTable(catalog, srcTable); } foreach (DataRelation relation in schema.Relations) { CreateRelation(catalog, relation); } } finally { // // TODO: is this still required. // // Force the system to let go of the connection, otherwise // it keeps a handle to the database file. if (catalog != null) { catalog.ActiveConnection = null; catalog = null; } GC.Collect(); } } /// <summary> /// Create a new database conforming to the passed schema. /// </summary> /// <param name="schema">a DataSet containing the schema</param> /// <param name="force">overwrite the database if it exists</param> /// <param name="TablePrefix">Adds a prefix to all tables</param> public void Create(DataSet schema, bool force, string TablePrefix) { Create(schema, force); } /// <summary> /// Create a new database conforming to the passed schema. /// </summary> /// <param name="schema">a DataSet containing the schema</param> /// <param name="force">overwrite the database if it exists</param> /// <param name="TablePrefix">Adds a prefix to all tables</param> /// <param name="DbOwner">Not Implemented yet</param> public void Create(DataSet schema, bool force, string TablePrefix, string DbOwner) { Create(schema, force); } public void Create(DataSet schema, bool force, string TablePrefix, string DbOwner, bool useExisting) { Create(schema, force); } /// <summary> /// /// </summary> /// <param name="catalog"></param> /// <param name="srcTable"></param> internal void CreateTable( Catalog catalog, DataTable srcTable) { string tableName = Sanitize(srcTable.TableName); Table newTable = new TableClass(); newTable.Name = tableName; catalog.Tables.Append(newTable); // ArrayList keySet = new ArrayList(); foreach (DataColumn srcColumn in srcTable.Columns) { Column column = new ColumnClass(); column.Name = Sanitize(srcColumn.ColumnName); column.Type = TypeFor(srcColumn); column.DefinedSize = SizeFor(srcColumn); column.ParentCatalog = catalog; if (srcColumn.AllowDBNull) { column.Attributes = ColumnAttributesEnum.adColNullable; } LookupTable(catalog, srcTable).Columns.Append( column, DataTypeEnum.adVarWChar, // default 0); // default } if (srcTable.PrimaryKey.Length > 0) { Key key = new KeyClass(); key.Name = Sanitize(String.Format("{0}", tableName)); key.Type = KeyTypeEnum.adKeyPrimary; key.RelatedTable = tableName; foreach (DataColumn srcColumn in srcTable.PrimaryKey) { Column column = LookupColumn(catalog, srcColumn); key.Columns.Append( column.Name, DataTypeEnum.adVarWChar, // default 0); // default } LookupTable(catalog, srcTable).Keys.Append( key, KeyTypeEnum.adKeyPrimary, // default Type.Missing, // default String.Empty, // default String.Empty); // default } } /// <summary> /// /// </summary> /// <param name="catalog"></param> /// <param name="column"></param> /// <returns></returns> internal Column LookupColumn( Catalog catalog, DataColumn column) { string columnName = Sanitize(column.ColumnName); Column result = LookupTable(catalog, column.Table).Columns[columnName]; Debug.Assert(result != null); return result; } /// <summary> /// /// </summary> /// <param name="catalog"></param> /// <param name="table"></param> /// <returns></returns> internal Table LookupTable( Catalog catalog, DataTable table) { string tableName = Sanitize(table.TableName); Table result = catalog.Tables[tableName]; Debug.Assert(result != null); return result; } /// <summary> /// /// </summary> /// <param name="catalog"></param> /// <param name="relation"></param> internal void CreateRelation( Catalog catalog, DataRelation relation) { Key foreignKey = new KeyClass(); Table parentTable = LookupTable(catalog, relation.ParentTable); Table childTable = LookupTable(catalog, relation.ChildTable); foreignKey.Name = Sanitize(relation.RelationName); foreignKey.Type = KeyTypeEnum.adKeyForeign; foreignKey.RelatedTable = parentTable.Name; foreignKey.DeleteRule = RuleEnum.adRICascade; foreignKey.UpdateRule = RuleEnum.adRINone; // // Assumption, child and parent columns are at the same index // in their respective collections. // Debug.Assert( relation.ChildColumns.Length == relation.ParentColumns.Length); for (int i = 0; i < relation.ChildColumns.Length; ++i) { Column childColumn = LookupColumn(catalog, relation.ChildColumns[i]); Column parentColumn = LookupColumn(catalog, relation.ParentColumns[i]); foreignKey.Columns.Append( childColumn.Name, DataTypeEnum.adVarWChar, // default 0); // default foreignKey.Columns[childColumn.Name].RelatedColumn = parentColumn.Name; } childTable.Keys.Append( foreignKey, KeyTypeEnum.adKeyPrimary, // default Type.Missing, // default String.Empty, // default String.Empty); // default } /// <summary> /// /// </summary> /// <param name="column"></param> /// <returns></returns> internal Type ResolveType(DataColumn column) { Type type = column.DataType; if (type.Equals(typeof (string)) && (column.MaxLength < 0)) { type = typeof (char[]); } return type; } /// <summary> /// /// </summary> /// <param name="column"></param> /// <returns></returns> internal DataTypeEnum TypeFor(DataColumn column) { Type type = ResolveType(column); object result = TypeMap[type]; Debug.Assert(result != null); return (DataTypeEnum) result; } /// <summary> /// /// </summary> /// <param name="column"></param> /// <returns></returns> internal int SizeFor(DataColumn column) { // // TODO: Maybe I should just return the max length for strings // and 0 (which means "use the default" for everything else? // Type type = ResolveType(column); if (type.Equals(typeof (char[])) || type.Equals(typeof (byte[]))) { return 0; } else if (type.Equals(typeof (string))) { return column.MaxLength; } else if (type.Equals(typeof (DateTime))) { return 0; } else { return Marshal.SizeOf(type); } } /// <summary> /// /// </summary> /// <param name="text"></param> /// <returns></returns> internal string Sanitize(string text) { return text.Trim().ToLower().Replace("-", "_").Replace(" ", "_"); } } }
// *********************************************************************** // Copyright (c) 2012 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections.Generic; using System.Threading; using NUnit.Framework.Compatibility; using NUnit.Framework.Interfaces; namespace NUnit.Framework.Internal.Execution { /// <summary> /// A WorkItem may be an individual test case, a fixture or /// a higher level grouping of tests. All WorkItems inherit /// from the abstract WorkItem class, which uses the template /// pattern to allow derived classes to perform work in /// whatever way is needed. /// /// A WorkItem is created with a particular TestExecutionContext /// and is responsible for re-establishing that context in the /// current thread before it begins or resumes execution. /// </summary> public abstract class WorkItem { static Logger log = InternalTrace.GetLogger("WorkItem"); #region Static Factory Method /// <summary> /// Creates a work item. /// </summary> /// <param name="test">The test for which this WorkItem is being created.</param> /// <param name="filter">The filter to be used in selecting any child Tests.</param> /// <returns></returns> static public WorkItem CreateWorkItem(ITest test, ITestFilter filter) { TestSuite suite = test as TestSuite; if (suite != null) return new CompositeWorkItem(suite, filter); else return new SimpleWorkItem((TestMethod)test, filter); } #endregion #region Construction and Initialization /// <summary> /// Construct a WorkItem for a particular test. /// </summary> /// <param name="test">The test that the WorkItem will run</param> public WorkItem(Test test) { Test = test; Result = test.MakeTestResult(); State = WorkItemState.Ready; Actions = new List<ITestAction>(); #if !PORTABLE && !SILVERLIGHT && !NETCF TargetApartment = Test.Properties.ContainsKey(PropertyNames.ApartmentState) ? (ApartmentState)Test.Properties.Get(PropertyNames.ApartmentState) : ApartmentState.Unknown; #endif } /// <summary> /// Initialize the TestExecutionContext. This must be done /// before executing the WorkItem. /// </summary> /// <remarks> /// Originally, the context was provided in the constructor /// but delaying initialization of the context until the item /// is about to be dispatched allows changes in the parent /// context during OneTimeSetUp to be reflected in the child. /// </remarks> /// <param name="context">The TestExecutionContext to use</param> public void InitializeContext(TestExecutionContext context) { Guard.OperationValid(Context == null, "The context has already been initialized"); Context = context; if (Test is TestAssembly) Actions.AddRange(ActionsHelper.GetActionsFromAttributeProvider(((TestAssembly)Test).Assembly)); else if (Test is ParameterizedMethodSuite) Actions.AddRange(ActionsHelper.GetActionsFromAttributeProvider(Test.Method.MethodInfo)); else if (Test.TypeInfo != null) Actions.AddRange(ActionsHelper.GetActionsFromTypesAttributes(Test.TypeInfo.Type)); } #endregion #region Properties and Events /// <summary> /// Event triggered when the item is complete /// </summary> public event EventHandler Completed; /// <summary> /// Gets the current state of the WorkItem /// </summary> public WorkItemState State { get; private set; } /// <summary> /// The test being executed by the work item /// </summary> public Test Test { get; private set; } /// <summary> /// The execution context /// </summary> public TestExecutionContext Context { get; private set; } /// <summary> /// The unique id of the worker executing this item. /// </summary> public string WorkerId {get; internal set;} /// <summary> /// The test actions to be performed before and after this test /// </summary> public List<ITestAction> Actions { get; private set; } #if PARALLEL /// <summary> /// Indicates whether this WorkItem may be run in parallel /// </summary> public bool IsParallelizable { get { ParallelScope scope = ParallelScope.None; if (Test.Properties.ContainsKey(PropertyNames.ParallelScope)) { scope = (ParallelScope)Test.Properties.Get(PropertyNames.ParallelScope); if ((scope & ParallelScope.Self) != 0) return true; } else { scope = Context.ParallelScope; if ((scope & ParallelScope.Children) != 0) return true; } if (Test is TestFixture && (scope & ParallelScope.Fixtures) != 0) return true; // Special handling for the top level TestAssembly. // If it has any scope specified other than None, // we will use the parallel queue. This heuristic // is intended to minimize creation of unneeded // queues and workers, since the assembly and // namespace level tests can easily run in any queue. if (Test is TestAssembly && scope != ParallelScope.None) return true; return false; } } #endif /// <summary> /// The test result /// </summary> public TestResult Result { get; protected set; } #if !SILVERLIGHT && !NETCF && !PORTABLE internal ApartmentState TargetApartment { get; set; } private ApartmentState CurrentApartment { get; set; } #endif #endregion #region Public Methods /// <summary> /// Execute the current work item, including any /// child work items. /// </summary> public virtual void Execute() { // Timeout set at a higher level int timeout = Context.TestCaseTimeout; // Timeout set on this test if (Test.Properties.ContainsKey(PropertyNames.Timeout)) timeout = (int)Test.Properties.Get(PropertyNames.Timeout); // Unless the context is single threaded, a supplementary thread // is created on the various platforms... // 1. If the test used the RequiresThreadAttribute. // 2. If a test method has a timeout. // 3. If the test needs to run in a different apartment. // // NOTE: We want to eliminate or significantly reduce // cases 2 and 3 in the future. // // Case 2 requires the ability to stop and start test workers // dynamically. We would cancel the worker thread, dispose of // the worker and start a new worker on a new thread. // // Case 3 occurs when using either dispatcher whenever a // child test calls for a different apartment from the one // used by it's parent. It routinely occurs under the simple // dispatcher (--workers=0 option). Under the parallel dispatcher // it is needed when test cases are not enabled for parallel // execution. Currently, test cases are always run sequentially, // so this continues to apply fairly generally. #if PORTABLE RunTest(); #elif SILVERLIGHT || NETCF if (Context.IsSingleThreaded) RunTest(); else if (Test.RequiresThread || Test is TestMethod && timeout > 0) RunTestOnOwnThread(timeout); else RunTest(); #else CurrentApartment = Thread.CurrentThread.GetApartmentState(); if (Context.IsSingleThreaded) RunTest(); else if (CurrentApartment != TargetApartment && TargetApartment != ApartmentState.Unknown) RunTestOnOwnThread(timeout, TargetApartment); else if (Test.RequiresThread || Test is TestMethod && timeout > 0) RunTestOnOwnThread(timeout, CurrentApartment); else RunTest(); #endif } #if SILVERLIGHT || NETCF private Thread thread; private void RunTestOnOwnThread(int timeout) { string reason = Test.RequiresThread ? "Has RequiresThreadAttribute." : timeout > 0 ? "Has Timeout value set." : null; if (reason != null) log.Debug("Running test on own thread. " + reason); else log.Error("Running test on own thread. Reason UNKNOWN."); thread = new Thread(RunTest); RunThread(timeout); } #endif #if !SILVERLIGHT && !NETCF && !PORTABLE private Thread thread; private void RunTestOnOwnThread(int timeout, ApartmentState apartment) { string reason = Test.RequiresThread ? "Has RequiresThreadAttribute." : timeout > 0 ? "Has Timeout value set." : CurrentApartment != apartment ? "Requires a different apartment." : null; if (reason != null) log.Debug("Running test on own thread. " + reason); else log.Error("Running test on own thread. Reason UNKNOWN."); thread = new Thread(new ThreadStart(RunTest)); thread.SetApartmentState(apartment); RunThread(timeout); } #endif #if !PORTABLE private void RunThread(int timeout) { #if !NETCF thread.CurrentCulture = Context.CurrentCulture; thread.CurrentUICulture = Context.CurrentUICulture; #endif thread.Start(); if (!Test.IsAsynchronous || timeout > 0) { if (timeout <= 0) timeout = Timeout.Infinite; if (!thread.Join(timeout)) { Thread tThread; lock (threadLock) { if (thread == null) return; tThread = thread; thread = null; } if (Context.ExecutionStatus == TestExecutionStatus.AbortRequested) return; log.Debug("Killing thread {0}, which exceeded timeout", tThread.ManagedThreadId); ThreadUtility.Kill(tThread); // NOTE: Without the use of Join, there is a race condition here. // The thread sets the result to Cancelled and our code below sets // it to Failure. In order for the result to be shown as a failure, // we need to ensure that the following code executes after the // thread has terminated. There is a risk here: the test code might // refuse to terminate. However, it's more important to deal with // the normal rather than a pathological case. tThread.Join(); log.Debug("Changing result from {0} to Timeout Failure", Result.ResultState); Result.SetResult(ResultState.Failure, string.Format("Test exceeded Timeout value of {0}ms", timeout)); WorkItemComplete(); } } } #endif private void RunTest() { Context.CurrentTest = this.Test; Context.CurrentResult = this.Result; Context.Listener.TestStarted(this.Test); Context.StartTime = DateTime.UtcNow; Context.StartTicks = Stopwatch.GetTimestamp(); Context.WorkerId = this.WorkerId; Context.EstablishExecutionEnvironment(); State = WorkItemState.Running; PerformWork(); } private object threadLock = new object(); /// <summary> /// Cancel (abort or stop) a WorkItem /// </summary> /// <param name="force">true if the WorkItem should be aborted, false if it should run to completion</param> public virtual void Cancel(bool force) { if (Context != null) Context.ExecutionStatus = force ? TestExecutionStatus.AbortRequested : TestExecutionStatus.StopRequested; if (!force) return; #if !PORTABLE Thread tThread; lock (threadLock) { if (thread == null) return; tThread = thread; thread = null; } if (!tThread.Join(0)) { log.Debug("Killing thread {0} for cancel", tThread.ManagedThreadId); ThreadUtility.Kill(tThread); tThread.Join(); log.Debug("Changing result from {0} to Cancelled", Result.ResultState); Result.SetResult(ResultState.Cancelled, "Cancelled by user"); WorkItemComplete(); } #endif } #endregion #region Protected Methods /// <summary> /// Method that performs actually performs the work. It should /// set the State to WorkItemState.Complete when done. /// </summary> protected abstract void PerformWork(); /// <summary> /// Method called by the derived class when all work is complete /// </summary> protected void WorkItemComplete() { State = WorkItemState.Complete; Result.StartTime = Context.StartTime; Result.EndTime = DateTime.UtcNow; long tickCount = Stopwatch.GetTimestamp() - Context.StartTicks; double seconds = (double)tickCount / Stopwatch.Frequency; Result.Duration = seconds; // We add in the assert count from the context. If // this item is for a test case, we are adding the // test assert count to zero. If it's a fixture, we // are adding in any asserts that were run in the // fixture setup or teardown. Each context only // counts the asserts taking place in that context. // Each result accumulates the count from child // results along with it's own asserts. Result.AssertCount += Context.AssertCount; Context.Listener.TestFinished(Result); if (Completed != null) Completed(this, EventArgs.Empty); } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using Microsoft.Azure.Management.Compute.Fluent; using Microsoft.Azure.Management.Compute.Fluent.Models; using Microsoft.Azure.Management.Fluent; using Microsoft.Azure.Management.Network.Fluent; using Microsoft.Azure.Management.ResourceManager.Fluent; using Microsoft.Azure.Management.ResourceManager.Fluent.Core; using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions; using Microsoft.Azure.Management.Samples.Common; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; namespace ManageApplicationGateway { public class Program { private static readonly string UserName = "tirekicker"; private static readonly string SshKey = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCfSPC2K7LZcFKEO+/t3dzmQYtrJFZNxOsbVgOVKietqHyvmYGHEC0J2wPdAqQ/63g/hhAEFRoyehM+rbeDri4txB3YFfnOK58jqdkyXzupWqXzOrlKY4Wz9SKjjN765+dqUITjKRIaAip1Ri137szRg71WnrmdP3SphTRlCx1Bk2nXqWPsclbRDCiZeF8QOTi4JqbmJyK5+0UqhqYRduun8ylAwKKQJ1NJt85sYIHn9f1Rfr6Tq2zS0wZ7DHbZL+zB5rSlAr8QyUdg/GQD+cmSs6LvPJKL78d6hMGk84ARtFo4A79ovwX/Fj01znDQkU6nJildfkaolH2rWFG/qttD azjava@javalib.Com"; private static readonly string SslCertificatePfxPath = "NetworkTestCertificate1.pfx"; // Relative to project root directory by default private static readonly string SslCertificatePfxPath2 = "NetworkTestCertificate2.pfx"; // Relative to project root directory by default private const int BackendPools = 2; private const int VMCountInAPool = 4; private static List<Region> Regions = new List<Region>(){ Region.USEast, Region.UKWest }; private static List<string> AddressSpaces = new List<string>(){ "172.16.0.0/16", "172.17.0.0/16" }; private static string[,] PublicIpCreatableKeys = new string[BackendPools, VMCountInAPool]; private static string[,] IPAddresses = new string[BackendPools,VMCountInAPool]; /** * Azure network sample for managing application gateways. * * - CREATE an application gateway for load balancing * HTTP/HTTPS requests to backend server pools of virtual machines * * This application gateway serves traffic for multiple * domain names * * Routing Rule 1 * Hostname 1 = None * Backend server pool 1 = 4 virtual machines with IP addresses * Backend server pool 1 settings = HTTP:8080 * Front end port 1 = HTTP:80 * Listener 1 = HTTP * Routing rule 1 = HTTP listener 1 => backend server pool 1 * (round-robin load distribution) * * Routing Rule 2 * Hostname 2 = None * Backend server pool 2 = 4 virtual machines with IP addresses * Backend server pool 2 settings = HTTP:8080 * Front end port 2 = HTTPS:443 * Listener 2 = HTTPS * Routing rule 2 = HTTPS listener 2 => backend server pool 2 * (round-robin load distribution) * * - MODIFY the application gateway - re-configure the Routing Rule 1 for SSL offload and * add a host name, www.Contoso.Com * * Change listener 1 from HTTP to HTTPS * Add SSL certificate to the listener * Update front end port 1 to HTTPS:1443 * Add a host name, www.Contoso.Com * Enable cookie-based affinity * * Modified Routing Rule 1 * Hostname 1 = www.Contoso.Com * Backend server pool 1 = 4 virtual machines with IP addresses * Backend server pool 1 settings = HTTP:8080 * Front end port 1 = HTTPS:1443 * Listener 1 = HTTPS * Routing rule 1 = HTTPS listener 1 => backend server pool 1 * (round-robin load distribution) * */ public static void RunSample(IAzure azure) { string rgName = SdkContext.RandomResourceName("rgNEAG", 15); string pipName = SdkContext.RandomResourceName("pip" + "-", 18); try { //============================================================= // Create a resource group (Where all resources get created) // var resourceGroup = azure.ResourceGroups .Define(rgName) .WithRegion(Region.USEast) .Create(); Utilities.Log("Created a new resource group - " + resourceGroup.Id); //============================================================= // Create a public IP address for the Application Gateway Utilities.Log("Creating a public IP address for the application gateway ..."); var publicIPAddress = azure.PublicIPAddresses.Define(pipName) .WithRegion(Region.USEast) .WithExistingResourceGroup(rgName) .Create().Refresh(); Utilities.Log("Created a public IP address"); // Print the public IP details Utilities.PrintIPAddress(publicIPAddress); //============================================================= // Create backend pools // Prepare a batch of Creatable definitions var creatableVirtualMachines = new List<ICreatable<IVirtualMachine>>(); for (var i = 0; i < BackendPools; i++) { //============================================================= // Create 1 network creatable per region // Prepare Creatable Network definition (Where all the virtual machines get added to) var networkName = SdkContext.RandomResourceName("vnetNEAG-", 20); var networkCreatable = azure.Networks .Define(networkName) .WithRegion(Regions[i]) .WithExistingResourceGroup(resourceGroup) .WithAddressSpace(AddressSpaces[i]); //============================================================= // Create 1 storage creatable per region (For storing VMs disk) var storageAccountName = SdkContext.RandomResourceName("stgneag", 20); var storageAccountCreatable = azure.StorageAccounts .Define(storageAccountName) .WithRegion(Regions[i]) .WithExistingResourceGroup(resourceGroup); var linuxVMNamePrefix = SdkContext.RandomResourceName("vm-", 15); for (int j = 0; j < VMCountInAPool; j++) { //============================================================= // Create 1 public IP address creatable var publicIPAddressCreatable = azure.PublicIPAddresses .Define(string.Format("{0}-{1}", linuxVMNamePrefix, j)) .WithRegion(Regions[i]) .WithExistingResourceGroup(resourceGroup) .WithLeafDomainLabel(string.Format("{0}-{1}", linuxVMNamePrefix, j)); PublicIpCreatableKeys[i, j] = publicIPAddressCreatable.Key; //============================================================= // Create 1 virtual machine creatable var virtualMachineCreatable = azure.VirtualMachines.Define(string.Format("{0}-{1}", linuxVMNamePrefix, j)) .WithRegion(Regions[i]) .WithExistingResourceGroup(resourceGroup) .WithNewPrimaryNetwork(networkCreatable) .WithPrimaryPrivateIPAddressDynamic() .WithNewPrimaryPublicIPAddress(publicIPAddressCreatable) .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts) .WithRootUsername(UserName) .WithSsh(SshKey) .WithSize(VirtualMachineSizeTypes.StandardD3V2) .WithNewStorageAccount(storageAccountCreatable); creatableVirtualMachines.Add(virtualMachineCreatable); } } //============================================================= // Create two backend pools of virtual machines Stopwatch t = Stopwatch.StartNew(); Utilities.Log("Creating virtual machines (two backend pools)"); var virtualMachines = azure.VirtualMachines.Create(creatableVirtualMachines.ToArray()); t.Stop(); Utilities.Log("Created virtual machines (two backend pools)"); foreach (var virtualMachine in virtualMachines) { Utilities.Log(virtualMachine.Id); } Utilities.Log("Virtual machines created: (took " + (t.ElapsedMilliseconds / 1000) + " seconds) to create == " + virtualMachines.Count() + " == virtual machines (4 virtual machines per backend pool)"); //======================================================================= // Get IP addresses from created resources Utilities.Log("IP Addresses in the backend pools are - "); for (var i = 0; i < BackendPools; i++) { for (var j = 0; j < VMCountInAPool; j++) { var pip = (IPublicIPAddress)virtualMachines .CreatedRelatedResource(PublicIpCreatableKeys[i, j]); pip.Refresh(); IPAddresses[i, j] = pip.IPAddress; Utilities.Log("[backend pool =" + i + "][vm = " + j + "] = " + IPAddresses[i, j]); } Utilities.Log("======"); } //======================================================================= // Create an application gateway Utilities.Log("================= CREATE ======================"); Utilities.Log("Creating an application gateway... (this can take about 20 min)"); t = Stopwatch.StartNew(); IApplicationGateway applicationGateway = azure.ApplicationGateways.Define("myFirstAppGateway") .WithRegion(Region.USEast) .WithExistingResourceGroup(resourceGroup) // Request routing rule for HTTP from public 80 to public 8080 .DefineRequestRoutingRule("HTTP-80-to-8080") .FromPublicFrontend() .FromFrontendHttpPort(80) .ToBackendHttpPort(8080) .ToBackendIPAddress(IPAddresses[0, 0]) .ToBackendIPAddress(IPAddresses[0, 1]) .ToBackendIPAddress(IPAddresses[0, 2]) .ToBackendIPAddress(IPAddresses[0, 3]) .Attach() // Request routing rule for HTTPS from public 443 to public 8080 .DefineRequestRoutingRule("HTTPs-443-to-8080") .FromPublicFrontend() .FromFrontendHttpsPort(443) .WithSslCertificateFromPfxFile( new FileInfo( Utilities.GetCertificatePath(SslCertificatePfxPath))) .WithSslCertificatePassword("Abc123") .ToBackendHttpPort(8080) .ToBackendIPAddress(IPAddresses[1, 0]) .ToBackendIPAddress(IPAddresses[1, 1]) .ToBackendIPAddress(IPAddresses[1, 2]) .ToBackendIPAddress(IPAddresses[1, 3]) .Attach() .WithExistingPublicIPAddress(publicIPAddress) .Create(); t.Stop(); Utilities.Log("Application gateway created: (took " + (t.ElapsedMilliseconds / 1000) + " seconds)"); Utilities.PrintAppGateway(applicationGateway); //======================================================================= // Update an application gateway // configure the first routing rule for SSL offload Utilities.Log("================= UPDATE ======================"); Utilities.Log("Updating the application gateway"); t = Stopwatch.StartNew(); applicationGateway.Update() .WithoutRequestRoutingRule("HTTP-80-to-8080") .DefineRequestRoutingRule("HTTPs-1443-to-8080") .FromPublicFrontend() .FromFrontendHttpsPort(1443) .WithSslCertificateFromPfxFile( new FileInfo( Utilities.GetCertificatePath(SslCertificatePfxPath2))) .WithSslCertificatePassword("Abc123") .ToBackendHttpPort(8080) .ToBackendIPAddress(IPAddresses[0, 0]) .ToBackendIPAddress(IPAddresses[0, 1]) .ToBackendIPAddress(IPAddresses[0, 2]) .ToBackendIPAddress(IPAddresses[0, 3]) .WithHostName("www.contoso.com") .WithCookieBasedAffinity() .Attach() .Apply(); t.Stop(); Utilities.Log("Application gateway updated: (took " + (t.ElapsedMilliseconds / 1000) + " seconds)"); Utilities.PrintAppGateway(applicationGateway); } finally { try { Utilities.Log("Deleting Resource Group: " + rgName); azure.ResourceGroups.DeleteByName(rgName); Utilities.Log("Deleted Resource Group: " + rgName); } catch (NullReferenceException) { Utilities.Log("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception e) { Utilities.Log(e.StackTrace); } } } public static void Main(string[] args) { try { //================================================================= // Authenticate var credentials = SdkContext.AzureCredentialsFactory.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION")); var azure = Azure .Configure() .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic) .Authenticate(credentials) .WithDefaultSubscription(); // Print selected subscription Utilities.Log("Selected subscription: " + azure.SubscriptionId); RunSample(azure); } catch (Exception e) { Utilities.Log(e.Message); Utilities.Log(e.StackTrace); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Windows; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Preview; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Differencing; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Projection; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Preview { [Export(typeof(IPreviewFactoryService)), Shared] internal class PreviewFactoryService : ForegroundThreadAffinitizedObject, IPreviewFactoryService { private const double DefaultZoomLevel = 0.75; private readonly ITextViewRoleSet _previewRoleSet; private readonly ITextBufferFactoryService _textBufferFactoryService; private readonly IContentTypeRegistryService _contentTypeRegistryService; private readonly IProjectionBufferFactoryService _projectionBufferFactoryService; private readonly IEditorOptionsFactoryService _editorOptionsFactoryService; private readonly ITextDifferencingSelectorService _differenceSelectorService; private readonly IDifferenceBufferFactoryService _differenceBufferService; private readonly IWpfDifferenceViewerFactoryService _differenceViewerService; [ImportingConstructor] public PreviewFactoryService( ITextBufferFactoryService textBufferFactoryService, IContentTypeRegistryService contentTypeRegistryService, IProjectionBufferFactoryService projectionBufferFactoryService, ITextEditorFactoryService textEditorFactoryService, IEditorOptionsFactoryService editorOptionsFactoryService, ITextDifferencingSelectorService differenceSelectorService, IDifferenceBufferFactoryService differenceBufferService, IWpfDifferenceViewerFactoryService differenceViewerService) { _textBufferFactoryService = textBufferFactoryService; _contentTypeRegistryService = contentTypeRegistryService; _projectionBufferFactoryService = projectionBufferFactoryService; _editorOptionsFactoryService = editorOptionsFactoryService; _differenceSelectorService = differenceSelectorService; _differenceBufferService = differenceBufferService; _differenceViewerService = differenceViewerService; _previewRoleSet = textEditorFactoryService.CreateTextViewRoleSet( TextViewRoles.PreviewRole, PredefinedTextViewRoles.Analyzable); } public SolutionPreviewResult GetSolutionPreviews(Solution oldSolution, Solution newSolution, CancellationToken cancellationToken) { return GetSolutionPreviews(oldSolution, newSolution, DefaultZoomLevel, cancellationToken); } public SolutionPreviewResult GetSolutionPreviews(Solution oldSolution, Solution newSolution, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Note: The order in which previews are added to the below list is significant. // Preview for a changed document is preferred over preview for changed references and so on. var previewItems = new List<SolutionPreviewItem>(); SolutionChangeSummary changeSummary = null; if (newSolution != null) { var solutionChanges = newSolution.GetChanges(oldSolution); foreach (var projectChanges in solutionChanges.GetProjectChanges()) { cancellationToken.ThrowIfCancellationRequested(); var projectId = projectChanges.ProjectId; var oldProject = projectChanges.OldProject; var newProject = projectChanges.NewProject; foreach (var documentId in projectChanges.GetChangedDocuments()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(documentId.ProjectId, documentId, c => CreateChangedDocumentPreviewViewAsync(oldSolution.GetDocument(documentId), newSolution.GetDocument(documentId), zoomLevel, c))); } foreach (var documentId in projectChanges.GetAddedDocuments()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(documentId.ProjectId, documentId, c => CreateAddedDocumentPreviewViewAsync(newSolution.GetDocument(documentId), zoomLevel, c))); } foreach (var documentId in projectChanges.GetRemovedDocuments()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, documentId, c => CreateRemovedDocumentPreviewViewAsync(oldSolution.GetDocument(documentId), zoomLevel, c))); } foreach (var documentId in projectChanges.GetChangedAdditionalDocuments()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(documentId.ProjectId, documentId, c => CreateChangedAdditionalDocumentPreviewViewAsync(oldSolution.GetAdditionalDocument(documentId), newSolution.GetAdditionalDocument(documentId), zoomLevel, c))); } foreach (var documentId in projectChanges.GetAddedAdditionalDocuments()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(documentId.ProjectId, documentId, c => CreateAddedAdditionalDocumentPreviewViewAsync(newSolution.GetAdditionalDocument(documentId), zoomLevel, c))); } foreach (var documentId in projectChanges.GetRemovedAdditionalDocuments()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, documentId, c => CreateRemovedAdditionalDocumentPreviewViewAsync(oldSolution.GetAdditionalDocument(documentId), zoomLevel, c))); } foreach (var metadataReference in projectChanges.GetAddedMetadataReferences()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, null, string.Format(EditorFeaturesResources.AddingReferenceTo, metadataReference.Display, oldProject.Name))); } foreach (var metadataReference in projectChanges.GetRemovedMetadataReferences()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, null, string.Format(EditorFeaturesResources.RemovingReferenceFrom, metadataReference.Display, oldProject.Name))); } foreach (var projectReference in projectChanges.GetAddedProjectReferences()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, null, string.Format(EditorFeaturesResources.AddingReferenceTo, newSolution.GetProject(projectReference.ProjectId).Name, oldProject.Name))); } foreach (var projectReference in projectChanges.GetRemovedProjectReferences()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, null, string.Format(EditorFeaturesResources.RemovingReferenceFrom, oldSolution.GetProject(projectReference.ProjectId).Name, oldProject.Name))); } foreach (var analyzer in projectChanges.GetAddedAnalyzerReferences()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, null, string.Format(EditorFeaturesResources.AddingAnalyzerReferenceTo, analyzer.Display, oldProject.Name))); } foreach (var analyzer in projectChanges.GetRemovedAnalyzerReferences()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, null, string.Format(EditorFeaturesResources.RemovingAnalyzerReferenceFrom, analyzer.Display, oldProject.Name))); } } foreach (var project in solutionChanges.GetAddedProjects()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(project.Id, null, string.Format(EditorFeaturesResources.AddingProject, project.Name))); } foreach (var project in solutionChanges.GetRemovedProjects()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(project.Id, null, string.Format(EditorFeaturesResources.RemovingProject, project.Name))); } foreach (var projectChanges in solutionChanges.GetProjectChanges().Where(ProjectReferencesChanged)) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(projectChanges.OldProject.Id, null, string.Format(EditorFeaturesResources.ChangingProjectReferencesFor, projectChanges.OldProject.Name))); } changeSummary = new SolutionChangeSummary(oldSolution, newSolution, solutionChanges); } return new SolutionPreviewResult(previewItems, changeSummary); } private bool ProjectReferencesChanged(ProjectChanges projectChanges) { var oldProjectReferences = projectChanges.OldProject.ProjectReferences.ToDictionary(r => r.ProjectId); var newProjectReferences = projectChanges.NewProject.ProjectReferences.ToDictionary(r => r.ProjectId); // These are the set of project reference that remained in the project. We don't care // about project references that were added or removed. Those will already be reported. var preservedProjectIds = oldProjectReferences.Keys.Intersect(newProjectReferences.Keys); foreach (var projectId in preservedProjectIds) { var oldProjectReference = oldProjectReferences[projectId]; var newProjectReference = newProjectReferences[projectId]; if (!oldProjectReference.Equals(newProjectReference)) { return true; } } return false; } public Task<object> CreateAddedDocumentPreviewViewAsync(Document document, CancellationToken cancellationToken) { return CreateAddedDocumentPreviewViewAsync(document, DefaultZoomLevel, cancellationToken); } private Task<object> CreateAddedDocumentPreviewViewCoreAsync(ITextBuffer newBuffer, PreviewWorkspace workspace, TextDocument document, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var firstLine = string.Format(EditorFeaturesResources.AddingToWithContent, document.Name, document.Project.Name); var originalBuffer = _projectionBufferFactoryService.CreatePreviewProjectionBuffer( sourceSpans: new List<object> { firstLine, "\r\n" }, registryService: _contentTypeRegistryService); var span = new SnapshotSpan(newBuffer.CurrentSnapshot, Span.FromBounds(0, newBuffer.CurrentSnapshot.Length)) .CreateTrackingSpan(SpanTrackingMode.EdgeExclusive); var changedBuffer = _projectionBufferFactoryService.CreatePreviewProjectionBuffer( sourceSpans: new List<object> { firstLine, "\r\n", span }, registryService: _contentTypeRegistryService); return CreateNewDifferenceViewerAsync(null, workspace, originalBuffer, changedBuffer, zoomLevel, cancellationToken); } public Task<object> CreateAddedDocumentPreviewViewAsync(Document document, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var newBuffer = CreateNewBuffer(document, cancellationToken); // Create PreviewWorkspace around the buffer to be displayed in the diff preview // so that all IDE services (colorizer, squiggles etc.) light up in this buffer. var rightWorkspace = new PreviewWorkspace( document.WithText(newBuffer.AsTextContainer().CurrentText).Project.Solution); rightWorkspace.OpenDocument(document.Id); return CreateAddedDocumentPreviewViewCoreAsync(newBuffer, rightWorkspace, document, zoomLevel, cancellationToken); } public Task<object> CreateAddedAdditionalDocumentPreviewViewAsync(TextDocument document, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var newBuffer = CreateNewPlainTextBuffer(document, cancellationToken); // Create PreviewWorkspace around the buffer to be displayed in the diff preview // so that all IDE services (colorizer, squiggles etc.) light up in this buffer. var rightWorkspace = new PreviewWorkspace( document.Project.Solution.WithAdditionalDocumentText(document.Id, newBuffer.AsTextContainer().CurrentText)); rightWorkspace.OpenAdditionalDocument(document.Id); return CreateAddedDocumentPreviewViewCoreAsync(newBuffer, rightWorkspace, document, zoomLevel, cancellationToken); } public Task<object> CreateRemovedDocumentPreviewViewAsync(Document document, CancellationToken cancellationToken) { return CreateRemovedDocumentPreviewViewAsync(document, DefaultZoomLevel, cancellationToken); } private Task<object> CreateRemovedDocumentPreviewViewCoreAsync(ITextBuffer oldBuffer, PreviewWorkspace workspace, TextDocument document, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var firstLine = string.Format(EditorFeaturesResources.RemovingFromWithContent, document.Name, document.Project.Name); var span = new SnapshotSpan(oldBuffer.CurrentSnapshot, Span.FromBounds(0, oldBuffer.CurrentSnapshot.Length)) .CreateTrackingSpan(SpanTrackingMode.EdgeExclusive); var originalBuffer = _projectionBufferFactoryService.CreatePreviewProjectionBuffer( sourceSpans: new List<object> { firstLine, "\r\n", span }, registryService: _contentTypeRegistryService); var changedBuffer = _projectionBufferFactoryService.CreatePreviewProjectionBuffer( sourceSpans: new List<object> { firstLine, "\r\n" }, registryService: _contentTypeRegistryService); return CreateNewDifferenceViewerAsync(workspace, null, originalBuffer, changedBuffer, zoomLevel, cancellationToken); } public Task<object> CreateRemovedDocumentPreviewViewAsync(Document document, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Note: We don't use the original buffer that is associated with oldDocument // (and possibly open in the editor) for oldBuffer below. This is because oldBuffer // will be used inside a projection buffer inside our inline diff preview below // and platform's implementation currently has a bug where projection buffers // are being leaked. This leak means that if we use the original buffer that is // currently visible in the editor here, the projection buffer span calculation // would be triggered every time user changes some code in this buffer (even though // the diff view would long have been dismissed by the time user edits the code) // resulting in crashes. Instead we create a new buffer from the same content. // TODO: We could use ITextBufferCloneService instead here to clone the original buffer. var oldBuffer = CreateNewBuffer(document, cancellationToken); // Create PreviewWorkspace around the buffer to be displayed in the diff preview // so that all IDE services (colorizer, squiggles etc.) light up in this buffer. var leftDocument = document.Project .RemoveDocument(document.Id) .AddDocument(document.Name, oldBuffer.AsTextContainer().CurrentText); var leftWorkspace = new PreviewWorkspace(leftDocument.Project.Solution); leftWorkspace.OpenDocument(leftDocument.Id); return CreateRemovedDocumentPreviewViewCoreAsync(oldBuffer, leftWorkspace, leftDocument, zoomLevel, cancellationToken); } public Task<object> CreateRemovedAdditionalDocumentPreviewViewAsync(TextDocument document, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Note: We don't use the original buffer that is associated with oldDocument // (and possibly open in the editor) for oldBuffer below. This is because oldBuffer // will be used inside a projection buffer inside our inline diff preview below // and platform's implementation currently has a bug where projection buffers // are being leaked. This leak means that if we use the original buffer that is // currently visible in the editor here, the projection buffer span calculation // would be triggered every time user changes some code in this buffer (even though // the diff view would long have been dismissed by the time user edits the code) // resulting in crashes. Instead we create a new buffer from the same content. // TODO: We could use ITextBufferCloneService instead here to clone the original buffer. var oldBuffer = CreateNewPlainTextBuffer(document, cancellationToken); // Create PreviewWorkspace around the buffer to be displayed in the diff preview // so that all IDE services (colorizer, squiggles etc.) light up in this buffer. var leftDocumentId = DocumentId.CreateNewId(document.Project.Id); var leftSolution = document.Project.Solution .RemoveAdditionalDocument(document.Id) .AddAdditionalDocument(leftDocumentId, document.Name, oldBuffer.AsTextContainer().CurrentText); var leftDocument = leftSolution.GetAdditionalDocument(leftDocumentId); var leftWorkspace = new PreviewWorkspace(leftSolution); leftWorkspace.OpenAdditionalDocument(leftDocumentId); return CreateRemovedDocumentPreviewViewCoreAsync(oldBuffer, leftWorkspace, leftDocument, zoomLevel, cancellationToken); } public Task<object> CreateChangedDocumentPreviewViewAsync(Document oldDocument, Document newDocument, CancellationToken cancellationToken) { return CreateChangedDocumentPreviewViewAsync(oldDocument, newDocument, DefaultZoomLevel, cancellationToken); } public Task<object> CreateChangedDocumentPreviewViewAsync(Document oldDocument, Document newDocument, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Note: We don't use the original buffer that is associated with oldDocument // (and currently open in the editor) for oldBuffer below. This is because oldBuffer // will be used inside a projection buffer inside our inline diff preview below // and platform's implementation currently has a bug where projection buffers // are being leaked. This leak means that if we use the original buffer that is // currently visible in the editor here, the projection buffer span calculation // would be triggered every time user changes some code in this buffer (even though // the diff view would long have been dismissed by the time user edits the code) // resulting in crashes. Instead we create a new buffer from the same content. // TODO: We could use ITextBufferCloneService instead here to clone the original buffer. var oldBuffer = CreateNewBuffer(oldDocument, cancellationToken); var newBuffer = CreateNewBuffer(newDocument, cancellationToken); // Convert the diffs to be line based. // Compute the diffs between the old text and the new. var diffResult = ComputeEditDifferences(oldDocument, newDocument, cancellationToken); // Need to show the spans in the right that are different. // We also need to show the spans that are in conflict. var originalSpans = GetOriginalSpans(diffResult, cancellationToken); var changedSpans = GetChangedSpans(diffResult, cancellationToken); var description = default(string); var allSpans = default(NormalizedSpanCollection); if (newDocument.SupportsSyntaxTree) { var newRoot = newDocument.GetSyntaxRootAsync(cancellationToken).WaitAndGetResult(cancellationToken); var conflictNodes = newRoot.GetAnnotatedNodesAndTokens(ConflictAnnotation.Kind); var conflictSpans = conflictNodes.Select(n => n.Span.ToSpan()).ToList(); var conflictDescriptions = conflictNodes.SelectMany(n => n.GetAnnotations(ConflictAnnotation.Kind)) .Select(a => ConflictAnnotation.GetDescription(a)) .Distinct(); var warningNodes = newRoot.GetAnnotatedNodesAndTokens(WarningAnnotation.Kind); var warningSpans = warningNodes.Select(n => n.Span.ToSpan()).ToList(); var warningDescriptions = warningNodes.SelectMany(n => n.GetAnnotations(WarningAnnotation.Kind)) .Select(a => WarningAnnotation.GetDescription(a)) .Distinct(); var suppressDiagnosticsNodes = newRoot.GetAnnotatedNodesAndTokens(SuppressDiagnosticsAnnotation.Kind); var suppressDiagnosticsSpans = suppressDiagnosticsNodes.Select(n => n.Span.ToSpan()).ToList(); AttachAnnotationsToBuffer(newBuffer, conflictSpans, warningSpans, suppressDiagnosticsSpans); description = conflictSpans.Count == 0 && warningSpans.Count == 0 ? null : string.Join(Environment.NewLine, conflictDescriptions.Concat(warningDescriptions)); allSpans = new NormalizedSpanCollection(conflictSpans.Concat(warningSpans).Concat(changedSpans)); } else { allSpans = new NormalizedSpanCollection(changedSpans); } var originalLineSpans = CreateLineSpans(oldBuffer.CurrentSnapshot, originalSpans, cancellationToken); var changedLineSpans = CreateLineSpans(newBuffer.CurrentSnapshot, allSpans, cancellationToken); if (!originalLineSpans.Any()) { // This means that we have no differences (likely because of conflicts). // In such cases, use the same spans for the left (old) buffer as the right (new) buffer. originalLineSpans = changedLineSpans; } // Create PreviewWorkspaces around the buffers to be displayed on the left and right // so that all IDE services (colorizer, squiggles etc.) light up in these buffers. var leftDocument = oldDocument.Project .RemoveDocument(oldDocument.Id) .AddDocument(oldDocument.Name, oldBuffer.AsTextContainer().CurrentText, oldDocument.Folders, oldDocument.FilePath); var leftWorkspace = new PreviewWorkspace(leftDocument.Project.Solution); leftWorkspace.OpenDocument(leftDocument.Id); var rightWorkspace = new PreviewWorkspace( newDocument.WithText(newBuffer.AsTextContainer().CurrentText).Project.Solution); rightWorkspace.OpenDocument(newDocument.Id); return CreateChangedDocumentViewAsync( oldBuffer, newBuffer, description, originalLineSpans, changedLineSpans, leftWorkspace, rightWorkspace, zoomLevel, cancellationToken); } public Task<object> CreateChangedAdditionalDocumentPreviewViewAsync(TextDocument oldDocument, TextDocument newDocument, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Note: We don't use the original buffer that is associated with oldDocument // (and currently open in the editor) for oldBuffer below. This is because oldBuffer // will be used inside a projection buffer inside our inline diff preview below // and platform's implementation currently has a bug where projection buffers // are being leaked. This leak means that if we use the original buffer that is // currently visible in the editor here, the projection buffer span calculation // would be triggered every time user changes some code in this buffer (even though // the diff view would long have been dismissed by the time user edits the code) // resulting in crashes. Instead we create a new buffer from the same content. // TODO: We could use ITextBufferCloneService instead here to clone the original buffer. var oldBuffer = CreateNewPlainTextBuffer(oldDocument, cancellationToken); var newBuffer = CreateNewPlainTextBuffer(newDocument, cancellationToken); // Convert the diffs to be line based. // Compute the diffs between the old text and the new. var diffResult = ComputeEditDifferences(oldDocument, newDocument, cancellationToken); // Need to show the spans in the right that are different. var originalSpans = GetOriginalSpans(diffResult, cancellationToken); var changedSpans = GetChangedSpans(diffResult, cancellationToken); string description = null; var originalLineSpans = CreateLineSpans(oldBuffer.CurrentSnapshot, originalSpans, cancellationToken); var changedLineSpans = CreateLineSpans(newBuffer.CurrentSnapshot, changedSpans, cancellationToken); // TODO: Why aren't we attaching conflict / warning annotations here like we do for regular documents above? // Create PreviewWorkspaces around the buffers to be displayed on the left and right // so that all IDE services (colorizer, squiggles etc.) light up in these buffers. var leftDocumentId = DocumentId.CreateNewId(oldDocument.Project.Id); var leftSolution = oldDocument.Project.Solution .RemoveAdditionalDocument(oldDocument.Id) .AddAdditionalDocument(leftDocumentId, oldDocument.Name, oldBuffer.AsTextContainer().CurrentText); var leftWorkspace = new PreviewWorkspace(leftSolution); leftWorkspace.OpenAdditionalDocument(leftDocumentId); var rightWorkSpace = new PreviewWorkspace( oldDocument.Project.Solution.WithAdditionalDocumentText(oldDocument.Id, newBuffer.AsTextContainer().CurrentText)); rightWorkSpace.OpenAdditionalDocument(newDocument.Id); return CreateChangedDocumentViewAsync( oldBuffer, newBuffer, description, originalLineSpans, changedLineSpans, leftWorkspace, rightWorkSpace, zoomLevel, cancellationToken); } private Task<object> CreateChangedDocumentViewAsync(ITextBuffer oldBuffer, ITextBuffer newBuffer, string description, List<LineSpan> originalSpans, List<LineSpan> changedSpans, PreviewWorkspace leftWorkspace, PreviewWorkspace rightWorkspace, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (!(originalSpans.Any() && changedSpans.Any())) { // Both line spans must be non-empty. Otherwise, below projection buffer factory API call will throw. // So if either is empty (signaling that there are no changes to preview in the document), then we bail out. // This can happen in cases where the user has already applied the fix and light bulb has already been dismissed, // but platform hasn't cancelled the preview operation yet. Since the light bulb has already been dismissed at // this point, the preview that we return will never be displayed to the user. So returning null here is harmless. return SpecializedTasks.Default<object>(); } var originalBuffer = _projectionBufferFactoryService.CreateProjectionBufferWithoutIndentation( _contentTypeRegistryService, _editorOptionsFactoryService.GlobalOptions, oldBuffer.CurrentSnapshot, "...", description, originalSpans.ToArray()); var changedBuffer = _projectionBufferFactoryService.CreateProjectionBufferWithoutIndentation( _contentTypeRegistryService, _editorOptionsFactoryService.GlobalOptions, newBuffer.CurrentSnapshot, "...", description, changedSpans.ToArray()); return CreateNewDifferenceViewerAsync(leftWorkspace, rightWorkspace, originalBuffer, changedBuffer, zoomLevel, cancellationToken); } private static void AttachAnnotationsToBuffer( ITextBuffer newBuffer, IEnumerable<Span> conflictSpans, IEnumerable<Span> warningSpans, IEnumerable<Span> suppressDiagnosticsSpans) { // Attach the spans to the buffer. newBuffer.Properties.AddProperty(PredefinedPreviewTaggerKeys.ConflictSpansKey, new NormalizedSnapshotSpanCollection(newBuffer.CurrentSnapshot, conflictSpans)); newBuffer.Properties.AddProperty(PredefinedPreviewTaggerKeys.WarningSpansKey, new NormalizedSnapshotSpanCollection(newBuffer.CurrentSnapshot, warningSpans)); newBuffer.Properties.AddProperty(PredefinedPreviewTaggerKeys.SuppressDiagnosticsSpansKey, new NormalizedSnapshotSpanCollection(newBuffer.CurrentSnapshot, suppressDiagnosticsSpans)); } private ITextBuffer CreateNewBuffer(Document document, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // is it okay to create buffer from threads other than UI thread? var contentTypeService = document.Project.LanguageServices.GetService<IContentTypeLanguageService>(); var contentType = contentTypeService.GetDefaultContentType(); return _textBufferFactoryService.CreateTextBuffer(document.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken).ToString(), contentType); } private ITextBuffer CreateNewPlainTextBuffer(TextDocument document, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var contentType = _textBufferFactoryService.TextContentType; return _textBufferFactoryService.CreateTextBuffer(document.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken).ToString(), contentType); } private async Task<object> CreateNewDifferenceViewerAsync(PreviewWorkspace leftWorkspace, PreviewWorkspace rightWorkspace, IProjectionBuffer originalBuffer, IProjectionBuffer changedBuffer, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // leftWorkspace can be null if the change is adding a document. // rightWorkspace can be null if the change is removing a document. // However both leftWorkspace and rightWorkspace can't be null at the same time. Contract.ThrowIfTrue((leftWorkspace == null) && (rightWorkspace == null)); var diffBuffer = _differenceBufferService.CreateDifferenceBuffer( originalBuffer, changedBuffer, new StringDifferenceOptions(), disableEditing: true); var diffViewer = _differenceViewerService.CreateDifferenceView(diffBuffer, _previewRoleSet); diffViewer.Closed += (s, e) => { if (leftWorkspace != null) { leftWorkspace.Dispose(); leftWorkspace = null; } if (rightWorkspace != null) { rightWorkspace.Dispose(); rightWorkspace = null; } }; const string DiffOverviewMarginName = "deltadifferenceViewerOverview"; if (leftWorkspace == null) { diffViewer.ViewMode = DifferenceViewMode.RightViewOnly; diffViewer.RightView.ZoomLevel *= zoomLevel; diffViewer.RightHost.GetTextViewMargin(DiffOverviewMarginName).VisualElement.Visibility = Visibility.Collapsed; } else if (rightWorkspace == null) { diffViewer.ViewMode = DifferenceViewMode.LeftViewOnly; diffViewer.LeftView.ZoomLevel *= zoomLevel; diffViewer.LeftHost.GetTextViewMargin(DiffOverviewMarginName).VisualElement.Visibility = Visibility.Collapsed; } else { diffViewer.ViewMode = DifferenceViewMode.Inline; diffViewer.InlineView.ZoomLevel *= zoomLevel; diffViewer.InlineHost.GetTextViewMargin(DiffOverviewMarginName).VisualElement.Visibility = Visibility.Collapsed; } // Disable focus / tab stop for the diff viewer. diffViewer.RightView.VisualElement.Focusable = false; diffViewer.LeftView.VisualElement.Focusable = false; diffViewer.InlineView.VisualElement.Focusable = false; // This code path must be invoked on UI thread. AssertIsForeground(); // We use ConfigureAwait(true) to stay on the UI thread. await diffViewer.SizeToFitAsync().ConfigureAwait(true); if (leftWorkspace != null) { leftWorkspace.EnableDiagnostic(); } if (rightWorkspace != null) { rightWorkspace.EnableDiagnostic(); } return new DifferenceViewerPreview(diffViewer); } private List<LineSpan> CreateLineSpans(ITextSnapshot textSnapshot, NormalizedSpanCollection allSpans, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var result = new List<LineSpan>(); foreach (var span in allSpans) { cancellationToken.ThrowIfCancellationRequested(); var lineSpan = GetLineSpan(textSnapshot, span); MergeLineSpans(result, lineSpan); } return result; } // Find the lines that surround the span of the difference. Try to expand the span to // include both the previous and next lines so that we can show more context to the // user. private LineSpan GetLineSpan( ITextSnapshot snapshot, Span span) { var startLine = snapshot.GetLineNumberFromPosition(span.Start); var endLine = snapshot.GetLineNumberFromPosition(span.End); if (startLine > 0) { startLine--; } if (endLine < snapshot.LineCount) { endLine++; } return LineSpan.FromBounds(startLine, endLine); } // Adds a line span to the spans we've been collecting. If the line span overlaps or // abuts a previous span then the two are merged. private static void MergeLineSpans(List<LineSpan> lineSpans, LineSpan nextLineSpan) { if (lineSpans.Count > 0) { var lastLineSpan = lineSpans.Last(); // We merge them if there's no more than one line between the two. Otherwise // we'd show "..." between two spans where we could just show the actual code. if (nextLineSpan.Start >= lastLineSpan.Start && nextLineSpan.Start <= (lastLineSpan.End + 1)) { nextLineSpan = LineSpan.FromBounds(lastLineSpan.Start, nextLineSpan.End); lineSpans.RemoveAt(lineSpans.Count - 1); } } lineSpans.Add(nextLineSpan); } private IHierarchicalDifferenceCollection ComputeEditDifferences(TextDocument oldDocument, TextDocument newDocument, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Get the text that's actually in the editor. var oldText = oldDocument.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken); var newText = newDocument.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken); // Defer to the editor to figure out what changes the client made. var diffService = _differenceSelectorService.GetTextDifferencingService( oldDocument.Project.LanguageServices.GetService<IContentTypeLanguageService>().GetDefaultContentType()); diffService = diffService ?? _differenceSelectorService.DefaultTextDifferencingService; return diffService.DiffStrings(oldText.ToString(), newText.ToString(), new StringDifferenceOptions() { DifferenceType = StringDifferenceTypes.Word | StringDifferenceTypes.Line, }); } private NormalizedSpanCollection GetOriginalSpans(IHierarchicalDifferenceCollection diffResult, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var lineSpans = new List<Span>(); foreach (var difference in diffResult) { cancellationToken.ThrowIfCancellationRequested(); var mappedSpan = diffResult.LeftDecomposition.GetSpanInOriginal(difference.Left); lineSpans.Add(mappedSpan); } return new NormalizedSpanCollection(lineSpans); } private NormalizedSpanCollection GetChangedSpans(IHierarchicalDifferenceCollection diffResult, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var lineSpans = new List<Span>(); foreach (var difference in diffResult) { cancellationToken.ThrowIfCancellationRequested(); var mappedSpan = diffResult.RightDecomposition.GetSpanInOriginal(difference.Right); lineSpans.Add(mappedSpan); } return new NormalizedSpanCollection(lineSpans); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Text; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Impl.Memory; using Apache.Ignite.Core.Impl.Unmanaged; using Apache.Ignite.Core.Impl.Unmanaged.Jni; using Apache.Ignite.Core.Log; /// <summary> /// Native interface manager. /// </summary> internal static class IgniteManager { /** Java Command line argument: Xms. Case sensitive. */ private const string CmdJvmMinMemJava = "-Xms"; /** Java Command line argument: Xmx. Case sensitive. */ private const string CmdJvmMaxMemJava = "-Xmx"; /** Java Command line argument: file.encoding. Case sensitive. */ private const string CmdJvmFileEncoding = "-Dfile.encoding="; /** Monitor for DLL load synchronization. */ private static readonly object SyncRoot = new object(); /** Configuration used on JVM start. */ private static JvmConfiguration _jvmCfg; /** Memory manager. */ private static readonly PlatformMemoryManager Mem = new PlatformMemoryManager(1024); /// <summary> /// Create JVM. /// </summary> /// <param name="cfg">Configuration.</param> /// <param name="log">Logger</param> /// <returns>Callback context.</returns> internal static UnmanagedCallbacks CreateJvmContext(IgniteConfiguration cfg, ILogger log) { lock (SyncRoot) { // 1. Warn about possible configuration inconsistency. JvmConfiguration jvmCfg = JvmConfig(cfg); if (!cfg.SuppressWarnings && _jvmCfg != null) { if (!_jvmCfg.Equals(jvmCfg)) { log.Warn("Attempting to start Ignite node with different Java " + "configuration; current Java configuration will be ignored (consider " + "starting node in separate process) [oldConfig=" + _jvmCfg + ", newConfig=" + jvmCfg + ']'); } } // 2. Create unmanaged pointer. var jvm = CreateJvm(cfg, log); if (cfg.RedirectJavaConsoleOutput) { jvm.EnableJavaConsoleWriter(); } var cbs = new UnmanagedCallbacks(log, jvm); jvm.RegisterCallbacks(cbs); // 3. If this is the first JVM created, preserve configuration. if (_jvmCfg == null) { _jvmCfg = jvmCfg; } return cbs; } } /// <summary> /// Memory manager attached to currently running JVM. /// </summary> internal static PlatformMemoryManager Memory { get { return Mem; } } /// <summary> /// Create JVM. /// </summary> /// <returns>JVM.</returns> private static Jvm CreateJvm(IgniteConfiguration cfg, ILogger log) { // Do not bother with classpath when JVM exists. var jvm = Jvm.Get(true); if (jvm != null) { return jvm; } var cp = Classpath.CreateClasspath(cfg, log: log); var jvmOpts = GetMergedJvmOptions(cfg); jvmOpts.Add(cp); return Jvm.GetOrCreate(jvmOpts); } /// <summary> /// Gets JvmOptions collection merged with individual properties (Min/Max mem, etc) according to priority. /// </summary> private static IList<string> GetMergedJvmOptions(IgniteConfiguration cfg) { var jvmOpts = cfg.JvmOptions == null ? new List<string>() : cfg.JvmOptions.ToList(); // JvmInitialMemoryMB / JvmMaxMemoryMB have lower priority than CMD_JVM_OPT if (!jvmOpts.Any(opt => opt.StartsWith(CmdJvmMinMemJava, StringComparison.OrdinalIgnoreCase)) && cfg.JvmInitialMemoryMb != IgniteConfiguration.DefaultJvmInitMem) jvmOpts.Add(string.Format(CultureInfo.InvariantCulture, "{0}{1}m", CmdJvmMinMemJava, cfg.JvmInitialMemoryMb)); if (!jvmOpts.Any(opt => opt.StartsWith(CmdJvmMaxMemJava, StringComparison.OrdinalIgnoreCase)) && cfg.JvmMaxMemoryMb != IgniteConfiguration.DefaultJvmMaxMem) jvmOpts.Add(string.Format(CultureInfo.InvariantCulture, "{0}{1}m", CmdJvmMaxMemJava, cfg.JvmMaxMemoryMb)); if (!jvmOpts.Any(opt => opt.StartsWith(CmdJvmFileEncoding, StringComparison.Ordinal))) jvmOpts.Add(string.Format(CultureInfo.InvariantCulture, "{0}UTF-8", CmdJvmFileEncoding)); return jvmOpts; } /// <summary> /// Create JVM configuration value object. /// </summary> /// <param name="cfg">Configuration.</param> /// <returns>JVM configuration.</returns> private static JvmConfiguration JvmConfig(IgniteConfiguration cfg) { return new JvmConfiguration { Home = cfg.IgniteHome, Dll = cfg.JvmDllPath, Classpath = cfg.JvmClasspath, Options = cfg.JvmOptions }; } /// <summary> /// JVM configuration. /// </summary> private class JvmConfiguration { /// <summary> /// Gets or sets the home. /// </summary> public string Home { get; set; } /// <summary> /// Gets or sets the DLL. /// </summary> public string Dll { get; set; } /// <summary> /// Gets or sets the cp. /// </summary> public string Classpath { get; set; } /// <summary> /// Gets or sets the options. /// </summary> public ICollection<string> Options { get; set; } /** <inheritDoc /> */ public override int GetHashCode() { return 0; } /** <inheritDoc /> */ [SuppressMessage("ReSharper", "FunctionComplexityOverflow")] public override bool Equals(object obj) { JvmConfiguration other = obj as JvmConfiguration; if (other == null) return false; if (!string.Equals(Home, other.Home, StringComparison.OrdinalIgnoreCase)) return false; if (!string.Equals(Classpath, other.Classpath, StringComparison.OrdinalIgnoreCase)) return false; if (!string.Equals(Dll, other.Dll, StringComparison.OrdinalIgnoreCase)) return false; return (Options == null && other.Options == null) || (Options != null && other.Options != null && Options.Count == other.Options.Count && !Options.Except(other.Options).Any()); } /** <inheritDoc /> */ public override string ToString() { var sb = new StringBuilder("[IgniteHome=" + Home + ", JvmDllPath=" + Dll); if (Options != null && Options.Count > 0) { sb.Append(", JvmOptions=["); bool first = true; foreach (string opt in Options) { if (first) first = false; else sb.Append(", "); sb.Append(opt); } sb.Append(']'); } sb.Append(", Classpath=" + Classpath + ']'); return sb.ToString(); } } } }
using System; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Controllers; using Breeze.WebApi; using Newtonsoft.Json.Linq; using DocCode.DataAccess; using Northwind.Models; namespace DocCode.Controllers { [BreezeController] public class NorthwindController : ApiController { private readonly NorthwindRepository _repository; public NorthwindController() : this(null){} // Todo: inject via an interface rather than "new" the concrete class public NorthwindController(NorthwindRepository repository) { _repository = repository ?? new NorthwindRepository(); } protected override void Initialize(HttpControllerContext controllerContext) { base.Initialize(controllerContext); _repository.UserSessionId = getUserSessionId(); } // ~/breeze/northwind/Metadata [HttpGet] public string Metadata() { return _repository.Metadata; } // ~/breeze/northwind/SaveChanges [HttpPost] public SaveResult SaveChanges(JObject saveBundle) { return _repository.SaveChanges(saveBundle); } [HttpGet] public IQueryable<Customer> Customers() { return _repository.Customers; } [HttpGet] public IQueryable<Customer> CustomersAndOrders() { return _repository.CustomersAndOrders; } [HttpGet] [BreezeQueryable] public HttpResponseMessage CustomersAsHRM() { return Request.CreateResponse(HttpStatusCode.OK, _repository.Customers); } [HttpGet] public IQueryable<Order> OrdersForProduct(int productID = 0) { return _repository.OrdersForProduct(productID); } [HttpGet] public IQueryable<Customer> CustomersStartingWithA() { return _repository.CustomersStartingWithA; } // "withParameters" example [HttpGet] public IQueryable<Customer> CustomersStartingWith(string companyName) { var custs = _repository.Customers.Where(c => c.CompanyName.StartsWith(companyName)); return custs; } [HttpGet] public IQueryable<Order> Orders() { return _repository.Orders; } [HttpGet] public IQueryable<Order> OrdersAndCustomers() { return _repository.OrdersAndCustomers; } [HttpGet] // should guard against pulling too much data with limiting Queryable, e.g. //[Queryable(MaxTop = 10)] public IQueryable<Order> OrdersAndDetails() { return _repository.OrdersAndDetails; } [HttpGet] public IQueryable<Employee> Employees() { return _repository.Employees; } [HttpGet] public IQueryable<OrderDetail> OrderDetails() { return _repository.OrderDetails; } [HttpGet] public IQueryable<Product> Products() { return _repository.Products; } [HttpGet] public IQueryable<ProductDto> ProductDtos(int? supplierID=null) { // TODO: move the following into the repository where it belongs var query = _repository.Products .Where(x => x.CategoryID == 1); // a surrogate for a security filter if (supplierID != null) { query = query.Where(x => x.SupplierID == supplierID); } return query.Select(x => new ProductDto { ProductID = x.ProductID, ProductName = x.ProductName }); } [HttpGet] public IQueryable<Region> Regions() { return _repository.Regions; } [HttpGet] public IQueryable<Supplier> Suppliers() { return _repository.Suppliers; } [HttpGet] public IQueryable<Territory> Territories() { return _repository.Territories; } // Demonstrate a "View Entity" a selection of "safe" entity properties // UserPartial is not in Metadata and won't be client cached unless // you define metadata for it on the Breeze client [HttpGet] public IQueryable<UserPartial> UserPartials() { return _repository.UserPartials; } // Useful when need ONE user and its roles // Could further restrict to the authenticated user [HttpGet] public UserPartial GetUserById(int id) { return _repository.GetUserById(id); } /********************************************************* * Lookups: Two ways of sending a bag of diverse entities; * no obvious advantage to one vs. the other ********************************************************/ /// <summary> /// Query returing an array of the entity lists: /// Regions, Territories, and Categories. /// </summary> /// <returns> /// Returns an array, not an IQueryable. /// Each array element is a different entity list. /// Note that the list elements arrive on the client /// as objects, not arrays, with properties /// such as '0', '1', '2' ... /// See the DocCode:QueryTests (Projections) module. /// </returns> /// <remarks> /// N.B. Category is only available through lookup; /// it doesn't have its own query method. /// </remarks> [HttpGet] public object LookupsArray() { var regions = _repository.Regions; var territories = _repository.Territories; var categories = _repository.Categories; var lookups = new object[] { regions, territories, categories }; return lookups; } /// <summary> /// Query returing a 1-element array with a lookups object whose /// properties are all Regions, Territories, and Categories. /// </summary> /// <returns> /// Returns one object, not an IQueryable, /// whose properties are "region", "territory", "category". /// The items arrive as arrays. /// </returns> /// <remarks> /// N.B. Category is only available through lookup; /// it doesn't have its own query method. /// </remarks> [HttpGet] public object Lookups() { var regions = _repository.Regions; var territories = _repository.Territories; var categories = _repository.Categories; var lookups = new { regions, territories, categories }; return lookups; } // ~/breeze/northwind/reset - clears the current user's changes // ~/breeze/Northwind/reset/?options=fullreset - clear out all user changes; back to base state. [HttpPost] public string Reset(string options = "") { return _repository.Reset(options); } /// <summary> /// Get the UserSessionId from value in the request header /// </summary> private Guid getUserSessionId() { try { var id = Request.Headers.GetValues("X-UserSessionId").First(); return Guid.Parse(id); } catch { return Guid.Empty; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.Common.Git { using System; using System.Collections.Concurrent; using System.Diagnostics; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Web; using Microsoft.DocAsCode.Plugins; public static class GitUtility { private static readonly string CommandName = "git"; private static readonly int GitTimeOut = 1000; private static readonly string GetRepoRootCommand = "rev-parse --show-toplevel"; private static readonly string GetLocalBranchCommand = "rev-parse --abbrev-ref HEAD"; private static readonly string GetLocalBranchCommitIdCommand = "rev-parse HEAD"; private static readonly string GetRemoteBranchCommand = "rev-parse --abbrev-ref @{u}"; private static readonly Regex GitHubRepoUrlRegex = new Regex(@"^((https|http):\/\/(.+@)?github\.com\/|git@github\.com:)(?<account>\S+)\/(?<repository>[A-Za-z0-9_.-]+)(\.git)?\/?$", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.RightToLeft); private static readonly Regex VsoGitRepoUrlRegex = new Regex(@"^(((https|http):\/\/(?<account>\S+))|((ssh:\/\/)(?<account>\S+)@(?:\S+)))\.visualstudio\.com(?<port>:\d+)?(?:\/DefaultCollection)?(\/(?<project>[^\/]+)(\/.*)*)*\/(?:_git|_ssh)\/(?<repository>([^._,]|[^._,][^@~;{}'+=,<>|\/\\?:&$*""#[\]]*[^.,]))$", RegexOptions.Compiled | RegexOptions.IgnoreCase); private static readonly string GitHubNormalizedRepoUrlTemplate = "https://github.com/{0}/{1}"; private static readonly string VsoNormalizedRepoUrlTemplate = "https://{0}.visualstudio.com/DefaultCollection/{1}/_git/{2}"; // TODO: only get default remote's url currently. private static readonly string GetOriginUrlCommand = "config --get remote.origin.url"; private static readonly string[] BuildSystemBranchName = new[] { "APPVEYOR_REPO_BRANCH", // AppVeyor "Git_Branch", // Team City "CI_BUILD_REF_NAME", // GitLab CI "GIT_LOCAL_BRANCH", // Jenkins "GIT_BRANCH", // Jenkins "BUILD_SOURCEBRANCHNAME" // VSO Agent }; private static readonly ConcurrentDictionary<string, GitRepoInfo> Cache = new ConcurrentDictionary<string, GitRepoInfo>(); private static bool? GitCommandExists = null; private static object SyncRoot = new object(); public static GitDetail TryGetFileDetail(string filePath) { if (EnvironmentContext.GitFeaturesDisabled) { return null; } try { return GetFileDetail(filePath); } catch (Exception ex) { Logger.LogWarning($"Skipping GetFileDetail. Exception found: {ex.GetType()}, Message: {ex.Message}"); Logger.LogVerbose(ex.ToString()); } return null; } public static GitRepoInfo Parse(string repoUrl) { if (string.IsNullOrEmpty(repoUrl)) { throw new ArgumentNullException(nameof(repoUrl)); } var githubMatch = GitHubRepoUrlRegex.Match(repoUrl); if (githubMatch.Success) { var gitRepositoryAccount = githubMatch.Groups["account"].Value; var gitRepositoryName = githubMatch.Groups["repository"].Value; return new GitRepoInfo { RepoType = RepoType.GitHub, RepoAccount = gitRepositoryAccount, RepoName = gitRepositoryName, RepoProject = null, NormalizedRepoUrl = new Uri(string.Format(GitHubNormalizedRepoUrlTemplate, gitRepositoryAccount, gitRepositoryName)) }; } var vsoMatch = VsoGitRepoUrlRegex.Match(repoUrl); if (vsoMatch.Success) { var gitRepositoryAccount = vsoMatch.Groups["account"].Value; var gitRepositoryName = vsoMatch.Groups["repository"].Value; // VSO has this logic: if the project name and repository name are same, then VSO will return the url without project name. // Sample: if you visit https://cpubwin.visualstudio.com/drivers/_git/drivers, it will return https://cpubwin.visualstudio.com/_git/drivers // We need to normalize it to keep same behavior with other projects. Always return https://<account>.visualstudio.com/<collection>/<project>/_git/<repository> var gitRepositoryProject = string.IsNullOrEmpty(vsoMatch.Groups["project"].Value) ? gitRepositoryName : vsoMatch.Groups["project"].Value; return new GitRepoInfo { RepoType = RepoType.Vso, RepoAccount = gitRepositoryAccount, RepoName = Uri.UnescapeDataString(gitRepositoryName), RepoProject = gitRepositoryProject, NormalizedRepoUrl = new Uri(string.Format(VsoNormalizedRepoUrlTemplate, gitRepositoryAccount, gitRepositoryProject, gitRepositoryName)) }; } throw new NotSupportedException($"'{repoUrl}' is not a valid Vso/GitHub repository url"); } public static Uri CombineUrl(string normalizedRepoUrl, string refName, string relativePathToRepoRoot, RepoType repoType) { switch (repoType) { case RepoType.GitHub: return new Uri(Path.Combine(normalizedRepoUrl, "blob", refName, relativePathToRepoRoot)); case RepoType.Vso: var rootedPathToRepo = "/" + relativePathToRepoRoot.ToNormalizedPath(); return new Uri($"{normalizedRepoUrl}?path={HttpUtility.UrlEncode(rootedPathToRepo)}&version=GB{HttpUtility.UrlEncode(refName)}&_a=contents"); default: throw new NotSupportedException($"RepoType '{repoType}' is not supported."); } } #region Private Methods private static GitDetail GetFileDetail(string filePath) { if (string.IsNullOrEmpty(filePath) || !ExistGitCommand()) { return null; } var path = Path.Combine(EnvironmentContext.BaseDirectory, filePath).ToNormalizedPath(); var detail = GetFileDetailCore(path); return detail; } private static GitRepoInfo GetRepoInfo(string directory) { if (directory == null) { return null; } if (IsGitRoot(directory)) { return Cache.GetOrAdd(directory, GetRepoInfoCore); } var parentDirInfo = Directory.GetParent(directory); if (parentDirInfo == null) { return null; } return Cache.GetOrAdd(directory, d => GetRepoInfo(parentDirInfo.FullName)); } private static bool IsGitRoot(string directory) { var gitPath = Path.Combine(directory, ".git"); // git submodule contains only a .git file instead of a .git folder return Directory.Exists(gitPath) || File.Exists(gitPath); } private static GitDetail GetFileDetailCore(string filePath) { string directory; if (PathUtility.IsDirectory(filePath)) { directory = filePath; } else { directory = Path.GetDirectoryName(filePath); } var repoInfo = Cache.GetOrAdd(directory, GetRepoInfo); return new GitDetail { // TODO: remove commit id to avoid config hash changed // CommitId = repoInfo?.RemoteHeadCommitId, RemoteBranch = repoInfo?.RemoteBranch, RemoteRepositoryUrl = repoInfo?.RemoteOriginUrl, RelativePath = PathUtility.MakeRelativePath(repoInfo?.RepoRootPath, filePath) }; } private static GitRepoInfo GetRepoInfoCore(string directory) { var repoRootPath = RunGitCommandAndGetLastLine(directory, GetRepoRootCommand); // the path of repo root got from git config file should be the same with path got from git command Debug.Assert(FilePathComparer.OSPlatformSensitiveComparer.Equals(repoRootPath, directory)); var branchNames = GetBranchNames(repoRootPath); var originUrl = RunGitCommandAndGetLastLine(repoRootPath, GetOriginUrlCommand); var repoInfo = new GitRepoInfo { // TODO: remove commit id to avoid config hash changed //LocalHeadCommitId = RunGitCommandAndGetFirstLine(repoRootPath, GetLocalHeadIdCommand), //RemoteHeadCommitId = TryRunGitCommandAndGetFirstLine(repoRootPath, GetRemoteHeadIdCommand), RemoteOriginUrl = originUrl, RepoRootPath = repoRootPath, LocalBranch = branchNames.Item1, RemoteBranch = branchNames.Item2 }; return repoInfo; } private static Tuple<string, string> GetBranchNames(string repoRootPath) { // Use the branch name specified by the environment variable. var localBranch = Environment.GetEnvironmentVariable("DOCFX_SOURCE_BRANCH_NAME"); if (!string.IsNullOrEmpty(localBranch)) { Logger.LogInfo($"For git repo <{repoRootPath}>, using branch '{localBranch}' from the environment variable DOCFX_SOURCE_BRANCH_NAME."); return Tuple.Create(localBranch, localBranch); } var isDetachedHead = "HEAD" == RunGitCommandAndGetLastLine(repoRootPath, GetLocalBranchCommand); if (isDetachedHead) { return GetBranchNamesFromDetachedHead(repoRootPath); } localBranch = RunGitCommandAndGetLastLine(repoRootPath, GetLocalBranchCommand); string remoteBranch; try { remoteBranch = RunGitCommandAndGetLastLine(repoRootPath, GetRemoteBranchCommand); var index = remoteBranch.IndexOf('/'); if (index > 0) { remoteBranch = remoteBranch.Substring(index + 1); } } catch (Exception ex) { Logger.LogInfo($"For git repo <{repoRootPath}>, can't find remote branch in this repo and fallback to use local branch [{localBranch}]: {ex.Message}"); remoteBranch = localBranch; } return Tuple.Create(localBranch, remoteBranch); } // Many build systems use a "detached head", which means that the normal git commands // to get branch names do not work. Thankfully, they set an environment variable. private static Tuple<string, string> GetBranchNamesFromDetachedHead(string repoRootPath) { foreach (var name in BuildSystemBranchName) { var branchName = Environment.GetEnvironmentVariable(name); if (!string.IsNullOrEmpty(branchName)) { Logger.LogInfo($"For git repo <{repoRootPath}>, using branch '{branchName}' from the environment variable {name}."); return Tuple.Create(branchName, branchName); } } // Use the comment id as the branch name. var commitId = RunGitCommandAndGetLastLine(repoRootPath, GetLocalBranchCommitIdCommand); Logger.LogInfo($"For git repo <{repoRootPath}>, using commit id {commitId} as the branch name."); return Tuple.Create(commitId, commitId); } private static void ProcessErrorMessage(string message) { throw new GitException(message); } private static string TryRunGitCommand(string repoPath, string arguments) { var content = new StringBuilder(); try { RunGitCommand(repoPath, arguments, output => content.AppendLine(output)); } catch (Exception ex) { Logger.LogWarning($"Skipping RunGitCommand. Exception found: {ex.GetType()}, Message: {ex.Message}"); Logger.LogVerbose(ex.ToString()); } return content.Length == 0 ? null : content.ToString(); } private static string TryRunGitCommandAndGetLastLine(string repoPath, string arguments) { string content = null; try { content = RunGitCommandAndGetLastLine(repoPath, arguments); } catch (Exception ex) { Logger.LogWarning($"Skipping RunGitCommandAndGetLastLine. Exception found: {ex.GetType()}, Message: {ex.Message}"); Logger.LogVerbose(ex.ToString()); } return content; } private static string RunGitCommandAndGetLastLine(string repoPath, string arguments) { string content = null; RunGitCommand(repoPath, arguments, output => content = output); if (string.IsNullOrEmpty(content)) { throw new GitException("The result can't be null or empty string"); } return content; } private static void RunGitCommand(string repoPath, string arguments, Action<string> processOutput) { var encoding = Encoding.UTF8; const int bufferSize = 4096; if (!Directory.Exists(repoPath)) { throw new ArgumentException($"Can't find repo: {repoPath}"); } using (var outputStream = new MemoryStream()) using (var errorStream = new MemoryStream()) { int exitCode; using (var outputStreamWriter = new StreamWriter(outputStream, encoding, bufferSize, true)) using (var errorStreamWriter = new StreamWriter(errorStream, encoding, bufferSize, true)) { exitCode = CommandUtility.RunCommand(new CommandInfo { Name = CommandName, Arguments = arguments, WorkingDirectory = repoPath, }, outputStreamWriter, errorStreamWriter, GitTimeOut); // writer streams have to be flushed before reading from memory streams // make sure that streamwriter is not closed before reading from memory stream outputStreamWriter.Flush(); errorStreamWriter.Flush(); if (exitCode != 0) { errorStream.Position = 0; using (var errorStreamReader = new StreamReader(errorStream, encoding, false, bufferSize, true)) { ProcessErrorMessage(errorStreamReader.ReadToEnd()); } } else { outputStream.Position = 0; using (var streamReader = new StreamReader(outputStream, encoding, false, bufferSize, true)) { string line; while ((line = streamReader.ReadLine()) != null) { processOutput(line); } } } } } } private static bool ExistGitCommand() { if (GitCommandExists == null) { lock (SyncRoot) { if (GitCommandExists == null) { GitCommandExists = CommandUtility.ExistCommand(CommandName); if (GitCommandExists != true) { Logger.LogInfo("Looks like Git is not installed globally. We depend on Git to extract repository information for source code and files."); } } } } return GitCommandExists.Value; } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Diagnostics.Contracts; using System.Globalization; using System.Linq; using System.Net; using System.Reflection; using Resta.UriTemplates; namespace Hyperspec { public class TemplateParameterInfo { public string Name { get; set; } public string Title { get; set; } public string Type { get; set; } public bool IsRequired { get; set; } public bool InTemplate { get; set; } public bool ForceTemplated { get; set; } } /// <summary> /// Common base class for ResourceLink and ResourceForm. /// </summary> public abstract class ResourceLinkBase : ILink { private readonly Dictionary<string, TemplateParameterInfo> _parameterInfos; private readonly UriTemplate _originalUriTemplate; private readonly UriTemplate _extendedUriTemplate; protected readonly IEnumerable<IContentContext> Contexts; private readonly string _title; protected ResourceLinkBase(string linkTemplate, IEnumerable<IContentContext> contexts, string title, IEnumerable<TemplateParameterInfo> parameterInfos = null) { _originalUriTemplate = _extendedUriTemplate = new UriTemplate(linkTemplate); _title = title; Contexts = contexts; _parameterInfos = new Dictionary<string, TemplateParameterInfo>(); foreach (var variable in _originalUriTemplate.Variables) { ParameterInfos[variable.Name.ToLowerInvariant()] = new TemplateParameterInfo() { Name = variable.Name, IsRequired = true, InTemplate = true }; } if (parameterInfos == null) return; var extendedUriBuilder = new UriTemplateBuilder(_originalUriTemplate); var isFirst = !_originalUriTemplate.Template.Contains("?"); var varspecs = new List<VarSpec>(); foreach (var param in parameterInfos) { // Add up all parameters to the template. Append any new ones to the template if (AddParameterInfo(param)) { varspecs.Add(new VarSpec(param.Name)); } } extendedUriBuilder.Append(isFirst ? '?' : '&', varspecs.ToArray()); _extendedUriTemplate = extendedUriBuilder.Build(); } public virtual string Title { get { return _title; } } public abstract string Href { get; } public abstract IDictionary<string, FormParameterInfo> Template { get; } protected IDictionary<string, TemplateParameterInfo> ParameterInfos { get { return _parameterInfos; } } protected string GetHref(bool includeExtraParameters) { var template = includeExtraParameters ? _extendedUriTemplate : _originalUriTemplate; var linkParts = GetParameters(); var templateResolver = template.GetResolver(); foreach (var part in linkParts.Where(p => !p.ForceTemplated)) // Don't resolve parameters that have been forced as templated { var value = GetParameter(Contexts, part.Name); if (value.Any()) { templateResolver.Bind(part.Name, value); } } var resolvedUri = templateResolver.ResolveTemplate().Template; return resolvedUri; } public IEnumerable<TemplateParameterInfo> GetParameters() { return ParameterInfos.Values; } private bool AddParameterInfo(TemplateParameterInfo parameter) { TemplateParameterInfo existingParam; if (ParameterInfos.TryGetValue(parameter.Name.ToLowerInvariant(), out existingParam)) { // This parameter info already existed. Let's update it. existingParam.Title = parameter.Title; existingParam.Type = parameter.Type; existingParam.IsRequired |= parameter.IsRequired; return false; } // No such parameter. Add it to the template. parameter.InTemplate = false; ParameterInfos[parameter.Name.ToLowerInvariant()] = parameter; return true; } protected static IEnumerable<string> GetParameter(IEnumerable<IContentContext> contexts, string paramName) { object val = null; foreach (var context in contexts) { var content = context.Content; var dict = content as IDictionary<string, object>; if (dict != null) { // The content object is a dictionary. Let's try to find a value. if (dict.TryGetValue(paramName, out val)) { // We found the value. Let's see if we want to use it? if (context.IncludeProperty(paramName, val)) { // Yep, no need to check any other context objects break; } // Not found, let's continue with the next context object val = null; } continue; } // So we didn't get a dictionary. What did we get then? var contextType = content.GetType(); // Find out if there's a property with this name var prop = contextType.GetProperty(paramName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase); if (prop != null) { // Get the value of the property if possible if (prop.CanRead) { val = prop.GetValue(content); if (context.IncludeProperty(paramName, val)) { // Found the value, no need to check any more context objects break; } } // Found a value but not supposed to use it. Let's reset and try the next context object val = null; } } // No value found if (val == null) yield break; if (val is DateTime) { yield return ((DateTime)val).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); yield break; } var ints = val as int[]; if (ints != null) { foreach (var i in ints) { yield return i.ToString(); } yield break; } var objects = val as IEnumerable<object>; if (objects != null) { foreach (var o in objects) { yield return o.ToString(); } yield break; } yield return val.ToString(); } protected IDictionary<string, FormParameterInfo> GetTemplate() { return ParameterInfos.Values.Where(pi => !pi.InTemplate).ToDictionary(pi => pi.Name, pi => new FormParameterInfo() { Title = pi.Title, Type = pi.Type, IsRequired = pi.IsRequired, DefaultValue = GetParameter(Contexts, pi.Name).FirstOrDefault() }); } } /// <summary> /// A Resource Link with a template. The /// </summary> /// <typeparam name="TTemplate"></typeparam> public abstract class ResourceLinkBase<TTemplate> : ResourceLinkBase { protected ResourceLinkBase(string linkTemplate, IEnumerable<IContentContext> contexts, string title, IEnumerable<TemplateParameterInfo> parameterInfos) : base(linkTemplate, contexts, title, GetParameterInfos(parameterInfos)) { } private static IEnumerable<TemplateParameterInfo> GetParameterInfos(IEnumerable<TemplateParameterInfo> overriddenParameters) { var templateType = typeof(TTemplate); var props = templateType.GetProperties(); var overriddenParametersArray = overriddenParameters as TemplateParameterInfo[] ?? overriddenParameters?.ToArray(); foreach (var property in props) { if (!property.CanWrite) continue; var propertyName = property.Name; if (overriddenParametersArray != null && overriddenParametersArray.Any(p => p.Name == propertyName)) continue; var type = property.PropertyType; string typeName = null; string title = null; bool isRequired = type.IsValueType; typeName = GetTypeName(type); if (type.IsNullableType()) { typeName = GetTypeName(type.GetTypeOfNullable()); isRequired = false; } var requiredAttr = property.GetCustomAttribute<RequiredAttribute>(); if (requiredAttr != null) { isRequired = true; } var descAttr = property.GetCustomAttribute<DisplayAttribute>(); if (descAttr != null) { title = descAttr.GetName(); } yield return new TemplateParameterInfo() { Name = propertyName, Type = typeName, IsRequired = isRequired, Title = title }; } if (overriddenParametersArray != null) { foreach (var parameterInfo in overriddenParametersArray) { yield return parameterInfo; } } } private static string GetTypeName(Type type) { if (type.IsArray) return GetTypeName(type.GetElementType()) + "[]"; if (type == typeof(string)) return "string"; if (type == typeof(short) || type == typeof(int) || type == typeof(long)) return "int"; if (type == typeof(DateTime)) return "date"; if (type == typeof(Guid)) return "guid"; return type.Name; } } }
#region /* Copyright (c) 2002-2012, Bas Geertsema, Xih Solutions (http://www.xihsolutions.net), Thiago.Sayao, Pang Wu, Ethem Evlice, Andy Phan, Chang Liu. All rights reserved. http://code.google.com/p/msnp-sharp/ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the names of Bas Geertsema or Xih Solutions nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #endregion using System; using System.Net; using System.Net.Sockets; using System.Threading; using System.Diagnostics; using System.Globalization; using System.Collections.Generic; namespace MSNPSharp.P2P { using MSNPSharp; using MSNPSharp.Core; public enum DCNonceType { None = 0, Plain = 1, Sha1 = 2 } partial class P2PSession { private Timer directNegotiationTimer = null; public static Guid ParseDCNonce(MimeDictionary bodyValues, out DCNonceType dcNonceType) { dcNonceType = DCNonceType.None; Guid nonce = Guid.Empty; if (bodyValues.ContainsKey("Hashed-Nonce")) { nonce = new Guid(bodyValues["Hashed-Nonce"].Value); dcNonceType = DCNonceType.Sha1; } else if (bodyValues.ContainsKey("Nonce")) { nonce = new Guid(bodyValues["Nonce"].Value); dcNonceType = DCNonceType.Plain; } return nonce; } internal static void ProcessDirectInvite(SLPMessage slp, NSMessageHandler ns, P2PSession startupSession) { switch (slp.ContentType) { case "application/x-msnmsgr-transreqbody": ProcessDCReqInvite(slp, ns, startupSession); break; case "application/x-msnmsgr-transrespbody": ProcessDCRespInvite(slp, ns, startupSession); break; case "application/x-msnmsgr-transdestaddrupdate": ProcessDirectAddrUpdate(slp, ns, startupSession); break; } } private void DirectNegotiationSuccessful() { if (directNegotiationTimer != null) { directNegotiationTimer.Dispose(); directNegotiationTimer = null; } Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose, "Direct connection negotiation was successful", GetType().Name); } private void DirectNegotiationTimedOut(object p2pSession) { Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose, "Direct connection negotiation timed out", GetType().Name); DirectNegotiationFailed(); } internal void DirectNegotiationFailed() { Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose, "Direct connection negotiation was unsuccessful", GetType().Name); if (directNegotiationTimer != null) { directNegotiationTimer.Dispose(); directNegotiationTimer = null; } if (p2pBridge != null) { p2pBridge.ResumeSending(this); if (Application != null && p2pBridge.Ready(this)) Application.BridgeIsReady(); } } private static string ConnectionType(NSMessageHandler nsMessageHandler, out int netId) { string connectionType = "Unknown-Connect"; netId = 0; IPEndPoint localEndPoint = nsMessageHandler.LocalEndPoint; IPEndPoint externalEndPoint = nsMessageHandler.ExternalEndPoint; if (localEndPoint == null || externalEndPoint == null) { } else { netId = BitConverter.ToInt32(localEndPoint.Address.GetAddressBytes(), 0); if (Settings.DisableP2PDirectConnections) { connectionType = "Firewall"; } else { if (localEndPoint.Address.Equals(externalEndPoint.Address)) { if (localEndPoint.Port == externalEndPoint.Port) connectionType = "Direct-Connect"; else connectionType = "Port-Restrict-NAT"; } else { if (localEndPoint.Port == externalEndPoint.Port) { netId = 0; connectionType = "IP-Restrict-NAT"; } else connectionType = "Symmetric-NAT"; } } } return connectionType; } internal bool SendDirectInvite() { // Skip if we're currently using a TCPBridge. if (Remote.DirectBridge != null && Remote.DirectBridge.IsOpen) return false; int netId; string connectionType = ConnectionType(nsMessageHandler, out netId); P2PMessage p2pMessage = new P2PMessage(Version); Trace.WriteLineIf(Settings.TraceSwitch.TraceInfo, String.Format("Connection type set to {0} for session {1}", connectionType, SessionId.ToString())); // Create the message SLPRequestMessage slpMessage = new SLPRequestMessage(RemoteContactEPIDString, MSNSLPRequestMethod.INVITE); slpMessage.Source = LocalContactEPIDString; slpMessage.CSeq = 0; slpMessage.CallId = Invitation.CallId; slpMessage.MaxForwards = 0; slpMessage.ContentType = "application/x-msnmsgr-transreqbody"; slpMessage.BodyValues["Bridges"] = "TCPv1 SBBridge"; slpMessage.BodyValues["Capabilities-Flags"] = "1"; slpMessage.BodyValues["NetID"] = netId.ToString(CultureInfo.InvariantCulture); slpMessage.BodyValues["Conn-Type"] = connectionType; slpMessage.BodyValues["TCP-Conn-Type"] = connectionType; slpMessage.BodyValues["UPnPNat"] = "false"; // UPNP Enabled slpMessage.BodyValues["ICF"] = (connectionType == "Firewall").ToString(); // Firewall enabled slpMessage.BodyValues["Nat-Trav-Msg-Type"] = "WLX-Nat-Trav-Msg-Direct-Connect-Req"; // We support Hashed-Nonce ( 2 way handshake ) Remote.GenerateNewDCKeys(); slpMessage.BodyValues["Hashed-Nonce"] = Remote.dcLocalHashedNonce.ToString("B").ToUpper(CultureInfo.InvariantCulture); p2pMessage.InnerMessage = slpMessage; if (p2pMessage.Version == P2PVersion.P2PV2) { p2pMessage.V2Header.TFCombination = TFCombination.First; } else if (p2pMessage.Version == P2PVersion.P2PV1) { p2pMessage.V1Header.Flags = P2PFlag.MSNSLPInfo; } // These 3 step is very important... // 1- Stop sending for this session on sdgbridge until we receive a response to the direct invite or the timeout expires nsMessageHandler.SDGBridge.StopSending(this); // 2- Setup a dc timer. SetupDCTimer(); // 3- Don't pass p2psession to the sdg bridge. Because, sdgbridge stopped this session. nsMessageHandler.SDGBridge.Send(null /*must be null to bypass queueing*/, Remote, RemoteContactEndPointID, p2pMessage); return true; } private static void ProcessDCReqInvite(SLPMessage message, NSMessageHandler ns, P2PSession startupSession) { if (startupSession != null && startupSession.Bridge != null && startupSession.Bridge is TCPv1Bridge) { return; // We are using a dc bridge already. Don't allow second one. } if (message.BodyValues.ContainsKey("Bridges") && message.BodyValues["Bridges"].ToString().Contains("TCPv1")) { SLPStatusMessage slpMessage = new SLPStatusMessage(message.Source, 200, "OK"); slpMessage.Target = message.Source; slpMessage.Source = message.Target; slpMessage.Branch = message.Branch; slpMessage.CSeq = 1; slpMessage.CallId = message.CallId; slpMessage.MaxForwards = 0; slpMessage.ContentType = "application/x-msnmsgr-transrespbody"; slpMessage.BodyValues["Bridge"] = "TCPv1"; Guid remoteGuid = message.FromEndPoint; Contact remote = ns.ContactList.GetContactWithCreate(message.FromEmailAccount, IMAddressInfoType.WindowsLive); DCNonceType dcNonceType; Guid remoteNonce = ParseDCNonce(message.BodyValues, out dcNonceType); if (remoteNonce == Guid.Empty) // Plain remoteNonce = remote.dcPlainKey; bool hashed = (dcNonceType == DCNonceType.Sha1); string nonceFieldName = hashed ? "Hashed-Nonce" : "Nonce"; Guid myHashedNonce = hashed ? remote.dcLocalHashedNonce : remoteNonce; Guid myPlainNonce = remote.dcPlainKey; if (dcNonceType == DCNonceType.Sha1) { // Remote contact supports Hashed-Nonce remote.dcType = dcNonceType; remote.dcRemoteHashedNonce = remoteNonce; } else { remote.dcType = DCNonceType.Plain; myPlainNonce = remote.dcPlainKey = remote.dcLocalHashedNonce = remote.dcRemoteHashedNonce = remoteNonce; } // Find host by name IPAddress ipAddress = ns.LocalEndPoint.Address; int port; P2PVersion ver = message.P2PVersion; if (Settings.DisableP2PDirectConnections || false == ipAddress.Equals(ns.ExternalEndPoint.Address) || (0 == (port = GetNextDirectConnectionPort(ipAddress)))) { slpMessage.BodyValues["Listening"] = "false"; slpMessage.BodyValues[nonceFieldName] = Guid.Empty.ToString("B").ToUpper(CultureInfo.InvariantCulture); } else { // Let's listen remote.DirectBridge = ListenForDirectConnection(remote, remoteGuid, ns, ver, startupSession, ipAddress, port, myPlainNonce, remoteNonce, hashed); slpMessage.BodyValues["Listening"] = "true"; slpMessage.BodyValues["Capabilities-Flags"] = "1"; slpMessage.BodyValues["IPv6-global"] = string.Empty; slpMessage.BodyValues["Nat-Trav-Msg-Type"] = "WLX-Nat-Trav-Msg-Direct-Connect-Resp"; slpMessage.BodyValues["UPnPNat"] = "false"; slpMessage.BodyValues["NeedConnectingEndpointInfo"] = "true"; slpMessage.BodyValues["Conn-Type"] = "Direct-Connect"; slpMessage.BodyValues["TCP-Conn-Type"] = "Direct-Connect"; slpMessage.BodyValues[nonceFieldName] = myHashedNonce.ToString("B").ToUpper(CultureInfo.InvariantCulture); slpMessage.BodyValues["IPv4Internal-Addrs"] = ipAddress.ToString(); slpMessage.BodyValues["IPv4Internal-Port"] = port.ToString(CultureInfo.InvariantCulture); // check if client is behind firewall (NAT-ted) // if so, send the public ip also the client, so it can try to connect to that ip if (!ns.ExternalEndPoint.Address.Equals(ns.LocalEndPoint.Address)) { slpMessage.BodyValues["IPv4External-Addrs"] = ns.ExternalEndPoint.Address.ToString(); slpMessage.BodyValues["IPv4External-Port"] = port.ToString(CultureInfo.InvariantCulture); } } P2PMessage p2pMessage = new P2PMessage(ver); p2pMessage.InnerMessage = slpMessage; if (ver == P2PVersion.P2PV2) { p2pMessage.V2Header.TFCombination = TFCombination.First; } else if (ver == P2PVersion.P2PV1) { p2pMessage.V1Header.Flags = P2PFlag.MSNSLPInfo; } if (startupSession != null) { startupSession.SetupDCTimer(); startupSession.Bridge.Send(null, startupSession.Remote, startupSession.RemoteContactEndPointID, p2pMessage); } else { ns.SDGBridge.Send(null, remote, remoteGuid, p2pMessage); } } else { if (startupSession != null) startupSession.DirectNegotiationFailed(); } } private void SetupDCTimer() { directNegotiationTimer = new Timer(new TimerCallback(DirectNegotiationTimedOut), this, 17000, 17000); } private static void ProcessDCRespInvite(SLPMessage message, NSMessageHandler ns, P2PSession startupSession) { MimeDictionary bodyValues = message.BodyValues; // Check the protocol if (bodyValues.ContainsKey("Bridge") && bodyValues["Bridge"].ToString() == "TCPv1" && bodyValues.ContainsKey("Listening") && bodyValues["Listening"].ToString().ToLowerInvariant().IndexOf("true") >= 0) { Contact remote = ns.ContactList.GetContactWithCreate(message.FromEmailAccount, IMAddressInfoType.WindowsLive); Guid remoteGuid = message.FromEndPoint; DCNonceType dcNonceType; Guid remoteNonce = ParseDCNonce(message.BodyValues, out dcNonceType); bool hashed = (dcNonceType == DCNonceType.Sha1); Guid replyGuid = hashed ? remote.dcPlainKey : remoteNonce; IPEndPoint[] selectedPoint = SelectIPEndPoint(bodyValues, ns); if (selectedPoint != null && selectedPoint.Length > 0) { P2PVersion ver = message.P2PVersion; // We must connect to the remote client ConnectivitySettings settings = new ConnectivitySettings(); settings.EndPoints = selectedPoint; remote.DirectBridge = CreateDirectConnection(remote, remoteGuid, ver, settings, replyGuid, remoteNonce, hashed, ns, startupSession); bool needConnectingEndpointInfo; if (bodyValues.ContainsKey("NeedConnectingEndpointInfo") && bool.TryParse(bodyValues["NeedConnectingEndpointInfo"], out needConnectingEndpointInfo) && needConnectingEndpointInfo == true) { IPEndPoint ipep = ((TCPv1Bridge)remote.DirectBridge).LocalEndPoint; string desc = "stroPdnAsrddAlanretnI4vPI"; char[] rev = ipep.ToString().ToCharArray(); Array.Reverse(rev); string ipandport = new string(rev); SLPRequestMessage slpResponseMessage = new SLPRequestMessage(message.Source, MSNSLPRequestMethod.ACK); slpResponseMessage.Source = message.Target; slpResponseMessage.Via = message.Via; slpResponseMessage.CSeq = 0; slpResponseMessage.CallId = Guid.Empty; slpResponseMessage.MaxForwards = 0; slpResponseMessage.ContentType = @"application/x-msnmsgr-transdestaddrupdate"; slpResponseMessage.BodyValues[desc] = ipandport; slpResponseMessage.BodyValues["Nat-Trav-Msg-Type"] = "WLX-Nat-Trav-Msg-Updated-Connecting-Port"; P2PMessage msg = new P2PMessage(ver); msg.InnerMessage = slpResponseMessage; ns.SDGBridge.Send(null, remote, remoteGuid, msg); } return; } } if (startupSession != null) startupSession.DirectNegotiationFailed(); } private static void ProcessDirectAddrUpdate( SLPMessage message, NSMessageHandler nsMessageHandler, P2PSession startupSession) { Contact from = nsMessageHandler.ContactList.GetContactWithCreate(message.FromEmailAccount, IMAddressInfoType.WindowsLive); IPEndPoint[] ipEndPoints = SelectIPEndPoint(message.BodyValues, nsMessageHandler); if (from.DirectBridge != null && ipEndPoints != null && ipEndPoints.Length > 0) { ((TCPv1Bridge)from.DirectBridge).OnDestinationAddressUpdated(new DestinationAddressUpdatedEventArgs(ipEndPoints)); } } private static TCPv1Bridge ListenForDirectConnection( Contact remote, Guid remoteGuid, NSMessageHandler nsMessageHandler, P2PVersion ver, P2PSession startupSession, IPAddress host, int port, Guid replyGuid, Guid remoteNonce, bool hashed) { ConnectivitySettings cs = new ConnectivitySettings(); if (nsMessageHandler.ConnectivitySettings.LocalHost == string.Empty) { cs.LocalHost = host.ToString(); cs.LocalPort = port; } else { cs.LocalHost = nsMessageHandler.ConnectivitySettings.LocalHost; cs.LocalPort = nsMessageHandler.ConnectivitySettings.LocalPort; } TCPv1Bridge tcpBridge = new TCPv1Bridge(cs, ver, replyGuid, remoteNonce, hashed, startupSession, nsMessageHandler, remote, remoteGuid); tcpBridge.Listen(IPAddress.Parse(cs.LocalHost), cs.LocalPort); Trace.WriteLineIf(Settings.TraceSwitch.TraceInfo, "Listening on " + cs.LocalHost + ":" + cs.LocalPort.ToString(CultureInfo.InvariantCulture)); return tcpBridge; } private static TCPv1Bridge CreateDirectConnection(Contact remote, Guid remoteGuid, P2PVersion ver, ConnectivitySettings cs, Guid replyGuid, Guid remoteNonce, bool hashed, NSMessageHandler nsMessageHandler, P2PSession startupSession) { string[] points = new string[cs.EndPoints.Length]; for (int i = 0; i < points.Length; i++) { points[i] = cs.EndPoints[i].ToString(); } TCPv1Bridge tcpBridge = new TCPv1Bridge(cs, ver, replyGuid, remoteNonce, hashed, startupSession, nsMessageHandler, remote, remoteGuid); Trace.WriteLineIf(Settings.TraceSwitch.TraceInfo, "Trying to setup direct connection with remote hosts " + string.Join(",", points)); tcpBridge.Connect(); return tcpBridge; } private static int GetNextDirectConnectionPort(IPAddress ipAddress) { int portAvail = 0; if (Settings.PublicPortPriority == PublicPortPriority.First) { portAvail = TryPublicPorts(ipAddress); if (portAvail != 0) { return portAvail; } } if (portAvail == 0) { // Don't try all ports for (int p = 1119, maxTry = 100; p <= IPEndPoint.MaxPort && maxTry < 1; p++, maxTry--) { Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { //s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); s.Bind(new IPEndPoint(ipAddress, p)); //s.Bind(new IPEndPoint(IPAddress.Any, p)); s.Close(); return p; } catch (SocketException ex) { // Permission denied if (ex.ErrorCode == 10048 /*Address already in use*/ || ex.ErrorCode == 10013 /*Permission denied*/) { p += 100; } continue; // throw; } catch (System.Security.SecurityException) { break; } } } if (portAvail == 0 && Settings.PublicPortPriority == PublicPortPriority.Last) { portAvail = TryPublicPorts(ipAddress); } return portAvail; } private static int TryPublicPorts(IPAddress localIP) { foreach (int p in Settings.PublicPorts) { Socket s = null; try { s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); s.Bind(new IPEndPoint(localIP, p)); return p; } catch (SocketException) { } finally { if (s != null) s.Close(); } } return 0; } private static IPEndPoint[] SelectIPEndPoint(MimeDictionary bodyValues, NSMessageHandler nsMessageHandler) { List<IPEndPoint> externalPoints = new List<IPEndPoint>(); List<IPEndPoint> internalPoints = new List<IPEndPoint>(); bool nat = false; #region External if (bodyValues.ContainsKey("IPv4External-Addrs") || bodyValues.ContainsKey("srddA-lanretxE4vPI") || bodyValues.ContainsKey("IPv4ExternalAddrsAndPorts") || bodyValues.ContainsKey("stroPdnAsrddAlanretxE4vPI")) { Trace.WriteLineIf(Settings.TraceSwitch.TraceInfo, "Using external IP addresses"); if (bodyValues.ContainsKey("IPv4External-Addrs")) { string[] addrs = bodyValues["IPv4External-Addrs"].Value.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); string[] ports = bodyValues["IPv4External-Port"].Value.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (addrs.Length > 0 && ports.Length > 0) { IPAddress ip; int port = 0; int.TryParse(ports[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out port); for (int i = 0; i < addrs.Length; i++) { if (IPAddress.TryParse(addrs[i], out ip)) { if (i < ports.Length) int.TryParse(ports[i], NumberStyles.Integer, CultureInfo.InvariantCulture, out port); if (port > 0) externalPoints.Add(new IPEndPoint(ip, port)); } } } } else if (bodyValues.ContainsKey("IPv4ExternalAddrsAndPorts")) { string[] addrsAndPorts = bodyValues["IPv4ExternalAddrsAndPorts"].Value.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); IPAddress ip; foreach (string str in addrsAndPorts) { string[] addrAndPort = str.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries); if (IPAddress.TryParse(addrAndPort[0], out ip)) externalPoints.Add(new IPEndPoint(ip, int.Parse(addrAndPort[1]))); } } else if (bodyValues.ContainsKey("srddA-lanretxE4vPI")) { nat = true; char[] revHost = bodyValues["srddA-lanretxE4vPI"].ToString().ToCharArray(); Array.Reverse(revHost); string[] addrs = new string(revHost).Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); char[] revPort = bodyValues["troP-lanretxE4vPI"].ToString().ToCharArray(); Array.Reverse(revPort); string[] ports = new string(revPort).Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (addrs.Length > 0 && ports.Length > 0) { IPAddress ip; int port = 0; int.TryParse(ports[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out port); for (int i = 0; i < addrs.Length; i++) { if (IPAddress.TryParse(addrs[i], out ip)) { if (i < ports.Length) int.TryParse(ports[i], NumberStyles.Integer, CultureInfo.InvariantCulture, out port); if (port > 0) externalPoints.Add(new IPEndPoint(ip, port)); } } } } else if (bodyValues.ContainsKey("stroPdnAsrddAlanretxE4vPI")) { nat = true; char[] rev = bodyValues["stroPdnAsrddAlanretxE4vPI"].ToString().ToCharArray(); Array.Reverse(rev); string[] addrsAndPorts = new string(rev).Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); IPAddress ip; foreach (string str in addrsAndPorts) { string[] addrAndPort = str.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries); if (IPAddress.TryParse(addrAndPort[0], out ip)) externalPoints.Add(new IPEndPoint(ip, int.Parse(addrAndPort[1]))); } } Trace.WriteLineIf(Settings.TraceSwitch.TraceWarning, String.Format("{0} external IP addresses found:", externalPoints.Count)); foreach (IPEndPoint ipep in externalPoints) { Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose, "\t" + ipep.ToString()); } } #endregion #region Internal if (bodyValues.ContainsKey("IPv4Internal-Addrs") || bodyValues.ContainsKey("srddA-lanretnI4vPI") || bodyValues.ContainsKey("IPv4InternalAddrsAndPorts") || bodyValues.ContainsKey("stroPdnAsrddAlanretnI4vPI")) { Trace.WriteLineIf(Settings.TraceSwitch.TraceInfo, "Using internal IP addresses"); if (bodyValues.ContainsKey("IPv4Internal-Addrs")) { string[] addrs = bodyValues["IPv4Internal-Addrs"].Value.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); string[] ports = bodyValues["IPv4Internal-Port"].Value.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (addrs.Length > 0 && ports.Length > 0) { IPAddress ip; int port = 0; int.TryParse(ports[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out port); for (int i = 0; i < addrs.Length; i++) { if (IPAddress.TryParse(addrs[i], out ip)) { if (i < ports.Length) int.TryParse(ports[i], NumberStyles.Integer, CultureInfo.InvariantCulture, out port); if (port > 0) internalPoints.Add(new IPEndPoint(ip, port)); } } } } else if (bodyValues.ContainsKey("IPv4InternalAddrsAndPorts")) { string[] addrsAndPorts = bodyValues["IPv4InternalAddrsAndPorts"].Value.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); IPAddress ip; foreach (string str in addrsAndPorts) { string[] addrAndPort = str.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries); if (IPAddress.TryParse(addrAndPort[0], out ip)) internalPoints.Add(new IPEndPoint(ip, int.Parse(addrAndPort[1]))); } } else if (bodyValues.ContainsKey("srddA-lanretnI4vPI")) { nat = true; char[] revHost = bodyValues["srddA-lanretnI4vPI"].ToString().ToCharArray(); Array.Reverse(revHost); string[] addrs = new string(revHost).Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); char[] revPort = bodyValues["troP-lanretnI4vPI"].ToString().ToCharArray(); Array.Reverse(revPort); string[] ports = new string(revPort).Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (addrs.Length > 0 && ports.Length > 0) { IPAddress ip; int port = 0; int.TryParse(ports[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out port); for (int i = 0; i < addrs.Length; i++) { if (IPAddress.TryParse(addrs[i], out ip)) { if (i < ports.Length) int.TryParse(ports[i], NumberStyles.Integer, CultureInfo.InvariantCulture, out port); if (port > 0) internalPoints.Add(new IPEndPoint(ip, port)); } } } } else if (bodyValues.ContainsKey("stroPdnAsrddAlanretnI4vPI")) { nat = true; char[] rev = bodyValues["stroPdnAsrddAlanretnI4vPI"].ToString().ToCharArray(); Array.Reverse(rev); string[] addrsAndPorts = new string(rev).Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); IPAddress ip; foreach (string str in addrsAndPorts) { string[] addrAndPort = str.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries); if (IPAddress.TryParse(addrAndPort[0], out ip)) internalPoints.Add(new IPEndPoint(ip, int.Parse(addrAndPort[1]))); } } Trace.WriteLineIf(Settings.TraceSwitch.TraceWarning, String.Format("{0} internal IP addresses found:", internalPoints.Count)); foreach (IPEndPoint ipep in internalPoints) { Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose, "\t" + ipep.ToString()); } } #endregion if (externalPoints.Count == 0 && internalPoints.Count == 0) { Trace.WriteLineIf(Settings.TraceSwitch.TraceError, "Unable to find any remote IP addresses"); // Failed return null; } Trace.WriteLineIf(Settings.TraceSwitch.TraceInfo, "Is NAT: " + nat); List<IPEndPoint> ret = new List<IPEndPoint>(); // Try to find the correct IP byte[] localBytes = nsMessageHandler.LocalEndPoint.Address.GetAddressBytes(); foreach (IPEndPoint ipep in internalPoints) { if (ipep.Address.AddressFamily == AddressFamily.InterNetwork) { // This is an IPv4 address // Check if the first 3 octets match our local IP address // If so, make use of that address (it's on our LAN) byte[] bytes = ipep.Address.GetAddressBytes(); if ((bytes[0] == localBytes[0]) && (bytes[1] == localBytes[1]) && (bytes[2] == localBytes[2])) { ret.Add(ipep); break; } } } if (ret.Count == 0) { foreach (IPEndPoint ipep in internalPoints) { if (!ret.Contains(ipep)) ret.Add(ipep); } } foreach (IPEndPoint ipep in externalPoints) { if (!ret.Contains(ipep)) ret.Add(ipep); } return ret.ToArray(); } } };
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Text; using System.Reflection; using System.Diagnostics; using System.Globalization; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.CompilerServices; using System.Reflection.Runtime.TypeInfos; using System.Reflection.Runtime.Assemblies; using System.Reflection.Runtime.MethodInfos; using Internal.LowLevelLinq; using Internal.Runtime.Augments; using Internal.Reflection.Augments; using Internal.Reflection.Core.Execution; using Internal.Reflection.Extensions.NonPortable; namespace System.Reflection.Runtime.General { internal static partial class Helpers { // This helper helps reduce the temptation to write "h == default(RuntimeTypeHandle)" which causes boxing. public static bool IsNull(this RuntimeTypeHandle h) { return h.Equals(default(RuntimeTypeHandle)); } // Clones a Type[] array for the purpose of returning it from an api. public static Type[] CloneTypeArray(this Type[] types) { int count = types.Length; if (count == 0) return Array.Empty<Type>(); // Ok not to clone empty arrays - those are immutable. Type[] clonedTypes = new Type[count]; for (int i = 0; i < count; i++) { clonedTypes[i] = types[i]; } return clonedTypes; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Type[] GetGenericTypeParameters(this Type type) { Debug.Assert(type.IsGenericTypeDefinition); return type.GetGenericArguments(); } public static RuntimeTypeInfo[] ToRuntimeTypeInfoArray(this Type[] types) { int count = types.Length; RuntimeTypeInfo[] typeInfos = new RuntimeTypeInfo[count]; for (int i = 0; i < count; i++) { typeInfos[i] = types[i].CastToRuntimeTypeInfo(); } return typeInfos; } public static string LastResortString(this RuntimeTypeHandle typeHandle) { return ReflectionCoreExecution.ExecutionEnvironment.GetLastResortString(typeHandle); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static RuntimeNamedTypeInfo CastToRuntimeNamedTypeInfo(this Type type) { Debug.Assert(type is RuntimeNamedTypeInfo); return (RuntimeNamedTypeInfo)type; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static RuntimeTypeInfo CastToRuntimeTypeInfo(this Type type) { Debug.Assert(type == null || type is RuntimeTypeInfo); return (RuntimeTypeInfo)type; } public static ReadOnlyCollection<T> ToReadOnlyCollection<T>(this IEnumerable<T> enumeration) { return new ReadOnlyCollection<T>(enumeration.ToArray()); } public static MethodInfo FilterAccessor(this MethodInfo accessor, bool nonPublic) { if (nonPublic) return accessor; if (accessor.IsPublic) return accessor; return null; } public static Type GetTypeCore(this Assembly assembly, string name, bool ignoreCase) { if (assembly is RuntimeAssembly runtimeAssembly) { // Not a recursion - this one goes to the actual instance method on RuntimeAssembly. return runtimeAssembly.GetTypeCore(name, ignoreCase: ignoreCase); } else { // This is a third-party Assembly object. We can emulate GetTypeCore() by calling the public GetType() // method. This is wasteful because it'll probably reparse a type string that we've already parsed // but it can't be helped. string escapedName = name.EscapeTypeNameIdentifier(); return assembly.GetType(escapedName, throwOnError: false, ignoreCase: ignoreCase); } } public static TypeLoadException CreateTypeLoadException(string typeName, Assembly assemblyIfAny) { if (assemblyIfAny == null) throw new TypeLoadException(SR.Format(SR.TypeLoad_TypeNotFound, typeName)); else throw Helpers.CreateTypeLoadException(typeName, assemblyIfAny.FullName); } public static TypeLoadException CreateTypeLoadException(string typeName, string assemblyName) { string message = SR.Format(SR.TypeLoad_TypeNotFoundInAssembly, typeName, assemblyName); return ReflectionAugments.CreateTypeLoadException(message, typeName); } // Escape identifiers as described in "Specifying Fully Qualified Type Names" on msdn. // Current link is http://msdn.microsoft.com/en-us/library/yfsftwz6(v=vs.110).aspx public static string EscapeTypeNameIdentifier(this string identifier) { // Some characters in a type name need to be escaped if (identifier != null && identifier.IndexOfAny(s_charsToEscape) != -1) { StringBuilder sbEscapedName = new StringBuilder(identifier.Length); foreach (char c in identifier) { if (c.NeedsEscapingInTypeName()) sbEscapedName.Append('\\'); sbEscapedName.Append(c); } identifier = sbEscapedName.ToString(); } return identifier; } public static bool NeedsEscapingInTypeName(this char c) { return Array.IndexOf(s_charsToEscape, c) >= 0; } private static readonly char[] s_charsToEscape = new char[] { '\\', '[', ']', '+', '*', '&', ',' }; public static RuntimeMethodInfo GetInvokeMethod(this RuntimeTypeInfo delegateType) { Debug.Assert(delegateType.IsDelegate); MethodInfo invokeMethod = delegateType.GetMethod("Invoke", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly); if (invokeMethod == null) { // No Invoke method found. Since delegate types are compiler constructed, the most likely cause is missing metadata rather than // a missing Invoke method. // We're deliberating calling FullName rather than ToString() because if it's the type that's missing metadata, // the FullName property constructs a more informative MissingMetadataException than we can. string fullName = delegateType.FullName; throw new MissingMetadataException(SR.Format(SR.Arg_InvokeMethodMissingMetadata, fullName)); // No invoke method found. } return (RuntimeMethodInfo)invokeMethod; } public static BinderBundle ToBinderBundle(this Binder binder, BindingFlags invokeAttr, CultureInfo cultureInfo) { if (binder == null || binder is DefaultBinder || ((invokeAttr & BindingFlags.ExactBinding) != 0)) return null; return new BinderBundle(binder, cultureInfo); } // Helper for ICustomAttributeProvider.GetCustomAttributes(). The result of this helper is returned directly to apps // so it must always return a newly allocated array. Unlike most of the newer custom attribute apis, the attribute type // need not derive from System.Attribute. (In particular, it can be an interface or System.Object.) public static object[] InstantiateAsArray(this IEnumerable<CustomAttributeData> cads, Type actualElementType) { LowLevelList<object> attributes = new LowLevelList<object>(); foreach (CustomAttributeData cad in cads) { object instantiatedAttribute = cad.Instantiate(); attributes.Add(instantiatedAttribute); } // This is here for desktop compatibility. ICustomAttribute.GetCustomAttributes() normally returns an array of the // exact attribute type requested except in two cases: when the passed in type is an open type and when // it is a value type. In these two cases, it returns an array of type Object[]. bool useObjectArray = actualElementType.ContainsGenericParameters || actualElementType.IsValueType; int count = attributes.Count; object[] result = useObjectArray ? new object[count] : (object[])Array.CreateInstance(actualElementType, count); attributes.CopyTo(result, 0); return result; } public static bool GetCustomAttributeDefaultValueIfAny(IEnumerable<CustomAttributeData> customAttributes, bool raw, out object defaultValue) { // Legacy: If there are multiple default value attribute, the desktop picks one at random (and so do we...) foreach (CustomAttributeData cad in customAttributes) { Type attributeType = cad.AttributeType; if (attributeType.IsSubclassOf(typeof(CustomConstantAttribute))) { if (raw) { foreach (CustomAttributeNamedArgument namedArgument in cad.NamedArguments) { if (namedArgument.MemberName.Equals("Value")) { defaultValue = namedArgument.TypedValue.Value; return true; } } defaultValue = null; return false; } else { CustomConstantAttribute customConstantAttribute = (CustomConstantAttribute)(cad.Instantiate()); defaultValue = customConstantAttribute.Value; return true; } } if (attributeType.Equals(typeof(DecimalConstantAttribute))) { // We should really do a non-instanting check if "raw == false" but given that we don't support // reflection-only loads, there isn't an observable difference. DecimalConstantAttribute decimalConstantAttribute = (DecimalConstantAttribute)(cad.Instantiate()); defaultValue = decimalConstantAttribute.Value; return true; } } defaultValue = null; return false; } } }
#region Disclaimer/Info /////////////////////////////////////////////////////////////////////////////////////////////////// // Subtext WebLog // // Subtext is an open source weblog system that is a fork of the .TEXT // weblog system. // // For updated news and information please visit http://subtextproject.com/ // Subtext is hosted at Google Code at http://code.google.com/p/subtext/ // The development mailing list is at subtext@googlegroups.com // // This project is licensed under the BSD license. See the License.txt file for more information. /////////////////////////////////////////////////////////////////////////////////////////////////// ///Part of this code derives from the original FileBrowserConnector shipped with ///the original FredCK.FCKeditorV2, which is redistributed with the following license #region Original License /* * FCKeditor - The text editor for internet * Copyright (C) 2003-2005 Frederico Caldeira Knabben * * Licensed under the terms of the GNU Lesser General Public License: * http://www.opensource.org/licenses/lgpl-license.php * * For further information visit: * http://www.fckeditor.net/ * * "Support Open Source software. What about a donation today?" * * * File Authors: * Frederico Caldeira Knabben (fredck@fckeditor.net) */ #endregion #endregion using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Net; using System.Security; using System.Text; using System.Text.RegularExpressions; using System.Web; using System.Xml; using FredCK.FCKeditorV2; using Subtext.Extensibility; using Subtext.Extensibility.Interfaces; using Subtext.Framework; using Subtext.Framework.Components; using Subtext.Framework.Configuration; using Subtext.Framework.Providers; using Subtext.Framework.Routing; using Subtext.Framework.Web.Handlers; namespace Subtext.Providers.BlogEntryEditor.FCKeditor { /// <summary> /// Used to provide file management functionality for FCKEditor. /// </summary> public class FileBrowserConnector : SubtextPage { protected override void OnInit(EventArgs e) { if(!SubtextContext.User.IsInRole("Admins")) { SubtextContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized; SubtextContext.HttpContext.Response.End(); } base.OnInit(e); } protected override void OnLoad(EventArgs e) { // Get the main request informaiton. string sCommand = Request.QueryString["Command"]; if(sCommand == null) { return; } string sResourceType = Request.QueryString["Type"]; if(sResourceType == null) { return; } string sCurrentFolder = Request.QueryString["CurrentFolder"]; if(sCurrentFolder == null) { return; } // Check the current folder syntax (must begin and start with a slash). if(!sCurrentFolder.EndsWith("/")) { sCurrentFolder += "/"; } if(!sCurrentFolder.StartsWith("/")) { sCurrentFolder = "/" + sCurrentFolder; } // File Upload doesn't have to return XML, so it must be intercepted before anything. if(sCommand == "FileUpload") { FileUpload(sResourceType, sCurrentFolder); return; } // Cleans the response buffer. Response.ClearHeaders(); Response.Clear(); // Prevent the browser from caching the result. Response.CacheControl = "no-cache"; // Set the response format. Response.ContentEncoding = Encoding.UTF8; Response.ContentType = "text/xml"; var oXML = new XmlDocument(); XmlNode oConnectorNode = CreateBaseXml(oXML, sCommand, sResourceType, sCurrentFolder); if(CreateImageFolder(oConnectorNode)) { if(sResourceType.Equals("Image")) { // Execute the required command. switch(sCommand) { case "GetFolders": GetFolders(oConnectorNode, sCurrentFolder); break; case "GetFoldersAndFiles": GetFolders(oConnectorNode, sCurrentFolder); GetFiles(oConnectorNode, sResourceType, sCurrentFolder); break; case "CreateFolder": CreateFolder(oConnectorNode, sResourceType, sCurrentFolder); break; } } else if(sResourceType.Equals("Posts")) { // Execute the required command. switch(sCommand) { case "GetFolders": GetCategories(oConnectorNode, sCurrentFolder); break; case "GetFoldersAndFiles": GetCategories(oConnectorNode, sCurrentFolder); GetPosts(oConnectorNode, sCurrentFolder); break; case "CreateFolder": CreateFolder(oConnectorNode, sResourceType, sCurrentFolder); break; } } else if(sResourceType.Equals("File")) { // Execute the required command. switch(sCommand) { case "GetFolders": GetFolders(oConnectorNode, sCurrentFolder); break; case "GetFoldersAndFiles": GetFolders(oConnectorNode, sCurrentFolder); GetFiles(oConnectorNode, sResourceType, sCurrentFolder); break; case "CreateFolder": CreateFolder(oConnectorNode, sResourceType, sCurrentFolder); break; } } } // Output the resulting XML. Response.Write(oXML.OuterXml); Response.End(); base.OnLoad(e); } private void GetFolders(XmlNode connectorNode, string currentFolder) { // Map the virtual path to the local server path. string sServerDir = ServerMapFolder(currentFolder, Url.ImageDirectoryUrl(Blog)); // Create the "Folders" node. XmlNode oFoldersNode = XmlUtil.AppendElement(connectorNode, "Folders"); var oDir = new DirectoryInfo(sServerDir); DirectoryInfo[] aSubDirs = oDir.GetDirectories(); for(int i = 0; i < aSubDirs.Length; i++) { // Create the "Folders" node. XmlNode oFolderNode = XmlUtil.AppendElement(oFoldersNode, "Folder"); XmlUtil.SetAttribute(oFolderNode, "name", aSubDirs[i].Name); } } private void GetFiles(XmlNode connectorNode, string resourceType, string currentFolder) { // Map the virtual path to the local server path. string sServerDir = ServerMapFolder(currentFolder, Url.ImageDirectoryUrl(Blog)); // Create the "Files" node. XmlNode oFilesNode = XmlUtil.AppendElement(connectorNode, "Files"); var oDir = new DirectoryInfo(sServerDir); FileInfo[] aFiles = oDir.GetFiles(); for(int i = 0; i < aFiles.Length; i++) { if(Regex.IsMatch(aFiles[i].Extension, GetAllowedExtension(resourceType), RegexOptions.IgnoreCase)) { Decimal iFileSize = Math.Round((Decimal)aFiles[i].Length / 1024); if(iFileSize < 1 && aFiles[i].Length != 0) { iFileSize = 1; } // Create the "File" node. XmlNode oFileNode = XmlUtil.AppendElement(oFilesNode, "File"); XmlUtil.SetAttribute(oFileNode, "name", aFiles[i].Name); XmlUtil.SetAttribute(oFileNode, "size", iFileSize.ToString(CultureInfo.InvariantCulture)); } } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The error number is used to create an error node in the XML document, so we need to catch a general exception as well." )] private void CreateFolder(XmlNode connectorNode, string resourceType, string currentFolder) { string sErrorNumber = "0"; if(resourceType.Equals("Posts")) { sErrorNumber = "103"; } else { string sNewFolderName = Request.QueryString["NewFolderName"]; if(sNewFolderName == null || sNewFolderName.Length == 0) { sErrorNumber = "102"; } else { // Map the virtual path to the local server path of the current folder. string sServerDir = ServerMapFolder(currentFolder, Url.ImageDirectoryUrl(Blog)); try { Util.CreateDirectory(Path.Combine(sServerDir, sNewFolderName)); } catch(ArgumentException) { sErrorNumber = "102"; } catch(PathTooLongException) { sErrorNumber = "102"; } catch(IOException) { sErrorNumber = "101"; } catch(SecurityException) { sErrorNumber = "103"; } catch(Exception) { sErrorNumber = "110"; } } } // Create the "Error" node. XmlNode oErrorNode = XmlUtil.AppendElement(connectorNode, "Error"); XmlUtil.SetAttribute(oErrorNode, "number", sErrorNumber); } private void FileUpload(string resourceType, string currentFolder) { string sErrorNumber = "0"; string sFileName = ""; if(!resourceType.Equals("Posts")) { HttpPostedFile oFile = Request.Files["NewFile"]; if(oFile != null) { // Map the virtual path to the local server path. string sServerDir = ServerMapFolder(currentFolder, Url.ImageDirectoryUrl(Blog)); // Get the uploaded file name. sFileName = Path.GetFileName(oFile.FileName); int iCounter = 0; while(true) { string sFilePath = Path.Combine(sServerDir, sFileName); if(File.Exists(sFilePath)) { iCounter++; sFileName = Path.GetFileNameWithoutExtension(oFile.FileName) + "(" + iCounter + ")" + Path.GetExtension(oFile.FileName); sErrorNumber = "201"; } else { oFile.SaveAs(sFilePath); break; } } } else { sErrorNumber = "202"; } } else { sErrorNumber = "203"; } Response.Clear(); Response.Write("<script type=\"text/javascript\">"); Response.Write("window.parent.frames['frmUpload'].OnUploadCompleted(" + sErrorNumber + ",'" + sFileName.Replace("'", "\\'") + "') ;"); Response.Write("</script>"); Response.End(); } private XmlNode CreateBaseXml(XmlDocument xml, string command, string resourceType, string currentFolder) { // Create the XML document header. xml.AppendChild(xml.CreateXmlDeclaration("1.0", "utf-8", null)); // Create the main "Connector" node. XmlNode connectorNode = XmlUtil.AppendElement(xml, "Connector"); XmlUtil.SetAttribute(connectorNode, "command", command); XmlUtil.SetAttribute(connectorNode, "resourceType", resourceType); // Add the current folder node. if(!resourceType.Equals("Posts")) { XmlNode oCurrentNode = XmlUtil.AppendElement(connectorNode, "CurrentFolder"); XmlUtil.SetAttribute(oCurrentNode, "path", currentFolder); XmlUtil.SetAttribute(oCurrentNode, "url", Url.ImageDirectoryUrl(Blog) + currentFolder); } else { XmlNode currentNode = XmlUtil.AppendElement(connectorNode, "CurrentFolder"); XmlUtil.SetAttribute(currentNode, "path", currentFolder); XmlUtil.SetAttribute(currentNode, "url", ""); } return connectorNode; } private string ServerMapFolder(string folderPath, string imageDirectoryUrl) { // Get the resource type directory. string imageDirectoryPath = Server.MapPath(imageDirectoryUrl); // Return the resource type directory combined with the required path. return Path.Combine(imageDirectoryPath, folderPath.TrimStart('/')); } private static string GetUrlFromPath(string folderPath, string imageDirectoryUrl) { return imageDirectoryUrl + folderPath.Substring(1); } private static string GetAllowedExtension(string resourceType) { string extStr = string.Empty; if(resourceType.Equals("File")) { extStr = FckBlogEntryEditorProvider.FileAllowedExtensions; } else if(resourceType.Equals("Image")) { extStr = FckBlogEntryEditorProvider.ImageAllowedExtensions; } return extStr; } private bool CreateImageFolder(XmlNode connectorNode) { bool retval; string imageDirectoryPath = Url.ImageDirectoryPath(Blog); try { if(!Directory.Exists(imageDirectoryPath)) { Directory.CreateDirectory(imageDirectoryPath); } retval = true; } catch(Exception) { // Create the "Error" node. XmlNode errorNode = XmlUtil.AppendElement(connectorNode, "Error"); XmlUtil.SetAttribute(errorNode, "number", "1"); XmlUtil.SetAttribute(errorNode, "text", "Cannot create folder: " + imageDirectoryPath + "." + Environment.NewLine + "Write access to this folder is required to initialize the image storage"); retval = false; } return retval; } #region Post Type Handler private static void GetCategories(XmlNode connectorNode, string currentFolder) { if(currentFolder.Equals("/")) { ICollection<LinkCategory> catList = Links.GetCategories(CategoryType.PostCollection, ActiveFilter.None); // Create the "Folders" node. XmlNode oFoldersNode = XmlUtil.AppendElement(connectorNode, "Folders"); foreach(LinkCategory category in catList) { // Create the "Folders" node. XmlNode oFolderNode = XmlUtil.AppendElement(oFoldersNode, "Folder"); XmlUtil.SetAttribute(oFolderNode, "name", category.Title); } } } private void GetPosts(XmlNode connectorNode, string currentFolder) { IPagedCollection<EntryStatsView> posts; if(currentFolder.Equals("/")) { posts = Repository.GetEntries(PostType.BlogPost, -1, 0, 1000); } else { string categoryName = currentFolder.Substring(1, currentFolder.Length - 2); LinkCategory cat = ObjectProvider.Instance().GetLinkCategory(categoryName, false); posts = Repository.GetEntries(PostType.BlogPost, cat.Id, 0, 1000); } // Create the "Files" node. XmlNode oFilesNode = XmlUtil.AppendElement(connectorNode, "Files"); foreach(var entry in posts) { // Create the "File" node. if(entry.IsActive) { XmlNode oFileNode = XmlUtil.AppendElement(oFilesNode, "File"); //TODO: Seriously refactor. var urlHelper = new UrlHelper(null, null); XmlUtil.SetAttribute(oFileNode, "name", string.Format(CultureInfo.InvariantCulture, "{0}|{1}", entry.Title, urlHelper.EntryUrl(entry).ToFullyQualifiedUrl(Config.CurrentBlog))); XmlUtil.SetAttribute(oFileNode, "size", entry.DateModified.ToShortDateString()); } } } #endregion } }
using System; using System.Linq; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Moq; using Newtonsoft.Json; using NUnit.Framework; using Umbraco.Cms.Core.Configuration.Models; using Umbraco.Cms.Core.IO; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.Models.PublishedContent; using Umbraco.Cms.Core.PropertyEditors; using Umbraco.Cms.Core.PropertyEditors.ValueConverters; using Umbraco.Cms.Core.Routing; using Umbraco.Cms.Core.Services; using Umbraco.Cms.Core.Strings; using Umbraco.Cms.Core.Web; using Umbraco.Cms.Tests.Common; using Umbraco.Cms.Tests.Common.Testing; using Umbraco.Tests.PublishedContent; using Umbraco.Tests.TestHelpers; using Constants = Umbraco.Cms.Core.Constants; namespace Umbraco.Tests.Routing { [TestFixture] [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerFixture)] public class MediaUrlProviderTests : BaseWebTest { private DefaultMediaUrlProvider _mediaUrlProvider; public override void SetUp() { base.SetUp(); var loggerFactory = NullLoggerFactory.Instance; var mediaFileManager = new MediaFileManager(Mock.Of<IFileSystem>(), Mock.Of<IMediaPathScheme>(), loggerFactory.CreateLogger<MediaFileManager>(), Mock.Of<IShortStringHelper>()); var contentSettings = new ContentSettings(); var dataTypeService = Mock.Of<IDataTypeService>(); var propertyEditors = new MediaUrlGeneratorCollection(new IMediaUrlGenerator[] { new FileUploadPropertyEditor(DataValueEditorFactory, mediaFileManager, Microsoft.Extensions.Options.Options.Create(contentSettings), dataTypeService, LocalizationService, LocalizedTextService, UploadAutoFillProperties, ContentService), new ImageCropperPropertyEditor(DataValueEditorFactory, loggerFactory, mediaFileManager, Microsoft.Extensions.Options.Options.Create(contentSettings), dataTypeService, IOHelper, UploadAutoFillProperties, ContentService), }); _mediaUrlProvider = new DefaultMediaUrlProvider(propertyEditors, UriUtility); } public override void TearDown() { base.TearDown(); _mediaUrlProvider = null; } [Test] public void Get_Media_Url_Resolves_Url_From_Upload_Property_Editor() { const string expected = "/media/rfeiw584/test.jpg"; var umbracoContext = GetUmbracoContext("/"); var publishedContent = CreatePublishedContent(Constants.PropertyEditors.Aliases.UploadField, expected, null); var resolvedUrl = GetPublishedUrlProvider(umbracoContext).GetMediaUrl(publishedContent, UrlMode.Auto); Assert.AreEqual(expected, resolvedUrl); } [Test] public void Get_Media_Url_Resolves_Url_From_Image_Cropper_Property_Editor() { const string expected = "/media/rfeiw584/test.jpg"; var configuration = new ImageCropperConfiguration(); var imageCropperValue = JsonConvert.SerializeObject(new ImageCropperValue { Src = expected }); var umbracoContext = GetUmbracoContext("/"); var publishedContent = CreatePublishedContent(Constants.PropertyEditors.Aliases.ImageCropper, imageCropperValue, configuration); var resolvedUrl = GetPublishedUrlProvider(umbracoContext).GetMediaUrl(publishedContent, UrlMode.Auto); Assert.AreEqual(expected, resolvedUrl); } [Test] public void Get_Media_Url_Can_Resolve_Absolute_Url() { const string mediaUrl = "/media/rfeiw584/test.jpg"; var expected = $"http://localhost{mediaUrl}"; var umbracoContext = GetUmbracoContext("http://localhost"); var publishedContent = CreatePublishedContent(Constants.PropertyEditors.Aliases.UploadField, mediaUrl, null); var resolvedUrl = GetPublishedUrlProvider(umbracoContext).GetMediaUrl(publishedContent, UrlMode.Absolute); Assert.AreEqual(expected, resolvedUrl); } [Test] public void Get_Media_Url_Returns_Absolute_Url_If_Stored_Url_Is_Absolute() { const string expected = "http://localhost/media/rfeiw584/test.jpg"; var umbracoContext = GetUmbracoContext("http://localhost"); var publishedContent = CreatePublishedContent(Constants.PropertyEditors.Aliases.UploadField, expected, null); var resolvedUrl = GetPublishedUrlProvider(umbracoContext).GetMediaUrl(publishedContent, UrlMode.Relative); Assert.AreEqual(expected, resolvedUrl); } [Test] public void Get_Media_Url_Returns_Empty_String_When_PropertyType_Is_Not_Supported() { var umbracoContext = GetUmbracoContext("/"); var publishedContent = CreatePublishedContent(Constants.PropertyEditors.Aliases.Boolean, "0", null); var resolvedUrl = GetPublishedUrlProvider(umbracoContext).GetMediaUrl(publishedContent, UrlMode.Absolute, propertyAlias: "test"); Assert.AreEqual(string.Empty, resolvedUrl); } [Test] public void Get_Media_Url_Can_Resolve_Variant_Property_Url() { var umbracoContext = GetUmbracoContext("http://localhost"); var umbracoFilePropertyType = CreatePropertyType(Constants.PropertyEditors.Aliases.UploadField, null, ContentVariation.Culture); const string enMediaUrl = "/media/rfeiw584/en.jpg"; const string daMediaUrl = "/media/uf8ewud2/da.jpg"; var property = new SolidPublishedPropertyWithLanguageVariants { Alias = "umbracoFile", PropertyType = umbracoFilePropertyType, }; property.SetSourceValue("en", enMediaUrl, true); property.SetSourceValue("da", daMediaUrl); var contentType = new PublishedContentType(Guid.NewGuid(), 666, "alias", PublishedItemType.Content, Enumerable.Empty<string>(), new [] { umbracoFilePropertyType }, ContentVariation.Culture); var publishedContent = new SolidPublishedContent(contentType) {Properties = new[] {property}}; var resolvedUrl = GetPublishedUrlProvider(umbracoContext).GetMediaUrl(publishedContent, UrlMode.Auto, "da"); Assert.AreEqual(daMediaUrl, resolvedUrl); } private IPublishedUrlProvider GetPublishedUrlProvider(IUmbracoContext umbracoContext) { var webRoutingSettings = new WebRoutingSettings(); return new UrlProvider( new TestUmbracoContextAccessor(umbracoContext), Microsoft.Extensions.Options.Options.Create(webRoutingSettings), new UrlProviderCollection(Enumerable.Empty<IUrlProvider>()), new MediaUrlProviderCollection(new []{_mediaUrlProvider}), Mock.Of<IVariationContextAccessor>() ); } private static IPublishedContent CreatePublishedContent(string propertyEditorAlias, string propertyValue, object dataTypeConfiguration) { var umbracoFilePropertyType = CreatePropertyType(propertyEditorAlias, dataTypeConfiguration, ContentVariation.Nothing); var contentType = new PublishedContentType(Guid.NewGuid(), 666, "alias", PublishedItemType.Content, Enumerable.Empty<string>(), new[] {umbracoFilePropertyType}, ContentVariation.Nothing); return new SolidPublishedContent(contentType) { Id = 1234, Key = Guid.NewGuid(), Properties = new[] { new SolidPublishedProperty { Alias = "umbracoFile", SolidSourceValue = propertyValue, SolidHasValue = true, PropertyType = umbracoFilePropertyType } } }; } private static PublishedPropertyType CreatePropertyType(string propertyEditorAlias, object dataTypeConfiguration, ContentVariation variation) { var uploadDataType = new PublishedDataType(1234, propertyEditorAlias, new Lazy<object>(() => dataTypeConfiguration)); var propertyValueConverters = new PropertyValueConverterCollection(new IPropertyValueConverter[] { new UploadPropertyConverter(), new ImageCropperValueConverter(Mock.Of<ILogger<ImageCropperValueConverter>>()), }); var publishedModelFactory = Mock.Of<IPublishedModelFactory>(); var publishedContentTypeFactory = new Mock<IPublishedContentTypeFactory>(); publishedContentTypeFactory.Setup(x => x.GetDataType(It.IsAny<int>())) .Returns(uploadDataType); return new PublishedPropertyType("umbracoFile", 42, true, variation, propertyValueConverters, publishedModelFactory, publishedContentTypeFactory.Object); } } }
using UnityEngine; using Pathfinding.Serialization; namespace Pathfinding { /** Base class for GridNode and LevelGridNode */ public abstract class GridNodeBase : GraphNode { protected GridNodeBase (AstarPath astar) : base(astar) { } const int GridFlagsWalkableErosionOffset = 8; const int GridFlagsWalkableErosionMask = 1 << GridFlagsWalkableErosionOffset; const int GridFlagsWalkableTmpOffset = 9; const int GridFlagsWalkableTmpMask = 1 << GridFlagsWalkableTmpOffset; protected const int NodeInGridIndexLayerOffset = 24; protected const int NodeInGridIndexMask = 0xFFFFFF; /** Bitfield containing the x and z coordinates of the node as well as the layer (for layered grid graphs). * \see NodeInGridIndex */ protected int nodeInGridIndex; protected ushort gridFlags; #if !ASTAR_GRID_NO_CUSTOM_CONNECTIONS public Connection[] connections; #endif /** The index of the node in the grid. * This is x + z*graph.width * So you can get the X and Z indices using * \code * int index = node.NodeInGridIndex; * int x = index % graph.width; * int z = index / graph.width; * // where graph is GridNode.GetGridGraph (node.graphIndex), i.e the graph the nodes are contained in. * \endcode */ public int NodeInGridIndex { get { return nodeInGridIndex & NodeInGridIndexMask; } set { nodeInGridIndex = (nodeInGridIndex & ~NodeInGridIndexMask) | value; } } /** X coordinate of the node in the grid. * The node in the bottom left corner has (x,z) = (0,0) and the one in the opposite * corner has (x,z) = (width-1, depth-1) * \see ZCoordInGrid * \see NodeInGridIndex */ public int XCoordinateInGrid { get { return NodeInGridIndex % GridNode.GetGridGraph(GraphIndex).width; } } /** Z coordinate of the node in the grid. * The node in the bottom left corner has (x,z) = (0,0) and the one in the opposite * corner has (x,z) = (width-1, depth-1) * \see XCoordInGrid * \see NodeInGridIndex */ public int ZCoordinateInGrid { get { return NodeInGridIndex / GridNode.GetGridGraph(GraphIndex).width; } } /** Stores walkability before erosion is applied. * Used internally when updating the graph. */ public bool WalkableErosion { get { return (gridFlags & GridFlagsWalkableErosionMask) != 0; } set { unchecked { gridFlags = (ushort)(gridFlags & ~GridFlagsWalkableErosionMask | (value ? (ushort)GridFlagsWalkableErosionMask : (ushort)0)); } } } /** Temporary variable used internally when updating the graph. */ public bool TmpWalkable { get { return (gridFlags & GridFlagsWalkableTmpMask) != 0; } set { unchecked { gridFlags = (ushort)(gridFlags & ~GridFlagsWalkableTmpMask | (value ? (ushort)GridFlagsWalkableTmpMask : (ushort)0)); } } } /** True if the node has grid connections to all its 8 neighbours. * \note This will always return false if GridGraph.neighbours is set to anything other than Eight. * \see GetNeighbourAlongDirection */ public abstract bool HasConnectionsToAllEightNeighbours { get; } public override float SurfaceArea () { GridGraph gg = GridNode.GetGridGraph(GraphIndex); return gg.nodeSize*gg.nodeSize; } public override Vector3 RandomPointOnSurface () { GridGraph gg = GridNode.GetGridGraph(GraphIndex); var graphSpacePosition = gg.transform.InverseTransform((Vector3)position); return gg.transform.Transform(graphSpacePosition + new Vector3(Random.value - 0.5f, 0, Random.value - 0.5f)); } public override int GetGizmoHashCode () { var hash = base.GetGizmoHashCode(); #if !ASTAR_GRID_NO_CUSTOM_CONNECTIONS if (connections != null) { for (int i = 0; i < connections.Length; i++) { hash ^= 17 * connections[i].GetHashCode(); } } #endif hash ^= 109 * gridFlags; return hash; } /** Adjacent grid node in the specified direction. * This will return null if the node does not have a connection to a node * in that direction. * * The dir parameter corresponds to directions in the grid as: * \code * Z * | * | * * 6 2 5 * \ | / * -- 3 - X - 1 ----- X * / | \ * 7 0 4 * * | * | * \endcode * * \see GetConnections */ public abstract GridNodeBase GetNeighbourAlongDirection (int direction); public override bool ContainsConnection (GraphNode node) { #if !ASTAR_GRID_NO_CUSTOM_CONNECTIONS if (connections != null) { for (int i = 0; i < connections.Length; i++) { if (connections[i].node == node) { return true; } } } #endif for (int i = 0; i < 8; i++) { if (node == GetNeighbourAlongDirection(i)) { return true; } } return false; } #if ASTAR_GRID_NO_CUSTOM_CONNECTIONS public override void AddConnection (GraphNode node, uint cost) { throw new System.NotImplementedException("GridNodes do not have support for adding manual connections with your current settings."+ "\nPlease disable ASTAR_GRID_NO_CUSTOM_CONNECTIONS in the Optimizations tab in the A* Inspector"); } public override void RemoveConnection (GraphNode node) { throw new System.NotImplementedException("GridNodes do not have support for adding manual connections with your current settings."+ "\nPlease disable ASTAR_GRID_NO_CUSTOM_CONNECTIONS in the Optimizations tab in the A* Inspector"); } public void ClearCustomConnections (bool alsoReverse) { } #else public override void FloodFill (System.Collections.Generic.Stack<GraphNode> stack, uint region) { if (connections != null) for (int i = 0; i < connections.Length; i++) { GraphNode other = connections[i].node; if (other.Area != region) { other.Area = region; stack.Push(other); } } } /** Same as #ClearConnections, but does not clear grid connections, only custom ones (e.g added by #AddConnection or a NodeLink component) */ public void ClearCustomConnections (bool alsoReverse) { if (connections != null) for (int i = 0; i < connections.Length; i++) connections[i].node.RemoveConnection(this); connections = null; } public override void ClearConnections (bool alsoReverse) { ClearCustomConnections(alsoReverse); } public override void GetConnections (System.Action<GraphNode> action) { if (connections != null) for (int i = 0; i < connections.Length; i++) action(connections[i].node); } public override void UpdateRecursiveG (Path path, PathNode pathNode, PathHandler handler) { ushort pid = handler.PathID; if (connections != null) for (int i = 0; i < connections.Length; i++) { GraphNode other = connections[i].node; PathNode otherPN = handler.GetPathNode(other); if (otherPN.parent == pathNode && otherPN.pathID == pid) other.UpdateRecursiveG(path, otherPN, handler); } } public override void Open (Path path, PathNode pathNode, PathHandler handler) { ushort pid = handler.PathID; if (connections != null) for (int i = 0; i < connections.Length; i++) { GraphNode other = connections[i].node; if (!path.CanTraverse(other)) continue; PathNode otherPN = handler.GetPathNode(other); uint tmpCost = connections[i].cost; if (otherPN.pathID != pid) { otherPN.parent = pathNode; otherPN.pathID = pid; otherPN.cost = tmpCost; otherPN.H = path.CalculateHScore(other); other.UpdateG(path, otherPN); //Debug.Log ("G " + otherPN.G + " F " + otherPN.F); handler.heap.Add(otherPN); //Debug.DrawRay ((Vector3)otherPN.node.Position, Vector3.up,Color.blue); } else { // Sorry for the huge number of #ifs //If not we can test if the path from the current node to this one is a better one then the one already used #if ASTAR_NO_TRAVERSAL_COST if (pathNode.G+tmpCost < otherPN.G) #else if (pathNode.G+tmpCost+path.GetTraversalCost(other) < otherPN.G) #endif { //Debug.Log ("Path better from " + NodeIndex + " to " + otherPN.node.NodeIndex + " " + (pathNode.G+tmpCost+path.GetTraversalCost(other)) + " < " + otherPN.G); otherPN.cost = tmpCost; otherPN.parent = pathNode; other.UpdateRecursiveG(path, otherPN, handler); //Or if the path from this node ("other") to the current ("current") is better } #if ASTAR_NO_TRAVERSAL_COST else if (otherPN.G+tmpCost < pathNode.G && other.ContainsConnection(this)) #else else if (otherPN.G+tmpCost+path.GetTraversalCost(this) < pathNode.G && other.ContainsConnection(this)) #endif { //Debug.Log ("Path better from " + otherPN.node.NodeIndex + " to " + NodeIndex + " " + (otherPN.G+tmpCost+path.GetTraversalCost (this)) + " < " + pathNode.G); pathNode.parent = otherPN; pathNode.cost = tmpCost; UpdateRecursiveG(path, pathNode, handler); } } } } /** Add a connection from this node to the specified node. * If the connection already exists, the cost will simply be updated and * no extra connection added. * * \note Only adds a one-way connection. Consider calling the same function on the other node * to get a two-way connection. */ public override void AddConnection (GraphNode node, uint cost) { if (node == null) throw new System.ArgumentNullException(); if (connections != null) { for (int i = 0; i < connections.Length; i++) { if (connections[i].node == node) { connections[i].cost = cost; return; } } } int connLength = connections != null ? connections.Length : 0; var newconns = new Connection[connLength+1]; for (int i = 0; i < connLength; i++) { newconns[i] = connections[i]; } newconns[connLength] = new Connection { node = node, cost = cost }; connections = newconns; } /** Removes any connection from this node to the specified node. * If no such connection exists, nothing will be done. * * \note This only removes the connection from this node to the other node. * You may want to call the same function on the other node to remove its eventual connection * to this node. */ public override void RemoveConnection (GraphNode node) { if (connections == null) return; for (int i = 0; i < connections.Length; i++) { if (connections[i].node == node) { int connLength = connections.Length; var newconns = new Connection[connLength-1]; for (int j = 0; j < i; j++) { newconns[j] = connections[j]; } for (int j = i+1; j < connLength; j++) { newconns[j-1] = connections[j]; } connections = newconns; return; } } } public override void SerializeReferences (GraphSerializationContext ctx) { // TODO: Deduplicate code if (connections == null) { ctx.writer.Write(-1); } else { ctx.writer.Write(connections.Length); for (int i = 0; i < connections.Length; i++) { ctx.SerializeNodeReference(connections[i].node); ctx.writer.Write(connections[i].cost); } } } /** Cached to avoid allocations */ static readonly System.Version VERSION_3_8_3 = new System.Version(3, 8, 3); public override void DeserializeReferences (GraphSerializationContext ctx) { // Grid nodes didn't serialize references before 3.8.3 if (ctx.meta.version < VERSION_3_8_3) return; int count = ctx.reader.ReadInt32(); if (count == -1) { connections = null; } else { connections = new Connection[count]; for (int i = 0; i < count; i++) { connections[i] = new Connection { node = ctx.DeserializeNodeReference(), cost = ctx.reader.ReadUInt32() }; } } } #endif } }
// // System.Web.UI.WebControls.XmlDataSource // // Authors: // Ben Maurer (bmaurer@users.sourceforge.net) // // (C) 2003 Ben Maurer // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // #if NET_2_0 using System.Collections; using System.Collections.Specialized; using System.Text; using System.Xml; using System.Xml.Xsl; using System.ComponentModel; using System.IO; namespace System.Web.UI.WebControls { [DesignerAttribute ("System.Web.UI.Design.WebControls.XmlDataSourceDesigner, System.Design, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.ComponentModel.Design.IDesigner")] [DefaultProperty ("DataFile")] [DefaultEvent ("Transforming")] [ParseChildren (true)] [PersistChildren (false)] [WebSysDescription ("Connect to an XML file.")] // [WebSysDisplayName ("XML file")] public class XmlDataSource : HierarchicalDataSourceControl, IDataSource, IListSource { event EventHandler IDataSource.DataSourceChanged { add { ((IHierarchicalDataSource)this).DataSourceChanged += value; } remove { ((IHierarchicalDataSource)this).DataSourceChanged -= value; } } static object EventTransforming = new object (); public event EventHandler Transforming { add { Events.AddHandler (EventTransforming, value); } remove { Events.RemoveHandler (EventTransforming, value); } } protected virtual void OnTransforming (EventArgs e) { EventHandler eh = Events [EventTransforming] as EventHandler; if (eh != null) eh (this, e); } XmlDataDocument xmlDataDocument; public XmlDataDocument GetXmlDataDocument () { if (xmlDataDocument == null) { xmlDataDocument = new XmlDataDocument (); LoadXmlDataDocument (xmlDataDocument); } return xmlDataDocument; } [MonoTODO ("XSLT, schema")] void LoadXmlDataDocument (XmlDataDocument document) { if (Transform == "" && TransformFile == "") { if (DataFile != "") document.Load (MapPathSecure (DataFile)); else document.LoadXml (Data); } else { throw new NotImplementedException ("XSLT transform not implemented"); } } public void Save () { if (!CanBeSaved) throw new InvalidOperationException (); xmlDataDocument.Save (MapPathSecure (DataFile)); } bool CanBeSaved { get { return !ReadOnly && Transform == "" && TransformFile == "" && DataFile != ""; } } [MonoTODO] protected override void LoadViewState (object savedState) { base.LoadViewState (savedState); } [MonoTODO] protected override object SaveViewState () { return base.SaveViewState (); } [MonoTODO] protected override void TrackViewState () { base.TrackViewState (); } protected override HierarchicalDataSourceView GetHierarchicalView (string viewPath) { XmlNode doc = this.GetXmlDataDocument (); XmlNodeList ret = null; if (viewPath != "") { XmlNode n = doc.SelectSingleNode (viewPath); if (n != null) ret = n.ChildNodes; } else if (XPath != "") { ret = doc.SelectNodes (XPath); } else { ret = doc.ChildNodes; } return new XmlHierarchicalDataSourceView (ret); } IList IListSource.GetList () { return ListSourceHelper.GetList (this); } bool IListSource.ContainsListCollection { get { return ListSourceHelper.ContainsListCollection (this); } } DataSourceView IDataSource.GetView (string viewName) { if (viewName == "") viewName = "DefaultView"; return new XmlDataSourceView (this, viewName, GetXmlDataDocument ().DocumentElement.SelectNodes (XPath != "" ? XPath : "./*")); } ICollection IDataSource.GetViewNames () { return new string [] { "DefaultView" }; } public virtual bool AutoSave { get { object ret = ViewState ["AutoSave"]; return ret != null ? (bool)ret : true; } set { ViewState ["AutoSave"] = value; } } // TODO: stub these apis //protected virtual FileDataSourceCache Cache { get; } //public virtual int CacheDuration { get; set; } //public virtual DataSourceCacheExpiry CacheExpirationPolicy { get; set; } //public virtual string CacheKeyDependency { get; set; } //public virtual bool EnableCaching { get; set; } [DefaultValue ("")] [PersistenceMode (PersistenceMode.InnerProperty)] [WebSysDescription ("Inline XML data.")] [WebCategory ("Data")] [EditorAttribute ("System.ComponentModel.Design.MultilineStringEditor,System.Design, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] // [TypeConverter (typeof(MultilineStringConverter))] public virtual string Data { get { string ret = ViewState ["Data"] as string; return ret != null ? ret : ""; } set { if (Data != value) { ViewState ["Data"] = value; xmlDataDocument = null; OnDataSourceChanged(EventArgs.Empty); } } } [DefaultValueAttribute ("")] [EditorAttribute ("System.Web.UI.Design.XmlDataFileEditor, System.Design, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] public virtual string DataFile { get { string ret = ViewState ["DataFile"] as string; return ret != null ? ret : ""; } set { if (DataFile != value) { ViewState ["DataFile"] = value; xmlDataDocument = null; OnDataSourceChanged(EventArgs.Empty); } } } public virtual bool ReadOnly { get { object ret = ViewState ["ReadOnly"]; return ret != null ? (bool)ret : true; } set { ViewState ["ReadOnly"] = value; } } // [TypeConverterAttribute (typeof(System.ComponentModel.MultilineStringConverter)] [EditorAttribute ("System.ComponentModel.Design.MultilineStringEditor,System.Design, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] [PersistenceModeAttribute (PersistenceMode.InnerProperty)] [DefaultValueAttribute ("")] public virtual string Schema { get { string ret = ViewState ["Schema"] as string; return ret != null ? ret : ""; } set { if (Schema != value) { ViewState ["Schema"] = value; xmlDataDocument = null; OnDataSourceChanged(EventArgs.Empty); } } } [DefaultValueAttribute ("")] [EditorAttribute ("System.Web.UI.Design.XsdSchemaFileEditor, System.Design, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] public virtual string SchemaFile { get { string ret = ViewState ["SchemaFile"] as string; return ret != null ? ret : ""; } set { if (SchemaFile != value) { ViewState ["SchemaFile"] = value; xmlDataDocument = null; OnDataSourceChanged(EventArgs.Empty); } } } XsltArgumentList transformArgumentList; [BrowsableAttribute (false)] public virtual XsltArgumentList TransformArgumentList { get { return transformArgumentList; } set { transformArgumentList = value; } } [PersistenceModeAttribute (PersistenceMode.InnerProperty)] [EditorAttribute ("System.ComponentModel.Design.MultilineStringEditor,System.Design, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] [DefaultValueAttribute ("")] // [TypeConverterAttribute (typeof(System.ComponentModel.MultilineStringConverter))] public virtual string Transform { get { string ret = ViewState ["Transform"] as string; return ret != null ? ret : ""; } set { if (Transform != value) { ViewState ["Transform"] = value; xmlDataDocument = null; OnDataSourceChanged(EventArgs.Empty); } } } [EditorAttribute ("System.Web.UI.Design.XslTransformFileEditor, System.Design, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] [DefaultValueAttribute ("")] public virtual string TransformFile { get { string ret = ViewState ["TransformFile"] as string; return ret != null ? ret : ""; } set { if (TransformFile != value) { ViewState ["TransformFile"] = value; xmlDataDocument = null; OnDataSourceChanged(EventArgs.Empty); } } } [DefaultValueAttribute ("")] public virtual string XPath { get { string ret = ViewState ["XPath"] as string; return ret != null ? ret : ""; } set { if (XPath != value) { ViewState ["XPath"] = value; OnDataSourceChanged(EventArgs.Empty); } } } } } #endif
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *********************************************************************/ using System; using System.Diagnostics; using System.IO; using Tao.DevIl; namespace Axiom.SceneManagers.Multiverse { public class TaoImage { public int Width { get; private set; } public int Height { get; private set; } public byte[] RawData { get { return buffer; } } protected int format; protected int bytesPerPixel; protected int depth; protected byte[] buffer; static TaoImage() { Il.ilInit(); Ilu.iluInit(); Il.ilEnable(Il.IL_FILE_OVERWRITE); } public TaoImage(string filename) { FileStream s = new FileStream(filename, FileMode.Open); int imageID; // create and bind a new image Il.ilGenImages(1, out imageID); Il.ilBindImage(imageID); // create a temp buffer and write the stream into it byte[] tmpBuffer = new byte[s.Length]; s.Read(tmpBuffer, 0, tmpBuffer.Length); // load the data into DevIL Il.ilLoadL(Il.IL_PNG, tmpBuffer, tmpBuffer.Length); // check for an error int ilError = Il.ilGetError(); if (ilError != Il.IL_NO_ERROR) { throw new Exception(string.Format("Error while decoding image data: '{0}'", Ilu.iluErrorString(ilError))); } // flip the image so that the mosaics produced match what L3DT produces Ilu.iluFlipImage(); format = Il.ilGetInteger(Il.IL_IMAGE_FORMAT); bytesPerPixel = Math.Max(Il.ilGetInteger(Il.IL_IMAGE_BPC), Il.ilGetInteger(Il.IL_IMAGE_BYTES_PER_PIXEL)); Width = Il.ilGetInteger(Il.IL_IMAGE_WIDTH); Height = Il.ilGetInteger(Il.IL_IMAGE_HEIGHT); depth = Il.ilGetInteger(Il.IL_IMAGE_DEPTH); // get the decoded data buffer = new byte[Width * Height * bytesPerPixel]; IntPtr ptr = Il.ilGetData(); // copy the data into the byte array unsafe { byte* pBuffer = (byte*)ptr; for (int i = 0; i < buffer.Length; i++) { buffer[i] = pBuffer[i]; } } // we won't be needing this anymore Il.ilDeleteImages(1, ref imageID); } /// <summary> /// Create an image from an area of another image /// </summary> /// <param name="src">source image</param> /// <param name="sx">x offset in source image to copy from</param> /// <param name="sy">y offset in source image to copy from</param> /// <param name="w">width of dest image and area to copy</param> /// <param name="h">width of dest image and area to copy</param> public TaoImage(TaoImage src, int sx, int sy, int w, int h) { format = src.format; bytesPerPixel = src.bytesPerPixel; depth = src.depth; Width = w; Height = h; buffer = new byte[w * h * bytesPerPixel]; int copyw = w; int copyh = h; if ((sx + w) > src.Width) { copyw = src.Width - sx; } if ((sy + h) > src.Height) { copyh = src.Height - sy; } Copy(src, sx, sy, 0, 0, copyw, copyh); } /// <summary> /// Create an image with a given width & height /// </summary> /// <param name="w">width of dest image and area to copy</param> /// <param name="h">width of dest image and area to copy</param> public TaoImage(int w, int h, int bytesPerPixel, int format) { this.format = format; this.bytesPerPixel = bytesPerPixel; depth = 1; Width = w; Height = h; buffer = new byte[w * h * bytesPerPixel]; } public TaoImage(int w, int h, byte[] source) { Width = w; Height = h; format = Il.IL_LUMINANCE; bytesPerPixel = 2; buffer = new byte[source.Length]; Array.Copy(source, buffer, buffer.Length); } public void SetPixel(int x, int y, uint value) { int index = (y * Width + x) * bytesPerPixel; for (int b=0; b < bytesPerPixel; b++) { // Write out the bytes in little-endian order byte bits = (byte) (value & 0xff); value >>= 8; buffer[index + b] = bits; } } public uint GetPixel(int x, int y) { int index = (y * Width + x) * bytesPerPixel; uint value = 0; // Bytes are organized in little-endian order for (int b = bytesPerPixel - 1; b >= 0; b--) { value <<= 8; value |= buffer[index + b]; } return value; } public void Copy(TaoImage src, int sx, int sy, int dx, int dy, int w, int h) { Debug.Assert(src.bytesPerPixel == bytesPerPixel); Debug.Assert((sx + w) <= src.Width); Debug.Assert((sy + h) <= src.Height); Debug.Assert((dx + w) <= Width); Debug.Assert((dy + h) <= Height); for (int y = 0; y < h; y++) { int destoff = ((dy + y) * Width + dx) * bytesPerPixel; int srcoff = ((sy + y) * src.Width + sx) * bytesPerPixel; for (int x = 0; x < (w * bytesPerPixel); x++) { buffer[destoff + x] = src.buffer[srcoff + x]; } } } public void Save(string savename) { int imageID; // create and bind a new image Il.ilGenImages(1, out imageID); Il.ilBindImage(imageID); Il.ilSetString(Il.IL_PNG_AUTHNAME_STRING, "Multiverse Network"); // stuff the data into the image if (bytesPerPixel == 2 && format == Il.IL_LUMINANCE) { // special case for 16 bit greyscale Il.ilTexImage(Width, Height, depth, 1, format, Il.IL_UNSIGNED_SHORT, buffer); } else { Il.ilTexImage(Width, Height, depth, (byte)bytesPerPixel, format, Il.IL_UNSIGNED_BYTE, buffer); } // flip the image so that the mosaics produced match what L3DT produces Ilu.iluFlipImage(); // save the image to file Il.ilEnable(Il.IL_FILE_OVERWRITE); Il.ilSaveImage(savename); // delete the image Il.ilDeleteImages(1, ref imageID); } public void DumpErrors(string title) { int error = Il.ilGetError(); while (error != 0) { Console.WriteLine(title + ": Error #" + error + " Message: " + Ilu.iluErrorString(error)); error = Il.ilGetError(); } } /// <summary> /// Converts a DevIL format enum to a PixelFormat enum. /// </summary> public string PixelFormatName { get { string ret = "Unknown"; switch (bytesPerPixel) { case 1: ret = "8-bit Greyscale"; break; case 2: switch (format) { case Il.IL_BGR: ret = "16-bit RGB (B5G6R5)"; break; case Il.IL_RGB: ret = "16-bit RGB (R5G6B5)"; break; case Il.IL_BGRA: ret = "16-bit BGRA (B4G4R4A4)"; break; case Il.IL_RGBA: ret = "16-bit RGBA (A4R4G4B4)"; break; case Il.IL_LUMINANCE: ret = "16-bit Greyscale"; break; } break; case 3: switch (format) { case Il.IL_BGR: ret = "24-bit BGR"; break; case Il.IL_RGB: ret = "24-bit RGB"; break; case Il.IL_LUMINANCE: ret = "24-bit Greyscale"; break; } break; case 4: switch (format) { case Il.IL_BGRA: ret = "32-bit BGRA"; break; case Il.IL_RGBA: ret = "32-bit RGBA"; break; case Il.IL_DXT1: ret = "32-bit DXT1"; break; case Il.IL_DXT2: ret = "32-bit DXT2"; break; case Il.IL_DXT3: ret = "32-bit DXT3"; break; case Il.IL_DXT4: ret = "32-bit DXT4"; break; case Il.IL_DXT5: ret = "32-bit DXT5"; break; } break; } return ret; } } } }
using UnityEngine; using UnityEngine.Experimental.Rendering.HDPipeline; using System.Collections.Generic; using UnityEditorInternal; namespace UnityEditor.Experimental.Rendering.HDPipeline { [CanEditMultipleObjects] [CustomEditor(typeof(DensityVolume))] class DensityVolumeEditor : Editor { internal const EditMode.SceneViewEditMode k_EditShape = EditMode.SceneViewEditMode.ReflectionProbeBox; internal const EditMode.SceneViewEditMode k_EditBlend = EditMode.SceneViewEditMode.GridBox; static HierarchicalBox s_ShapeBox; internal static HierarchicalBox s_BlendBox; SerializedDensityVolume m_SerializedDensityVolume; void OnEnable() { m_SerializedDensityVolume = new SerializedDensityVolume(serializedObject); if (s_ShapeBox == null || s_ShapeBox.Equals(null)) { s_ShapeBox = new HierarchicalBox(DensityVolumeUI.Styles.k_GizmoColorBase, DensityVolumeUI.Styles.k_BaseHandlesColor); s_ShapeBox.monoHandle = false; } if (s_BlendBox == null || s_BlendBox.Equals(null)) { s_BlendBox = new HierarchicalBox(DensityVolumeUI.Styles.k_GizmoColorBase, InfluenceVolumeUI.k_HandlesColor, parent: s_ShapeBox); } } public override void OnInspectorGUI() { serializedObject.Update(); DensityVolumeUI.Inspector.Draw(m_SerializedDensityVolume, this); m_SerializedDensityVolume.Apply(); } static Vector3 CenterBlendLocalPosition(DensityVolume densityVolume) { if (densityVolume.parameters.m_EditorAdvancedFade) { Vector3 size = densityVolume.parameters.size; Vector3 posBlend = densityVolume.parameters.m_EditorPositiveFade; posBlend.x *= size.x; posBlend.y *= size.y; posBlend.z *= size.z; Vector3 negBlend = densityVolume.parameters.m_EditorNegativeFade; negBlend.x *= size.x; negBlend.y *= size.y; negBlend.z *= size.z; Vector3 localPosition = (negBlend - posBlend) * 0.5f; return localPosition; } else return Vector3.zero; } static Vector3 BlendSize(DensityVolume densityVolume) { Vector3 size = densityVolume.parameters.size; if (densityVolume.parameters.m_EditorAdvancedFade) { Vector3 blendSize = (Vector3.one - densityVolume.parameters.m_EditorPositiveFade - densityVolume.parameters.m_EditorNegativeFade); blendSize.x *= size.x; blendSize.y *= size.y; blendSize.z *= size.z; return blendSize; } else return size - densityVolume.parameters.m_EditorUniformFade * 2f * Vector3.one; } [DrawGizmo(GizmoType.Selected|GizmoType.Active)] static void DrawGizmosSelected(DensityVolume densityVolume, GizmoType gizmoType) { using (new Handles.DrawingScope(Matrix4x4.TRS(densityVolume.transform.position, densityVolume.transform.rotation, Vector3.one))) { // Blend box s_BlendBox.center = CenterBlendLocalPosition(densityVolume); s_BlendBox.size = BlendSize(densityVolume); Color baseColor = densityVolume.parameters.albedo; baseColor.a = 8/255f; s_BlendBox.baseColor = baseColor; s_BlendBox.DrawHull(EditMode.editMode == k_EditBlend); // Bounding box. s_ShapeBox.center = Vector3.zero; s_ShapeBox.size = densityVolume.parameters.size; s_ShapeBox.DrawHull(EditMode.editMode == k_EditShape); } } void OnSceneGUI() { //Note: for each handle to be independent when multi-selecting DensityVolume, //We cannot rely hereon SerializedDensityVolume which is the collection of //selected DensityVolume. Thus code is almost the same of the UI. DensityVolume densityVolume = target as DensityVolume; switch (EditMode.editMode) { case k_EditBlend: using (new Handles.DrawingScope(Matrix4x4.TRS(densityVolume.transform.position, densityVolume.transform.rotation, Vector3.one))) { //contained must be initialized in all case s_ShapeBox.center = Vector3.zero; s_ShapeBox.size = densityVolume.parameters.size; Color baseColor = densityVolume.parameters.albedo; baseColor.a = 8 / 255f; s_BlendBox.baseColor = baseColor; s_BlendBox.monoHandle = !densityVolume.parameters.m_EditorAdvancedFade; s_BlendBox.center = CenterBlendLocalPosition(densityVolume); s_BlendBox.size = BlendSize(densityVolume); EditorGUI.BeginChangeCheck(); s_BlendBox.DrawHandle(); if (EditorGUI.EndChangeCheck()) { Undo.RecordObject(densityVolume, "Change Density Volume Blend"); if (densityVolume.parameters.m_EditorAdvancedFade) { //work in local space to compute the change on positiveFade and negativeFade Vector3 newCenterBlendLocalPosition = s_BlendBox.center; Vector3 halfSize = s_BlendBox.size * 0.5f; Vector3 size = densityVolume.parameters.size; Vector3 posFade = newCenterBlendLocalPosition + halfSize; posFade.x = 0.5f - posFade.x / size.x; posFade.y = 0.5f - posFade.y / size.y; posFade.z = 0.5f - posFade.z / size.z; Vector3 negFade = newCenterBlendLocalPosition - halfSize; negFade.x = 0.5f + negFade.x / size.x; negFade.y = 0.5f + negFade.y / size.y; negFade.z = 0.5f + negFade.z / size.z; densityVolume.parameters.m_EditorPositiveFade = posFade; densityVolume.parameters.m_EditorNegativeFade = negFade; } else { float uniformDistance = (s_ShapeBox.size.x - s_BlendBox.size.x) * 0.5f; float max = Mathf.Min(s_ShapeBox.size.x, s_ShapeBox.size.y, s_ShapeBox.size.z) * 0.5f; densityVolume.parameters.m_EditorUniformFade = Mathf.Clamp(uniformDistance, 0f, max); } } } break; case k_EditShape: //important: if the origin of the handle's space move along the handle, //handles displacement will appears as moving two time faster. using (new Handles.DrawingScope(Matrix4x4.TRS(Vector3.zero, densityVolume.transform.rotation, Vector3.one))) { //contained must be initialized in all case s_ShapeBox.center = Quaternion.Inverse(densityVolume.transform.rotation) * densityVolume.transform.position; s_ShapeBox.size = densityVolume.parameters.size; Vector3 previousSize = densityVolume.parameters.size; Vector3 previousPositiveFade = densityVolume.parameters.m_EditorPositiveFade; Vector3 previousNegativeFade = densityVolume.parameters.m_EditorNegativeFade; EditorGUI.BeginChangeCheck(); s_ShapeBox.DrawHandle(); if (EditorGUI.EndChangeCheck()) { Undo.RecordObjects(new Object[] { densityVolume, densityVolume.transform }, "ChangeDensity Volume Bounding Box"); Vector3 newSize = s_ShapeBox.size; densityVolume.parameters.size = newSize; Vector3 newPositiveFade = new Vector3( newSize.x < 0.00001 ? 0 : previousPositiveFade.x * previousSize.x / newSize.x, newSize.y < 0.00001 ? 0 : previousPositiveFade.y * previousSize.y / newSize.y, newSize.z < 0.00001 ? 0 : previousPositiveFade.z * previousSize.z / newSize.z ); Vector3 newNegativeFade = new Vector3( newSize.x < 0.00001 ? 0 : previousNegativeFade.x * previousSize.x / newSize.x, newSize.y < 0.00001 ? 0 : previousNegativeFade.y * previousSize.y / newSize.y, newSize.z < 0.00001 ? 0 : previousNegativeFade.z * previousSize.z / newSize.z ); for (int axeIndex = 0; axeIndex < 3; ++axeIndex) { if (newPositiveFade[axeIndex] + newNegativeFade[axeIndex] > 1) { float overValue = (newPositiveFade[axeIndex] + newNegativeFade[axeIndex] - 1f) * 0.5f; newPositiveFade[axeIndex] -= overValue; newNegativeFade[axeIndex] -= overValue; if (newPositiveFade[axeIndex] < 0) { newNegativeFade[axeIndex] += newPositiveFade[axeIndex]; newPositiveFade[axeIndex] = 0f; } if (newNegativeFade[axeIndex] < 0) { newPositiveFade[axeIndex] += newNegativeFade[axeIndex]; newNegativeFade[axeIndex] = 0f; } } } densityVolume.parameters.m_EditorPositiveFade = newPositiveFade; densityVolume.parameters.m_EditorNegativeFade = newNegativeFade; //update normal mode blend float max = Mathf.Min(newSize.x, newSize.y, newSize.z) * 0.5f; float newUniformFade = Mathf.Clamp(densityVolume.parameters.m_EditorUniformFade, 0f, max); densityVolume.parameters.m_EditorUniformFade = newUniformFade; //update engine used percents if (densityVolume.parameters.m_EditorAdvancedFade) { densityVolume.parameters.positiveFade = newPositiveFade; densityVolume.parameters.negativeFade = newNegativeFade; } else { densityVolume.parameters.positiveFade = densityVolume.parameters.negativeFade = new Vector3( newSize.x > 0.00001 ? (newSize.x - newUniformFade) / newSize.x : 0f, newSize.y > 0.00001 ? (newSize.y - newUniformFade) / newSize.y : 0f, newSize.z > 0.00001 ? (newSize.z - newUniformFade) / newSize.z : 0f ); } Vector3 delta = densityVolume.transform.rotation * s_ShapeBox.center - densityVolume.transform.position; densityVolume.transform.position += delta; } } break; } } } }
#region License /* The MIT License Copyright (c) 2008 Sky Morey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion namespace System.Web.UI { public partial class HtmlBuilder { public HtmlBuilder BeginSmartTag(HtmlTag tag, params string[] args) { return BeginSmartTag(tag, Nparams.Parse(args)); } public HtmlBuilder BeginSmartTag(HtmlTag tag, Nparams args) { string c; switch (tag) { case HtmlTag._CommandTarget: throw new NotSupportedException(); case HtmlTag.Script: o_Script(args); return this; // Container case HtmlTag.Div: o_Div(args); return this; // Content case HtmlTag.A: if ((args == null) || (string.IsNullOrEmpty(c = args.Slice<string>("url")))) throw new ArgumentException("Local.UndefinedAttribUrl", "attrib"); o_A(c, args); return this; case HtmlTag.H1: o_H1(args); return this; case HtmlTag.H2: o_H2(args); return this; case HtmlTag.H3: o_H3(args); return this; case HtmlTag.P: o_P(args); return this; case HtmlTag.Span: o_Span(args); return this; // List case HtmlTag.Li: o_Li(args); return this; case HtmlTag.Ol: o_Ol(args); return this; case HtmlTag.Ul: o_Ul(args); return this; // Table case HtmlTag.Colgroup: o_Colgroup(args); return this; case HtmlTag.Table: o_Table(args); return this; case HtmlTag.Tbody: o_Tbody(args); return this; case HtmlTag.Td: o_Td(args); return this; case HtmlTag.Tfoot: o_Tfoot(args); return this; case HtmlTag.Th: o_Th(args); return this; case HtmlTag.Thead: o_Thead(args); return this; case HtmlTag.Tr: o_Tr(args); return this; // Form case HtmlTag.Button: o_Button(args); return this; case HtmlTag.Fieldset: o_Fieldset(args); return this; case HtmlTag.Form: throw new NotSupportedException(); case HtmlTag._FormReference: throw new NotSupportedException(); case HtmlTag.Label: if ((args == null) || (string.IsNullOrEmpty(c = args.Slice<string>("forName")))) throw new ArgumentException("Local.UndefinedAttribForName", "attrib"); o_Label(c, args); return this; // o_optgroup - no match case HtmlTag.Option: if ((args == null) || (string.IsNullOrEmpty(c = args.Slice<string>("value")))) throw new ArgumentException("Local.UndefinedAttribValue", "attrib"); o_Option(c, args); return this; case HtmlTag.Select: if ((args == null) || (string.IsNullOrEmpty(c = args.Slice<string>("name")))) throw new ArgumentException("Local.UndefinedAttribName", "attrib"); o_Select(c, args); return this; case HtmlTag.Textarea: if ((args == null) || (string.IsNullOrEmpty(c = args.Slice<string>("name")))) throw new ArgumentException("Local.UndefinedAttribName", "attrib"); o_Textarea(c, args); return this; } BeginHtmlTag(tag); return this; } public HtmlBuilder EndSmartTag(HtmlTag tag, params string[] args) { return EndSmartTag(tag, Nparams.Parse(args)); } public HtmlBuilder EndSmartTag(HtmlTag tag, Nparams args) { string c; string c2; switch (tag) { case HtmlTag._CommandTarget: x_CommandTarget(); return this; case HtmlTag.Script: x_Script(); return this; // Container case HtmlTag.Div: x_Div(); return this; case HtmlTag.Iframe: if ((args == null) || (string.IsNullOrEmpty(c = args.Slice<string>("url")))) throw new ArgumentException("Local.UndefinedAttribUrl", "attrib"); x_Iframe(c, args); return this; // Content case HtmlTag.A: x_A(); return this; case HtmlTag.Br: x_Br(); return this; case HtmlTag.H1: x_H1(); return this; case HtmlTag.H2: x_H2(); return this; case HtmlTag.H3: x_H3(); return this; case HtmlTag.Hr: x_Hr(args); return this; case HtmlTag.Img: if ((args == null) || (string.IsNullOrEmpty(c = args.Slice<string>("url")))) throw new ArgumentException("Local.UndefinedAttribUrl", "attrib"); if (string.IsNullOrEmpty(c2 = args.Slice<string>("value"))) throw new ArgumentException("Local.UndefinedAttribValue", "attrib"); x_Img(c, c2, args); return this; case HtmlTag.P: x_P(); return this; case HtmlTag.Span: x_Span(); return this; //- x_tofu - no match // List case HtmlTag.Li: x_Li(); return this; case HtmlTag.Ol: x_Ol(); return this; case HtmlTag.Ul: x_Ul(); return this; // Table case HtmlTag.Col: x_Col(args); return this; case HtmlTag.Colgroup: x_Colgroup(); return this; case HtmlTag.Table: x_Table(); return this; case HtmlTag.Tbody: x_Tbody(); return this; case HtmlTag.Td: x_Td(); return this; case HtmlTag.Tfoot: x_Tfoot(); return this; case HtmlTag.Th: x_Th(); return this; case HtmlTag.Thead: x_Thead(); return this; case HtmlTag.Tr: x_Tr(); return this; // Form case HtmlTag.Button: x_Button(); return this; case HtmlTag.Fieldset: x_Fieldset(); return this; case HtmlTag.Form: x_Form(); return this; case HtmlTag._FormReference: x_FormReference(); return this; case HtmlTag.Input: if ((args == null) || (string.IsNullOrEmpty(c = args.Slice<string>("name")))) throw new ArgumentException("Local.UndefinedAttribName", "attrib"); if (string.IsNullOrEmpty(c2 = args.Slice<string>("value"))) throw new ArgumentException("Local.UndefinedAttribValue", "attrib"); x_Input(c, c2, args); return this; case HtmlTag.Label: x_Label(); return this; // x_optgroup - no match case HtmlTag.Option: x_Option(); return this; case HtmlTag.Select: x_Select(); return this; case HtmlTag.Textarea: x_Textarea(); return this; } EndHtmlTag(); return this; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Security; using System.Windows.Input; using Internal.Runtime.CompilerServices; namespace System.Runtime.InteropServices.WindowsRuntime { // Local definition of Windows.UI.Xaml.Interop.INotifyCollectionChangedEventArgs [ComImport] [Guid("4cf68d33-e3f2-4964-b85e-945b4f7e2f21")] [WindowsRuntimeImport] internal interface INotifyCollectionChangedEventArgs { NotifyCollectionChangedAction Action { get; } IList NewItems { get; } IList OldItems { get; } int NewStartingIndex { get; } int OldStartingIndex { get; } } // Local definition of Windows.UI.Xaml.Data.IPropertyChangedEventArgs [ComImport] [Guid("4f33a9a0-5cf4-47a4-b16f-d7faaf17457e")] [WindowsRuntimeImport] internal interface IPropertyChangedEventArgs { string PropertyName { get; } } // Local definition of Windows.UI.Xaml.Interop.INotifyCollectionChanged [ComImport] [Guid("28b167d5-1a31-465b-9b25-d5c3ae686c40")] [WindowsRuntimeImport] internal interface INotifyCollectionChanged_WinRT { EventRegistrationToken add_CollectionChanged(NotifyCollectionChangedEventHandler value); void remove_CollectionChanged(EventRegistrationToken token); } // Local definition of Windows.UI.Xaml.Data.INotifyPropertyChanged [ComImport] [Guid("cf75d69c-f2f4-486b-b302-bb4c09baebfa")] [WindowsRuntimeImport] internal interface INotifyPropertyChanged_WinRT { EventRegistrationToken add_PropertyChanged(PropertyChangedEventHandler value); void remove_PropertyChanged(EventRegistrationToken token); } // Local definition of Windows.UI.Xaml.Input.ICommand [ComImport] [Guid("e5af3542-ca67-4081-995b-709dd13792df")] [WindowsRuntimeImport] internal interface ICommand_WinRT { EventRegistrationToken add_CanExecuteChanged(EventHandler<object> value); void remove_CanExecuteChanged(EventRegistrationToken token); bool CanExecute(object parameter); void Execute(object parameter); } // Local definition of Windows.UI.Xaml.Interop.NotifyCollectionChangedEventHandler [Guid("ca10b37c-f382-4591-8557-5e24965279b0")] [WindowsRuntimeImport] internal delegate void NotifyCollectionChangedEventHandler_WinRT(object sender, NotifyCollectionChangedEventArgs e); // Local definition of Windows.UI.Xaml.Data.PropertyChangedEventHandler [Guid("50f19c16-0a22-4d8e-a089-1ea9951657d2")] [WindowsRuntimeImport] internal delegate void PropertyChangedEventHandler_WinRT(object sender, PropertyChangedEventArgs e); // Local definition of Windows.UI.Xaml.Interop.INotifyCollectionChangedEventArgsFactory [ComImport] [Guid("b30c3e3a-df8d-44a5-9a38-7ac0d08ce63d")] [WindowsRuntimeImport] internal interface INotifyCollectionChangedEventArgsFactory { // The return type for this function is actually an INotifyCollectionChangedEventArgs* // but we need to make sure we don't accidentally project our native object back to managed // when marshalling it to native (which happens when correctly typing the return type as an INotifyCollectionChangedEventArgs). IntPtr CreateInstanceWithAllParameters(int action, IList newItems, IList oldItems, int newIndex, int oldIndex, object outer, ref object inner); } // Local definition of Windows.UI.Xaml.Data.INotifyCollectionChangedEventArgsFactory [ComImport] [Guid("6dcc9c03-e0c7-4eee-8ea9-37e3406eeb1c")] [WindowsRuntimeImport] internal interface IPropertyChangedEventArgsFactory { // The return type for this function is actually an IPropertyChangedEventArgs* // but we need to make sure we don't accidentally project our native object back to managed // when marshalling it to native (which happens when correctly typing the return type as an IPropertyChangedEventArgs). IntPtr CreateInstance(string name, object outer, ref object inner); } internal static class NotifyCollectionChangedEventArgsMarshaler { private const string WinRTNotifyCollectionChangedEventArgsName = "Windows.UI.Xaml.Interop.NotifyCollectionChangedEventArgs"; private static INotifyCollectionChangedEventArgsFactory s_EventArgsFactory; // Extracts properties from a managed NotifyCollectionChangedEventArgs and passes them to // a VM-implemented helper that creates a WinRT NotifyCollectionChangedEventArgs instance. // This method is called from IL stubs and needs to have its token stabilized. internal static IntPtr ConvertToNative(NotifyCollectionChangedEventArgs managedArgs) { if (managedArgs == null) return IntPtr.Zero; if (s_EventArgsFactory == null) { object factory = null; Guid guid = typeof(INotifyCollectionChangedEventArgsFactory).GUID; int hr = Interop.mincore.RoGetActivationFactory(WinRTNotifyCollectionChangedEventArgsName, ref guid, out factory); if (hr < 0) Marshal.ThrowExceptionForHR(hr); s_EventArgsFactory = (INotifyCollectionChangedEventArgsFactory)factory; } object inner = null; return s_EventArgsFactory.CreateInstanceWithAllParameters((int)managedArgs.Action, managedArgs.NewItems, managedArgs.OldItems, managedArgs.NewStartingIndex, managedArgs.OldStartingIndex, null, ref inner); } // Extracts properties from a WinRT NotifyCollectionChangedEventArgs and creates a new // managed NotifyCollectionChangedEventArgs instance. // This method is called from IL stubs and needs to have its token stabilized. internal static NotifyCollectionChangedEventArgs ConvertToManaged(IntPtr nativeArgsIP) { if (nativeArgsIP == IntPtr.Zero) return null; object obj = WindowsRuntimeMarshal.GetUniqueObjectForIUnknownWithoutUnboxing(nativeArgsIP); INotifyCollectionChangedEventArgs nativeArgs = (INotifyCollectionChangedEventArgs)obj; return CreateNotifyCollectionChangedEventArgs( nativeArgs.Action, nativeArgs.NewItems, nativeArgs.OldItems, nativeArgs.NewStartingIndex, nativeArgs.OldStartingIndex); } internal static NotifyCollectionChangedEventArgs CreateNotifyCollectionChangedEventArgs( NotifyCollectionChangedAction action, IList newItems, IList oldItems, int newStartingIndex, int oldStartingIndex) => action switch { NotifyCollectionChangedAction.Add => new NotifyCollectionChangedEventArgs(action, newItems, newStartingIndex), NotifyCollectionChangedAction.Remove => new NotifyCollectionChangedEventArgs(action, oldItems, oldStartingIndex), NotifyCollectionChangedAction.Replace => new NotifyCollectionChangedEventArgs(action, newItems, oldItems, newStartingIndex), NotifyCollectionChangedAction.Move => new NotifyCollectionChangedEventArgs(action, newItems, newStartingIndex, oldStartingIndex), NotifyCollectionChangedAction.Reset => new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset), _ => throw new ArgumentException("Invalid action value: " + action), }; } internal static class PropertyChangedEventArgsMarshaler { private const string WinRTPropertyChangedEventArgsName = "Windows.UI.Xaml.Data.PropertyChangedEventArgs"; private static IPropertyChangedEventArgsFactory s_pPCEventArgsFactory; // Extracts PropertyName from a managed PropertyChangedEventArgs and passes them to // a VM-implemented helper that creates a WinRT PropertyChangedEventArgs instance. // This method is called from IL stubs and needs to have its token stabilized. internal static IntPtr ConvertToNative(PropertyChangedEventArgs managedArgs) { if (managedArgs == null) return IntPtr.Zero; if (s_pPCEventArgsFactory == null) { object factory = null; Guid guid = typeof(IPropertyChangedEventArgsFactory).GUID; int hr = Interop.mincore.RoGetActivationFactory(WinRTPropertyChangedEventArgsName, ref guid, out factory); if (hr < 0) Marshal.ThrowExceptionForHR(hr); s_pPCEventArgsFactory = (IPropertyChangedEventArgsFactory)factory; } object inner = null; return s_pPCEventArgsFactory.CreateInstance(managedArgs.PropertyName, null, ref inner); } // Extracts properties from a WinRT PropertyChangedEventArgs and creates a new // managed PropertyChangedEventArgs instance. // This method is called from IL stubs and needs to have its token stabilized. internal static PropertyChangedEventArgs ConvertToManaged(IntPtr nativeArgsIP) { if (nativeArgsIP == IntPtr.Zero) return null; object obj = WindowsRuntimeMarshal.GetUniqueObjectForIUnknownWithoutUnboxing(nativeArgsIP); IPropertyChangedEventArgs nativeArgs = (IPropertyChangedEventArgs)obj; return new PropertyChangedEventArgs(nativeArgs.PropertyName); } } // This is a set of stub methods implementing the support for the managed INotifyCollectionChanged // interface on WinRT objects that support the WinRT INotifyCollectionChanged. Used by the interop // mashaling infrastructure. internal sealed class NotifyCollectionChangedToManagedAdapter { private NotifyCollectionChangedToManagedAdapter() { Debug.Fail("This class is never instantiated"); } internal event NotifyCollectionChangedEventHandler CollectionChanged { // void CollectionChanged.add(NotifyCollectionChangedEventHandler) add { INotifyCollectionChanged_WinRT _this = Unsafe.As<INotifyCollectionChanged_WinRT>(this); // call the WinRT eventing support in mscorlib to subscribe the event Func<NotifyCollectionChangedEventHandler, EventRegistrationToken> addMethod = new Func<NotifyCollectionChangedEventHandler, EventRegistrationToken>(_this.add_CollectionChanged); Action<EventRegistrationToken> removeMethod = new Action<EventRegistrationToken>(_this.remove_CollectionChanged); WindowsRuntimeMarshal.AddEventHandler<NotifyCollectionChangedEventHandler>(addMethod, removeMethod, value); } // void CollectionChanged.remove(NotifyCollectionChangedEventHandler) remove { INotifyCollectionChanged_WinRT _this = Unsafe.As<INotifyCollectionChanged_WinRT>(this); // call the WinRT eventing support in mscorlib to unsubscribe the event Action<EventRegistrationToken> removeMethod = new Action<EventRegistrationToken>(_this.remove_CollectionChanged); WindowsRuntimeMarshal.RemoveEventHandler<NotifyCollectionChangedEventHandler>(removeMethod, value); } } } // This is a set of stub methods implementing the support for the WinRT INotifyCollectionChanged // interface on managed objects that support the managed INotifyCollectionChanged. Used by the interop // mashaling infrastructure. internal sealed class NotifyCollectionChangedToWinRTAdapter { private NotifyCollectionChangedToWinRTAdapter() { Debug.Fail("This class is never instantiated"); } // An instance field typed as EventRegistrationTokenTable is injected into managed classed by the compiler when compiling for /t:winmdobj. // Since here the class can be an arbitrary implementation of INotifyCollectionChanged, we have to keep the EventRegistrationTokenTable's // separately, associated with the implementations using ConditionalWeakTable. private static readonly ConditionalWeakTable<INotifyCollectionChanged, EventRegistrationTokenTable<NotifyCollectionChangedEventHandler>> s_weakTable = new ConditionalWeakTable<INotifyCollectionChanged, EventRegistrationTokenTable<NotifyCollectionChangedEventHandler>>(); // EventRegistrationToken CollectionChanged.add(NotifyCollectionChangedEventHandler value) internal EventRegistrationToken add_CollectionChanged(NotifyCollectionChangedEventHandler value) { INotifyCollectionChanged _this = Unsafe.As<INotifyCollectionChanged>(this); EventRegistrationTokenTable<NotifyCollectionChangedEventHandler> table = s_weakTable.GetOrCreateValue(_this); EventRegistrationToken token = table.AddEventHandler(value); _this.CollectionChanged += value; return token; } // void CollectionChanged.remove(EventRegistrationToken token) internal void remove_CollectionChanged(EventRegistrationToken token) { INotifyCollectionChanged _this = Unsafe.As<INotifyCollectionChanged>(this); EventRegistrationTokenTable<NotifyCollectionChangedEventHandler> table = s_weakTable.GetOrCreateValue(_this); if (table.RemoveEventHandler(token, out NotifyCollectionChangedEventHandler handler)) { _this.CollectionChanged -= handler; } } } // This is a set of stub methods implementing the support for the managed INotifyPropertyChanged // interface on WinRT objects that support the WinRT INotifyPropertyChanged. Used by the interop // mashaling infrastructure. internal sealed class NotifyPropertyChangedToManagedAdapter { private NotifyPropertyChangedToManagedAdapter() { Debug.Fail("This class is never instantiated"); } internal event PropertyChangedEventHandler PropertyChanged { // void PropertyChanged.add(PropertyChangedEventHandler) add { INotifyPropertyChanged_WinRT _this = Unsafe.As<INotifyPropertyChanged_WinRT>(this); // call the WinRT eventing support in mscorlib to subscribe the event Func<PropertyChangedEventHandler, EventRegistrationToken> addMethod = new Func<PropertyChangedEventHandler, EventRegistrationToken>(_this.add_PropertyChanged); Action<EventRegistrationToken> removeMethod = new Action<EventRegistrationToken>(_this.remove_PropertyChanged); WindowsRuntimeMarshal.AddEventHandler<PropertyChangedEventHandler>(addMethod, removeMethod, value); } // void PropertyChanged.remove(PropertyChangedEventHandler) remove { INotifyPropertyChanged_WinRT _this = Unsafe.As<INotifyPropertyChanged_WinRT>(this); // call the WinRT eventing support in mscorlib to unsubscribe the event Action<EventRegistrationToken> removeMethod = new Action<EventRegistrationToken>(_this.remove_PropertyChanged); WindowsRuntimeMarshal.RemoveEventHandler<PropertyChangedEventHandler>(removeMethod, value); } } } // This is a set of stub methods implementing the support for the WinRT INotifyPropertyChanged // interface on managed objects that support the managed INotifyPropertyChanged. Used by the interop // mashaling infrastructure. internal sealed class NotifyPropertyChangedToWinRTAdapter { private NotifyPropertyChangedToWinRTAdapter() { Debug.Fail("This class is never instantiated"); } // An instance field typed as EventRegistrationTokenTable is injected into managed classed by the compiler when compiling for /t:winmdobj. // Since here the class can be an arbitrary implementation of INotifyCollectionChanged, we have to keep the EventRegistrationTokenTable's // separately, associated with the implementations using ConditionalWeakTable. private static readonly ConditionalWeakTable<INotifyPropertyChanged, EventRegistrationTokenTable<PropertyChangedEventHandler>> s_weakTable = new ConditionalWeakTable<INotifyPropertyChanged, EventRegistrationTokenTable<PropertyChangedEventHandler>>(); // EventRegistrationToken PropertyChanged.add(PropertyChangedEventHandler value) internal EventRegistrationToken add_PropertyChanged(PropertyChangedEventHandler value) { INotifyPropertyChanged _this = Unsafe.As<INotifyPropertyChanged>(this); EventRegistrationTokenTable<PropertyChangedEventHandler> table = s_weakTable.GetOrCreateValue(_this); EventRegistrationToken token = table.AddEventHandler(value); _this.PropertyChanged += value; return token; } // void PropertyChanged.remove(EventRegistrationToken token) internal void remove_PropertyChanged(EventRegistrationToken token) { INotifyPropertyChanged _this = Unsafe.As<INotifyPropertyChanged>(this); EventRegistrationTokenTable<PropertyChangedEventHandler> table = s_weakTable.GetOrCreateValue(_this); if (table.RemoveEventHandler(token, out PropertyChangedEventHandler handler)) { _this.PropertyChanged -= handler; } } } // This is a set of stub methods implementing the support for the managed ICommand // interface on WinRT objects that support the WinRT ICommand_WinRT. // Used by the interop mashaling infrastructure. // Instances of this are really RCWs of ICommand_WinRT (not ICommandToManagedAdapter or any ICommand). internal sealed class ICommandToManagedAdapter /*: System.Windows.Input.ICommand*/ { private static readonly ConditionalWeakTable<EventHandler, EventHandler<object>> s_weakTable = new ConditionalWeakTable<EventHandler, EventHandler<object>>(); private ICommandToManagedAdapter() { Debug.Fail("This class is never instantiated"); } private event EventHandler CanExecuteChanged { // void CanExecuteChanged.add(EventHandler) add { ICommand_WinRT _this = Unsafe.As<ICommand_WinRT>(this); // call the WinRT eventing support in mscorlib to subscribe the event Func<EventHandler<object>, EventRegistrationToken> addMethod = new Func<EventHandler<object>, EventRegistrationToken>(_this.add_CanExecuteChanged); Action<EventRegistrationToken> removeMethod = new Action<EventRegistrationToken>(_this.remove_CanExecuteChanged); // value is of type System.EventHandler, but ICommand_WinRT (and thus WindowsRuntimeMarshal.AddEventHandler) // expects an instance of EventHandler<object>. So we get/create a wrapper of value here. EventHandler<object> handler_WinRT = s_weakTable.GetValue(value, ICommandAdapterHelpers.CreateWrapperHandler); WindowsRuntimeMarshal.AddEventHandler<EventHandler<object>>(addMethod, removeMethod, handler_WinRT); } // void CanExecuteChanged.remove(EventHandler) remove { ICommand_WinRT _this = Unsafe.As<ICommand_WinRT>(this); // call the WinRT eventing support in mscorlib to unsubscribe the event Action<EventRegistrationToken> removeMethod = new Action<EventRegistrationToken>(_this.remove_CanExecuteChanged); // value is of type System.EventHandler, but ICommand_WinRT (and thus WindowsRuntimeMarshal.RemoveEventHandler) // expects an instance of EventHandler<object>. So we get/create a wrapper of value here. // Also we do a value check rather than an instance check to ensure that different instances of the same delegates are treated equal. EventHandler<object> handler_WinRT = ICommandAdapterHelpers.GetValueFromEquivalentKey(s_weakTable, value, ICommandAdapterHelpers.CreateWrapperHandler); WindowsRuntimeMarshal.RemoveEventHandler<EventHandler<object>>(removeMethod, handler_WinRT); } } private bool CanExecute(object parameter) { ICommand_WinRT _this = Unsafe.As<ICommand_WinRT>(this); return _this.CanExecute(parameter); } private void Execute(object parameter) { ICommand_WinRT _this = Unsafe.As<ICommand_WinRT>(this); _this.Execute(parameter); } } // This is a set of stub methods implementing the support for the WinRT ICommand_WinRT // interface on managed objects that support the managed ICommand interface. // Used by the interop mashaling infrastructure. // Instances of this are really CCWs of ICommand (not ICommandToWinRTAdapter or any ICommand_WinRT). internal sealed class ICommandToWinRTAdapter /*: ICommand_WinRT*/ { private ICommandToWinRTAdapter() { Debug.Fail("This class is never instantiated"); } // An instance field typed as EventRegistrationTokenTable is injected into managed classed by the compiler when compiling for /t:winmdobj. // Since here the class can be an arbitrary implementation of ICommand, we have to keep the EventRegistrationTokenTable's // separately, associated with the implementations using ConditionalWeakTable. private static readonly ConditionalWeakTable<ICommand, EventRegistrationTokenTable<EventHandler>> s_weakTable = new ConditionalWeakTable<ICommand, EventRegistrationTokenTable<EventHandler>>(); // EventRegistrationToken PropertyChanged.add(EventHandler<object> value) private EventRegistrationToken add_CanExecuteChanged(EventHandler<object> value) { ICommand _this = Unsafe.As<ICommand>(this); EventRegistrationTokenTable<EventHandler> table = s_weakTable.GetOrCreateValue(_this); EventHandler handler = ICommandAdapterHelpers.CreateWrapperHandler(value); EventRegistrationToken token = table.AddEventHandler(handler); _this.CanExecuteChanged += handler; return token; } // void PropertyChanged.remove(EventRegistrationToken token) private void remove_CanExecuteChanged(EventRegistrationToken token) { ICommand _this = Unsafe.As<ICommand>(this); EventRegistrationTokenTable<EventHandler> table = s_weakTable.GetOrCreateValue(_this); if (table.RemoveEventHandler(token, out EventHandler handler)) { _this.CanExecuteChanged -= handler; } } private bool CanExecute(object parameter) { ICommand _this = Unsafe.As<ICommand>(this); return _this.CanExecute(parameter); } private void Execute(object parameter) { ICommand _this = Unsafe.As<ICommand>(this); _this.Execute(parameter); } } // A couple of ICommand adapter helpers need to be transparent, and so are in their own type internal static class ICommandAdapterHelpers { internal static EventHandler<object> CreateWrapperHandler(EventHandler handler) { // Check whether it is a round-tripping case i.e. the sender is of the type eventArgs, // If so we use it else we pass EventArgs.Empty return (object sender, object e) => { EventArgs eventArgs = e as EventArgs; handler(sender, (eventArgs == null ? System.EventArgs.Empty : eventArgs)); }; } internal static EventHandler CreateWrapperHandler(EventHandler<object> handler) { return (object sender, EventArgs e) => handler(sender, e); } internal static EventHandler<object> GetValueFromEquivalentKey( ConditionalWeakTable<EventHandler, EventHandler<object>> table, EventHandler key, ConditionalWeakTable<EventHandler, EventHandler<object>>.CreateValueCallback callback) { foreach (KeyValuePair<EventHandler, EventHandler<object>> item in table) { if (object.Equals(item.Key, key)) return item.Value; } EventHandler<object> value = callback(key); table.Add(key, value); return value; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Baseline.Dates; using Marten.Events.Projections; using Marten.Events.Projections.Async; using Marten.Services; using Marten.Testing.Harness; using Shouldly; using Xunit; namespace Marten.Testing.Events.Projections { public class project_events_from_multiple_streams_into_view: IntegrationContext { private static readonly Guid streamId = Guid.NewGuid(); private static readonly Guid streamId2 = Guid.NewGuid(); private QuestStarted started = new QuestStarted { Id = streamId, Name = "Find the Orb" }; private QuestStarted started2 = new QuestStarted { Id = streamId2, Name = "Find the Orb 2.0" }; private MonsterQuestsAdded monsterQuestsAdded = new MonsterQuestsAdded { QuestIds = new List<Guid> { streamId, streamId2 }, Name = "Dragon" }; private MonsterQuestsRemoved monsterQuestsRemoved = new MonsterQuestsRemoved { QuestIds = new List<Guid> { streamId, streamId2 }, Name = "Dragon" }; private QuestEnded ended = new QuestEnded { Id = streamId, Name = "Find the Orb" }; private MembersJoined joined = new MembersJoined { QuestId = streamId, Day = 2, Location = "Faldor's Farm", Members = new[] { "Garion", "Polgara", "Belgarath" } }; private MonsterSlayed slayed1 = new MonsterSlayed { QuestId = streamId, Name = "Troll" }; private MonsterSlayed slayed2 = new MonsterSlayed { QuestId = streamId, Name = "Dragon" }; private MonsterDestroyed destroyed = new MonsterDestroyed { QuestId = streamId, Name = "Troll" }; private MembersDeparted departed = new MembersDeparted { QuestId = streamId, Day = 5, Location = "Sendaria", Members = new[] { "Silk", "Barak" } }; private MembersJoined joined2 = new MembersJoined { QuestId = streamId, Day = 5, Location = "Sendaria", Members = new[] { "Silk", "Barak" } }; [Fact] public void from_configuration() { StoreOptions(_ => { _.AutoCreateSchemaObjects = AutoCreate.All; _.Events.TenancyStyle = Marten.Storage.TenancyStyle.Conjoined; _.Events.InlineProjections.AggregateStreamsWith<QuestParty>(); _.Events.ProjectView<PersistedView, Guid>() .ProjectEvent<ProjectionEvent<QuestStarted>>((view, @event) => { view.Events.Add(@event.Data); view.StreamIdsForEvents.Add(@event.StreamId); }) .ProjectEvent<MembersJoined>(e => e.QuestId, (view, @event) => view.Events.Add(@event)) .ProjectEvent<ProjectionEvent<MonsterSlayed>>(e => e.Data.QuestId, (view, @event) => { view.Events.Add(@event.Data); view.StreamIdsForEvents.Add(@event.StreamId); }) .DeleteEvent<QuestEnded>() .DeleteEvent<MembersDeparted>(e => e.QuestId) .DeleteEvent<MonsterDestroyed>((session, e) => session.Load<QuestParty>(e.QuestId).Id); }); theSession.Events.StartStream<QuestParty>(streamId, started, joined); theSession.SaveChanges(); theSession.Events.StartStream<Monster>(slayed1, slayed2); theSession.SaveChanges(); theSession.Events.Append(streamId, joined2); theSession.SaveChanges(); var document = theSession.Load<PersistedView>(streamId); document.Events.Count.ShouldBe(5); document.Events.ShouldHaveTheSameElementsAs(started, joined, slayed1, slayed2, joined2); theSession.Events.Append(streamId, ended); theSession.SaveChanges(); var nullDocument = theSession.Load<PersistedView>(streamId); SpecificationExtensions.ShouldBeNull(nullDocument); // Add document back to so we can delete it by selector theSession.Events.Append(streamId, started); theSession.SaveChanges(); var document2 = theSession.Load<PersistedView>(streamId); document2.Events.Count.ShouldBe(1); theSession.Events.Append(streamId, departed); theSession.SaveChanges(); var nullDocument2 = theSession.Load<PersistedView>(streamId); SpecificationExtensions.ShouldBeNull(nullDocument2); // Add document back to so we can delete it by other selector type theSession.Events.Append(streamId, started); theSession.SaveChanges(); var document3 = theSession.Load<PersistedView>(streamId); document3.Events.Count.ShouldBe(1); theSession.Events.Append(streamId, destroyed); theSession.SaveChanges(); var nullDocument3 = theSession.Load<PersistedView>(streamId); SpecificationExtensions.ShouldBeNull(nullDocument3); // Add document back to see if we can project stream ids from event handlers (Applies to other IEvent properties) theSession.Events.Append(streamId, started, joined); var monsterId = Guid.NewGuid(); theSession.Events.StartStream(monsterId, slayed1); theSession.SaveChanges(); var document4 = theSession.Load<PersistedView>(streamId); document4.StreamIdsForEvents.Count.ShouldBe(2); // Ids of the two streams document4.StreamIdsForEvents.Contains(streamId).ShouldBeTrue(); document4.StreamIdsForEvents.Contains(monsterId).ShouldBeTrue(); theSession.Events.Append(streamId, ended); theSession.SaveChanges(); var nullDocument4 = theSession.Load<PersistedView>(streamId); SpecificationExtensions.ShouldBeNull(nullDocument4); } [Fact] public async void from_configuration_async() { // SAMPLE: viewprojection-from-configuration StoreOptions(_ => { _.AutoCreateSchemaObjects = AutoCreate.All; _.Events.InlineProjections.AggregateStreamsWith<QuestParty>(); _.Events.ProjectView<PersistedView, Guid>() .ProjectEvent<ProjectionEvent<QuestStarted>>((view, @event) => { view.Events.Add(@event.Data); view.StreamIdsForEvents.Add(@event.StreamId); }) .ProjectEvent<MembersJoined>(e => e.QuestId, (view, @event) => { view.Events.Add(@event); }) .ProjectEvent<ProjectionEvent<MonsterSlayed>>(e => e.Data.QuestId, (view, @event) => { view.Events.Add(@event.Data); view.StreamIdsForEvents.Add(@event.StreamId); }) .DeleteEvent<QuestEnded>() .DeleteEvent<MembersDeparted>(e => e.QuestId) .DeleteEvent<MonsterDestroyed>((session, e) => session.Load<QuestParty>(e.QuestId).Id); }); // ENDSAMPLE theSession.Events.StartStream<QuestParty>(streamId, started, joined); await theSession.SaveChangesAsync(); theSession.Events.StartStream<Monster>(slayed1, slayed2); await theSession.SaveChangesAsync(); theSession.Events.Append(streamId, joined2); await theSession.SaveChangesAsync(); var document = theSession.Load<PersistedView>(streamId); document.Events.Count.ShouldBe(5); document.Events.ShouldHaveTheSameElementsAs(started, joined, slayed1, slayed2, joined2); theSession.Events.Append(streamId, ended); await theSession.SaveChangesAsync(); var nullDocument = theSession.Load<PersistedView>(streamId); SpecificationExtensions.ShouldBeNull(nullDocument); // Add document back to so we can delete it by selector theSession.Events.Append(streamId, started); await theSession.SaveChangesAsync(); var document2 = theSession.Load<PersistedView>(streamId); document2.Events.Count.ShouldBe(1); theSession.Events.Append(streamId, departed); await theSession.SaveChangesAsync(); var nullDocument2 = theSession.Load<PersistedView>(streamId); SpecificationExtensions.ShouldBeNull(nullDocument2); // Add document back to so we can delete it by other selector type theSession.Events.Append(streamId, started); await theSession.SaveChangesAsync(); var document3 = theSession.Load<PersistedView>(streamId); document3.Events.Count.ShouldBe(1); theSession.Events.Append(streamId, destroyed); await theSession.SaveChangesAsync(); var nullDocument3 = theSession.Load<PersistedView>(streamId); SpecificationExtensions.ShouldBeNull(nullDocument3); // Add document back to see if we can project stream ids from event handlers (Applies to other IEvent properties) theSession.Events.Append(streamId, started, joined); var monsterId = Guid.NewGuid(); theSession.Events.StartStream(monsterId, slayed1); await theSession.SaveChangesAsync(); var document4 = theSession.Load<PersistedView>(streamId); document4.StreamIdsForEvents.Count.ShouldBe(2); // Ids of the two streams document4.StreamIdsForEvents.Contains(streamId).ShouldBeTrue(); document4.StreamIdsForEvents.Contains(monsterId).ShouldBeTrue(); theSession.Events.Append(streamId, ended); await theSession.SaveChangesAsync(); var nullDocument4 = theSession.Load<PersistedView>(streamId); SpecificationExtensions.ShouldBeNull(nullDocument4); } [Fact] public void from_projection() { StoreOptions(_ => { _.AutoCreateSchemaObjects = AutoCreate.All; _.Events.InlineProjections.AggregateStreamsWith<QuestParty>(); _.Events.InlineProjections.Add(new PersistViewProjection()); }); theSession.Events.StartStream<QuestParty>(streamId, started, joined); theSession.SaveChanges(); theSession.Events.StartStream<Monster>(slayed1, slayed2); theSession.SaveChanges(); theSession.Events.Append(streamId, joined2); theSession.SaveChanges(); var document = theSession.Load<PersistedView>(streamId); document.Events.Count.ShouldBe(5); document.Events.ShouldHaveTheSameElementsAs(started, joined, slayed1, slayed2, joined2); theSession.Events.Append(streamId, ended); theSession.SaveChanges(); var nullDocument = theSession.Load<PersistedView>(streamId); SpecificationExtensions.ShouldBeNull(nullDocument); // Add document back to so we can delete it by selector theSession.Events.Append(streamId, started); theSession.SaveChanges(); var document2 = theSession.Load<PersistedView>(streamId); document2.Events.Count.ShouldBe(1); theSession.Events.Append(streamId, departed); theSession.SaveChanges(); var nullDocument2 = theSession.Load<PersistedView>(streamId); SpecificationExtensions.ShouldBeNull(nullDocument2); // Add document back to so we can delete it by other selector type theSession.Events.Append(streamId, started); theSession.SaveChanges(); var document3 = theSession.Load<PersistedView>(streamId); document3.Events.Count.ShouldBe(1); theSession.Events.Append(streamId, destroyed); theSession.SaveChanges(); var nullDocument3 = theSession.Load<PersistedView>(streamId); SpecificationExtensions.ShouldBeNull(nullDocument3); } [Fact] public async void from_projection_async() { StoreOptions(_ => { _.AutoCreateSchemaObjects = AutoCreate.All; _.Events.InlineProjections.AggregateStreamsWith<QuestParty>(); _.Events.InlineProjections.Add(new PersistViewProjection()); }); theSession.Events.StartStream<QuestParty>(streamId, started, joined); await theSession.SaveChangesAsync(); theSession.Events.StartStream<Monster>(slayed1, slayed2); await theSession.SaveChangesAsync(); theSession.Events.Append(streamId, joined2); await theSession.SaveChangesAsync(); var document = theSession.Load<PersistedView>(streamId); document.Events.Count.ShouldBe(5); document.Events.ShouldHaveTheSameElementsAs(started, joined, slayed1, slayed2, joined2); theSession.Events.Append(streamId, ended); await theSession.SaveChangesAsync(); var nullDocument = theSession.Load<PersistedView>(streamId); SpecificationExtensions.ShouldBeNull(nullDocument); // Add document back to so we can delete it by selector theSession.Events.Append(streamId, started); await theSession.SaveChangesAsync(); var document2 = theSession.Load<PersistedView>(streamId); document2.Events.Count.ShouldBe(1); theSession.Events.Append(streamId, departed); await theSession.SaveChangesAsync(); var nullDocument2 = theSession.Load<PersistedView>(streamId); SpecificationExtensions.ShouldBeNull(nullDocument2); // Add document back to so we can delete it by other selector type theSession.Events.Append(streamId, started); await theSession.SaveChangesAsync(); var document3 = theSession.Load<PersistedView>(streamId); document3.Events.Count.ShouldBe(1); theSession.Events.Append(streamId, destroyed); await theSession.SaveChangesAsync(); var nullDocument3 = theSession.Load<PersistedView>(streamId); SpecificationExtensions.ShouldBeNull(nullDocument3); } [Fact] public void using_collection_of_ids() { StoreOptions(_ => { _.AutoCreateSchemaObjects = AutoCreate.All; _.Events.InlineProjections.AggregateStreamsWith<QuestParty>(); _.Events.ProjectView<QuestView, Guid>() .ProjectEvent<QuestStarted>((view, @event) => view.Name = @event.Name) .ProjectEvent<MonsterQuestsAdded>(e => e.QuestIds, (view, @event) => view.Name = view.Name.Insert(0, $"{@event.Name}: ")) .DeleteEvent<MonsterQuestsRemoved>(e => e.QuestIds); }); theSession.Events.StartStream<QuestParty>(streamId, started); theSession.Events.StartStream<QuestParty>(streamId2, started2); theSession.SaveChanges(); theSession.Events.StartStream<Monster>(monsterQuestsAdded); theSession.SaveChanges(); var document = theSession.Load<QuestView>(streamId); SpecificationExtensions.ShouldStartWith(document.Name, monsterQuestsAdded.Name); var document2 = theSession.Load<QuestView>(streamId2); SpecificationExtensions.ShouldStartWith(document2.Name, monsterQuestsAdded.Name); theSession.Events.StartStream<Monster>(monsterQuestsRemoved); theSession.SaveChanges(); var nullDocument = theSession.Load<QuestView>(streamId); SpecificationExtensions.ShouldBeNull(nullDocument); var nullDocument2 = theSession.Load<QuestView>(streamId2); SpecificationExtensions.ShouldBeNull(nullDocument2); } [Fact] public async void using_collection_of_ids_async() { StoreOptions(_ => { _.AutoCreateSchemaObjects = AutoCreate.All; _.Events.InlineProjections.AggregateStreamsWith<QuestParty>(); _.Events.ProjectView<QuestView, Guid>() .ProjectEvent<QuestStarted>((view, @event) => view.Name = @event.Name) .ProjectEvent<MonsterQuestsAdded>(e => e.QuestIds, (view, @event) => view.Name = view.Name.Insert(0, $"{@event.Name}: ")) .DeleteEvent<MonsterQuestsRemoved>(e => e.QuestIds); }); theSession.Events.StartStream<QuestParty>(streamId, started); theSession.Events.StartStream<QuestParty>(streamId2, started2); await theSession.SaveChangesAsync(); theSession.Events.StartStream<Monster>(monsterQuestsAdded); await theSession.SaveChangesAsync(); var document = theSession.Load<QuestView>(streamId); SpecificationExtensions.ShouldStartWith(document.Name, monsterQuestsAdded.Name); var document2 = theSession.Load<QuestView>(streamId2); SpecificationExtensions.ShouldStartWith(document2.Name, monsterQuestsAdded.Name); theSession.Events.StartStream<Monster>(monsterQuestsRemoved); await theSession.SaveChangesAsync(); var nullDocument = theSession.Load<QuestView>(streamId); SpecificationExtensions.ShouldBeNull(nullDocument); var nullDocument2 = theSession.Load<QuestView>(streamId2); SpecificationExtensions.ShouldBeNull(nullDocument2); } [Fact] public async Task updateonly_event_should_not_create_new_document() { StoreOptions(_ => { _.AutoCreateSchemaObjects = AutoCreate.All; _.Events.TenancyStyle = Marten.Storage.TenancyStyle.Conjoined; _.Events.ProjectView<PersistedView, Guid>() .ProjectEvent<QuestStarted>((view, @event) => view.Events.Add(@event)) .ProjectEvent<MembersJoined>(e => e.QuestId, (view, @event) => view.Events.Add(@event)) .ProjectEvent<MonsterSlayed>(e => { return Guid.NewGuid(); }, (view, @event) => view.Events.Add(@event), onlyUpdate: true); }); theSession.Events.StartStream<QuestParty>(streamId, started); theSession.SaveChanges(); var document = await theSession.LoadAsync<PersistedView>(streamId); document.Events.Count.ShouldBe(1); theSession.Events.StartStream<Monster>(slayed1); theSession.SaveChanges(); var document2 = await theSession.LoadAsync<PersistedView>(streamId); document2.Events.Count.ShouldBe(1); theSession.Events.StartStream<QuestParty>(joined); theSession.SaveChanges(); var document3 = await theSession.LoadAsync<PersistedView>(streamId); document3.Events.Count.ShouldBe(2); } [Fact] public async Task updateonly_event_for_custom_view_projection_should_not_create_new_document() { StoreOptions(_ => { _.AutoCreateSchemaObjects = AutoCreate.All; _.Events.TenancyStyle = Marten.Storage.TenancyStyle.Conjoined; _.Events.InlineProjections.Add<NewsletterSubscriptionProjection>(); }); var subscriptionId = Guid.NewGuid(); var newsletterId = Guid.NewGuid(); var readerId = Guid.NewGuid(); var readerSubscribed = new ReaderSubscribed(subscriptionId, newsletterId, readerId, "John Doe"); theSession.Events.StartStream<NewsletterSubscription>(streamId, readerSubscribed); await theSession.SaveChangesAsync(); var subscription = await theSession.LoadAsync<NewsletterSubscription>(subscriptionId); subscription.ShouldNotBeNull(); var newsletterOpened = new NewsletterOpened(subscriptionId, DateTime.Now); theSession.Events.Append(subscriptionId, newsletterOpened); await theSession.SaveChangesAsync(); subscription = await theSession.LoadAsync<NewsletterSubscription>(subscriptionId); subscription.ShouldNotBeNull(); var readerUnsubscribed = new ReaderUnsubscribed(subscriptionId); theSession.Events.Append(subscriptionId, readerUnsubscribed); await theSession.SaveChangesAsync(); subscription = await theSession.LoadAsync<NewsletterSubscription>(subscriptionId); subscription.ShouldBeNull(); var newsletterOpenedAfterUnsubscribe = new NewsletterOpened(subscriptionId, DateTime.Now); theSession.Events.Append(subscriptionId, newsletterOpenedAfterUnsubscribe); await theSession.SaveChangesAsync(); subscription = await theSession.LoadAsync<NewsletterSubscription>(subscriptionId); subscription.ShouldBeNull(); } [Fact] public async Task default_id_event_should_not_create_new_document() { StoreOptions(_ => { _.AutoCreateSchemaObjects = AutoCreate.All; _.Events.TenancyStyle = Marten.Storage.TenancyStyle.Conjoined; _.Events.ProjectView<PersistedView, Guid>() .ProjectEvent<QuestStarted>(e => { return Guid.Empty; }, (view, @event) => view.Events.Add(@event)); }); theSession.Events.StartStream<QuestParty>(streamId, started); theSession.SaveChanges(); var document = await theSession.LoadAsync<PersistedView>(streamId); SpecificationExtensions.ShouldBeNull(document); var documentCount = await theSession.Query<PersistedView>().CountAsync(); documentCount.ShouldBe(0); } [Fact(Skip = "Failing test for #1302")] public async Task projectview_withdeleteevent_should_be_respected_during_projection_rebuild() { StoreOptions(_ => { _.AutoCreateSchemaObjects = AutoCreate.All; _.Events.InlineProjections.AggregateStreamsWith<Project>(); _.Events.ProjectView<Project, Guid>().DeleteEvent<ProjectClosed>(); }); var projectId = Guid.NewGuid(); theSession.Events.Append(projectId, new ProjectStarted { Id = projectId, Name = "Marten"}); await theSession.SaveChangesAsync(); theSession.Query<Project>().Count().ShouldBe(1); theSession.Events.Append(projectId, new ProjectClosed { Id = projectId }); await theSession.SaveChangesAsync(); theSession.Query<Project>().Count().ShouldBe(0); var settings = new DaemonSettings { LeadingEdgeBuffer = 0.Seconds() }; using (var daemon = theStore.BuildProjectionDaemon(new[] {typeof(Project)}, settings: settings)) { await daemon.RebuildAll(); } //fails as user is back in the database after rebuilding theSession.Query<Project>().Count().ShouldBe(0); } public project_events_from_multiple_streams_into_view(DefaultStoreFixture fixture) : base(fixture) { } } public class QuestView { public Guid Id { get; set; } public string Name { get; set; } } public class PersistedView { public Guid Id { get; set; } public List<object> Events { get; } = new List<object>(); public List<Guid> StreamIdsForEvents { get; set; } = new List<Guid>(); } // SAMPLE: viewprojection-from-class public class PersistViewProjection: ViewProjection<PersistedView, Guid> { public PersistViewProjection() { ProjectEvent<QuestStarted>(Persist); ProjectEvent<MembersJoined>(e => e.QuestId, Persist); ProjectEvent<MonsterSlayed>((session, e) => session.Load<QuestParty>(e.QuestId).Id, Persist); DeleteEvent<QuestEnded>(); DeleteEvent<MembersDeparted>(e => e.QuestId); DeleteEvent<MonsterDestroyed>((session, e) => session.Load<QuestParty>(e.QuestId).Id); } private void Persist<T>(PersistedView view, T @event) { view.Events.Add(@event); } } // ENDSAMPLE // SAMPLE: viewprojection-from-class-with-eventdata public class Lap { public Guid Id { get; set; } public DateTimeOffset? Start { get; set; } public DateTimeOffset? End { get; set; } } public class LapStarted { public Guid LapId { get; set; } } public class LapFinished { public Guid LapId { get; set; } } public class LapViewProjection: ViewProjection<Lap, Guid> { public LapViewProjection() { ProjectEvent<ProjectionEvent<LapStarted>>(e => e.Data.LapId, Persist); ProjectEvent<ProjectionEvent<LapFinished>>(e => e.Data.LapId, Persist); } private void Persist(Lap view, ProjectionEvent<LapStarted> eventData) { view.Start = eventData.Timestamp; } private void Persist(Lap view, ProjectionEvent<LapFinished> eventData) { view.End = eventData.Timestamp; } } // ENDSAMPLE // SAMPLE: viewprojection-with-update-only public class NewsletterSubscription { public Guid Id { get; set; } public Guid NewsletterId { get; set; } public Guid ReaderId { get; set; } public string FirstName { get; set; } public int OpensCount { get; set; } } public class ReaderSubscribed { public Guid SubscriptionId { get; } public Guid NewsletterId { get; } public Guid ReaderId { get; } public string FirstName { get; } public ReaderSubscribed(Guid subscriptionId, Guid newsletterId, Guid readerId, string firstName) { SubscriptionId = subscriptionId; NewsletterId = newsletterId; ReaderId = readerId; FirstName = firstName; } } public class NewsletterOpened { public Guid SubscriptionId { get; } public DateTime OpenedAt { get; } public NewsletterOpened(Guid subscriptionId, DateTime openedAt) { SubscriptionId = subscriptionId; OpenedAt = openedAt; } } public class ReaderUnsubscribed { public Guid SubscriptionId { get; } public ReaderUnsubscribed(Guid subscriptionId) { SubscriptionId = subscriptionId; } } public class NewsletterSubscriptionProjection : ViewProjection<NewsletterSubscription, Guid> { public NewsletterSubscriptionProjection() { ProjectEvent<ReaderSubscribed>(@event => @event.SubscriptionId, Persist); ProjectEvent<NewsletterOpened>(@event => @event.SubscriptionId, Persist, onlyUpdate: true); DeleteEvent<ReaderUnsubscribed>(@event => @event.SubscriptionId); } private void Persist(NewsletterSubscription view, ReaderSubscribed @event) { view.Id = @event.SubscriptionId; view.NewsletterId = @event.NewsletterId; view.ReaderId = @event.ReaderId; view.FirstName = @event.FirstName; view.OpensCount = 0; } private void Persist(NewsletterSubscription view, NewsletterOpened @event) { view.OpensCount++; } } // ENDSAMPLE public class Project { public Guid Id { get; set; } public string Name { get; set; } public void Apply(ProjectStarted e) { Id = e.Id; Name = e.Name; } public void Apply(ProjectClosed e) { } } public class ProjectStarted { public Guid Id { get; set; } public string Name { get; set; } } public class ProjectClosed { public Guid Id { get; set; } } }
using UnityEngine; using System; using System.Collections.Generic; /// <summary> /// Very simple example of how to use a TextList with a UIInput for chat. /// </summary> [RequireComponent(typeof(UIInput))] [AddComponentMenu("NGUI/Examples/Chat Input")] public class ChatInput : MonoBehaviour { public Dictionary<string, UITextList> textList = new Dictionary<string, UITextList>(); public bool fillWithDummyData = false; UIInput mInput; public static bool mIgnoreNextEnter = false; public string myName = "Me"; public NetworkController netController; public string currentGroup = "GlobalChat"; public UITextList publicTextList; public UITextList unionTextList; public UITextList managementTextList; UILabel myLabel; public GameObject button; public bool isChattingPrivately; public Transform textListPrefab; public Transform chatWindow; public Transform chatTabPrefab; public Transform chatTabParent; public GameObject unionChatTab; public GameObject managementChatTab; public GameObject allChatTab; public UISlicedSprite mySlicedSprite; public Dictionary<string, GameObject> labels = new Dictionary<string, GameObject>(); /// <summary> /// Add some dummy text to the text list. /// </summary> void Start () { netController=GameObject.Find("NetworkController").GetComponent<NetworkController>(); textList["Union"] = unionTextList; textList["Management"] = managementTextList; textList["GlobalChat"] = publicTextList; labels["Union"] = unionChatTab; labels["Management"] = managementChatTab; labels["GlobalChat"] = allChatTab; mInput = GetComponent<UIInput>(); myLabel = GetComponentInChildren<UILabel>(); mySlicedSprite = GetComponentInChildren<UISlicedSprite>(); if (fillWithDummyData && textList != null) { for (int i = 0; i < 51; ++i) { textList[currentGroup].Add(((i % 2 == 0) ? "[FFFFFF]" : "[AAAAAA]") + "This is an example paragraph for the text list, testing line " + i + "[-]"); } } } void JibeInit () { myName=netController.GetMyName(); } /// <summary> /// Pressing 'enter' should immediately give focus to the input field. /// </summary> void Update () { if (Input.GetKeyUp(KeyCode.Return)) { if (!mIgnoreNextEnter && !mInput.selected) { button.SendMessage("Toggle", false); mInput.selected = true; } } } /// <summary> /// Submit notification is sent by UIInput when 'enter' is pressed or iOS/Android keyboard finalizes input. /// </summary> void OnSelect (bool isSelected) { Debug.Log("Selecting chat window"); if(isSelected) { mySlicedSprite.spriteName="Chat window"; } else { mySlicedSprite.spriteName="TextEntry"; } } void OnSubmit () { if (textList != null) { // It's a good idea to strip out all symbols as we don't want user input to alter colors, add new lines, etc string text = NGUITools.StripSymbols(mInput.text); if (!string.IsNullOrEmpty(text)) { if(text=="/dance") { GameObject.Find("localPlayer").BroadcastMessage("StartDancing"); } else { text= myName+": " + text; textList[currentGroup].Add(text); if(!isChattingPrivately) { SendMessage(currentGroup, text); } else { SendPrivateChatMessage(text, Int32.Parse(currentGroup)); } } mInput.text = ""; } } //mIgnoreNextEnter = true; } public void AddMessage (string chatMessage, string sendingUser, string groupName) { //the sender should have already appended their name to the chat message textList[groupName].Add(chatMessage); if(!groupName.Equals(currentGroup)) { labels[groupName].SendMessage("BlinkMe", true); } button.SendMessage("BlinkMe", true); } void SendMessage(string groupName, string chatMessage) { netController.SendChatMessage(chatMessage); } public void AddPrivateChatMessage (string chatMessage, string sendingUser, int sendingUserID) { //THIS IS TRIGGERED WHEN YOU RECEIVE A PRIVATE CHAT Debug.Log("Received private chat: " + chatMessage + "from user:" + sendingUserID); if(!textList.ContainsKey(""+sendingUserID)) { AddNewChatTab(sendingUser, ""+sendingUserID); } textList[""+sendingUserID].Add(chatMessage); if(!currentGroup.Equals(""+sendingUserID)) { labels[""+sendingUserID].SendMessage("BlinkMe", true); } button.SendMessage("BlinkMe", true); } public void SendPrivateChatMessage (string chatMessage, int recipientID) { netController.SendPrivateChatMessage(chatMessage, recipientID); } public bool IsChatting() { return mInput.selected; } public void AddDebugMessage(string message) { textList[currentGroup].Add("Debug:" + message); } public void InitiatePrivateChat(string idToPrivateChatWith, string nameToPrivateChatWith) { Debug.Log("Opening private chat with user who has id : " + idToPrivateChatWith); if(!textList.ContainsKey(idToPrivateChatWith)) { AddNewChatTab(nameToPrivateChatWith, idToPrivateChatWith); } GameObject.FindWithTag("WindowLabel").GetComponent<UILabel>().text=nameToPrivateChatWith; isChattingPrivately=true; currentGroup=idToPrivateChatWith; DisableOtherGroups(); } private void AddNewChatTab(string name, string id) { Transform newTextList = GameObject.Instantiate(textListPrefab, new Vector3(3f, 78.16923f, 0f), Quaternion.identity) as Transform; newTextList.name=id; newTextList.parent=chatWindow; newTextList.transform.localScale = new Vector3(1f, 0.7868515f, 1f); textList[id] = newTextList.gameObject.GetComponent<UITextList>(); newTextList.GetComponent<ToggleMe>().startPosition = new Vector3(3f, 78.16923f, 0f); Transform newChatTab = GameObject.Instantiate(chatTabPrefab) as Transform; Vector3 position = new Vector3(0f,0f, -15f); Vector3 scale = new Vector3(.475f, .7f, 1f); newChatTab.parent = chatTabParent; newChatTab.localPosition=position; newChatTab.localScale=scale; newChatTab.GetComponentInChildren<UILabel>().text=name; newChatTab.GetComponentInChildren<ChangeGroup>().groupToJoin = id; newChatTab.GetComponentInChildren<ChangeGroup>().isPrivateGroup = true; newChatTab.GetComponentInChildren<ChangeGroup>().nameToDisplay = name; chatTabParent.GetComponentInChildren<UIGrid>().repositionNow=true; labels["" + id] = newChatTab.gameObject; } public void DisableOtherGroups() { foreach(string key in textList.Keys) { if(!key.Equals(currentGroup)) { textList[key].SendMessage("Toggle", true); if(labels[key]!=null) //double check that we didn't delete the tab. { labels[key].GetComponentInChildren<UISlicedSprite>().spriteName="LabelBackground"; } } else { textList[key].SendMessage("Toggle", false); } } } }
using System; using System.Globalization; using System.Reflection; using System.Runtime.CompilerServices; using Orleans.Core; using Orleans.Serialization; namespace Orleans.Runtime { [Serializable] internal class GrainId : UniqueIdentifier, IEquatable<GrainId>, IGrainIdentity { private static readonly object lockable = new object(); private const int INTERN_CACHE_INITIAL_SIZE = InternerConstants.SIZE_LARGE; private static readonly TimeSpan internCacheCleanupInterval = InternerConstants.DefaultCacheCleanupFreq; private static Interner<UniqueKey, GrainId> grainIdInternCache; public UniqueKey.Category Category { get { return Key.IdCategory; } } public bool IsSystemTarget { get { return Key.IsSystemTargetKey; } } public bool IsGrain { get { return Category == UniqueKey.Category.Grain || Category == UniqueKey.Category.KeyExtGrain; } } public bool IsClient { get { return Category == UniqueKey.Category.Client || Category == UniqueKey.Category.GeoClient; } } private GrainId(UniqueKey key) : base(key) { } public static GrainId NewId() { return FindOrCreateGrainId(UniqueKey.NewKey(Guid.NewGuid(), UniqueKey.Category.Grain)); } public static GrainId NewClientId(string clusterId = null) { return NewClientId(Guid.NewGuid(), clusterId); } internal static GrainId NewClientId(Guid id, string clusterId = null) { return FindOrCreateGrainId(UniqueKey.NewKey(id, clusterId == null ? UniqueKey.Category.Client : UniqueKey.Category.GeoClient, 0, clusterId)); } internal static GrainId GetGrainId(UniqueKey key) { return FindOrCreateGrainId(key); } internal static GrainId GetSystemGrainId(Guid guid) { return FindOrCreateGrainId(UniqueKey.NewKey(guid, UniqueKey.Category.SystemGrain)); } // For testing only. internal static GrainId GetGrainIdForTesting(Guid guid) { return FindOrCreateGrainId(UniqueKey.NewKey(guid, UniqueKey.Category.None)); } internal static GrainId NewSystemTargetGrainIdByTypeCode(int typeData) { return FindOrCreateGrainId(UniqueKey.NewSystemTargetKey(Guid.NewGuid(), typeData)); } internal static GrainId GetSystemTargetGrainId(short systemGrainId) { return FindOrCreateGrainId(UniqueKey.NewSystemTargetKey(systemGrainId)); } internal static GrainId GetGrainId(long typeCode, long primaryKey, string keyExt=null) { return FindOrCreateGrainId(UniqueKey.NewKey(primaryKey, keyExt == null ? UniqueKey.Category.Grain : UniqueKey.Category.KeyExtGrain, typeCode, keyExt)); } internal static GrainId GetGrainId(long typeCode, Guid primaryKey, string keyExt=null) { return FindOrCreateGrainId(UniqueKey.NewKey(primaryKey, keyExt == null ? UniqueKey.Category.Grain : UniqueKey.Category.KeyExtGrain, typeCode, keyExt)); } internal static GrainId GetGrainId(long typeCode, string primaryKey) { return FindOrCreateGrainId(UniqueKey.NewKey(0L, UniqueKey.Category.KeyExtGrain, typeCode, primaryKey)); } internal static GrainId GetGrainServiceGrainId(short id, int typeData) { return FindOrCreateGrainId(UniqueKey.NewGrainServiceKey(id, typeData)); } public Guid PrimaryKey { get { return GetPrimaryKey(); } } public long PrimaryKeyLong { get { return GetPrimaryKeyLong(); } } public string PrimaryKeyString { get { return GetPrimaryKeyString(); } } public string IdentityString { get { return ToDetailedString(); } } public bool IsLongKey { get { return Key.IsLongKey; } } public long GetPrimaryKeyLong(out string keyExt) { return Key.PrimaryKeyToLong(out keyExt); } internal long GetPrimaryKeyLong() { return Key.PrimaryKeyToLong(); } public Guid GetPrimaryKey(out string keyExt) { return Key.PrimaryKeyToGuid(out keyExt); } internal Guid GetPrimaryKey() { return Key.PrimaryKeyToGuid(); } internal string GetPrimaryKeyString() { string key; var tmp = GetPrimaryKey(out key); return key; } public int TypeCode => Key.BaseTypeCode; private static GrainId FindOrCreateGrainId(UniqueKey key) { // Note: This is done here to avoid a wierd cyclic dependency / static initialization ordering problem involving the GrainId, Constants & Interner classes if (grainIdInternCache != null) return grainIdInternCache.FindOrCreate(key, k => new GrainId(k)); lock (lockable) { if (grainIdInternCache == null) { grainIdInternCache = new Interner<UniqueKey, GrainId>(INTERN_CACHE_INITIAL_SIZE, internCacheCleanupInterval); } } return grainIdInternCache.FindOrCreate(key, k => new GrainId(k)); } #region IEquatable<GrainId> Members public bool Equals(GrainId other) { return other != null && Key.Equals(other.Key); } #endregion public override bool Equals(UniqueIdentifier obj) { var o = obj as GrainId; return o != null && Key.Equals(o.Key); } public override bool Equals(object obj) { var o = obj as GrainId; return o != null && Key.Equals(o.Key); } // Keep compiler happy -- it does not like classes to have Equals(...) without GetHashCode() methods public override int GetHashCode() { return Key.GetHashCode(); } /// <summary> /// Get a uniformly distributed hash code value for this grain, based on Jenkins Hash function. /// NOTE: Hash code value may be positive or NEGATIVE. /// </summary> /// <returns>Hash code for this GrainId</returns> public uint GetUniformHashCode() { return Key.GetUniformHashCode(); } public override string ToString() { return ToStringImpl(false); } // same as ToString, just full primary key and type code internal string ToDetailedString() { return ToStringImpl(true); } // same as ToString, just full primary key and type code private string ToStringImpl(bool detailed) { string name = string.Empty; if (Constants.TryGetSystemGrainName(this, out name)) { return name; } var keyString = Key.ToString(); // this should grab the least-significant half of n1, suffixing it with the key extension. string idString = keyString; if (!detailed) { if (keyString.Length >= 48) idString = keyString.Substring(24, 8) + keyString.Substring(48); else idString = keyString.Substring(24, 8); } string fullString = null; switch (Category) { case UniqueKey.Category.Grain: case UniqueKey.Category.KeyExtGrain: var typeString = TypeCode.ToString("X"); if (!detailed) typeString = typeString.Tail(8); fullString = String.Format("*grn/{0}/{1}", typeString, idString); break; case UniqueKey.Category.Client: fullString = "*cli/" + idString; break; case UniqueKey.Category.GeoClient: fullString = string.Format("*gcl/{0}/{1}", Key.KeyExt, idString); break; case UniqueKey.Category.SystemTarget: string explicitName = Constants.SystemTargetName(this); if (TypeCode != 0) { var typeStr = TypeCode.ToString("X"); return String.Format("{0}/{1}/{2}", explicitName, typeStr, idString); } fullString = explicitName; break; default: fullString = "???/" + idString; break; } return detailed ? String.Format("{0}-0x{1, 8:X8}", fullString, GetUniformHashCode()) : fullString; } internal string ToFullString() { string kx; string pks = Key.IsLongKey ? GetPrimaryKeyLong(out kx).ToString(CultureInfo.InvariantCulture) : GetPrimaryKey(out kx).ToString(); string pksHex = Key.IsLongKey ? GetPrimaryKeyLong(out kx).ToString("X") : GetPrimaryKey(out kx).ToString("X"); return String.Format( "[GrainId: {0}, IdCategory: {1}, BaseTypeCode: {2} (x{3}), PrimaryKey: {4} (x{5}), UniformHashCode: {6} (0x{7, 8:X8}){8}]", ToDetailedString(), // 0 Category, // 1 TypeCode, // 2 TypeCode.ToString("X"), // 3 pks, // 4 pksHex, // 5 GetUniformHashCode(), // 6 GetUniformHashCode(), // 7 Key.HasKeyExt ? String.Format(", KeyExtension: {0}", kx) : ""); // 8 } internal string ToStringWithHashCode() { return String.Format("{0}-0x{1, 8:X8}", this.ToString(), this.GetUniformHashCode()); } /// <summary> /// Return this GrainId in a standard string form, suitable for later use with the <c>FromParsableString</c> method. /// </summary> /// <returns>GrainId in a standard string format.</returns> internal string ToParsableString() { // NOTE: This function must be the "inverse" of FromParsableString, and data must round-trip reliably. return Key.ToHexString(); } /// <summary> /// Create a new GrainId object by parsing string in a standard form returned from <c>ToParsableString</c> method. /// </summary> /// <param name="grainId">String containing the GrainId info to be parsed.</param> /// <returns>New GrainId object created from the input data.</returns> internal static GrainId FromParsableString(string grainId) { // NOTE: This function must be the "inverse" of ToParsableString, and data must round-trip reliably. var key = UniqueKey.Parse(grainId); return FindOrCreateGrainId(key); } internal byte[] ToByteArray() { var writer = new BinaryTokenStreamWriter(); writer.Write(this); var result = writer.ToByteArray(); writer.ReleaseBuffers(); return result; } internal static GrainId FromByteArray(byte[] byteArray) { var reader = new BinaryTokenStreamReader(byteArray); return reader.ReadGrainId(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Text; namespace System.Net.Tests { // Utilities for generating URL prefixes for HttpListener public class HttpListenerFactory : IDisposable { const int StartPort = 1025; const int MaxStartAttempts = IPEndPoint.MaxPort - StartPort + 1; private static readonly object s_nextPortLock = new object(); private static int s_nextPort = StartPort; private readonly HttpListener _processPrefixListener; private readonly Exception _processPrefixException; private readonly string _processPrefix; private readonly string _hostname; private readonly string _path; private readonly int _port; internal HttpListenerFactory(string hostname = "localhost", string path = null) { // Find a URL prefix that is not in use on this machine *and* uses a port that's not in use. // Once we find this prefix, keep a listener on it for the duration of the process, so other processes // can't steal it. _hostname = hostname; _path = path ?? Guid.NewGuid().ToString("N"); string pathComponent = string.IsNullOrEmpty(_path) ? _path : $"{_path}/"; for (int attempt = 0; attempt < MaxStartAttempts; attempt++) { int port = GetNextPort(); string prefix = $"http://{hostname}:{port}/{pathComponent}"; var listener = new HttpListener(); try { listener.Prefixes.Add(prefix); listener.Start(); _processPrefixListener = listener; _processPrefix = prefix; _port = port; _processPrefixException = null; Socket socket = GetConnectedSocket(); socket.Close(); break; } catch (Exception e) { // can't use this prefix listener.Close(); // Remember the exception for later _processPrefixException = e; if (e is HttpListenerException listenerException) { // If we can't access the host (e.g. if it is '+' or '*' and the current user is the administrator) // then throw. const int ERROR_ACCESS_DENIED = 5; if (listenerException.ErrorCode == ERROR_ACCESS_DENIED && (hostname == "*" || hostname == "+")) { throw new InvalidOperationException($"Access denied for host {hostname}"); } } else if (!(e is SocketException)) { // If this is not an HttpListenerException or SocketException, something very wrong has happened, and there's no point // in trying again. break; } } } // At this point, either we've reserved a prefix, or we've tried everything and failed. If we failed, // we've saved the exception for later. We'll defer actually *throwing* the exception until a test // asks for the prefix, because dealing with a type initialization exception is not nice in xunit. } public int Port { get { if (_port == 0) { throw new Exception("Could not reserve a port for HttpListener", _processPrefixException); } return _port; } } public string ListeningUrl { get { if (_processPrefix == null) { throw new Exception("Could not reserve a port for HttpListener", _processPrefixException); } return _processPrefix; } } public string Hostname => _hostname; public string Path => _path; private static bool? s_supportsWildcards; public static bool SupportsWildcards { get { if (!s_supportsWildcards.HasValue) { try { using (new HttpListenerFactory("*")) { s_supportsWildcards = true; } } catch (InvalidOperationException) { s_supportsWildcards = false; } } return s_supportsWildcards.Value; } } public HttpListener GetListener() => _processPrefixListener ?? throw new Exception("Could not reserve a port for HttpListener", _processPrefixException); public void Dispose() => _processPrefixListener?.Close(); public Socket GetConnectedSocket() { if (_processPrefixException != null) { throw new Exception("Could not create HttpListener", _processPrefixException); } string hostname = _hostname == "*" || _hostname == "+" ? "localhost" : _hostname; // Some platforms or distributions require IPv6 sockets if the OS supports IPv6. Others (e.g. Ubuntu) don't. try { AddressFamily addressFamily = Socket.OSSupportsIPv6 ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork; Socket socket = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp); socket.Connect(hostname, Port); return socket; } catch { Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Connect(hostname, Port); return socket; } } public byte[] GetContent(string httpVersion, string requestType, string query, string text, IEnumerable<string> headers, bool headerOnly) { headers = headers ?? Enumerable.Empty<string>(); Uri listeningUri = new Uri(ListeningUrl); string rawUrl = listeningUri.PathAndQuery; if (query != null) { rawUrl += query; } string content = $"{requestType} {rawUrl} HTTP/{httpVersion}\r\n"; if (!headers.Any(header => header.ToLower().StartsWith("host:"))) { content += $"Host: { listeningUri.Host}\r\n"; } if (text != null && !headers.Any(header => header.ToLower().StartsWith("content-length:"))) { content += $"Content-Length: {text.Length}\r\n"; } foreach (string header in headers) { content += header + "\r\n"; } content += "\r\n"; if (!headerOnly && text != null) { content += text; } return Encoding.UTF8.GetBytes(content); } public byte[] GetContent(string requestType, string text, bool headerOnly) { return GetContent("1.1", requestType, query: null, text: text, headers: null, headerOnly: headerOnly); } private static int GetNextPort() { lock (s_nextPortLock) { int port = s_nextPort++; if (s_nextPort > IPEndPoint.MaxPort) { s_nextPort = StartPort; } return port; } } } public static class RequestTypes { public const string POST = "POST"; } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using Google.GData.Client; namespace Google.GData.Tools { /// <summary> /// This is a sample implementation for a login dialog. It returns you the authToken gained /// from the Google Client Login Service /// </summary> public class GoogleClientLogin : System.Windows.Forms.Form { private GDataCredentials credentials; private System.Windows.Forms.TextBox Password; private System.Windows.Forms.CheckBox RememberToken; private System.Windows.Forms.Button Login; private System.Windows.Forms.Button Cancel; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox Username; private Service service; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; /// <summary> /// allows you to construct the dialog with a given service /// </summary> /// <param name="serviceToUse">the service object to use</param> public GoogleClientLogin() { // // Required for Windows Form Designer support // InitializeComponent(); } /// <summary> /// allows you to construct the dialog with a given service /// and prefill the username to show /// </summary> /// <param name="serviceToUse">the service object to use</param> /// <param name="username">the username</param> public GoogleClientLogin(Service serviceToUse, string username) { // // Required for Windows Form Designer support // InitializeComponent(); this.service = serviceToUse; this.Username.Text = username; } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Login = new System.Windows.Forms.Button(); this.Cancel = new System.Windows.Forms.Button(); this.Username = new System.Windows.Forms.TextBox(); this.Password = new System.Windows.Forms.TextBox(); this.RememberToken = new System.Windows.Forms.CheckBox(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.SuspendLayout(); // // Login // this.Login.Location = new System.Drawing.Point(240, 104); this.Login.Name = "Login"; this.Login.Size = new System.Drawing.Size(80, 32); this.Login.TabIndex = 4; this.Login.Text = "&Login"; this.Login.Click += new System.EventHandler(this.Login_Click); // // Cancel // this.Cancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.Cancel.Location = new System.Drawing.Point(144, 104); this.Cancel.Name = "Cancel"; this.Cancel.Size = new System.Drawing.Size(80, 32); this.Cancel.TabIndex = 3; this.Cancel.Text = "&Cancel"; this.Cancel.Click += new System.EventHandler(this.Cancel_Click); // // Username // this.Username.Location = new System.Drawing.Point(112, 16); this.Username.Name = "Username"; this.Username.Size = new System.Drawing.Size(208, 22); this.Username.TabIndex = 1; // // Password // this.Password.Location = new System.Drawing.Point(112, 48); this.Password.Name = "Password"; this.Password.PasswordChar = '*'; this.Password.Size = new System.Drawing.Size(208, 22); this.Password.TabIndex = 2; // // RememberToken // this.RememberToken.Location = new System.Drawing.Point(16, 80); this.RememberToken.Name = "RememberToken"; this.RememberToken.Size = new System.Drawing.Size(160, 24); this.RememberToken.TabIndex = 4; this.RememberToken.Text = "Remember the Token"; this.RememberToken.Visible = false; // // label1 // this.label1.Location = new System.Drawing.Point(16, 16); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(88, 32); this.label1.TabIndex = 5; this.label1.Text = "Username:"; // // label2 // this.label2.Location = new System.Drawing.Point(16, 48); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(88, 32); this.label2.TabIndex = 6; this.label2.Text = "Password: "; // // GoogleClientLogin // this.AcceptButton = this.Login; this.AutoScaleBaseSize = new System.Drawing.Size(6, 15); this.CancelButton = this.Cancel; this.ClientSize = new System.Drawing.Size(344, 152); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.RememberToken); this.Controls.Add(this.Password); this.Controls.Add(this.Username); this.Controls.Add(this.Cancel); this.Controls.Add(this.Login); this.Name = "GoogleClientLogin"; this.Text = "GoogleClientLogin"; this.ResumeLayout(false); this.PerformLayout(); } #endregion /// <summary> /// returns the authentication token /// </summary> public GDataCredentials Credentials { get { return this.credentials; } } /// <summary> /// returns the user name /// </summary> public string User { get { return this.Username.Text; } } private void Cancel_Click(object sender, System.EventArgs e) { this.credentials = null; this.Close(); } private void Login_Click(object sender, System.EventArgs e) { try { this.credentials = new GDataCredentials(this.Username.Text, this.Password.Text); this.DialogResult = DialogResult.OK; this.Close(); } catch (AuthenticationException a) { MessageBox.Show(a.Message); } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.Azure.Management.DataFactories.Common.Models; using Microsoft.Azure.Management.DataFactories.Models; namespace Microsoft.Azure.Management.DataFactories.Core { /// <summary> /// Operations for managing data factory gateways. /// </summary> public partial interface IGatewayOperations { /// <summary> /// Create or update a data factory gateway. /// </summary> /// <param name='resourceGroupName'> /// The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// A unique data factory instance name. /// </param> /// <param name='parameters'> /// The parameters required to create or update a data factory gateway. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The create or update data factory gateway operation response. /// </returns> Task<GatewayCreateOrUpdateResponse> BeginCreateOrUpdateAsync(string resourceGroupName, string dataFactoryName, GatewayCreateOrUpdateParameters parameters, CancellationToken cancellationToken); /// <summary> /// Delete a data factory gateway. /// </summary> /// <param name='resourceGroupName'> /// The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// A unique data factory instance name. /// </param> /// <param name='gatewayName'> /// Name of the gateway to delete. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> BeginDeleteAsync(string resourceGroupName, string dataFactoryName, string gatewayName, CancellationToken cancellationToken); /// <summary> /// Create or update a data factory gateway. /// </summary> /// <param name='resourceGroupName'> /// The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// A unique data factory instance name. /// </param> /// <param name='parameters'> /// The parameters required to create or update a data factory gateway. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The create or update data factory gateway operation response. /// </returns> Task<GatewayCreateOrUpdateResponse> CreateOrUpdateAsync(string resourceGroupName, string dataFactoryName, GatewayCreateOrUpdateParameters parameters, CancellationToken cancellationToken); /// <summary> /// Delete a data factory gateway. /// </summary> /// <param name='resourceGroupName'> /// The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// A unique data factory instance name. /// </param> /// <param name='gatewayName'> /// Name of the gateway to delete. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string dataFactoryName, string gatewayName, CancellationToken cancellationToken); /// <summary> /// Gets a data factory gateway. /// </summary> /// <param name='resourceGroupName'> /// The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// A unique data factory instance name. /// </param> /// <param name='gatewayName'> /// Name of the gateway to get. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The Get data factory gateway operation response. /// </returns> Task<GatewayGetResponse> GetAsync(string resourceGroupName, string dataFactoryName, string gatewayName, CancellationToken cancellationToken); /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operationStatusLink'> /// Location value returned by the Begin operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The create or update data factory gateway operation response. /// </returns> Task<GatewayCreateOrUpdateResponse> GetCreateOrUpdateStatusAsync(string operationStatusLink, CancellationToken cancellationToken); /// <summary> /// List all gateways under a data factory. /// </summary> /// <param name='resourceGroupName'> /// The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// A unique data factory instance name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List data factory gateways operation response. /// </returns> Task<GatewayListResponse> ListAsync(string resourceGroupName, string dataFactoryName, CancellationToken cancellationToken); /// <summary> /// List gateway authentication keys. /// </summary> /// <param name='resourceGroupName'> /// The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// A unique data factory instance name. /// </param> /// <param name='gatewayName'> /// The name of the gateway to list auth keys. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The list gateway auth keys operation response. /// </returns> Task<GatewayListAuthKeysResponse> ListAuthKeysAsync(string resourceGroupName, string dataFactoryName, string gatewayName, CancellationToken cancellationToken); /// <summary> /// Regenerate gateway authentication key. /// </summary> /// <param name='resourceGroupName'> /// The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// A unique data factory instance name. /// </param> /// <param name='gatewayName'> /// The name of the gateway to regenerate key. /// </param> /// <param name='parameters'> /// The name of the authentication key to be regenerated. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The regenerate gateway auth key operation response. /// </returns> Task<GatewayRegenerateAuthKeyResponse> RegenerateAuthKeyAsync(string resourceGroupName, string dataFactoryName, string gatewayName, GatewayRegenerateAuthKeyParameters parameters, CancellationToken cancellationToken); /// <summary> /// Regenerate gateway key. This API has been deprecated and /// RegenerateAuthKey should be used instead. /// </summary> /// <param name='resourceGroupName'> /// The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// A unique data factory instance name. /// </param> /// <param name='gatewayName'> /// The name of the gateway to regenerate key. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The regenerate gateway key operation response. /// </returns> Task<GatewayRegenerateKeyResponse> RegenerateKeyAsync(string resourceGroupName, string dataFactoryName, string gatewayName, CancellationToken cancellationToken); /// <summary> /// Retrieve gateway connection information. /// </summary> /// <param name='resourceGroupName'> /// The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// A unique data factory instance name. /// </param> /// <param name='gatewayName'> /// Name of the gateway. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The retrieve gateway connection information operation response. /// </returns> Task<GatewayConnectionInfoRetrieveResponse> RetrieveConnectionInfoAsync(string resourceGroupName, string dataFactoryName, string gatewayName, CancellationToken cancellationToken); /// <summary> /// Update a data factory gateway. /// </summary> /// <param name='resourceGroupName'> /// The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// A unique data factory instance name. /// </param> /// <param name='parameters'> /// The parameters required to create or update a data factory gateway. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The create or update data factory gateway operation response. /// </returns> Task<GatewayCreateOrUpdateResponse> UpdateAsync(string resourceGroupName, string dataFactoryName, GatewayCreateOrUpdateParameters parameters, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Xml.Xsl.XsltOld { using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using System.Xml.XPath; using System.Xml.Xsl.XsltOld.Debugger; using MS.Internal.Xml.XPath; internal sealed class Processor : IXsltProcessor { // // Static constants // private const int StackIncrement = 10; // // Execution result // internal enum ExecResult { Continue, // Continues next iteration immediately Interrupt, // Returns to caller, was processed enough Done // Execution finished } internal enum OutputResult { Continue, Interrupt, Overflow, Error, Ignore } private ExecResult _execResult; // // Compiled stylesheet // private Stylesheet _stylesheet; // Root of import tree of template managers private RootAction _rootAction; private Key[] _keyList; private List<TheQuery> _queryStore; // // Document Being transformed // private XPathNavigator _document; // // Execution action stack // private HWStack _actionStack; private HWStack _debuggerStack; // // Register for returning value from calling nested action // private StringBuilder _sharedStringBuilder; // // Output related member variables // private int _ignoreLevel; private StateMachine _xsm; private RecordBuilder _builder; private XsltOutput _output; private XmlNameTable _nameTable = new NameTable(); private XmlResolver _resolver; #pragma warning disable 618 private XsltArgumentList _args; #pragma warning restore 618 private Hashtable _scriptExtensions; private ArrayList _numberList; // // Template lookup action // private TemplateLookupAction _templateLookup = new TemplateLookupAction(); private IXsltDebugger _debugger; private Query[] _queryList; private ArrayList _sortArray; private Hashtable _documentCache; // NOTE: ValueOf() can call Matches() through XsltCompileContext.PreserveWhitespace(), // that's why we use two different contexts here, valueOfContext and matchesContext private XsltCompileContext _valueOfContext; private XsltCompileContext _matchesContext; internal XPathNavigator Current { get { ActionFrame frame = (ActionFrame)_actionStack.Peek(); return frame != null ? frame.Node : null; } } internal ExecResult ExecutionResult { get { return _execResult; } set { Debug.Assert(_execResult == ExecResult.Continue); _execResult = value; } } internal Stylesheet Stylesheet { get { return _stylesheet; } } internal XmlResolver Resolver { get { Debug.Assert(_resolver != null, "Constructor should create it if null passed"); return _resolver; } } internal ArrayList SortArray { get { Debug.Assert(_sortArray != null, "InitSortArray() wasn't called"); return _sortArray; } } internal Key[] KeyList { get { return _keyList; } } internal XPathNavigator GetNavigator(Uri ruri) { XPathNavigator result = null; if (_documentCache != null) { result = _documentCache[ruri] as XPathNavigator; if (result != null) { return result.Clone(); } } else { _documentCache = new Hashtable(); } object input = _resolver.GetEntity(ruri, null, null); if (input is Stream) { XmlTextReaderImpl tr = new XmlTextReaderImpl(ruri.ToString(), (Stream)input); { tr.XmlResolver = _resolver; } // reader is closed by Compiler.LoadDocument() result = ((IXPathNavigable)Compiler.LoadDocument(tr)).CreateNavigator(); } else if (input is XPathNavigator) { result = (XPathNavigator)input; } else { throw XsltException.Create(SR.Xslt_CantResolve, ruri.ToString()); } _documentCache[ruri] = result.Clone(); return result; } internal void AddSort(Sort sortinfo) { Debug.Assert(_sortArray != null, "InitSortArray() wasn't called"); _sortArray.Add(sortinfo); } internal void InitSortArray() { if (_sortArray == null) { _sortArray = new ArrayList(); } else { _sortArray.Clear(); } } internal object GetGlobalParameter(XmlQualifiedName qname) { object parameter = _args.GetParam(qname.Name, qname.Namespace); if (parameter == null) { return null; } if ( parameter is XPathNodeIterator || parameter is XPathNavigator || parameter is bool || parameter is double || parameter is string ) { // doing nothing } else if ( parameter is short || parameter is ushort || parameter is int || parameter is uint || parameter is long || parameter is ulong || parameter is float || parameter is decimal ) { parameter = XmlConvert.ToXPathDouble(parameter); } else { parameter = parameter.ToString(); } return parameter; } internal object GetExtensionObject(string nsUri) { return _args.GetExtensionObject(nsUri); } internal object GetScriptObject(string nsUri) { return _scriptExtensions[nsUri]; } internal RootAction RootAction { get { return _rootAction; } } internal XPathNavigator Document { get { return _document; } } #if DEBUG private bool _stringBuilderLocked = false; #endif internal StringBuilder GetSharedStringBuilder() { #if DEBUG Debug.Assert(!_stringBuilderLocked); #endif if (_sharedStringBuilder == null) { _sharedStringBuilder = new StringBuilder(); } else { _sharedStringBuilder.Length = 0; } #if DEBUG _stringBuilderLocked = true; #endif return _sharedStringBuilder; } internal void ReleaseSharedStringBuilder() { // don't clean stringBuilderLocked here. ToString() will happen after this call #if DEBUG _stringBuilderLocked = false; #endif } internal ArrayList NumberList { get { if (_numberList == null) { _numberList = new ArrayList(); } return _numberList; } } internal IXsltDebugger Debugger { get { return _debugger; } } internal HWStack ActionStack { get { return _actionStack; } } internal XsltOutput Output { get { return _output; } } // // Construction // public Processor( XPathNavigator doc, XsltArgumentList args, XmlResolver resolver, Stylesheet stylesheet, List<TheQuery> queryStore, RootAction rootAction, IXsltDebugger debugger ) { _stylesheet = stylesheet; _queryStore = queryStore; _rootAction = rootAction; _queryList = new Query[queryStore.Count]; { for (int i = 0; i < queryStore.Count; i++) { _queryList[i] = Query.Clone(queryStore[i].CompiledQuery.QueryTree); } } _xsm = new StateMachine(); _document = doc; _builder = null; _actionStack = new HWStack(StackIncrement); _output = _rootAction.Output; _resolver = resolver ?? XmlNullResolver.Singleton; _args = args ?? new XsltArgumentList(); _debugger = debugger; if (_debugger != null) { _debuggerStack = new HWStack(StackIncrement, /*limit:*/1000); _templateLookup = new TemplateLookupActionDbg(); } // Clone the compile-time KeyList if (_rootAction.KeyList != null) { _keyList = new Key[_rootAction.KeyList.Count]; for (int i = 0; i < _keyList.Length; i++) { _keyList[i] = _rootAction.KeyList[i].Clone(); } } _scriptExtensions = new Hashtable(_stylesheet.ScriptObjectTypes.Count); { foreach (DictionaryEntry entry in _stylesheet.ScriptObjectTypes) { string namespaceUri = (string)entry.Key; if (GetExtensionObject(namespaceUri) != null) { throw XsltException.Create(SR.Xslt_ScriptDub, namespaceUri); } _scriptExtensions.Add(namespaceUri, Activator.CreateInstance((Type)entry.Value, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, null, null)); } } this.PushActionFrame(_rootAction, /*nodeSet:*/null); } public ReaderOutput StartReader() { ReaderOutput output = new ReaderOutput(this); _builder = new RecordBuilder(output, _nameTable); return output; } public void Execute(Stream stream) { RecordOutput recOutput = null; switch (_output.Method) { case XsltOutput.OutputMethod.Text: recOutput = new TextOnlyOutput(this, stream); break; case XsltOutput.OutputMethod.Xml: case XsltOutput.OutputMethod.Html: case XsltOutput.OutputMethod.Other: case XsltOutput.OutputMethod.Unknown: recOutput = new TextOutput(this, stream); break; } _builder = new RecordBuilder(recOutput, _nameTable); Execute(); } public void Execute(TextWriter writer) { RecordOutput recOutput = null; switch (_output.Method) { case XsltOutput.OutputMethod.Text: recOutput = new TextOnlyOutput(this, writer); break; case XsltOutput.OutputMethod.Xml: case XsltOutput.OutputMethod.Html: case XsltOutput.OutputMethod.Other: case XsltOutput.OutputMethod.Unknown: recOutput = new TextOutput(this, writer); break; } _builder = new RecordBuilder(recOutput, _nameTable); Execute(); } public void Execute(XmlWriter writer) { _builder = new RecordBuilder(new WriterOutput(this, writer), _nameTable); Execute(); } // // Execution part of processor // internal void Execute() { Debug.Assert(_actionStack != null); while (_execResult == ExecResult.Continue) { ActionFrame frame = (ActionFrame)_actionStack.Peek(); if (frame == null) { Debug.Assert(_builder != null); _builder.TheEnd(); ExecutionResult = ExecResult.Done; break; } // Execute the action which was on the top of the stack if (frame.Execute(this)) { _actionStack.Pop(); } } if (_execResult == ExecResult.Interrupt) { _execResult = ExecResult.Continue; } } // // Action frame support // internal ActionFrame PushNewFrame() { ActionFrame prent = (ActionFrame)_actionStack.Peek(); ActionFrame frame = (ActionFrame)_actionStack.Push(); if (frame == null) { frame = new ActionFrame(); _actionStack.AddToTop(frame); } Debug.Assert(frame != null); if (prent != null) { frame.Inherit(prent); } return frame; } internal void PushActionFrame(Action action, XPathNodeIterator nodeSet) { ActionFrame frame = PushNewFrame(); frame.Init(action, nodeSet); } internal void PushActionFrame(ActionFrame container) { this.PushActionFrame(container, container.NodeSet); } internal void PushActionFrame(ActionFrame container, XPathNodeIterator nodeSet) { ActionFrame frame = PushNewFrame(); frame.Init(container, nodeSet); } internal void PushTemplateLookup(XPathNodeIterator nodeSet, XmlQualifiedName mode, Stylesheet importsOf) { Debug.Assert(_templateLookup != null); _templateLookup.Initialize(mode, importsOf); PushActionFrame(_templateLookup, nodeSet); } internal string GetQueryExpression(int key) { Debug.Assert(key != Compiler.InvalidQueryKey); return _queryStore[key].CompiledQuery.Expression; } internal Query GetCompiledQuery(int key) { Debug.Assert(key != Compiler.InvalidQueryKey); TheQuery theQuery = _queryStore[key]; theQuery.CompiledQuery.CheckErrors(); Query expr = Query.Clone(_queryList[key]); expr.SetXsltContext(new XsltCompileContext(theQuery._ScopeManager, this)); return expr; } internal Query GetValueQuery(int key) { return GetValueQuery(key, null); } internal Query GetValueQuery(int key, XsltCompileContext context) { Debug.Assert(key != Compiler.InvalidQueryKey); TheQuery theQuery = _queryStore[key]; theQuery.CompiledQuery.CheckErrors(); Query expr = _queryList[key]; if (context == null) { context = new XsltCompileContext(theQuery._ScopeManager, this); } else { context.Reinitialize(theQuery._ScopeManager, this); } expr.SetXsltContext(context); return expr; } private XsltCompileContext GetValueOfContext() { if (_valueOfContext == null) { _valueOfContext = new XsltCompileContext(); } return _valueOfContext; } [Conditional("DEBUG")] private void RecycleValueOfContext() { if (_valueOfContext != null) { _valueOfContext.Recycle(); } } private XsltCompileContext GetMatchesContext() { if (_matchesContext == null) { _matchesContext = new XsltCompileContext(); } return _matchesContext; } [Conditional("DEBUG")] private void RecycleMatchesContext() { if (_matchesContext != null) { _matchesContext.Recycle(); } } internal string ValueOf(ActionFrame context, int key) { string result; Query query = this.GetValueQuery(key, GetValueOfContext()); object value = query.Evaluate(context.NodeSet); if (value is XPathNodeIterator) { XPathNavigator n = query.Advance(); result = n != null ? ValueOf(n) : string.Empty; } else { result = XmlConvert.ToXPathString(value); } RecycleValueOfContext(); return result; } internal string ValueOf(XPathNavigator n) { if (_stylesheet.Whitespace && n.NodeType == XPathNodeType.Element) { StringBuilder builder = this.GetSharedStringBuilder(); ElementValueWithoutWS(n, builder); this.ReleaseSharedStringBuilder(); return builder.ToString(); } return n.Value; } private void ElementValueWithoutWS(XPathNavigator nav, StringBuilder builder) { Debug.Assert(nav.NodeType == XPathNodeType.Element); bool preserve = this.Stylesheet.PreserveWhiteSpace(this, nav); if (nav.MoveToFirstChild()) { do { switch (nav.NodeType) { case XPathNodeType.Text: case XPathNodeType.SignificantWhitespace: builder.Append(nav.Value); break; case XPathNodeType.Whitespace: if (preserve) { builder.Append(nav.Value); } break; case XPathNodeType.Element: ElementValueWithoutWS(nav, builder); break; } } while (nav.MoveToNext()); nav.MoveToParent(); } } internal XPathNodeIterator StartQuery(XPathNodeIterator context, int key) { Query query = GetCompiledQuery(key); object result = query.Evaluate(context); if (result is XPathNodeIterator) { return new XPathSelectionIterator(context.Current, query); } throw XsltException.Create(SR.XPath_NodeSetExpected); } internal object Evaluate(ActionFrame context, int key) { return GetValueQuery(key).Evaluate(context.NodeSet); } internal object RunQuery(ActionFrame context, int key) { Query query = GetCompiledQuery(key); object value = query.Evaluate(context.NodeSet); XPathNodeIterator it = value as XPathNodeIterator; if (it != null) { return new XPathArrayIterator(it); } return value; } internal string EvaluateString(ActionFrame context, int key) { object objValue = Evaluate(context, key); string value = null; if (objValue != null) value = XmlConvert.ToXPathString(objValue); if (value == null) value = string.Empty; return value; } internal bool EvaluateBoolean(ActionFrame context, int key) { object objValue = Evaluate(context, key); if (objValue != null) { XPathNavigator nav = objValue as XPathNavigator; return nav != null ? Convert.ToBoolean(nav.Value, CultureInfo.InvariantCulture) : Convert.ToBoolean(objValue, CultureInfo.InvariantCulture); } else { return false; } } internal bool Matches(XPathNavigator context, int key) { // We don't use XPathNavigator.Matches() to avoid cloning of Query on each call Query query = this.GetValueQuery(key, GetMatchesContext()); try { bool result = query.MatchNode(context) != null; RecycleMatchesContext(); return result; } catch (XPathException) { throw XsltException.Create(SR.Xslt_InvalidPattern, this.GetQueryExpression(key)); } } // // Outputting part of processor // internal XmlNameTable NameTable { get { return _nameTable; } } internal bool CanContinue { get { return _execResult == ExecResult.Continue; } } internal bool ExecutionDone { get { return _execResult == ExecResult.Done; } } internal void ResetOutput() { Debug.Assert(_builder != null); _builder.Reset(); } internal bool BeginEvent(XPathNodeType nodeType, string prefix, string name, string nspace, bool empty) { return BeginEvent(nodeType, prefix, name, nspace, empty, null, true); } internal bool BeginEvent(XPathNodeType nodeType, string prefix, string name, string nspace, bool empty, object htmlProps, bool search) { Debug.Assert(_xsm != null); int stateOutlook = _xsm.BeginOutlook(nodeType); if (_ignoreLevel > 0 || stateOutlook == StateMachine.Error) { _ignoreLevel++; return true; // We consumed the event, so pretend it was output. } switch (_builder.BeginEvent(stateOutlook, nodeType, prefix, name, nspace, empty, htmlProps, search)) { case OutputResult.Continue: _xsm.Begin(nodeType); Debug.Assert(StateMachine.StateOnly(stateOutlook) == _xsm.State); Debug.Assert(ExecutionResult == ExecResult.Continue); return true; case OutputResult.Interrupt: _xsm.Begin(nodeType); Debug.Assert(StateMachine.StateOnly(stateOutlook) == _xsm.State); ExecutionResult = ExecResult.Interrupt; return true; case OutputResult.Overflow: ExecutionResult = ExecResult.Interrupt; return false; case OutputResult.Error: _ignoreLevel++; return true; case OutputResult.Ignore: return true; default: Debug.Fail("Unexpected result of RecordBuilder.BeginEvent()"); return true; } } internal bool TextEvent(string text) { return this.TextEvent(text, false); } internal bool TextEvent(string text, bool disableOutputEscaping) { Debug.Assert(_xsm != null); if (_ignoreLevel > 0) { return true; } int stateOutlook = _xsm.BeginOutlook(XPathNodeType.Text); switch (_builder.TextEvent(stateOutlook, text, disableOutputEscaping)) { case OutputResult.Continue: _xsm.Begin(XPathNodeType.Text); Debug.Assert(StateMachine.StateOnly(stateOutlook) == _xsm.State); Debug.Assert(ExecutionResult == ExecResult.Continue); return true; case OutputResult.Interrupt: _xsm.Begin(XPathNodeType.Text); Debug.Assert(StateMachine.StateOnly(stateOutlook) == _xsm.State); ExecutionResult = ExecResult.Interrupt; return true; case OutputResult.Overflow: ExecutionResult = ExecResult.Interrupt; return false; case OutputResult.Error: case OutputResult.Ignore: return true; default: Debug.Fail("Unexpected result of RecordBuilder.TextEvent()"); return true; } } internal bool EndEvent(XPathNodeType nodeType) { Debug.Assert(_xsm != null); if (_ignoreLevel > 0) { _ignoreLevel--; return true; } int stateOutlook = _xsm.EndOutlook(nodeType); switch (_builder.EndEvent(stateOutlook, nodeType)) { case OutputResult.Continue: _xsm.End(nodeType); Debug.Assert(StateMachine.StateOnly(stateOutlook) == _xsm.State); return true; case OutputResult.Interrupt: _xsm.End(nodeType); Debug.Assert(StateMachine.StateOnly(stateOutlook) == _xsm.State, "StateMachine.StateOnly(stateOutlook) == this.xsm.State"); ExecutionResult = ExecResult.Interrupt; return true; case OutputResult.Overflow: ExecutionResult = ExecResult.Interrupt; return false; case OutputResult.Error: case OutputResult.Ignore: default: Debug.Fail("Unexpected result of RecordBuilder.TextEvent()"); return true; } } internal bool CopyBeginEvent(XPathNavigator node, bool emptyflag) { switch (node.NodeType) { case XPathNodeType.Element: case XPathNodeType.Attribute: case XPathNodeType.ProcessingInstruction: case XPathNodeType.Comment: return BeginEvent(node.NodeType, node.Prefix, node.LocalName, node.NamespaceURI, emptyflag); case XPathNodeType.Namespace: // value instead of namespace here! return BeginEvent(XPathNodeType.Namespace, null, node.LocalName, node.Value, false); case XPathNodeType.Text: // Text will be copied in CopyContents(); break; case XPathNodeType.Root: case XPathNodeType.Whitespace: case XPathNodeType.SignificantWhitespace: case XPathNodeType.All: break; default: Debug.Fail("Invalid XPathNodeType in CopyBeginEvent"); break; } return true; } internal bool CopyTextEvent(XPathNavigator node) { switch (node.NodeType) { case XPathNodeType.Element: case XPathNodeType.Namespace: break; case XPathNodeType.Attribute: case XPathNodeType.ProcessingInstruction: case XPathNodeType.Comment: case XPathNodeType.Text: case XPathNodeType.Whitespace: case XPathNodeType.SignificantWhitespace: string text = node.Value; return TextEvent(text); case XPathNodeType.Root: case XPathNodeType.All: break; default: Debug.Fail("Invalid XPathNodeType in CopyTextEvent"); break; } return true; } internal bool CopyEndEvent(XPathNavigator node) { switch (node.NodeType) { case XPathNodeType.Element: case XPathNodeType.Attribute: case XPathNodeType.ProcessingInstruction: case XPathNodeType.Comment: case XPathNodeType.Namespace: return EndEvent(node.NodeType); case XPathNodeType.Text: // Text was copied in CopyContents(); break; case XPathNodeType.Root: case XPathNodeType.Whitespace: case XPathNodeType.SignificantWhitespace: case XPathNodeType.All: break; default: Debug.Fail("Invalid XPathNodeType in CopyEndEvent"); break; } return true; } internal static bool IsRoot(XPathNavigator navigator) { Debug.Assert(navigator != null); if (navigator.NodeType == XPathNodeType.Root) { return true; } else if (navigator.NodeType == XPathNodeType.Element) { XPathNavigator clone = navigator.Clone(); clone.MoveToRoot(); return clone.IsSamePosition(navigator); } else { return false; } } // // Builder stack // internal void PushOutput(RecordOutput output) { Debug.Assert(output != null); _builder.OutputState = _xsm.State; RecordBuilder lastBuilder = _builder; _builder = new RecordBuilder(output, _nameTable); _builder.Next = lastBuilder; _xsm.Reset(); } internal RecordOutput PopOutput() { Debug.Assert(_builder != null); RecordBuilder topBuilder = _builder; _builder = topBuilder.Next; _xsm.State = _builder.OutputState; topBuilder.TheEnd(); return topBuilder.Output; } internal bool SetDefaultOutput(XsltOutput.OutputMethod method) { if (Output.Method != method) { _output = _output.CreateDerivedOutput(method); return true; } return false; } internal object GetVariableValue(VariableAction variable) { int variablekey = variable.VarKey; if (variable.IsGlobal) { ActionFrame rootFrame = (ActionFrame)_actionStack[0]; object result = rootFrame.GetVariable(variablekey); if (result == VariableAction.BeingComputedMark) { throw XsltException.Create(SR.Xslt_CircularReference, variable.NameStr); } if (result != null) { return result; } // Variable wasn't evaluated yet int saveStackSize = _actionStack.Length; ActionFrame varFrame = PushNewFrame(); varFrame.Inherit(rootFrame); varFrame.Init(variable, rootFrame.NodeSet); do { bool endOfFrame = ((ActionFrame)_actionStack.Peek()).Execute(this); if (endOfFrame) { _actionStack.Pop(); } } while (saveStackSize < _actionStack.Length); Debug.Assert(saveStackSize == _actionStack.Length); result = rootFrame.GetVariable(variablekey); Debug.Assert(result != null, "Variable was just calculated and result can't be null"); return result; } else { return ((ActionFrame)_actionStack.Peek()).GetVariable(variablekey); } } internal void SetParameter(XmlQualifiedName name, object value) { Debug.Assert(1 < _actionStack.Length); ActionFrame parentFrame = (ActionFrame)_actionStack[_actionStack.Length - 2]; parentFrame.SetParameter(name, value); } internal void ResetParams() { ActionFrame frame = (ActionFrame)_actionStack[_actionStack.Length - 1]; frame.ResetParams(); } internal object GetParameter(XmlQualifiedName name) { Debug.Assert(2 < _actionStack.Length); ActionFrame parentFrame = (ActionFrame)_actionStack[_actionStack.Length - 3]; return parentFrame.GetParameter(name); } // ---------------------- Debugger stack ----------------------- internal class DebuggerFrame { internal ActionFrame actionFrame; internal XmlQualifiedName currentMode; } internal void PushDebuggerStack() { Debug.Assert(this.Debugger != null, "We don't generate calls this function if ! debugger"); DebuggerFrame dbgFrame = (DebuggerFrame)_debuggerStack.Push(); if (dbgFrame == null) { dbgFrame = new DebuggerFrame(); _debuggerStack.AddToTop(dbgFrame); } dbgFrame.actionFrame = (ActionFrame)_actionStack.Peek(); // In a case of next builtIn action. } internal void PopDebuggerStack() { Debug.Assert(this.Debugger != null, "We don't generate calls this function if ! debugger"); _debuggerStack.Pop(); } internal void OnInstructionExecute() { Debug.Assert(this.Debugger != null, "We don't generate calls this function if ! debugger"); DebuggerFrame dbgFrame = (DebuggerFrame)_debuggerStack.Peek(); Debug.Assert(dbgFrame != null, "PushDebuggerStack() wasn't ever called"); dbgFrame.actionFrame = (ActionFrame)_actionStack.Peek(); this.Debugger.OnInstructionExecute((IXsltProcessor)this); } internal XmlQualifiedName GetPrevioseMode() { Debug.Assert(this.Debugger != null, "We don't generate calls this function if ! debugger"); Debug.Assert(2 <= _debuggerStack.Length); return ((DebuggerFrame)_debuggerStack[_debuggerStack.Length - 2]).currentMode; } internal void SetCurrentMode(XmlQualifiedName mode) { Debug.Assert(this.Debugger != null, "We don't generate calls this function if ! debugger"); ((DebuggerFrame)_debuggerStack[_debuggerStack.Length - 1]).currentMode = mode; } } }
//------------------------------------------------------------------------------ // <copyright file="Region.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Drawing { using System.Runtime.InteropServices; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System; using Microsoft.Win32; using System.ComponentModel; using System.Drawing.Drawing2D; using System.Drawing; using System.Drawing.Internal; using System.Globalization; using System.Runtime.Versioning; /** * Represent a Region object */ /// <include file='doc\Region.uex' path='docs/doc[@for="Region"]/*' /> /// <devdoc> /// <para> /// Describes the interior of a graphics shape /// composed of rectangles and paths. /// </para> /// </devdoc> public sealed class Region : MarshalByRefObject, IDisposable { #if FINALIZATION_WATCH private string allocationSite = Graphics.GetAllocationStack(); #endif /** * Construct a new region object */ /// <include file='doc\Region.uex' path='docs/doc[@for="Region.Region"]/*' /> /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Drawing.Region'/> class. /// </para> /// </devdoc> [ResourceExposure(ResourceScope.Process)] [ResourceConsumption(ResourceScope.Process)] public Region() { IntPtr region = IntPtr.Zero; int status = SafeNativeMethods.Gdip.GdipCreateRegion(out region); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); SetNativeRegion(region); } /// <include file='doc\Region.uex' path='docs/doc[@for="Region.Region1"]/*' /> /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Drawing.Region'/> class from the specified <see cref='System.Drawing.RectangleF'/> . /// </para> /// </devdoc> [ResourceExposure(ResourceScope.Process)] [ResourceConsumption(ResourceScope.Process)] public Region(RectangleF rect) { IntPtr region = IntPtr.Zero; GPRECTF gprectf = rect.ToGPRECTF(); int status = SafeNativeMethods.Gdip.GdipCreateRegionRect(ref gprectf, out region); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); SetNativeRegion(region); } /// <include file='doc\Region.uex' path='docs/doc[@for="Region.Region2"]/*' /> /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Drawing.Region'/> class from the specified <see cref='System.Drawing.Rectangle'/>. /// </para> /// </devdoc> [ResourceExposure(ResourceScope.Process)] [ResourceConsumption(ResourceScope.Process)] public Region(Rectangle rect) { IntPtr region = IntPtr.Zero; GPRECT gprect = new GPRECT(rect); int status = SafeNativeMethods.Gdip.GdipCreateRegionRectI(ref gprect, out region); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); SetNativeRegion(region); } /// <include file='doc\Region.uex' path='docs/doc[@for="Region.Region3"]/*' /> /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Drawing.Region'/> class /// with the specified <see cref='System.Drawing.Drawing2D.GraphicsPath'/>. /// </para> /// </devdoc> [ResourceExposure(ResourceScope.Process)] [ResourceConsumption(ResourceScope.Process)] public Region(GraphicsPath path) { if (path == null) throw new ArgumentNullException("path"); IntPtr region = IntPtr.Zero; int status = SafeNativeMethods.Gdip.GdipCreateRegionPath(new HandleRef(path, path.nativePath), out region); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); SetNativeRegion(region); } /// <include file='doc\Region.uex' path='docs/doc[@for="Region.Region4"]/*' /> /// <devdoc> /// Initializes a new instance of the <see cref='System.Drawing.Region'/> class /// from the specified data. /// </devdoc> [ResourceExposure(ResourceScope.Process)] [ResourceConsumption(ResourceScope.Process)] public Region(RegionData rgnData) { if (rgnData == null) throw new ArgumentNullException("rgnData"); IntPtr region = IntPtr.Zero; int status = SafeNativeMethods.Gdip.GdipCreateRegionRgnData(rgnData.Data, rgnData.Data.Length, out region); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); SetNativeRegion(region); } internal Region(IntPtr nativeRegion) { SetNativeRegion(nativeRegion); } /// <include file='doc\Region.uex' path='docs/doc[@for="Region.FromHrgn"]/*' /> /// <devdoc> /// Initializes a new instance of the <see cref='System.Drawing.Region'/> class /// from the specified existing <see cref='System.Drawing.Region'/>. /// </devdoc> [ResourceExposure(ResourceScope.Process)] [ResourceConsumption(ResourceScope.Process)] public static Region FromHrgn(IntPtr hrgn) { IntSecurity.ObjectFromWin32Handle.Demand(); IntPtr region = IntPtr.Zero; int status = SafeNativeMethods.Gdip.GdipCreateRegionHrgn(new HandleRef(null, hrgn), out region); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); return new Region(region); } private void SetNativeRegion(IntPtr nativeRegion) { if (nativeRegion == IntPtr.Zero) throw new ArgumentNullException("nativeRegion"); this.nativeRegion = nativeRegion; } /** * Make a copy of the region object */ /// <include file='doc\Region.uex' path='docs/doc[@for="Region.Clone"]/*' /> /// <devdoc> /// Creates an exact copy if this <see cref='System.Drawing.Region'/>. /// </devdoc> [ResourceExposure(ResourceScope.Process)] [ResourceConsumption(ResourceScope.Process)] public Region Clone() { IntPtr region = IntPtr.Zero; int status = SafeNativeMethods.Gdip.GdipCloneRegion(new HandleRef(this, nativeRegion), out region); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); return new Region(region); } /** * Dispose of resources associated with the */ /// <include file='doc\Region.uex' path='docs/doc[@for="Region.Dispose"]/*' /> /// <devdoc> /// <para> /// Cleans up Windows resources for this /// <see cref='System.Drawing.Region'/>. /// </para> /// </devdoc> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } void Dispose(bool disposing) { #if FINALIZATION_WATCH if (!disposing && nativeRegion != IntPtr.Zero) Debug.WriteLine("**********************\nDisposed through finalization:\n" + allocationSite); #endif if (nativeRegion != IntPtr.Zero) { try{ #if DEBUG int status = #endif SafeNativeMethods.Gdip.GdipDeleteRegion(new HandleRef(this, nativeRegion)); #if DEBUG Debug.Assert(status == SafeNativeMethods.Gdip.Ok, "GDI+ returned an error status: " + status.ToString(CultureInfo.InvariantCulture)); #endif } catch( Exception ex ){ if( ClientUtils.IsSecurityOrCriticalException( ex ) ) { throw; } Debug.Fail( "Exception thrown during Dispose: " + ex.ToString() ); } finally{ nativeRegion = IntPtr.Zero; } } } /// <include file='doc\Region.uex' path='docs/doc[@for="Region.Finalize"]/*' /> /// <devdoc> /// Cleans up Windows resources for this /// <see cref='System.Drawing.Region'/>. /// </devdoc> ~Region() { Dispose(false); } /* * Region operations */ /// <include file='doc\Region.uex' path='docs/doc[@for="Region.MakeInfinite"]/*' /> /// <devdoc> /// Initializes this <see cref='System.Drawing.Region'/> to an /// infinite interior. /// </devdoc> public void MakeInfinite() { int status = SafeNativeMethods.Gdip.GdipSetInfinite(new HandleRef(this, nativeRegion)); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\Region.uex' path='docs/doc[@for="Region.MakeEmpty"]/*' /> /// <devdoc> /// Initializes this <see cref='System.Drawing.Region'/> to an /// empty interior. /// </devdoc> public void MakeEmpty() { int status = SafeNativeMethods.Gdip.GdipSetEmpty(new HandleRef(this, nativeRegion)); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } // float version /// <include file='doc\Region.uex' path='docs/doc[@for="Region.Intersect"]/*' /> /// <devdoc> /// Updates this <see cref='System.Drawing.Region'/> to the intersection of itself /// with the specified <see cref='System.Drawing.RectangleF'/>. /// </devdoc> public void Intersect(RectangleF rect) { GPRECTF gprectf = rect.ToGPRECTF(); int status = SafeNativeMethods.Gdip.GdipCombineRegionRect(new HandleRef(this, nativeRegion), ref gprectf, CombineMode.Intersect); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } // int version /// <include file='doc\Region.uex' path='docs/doc[@for="Region.Intersect1"]/*' /> /// <devdoc> /// <para> /// Updates this <see cref='System.Drawing.Region'/> to the intersection of itself with the specified /// <see cref='System.Drawing.Rectangle'/>. /// </para> /// </devdoc> public void Intersect(Rectangle rect) { GPRECT gprect = new GPRECT(rect); int status = SafeNativeMethods.Gdip.GdipCombineRegionRectI(new HandleRef(this, nativeRegion), ref gprect, CombineMode.Intersect); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\Region.uex' path='docs/doc[@for="Region.Intersect2"]/*' /> /// <devdoc> /// <para> /// Updates this <see cref='System.Drawing.Region'/> to the intersection of itself with the specified /// <see cref='System.Drawing.Drawing2D.GraphicsPath'/>. /// </para> /// </devdoc> public void Intersect(GraphicsPath path) { if (path == null) throw new ArgumentNullException("path"); int status = SafeNativeMethods.Gdip.GdipCombineRegionPath(new HandleRef(this, nativeRegion), new HandleRef(path, path.nativePath), CombineMode.Intersect); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\Region.uex' path='docs/doc[@for="Region.Intersect3"]/*' /> /// <devdoc> /// <para> /// Updates this <see cref='System.Drawing.Region'/> to the intersection of itself with the specified /// <see cref='System.Drawing.Region'/>. /// </para> /// </devdoc> public void Intersect(Region region) { if (region == null) throw new ArgumentNullException("region"); int status = SafeNativeMethods.Gdip.GdipCombineRegionRegion(new HandleRef(this, nativeRegion), new HandleRef(region, region.nativeRegion), CombineMode.Intersect); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\Region.uex' path='docs/doc[@for="Region.ReleaseHrgn"]/*' /> /// <devdoc> /// Releases the handle to the region handle. /// </devdoc> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] public void ReleaseHrgn(IntPtr regionHandle) { IntSecurity.ObjectFromWin32Handle.Demand(); if (regionHandle == IntPtr.Zero) { throw new ArgumentNullException("regionHandle"); } SafeNativeMethods.IntDeleteObject(new HandleRef(this, regionHandle)); } // float version /// <include file='doc\Region.uex' path='docs/doc[@for="Region.Union"]/*' /> /// <devdoc> /// <para> /// Updates this <see cref='System.Drawing.Region'/> to the union of itself and the /// specified <see cref='System.Drawing.RectangleF'/>. /// </para> /// </devdoc> public void Union(RectangleF rect) { GPRECTF gprectf = new GPRECTF(rect); int status = SafeNativeMethods.Gdip.GdipCombineRegionRect(new HandleRef(this, nativeRegion), ref gprectf, CombineMode.Union); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } // int version /// <include file='doc\Region.uex' path='docs/doc[@for="Region.Union1"]/*' /> /// <devdoc> /// Updates this <see cref='System.Drawing.Region'/> to the union of itself and the /// specified <see cref='System.Drawing.Rectangle'/>. /// </devdoc> public void Union(Rectangle rect) { GPRECT gprect = new GPRECT(rect); int status = SafeNativeMethods.Gdip.GdipCombineRegionRectI(new HandleRef(this, nativeRegion), ref gprect, CombineMode.Union); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\Region.uex' path='docs/doc[@for="Region.Union2"]/*' /> /// <devdoc> /// Updates this <see cref='System.Drawing.Region'/> to the union of itself and the /// specified <see cref='System.Drawing.Drawing2D.GraphicsPath'/>. /// </devdoc> public void Union(GraphicsPath path) { if (path == null) throw new ArgumentNullException("path"); int status = SafeNativeMethods.Gdip.GdipCombineRegionPath(new HandleRef(this, nativeRegion), new HandleRef(path, path.nativePath), CombineMode.Union); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\Region.uex' path='docs/doc[@for="Region.Union3"]/*' /> /// <devdoc> /// <para> /// Updates this <see cref='System.Drawing.Region'/> to the union of itself and the specified <see cref='System.Drawing.Region'/>. /// </para> /// </devdoc> public void Union(Region region) { if (region == null) throw new ArgumentNullException("region"); int status = SafeNativeMethods.Gdip.GdipCombineRegionRegion(new HandleRef(this, nativeRegion), new HandleRef(region, region.nativeRegion), CombineMode.Union); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } // float version /// <include file='doc\Region.uex' path='docs/doc[@for="Region.Xor"]/*' /> /// <devdoc> /// Updates this <see cref='System.Drawing.Region'/> to the union minus the /// intersection of itself with the specified <see cref='System.Drawing.RectangleF'/>. /// </devdoc> public void Xor(RectangleF rect) { GPRECTF gprectf = new GPRECTF(rect); int status = SafeNativeMethods.Gdip.GdipCombineRegionRect(new HandleRef(this, nativeRegion), ref gprectf, CombineMode.Xor); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } // int version /// <include file='doc\Region.uex' path='docs/doc[@for="Region.Xor1"]/*' /> /// <devdoc> /// Updates this <see cref='System.Drawing.Region'/> to the union minus the /// intersection of itself with the specified <see cref='System.Drawing.Rectangle'/>. /// </devdoc> public void Xor(Rectangle rect) { GPRECT gprect = new GPRECT(rect); int status = SafeNativeMethods.Gdip.GdipCombineRegionRectI(new HandleRef(this, nativeRegion), ref gprect, CombineMode.Xor); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\Region.uex' path='docs/doc[@for="Region.Xor2"]/*' /> /// <devdoc> /// Updates this <see cref='System.Drawing.Region'/> to the union minus the /// intersection of itself with the specified <see cref='System.Drawing.Drawing2D.GraphicsPath'/>. /// </devdoc> public void Xor(GraphicsPath path) { if (path == null) throw new ArgumentNullException("path"); int status = SafeNativeMethods.Gdip.GdipCombineRegionPath(new HandleRef(this, nativeRegion), new HandleRef(path, path.nativePath), CombineMode.Xor); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\Region.uex' path='docs/doc[@for="Region.Xor3"]/*' /> /// <devdoc> /// Updates this <see cref='System.Drawing.Region'/> to the union minus the /// intersection of itself with the specified <see cref='System.Drawing.Region'/>. /// </devdoc> public void Xor(Region region) { if (region == null) throw new ArgumentNullException("region"); int status = SafeNativeMethods.Gdip.GdipCombineRegionRegion(new HandleRef(this, nativeRegion), new HandleRef(region, region.nativeRegion), CombineMode.Xor); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } // float version /// <include file='doc\Region.uex' path='docs/doc[@for="Region.Exclude"]/*' /> /// <devdoc> /// Updates this <see cref='System.Drawing.Region'/> to the portion of its interior /// that does not intersect with the specified <see cref='System.Drawing.RectangleF'/>. /// </devdoc> public void Exclude(RectangleF rect) { GPRECTF gprectf = new GPRECTF(rect); int status = SafeNativeMethods.Gdip.GdipCombineRegionRect(new HandleRef(this, nativeRegion), ref gprectf, CombineMode.Exclude); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } // int version /// <include file='doc\Region.uex' path='docs/doc[@for="Region.Exclude1"]/*' /> /// <devdoc> /// Updates this <see cref='System.Drawing.Region'/> to the portion of its interior /// that does not intersect with the specified <see cref='System.Drawing.Rectangle'/>. /// </devdoc> public void Exclude(Rectangle rect) { GPRECT gprect = new GPRECT(rect); int status = SafeNativeMethods.Gdip.GdipCombineRegionRectI(new HandleRef(this, nativeRegion), ref gprect, CombineMode.Exclude); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\Region.uex' path='docs/doc[@for="Region.Exclude2"]/*' /> /// <devdoc> /// Updates this <see cref='System.Drawing.Region'/> to the portion of its interior /// that does not intersect with the specified <see cref='System.Drawing.Drawing2D.GraphicsPath'/>. /// </devdoc> public void Exclude(GraphicsPath path) { if (path == null) throw new ArgumentNullException("path"); int status = SafeNativeMethods.Gdip.GdipCombineRegionPath(new HandleRef(this, nativeRegion), new HandleRef(path, path.nativePath), CombineMode.Exclude); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\Region.uex' path='docs/doc[@for="Region.Exclude3"]/*' /> /// <devdoc> /// Updates this <see cref='System.Drawing.Region'/> to the portion of its interior /// that does not intersect with the specified <see cref='System.Drawing.Region'/>. /// </devdoc> public void Exclude(Region region) { if (region == null) throw new ArgumentNullException("region"); int status = SafeNativeMethods.Gdip.GdipCombineRegionRegion(new HandleRef(this, nativeRegion), new HandleRef(region, region.nativeRegion), CombineMode.Exclude); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } // float version /// <include file='doc\Region.uex' path='docs/doc[@for="Region.Complement"]/*' /> /// <devdoc> /// Updates this <see cref='System.Drawing.Region'/> to the portion of the /// specified <see cref='System.Drawing.RectangleF'/> that does not intersect with this <see cref='System.Drawing.Region'/>. /// </devdoc> public void Complement(RectangleF rect) { GPRECTF gprectf = rect.ToGPRECTF(); int status = SafeNativeMethods.Gdip.GdipCombineRegionRect(new HandleRef(this, nativeRegion), ref gprectf, CombineMode.Complement); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } // int version /// <include file='doc\Region.uex' path='docs/doc[@for="Region.Complement1"]/*' /> /// <devdoc> /// Updates this <see cref='System.Drawing.Region'/> to the portion of the /// specified <see cref='System.Drawing.Rectangle'/> that does not intersect with this <see cref='System.Drawing.Region'/>. /// </devdoc> public void Complement(Rectangle rect) { GPRECT gprect = new GPRECT(rect); int status = SafeNativeMethods.Gdip.GdipCombineRegionRectI(new HandleRef(this, nativeRegion), ref gprect, CombineMode.Complement); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\Region.uex' path='docs/doc[@for="Region.Complement2"]/*' /> /// <devdoc> /// Updates this <see cref='System.Drawing.Region'/> to the portion of the /// specified <see cref='System.Drawing.Drawing2D.GraphicsPath'/> that does not intersect with this /// <see cref='System.Drawing.Region'/>. /// </devdoc> public void Complement(GraphicsPath path) { if (path == null) throw new ArgumentNullException("path"); int status = SafeNativeMethods.Gdip.GdipCombineRegionPath(new HandleRef(this, nativeRegion), new HandleRef(path, path.nativePath), CombineMode.Complement); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\Region.uex' path='docs/doc[@for="Region.Complement3"]/*' /> /// <devdoc> /// <para> /// Updates this <see cref='System.Drawing.Region'/> to the portion of the /// specified <see cref='System.Drawing.Region'/> that does not intersect with this <see cref='System.Drawing.Region'/>. /// </para> /// </devdoc> public void Complement(Region region) { if (region == null) throw new ArgumentNullException("region"); int status = SafeNativeMethods.Gdip.GdipCombineRegionRegion(new HandleRef(this, nativeRegion), new HandleRef(region, region.nativeRegion), CombineMode.Complement); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /** * Transform operations */ /// <include file='doc\Region.uex' path='docs/doc[@for="Region.Translate"]/*' /> /// <devdoc> /// Offsets the coordinates of this <see cref='System.Drawing.Region'/> by the /// specified amount. /// </devdoc> public void Translate(float dx, float dy) { int status = SafeNativeMethods.Gdip.GdipTranslateRegion(new HandleRef(this, nativeRegion), dx, dy); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\Region.uex' path='docs/doc[@for="Region.Translate1"]/*' /> /// <devdoc> /// Offsets the coordinates of this <see cref='System.Drawing.Region'/> by the /// specified amount. /// </devdoc> public void Translate(int dx, int dy) { int status = SafeNativeMethods.Gdip.GdipTranslateRegionI(new HandleRef(this, nativeRegion), dx, dy); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\Region.uex' path='docs/doc[@for="Region.Transform"]/*' /> /// <devdoc> /// Transforms this <see cref='System.Drawing.Region'/> by the /// specified <see cref='System.Drawing.Drawing2D.Matrix'/>. /// </devdoc> public void Transform(Matrix matrix) { if (matrix == null) throw new ArgumentNullException("matrix"); int status = SafeNativeMethods.Gdip.GdipTransformRegion(new HandleRef(this, nativeRegion), new HandleRef(matrix, matrix.nativeMatrix)); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /** * Get region attributes */ /// <include file='doc\Region.uex' path='docs/doc[@for="Region.GetBounds"]/*' /> /// <devdoc> /// Returns a <see cref='System.Drawing.RectangleF'/> that represents a rectangular /// region that bounds this <see cref='System.Drawing.Region'/> on the drawing surface of a <see cref='System.Drawing.Graphics'/>. /// </devdoc> public RectangleF GetBounds(Graphics g) { if (g == null) throw new ArgumentNullException("g"); GPRECTF gprectf = new GPRECTF(); int status = SafeNativeMethods.Gdip.GdipGetRegionBounds(new HandleRef(this, nativeRegion), new HandleRef(g, g.NativeGraphics), ref gprectf); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); return gprectf.ToRectangleF(); } /// <include file='doc\Region.uex' path='docs/doc[@for="Region.GetHrgn"]/*' /> /// <devdoc> /// Returns a Windows handle to this <see cref='System.Drawing.Region'/> in the /// specified graphics context. /// /// Remarks from MSDN: /// It is the caller's responsibility to call the GDI function /// DeleteObject to free the GDI region when it is no longer needed. /// </devdoc> public IntPtr GetHrgn(Graphics g) { if (g == null) throw new ArgumentNullException("g"); IntPtr hrgn = IntPtr.Zero; int status = SafeNativeMethods.Gdip.GdipGetRegionHRgn(new HandleRef(this, nativeRegion), new HandleRef(g, g.NativeGraphics), out hrgn); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); return hrgn; } /// <include file='doc\Region.uex' path='docs/doc[@for="Region.IsEmpty"]/*' /> /// <devdoc> /// <para> /// Tests whether this <see cref='System.Drawing.Region'/> has an /// empty interior on the specified drawing surface. /// </para> /// </devdoc> public bool IsEmpty(Graphics g) { if (g == null) throw new ArgumentNullException("g"); int isEmpty; int status = SafeNativeMethods.Gdip.GdipIsEmptyRegion(new HandleRef(this, nativeRegion), new HandleRef(g, g.NativeGraphics), out isEmpty); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); return isEmpty != 0; } /// <include file='doc\Region.uex' path='docs/doc[@for="Region.IsInfinite"]/*' /> /// <devdoc> /// <para> /// Tests whether this <see cref='System.Drawing.Region'/> has /// an infinite interior on the specified drawing surface. /// </para> /// </devdoc> public bool IsInfinite(Graphics g) { if (g == null) throw new ArgumentNullException("g"); int isInfinite; int status = SafeNativeMethods.Gdip.GdipIsInfiniteRegion(new HandleRef(this, nativeRegion), new HandleRef(g, g.NativeGraphics), out isInfinite); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); return isInfinite != 0; } /// <include file='doc\Region.uex' path='docs/doc[@for="Region.Equals"]/*' /> /// <devdoc> /// <para> /// Tests whether the specified <see cref='System.Drawing.Region'/> is /// identical to this <see cref='System.Drawing.Region'/> /// on the specified drawing surface. /// </para> /// </devdoc> public bool Equals(Region region, Graphics g) { if (g == null) throw new ArgumentNullException("g"); if (region == null) throw new ArgumentNullException("region"); int isEqual; int status = SafeNativeMethods.Gdip.GdipIsEqualRegion(new HandleRef(this, nativeRegion), new HandleRef(region, region.nativeRegion), new HandleRef(g, g.NativeGraphics), out isEqual); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); return isEqual != 0; } /// <include file='doc\Region.uex' path='docs/doc[@for="Region.GetRegionData"]/*' /> /// <devdoc> /// Returns a <see cref='System.Drawing.Drawing2D.RegionData'/> that represents the /// information that describes this <see cref='System.Drawing.Region'/>. /// </devdoc> public RegionData GetRegionData() { int regionSize = 0; int status = SafeNativeMethods.Gdip.GdipGetRegionDataSize(new HandleRef(this, nativeRegion), out regionSize); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); if (regionSize == 0) return null; byte[] regionData = new byte[regionSize]; status = SafeNativeMethods.Gdip.GdipGetRegionData(new HandleRef(this, nativeRegion), regionData, regionSize, out regionSize); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); return new RegionData(regionData); } /* * Hit testing operations */ // float version /// <include file='doc\Region.uex' path='docs/doc[@for="Region.IsVisible"]/*' /> /// <devdoc> /// <para> /// Tests whether the specified point is /// contained within this <see cref='System.Drawing.Region'/> in the specified graphics context. /// </para> /// </devdoc> public bool IsVisible(float x, float y) { return IsVisible(new PointF(x, y), null); } /// <include file='doc\Region.uex' path='docs/doc[@for="Region.IsVisible1"]/*' /> /// <devdoc> /// <para> /// Tests whether the specified <see cref='System.Drawing.PointF'/> is contained within this <see cref='System.Drawing.Region'/>. /// </para> /// </devdoc> public bool IsVisible(PointF point) { return IsVisible(point, null); } /// <include file='doc\Region.uex' path='docs/doc[@for="Region.IsVisible2"]/*' /> /// <devdoc> /// <para> /// Tests whether the specified point is contained within this <see cref='System.Drawing.Region'/> in the /// specified graphics context. /// </para> /// </devdoc> public bool IsVisible(float x, float y, Graphics g) { return IsVisible(new PointF(x, y), g); } /// <include file='doc\Region.uex' path='docs/doc[@for="Region.IsVisible3"]/*' /> /// <devdoc> /// <para> /// Tests whether the specified <see cref='System.Drawing.PointF'/> is /// contained within this <see cref='System.Drawing.Region'/> in the specified graphics context. /// </para> /// </devdoc> public bool IsVisible(PointF point, Graphics g) { int isVisible; int status = SafeNativeMethods.Gdip.GdipIsVisibleRegionPoint(new HandleRef(this, nativeRegion), point.X, point.Y, new HandleRef(g, (g==null) ? IntPtr.Zero : g.NativeGraphics), out isVisible); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); return isVisible != 0; } /// <include file='doc\Region.uex' path='docs/doc[@for="Region.IsVisible4"]/*' /> /// <devdoc> /// <para> /// Tests whether the specified rectangle is contained within this <see cref='System.Drawing.Region'/> /// . /// </para> /// </devdoc> public bool IsVisible(float x, float y, float width, float height) { return IsVisible(new RectangleF(x, y, width, height), null); } /// <include file='doc\Region.uex' path='docs/doc[@for="Region.IsVisible5"]/*' /> /// <devdoc> /// <para> /// Tests whether the specified <see cref='System.Drawing.RectangleF'/> is contained within this /// <see cref='System.Drawing.Region'/>. /// </para> /// </devdoc> public bool IsVisible(RectangleF rect) { return IsVisible(rect, null); } /// <include file='doc\Region.uex' path='docs/doc[@for="Region.IsVisible6"]/*' /> /// <devdoc> /// <para> /// Tests whether the specified rectangle is contained within this <see cref='System.Drawing.Region'/> in the /// specified graphics context. /// </para> /// </devdoc> public bool IsVisible(float x, float y, float width, float height, Graphics g) { return IsVisible(new RectangleF(x, y, width, height), g); } /// <include file='doc\Region.uex' path='docs/doc[@for="Region.IsVisible7"]/*' /> /// <devdoc> /// <para> /// Tests whether the specified <see cref='System.Drawing.RectangleF'/> is contained within this <see cref='System.Drawing.Region'/> in the specified graphics context. /// </para> /// </devdoc> public bool IsVisible(RectangleF rect, Graphics g) { int isVisible = 0; int status = SafeNativeMethods.Gdip.GdipIsVisibleRegionRect(new HandleRef(this, nativeRegion), rect.X, rect.Y, rect.Width, rect.Height, new HandleRef(g, (g==null) ? IntPtr.Zero : g.NativeGraphics), out isVisible); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); return isVisible != 0; } // int version /// <include file='doc\Region.uex' path='docs/doc[@for="Region.IsVisible8"]/*' /> /// <devdoc> /// <para> /// Tests whether the specified point is contained within this <see cref='System.Drawing.Region'/> in the /// specified graphics context. /// </para> /// </devdoc> public bool IsVisible(int x, int y, Graphics g) { return IsVisible(new Point(x, y), g); } /// <include file='doc\Region.uex' path='docs/doc[@for="Region.IsVisible9"]/*' /> /// <devdoc> /// <para> /// Tests whether the specified <see cref='System.Drawing.Point'/> is contained within this <see cref='System.Drawing.Region'/>. /// </para> /// </devdoc> public bool IsVisible(Point point) { return IsVisible(point, null); } /// <include file='doc\Region.uex' path='docs/doc[@for="Region.IsVisible10"]/*' /> /// <devdoc> /// <para> /// Tests whether the specified <see cref='System.Drawing.Point'/> is contained within this /// <see cref='System.Drawing.Region'/> in the specified /// graphics context. /// </para> /// </devdoc> public bool IsVisible(Point point, Graphics g) { int isVisible = 0; int status = SafeNativeMethods.Gdip.GdipIsVisibleRegionPointI(new HandleRef(this, nativeRegion), point.X, point.Y, new HandleRef(g, (g == null) ? IntPtr.Zero : g.NativeGraphics), out isVisible); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); return isVisible != 0; } /// <include file='doc\Region.uex' path='docs/doc[@for="Region.IsVisible11"]/*' /> /// <devdoc> /// <para> /// Tests whether the specified rectangle is contained within this <see cref='System.Drawing.Region'/> /// . /// </para> /// </devdoc> public bool IsVisible(int x, int y, int width, int height) { return IsVisible(new Rectangle(x, y, width, height), null); } /// <include file='doc\Region.uex' path='docs/doc[@for="Region.IsVisible12"]/*' /> /// <devdoc> /// <para> /// Tests whether the specified <see cref='System.Drawing.Rectangle'/> is contained within this /// <see cref='System.Drawing.Region'/>. /// </para> /// </devdoc> public bool IsVisible(Rectangle rect) { return IsVisible(rect, null); } /// <include file='doc\Region.uex' path='docs/doc[@for="Region.IsVisible13"]/*' /> /// <devdoc> /// <para> /// Tests whether the specified rectangle is contained within this <see cref='System.Drawing.Region'/> in the /// specified graphics context. /// </para> /// </devdoc> public bool IsVisible(int x, int y, int width, int height, Graphics g) { return IsVisible(new Rectangle(x, y, width, height), g); } /// <include file='doc\Region.uex' path='docs/doc[@for="Region.IsVisible14"]/*' /> /// <devdoc> /// <para> /// Tests whether the specified <see cref='System.Drawing.Rectangle'/> is contained within this /// <see cref='System.Drawing.Region'/> /// in the specified graphics context. /// </para> /// </devdoc> public bool IsVisible(Rectangle rect, Graphics g) { int isVisible = 0; int status = SafeNativeMethods.Gdip.GdipIsVisibleRegionRectI(new HandleRef(this, nativeRegion), rect.X, rect.Y, rect.Width, rect.Height, new HandleRef(g, (g == null) ? IntPtr.Zero : g.NativeGraphics), out isVisible); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); return isVisible != 0; } /// <include file='doc\Region.uex' path='docs/doc[@for="Region.GetRegionScans"]/*' /> /// <devdoc> /// <para> /// Returns an array of <see cref='System.Drawing.RectangleF'/> /// objects that approximate this Region on the specified /// </para> /// </devdoc> [SuppressMessage("Microsoft.Performance", "CA1808:AvoidCallsThatBoxValueTypes")] public RectangleF[] GetRegionScans(Matrix matrix) { if (matrix == null) throw new ArgumentNullException("matrix"); int count = 0; // call first time to get actual count of rectangles int status = SafeNativeMethods.Gdip.GdipGetRegionScansCount(new HandleRef(this, nativeRegion), out count, new HandleRef(matrix, matrix.nativeMatrix)); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); RectangleF[] rectangles; int rectsize = (int)Marshal.SizeOf(typeof(GPRECTF)); IntPtr memoryRects = Marshal.AllocHGlobal(checked(rectsize*count)); try { status = SafeNativeMethods.Gdip.GdipGetRegionScans(new HandleRef(this, nativeRegion), memoryRects, out count, new HandleRef(matrix, matrix.nativeMatrix)); if (status != SafeNativeMethods.Gdip.Ok) { throw SafeNativeMethods.Gdip.StatusException(status); } int index; GPRECTF gprectf = new GPRECTF(); rectangles = new RectangleF[count]; for (index=0; index<count; index++) { gprectf = (GPRECTF) UnsafeNativeMethods.PtrToStructure((IntPtr)(checked((long)memoryRects + rectsize*index)), typeof(GPRECTF)); rectangles[index] = gprectf.ToRectangleF(); } }finally { Marshal.FreeHGlobal(memoryRects); } return rectangles; } /* * handle to native region object */ internal IntPtr nativeRegion; } }
#region Copyright // // DotNetNuke? - http://www.dotnetnuke.com // Copyright (c) 2002-2016 // by DotNetNuke Corporation // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and // to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions // of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF // CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #endregion #region Usings using System; using System.Text; using System.Text.RegularExpressions; using DotNetNuke.Common; using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Tabs; #endregion namespace DotNetNuke.UI.Skins.Controls { /// ----------------------------------------------------------------------------- /// <summary></summary> /// <returns></returns> /// <remarks></remarks> public partial class BreadCrumb : SkinObjectBase { private const string UrlRegex = "(href|src)=(\\\"|'|)(.[^\\\"']*)(\\\"|'|)"; private string _separator = "<img alt=\"breadcrumb separator\" src=\"" + Globals.ApplicationPath + "/images/breadcrumb.gif\">"; private string _cssClass = "SkinObject"; private int _rootLevel = 0; private bool _showRoot = false; private readonly StringBuilder _breadcrumb = new StringBuilder("<span itemscope itemtype=\"http://schema.org/BreadcrumbList\">"); private string _homeUrl = ""; private string _homeTabName = "Root"; // Separator between breadcrumb elements public string Separator { get { return _separator; } set { _separator = value; } } public string CssClass { get { return _cssClass; } set { _cssClass = value; } } // Level to begin processing breadcrumb at. // -1 means show root breadcrumb public string RootLevel { get { return _rootLevel.ToString(); } set { _rootLevel = int.Parse(value); if (_rootLevel < 0) { _showRoot = true; _rootLevel = 0; } } } // Use the page title instead of page name public bool UseTitle { get; set; } // Do not show when there is no breadcrumb (only has current tab) public bool HideWithNoBreadCrumb { get; set; } public int ProfileUserId { get { return string.IsNullOrEmpty(Request.Params["UserId"]) ? Null.NullInteger : int.Parse(Request.Params["UserId"]); } } public int GroupId { get { return string.IsNullOrEmpty(Request.Params["GroupId"]) ? Null.NullInteger : int.Parse(Request.Params["GroupId"]); } } protected override void OnLoad(EventArgs e) { base.OnLoad(e); // Position in breadcrumb list var position = 1; //resolve image path in separator content ResolveSeparatorPaths(); // If we have enabled hiding when there are no breadcrumbs, simply return if (HideWithNoBreadCrumb && PortalSettings.ActiveTab.BreadCrumbs.Count == (_rootLevel + 1)) { return; } // Without checking if the current tab is the home tab, we would duplicate the root tab if (_showRoot && PortalSettings.ActiveTab.TabID != PortalSettings.HomeTabId) { // Add the current protocal to the current URL _homeUrl = Globals.AddHTTP(PortalSettings.PortalAlias.HTTPAlias); // Make sure we have a home tab ID set if (PortalSettings.HomeTabId != -1) { _homeUrl = Globals.NavigateURL(PortalSettings.HomeTabId); var tc = new TabController(); var homeTab = tc.GetTab(PortalSettings.HomeTabId, PortalSettings.PortalId, false); _homeTabName = homeTab.LocalizedTabName; // Check if we should use the tab's title instead if (UseTitle && !string.IsNullOrEmpty(homeTab.Title)) { _homeTabName = homeTab.Title; } } // Append all of the HTML for the root breadcrumb _breadcrumb.Append("<span itemprop=\"itemListElement\" itemscope itemtype=\"http://schema.org/ListItem\">"); _breadcrumb.Append("<a href=\"" + _homeUrl + "\" class=\"" + _cssClass + "\" itemprop=\"item\" ><span itemprop=\"name\">" + _homeTabName + "</span></a>"); _breadcrumb.Append("<meta itemprop=\"position\" content=\"" + position++ + "\" />"); // Notice we post-increment the position variable _breadcrumb.Append("</span>"); // Add a separator _breadcrumb.Append(_separator); } //process bread crumbs for (var i = _rootLevel; i < PortalSettings.ActiveTab.BreadCrumbs.Count; ++i) { // Only add separators if we're past the root level if (i > _rootLevel) { _breadcrumb.Append(_separator); } // Grab the current tab var tab = (TabInfo)PortalSettings.ActiveTab.BreadCrumbs[i]; var tabName = tab.LocalizedTabName; // Determine if we should use the tab's title instead of tab name if (UseTitle && !string.IsNullOrEmpty(tab.Title)) { tabName = tab.Title; } // Get the absolute URL of the tab var tabUrl = tab.FullUrl; // if (ProfileUserId > -1) { tabUrl = Globals.NavigateURL(tab.TabID, "", "UserId=" + ProfileUserId); } // if (GroupId > -1) { tabUrl = Globals.NavigateURL(tab.TabID, "", "GroupId=" + GroupId); } // Begin breadcrumb _breadcrumb.Append("<span itemprop=\"itemListElement\" itemscope itemtype=\"http://schema.org/ListItem\">"); // Is this tab disabled? If so, only render the text if (tab.DisableLink) { _breadcrumb.Append("<span class=\"" + _cssClass + "\" itemprop=\"name\">" + tabName + "</span>"); } else { _breadcrumb.Append("<a href=\"" + tabUrl + "\" class=\"" + _cssClass + "\" itemprop=\"item\"><span itemprop=\"name\">" + tabName + "</span></a>"); } _breadcrumb.Append("<meta itemprop=\"position\" content=\"" + position++ + "\" />"); // Notice we post-increment the position variable _breadcrumb.Append("</span>"); } _breadcrumb.Append("</span>"); //End of BreadcrumbList lblBreadCrumb.Text = _breadcrumb.ToString(); } private void ResolveSeparatorPaths() { if (string.IsNullOrEmpty(_separator)) { return; } var urlMatches = Regex.Matches(_separator, UrlRegex, RegexOptions.IgnoreCase); if (urlMatches.Count > 0) { foreach (Match match in urlMatches) { var url = match.Groups[3].Value; var changed = false; if (url.StartsWith("/")) { if (!string.IsNullOrEmpty(Globals.ApplicationPath)) { url = string.Format("{0}{1}", Globals.ApplicationPath, url); changed = true; } } else if (url.StartsWith("~/")) { url = Globals.ResolveUrl(url); changed = true; } else { url = string.Format("{0}{1}", PortalSettings.ActiveTab.SkinPath, url); changed = true; } if (changed) { var newMatch = string.Format("{0}={1}{2}{3}", match.Groups[1].Value, match.Groups[2].Value, url, match.Groups[4].Value); _separator = _separator.Replace(match.Value, newMatch); } } } } } }
/** * (C) Copyright IBM Corp. 2018, 2020. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using NSubstitute; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.IO; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Collections.Generic; using IBM.Cloud.SDK.Core.Http; using IBM.Cloud.SDK.Core.Http.Exceptions; using IBM.Cloud.SDK.Core.Authentication.NoAuth; using IBM.Watson.TextToSpeech.v1.Model; using IBM.Cloud.SDK.Core.Model; namespace IBM.Watson.TextToSpeech.v1.UnitTests { [TestClass] public class TextToSpeechServiceUnitTests { #region Constructor [TestMethod, ExpectedException(typeof(ArgumentNullException))] public void Constructor_HttpClient_Null() { TextToSpeechService service = new TextToSpeechService(httpClient: null); } [TestMethod] public void ConstructorHttpClient() { TextToSpeechService service = new TextToSpeechService(new IBMHttpClient()); Assert.IsNotNull(service); } [TestMethod] public void ConstructorExternalConfig() { var apikey = System.Environment.GetEnvironmentVariable("TEXT_TO_SPEECH_APIKEY"); System.Environment.SetEnvironmentVariable("TEXT_TO_SPEECH_APIKEY", "apikey"); TextToSpeechService service = Substitute.For<TextToSpeechService>(); Assert.IsNotNull(service); System.Environment.SetEnvironmentVariable("TEXT_TO_SPEECH_APIKEY", apikey); } [TestMethod] public void Constructor() { TextToSpeechService service = new TextToSpeechService(new IBMHttpClient()); Assert.IsNotNull(service); } [TestMethod] public void ConstructorAuthenticator() { TextToSpeechService service = new TextToSpeechService(new NoAuthAuthenticator()); Assert.IsNotNull(service); } [TestMethod] public void ConstructorNoUrl() { var apikey = System.Environment.GetEnvironmentVariable("TEXT_TO_SPEECH_APIKEY"); System.Environment.SetEnvironmentVariable("TEXT_TO_SPEECH_APIKEY", "apikey"); var url = System.Environment.GetEnvironmentVariable("TEXT_TO_SPEECH_URL"); System.Environment.SetEnvironmentVariable("TEXT_TO_SPEECH_URL", null); TextToSpeechService service = Substitute.For<TextToSpeechService>(); Assert.IsTrue(service.ServiceUrl == "https://api.us-south.text-to-speech.watson.cloud.ibm.com"); System.Environment.SetEnvironmentVariable("TEXT_TO_SPEECH_URL", url); System.Environment.SetEnvironmentVariable("TEXT_TO_SPEECH_APIKEY", apikey); } #endregion [TestMethod] public void ListVoices_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.GetAsync(Arg.Any<string>()) .Returns(request); TextToSpeechService service = new TextToSpeechService(client); var result = service.ListVoices(); } [TestMethod] public void GetVoice_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.GetAsync(Arg.Any<string>()) .Returns(request); TextToSpeechService service = new TextToSpeechService(client); var voice = "voice"; var customizationId = "customizationId"; var result = service.GetVoice(voice: voice, customizationId: customizationId); client.Received().GetAsync($"{service.ServiceUrl}/v1/voices/{voice}"); } [TestMethod] public void Synthesize_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.PostAsync(Arg.Any<string>()) .Returns(request); TextToSpeechService service = new TextToSpeechService(client); var text = "text"; var accept = "accept"; var voice = "voice"; var customizationId = "customizationId"; var result = service.Synthesize(text: text, accept: accept, voice: voice, customizationId: customizationId); JObject bodyObject = new JObject(); if (!string.IsNullOrEmpty(text)) { bodyObject["text"] = JToken.FromObject(text); } var json = JsonConvert.SerializeObject(bodyObject); request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json))); } [TestMethod] public void GetPronunciation_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.GetAsync(Arg.Any<string>()) .Returns(request); TextToSpeechService service = new TextToSpeechService(client); var text = "text"; var voice = "voice"; var format = "format"; var customizationId = "customizationId"; var result = service.GetPronunciation(text: text, voice: voice, format: format, customizationId: customizationId); } [TestMethod] public void CreateVoiceModel_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.PostAsync(Arg.Any<string>()) .Returns(request); TextToSpeechService service = new TextToSpeechService(client); var name = "name"; var language = "language"; var description = "description"; var result = service.CreateCustomModel(name: name, language: language, description: description); JObject bodyObject = new JObject(); if (!string.IsNullOrEmpty(name)) { bodyObject["name"] = JToken.FromObject(name); } if (!string.IsNullOrEmpty(language)) { bodyObject["language"] = JToken.FromObject(language); } if (!string.IsNullOrEmpty(description)) { bodyObject["description"] = JToken.FromObject(description); } var json = JsonConvert.SerializeObject(bodyObject); request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json))); } [TestMethod] public void ListVoiceModels_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.GetAsync(Arg.Any<string>()) .Returns(request); TextToSpeechService service = new TextToSpeechService(client); var language = "language"; var result = service.ListCustomModels(language: language); } [TestMethod] public void UpdateVoiceModel_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.PostAsync(Arg.Any<string>()) .Returns(request); TextToSpeechService service = new TextToSpeechService(client); var customizationId = "customizationId"; var name = "name"; var description = "description"; var words = new List<Word>(); var result = service.UpdateCustomModel(customizationId: customizationId, name: name, description: description, words: words); JObject bodyObject = new JObject(); if (!string.IsNullOrEmpty(name)) { bodyObject["name"] = JToken.FromObject(name); } if (!string.IsNullOrEmpty(description)) { bodyObject["description"] = JToken.FromObject(description); } if (words != null && words.Count > 0) { bodyObject["words"] = JToken.FromObject(words); } var json = JsonConvert.SerializeObject(bodyObject); request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json))); client.Received().PostAsync($"{service.ServiceUrl}/v1/customizations/{customizationId}"); } [TestMethod] public void GetVoiceModel_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.GetAsync(Arg.Any<string>()) .Returns(request); TextToSpeechService service = new TextToSpeechService(client); var customizationId = "customizationId"; var result = service.GetCustomModel(customizationId: customizationId); client.Received().GetAsync($"{service.ServiceUrl}/v1/customizations/{customizationId}"); } [TestMethod] public void DeleteVoiceModel_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.DeleteAsync(Arg.Any<string>()) .Returns(request); TextToSpeechService service = new TextToSpeechService(client); var customizationId = "customizationId"; var result = service.DeleteCustomModel(customizationId: customizationId); client.Received().DeleteAsync($"{service.ServiceUrl}/v1/customizations/{customizationId}"); } [TestMethod] public void AddWords_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.PostAsync(Arg.Any<string>()) .Returns(request); TextToSpeechService service = new TextToSpeechService(client); var customizationId = "customizationId"; var words = new List<Word>(); var result = service.AddWords(customizationId: customizationId, words: words); JObject bodyObject = new JObject(); if (words != null && words.Count > 0) { bodyObject["words"] = JToken.FromObject(words); } var json = JsonConvert.SerializeObject(bodyObject); request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json))); client.Received().PostAsync($"{service.ServiceUrl}/v1/customizations/{customizationId}/words"); } [TestMethod] public void ListWords_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.GetAsync(Arg.Any<string>()) .Returns(request); TextToSpeechService service = new TextToSpeechService(client); var customizationId = "customizationId"; var result = service.ListWords(customizationId: customizationId); client.Received().GetAsync($"{service.ServiceUrl}/v1/customizations/{customizationId}/words"); } [TestMethod] public void AddWord_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.PutAsync(Arg.Any<string>()) .Returns(request); TextToSpeechService service = new TextToSpeechService(client); var customizationId = "customizationId"; var word = "word"; var translation = "translation"; var partOfSpeech = "partOfSpeech"; var result = service.AddWord(customizationId: customizationId, word: word, translation: translation, partOfSpeech: partOfSpeech); JObject bodyObject = new JObject(); if (!string.IsNullOrEmpty(translation)) { bodyObject["translation"] = JToken.FromObject(translation); } if (!string.IsNullOrEmpty(partOfSpeech)) { bodyObject["part_of_speech"] = JToken.FromObject(partOfSpeech); } var json = JsonConvert.SerializeObject(bodyObject); request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json))); client.Received().PutAsync($"{service.ServiceUrl}/v1/customizations/{customizationId}/words/{word}"); } [TestMethod] public void GetWord_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.GetAsync(Arg.Any<string>()) .Returns(request); TextToSpeechService service = new TextToSpeechService(client); var customizationId = "customizationId"; var word = "word"; var result = service.GetWord(customizationId: customizationId, word: word); client.Received().GetAsync($"{service.ServiceUrl}/v1/customizations/{customizationId}/words/{word}"); } [TestMethod] public void DeleteWord_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.DeleteAsync(Arg.Any<string>()) .Returns(request); TextToSpeechService service = new TextToSpeechService(client); var customizationId = "customizationId"; var word = "word"; var result = service.DeleteWord(customizationId: customizationId, word: word); client.Received().DeleteAsync($"{service.ServiceUrl}/v1/customizations/{customizationId}/words/{word}"); } [TestMethod] public void DeleteUserData_Success() { IClient client = Substitute.For<IClient>(); IRequest request = Substitute.For<IRequest>(); client.DeleteAsync(Arg.Any<string>()) .Returns(request); TextToSpeechService service = new TextToSpeechService(client); var customerId = "customerId"; var result = service.DeleteUserData(customerId: customerId); } } }
#region License // Copyright (c) Nick Hao http://www.cnblogs.com/haoxinyue // // Licensed under the Apache License, Version 2.0 (the 'License'); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an 'AS IS' BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Text; using System.Xml.Linq; using Octopus.Activator; using Octopus.Adapter; using Octopus.Channel; using Octopus.Command; using Octopus.Exceptions; using Octopus.Interpreter; using Octopus.Interpreter.FormatterFilters; using Octopus.Interpreter.Formatters; using Octopus.Interpreter.Items; namespace Octopus.Config { public class OctopusConfig { private Dictionary<string, IAdapter> _adapters = new Dictionary<string, IAdapter>(); private string _currentAdapterName = string.Empty; private Dictionary<string, Dictionary<string, object>> _adapterObjects = new Dictionary<string, Dictionary<string, object>>(); public Dictionary<string, IAdapter> Adapters { get { return _adapters; } } public void Load(string filePath) { XDocument xDoc = null; using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { xDoc = XDocument.Load(fs); } Load(xDoc); } private void Load(XDocument xDoc) { foreach (var adapterElement in xDoc.Elements("Adapter")) { IAdapter adapter = null; string adapterType = GetAttribute(adapterElement, "Type"); string adapterName = GetAttribute(adapterElement, "Name"); _currentAdapterName = adapterName; Dictionary<string, object> adapterObjects = new Dictionary<string, object>(); _adapterObjects.Add(adapterName, adapterObjects); adapter = GetAdapter(adapterElement); _adapters.Add(adapter.Name, adapter); foreach (var activatorElement in adapterElement.Elements("Activator")) { IActivator activator = GetActivator(activatorElement, adapter.GetChannel()); adapter.AddActivator(activator); } if (adapterElement.Element("EventConnecter") != null) { foreach (var eventConnecterElement in adapterElement.Elements("EventConnecter")) { GetEventConnecter(eventConnecterElement); } } } } private IAdapter GetAdapter(XElement element) { string adapterType = GetAttribute(element, "Type"); string adapterName = GetAttribute(element, "Name"); IAdapter adapter = null; var channelElement = element.Element("Channel"); if (channelElement == null) { throw new ElementNotFoundException("Channel elemnt not found."); } var interpreterElement = element.Element("Interpreter"); if (interpreterElement == null) { throw new ElementNotFoundException("Interpreter elemnt not found."); } if (adapterType == "ByteArrayAdapter") { IChannel<byte[]> channel = (IChannel<byte[]>)GetChannel(channelElement); IInterpreter<byte[]> interpreter = (IInterpreter<byte[]>)GetInterpreter(interpreterElement); adapter = new ByteArrayAdapter(adapterName, channel, interpreter); } else if (adapterType == "StringAdapter") { IChannel<string> channel = (IChannel<string>)GetChannel(channelElement); IInterpreter<string> interpreter = (IInterpreter<string>)GetInterpreter(interpreterElement); adapter = new StringAdapter(adapterName, channel, interpreter); } else { throw new UnknownElementException("Unknown adapter type:" + adapterType); } _adapterObjects[_currentAdapterName].Add(adapter.Name, adapter); return adapter; } private object GetChannel(XElement element) { string channelType = GetAttribute(element, "Type"); string name = GetAttribute(element, "Name"); IObjectWithName channel = null; if (channelType == "TcpServerChannel") { int port = int.Parse(GetAttribute(element, "LocalPort")); TcpServerChannel tcpServerChannel = new TcpServerChannel(name, port); channel = tcpServerChannel; } else if (channelType == "TcpClientChannel") { TcpClientChannel tcpClientChannel = null; string ip = GetAttribute(element, "RemoteIP"); int port = int.Parse(GetAttribute(element, "RemotePort")); IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse(ip), port); if (element.Attribute("RetryInterval") != null && !string.IsNullOrEmpty(element.Attribute("RetryInterval").Value)) { int retryInterval = int.Parse(GetAttribute(element, "RetryInterval")); tcpClientChannel = new TcpClientChannel(name, ipEndPoint, retryInterval); } else { tcpClientChannel = new TcpClientChannel(name, ipEndPoint); } channel = tcpClientChannel; } else if (channelType == "UdpChannel") { UdpChannel udpChannel = null; int remotePort = int.Parse(GetAttribute(element, "RemotePort")); int localPort = int.Parse(GetAttribute(element, "LocalPort")); if (element.Attribute("LocalIP") != null && !string.IsNullOrEmpty(element.Attribute("LocalIP").Value)) { string localIP = GetAttribute(element, "LocalIP"); udpChannel = new UdpChannel(name, remotePort, localPort, IPAddress.Parse(localIP)); } else { udpChannel = new UdpChannel(name, remotePort, localPort); } channel = udpChannel; } else if (channelType == "HttpReaderChannel") { HttpReaderChannel httpReaderChannel = null; int remotePort = int.Parse(GetAttribute(element, "RemotePort")); string remoteIP = GetAttribute(element, "RemoteIP"); string requestUrl = GetAttribute(element, "RequestUrl"); string userName = string.Empty; string password = string.Empty; if (element.Attribute("UserName") != null && !string.IsNullOrEmpty(element.Attribute("UserName").Value)) { userName = GetAttribute(element, "UserName"); } if (element.Attribute("Password") != null && !string.IsNullOrEmpty(element.Attribute("Password").Value)) { password = GetAttribute(element, "Password"); } httpReaderChannel = new HttpReaderChannel(name, remoteIP, remotePort, requestUrl, userName, password); channel = httpReaderChannel; } else { throw new UnknownElementException("Unknown channel type:" + channelType); } _adapterObjects[_currentAdapterName].Add(channel.Name, channel); return channel; } public string GetAttribute(XElement element, string attributeName) { XAttribute xAttri = element.Attribute(attributeName); if (xAttri != null) { string attriValue = xAttri.Value; if (!string.IsNullOrEmpty(attriValue)) { return attriValue; } else { throw new AttributeNotFoundException("Attribute Name:" + attributeName + " cannot be empty"); } } else { throw new AttributeNotFoundException("Attribute Name:" + attributeName + " not found"); } } private object GetInterpreter(XElement element) { string interpreterType = GetAttribute(element, "Type"); string interpreterName = GetAttribute(element, "Name"); var headerElement = element.Element("Header"); var trailerElement = element.Element("Tailer"); IObjectWithName returnInterpreter = null; if (interpreterType == "MultipleFormatterByteArrayInterpreter") { MultipleFormatterByteArrayInterpreter interpreter = new MultipleFormatterByteArrayInterpreter(interpreterName); if (headerElement != null && !string.IsNullOrEmpty(headerElement.Value.Trim())) { string headerString = headerElement.Value; interpreter.SetHeaders(HexStringToByteArray(headerString)); } if (trailerElement != null && !string.IsNullOrEmpty(trailerElement.Value.Trim())) { string tailerString = trailerElement.Value; interpreter.SetTailers(HexStringToByteArray(tailerString)); } foreach (var formatterElement in element.Elements("Formatter")) { interpreter.AddFormatter((IFormatter<byte[]>)GetFormatter(formatterElement)); } if (element.Element("FormatterFilter") != null) { foreach (var filterElement in element.Elements("FormatterFilter")) { IFormatterFilter<byte[]> filter = (IFormatterFilter<byte[]>)GetFormatterFilter(filterElement); interpreter.AddFormatterFilter(filter); } } returnInterpreter = interpreter; } else if (interpreterType == "SingleFormatterByteArrayInterpreter") { SingleFormatterByteArrayInterpreter interpreter = new SingleFormatterByteArrayInterpreter(interpreterName); if (headerElement != null && !string.IsNullOrEmpty(headerElement.Value.Trim())) { string headerString = headerElement.Value; interpreter.SetHeaders(HexStringToByteArray(headerString)); } if (trailerElement != null && !string.IsNullOrEmpty(trailerElement.Value.Trim())) { string tailerString = trailerElement.Value; interpreter.SetTailers(HexStringToByteArray(tailerString)); } var formatterElement = element.Element("Formatter"); interpreter.AddFormatter((IFormatter<byte[]>)GetFormatter(formatterElement)); returnInterpreter = interpreter; } else if (interpreterType == "StringInterpreter") { StringInterpreter interpreter = new StringInterpreter(interpreterName); var formatterElement = element.Element("Formatter"); interpreter.AddFormatter((IFormatter<string>)GetFormatter(formatterElement)); returnInterpreter = interpreter; } else { throw new UnknownElementException("Unknown interpreter type:" + interpreterType); } _adapterObjects[_currentAdapterName].Add(returnInterpreter.Name, returnInterpreter); return returnInterpreter; } private object GetFormatter(XElement element) { string formatterType = GetAttribute(element, "Type"); string formatterName = GetAttribute(element, "Name"); IObjectWithName returnFormatter = null; if (formatterType == "ByteArrayFormatter") { ByteArrayFormatter formatter = null; if (element.Attribute("TypeId") != null && !string.IsNullOrEmpty(element.Attribute("TypeId").Value)) { formatter = new ByteArrayFormatter(formatterName, byte.Parse(element.Attribute("TypeId").Value)); } else { formatter = new ByteArrayFormatter(formatterName); } foreach (var itemElement in element.Elements("Item")) { formatter.AddItem(GetItem(itemElement)); } returnFormatter = formatter; } else if (formatterType == "StringFormatter") { StringFormatter formatter = new StringFormatter(formatterName); foreach (var itemElement in element.Elements("Item")) { formatter.AddItem(GetItem(itemElement)); } returnFormatter = formatter; } else { throw new UnknownElementException("Unkown formatter type:" + formatterType); } _adapterObjects[_currentAdapterName].Add(returnFormatter.Name, returnFormatter); return returnFormatter; } private object GetFormatterFilter(XElement element) { string filterType = GetAttribute(element, "Type"); string filterName = GetAttribute(element, "Name"); if (filterType == "ByteArrayTypedFormatterFilter") { int formatterTypeIndex = int.Parse(GetAttribute(element, "FormatterTypeIndex")); ByteArrayTypedFormatterFilter filter = new ByteArrayTypedFormatterFilter(filterName, formatterTypeIndex); if (element.Element("FormatterFilter") != null) { foreach (var subFilterElement in element.Elements("FormatterFilter")) { IFormatterFilter<byte[]> subFilter = (IFormatterFilter<byte[]>)GetFormatterFilter(subFilterElement); } } return filter; } else if (filterType == "ByteArrayLengthGreatThanFormatterFilter") { int length = int.Parse(GetAttribute(element, "Length")); ByteArrayLengthGreatThanFormatterFilter filter = new ByteArrayLengthGreatThanFormatterFilter(filterName, length); if (element.Element("FormatterFilter") != null) { foreach (var subFilterElement in element.Elements("FormatterFilter")) { IFormatterFilter<byte[]> subFilter = (IFormatterFilter<byte[]>)GetFormatterFilter(subFilterElement); } } return filter; } else if (filterType == "ByteArrayLengthEqualFormatterFilter") { int length = int.Parse(GetAttribute(element, "Length")); ByteArrayLengthEqualFormatterFilter filter = new ByteArrayLengthEqualFormatterFilter(filterName, length); if (element.Element("FormatterFilter") != null) { foreach (var subFilterElement in element.Elements("FormatterFilter")) { IFormatterFilter<byte[]> subFilter = (IFormatterFilter<byte[]>)GetFormatterFilter(subFilterElement); } } return filter; } else if (filterType == "Custom") { string customTypeName = GetAttribute(element, "CustomTypeName"); Type type = Type.GetType(customTypeName); object[] args = null; if (element.Elements("Parameter") != null) { args = new object[element.Elements("Parameter").Count()]; int i = 0; foreach (var paraElement in element.Elements("Parameter")) { string pType = GetAttribute(paraElement, "Type"); string pValue = GetAttribute(paraElement, "Value"); object p = Convert.ChangeType(pValue, Type.GetType(pType)); args[i] = p; i++; } } object custom = System.Activator.CreateInstance(type, args); return custom; } else { throw new UnknownElementException("Unknown FormatterFilter type:" + filterType); } } private Item GetItem(XElement element) { Item item = null; string itemType = GetAttribute(element, "Type"); string name = GetAttribute(element, "Name"); short index = short.Parse(GetAttribute(element, "SortIndex")); switch (itemType) { case "ByteArrayByteCrcItem": int crcFromIndex = int.Parse(GetAttribute(element, "CrcFromIndex")); int crcToIndex = int.Parse(GetAttribute(element, "CrcToIndex")); item = new ByteArrayByteCrcItem(name, index, crcFromIndex, crcToIndex); break; case "ByteArrayByteItem": item = new ByteArrayByteItem(name, index); foreach (var subItemElement in element.Elements("BitItem")) { string bitItemName = GetAttribute(subItemElement, "Name"); int bitItemLength = int.Parse(GetAttribute(subItemElement, "Length")); ((ByteArrayByteItem)item).AddBitItem(bitItemName, bitItemLength); } break; case "ByteArrayCompositeValueItem": item = new ByteArrayCompositeValueItem(name, index); foreach (var subItemElement in element.Elements("Item")) { Item subItem = GetItem(subItemElement); ((ByteArrayCompositeValueItem)item).AddItem((ValueItem<byte[], DataItem>)subItem); } break; case "ByteArrayDoubleItem": item = new ByteArrayDoubleItem(name, index); break; case "ByteArrayInt16Item": item = new ByteArrayInt16Item(name, index); break; case "ByteArrayInt32Item": item = new ByteArrayInt32Item(name, index); break; case "ByteArrayInt64Item": item = new ByteArrayInt64Item(name, index); break; case "ByteArrayLoopItem": ByteArrayCompositeValueItem itemByteArrayCompositeValue = null; foreach (var subItemElement in element.Elements("Item")) { if (GetAttribute(subItemElement, "Type") == "ByteArrayCompositeValueItem") { itemByteArrayCompositeValue = (ByteArrayCompositeValueItem)GetItem(subItemElement); break; } } if (itemByteArrayCompositeValue == null) { throw new ElementNotFoundException("Element ByteArrayCompositeValueItem Item not found"); } item = new ByteArrayLoopItem(name, index, itemByteArrayCompositeValue); break; case "ByteArrayStringItem": int byteCount = int.Parse(GetAttribute(element, "ByteCount")); string encoding = GetAttribute(element, "Encoding"); item = new ByteArrayStringItem(name, index, byteCount, Encoding.GetEncoding(encoding)); break; case "SimpleStringValueItem": item = new SimpleStringValueItem(name, index); break; case "CustomItem": { string customTypeName = GetAttribute(element, "CustomTypeName"); Type type = Type.GetType(customTypeName); object[] args = null; if (element.Elements("Parameter") != null) { args = new object[element.Elements("Parameter").Count() + 2]; int i = 0; args[0] = name; args[1] = index; foreach (var paraElement in element.Elements("Parameter")) { string pType = GetAttribute(paraElement, "Type"); string pValue = GetAttribute(paraElement, "Value"); object p = Convert.ChangeType(pValue, Type.GetType(pType)); args[i + 2] = p; i++; } } item = (Item)System.Activator.CreateInstance(type, args); break; } default: throw new UnknownElementException("Unknown item type:" + itemType); } _adapterObjects[_currentAdapterName].Add(item.Name, item); return item; } private IActivator GetActivator(XElement element, object channel) { IActivator activator = null; string activatorType = GetAttribute(element, "Type"); string activatorName = GetAttribute(element, "Name"); if (activatorType == "OneTimeActivator") { activator = new OneTimeActivator(activatorName); } else if (activatorType == "IntervalActivator") { if (element.Attribute("ExecuteInterval") != null && !string.IsNullOrEmpty(element.Attribute("ExecuteInterval").Value)) { activator = new IntervalActivator(activatorName, int.Parse(element.Attribute("ExecuteInterval").Value)); } else { activator = new IntervalActivator(activatorName); } } else { throw new UnknownElementException("Unknown activator type:" + activatorType); } if (element.Element("Command") == null) { throw new ElementNotFoundException("Element Command cannot be found"); } foreach (var commandElement in element.Elements("Command")) { ICommand command = GetCommand(commandElement, channel); activator.AddCommand(command); } _adapterObjects[_currentAdapterName].Add(activator.Name, activator); return activator; } private ICommand GetCommand(XElement element, object channel) { ICommand command = null; string commandType = GetAttribute(element, "Type"); string commandName = GetAttribute(element, "Name"); if (commandType == "ByteArrayCommand") { if (!string.IsNullOrEmpty(element.Value.Trim())) { command = new ByteArrayCommand(commandName, (IChannel<byte[]>)channel, HexStringToByteArray(element.Value.Trim().Replace(" ", ""))); } else { throw new ElementValueNotFoundException("Command value not found."); } } else if (commandType == "StringCommand") { if (!string.IsNullOrEmpty(element.Value.Trim())) { command = new StringCommand(commandName, (IChannel<string>)channel, element.Value.Trim()); } else { throw new ElementValueNotFoundException("Command value not found."); } } else { throw new UnknownElementException("Unknown command type:" + commandType); } _adapterObjects[_currentAdapterName].Add(command.Name, command); return command; } private byte[] HexStringToByteArray(string hex) { return Enumerable.Range(0, hex.Length) .Where(x => x % 2 == 0) .Select(x => Convert.ToByte(hex.Substring(x, 2), 16)) .ToArray(); } private void GetEventConnecter(XElement element) { if (element.Elements("Linker") != null) { foreach (var linkerElement in element.Elements("Linker")) { string raiserName = GetAttribute(linkerElement, "RaiserName"); string eventName = GetAttribute(linkerElement, "EventName"); string handlerName = GetAttribute(linkerElement, "HandlerName"); string handlerMethodName = GetAttribute(linkerElement, "HandlerMethodName"); EventInfo ei = _adapterObjects[_currentAdapterName][raiserName].GetType().GetEvent(eventName); Delegate d = Delegate.CreateDelegate(ei.EventHandlerType, _adapterObjects[_currentAdapterName][handlerName], handlerMethodName); ei.AddEventHandler(_adapterObjects[_currentAdapterName][raiserName], d); } } } } }
using System; using System.Globalization; using Lucene.Net.Documents; namespace Lucene.Net.Search { using Lucene.Net.Randomized.Generators; using NUnit.Framework; using DefaultSimilarity = Lucene.Net.Search.Similarities.DefaultSimilarity; using Directory = Lucene.Net.Store.Directory; using Document = Documents.Document; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Field = Field; using IndexReader = Lucene.Net.Index.IndexReader; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter; using Similarity = Lucene.Net.Search.Similarities.Similarity; using Term = Lucene.Net.Index.Term; /// <summary> /// Test that BooleanQuery.setMinimumNumberShouldMatch works. /// </summary> [TestFixture] public class TestBooleanMinShouldMatch : LuceneTestCase { private static Directory Index; private static IndexReader r; private static IndexSearcher s; [TestFixtureSetUp] public static void BeforeClass() { string[] data = new string[] { "A 1 2 3 4 5 6", "Z 4 5 6", null, "B 2 4 5 6", "Y 3 5 6", null, "C 3 6", "X 4 5 6" }; Index = NewDirectory(); RandomIndexWriter w = new RandomIndexWriter(Random(), Index); for (int i = 0; i < data.Length; i++) { Document doc = new Document(); doc.Add(NewStringField("id", Convert.ToString(i), Field.Store.YES)); //Field.Keyword("id",String.valueOf(i))); doc.Add(NewStringField("all", "all", Field.Store.YES)); //Field.Keyword("all","all")); if (null != data[i]) { doc.Add(NewTextField("data", data[i], Field.Store.YES)); //Field.Text("data",data[i])); } w.AddDocument(doc); } r = w.Reader; s = NewSearcher(r); w.Dispose(); //System.out.println("Set up " + getName()); } [TestFixtureTearDown] public static void AfterClass() { s = null; r.Dispose(); r = null; Index.Dispose(); Index = null; } public virtual void VerifyNrHits(Query q, int expected) { // bs1 ScoreDoc[] h = s.Search(q, null, 1000).ScoreDocs; if (expected != h.Length) { PrintHits(TestName, h, s); } Assert.AreEqual(expected, h.Length, "result count"); //System.out.println("TEST: now check"); // bs2 TopScoreDocCollector collector = TopScoreDocCollector.Create(1000, true); s.Search(q, collector); ScoreDoc[] h2 = collector.TopDocs().ScoreDocs; if (expected != h2.Length) { PrintHits(TestName, h2, s); } Assert.AreEqual(expected, h2.Length, "result count (bs2)"); QueryUtils.Check(Random(), q, s); } [Test] public virtual void TestAllOptional() { BooleanQuery q = new BooleanQuery(); for (int i = 1; i <= 4; i++) { q.Add(new TermQuery(new Term("data", "" + i)), BooleanClause.Occur.SHOULD); //false, false); } q.MinimumNumberShouldMatch = 2; // match at least two of 4 VerifyNrHits(q, 2); } [Test] public virtual void TestOneReqAndSomeOptional() { /* one required, some optional */ BooleanQuery q = new BooleanQuery(); q.Add(new TermQuery(new Term("all", "all")), BooleanClause.Occur.MUST); //true, false); q.Add(new TermQuery(new Term("data", "5")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "4")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "3")), BooleanClause.Occur.SHOULD); //false, false); q.MinimumNumberShouldMatch = 2; // 2 of 3 optional VerifyNrHits(q, 5); } [Test] public virtual void TestSomeReqAndSomeOptional() { /* two required, some optional */ BooleanQuery q = new BooleanQuery(); q.Add(new TermQuery(new Term("all", "all")), BooleanClause.Occur.MUST); //true, false); q.Add(new TermQuery(new Term("data", "6")), BooleanClause.Occur.MUST); //true, false); q.Add(new TermQuery(new Term("data", "5")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "4")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "3")), BooleanClause.Occur.SHOULD); //false, false); q.MinimumNumberShouldMatch = 2; // 2 of 3 optional VerifyNrHits(q, 5); } [Test] public virtual void TestOneProhibAndSomeOptional() { /* one prohibited, some optional */ BooleanQuery q = new BooleanQuery(); q.Add(new TermQuery(new Term("data", "1")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "2")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "3")), BooleanClause.Occur.MUST_NOT); //false, true ); q.Add(new TermQuery(new Term("data", "4")), BooleanClause.Occur.SHOULD); //false, false); q.MinimumNumberShouldMatch = 2; // 2 of 3 optional VerifyNrHits(q, 1); } [Test] public virtual void TestSomeProhibAndSomeOptional() { /* two prohibited, some optional */ BooleanQuery q = new BooleanQuery(); q.Add(new TermQuery(new Term("data", "1")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "2")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "3")), BooleanClause.Occur.MUST_NOT); //false, true ); q.Add(new TermQuery(new Term("data", "4")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "C")), BooleanClause.Occur.MUST_NOT); //false, true ); q.MinimumNumberShouldMatch = 2; // 2 of 3 optional VerifyNrHits(q, 1); } [Test] public virtual void TestOneReqOneProhibAndSomeOptional() { /* one required, one prohibited, some optional */ BooleanQuery q = new BooleanQuery(); q.Add(new TermQuery(new Term("data", "6")), BooleanClause.Occur.MUST); // true, false); q.Add(new TermQuery(new Term("data", "5")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "4")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "3")), BooleanClause.Occur.MUST_NOT); //false, true ); q.Add(new TermQuery(new Term("data", "2")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "1")), BooleanClause.Occur.SHOULD); //false, false); q.MinimumNumberShouldMatch = 3; // 3 of 4 optional VerifyNrHits(q, 1); } [Test] public virtual void TestSomeReqOneProhibAndSomeOptional() { /* two required, one prohibited, some optional */ BooleanQuery q = new BooleanQuery(); q.Add(new TermQuery(new Term("all", "all")), BooleanClause.Occur.MUST); //true, false); q.Add(new TermQuery(new Term("data", "6")), BooleanClause.Occur.MUST); //true, false); q.Add(new TermQuery(new Term("data", "5")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "4")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "3")), BooleanClause.Occur.MUST_NOT); //false, true ); q.Add(new TermQuery(new Term("data", "2")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "1")), BooleanClause.Occur.SHOULD); //false, false); q.MinimumNumberShouldMatch = 3; // 3 of 4 optional VerifyNrHits(q, 1); } [Test] public virtual void TestOneReqSomeProhibAndSomeOptional() { /* one required, two prohibited, some optional */ BooleanQuery q = new BooleanQuery(); q.Add(new TermQuery(new Term("data", "6")), BooleanClause.Occur.MUST); //true, false); q.Add(new TermQuery(new Term("data", "5")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "4")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "3")), BooleanClause.Occur.MUST_NOT); //false, true ); q.Add(new TermQuery(new Term("data", "2")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "1")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "C")), BooleanClause.Occur.MUST_NOT); //false, true ); q.MinimumNumberShouldMatch = 3; // 3 of 4 optional VerifyNrHits(q, 1); } [Test] public virtual void TestSomeReqSomeProhibAndSomeOptional() { /* two required, two prohibited, some optional */ BooleanQuery q = new BooleanQuery(); q.Add(new TermQuery(new Term("all", "all")), BooleanClause.Occur.MUST); //true, false); q.Add(new TermQuery(new Term("data", "6")), BooleanClause.Occur.MUST); //true, false); q.Add(new TermQuery(new Term("data", "5")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "4")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "3")), BooleanClause.Occur.MUST_NOT); //false, true ); q.Add(new TermQuery(new Term("data", "2")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "1")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "C")), BooleanClause.Occur.MUST_NOT); //false, true ); q.MinimumNumberShouldMatch = 3; // 3 of 4 optional VerifyNrHits(q, 1); } [Test] public virtual void TestMinHigherThenNumOptional() { /* two required, two prohibited, some optional */ BooleanQuery q = new BooleanQuery(); q.Add(new TermQuery(new Term("all", "all")), BooleanClause.Occur.MUST); //true, false); q.Add(new TermQuery(new Term("data", "6")), BooleanClause.Occur.MUST); //true, false); q.Add(new TermQuery(new Term("data", "5")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "4")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "3")), BooleanClause.Occur.MUST_NOT); //false, true ); q.Add(new TermQuery(new Term("data", "2")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "1")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "C")), BooleanClause.Occur.MUST_NOT); //false, true ); q.MinimumNumberShouldMatch = 90; // 90 of 4 optional ?!?!?! VerifyNrHits(q, 0); } [Test] public virtual void TestMinEqualToNumOptional() { /* two required, two optional */ BooleanQuery q = new BooleanQuery(); q.Add(new TermQuery(new Term("all", "all")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "6")), BooleanClause.Occur.MUST); //true, false); q.Add(new TermQuery(new Term("data", "3")), BooleanClause.Occur.MUST); //true, false); q.Add(new TermQuery(new Term("data", "2")), BooleanClause.Occur.SHOULD); //false, false); q.MinimumNumberShouldMatch = 2; // 2 of 2 optional VerifyNrHits(q, 1); } [Test] public virtual void TestOneOptionalEqualToMin() { /* two required, one optional */ BooleanQuery q = new BooleanQuery(); q.Add(new TermQuery(new Term("all", "all")), BooleanClause.Occur.MUST); //true, false); q.Add(new TermQuery(new Term("data", "3")), BooleanClause.Occur.SHOULD); //false, false); q.Add(new TermQuery(new Term("data", "2")), BooleanClause.Occur.MUST); //true, false); q.MinimumNumberShouldMatch = 1; // 1 of 1 optional VerifyNrHits(q, 1); } [Test] public virtual void TestNoOptionalButMin() { /* two required, no optional */ BooleanQuery q = new BooleanQuery(); q.Add(new TermQuery(new Term("all", "all")), BooleanClause.Occur.MUST); //true, false); q.Add(new TermQuery(new Term("data", "2")), BooleanClause.Occur.MUST); //true, false); q.MinimumNumberShouldMatch = 1; // 1 of 0 optional VerifyNrHits(q, 0); } [Test] public virtual void TestNoOptionalButMin2() { /* one required, no optional */ BooleanQuery q = new BooleanQuery(); q.Add(new TermQuery(new Term("all", "all")), BooleanClause.Occur.MUST); //true, false); q.MinimumNumberShouldMatch = 1; // 1 of 0 optional VerifyNrHits(q, 0); } [Test] public virtual void TestRandomQueries() { const string field = "data"; string[] vals = new string[] { "1", "2", "3", "4", "5", "6", "A", "Z", "B", "Y", "Z", "X", "foo" }; int maxLev = 4; // callback object to set a random setMinimumNumberShouldMatch TestBoolean2.Callback minNrCB = new CallbackAnonymousInnerClassHelper(this, field, vals); // increase number of iterations for more complete testing int num = AtLeast(20); for (int i = 0; i < num; i++) { int lev = Random().Next(maxLev); int seed = Random().Next(); BooleanQuery q1 = TestBoolean2.RandBoolQuery(new Random(seed), true, lev, field, vals, null); // BooleanQuery q2 = TestBoolean2.randBoolQuery(new Random(seed), lev, field, vals, minNrCB); BooleanQuery q2 = TestBoolean2.RandBoolQuery(new Random(seed), true, lev, field, vals, null); // only set minimumNumberShouldMatch on the top level query since setting // at a lower level can change the score. minNrCB.PostCreate(q2); // Can't use Hits because normalized scores will mess things // up. The non-sorting version of search() that returns TopDocs // will not normalize scores. TopDocs top1 = s.Search(q1, null, 100); TopDocs top2 = s.Search(q2, null, 100); if (i < 100) { QueryUtils.Check(Random(), q1, s); QueryUtils.Check(Random(), q2, s); } AssertSubsetOfSameScores(q2, top1, top2); } // System.out.println("Total hits:"+tot); } private class CallbackAnonymousInnerClassHelper : TestBoolean2.Callback { private readonly TestBooleanMinShouldMatch OuterInstance; private string Field; private string[] Vals; public CallbackAnonymousInnerClassHelper(TestBooleanMinShouldMatch outerInstance, string field, string[] vals) { this.OuterInstance = outerInstance; this.Field = field; this.Vals = vals; } public virtual void PostCreate(BooleanQuery q) { BooleanClause[] c = q.Clauses; int opt = 0; for (int i = 0; i < c.Length; i++) { if (c[i].Occur_ == BooleanClause.Occur.SHOULD) { opt++; } } q.MinimumNumberShouldMatch = Random().Next(opt + 2); if (Random().NextBoolean()) { // also add a random negation Term randomTerm = new Term(Field, Vals[Random().Next(Vals.Length)]); q.Add(new TermQuery(randomTerm), BooleanClause.Occur.MUST_NOT); } } } private void AssertSubsetOfSameScores(Query q, TopDocs top1, TopDocs top2) { // The constrained query // should be a subset to the unconstrained query. if (top2.TotalHits > top1.TotalHits) { Assert.Fail("Constrained results not a subset:\n" + CheckHits.TopdocsString(top1, 0, 0) + CheckHits.TopdocsString(top2, 0, 0) + "for query:" + q.ToString()); } for (int hit = 0; hit < top2.TotalHits; hit++) { int id = top2.ScoreDocs[hit].Doc; float score = top2.ScoreDocs[hit].Score; bool found = false; // find this doc in other hits for (int other = 0; other < top1.TotalHits; other++) { if (top1.ScoreDocs[other].Doc == id) { found = true; float otherScore = top1.ScoreDocs[other].Score; // check if scores match Assert.AreEqual(score, otherScore, CheckHits.ExplainToleranceDelta(score, otherScore), "Doc " + id + " scores don't match\n" + CheckHits.TopdocsString(top1, 0, 0) + CheckHits.TopdocsString(top2, 0, 0) + "for query:" + q.ToString()); } } // check if subset if (!found) { Assert.Fail("Doc " + id + " not found\n" + CheckHits.TopdocsString(top1, 0, 0) + CheckHits.TopdocsString(top2, 0, 0) + "for query:" + q.ToString()); } } } [Test] public virtual void TestRewriteCoord1() { Similarity oldSimilarity = s.Similarity; try { s.Similarity = new DefaultSimilarityAnonymousInnerClassHelper(this); BooleanQuery q1 = new BooleanQuery(); q1.Add(new TermQuery(new Term("data", "1")), BooleanClause.Occur.SHOULD); BooleanQuery q2 = new BooleanQuery(); q2.Add(new TermQuery(new Term("data", "1")), BooleanClause.Occur.SHOULD); q2.MinimumNumberShouldMatch = 1; TopDocs top1 = s.Search(q1, null, 100); TopDocs top2 = s.Search(q2, null, 100); AssertSubsetOfSameScores(q2, top1, top2); } finally { s.Similarity = oldSimilarity; } } private class DefaultSimilarityAnonymousInnerClassHelper : DefaultSimilarity { private readonly TestBooleanMinShouldMatch OuterInstance; public DefaultSimilarityAnonymousInnerClassHelper(TestBooleanMinShouldMatch outerInstance) { this.OuterInstance = outerInstance; } public override float Coord(int overlap, int maxOverlap) { return overlap / ((float)maxOverlap + 1); } } [Test] public virtual void TestRewriteNegate() { Similarity oldSimilarity = s.Similarity; try { s.Similarity = new DefaultSimilarityAnonymousInnerClassHelper2(this); BooleanQuery q1 = new BooleanQuery(); q1.Add(new TermQuery(new Term("data", "1")), BooleanClause.Occur.SHOULD); BooleanQuery q2 = new BooleanQuery(); q2.Add(new TermQuery(new Term("data", "1")), BooleanClause.Occur.SHOULD); q2.Add(new TermQuery(new Term("data", "Z")), BooleanClause.Occur.MUST_NOT); TopDocs top1 = s.Search(q1, null, 100); TopDocs top2 = s.Search(q2, null, 100); AssertSubsetOfSameScores(q2, top1, top2); } finally { s.Similarity = oldSimilarity; } } private class DefaultSimilarityAnonymousInnerClassHelper2 : DefaultSimilarity { private readonly TestBooleanMinShouldMatch OuterInstance; public DefaultSimilarityAnonymousInnerClassHelper2(TestBooleanMinShouldMatch outerInstance) { this.OuterInstance = outerInstance; } public override float Coord(int overlap, int maxOverlap) { return overlap / ((float)maxOverlap + 1); } } protected internal virtual void PrintHits(string test, ScoreDoc[] h, IndexSearcher searcher) { Console.Error.WriteLine("------- " + test + " -------"); NumberFormatInfo f = new NumberFormatInfo(); f.NumberDecimalSeparator = "."; //DecimalFormat f = new DecimalFormat("0.000000", DecimalFormatSymbols.getInstance(Locale.ROOT)); for (int i = 0; i < h.Length; i++) { Document d = searcher.Doc(h[i].Doc); decimal score = (decimal)h[i].Score; Console.Error.WriteLine("#" + i + ": " + score.ToString(f) + " - " + d.Get("id") + " - " + d.Get("data")); } } } }
using System.Collections.Generic; using Chronic.Tags; using Chronic.Tags.Repeaters; namespace Chronic.Handlers { public class MyHandlerRegistry : HandlerRegistry { public MyHandlerRegistry() { RegisterTimeHandler(); RegisterDateHandlers(); RegisterAnchorHandlers(); RegisterArrowHandlers(); RegisterNarrowHandlers(); } void RegisterNarrowHandlers() { var handlers = new List<ComplexHandler>() { Handle .Required<Ordinal>() .Required<IRepeater>() .Required<Separator>() .Required<IRepeater>() .Using<ORSRHandler>(), Handle .Required<Ordinal>() .Required<IRepeater>() .Required<Grabber>() .Required<IRepeater>() .Using<ORGRHandler>(), Handle .Required<Grabber>() .Required<IRepeater>() .Required<Grabber>() .Required<IRepeater>() .Using<GRGRHandler>(), }; Add(HandlerType.Narrow, handlers); } void RegisterArrowHandlers() { var handlers = new List<ComplexHandler>() { Handle .Required<Scalar>() .Required<IRepeater>() .Required<Pointer>() .Using<SRPHandler>(), Handle .Required<Pointer>() .Required<Scalar>() .Required<IRepeater>() .Using<PSRHandler>(), Handle .Required<Scalar>() .Required<IRepeater>() .Required<Pointer>() .Required(HandlerType.Anchor) .Using<SRPAHandler>(), }; Add(HandlerType.Arrow, handlers); } void RegisterAnchorHandlers() { // tonight at 7pm var handlers = new List<ComplexHandler>() { Handle .Optional<Grabber>() .Required<IRepeater>() .Optional<SeparatorAt>() .Optional<IRepeater>() .Optional<IRepeater>() .Using<RHandler>(), Handle .Optional<Grabber>() .Required<IRepeater>() .Required<IRepeater>() .Optional<SeparatorAt>() .Optional<IRepeater>() .Optional<IRepeater>() .Using<RHandler>(), Handle .Required<IRepeater>() .Required<Grabber>() .Required<IRepeater>() .Using<RGRHandler>(), }; Add(HandlerType.Anchor, handlers); } void RegisterDateHandlers() { var dateHandlers = new List<ComplexHandler>() { Handle .Required<RepeaterDayName>() .Required<RepeaterMonthName>() .Required<ScalarDay>() .Using<RdnRmnSdHandler>(), Handle .Required<RepeaterDayName>() .Required<RepeaterMonthName>() .Required<OrdinalDay>() .Using<RdnRmnOdHandler>(), Handle .Required<RepeaterMonthName>() .Required<ScalarDay>() .Optional<SeparatorComma>() .Required<ScalarYear>() .Using<RmnSdSyHandler>(), Handle .Required<RepeaterMonthName>() .Required<OrdinalDay>() .Optional<SeparatorComma>() .Required<ScalarYear>() .Using<RmnOdSyHandler>(), Handle .Required<RepeaterMonthName>() .Required<ScalarDay>() .Required<ScalarYear>() .Optional<SeparatorAt>() .Optional(HandlerType.Time) .Using<RmnSdSyHandler>(), Handle .Required<RepeaterMonthName>() .Required<OrdinalDay>() .Required<ScalarYear>() .Optional<SeparatorAt>() .Optional(HandlerType.Time) .Using<RmnOdSyHandler>(), Handle .Required<RepeaterMonthName>() .Required<ScalarDay>() .Optional<SeparatorAt>() .Optional(HandlerType.Time) .Using<RmnSdHandler>(), Handle .Required<RepeaterTime>() .Optional<IRepeaterDayPortion>() .Optional<SeparatorOn>() .Required<RepeaterMonthName>() .Required<ScalarDay>() .Using<RmnSdOnHandler>(), Handle .Required<RepeaterMonthName>() .Required<OrdinalDay>() .Optional<SeparatorAt>() .Optional(HandlerType.Time) .Using<RmnOdHandler>(), Handle .Required<OrdinalDay>() .Required<RepeaterMonthName>() .Required<ScalarYear>() .Optional<SeparatorAt>() .Optional(HandlerType.Time) .Using<OdRmnSyHandler>(), Handle .Required<OrdinalDay>() .Required<RepeaterMonthName>() .Optional<SeparatorAt>() .Optional(HandlerType.Time) .Using<OdRmnHandler>(), Handle .Required<ScalarYear>() .Required<RepeaterMonthName>() .Required<OrdinalDay>() .Using<SyRmnOdHandler>(), Handle .Required<RepeaterTime>() .Optional<IRepeaterDayPortion>() .Optional<SeparatorOn>() .Required<RepeaterMonthName>() .Required<OrdinalDay>() .Using<RmnOdOnHandler>(), Handle .Required<RepeaterMonthName>() .Required<ScalarDay>() .Required<ScalarYear>() .Optional<SeparatorAt>() .Optional(HandlerType.Time) .Using<RmnSdSyHandler>(), Handle .Required<RepeaterMonthName>() .Required<ScalarYear>() .Using<RmnSyHandler>(), Handle .Required<ScalarDay>() .Required<RepeaterMonthName>() .Required<ScalarYear>() .Optional<SeparatorAt>() .Optional(HandlerType.Time) .Using<SdRmnSyHandler>(), Handle .Required<ScalarDay>() .Required<RepeaterMonthName>() .Optional<SeparatorAt>() .Optional(HandlerType.Time) .Using<SdRmnHandler>(), Handle .Required<ScalarYear>() .Required<SeparatorDate>() .Required<ScalarMonth>() .Required<SeparatorDate>() .Required<ScalarDay>() .Optional<SeparatorAt>() .Optional(HandlerType.Time) .Using<SySmSdHandler>(), Handle .Required<ScalarMonth>() .Required<SeparatorDate>() .Required<ScalarYear>() .Using<SmSyHandler>(), Handle .Required<Scalar>() .Required<IRepeater>() .Optional<SeparatorComma>() .Required<Pointer>() .Required(HandlerType.Anchor) .Required<SeparatorAt>() .Required(HandlerType.Time) .Using<SRPAHandler>(), Handle .Repeat(pattern => pattern .Required<Scalar>() .Required<IRepeater>() .Optional<SeparatorComma>() ).AnyNumberOfTimes() .Required<Pointer>() .Optional(HandlerType.Anchor) .Optional<SeparatorAt>() .Optional(HandlerType.Time) .Using<MultiSRHandler>(), //Handle // .Required<ScalarMonth>() // .Required<SeparatorDate>() // .Required<ScalarDay>() // .Using<SmSdHandler>(), //Handle // .Required<ScalarMonth>() // .Required<SeparatorDate>() // .Required<ScalarDay>() // .Required<SeparatorDate>() // .Required<ScalarYear>() // .Optional<SeparatorAt>() // .Optional(HandlerType.Time) // .Using<SmSdSyHandler>(), //Handle // .Required<ScalarDay>() // .Required<SeparatorDate>() // .Required<ScalarMonth>() // .Required<SeparatorDate>() // .Required<ScalarYear>() // .Optional<SeparatorAt>() // .Optional(HandlerType.Time) // .Using<SdSmSyHandler>(), }; Add(HandlerType.Date, dateHandlers); } void RegisterTimeHandler() { var timeHandlers = new List<ComplexHandler>() { Handle .Required<RepeaterTime>() .Optional<IRepeaterDayPortion>() .UsingNothing(), }; Add(HandlerType.Time, timeHandlers); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/api/servicecontrol/v1/distribution.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Api.Servicecontrol.V1 { /// <summary>Holder for reflection information generated from google/api/servicecontrol/v1/distribution.proto</summary> public static partial class DistributionReflection { #region Descriptor /// <summary>File descriptor for google/api/servicecontrol/v1/distribution.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static DistributionReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Ci9nb29nbGUvYXBpL3NlcnZpY2Vjb250cm9sL3YxL2Rpc3RyaWJ1dGlvbi5w", "cm90bxIcZ29vZ2xlLmFwaS5zZXJ2aWNlY29udHJvbC52MSLoBAoMRGlzdHJp", "YnV0aW9uEg0KBWNvdW50GAEgASgDEgwKBG1lYW4YAiABKAESDwoHbWluaW11", "bRgDIAEoARIPCgdtYXhpbXVtGAQgASgBEiAKGHN1bV9vZl9zcXVhcmVkX2Rl", "dmlhdGlvbhgFIAEoARIVCg1idWNrZXRfY291bnRzGAYgAygDElIKDmxpbmVh", "cl9idWNrZXRzGAcgASgLMjguZ29vZ2xlLmFwaS5zZXJ2aWNlY29udHJvbC52", "MS5EaXN0cmlidXRpb24uTGluZWFyQnVja2V0c0gAElwKE2V4cG9uZW50aWFs", "X2J1Y2tldHMYCCABKAsyPS5nb29nbGUuYXBpLnNlcnZpY2Vjb250cm9sLnYx", "LkRpc3RyaWJ1dGlvbi5FeHBvbmVudGlhbEJ1Y2tldHNIABJWChBleHBsaWNp", "dF9idWNrZXRzGAkgASgLMjouZ29vZ2xlLmFwaS5zZXJ2aWNlY29udHJvbC52", "MS5EaXN0cmlidXRpb24uRXhwbGljaXRCdWNrZXRzSAAaSgoNTGluZWFyQnVj", "a2V0cxIaChJudW1fZmluaXRlX2J1Y2tldHMYASABKAUSDQoFd2lkdGgYAiAB", "KAESDgoGb2Zmc2V0GAMgASgBGlYKEkV4cG9uZW50aWFsQnVja2V0cxIaChJu", "dW1fZmluaXRlX2J1Y2tldHMYASABKAUSFQoNZ3Jvd3RoX2ZhY3RvchgCIAEo", "ARINCgVzY2FsZRgDIAEoARohCg9FeHBsaWNpdEJ1Y2tldHMSDgoGYm91bmRz", "GAEgAygBQg8KDWJ1Y2tldF9vcHRpb25ChgEKIGNvbS5nb29nbGUuYXBpLnNl", "cnZpY2Vjb250cm9sLnYxQhFEaXN0cmlidXRpb25Qcm90b1ABWkpnb29nbGUu", "Z29sYW5nLm9yZy9nZW5wcm90by9nb29nbGVhcGlzL2FwaS9zZXJ2aWNlY29u", "dHJvbC92MTtzZXJ2aWNlY29udHJvbPgBAWIGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.Servicecontrol.V1.Distribution), global::Google.Api.Servicecontrol.V1.Distribution.Parser, new[]{ "Count", "Mean", "Minimum", "Maximum", "SumOfSquaredDeviation", "BucketCounts", "LinearBuckets", "ExponentialBuckets", "ExplicitBuckets" }, new[]{ "BucketOption" }, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.Servicecontrol.V1.Distribution.Types.LinearBuckets), global::Google.Api.Servicecontrol.V1.Distribution.Types.LinearBuckets.Parser, new[]{ "NumFiniteBuckets", "Width", "Offset" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.Servicecontrol.V1.Distribution.Types.ExponentialBuckets), global::Google.Api.Servicecontrol.V1.Distribution.Types.ExponentialBuckets.Parser, new[]{ "NumFiniteBuckets", "GrowthFactor", "Scale" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.Servicecontrol.V1.Distribution.Types.ExplicitBuckets), global::Google.Api.Servicecontrol.V1.Distribution.Types.ExplicitBuckets.Parser, new[]{ "Bounds" }, null, null, null)}) })); } #endregion } #region Messages /// <summary> /// Distribution represents a frequency distribution of double-valued sample /// points. It contains the size of the population of sample points plus /// additional optional information: /// /// - the arithmetic mean of the samples /// - the minimum and maximum of the samples /// - the sum-squared-deviation of the samples, used to compute variance /// - a histogram of the values of the sample points /// </summary> public sealed partial class Distribution : pb::IMessage<Distribution> { private static readonly pb::MessageParser<Distribution> _parser = new pb::MessageParser<Distribution>(() => new Distribution()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Distribution> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Api.Servicecontrol.V1.DistributionReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Distribution() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Distribution(Distribution other) : this() { count_ = other.count_; mean_ = other.mean_; minimum_ = other.minimum_; maximum_ = other.maximum_; sumOfSquaredDeviation_ = other.sumOfSquaredDeviation_; bucketCounts_ = other.bucketCounts_.Clone(); switch (other.BucketOptionCase) { case BucketOptionOneofCase.LinearBuckets: LinearBuckets = other.LinearBuckets.Clone(); break; case BucketOptionOneofCase.ExponentialBuckets: ExponentialBuckets = other.ExponentialBuckets.Clone(); break; case BucketOptionOneofCase.ExplicitBuckets: ExplicitBuckets = other.ExplicitBuckets.Clone(); break; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Distribution Clone() { return new Distribution(this); } /// <summary>Field number for the "count" field.</summary> public const int CountFieldNumber = 1; private long count_; /// <summary> /// The total number of samples in the distribution. Must be >= 0. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public long Count { get { return count_; } set { count_ = value; } } /// <summary>Field number for the "mean" field.</summary> public const int MeanFieldNumber = 2; private double mean_; /// <summary> /// The arithmetic mean of the samples in the distribution. If `count` is /// zero then this field must be zero. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public double Mean { get { return mean_; } set { mean_ = value; } } /// <summary>Field number for the "minimum" field.</summary> public const int MinimumFieldNumber = 3; private double minimum_; /// <summary> /// The minimum of the population of values. Ignored if `count` is zero. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public double Minimum { get { return minimum_; } set { minimum_ = value; } } /// <summary>Field number for the "maximum" field.</summary> public const int MaximumFieldNumber = 4; private double maximum_; /// <summary> /// The maximum of the population of values. Ignored if `count` is zero. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public double Maximum { get { return maximum_; } set { maximum_ = value; } } /// <summary>Field number for the "sum_of_squared_deviation" field.</summary> public const int SumOfSquaredDeviationFieldNumber = 5; private double sumOfSquaredDeviation_; /// <summary> /// The sum of squared deviations from the mean: /// Sum[i=1..count]((x_i - mean)^2) /// where each x_i is a sample values. If `count` is zero then this field /// must be zero, otherwise validation of the request fails. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public double SumOfSquaredDeviation { get { return sumOfSquaredDeviation_; } set { sumOfSquaredDeviation_ = value; } } /// <summary>Field number for the "bucket_counts" field.</summary> public const int BucketCountsFieldNumber = 6; private static readonly pb::FieldCodec<long> _repeated_bucketCounts_codec = pb::FieldCodec.ForInt64(50); private readonly pbc::RepeatedField<long> bucketCounts_ = new pbc::RepeatedField<long>(); /// <summary> /// The number of samples in each histogram bucket. `bucket_counts` are /// optional. If present, they must sum to the `count` value. /// /// The buckets are defined below in `bucket_option`. There are N buckets. /// `bucket_counts[0]` is the number of samples in the underflow bucket. /// `bucket_counts[1]` to `bucket_counts[N-1]` are the numbers of samples /// in each of the finite buckets. And `bucket_counts[N] is the number /// of samples in the overflow bucket. See the comments of `bucket_option` /// below for more details. /// /// Any suffix of trailing zeros may be omitted. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<long> BucketCounts { get { return bucketCounts_; } } /// <summary>Field number for the "linear_buckets" field.</summary> public const int LinearBucketsFieldNumber = 7; /// <summary> /// Buckets with constant width. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Api.Servicecontrol.V1.Distribution.Types.LinearBuckets LinearBuckets { get { return bucketOptionCase_ == BucketOptionOneofCase.LinearBuckets ? (global::Google.Api.Servicecontrol.V1.Distribution.Types.LinearBuckets) bucketOption_ : null; } set { bucketOption_ = value; bucketOptionCase_ = value == null ? BucketOptionOneofCase.None : BucketOptionOneofCase.LinearBuckets; } } /// <summary>Field number for the "exponential_buckets" field.</summary> public const int ExponentialBucketsFieldNumber = 8; /// <summary> /// Buckets with exponentially growing width. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Api.Servicecontrol.V1.Distribution.Types.ExponentialBuckets ExponentialBuckets { get { return bucketOptionCase_ == BucketOptionOneofCase.ExponentialBuckets ? (global::Google.Api.Servicecontrol.V1.Distribution.Types.ExponentialBuckets) bucketOption_ : null; } set { bucketOption_ = value; bucketOptionCase_ = value == null ? BucketOptionOneofCase.None : BucketOptionOneofCase.ExponentialBuckets; } } /// <summary>Field number for the "explicit_buckets" field.</summary> public const int ExplicitBucketsFieldNumber = 9; /// <summary> /// Buckets with arbitrary user-provided width. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Api.Servicecontrol.V1.Distribution.Types.ExplicitBuckets ExplicitBuckets { get { return bucketOptionCase_ == BucketOptionOneofCase.ExplicitBuckets ? (global::Google.Api.Servicecontrol.V1.Distribution.Types.ExplicitBuckets) bucketOption_ : null; } set { bucketOption_ = value; bucketOptionCase_ = value == null ? BucketOptionOneofCase.None : BucketOptionOneofCase.ExplicitBuckets; } } private object bucketOption_; /// <summary>Enum of possible cases for the "bucket_option" oneof.</summary> public enum BucketOptionOneofCase { None = 0, LinearBuckets = 7, ExponentialBuckets = 8, ExplicitBuckets = 9, } private BucketOptionOneofCase bucketOptionCase_ = BucketOptionOneofCase.None; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public BucketOptionOneofCase BucketOptionCase { get { return bucketOptionCase_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void ClearBucketOption() { bucketOptionCase_ = BucketOptionOneofCase.None; bucketOption_ = null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Distribution); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Distribution other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Count != other.Count) return false; if (Mean != other.Mean) return false; if (Minimum != other.Minimum) return false; if (Maximum != other.Maximum) return false; if (SumOfSquaredDeviation != other.SumOfSquaredDeviation) return false; if(!bucketCounts_.Equals(other.bucketCounts_)) return false; if (!object.Equals(LinearBuckets, other.LinearBuckets)) return false; if (!object.Equals(ExponentialBuckets, other.ExponentialBuckets)) return false; if (!object.Equals(ExplicitBuckets, other.ExplicitBuckets)) return false; if (BucketOptionCase != other.BucketOptionCase) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Count != 0L) hash ^= Count.GetHashCode(); if (Mean != 0D) hash ^= Mean.GetHashCode(); if (Minimum != 0D) hash ^= Minimum.GetHashCode(); if (Maximum != 0D) hash ^= Maximum.GetHashCode(); if (SumOfSquaredDeviation != 0D) hash ^= SumOfSquaredDeviation.GetHashCode(); hash ^= bucketCounts_.GetHashCode(); if (bucketOptionCase_ == BucketOptionOneofCase.LinearBuckets) hash ^= LinearBuckets.GetHashCode(); if (bucketOptionCase_ == BucketOptionOneofCase.ExponentialBuckets) hash ^= ExponentialBuckets.GetHashCode(); if (bucketOptionCase_ == BucketOptionOneofCase.ExplicitBuckets) hash ^= ExplicitBuckets.GetHashCode(); hash ^= (int) bucketOptionCase_; return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Count != 0L) { output.WriteRawTag(8); output.WriteInt64(Count); } if (Mean != 0D) { output.WriteRawTag(17); output.WriteDouble(Mean); } if (Minimum != 0D) { output.WriteRawTag(25); output.WriteDouble(Minimum); } if (Maximum != 0D) { output.WriteRawTag(33); output.WriteDouble(Maximum); } if (SumOfSquaredDeviation != 0D) { output.WriteRawTag(41); output.WriteDouble(SumOfSquaredDeviation); } bucketCounts_.WriteTo(output, _repeated_bucketCounts_codec); if (bucketOptionCase_ == BucketOptionOneofCase.LinearBuckets) { output.WriteRawTag(58); output.WriteMessage(LinearBuckets); } if (bucketOptionCase_ == BucketOptionOneofCase.ExponentialBuckets) { output.WriteRawTag(66); output.WriteMessage(ExponentialBuckets); } if (bucketOptionCase_ == BucketOptionOneofCase.ExplicitBuckets) { output.WriteRawTag(74); output.WriteMessage(ExplicitBuckets); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Count != 0L) { size += 1 + pb::CodedOutputStream.ComputeInt64Size(Count); } if (Mean != 0D) { size += 1 + 8; } if (Minimum != 0D) { size += 1 + 8; } if (Maximum != 0D) { size += 1 + 8; } if (SumOfSquaredDeviation != 0D) { size += 1 + 8; } size += bucketCounts_.CalculateSize(_repeated_bucketCounts_codec); if (bucketOptionCase_ == BucketOptionOneofCase.LinearBuckets) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(LinearBuckets); } if (bucketOptionCase_ == BucketOptionOneofCase.ExponentialBuckets) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(ExponentialBuckets); } if (bucketOptionCase_ == BucketOptionOneofCase.ExplicitBuckets) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(ExplicitBuckets); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Distribution other) { if (other == null) { return; } if (other.Count != 0L) { Count = other.Count; } if (other.Mean != 0D) { Mean = other.Mean; } if (other.Minimum != 0D) { Minimum = other.Minimum; } if (other.Maximum != 0D) { Maximum = other.Maximum; } if (other.SumOfSquaredDeviation != 0D) { SumOfSquaredDeviation = other.SumOfSquaredDeviation; } bucketCounts_.Add(other.bucketCounts_); switch (other.BucketOptionCase) { case BucketOptionOneofCase.LinearBuckets: LinearBuckets = other.LinearBuckets; break; case BucketOptionOneofCase.ExponentialBuckets: ExponentialBuckets = other.ExponentialBuckets; break; case BucketOptionOneofCase.ExplicitBuckets: ExplicitBuckets = other.ExplicitBuckets; break; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { Count = input.ReadInt64(); break; } case 17: { Mean = input.ReadDouble(); break; } case 25: { Minimum = input.ReadDouble(); break; } case 33: { Maximum = input.ReadDouble(); break; } case 41: { SumOfSquaredDeviation = input.ReadDouble(); break; } case 50: case 48: { bucketCounts_.AddEntriesFrom(input, _repeated_bucketCounts_codec); break; } case 58: { global::Google.Api.Servicecontrol.V1.Distribution.Types.LinearBuckets subBuilder = new global::Google.Api.Servicecontrol.V1.Distribution.Types.LinearBuckets(); if (bucketOptionCase_ == BucketOptionOneofCase.LinearBuckets) { subBuilder.MergeFrom(LinearBuckets); } input.ReadMessage(subBuilder); LinearBuckets = subBuilder; break; } case 66: { global::Google.Api.Servicecontrol.V1.Distribution.Types.ExponentialBuckets subBuilder = new global::Google.Api.Servicecontrol.V1.Distribution.Types.ExponentialBuckets(); if (bucketOptionCase_ == BucketOptionOneofCase.ExponentialBuckets) { subBuilder.MergeFrom(ExponentialBuckets); } input.ReadMessage(subBuilder); ExponentialBuckets = subBuilder; break; } case 74: { global::Google.Api.Servicecontrol.V1.Distribution.Types.ExplicitBuckets subBuilder = new global::Google.Api.Servicecontrol.V1.Distribution.Types.ExplicitBuckets(); if (bucketOptionCase_ == BucketOptionOneofCase.ExplicitBuckets) { subBuilder.MergeFrom(ExplicitBuckets); } input.ReadMessage(subBuilder); ExplicitBuckets = subBuilder; break; } } } } #region Nested types /// <summary>Container for nested types declared in the Distribution message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static partial class Types { /// <summary> /// Describing buckets with constant width. /// </summary> public sealed partial class LinearBuckets : pb::IMessage<LinearBuckets> { private static readonly pb::MessageParser<LinearBuckets> _parser = new pb::MessageParser<LinearBuckets>(() => new LinearBuckets()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<LinearBuckets> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Api.Servicecontrol.V1.Distribution.Descriptor.NestedTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public LinearBuckets() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public LinearBuckets(LinearBuckets other) : this() { numFiniteBuckets_ = other.numFiniteBuckets_; width_ = other.width_; offset_ = other.offset_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public LinearBuckets Clone() { return new LinearBuckets(this); } /// <summary>Field number for the "num_finite_buckets" field.</summary> public const int NumFiniteBucketsFieldNumber = 1; private int numFiniteBuckets_; /// <summary> /// The number of finite buckets. With the underflow and overflow buckets, /// the total number of buckets is `num_finite_buckets` + 2. /// See comments on `bucket_options` for details. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int NumFiniteBuckets { get { return numFiniteBuckets_; } set { numFiniteBuckets_ = value; } } /// <summary>Field number for the "width" field.</summary> public const int WidthFieldNumber = 2; private double width_; /// <summary> /// The i'th linear bucket covers the interval /// [offset + (i-1) * width, offset + i * width) /// where i ranges from 1 to num_finite_buckets, inclusive. /// Must be strictly positive. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public double Width { get { return width_; } set { width_ = value; } } /// <summary>Field number for the "offset" field.</summary> public const int OffsetFieldNumber = 3; private double offset_; /// <summary> /// The i'th linear bucket covers the interval /// [offset + (i-1) * width, offset + i * width) /// where i ranges from 1 to num_finite_buckets, inclusive. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public double Offset { get { return offset_; } set { offset_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as LinearBuckets); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(LinearBuckets other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (NumFiniteBuckets != other.NumFiniteBuckets) return false; if (Width != other.Width) return false; if (Offset != other.Offset) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (NumFiniteBuckets != 0) hash ^= NumFiniteBuckets.GetHashCode(); if (Width != 0D) hash ^= Width.GetHashCode(); if (Offset != 0D) hash ^= Offset.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (NumFiniteBuckets != 0) { output.WriteRawTag(8); output.WriteInt32(NumFiniteBuckets); } if (Width != 0D) { output.WriteRawTag(17); output.WriteDouble(Width); } if (Offset != 0D) { output.WriteRawTag(25); output.WriteDouble(Offset); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (NumFiniteBuckets != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(NumFiniteBuckets); } if (Width != 0D) { size += 1 + 8; } if (Offset != 0D) { size += 1 + 8; } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(LinearBuckets other) { if (other == null) { return; } if (other.NumFiniteBuckets != 0) { NumFiniteBuckets = other.NumFiniteBuckets; } if (other.Width != 0D) { Width = other.Width; } if (other.Offset != 0D) { Offset = other.Offset; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { NumFiniteBuckets = input.ReadInt32(); break; } case 17: { Width = input.ReadDouble(); break; } case 25: { Offset = input.ReadDouble(); break; } } } } } /// <summary> /// Describing buckets with exponentially growing width. /// </summary> public sealed partial class ExponentialBuckets : pb::IMessage<ExponentialBuckets> { private static readonly pb::MessageParser<ExponentialBuckets> _parser = new pb::MessageParser<ExponentialBuckets>(() => new ExponentialBuckets()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ExponentialBuckets> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Api.Servicecontrol.V1.Distribution.Descriptor.NestedTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ExponentialBuckets() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ExponentialBuckets(ExponentialBuckets other) : this() { numFiniteBuckets_ = other.numFiniteBuckets_; growthFactor_ = other.growthFactor_; scale_ = other.scale_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ExponentialBuckets Clone() { return new ExponentialBuckets(this); } /// <summary>Field number for the "num_finite_buckets" field.</summary> public const int NumFiniteBucketsFieldNumber = 1; private int numFiniteBuckets_; /// <summary> /// The number of finite buckets. With the underflow and overflow buckets, /// the total number of buckets is `num_finite_buckets` + 2. /// See comments on `bucket_options` for details. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int NumFiniteBuckets { get { return numFiniteBuckets_; } set { numFiniteBuckets_ = value; } } /// <summary>Field number for the "growth_factor" field.</summary> public const int GrowthFactorFieldNumber = 2; private double growthFactor_; /// <summary> /// The i'th exponential bucket covers the interval /// [scale * growth_factor^(i-1), scale * growth_factor^i) /// where i ranges from 1 to num_finite_buckets inclusive. /// Must be larger than 1.0. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public double GrowthFactor { get { return growthFactor_; } set { growthFactor_ = value; } } /// <summary>Field number for the "scale" field.</summary> public const int ScaleFieldNumber = 3; private double scale_; /// <summary> /// The i'th exponential bucket covers the interval /// [scale * growth_factor^(i-1), scale * growth_factor^i) /// where i ranges from 1 to num_finite_buckets inclusive. /// Must be > 0. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public double Scale { get { return scale_; } set { scale_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ExponentialBuckets); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ExponentialBuckets other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (NumFiniteBuckets != other.NumFiniteBuckets) return false; if (GrowthFactor != other.GrowthFactor) return false; if (Scale != other.Scale) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (NumFiniteBuckets != 0) hash ^= NumFiniteBuckets.GetHashCode(); if (GrowthFactor != 0D) hash ^= GrowthFactor.GetHashCode(); if (Scale != 0D) hash ^= Scale.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (NumFiniteBuckets != 0) { output.WriteRawTag(8); output.WriteInt32(NumFiniteBuckets); } if (GrowthFactor != 0D) { output.WriteRawTag(17); output.WriteDouble(GrowthFactor); } if (Scale != 0D) { output.WriteRawTag(25); output.WriteDouble(Scale); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (NumFiniteBuckets != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(NumFiniteBuckets); } if (GrowthFactor != 0D) { size += 1 + 8; } if (Scale != 0D) { size += 1 + 8; } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ExponentialBuckets other) { if (other == null) { return; } if (other.NumFiniteBuckets != 0) { NumFiniteBuckets = other.NumFiniteBuckets; } if (other.GrowthFactor != 0D) { GrowthFactor = other.GrowthFactor; } if (other.Scale != 0D) { Scale = other.Scale; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { NumFiniteBuckets = input.ReadInt32(); break; } case 17: { GrowthFactor = input.ReadDouble(); break; } case 25: { Scale = input.ReadDouble(); break; } } } } } /// <summary> /// Describing buckets with arbitrary user-provided width. /// </summary> public sealed partial class ExplicitBuckets : pb::IMessage<ExplicitBuckets> { private static readonly pb::MessageParser<ExplicitBuckets> _parser = new pb::MessageParser<ExplicitBuckets>(() => new ExplicitBuckets()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ExplicitBuckets> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Api.Servicecontrol.V1.Distribution.Descriptor.NestedTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ExplicitBuckets() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ExplicitBuckets(ExplicitBuckets other) : this() { bounds_ = other.bounds_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ExplicitBuckets Clone() { return new ExplicitBuckets(this); } /// <summary>Field number for the "bounds" field.</summary> public const int BoundsFieldNumber = 1; private static readonly pb::FieldCodec<double> _repeated_bounds_codec = pb::FieldCodec.ForDouble(10); private readonly pbc::RepeatedField<double> bounds_ = new pbc::RepeatedField<double>(); /// <summary> /// 'bound' is a list of strictly increasing boundaries between /// buckets. Note that a list of length N-1 defines N buckets because /// of fenceposting. See comments on `bucket_options` for details. /// /// The i'th finite bucket covers the interval /// [bound[i-1], bound[i]) /// where i ranges from 1 to bound_size() - 1. Note that there are no /// finite buckets at all if 'bound' only contains a single element; in /// that special case the single bound defines the boundary between the /// underflow and overflow buckets. /// /// bucket number lower bound upper bound /// i == 0 (underflow) -inf bound[i] /// 0 &lt; i &lt; bound_size() bound[i-1] bound[i] /// i == bound_size() (overflow) bound[i-1] +inf /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<double> Bounds { get { return bounds_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ExplicitBuckets); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ExplicitBuckets other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!bounds_.Equals(other.bounds_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= bounds_.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { bounds_.WriteTo(output, _repeated_bounds_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += bounds_.CalculateSize(_repeated_bounds_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ExplicitBuckets other) { if (other == null) { return; } bounds_.Add(other.bounds_); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: case 9: { bounds_.AddEntriesFrom(input, _repeated_bounds_codec); break; } } } } } } #endregion } #endregion } #endregion Designer generated code
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using Microsoft.Win32; namespace Microsoft.PythonTools.Analysis { public class AnalysisLimits { /// <summary> /// Returns a new set of limits, set to the defaults for analyzing user /// projects. /// </summary> public static AnalysisLimits GetDefaultLimits() { return new AnalysisLimits(); } /// <summary> /// Returns a new set of limits, set to the default for analyzing a /// standard library. /// </summary> public static AnalysisLimits GetStandardLibraryLimits() { var limits = new AnalysisLimits(); limits.CallDepth = 2; limits.DecreaseCallDepth = 20; limits.NormalArgumentTypes = 10; limits.ListArgumentTypes = 5; limits.DictArgumentTypes = 5; limits.ReturnTypes = 10; limits.YieldTypes = 10; limits.InstanceMembers = 5; limits.DictKeyTypes = 5; limits.DictValueTypes = 20; limits.IndexTypes = 5; limits.AssignedTypes = 50; limits.UnifyCallsToNew = true; limits.ProcessCustomDecorators = true; return limits; } private const string CallDepthId = "CallDepth"; private const string DecreaseCallDepthId = "DecreaseCallDepth"; private const string NormalArgumentTypesId = "NormalArgumentTypes"; private const string ListArgumentTypesId = "ListArgumentTypes"; private const string DictArgumentTypesId = "DictArgumentTypes"; private const string ReturnTypesId = "ReturnTypes"; private const string YieldTypesId = "YieldTypes"; private const string InstanceMembersId = "InstanceMembers"; private const string DictKeyTypesId = "DictKeyTypes"; private const string DictValueTypesId = "DictValueTypes"; private const string IndexTypesId = "IndexTypes"; private const string AssignedTypesId = "AssignedTypes"; private const string UnifyCallsToNewId = "UnifyCallsToNew"; private const string ProcessCustomDecoratorsId = "ProcessCustomDecorators"; /// <summary> /// Loads a new instance from the specified registry key. /// </summary> /// <param name="key"> /// The key to load settings from. Each setting is a DWORD value. If /// null, all settings are assumed to be unspecified and the default /// values are used. /// </param> /// <param name="defaultToStdLib"> /// If True, unspecified settings are taken from the defaults for /// standard library analysis. Otherwise, they are taken from the /// usual defaults. /// </param> public static AnalysisLimits LoadFromStorage(RegistryKey key, bool defaultToStdLib = false) { var limits = defaultToStdLib ? GetStandardLibraryLimits() : new AnalysisLimits(); if (key != null) { limits.CallDepth = (key.GetValue(CallDepthId) as int?) ?? limits.CallDepth; limits.DecreaseCallDepth = (key.GetValue(DecreaseCallDepthId) as int?) ?? limits.DecreaseCallDepth; limits.NormalArgumentTypes = (key.GetValue(NormalArgumentTypesId) as int?) ?? limits.NormalArgumentTypes; limits.ListArgumentTypes = (key.GetValue(ListArgumentTypesId) as int?) ?? limits.ListArgumentTypes; limits.DictArgumentTypes = (key.GetValue(DictArgumentTypesId) as int?) ?? limits.DictArgumentTypes; limits.ReturnTypes = (key.GetValue(ReturnTypesId) as int?) ?? limits.ReturnTypes; limits.YieldTypes = (key.GetValue(YieldTypesId) as int?) ?? limits.YieldTypes; limits.InstanceMembers = (key.GetValue(InstanceMembersId) as int?) ?? limits.InstanceMembers; limits.DictKeyTypes = (key.GetValue(DictKeyTypesId) as int?) ?? limits.DictKeyTypes; limits.DictValueTypes = (key.GetValue(DictValueTypesId) as int?) ?? limits.DictValueTypes; limits.IndexTypes = (key.GetValue(IndexTypesId) as int?) ?? limits.IndexTypes; limits.AssignedTypes = (key.GetValue(AssignedTypesId) as int?) ?? limits.AssignedTypes; limits.UnifyCallsToNew = ((key.GetValue(UnifyCallsToNewId) as int?) ?? (limits.UnifyCallsToNew ? 1 : 0)) != 0; limits.ProcessCustomDecorators = ((key.GetValue(ProcessCustomDecoratorsId) as int?) ?? (limits.ProcessCustomDecorators ? 1 : 0)) != 0; } return limits; } /// <summary> /// Saves the current instance's settings to the specified registry key. /// </summary> public void SaveToStorage(RegistryKey key) { key.SetValue(CallDepthId, CallDepth, RegistryValueKind.DWord); key.SetValue(DecreaseCallDepthId, DecreaseCallDepth, RegistryValueKind.DWord); key.SetValue(NormalArgumentTypesId, NormalArgumentTypes, RegistryValueKind.DWord); key.SetValue(ListArgumentTypesId, ListArgumentTypes, RegistryValueKind.DWord); key.SetValue(DictArgumentTypesId, DictArgumentTypes, RegistryValueKind.DWord); key.SetValue(ReturnTypesId, ReturnTypes, RegistryValueKind.DWord); key.SetValue(YieldTypesId, YieldTypes, RegistryValueKind.DWord); key.SetValue(InstanceMembersId, InstanceMembers, RegistryValueKind.DWord); key.SetValue(DictKeyTypesId, DictKeyTypes, RegistryValueKind.DWord); key.SetValue(DictValueTypesId, DictValueTypes, RegistryValueKind.DWord); key.SetValue(IndexTypesId, IndexTypes, RegistryValueKind.DWord); key.SetValue(AssignedTypesId, AssignedTypes, RegistryValueKind.DWord); key.SetValue(UnifyCallsToNewId, UnifyCallsToNew ? 1 : 0, RegistryValueKind.DWord); key.SetValue(ProcessCustomDecoratorsId, ProcessCustomDecorators ? 1 : 0, RegistryValueKind.DWord); } /// <summary> /// The key to use with ProjectEntry.Properties to override the call /// depth for functions in that module. /// </summary> public static readonly object CallDepthKey = new object(); public AnalysisLimits() { CallDepth = 3; DecreaseCallDepth = 30; NormalArgumentTypes = 50; ListArgumentTypes = 20; DictArgumentTypes = 20; ReturnTypes = 20; YieldTypes = 20; InstanceMembers = 50; DictKeyTypes = 10; DictValueTypes = 30; IndexTypes = 30; AssignedTypes = 100; ProcessCustomDecorators = true; } /// <summary> /// The maximum number of files which will be used for cross module /// analysis. /// /// If null, cross module analysis will not be limited. Otherwise, a /// value will cause cross module analysis to be disabled after that /// number of files have been loaded. /// </summary> public int? CrossModule { get; set; } /// <summary> /// The initial call stack depth to compare for reusing function /// analysis units. /// /// The minimum value (1) will produce one unit for each call site. /// Higher values take the callers of the function containing the call /// site into account. Calls outside of functions are unaffected. /// /// This value cannot vary during analysis. /// </summary> public int CallDepth { get; set; } /// <summary> /// The number of calls to a function at which to decrement the depth /// used to distinguish calls to that function. /// /// This value applies to all new calls following the last decrement. /// It is permitted to vary during analysis. /// </summary> public int DecreaseCallDepth { get; set; } /// <summary> /// The number of types in a normal argument at which to start /// combining similar types. /// </summary> public int NormalArgumentTypes { get; set; } /// <summary> /// The number of types in a list argument at which to start combining /// similar types. /// </summary> public int ListArgumentTypes { get; set; } /// <summary> /// The number of types in a dict argument at which to start combining /// similar types. /// </summary> public int DictArgumentTypes { get; set; } /// <summary> /// The number of types in a return value at which to start combining /// similar types. /// </summary> public int ReturnTypes { get; set; } /// <summary> /// The number of types in a yielded value at which to start combining /// similar types. /// </summary> public int YieldTypes { get; set; } /// <summary> /// The number of types in an instance attribute at which to start /// combining similar types. /// </summary> public int InstanceMembers { get; set; } /// <summary> /// True if calls to '__new__' should not be distinguished based on the /// call site. This applies to both implicit and explicit calls for /// user-defined '__new__' functions. /// </summary> public bool UnifyCallsToNew { get; set; } /// <summary> /// The number of keys in a dictionary at which to start combining /// similar types. /// </summary> public int DictKeyTypes { get; set; } /// <summary> /// The number of values in a dictionary entry at which to start /// combining similar types. Note that this applies to each value in a /// dictionary, not to all values at once. /// </summary> public int DictValueTypes { get; set; } /// <summary> /// The number of values in a collection at which to start combining /// similar types. This does not apply to dictionaries. /// </summary> public int IndexTypes { get; set; } /// <summary> /// The number of values in a normal variable at which to start /// combining similar types. This is only applied by assignment /// analysis. /// </summary> public int AssignedTypes { get; set; } /// <summary> /// True to evaluate custom decorators. If false, all decorators are /// assumed to return the original function unmodified. /// </summary> public bool ProcessCustomDecorators { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.Serialization; using Orleans.Runtime; namespace Orleans.Serialization { internal class ILSerializerGenerator { private static readonly RuntimeTypeHandle IntPtrTypeHandle = typeof(IntPtr).TypeHandle; private static readonly RuntimeTypeHandle UIntPtrTypeHandle = typeof(UIntPtr).TypeHandle; private static readonly Type DelegateType = typeof(Delegate); private static readonly Dictionary<RuntimeTypeHandle, SimpleTypeSerializer> DirectSerializers; private static readonly ReflectedSerializationMethodInfo SerializationMethodInfos = new ReflectedSerializationMethodInfo(); private static readonly DeepCopier ImmutableTypeCopier = (obj, context) => obj; private static readonly ILFieldBuilder FieldBuilder = new ILFieldBuilder(); static ILSerializerGenerator() { DirectSerializers = new Dictionary<RuntimeTypeHandle, SimpleTypeSerializer> { [typeof(int).TypeHandle] = new SimpleTypeSerializer(w => w.Write(default(int)), r => r.ReadInt()), [typeof(uint).TypeHandle] = new SimpleTypeSerializer(w => w.Write(default(uint)), r => r.ReadUInt()), [typeof(short).TypeHandle] = new SimpleTypeSerializer(w => w.Write(default(short)), r => r.ReadShort()), [typeof(ushort).TypeHandle] = new SimpleTypeSerializer(w => w.Write(default(ushort)), r => r.ReadUShort()), [typeof(long).TypeHandle] = new SimpleTypeSerializer(w => w.Write(default(long)), r => r.ReadLong()), [typeof(ulong).TypeHandle] = new SimpleTypeSerializer(w => w.Write(default(ulong)), r => r.ReadULong()), [typeof(byte).TypeHandle] = new SimpleTypeSerializer(w => w.Write(default(byte)), r => r.ReadByte()), [typeof(sbyte).TypeHandle] = new SimpleTypeSerializer(w => w.Write(default(sbyte)), r => r.ReadSByte()), [typeof(float).TypeHandle] = new SimpleTypeSerializer(w => w.Write(default(float)), r => r.ReadFloat()), [typeof(double).TypeHandle] = new SimpleTypeSerializer(w => w.Write(default(double)), r => r.ReadDouble()), [typeof(decimal).TypeHandle] = new SimpleTypeSerializer(w => w.Write(default(decimal)), r => r.ReadDecimal()), [typeof(string).TypeHandle] = new SimpleTypeSerializer(w => w.Write(default(string)), r => r.ReadString()), [typeof(char).TypeHandle] = new SimpleTypeSerializer(w => w.Write(default(char)), r => r.ReadChar()), [typeof(Guid).TypeHandle] = new SimpleTypeSerializer(w => w.Write(default(Guid)), r => r.ReadGuid()), [typeof(DateTime).TypeHandle] = new SimpleTypeSerializer(w => w.Write(default(DateTime)), r => r.ReadDateTime()), [typeof(TimeSpan).TypeHandle] = new SimpleTypeSerializer(w => w.Write(default(TimeSpan)), r => r.ReadTimeSpan()) }; } /// <summary> /// Returns a value indicating whether the provided <paramref name="type"/> is supported. /// </summary> /// <param name="type">The type.</param> /// <returns>A value indicating whether the provided <paramref name="type"/> is supported.</returns> public static bool IsSupportedType(Type type) { return !type.IsAbstract && !type.IsInterface && !type.IsArray && !type.IsEnum && IsSupportedFieldType(type); } /// <summary> /// Generates a serializer for the specified type. /// </summary> /// <param name="type">The type to generate the serializer for.</param> /// <param name="serializationFieldsFilter"> /// The predicate used in addition to the default logic to select which fields are included in serialization and deserialization. /// </param> /// <param name="copyFieldsFilter"> /// The predicate used in addition to the default logic to select which fields are included in copying. /// </param> /// <param name="fieldComparer">The comparer used to sort fields, or <see langword="null"/> to use the default.</param> /// <returns>The generated serializer.</returns> public SerializerMethods GenerateSerializer( Type type, Func<FieldInfo, bool> serializationFieldsFilter = null, Func<FieldInfo, bool> copyFieldsFilter = null, IComparer<FieldInfo> fieldComparer = null) { try { bool SerializationFieldFilter(FieldInfo field) => !field.IsNotSerialized() && (serializationFieldsFilter?.Invoke(field) ?? true); var serializationFields = this.GetFields(type, SerializationFieldFilter, fieldComparer); var callbacks = GetSerializationCallbacks(type); DeepCopier copier; if (type.IsOrleansShallowCopyable()) { copier = ImmutableTypeCopier; } else { var copyFields = this.GetFields(type, copyFieldsFilter, fieldComparer); copier = this.EmitCopier(type, copyFields).CreateDelegate(); } var serializer = this.EmitSerializer(type, serializationFields, callbacks); var deserializer = this.EmitDeserializer(type, serializationFields, callbacks); return new SerializerMethods( copier, serializer.CreateDelegate(), deserializer.CreateDelegate()); } catch (Exception exception) { throw new ILGenerationException($"Serializer generation failed for type {type}", exception); } } private ILDelegateBuilder<DeepCopier> EmitCopier(Type type, List<FieldInfo> fields) { var il = new ILDelegateBuilder<DeepCopier>( FieldBuilder, type.Name + "DeepCopier", SerializationMethodInfos.DeepCopierDelegate); // Declare local variables. var result = il.DeclareLocal(type); var typedInput = il.DeclareLocal(type); // Set the typed input variable from the method parameter. il.LoadArgument(0); il.CastOrUnbox(type); il.StoreLocal(typedInput); // Construct the result. il.CreateInstance(type, result, SerializationMethodInfos.GetUninitializedObject); // Record the object. il.LoadArgument(1); // Load 'context' parameter. il.LoadArgument(0); // Load 'original' parameter. il.LoadLocal(result); // Load 'result' local. il.BoxIfValueType(type); il.Call(SerializationMethodInfos.RecordObjectWhileCopying); // Copy each field. foreach (var field in fields) { // Load the field. il.LoadLocalAsReference(type, result); il.LoadLocal(typedInput); il.LoadField(field); // Deep-copy the field if needed, otherwise just leave it as-is. if (!field.FieldType.IsOrleansShallowCopyable()) { var copyMethod = SerializationMethodInfos.DeepCopyInner; il.BoxIfValueType(field.FieldType); il.LoadArgument(1); il.Call(copyMethod); il.CastOrUnbox(field.FieldType); } // Store the copy of the field on the result. il.StoreField(field); } il.LoadLocal(result); il.BoxIfValueType(type); il.Return(); return il; } private ILDelegateBuilder<Serializer> EmitSerializer(Type type, List<FieldInfo> fields, SerializationCallbacks callbacks) { var il = new ILDelegateBuilder<Serializer>( FieldBuilder, type.Name + "Serializer", SerializationMethodInfos.SerializerDelegate); // Declare local variables. var typedInput = il.DeclareLocal(type); var streamingContext = default(ILDelegateBuilder<Serializer>.Local); if (callbacks.OnSerializing != null || callbacks.OnSerialized != null) { streamingContext = il.DeclareLocal(typeof(StreamingContext)); il.LoadLocalAddress(streamingContext); il.LoadConstant((int) StreamingContextStates.All); il.LoadArgument(1); il.Call(typeof(StreamingContext).GetConstructor(new[] {typeof(StreamingContextStates), typeof(object)})); } // Set the typed input variable from the method parameter. il.LoadArgument(0); il.CastOrUnbox(type); il.StoreLocal(typedInput); if (callbacks.OnSerializing != null) { il.LoadLocalAsReference(type, typedInput); il.LoadLocal(streamingContext); il.Call(callbacks.OnSerializing); } // Serialize each field foreach (var field in fields) { var fieldType = field.FieldType; var typeHandle = field.FieldType.TypeHandle; if (fieldType.IsEnum) { typeHandle = fieldType.GetEnumUnderlyingType().TypeHandle; } if (DirectSerializers.TryGetValue(typeHandle, out var serializer)) { il.LoadArgument(1); il.Call(SerializationMethodInfos.GetStreamFromSerializationContext); il.LoadLocal(typedInput); il.LoadField(field); il.Call(serializer.WriteMethod); } else { var serializeMethod = SerializationMethodInfos.SerializeInner; // Load the field. il.LoadLocal(typedInput); il.LoadField(field); il.BoxIfValueType(field.FieldType); // Serialize the field. il.LoadArgument(1); il.LoadType(field.FieldType); il.Call(serializeMethod); } } if (callbacks.OnSerialized != null) { il.LoadLocalAsReference(type, typedInput); il.LoadLocal(streamingContext); il.Call(callbacks.OnSerialized); } il.Return(); return il; } private ILDelegateBuilder<Deserializer> EmitDeserializer(Type type, List<FieldInfo> fields, SerializationCallbacks callbacks) { var il = new ILDelegateBuilder<Deserializer>( FieldBuilder, type.Name + "Deserializer", SerializationMethodInfos.DeserializerDelegate); var streamingContext = default(ILDelegateBuilder<Deserializer>.Local); if (callbacks.OnDeserializing != null || callbacks.OnDeserialized != null) { streamingContext = il.DeclareLocal(typeof(StreamingContext)); il.LoadLocalAddress(streamingContext); il.LoadConstant((int) StreamingContextStates.All); il.LoadArgument(1); il.Call(typeof(StreamingContext).GetConstructor(new[] {typeof(StreamingContextStates), typeof(object)})); } // Declare local variables. var result = il.DeclareLocal(type); // Construct the result. il.CreateInstance(type, result, SerializationMethodInfos.GetUninitializedObject); // Record the object. il.LoadArgument(1); // Load the 'context' parameter. il.LoadLocal(result); il.BoxIfValueType(type); il.Call(SerializationMethodInfos.RecordObjectWhileDeserializing); if (callbacks.OnDeserializing != null) { il.LoadLocalAsReference(type, result); il.LoadLocal(streamingContext); il.Call(callbacks.OnDeserializing); } // Deserialize each field. foreach (var field in fields) { // Deserialize the field. var fieldType = field.FieldType; if (fieldType.IsEnum) { var typeHandle = fieldType.GetEnumUnderlyingType().TypeHandle; il.LoadLocalAsReference(type, result); il.LoadArgument(1); il.Call(SerializationMethodInfos.GetStreamFromDeserializationContext); il.Call(DirectSerializers[typeHandle].ReadMethod); il.StoreField(field); } else if (DirectSerializers.TryGetValue(field.FieldType.TypeHandle, out var serializer)) { il.LoadLocalAsReference(type, result); il.LoadArgument(1); il.Call(SerializationMethodInfos.GetStreamFromDeserializationContext); il.Call(serializer.ReadMethod); il.StoreField(field); } else { var deserializeMethod = SerializationMethodInfos.DeserializeInner; il.LoadLocalAsReference(type, result); il.LoadType(field.FieldType); il.LoadArgument(1); il.Call(deserializeMethod); // Store the value on the result. il.CastOrUnbox(field.FieldType); il.StoreField(field); } } if (callbacks.OnDeserialized != null) { il.LoadLocalAsReference(type, result); il.LoadLocal(streamingContext); il.Call(callbacks.OnDeserialized); } // If the type implements the IOnDeserialized lifecycle handler, call that method now. if (typeof(IOnDeserialized).IsAssignableFrom(type)) { il.LoadLocalAsReference(type, result); il.LoadArgument(1); var concreteMethod = GetConcreteMethod( type, TypeUtils.Method((IOnDeserialized i) => i.OnDeserialized(default(ISerializerContext)))); il.Call(concreteMethod); } // If the type implements the IDeserializationCallback lifecycle handler, call that method now. if (typeof(IDeserializationCallback).IsAssignableFrom(type)) { il.LoadLocalAsReference(type, result); il.LoadArgument(1); var concreteMethod = GetConcreteMethod( type, TypeUtils.Method((IDeserializationCallback i) => i.OnDeserialization(default(object)))); il.Call(concreteMethod); } il.LoadLocal(result); il.BoxIfValueType(type); il.Return(); return il; } private static MethodInfo GetConcreteMethod(Type type, MethodInfo interfaceMethod) { if (interfaceMethod == null) throw new ArgumentNullException(nameof(interfaceMethod)); var map = type.GetInterfaceMap(interfaceMethod.DeclaringType); var concreteMethod = default(MethodInfo); for (var i = 0; i < map.InterfaceMethods.Length; i++) { if (map.InterfaceMethods[i] == interfaceMethod) { concreteMethod = map.TargetMethods[i]; break; } } if (concreteMethod == null) { throw new InvalidOperationException( $"Unable to find implementation of method {interfaceMethod.DeclaringType}.{interfaceMethod} on type {type} while generating serializer."); } return concreteMethod; } private SerializationCallbacks GetSerializationCallbacks(Type type) { var result = new SerializationCallbacks(); foreach (var method in type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) { var parameters = method.GetParameters(); if (parameters.Length != 1) continue; if (parameters[0].ParameterType != typeof(StreamingContext)) continue; if (method.GetCustomAttribute<OnDeserializingAttribute>() != null) { result.OnDeserializing = method; } if (method.GetCustomAttribute<OnDeserializedAttribute>() != null) { result.OnDeserialized = method; } if (method.GetCustomAttribute<OnSerializingAttribute>() != null) { result.OnSerializing = method; } if (method.GetCustomAttribute<OnSerializedAttribute>() != null) { result.OnSerialized = method; } } return result; } private class SerializationCallbacks { public MethodInfo OnDeserializing { get; set; } public MethodInfo OnDeserialized { get; set; } public MethodInfo OnSerializing { get; set; } public MethodInfo OnSerialized { get; set; } } /// <summary> /// Returns a sorted list of the fields of the provided type. /// </summary> /// <param name="type">The type.</param> /// <param name="fieldFilter">The predicate used in addition to the default logic to select which fields are included.</param> /// <param name="fieldInfoComparer">The comparer used to sort fields, or <see langword="null"/> to use the default.</param> /// <returns>A sorted list of the fields of the provided type.</returns> private List<FieldInfo> GetFields( Type type, Func<FieldInfo, bool> fieldFilter = null, IComparer<FieldInfo> fieldInfoComparer = null) { var result = type.GetAllFields() .Where( field => !field.IsStatic && IsSupportedFieldType(field.FieldType) && (fieldFilter == null || fieldFilter(field))) .ToList(); result.Sort(fieldInfoComparer ?? FieldInfoComparer.Instance); return result; } /// <summary> /// Returns a value indicating whether the provided type is supported as a field by this class. /// </summary> /// <param name="type">The type.</param> /// <returns>A value indicating whether the provided type is supported as a field by this class.</returns> private static bool IsSupportedFieldType(Type type) { if (type.IsPointer || type.IsByRef) return false; var handle = type.TypeHandle; if (handle.Equals(IntPtrTypeHandle)) return false; if (handle.Equals(UIntPtrTypeHandle)) return false; if (DelegateType.IsAssignableFrom(type)) return false; return true; } /// <summary> /// A comparer for <see cref="FieldInfo"/> which compares by name. /// </summary> private class FieldInfoComparer : IComparer<FieldInfo> { /// <summary> /// Gets the singleton instance of this class. /// </summary> public static FieldInfoComparer Instance { get; } = new FieldInfoComparer(); public int Compare(FieldInfo x, FieldInfo y) { return string.Compare(x.Name, y.Name, StringComparison.Ordinal); } } private class SimpleTypeSerializer { public SimpleTypeSerializer( Expression<Action<IBinaryTokenStreamWriter>> write, Expression<Action<IBinaryTokenStreamReader>> read) { this.WriteMethod = TypeUtils.Method(write); this.ReadMethod = TypeUtils.Method(read); } public MethodInfo WriteMethod { get; } public MethodInfo ReadMethod { get; } } } }
namespace AngleSharp.Core.Tests.Html { using AngleSharp.Dom; using AngleSharp.Dom.Html; using NUnit.Framework; using System; /// <summary> /// Tests generated according to the W3C-Test.org page: /// http://www.w3c-test.org/html/semantics/forms/constraints/form-validation-validity-stepMismatch.html /// </summary> [TestFixture] public class ValidityStepMismatchTests { static IDocument Html(String code) { return code.ToHtmlDocument(); } [Test] public void TestStepmismatchInputDatetime1() { var document = Html(""); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "datetime"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("step", ""); element.Value = "2000-01-01T12:00:00Z"; Assert.AreEqual("datetime", element.Type); Assert.AreEqual(false, element.Validity.IsStepMismatch); } [Test] public void TestStepmismatchInputDatetime2() { var document = Html(""); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "datetime"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("step", "120"); element.Value = ""; Assert.AreEqual("datetime", element.Type); Assert.AreEqual(false, element.Validity.IsStepMismatch); } [Test] public void TestStepmismatchInputDatetime3() { var document = Html(""); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "datetime"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("step", "120"); element.Value = "2000-01-01T12:58Z"; Assert.AreEqual("datetime", element.Type); Assert.AreEqual(false, element.Validity.IsStepMismatch); } [Test] public void TestStepmismatchInputDatetime4() { var document = Html(""); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "datetime"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("step", "120"); element.Value = "2000-01-01T12:59Z"; Assert.AreEqual("datetime", element.Type); Assert.AreEqual(true, element.Validity.IsStepMismatch); } [Test] public void TestStepmismatchInputDatetimeLocal1() { var document = Html(""); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "datetime-local"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("step", ""); element.Value = "2000-01-01T12:00:00"; Assert.AreEqual("datetime-local", element.Type); Assert.AreEqual(false, element.Validity.IsStepMismatch); } [Test] public void TestStepmismatchInputDatetimeLocal2() { var document = Html(""); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "datetime-local"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("step", "120000"); element.Value = ""; Assert.AreEqual("datetime-local", element.Type); Assert.AreEqual(false, element.Validity.IsStepMismatch); } [Test] public void TestStepmismatchInputDatetimeLocal3() { var document = Html(""); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "datetime-local"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("step", "120000"); element.Value = "1970-01-01T12:02:00"; Assert.AreEqual("datetime-local", element.Type); Assert.AreEqual(true, element.Validity.IsStepMismatch); } [Test] public void TestStepmismatchInputDatetimeLocal4() { var document = Html(""); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "datetime-local"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("step", "120000"); element.Value = "1970-01-01T12:03:00"; Assert.AreEqual("datetime-local", element.Type); Assert.AreEqual(true, element.Validity.IsStepMismatch); } [Test] public void TestStepmismatchInputDate1() { var document = Html(""); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "date"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("step", ""); element.Value = "2000-01-01"; Assert.AreEqual("date", element.Type); Assert.AreEqual(false, element.Validity.IsStepMismatch); } [Test] public void TestStepmismatchInputDate2() { var document = Html(""); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "date"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("step", "2"); element.Value = ""; Assert.AreEqual("date", element.Type); Assert.AreEqual(false, element.Validity.IsStepMismatch); } [Test] public void TestStepmismatchInputDate3() { var document = Html(""); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "date"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("step", "2"); element.Value = "1970-01-02"; Assert.AreEqual("date", element.Type); Assert.AreEqual(true, element.Validity.IsStepMismatch); } [Test] public void TestStepmismatchInputDate4() { var document = Html(""); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "date"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("step", "2"); element.Value = "1970-01-03"; Assert.AreEqual("date", element.Type); Assert.AreEqual(false, element.Validity.IsStepMismatch); } [Test] public void TestStepmismatchInputMonth1() { var document = Html(""); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "month"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("step", ""); element.Value = "2000-01"; Assert.AreEqual("month", element.Type); Assert.AreEqual(false, element.Validity.IsStepMismatch); } [Test] public void TestStepmismatchInputMonth2() { var document = Html(""); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "month"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("step", "2"); element.Value = ""; Assert.AreEqual("month", element.Type); Assert.AreEqual(false, element.Validity.IsStepMismatch); } [Test] public void TestStepmismatchInputMonth3() { var document = Html(""); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "month"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("step", "2"); element.Value = "1970-03"; Assert.AreEqual("month", element.Type); Assert.AreEqual(false, element.Validity.IsStepMismatch); } [Test] public void TestStepmismatchInputMonth4() { var document = Html(""); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "month"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("step", "2"); element.Value = "1970-04"; Assert.AreEqual("month", element.Type); Assert.AreEqual(true, element.Validity.IsStepMismatch); } [Test] public void TestStepmismatchInputWeek1() { var document = Html(""); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "week"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("step", ""); element.Value = "1970-W01"; Assert.AreEqual("week", element.Type); Assert.AreEqual(false, element.Validity.IsStepMismatch); } [Test] public void TestStepmismatchInputWeek2() { var document = Html(""); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "week"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("step", "2"); element.Value = ""; Assert.AreEqual("week", element.Type); Assert.AreEqual(false, element.Validity.IsStepMismatch); } [Test] public void TestStepmismatchInputWeek3() { var document = Html(""); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "week"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("step", "2"); element.Value = "1970-W03"; Assert.AreEqual("week", element.Type); Assert.AreEqual(false, element.Validity.IsStepMismatch); } [Test] public void TestStepmismatchInputWeek4() { var document = Html(""); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "week"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("step", "2"); element.Value = "1970-W04"; Assert.AreEqual("week", element.Type); Assert.AreEqual(true, element.Validity.IsStepMismatch); } [Test] public void TestStepmismatchInputTime1() { var document = Html(""); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "time"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("step", ""); element.Value = "12:00:00"; Assert.AreEqual("time", element.Type); Assert.AreEqual(false, element.Validity.IsStepMismatch); } [Test] public void TestStepmismatchInputTime2() { var document = Html(""); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "time"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("step", "120"); element.Value = ""; Assert.AreEqual("time", element.Type); Assert.AreEqual(false, element.Validity.IsStepMismatch); } [Test] public void TestStepmismatchInputTime3() { var document = Html(""); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "time"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("step", "120"); element.Value = "12:02:00"; Assert.AreEqual("time", element.Type); Assert.AreEqual(false, element.Validity.IsStepMismatch); } [Test] public void TestStepmismatchInputTime4() { var document = Html(""); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "time"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("step", "120"); element.Value = "12:03:00"; Assert.AreEqual("time", element.Type); Assert.AreEqual(true, element.Validity.IsStepMismatch); } [Test] public void TestStepmismatchInputNumber1() { var document = Html(""); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "number"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("step", ""); element.Value = "1"; Assert.AreEqual("number", element.Type); Assert.AreEqual(false, element.Validity.IsStepMismatch); } [Test] public void TestStepmismatchInputNumber2() { var document = Html(""); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "number"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("step", "2"); element.Value = ""; Assert.AreEqual("number", element.Type); Assert.AreEqual(false, element.Validity.IsStepMismatch); } [Test] public void TestStepmismatchInputNumber3() { var document = Html(""); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "number"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("step", "2"); element.Value = "2"; Assert.AreEqual("number", element.Type); Assert.AreEqual(false, element.Validity.IsStepMismatch); } [Test] public void TestStepmismatchInputNumber4() { var document = Html(""); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "number"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("step", "2"); element.Value = "3"; Assert.AreEqual("number", element.Type); Assert.AreEqual(true, element.Validity.IsStepMismatch); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; namespace Wve { /// <summary> /// Custom DateTime picker that allows quick entry and editing of dates /// </summary> public partial class WveDatePicker : UserControl { /// <summary> /// text to show when user rests pointer over control's textbox part /// </summary> private string toolTipTextForTextbox = "T= today\r\nD= +day\r\nW= +week\r\nM= +month\r\nY= +year \r\nX= minim"; /// <summary> /// constructor for custom date time picker /// </summary> public WveDatePicker() { InitializeComponent(); textBoxDate.Text = ""; dateTimePicker1.Value = DateTimePicker.MinimumDateTime; toolTip1.SetToolTip(dateTimePicker1, toolTipTextForTextbox); } /// <summary> /// WveDatePicker's value, or DateTime.MinValue to represent 'null' /// </summary> public DateTime Value { get { //return DateTime.MinValue to indicate 'null' // which may be different from the picker's MinValue if (dateTimePicker1.Value == DateTimePicker.MinimumDateTime) { return DateTime.MinValue; } else { return dateTimePicker1.Value; } } set { //set to picker to MinimumDateTime to represent 'null' // if value is DateTime.MinValue, which may be different // from DateTimePicker.MinimumDateTime if ((value == DateTime.MinValue) || (value <= DateTimePicker.MinimumDateTime)) { dateTimePicker1.Value = DateTimePicker.MinimumDateTime; } else { dateTimePicker1.Value = value; } //this will fire event to show the value in the textbox } } /// <summary> /// occurs when user changes focus from the text box, which will usually /// be to go to the datetime picker /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void textBoxDate_Validating(object sender, CancelEventArgs e) { } /// <summary> /// occurs when value set by program or user /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void dateTimePicker1_ValueChanged(object sender, EventArgs e) { //show date in text box, or blank if null if (dateTimePicker1.Value == DateTimePicker.MinimumDateTime) { textBoxDate.Clear(); } else { textBoxDate.Text = dateTimePicker1.Value.ToShortDateString(); } //tell the world the value has changed if (this.ValueChanged != null) { ValueChanged(this, e); } } //make event raiser to show the world when value changes /// <summary> /// value of MM3DatePicker has changed /// </summary> public event EventHandler ValueChanged; //process keystrokes private void control_KeyDown(object sender, KeyEventArgs e) { } /* * not used because sometimes locks out subsequent keypresses; use keypress instead /// <summary> /// trap letters to alter date value /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void dateTimePicker1_KeyDown(object sender, KeyEventArgs e) { //allow numbers, dashes, etc, but // if key is alphabet, then process it and supress it so it won't print // note A=65, Z=90 if (e.KeyValue > 64 && e.KeyValue < 91) { //don't pass key to textbox e.SuppressKeyPress = true; //now process letters: //reset if x if (e.KeyCode == Keys.X) dateTimePicker1.Value = DateTimePicker.MinimumDateTime; //set to today if t else if (e.KeyCode == Keys.T) dateTimePicker1.Value = DateTime.Today; //subtract if tab key is down else if ((e.Modifiers & Keys.Shift) == Keys.Shift) { if (e.KeyCode == Keys.D) dateTimePicker1.Value = dateTimePicker1.Value.AddDays(-1); else if (e.KeyCode == Keys.W) dateTimePicker1.Value = dateTimePicker1.Value.AddDays(-7); else if (e.KeyCode == Keys.M) dateTimePicker1.Value = dateTimePicker1.Value.AddMonths(-1); else if (e.KeyCode == Keys.Y) dateTimePicker1.Value = dateTimePicker1.Value.AddYears(-1); } else //no tab { if (e.KeyCode == Keys.D) dateTimePicker1.Value = dateTimePicker1.Value.AddDays(1); else if (e.KeyCode == Keys.W) dateTimePicker1.Value = dateTimePicker1.Value.AddDays(7); else if (e.KeyCode == Keys.M) dateTimePicker1.Value = dateTimePicker1.Value.AddMonths(1); else if (e.KeyCode == Keys.Y) dateTimePicker1.Value = dateTimePicker1.Value.AddYears(1); } }//from if alphabet }*/ /// <summary> /// process alpha chars that have special meaning /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void dateTimePicker1_KeyPress(object sender, KeyPressEventArgs e) { //allow numbers, dashes, etc, but // if key is alphabet, then process it and supress it so it won't print // note A=65, Z=90 if (char.IsLetter(e.KeyChar)) { //don't pass key to other controls e.Handled = true; //now process letters: //reset if x if (e.KeyChar == 'x') dateTimePicker1.Value = DateTimePicker.MinimumDateTime; //set to today if t else if (e.KeyChar == 't') dateTimePicker1.Value = DateTime.Today; //subtract if tab key is down else if (e.KeyChar == 'D') dateTimePicker1.Value = dateTimePicker1.Value.AddDays(-1); else if (e.KeyChar == 'W') dateTimePicker1.Value = dateTimePicker1.Value.AddDays(-7); else if (e.KeyChar == 'M') dateTimePicker1.Value = dateTimePicker1.Value.AddMonths(-1); else if (e.KeyChar == 'Y') dateTimePicker1.Value = dateTimePicker1.Value.AddYears(-1); else if (e.KeyChar == 'd') dateTimePicker1.Value = dateTimePicker1.Value.AddDays(1); else if (e.KeyChar == 'w') dateTimePicker1.Value = dateTimePicker1.Value.AddDays(7); else if (e.KeyChar == 'm') dateTimePicker1.Value = dateTimePicker1.Value.AddMonths(1); else if (e.KeyChar == 'y') dateTimePicker1.Value = dateTimePicker1.Value.AddYears(1); }//from if alphabet } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Globalization; using System.Reflection; using System.IO; using Microsoft.CSharp; //using Microsoft.JScript; using Microsoft.VisualBasic; using log4net; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.ScriptEngine.Interfaces; using OpenMetaverse; namespace OpenSim.Region.ScriptEngine.Shared.CodeTools { public class Compiler : ICompiler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); // * Uses "LSL2Converter" to convert LSL to C# if necessary. // * Compiles C#-code into an assembly // * Returns assembly name ready for AppDomain load. // // Assembly is compiled using LSL_BaseClass as base. Look at debug C# code file created when LSL script is compiled for full details. // internal enum enumCompileType { lsl = 0, cs = 1, vb = 2, js = 3, yp = 4 } /// <summary> /// This contains number of lines WE use for header when compiling script. User will get error in line x-LinesToRemoveOnError when error occurs. /// </summary> public int LinesToRemoveOnError = 3; private enumCompileType DefaultCompileLanguage; private bool WriteScriptSourceToDebugFile; private bool CompileWithDebugInformation; private Dictionary<string, bool> AllowedCompilers = new Dictionary<string, bool>(StringComparer.CurrentCultureIgnoreCase); private Dictionary<string, enumCompileType> LanguageMapping = new Dictionary<string, enumCompileType>(StringComparer.CurrentCultureIgnoreCase); private string FilePrefix; private string ScriptEnginesPath = null; // mapping between LSL and C# line/column numbers private ICodeConverter LSL_Converter; private List<string> m_warnings = new List<string>(); // private object m_syncy = new object(); private static CSharpCodeProvider CScodeProvider = new CSharpCodeProvider(); private static VBCodeProvider VBcodeProvider = new VBCodeProvider(); // private static JScriptCodeProvider JScodeProvider = new JScriptCodeProvider(); private static CSharpCodeProvider YPcodeProvider = new CSharpCodeProvider(); // YP is translated into CSharp private static YP2CSConverter YP_Converter = new YP2CSConverter(); // private static int instanceID = new Random().Next(0, int.MaxValue); // Unique number to use on our compiled files private static UInt64 scriptCompileCounter = 0; // And a counter public IScriptEngine m_scriptEngine; private Dictionary<string, Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>> m_lineMaps = new Dictionary<string, Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>>(); public Compiler(IScriptEngine scriptEngine) { m_scriptEngine = scriptEngine;; ScriptEnginesPath = scriptEngine.ScriptEnginePath; ReadConfig(); } public bool in_startup = true; public void ReadConfig() { // Get some config WriteScriptSourceToDebugFile = m_scriptEngine.Config.GetBoolean("WriteScriptSourceToDebugFile", false); CompileWithDebugInformation = m_scriptEngine.Config.GetBoolean("CompileWithDebugInformation", true); // Get file prefix from scriptengine name and make it file system safe: FilePrefix = "CommonCompiler"; foreach (char c in Path.GetInvalidFileNameChars()) { FilePrefix = FilePrefix.Replace(c, '_'); } // First time we start? Delete old files if (in_startup) { in_startup = false; DeleteOldFiles(); } // Map name and enum type of our supported languages LanguageMapping.Add(enumCompileType.cs.ToString(), enumCompileType.cs); LanguageMapping.Add(enumCompileType.vb.ToString(), enumCompileType.vb); LanguageMapping.Add(enumCompileType.lsl.ToString(), enumCompileType.lsl); LanguageMapping.Add(enumCompileType.js.ToString(), enumCompileType.js); LanguageMapping.Add(enumCompileType.yp.ToString(), enumCompileType.yp); // Allowed compilers string allowComp = m_scriptEngine.Config.GetString("AllowedCompilers", "lsl"); AllowedCompilers.Clear(); #if DEBUG m_log.Debug("[Compiler]: Allowed languages: " + allowComp); #endif foreach (string strl in allowComp.Split(',')) { string strlan = strl.Trim(" \t".ToCharArray()).ToLower(); if (!LanguageMapping.ContainsKey(strlan)) { m_log.Error("[Compiler]: Config error. Compiler is unable to recognize language type \"" + strlan + "\" specified in \"AllowedCompilers\"."); } else { #if DEBUG //m_log.Debug("[Compiler]: Config OK. Compiler recognized language type \"" + strlan + "\" specified in \"AllowedCompilers\"."); #endif } AllowedCompilers.Add(strlan, true); } if (AllowedCompilers.Count == 0) m_log.Error("[Compiler]: Config error. Compiler could not recognize any language in \"AllowedCompilers\". Scripts will not be executed!"); // Default language string defaultCompileLanguage = m_scriptEngine.Config.GetString("DefaultCompileLanguage", "lsl").ToLower(); // Is this language recognized at all? if (!LanguageMapping.ContainsKey(defaultCompileLanguage)) { m_log.Error("[Compiler]: " + "Config error. Default language \"" + defaultCompileLanguage + "\" specified in \"DefaultCompileLanguage\" is not recognized as a valid language. Changing default to: \"lsl\"."); defaultCompileLanguage = "lsl"; } // Is this language in allow-list? if (!AllowedCompilers.ContainsKey(defaultCompileLanguage)) { m_log.Error("[Compiler]: " + "Config error. Default language \"" + defaultCompileLanguage + "\"specified in \"DefaultCompileLanguage\" is not in list of \"AllowedCompilers\". Scripts may not be executed!"); } else { #if DEBUG // m_log.Debug("[Compiler]: " + // "Config OK. Default language \"" + defaultCompileLanguage + "\" specified in \"DefaultCompileLanguage\" is recognized as a valid language."); #endif // LANGUAGE IS IN ALLOW-LIST DefaultCompileLanguage = LanguageMapping[defaultCompileLanguage]; } // We now have an allow-list, a mapping list, and a default language } /// <summary> /// Delete old script files /// </summary> private void DeleteOldFiles() { // CREATE FOLDER IF IT DOESNT EXIST if (!Directory.Exists(ScriptEnginesPath)) { try { Directory.CreateDirectory(ScriptEnginesPath); } catch (Exception ex) { m_log.Error("[Compiler]: Exception trying to create ScriptEngine directory \"" + ScriptEnginesPath + "\": " + ex.ToString()); } } if (!Directory.Exists(Path.Combine(ScriptEnginesPath, m_scriptEngine.World.RegionInfo.RegionID.ToString()))) { try { Directory.CreateDirectory(Path.Combine(ScriptEnginesPath, m_scriptEngine.World.RegionInfo.RegionID.ToString())); } catch (Exception ex) { m_log.Error("[Compiler]: Exception trying to create ScriptEngine directory \"" + Path.Combine(ScriptEnginesPath, m_scriptEngine.World.RegionInfo.RegionID.ToString()) + "\": " + ex.ToString()); } } foreach (string file in Directory.GetFiles(Path.Combine(ScriptEnginesPath, m_scriptEngine.World.RegionInfo.RegionID.ToString()), FilePrefix + "_compiled*")) { try { File.Delete(file); } catch (Exception ex) { m_log.Error("[Compiler]: Exception trying delete old script file \"" + file + "\": " + ex.ToString()); } } foreach (string file in Directory.GetFiles(Path.Combine(ScriptEnginesPath, m_scriptEngine.World.RegionInfo.RegionID.ToString()), FilePrefix + "_source*")) { try { File.Delete(file); } catch (Exception ex) { m_log.Error("[Compiler]: Exception trying delete old script file \"" + file + "\": " + ex.ToString()); } } } ////private ICodeCompiler icc = codeProvider.CreateCompiler(); //public string CompileFromFile(string LSOFileName) //{ // switch (Path.GetExtension(LSOFileName).ToLower()) // { // case ".txt": // case ".lsl": // Common.ScriptEngineBase.Shared.SendToDebug("Source code is LSL, converting to CS"); // return CompileFromLSLText(File.ReadAllText(LSOFileName)); // case ".cs": // Common.ScriptEngineBase.Shared.SendToDebug("Source code is CS"); // return CompileFromCSText(File.ReadAllText(LSOFileName)); // default: // throw new Exception("Unknown script type."); // } //} public string GetCompilerOutput(string assetID) { return Path.Combine(ScriptEnginesPath, Path.Combine( m_scriptEngine.World.RegionInfo.RegionID.ToString(), FilePrefix + "_compiled_" + assetID + ".dll")); } public string GetCompilerOutput(UUID assetID) { return GetCompilerOutput(assetID.ToString()); } /// <summary> /// Converts script from LSL to CS and calls CompileFromCSText /// </summary> /// <param name="Script">LSL script</param> /// <returns>Filename to .dll assembly</returns> public void PerformScriptCompile(string Script, string asset, UUID ownerUUID, out string assembly, out Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> linemap) { linemap = null; m_warnings.Clear(); assembly = GetCompilerOutput(asset); if (!Directory.Exists(ScriptEnginesPath)) { try { Directory.CreateDirectory(ScriptEnginesPath); } catch (Exception) { } } if (!Directory.Exists(Path.Combine(ScriptEnginesPath, m_scriptEngine.World.RegionInfo.RegionID.ToString()))) { try { Directory.CreateDirectory(ScriptEnginesPath); } catch (Exception) { } } // Don't recompile if we already have it // Performing 3 file exists tests for every script can still be slow if (File.Exists(assembly) && File.Exists(assembly + ".text") && File.Exists(assembly + ".map")) { // If we have already read this linemap file, then it will be in our dictionary. // Don't build another copy of the dictionary (saves memory) and certainly // don't keep reading the same file from disk multiple times. if (!m_lineMaps.ContainsKey(assembly)) m_lineMaps[assembly] = ReadMapFile(assembly + ".map"); linemap = m_lineMaps[assembly]; return; } if (Script == String.Empty) { throw new Exception("Cannot find script assembly and no script text present"); } enumCompileType language = DefaultCompileLanguage; if (Script.StartsWith("//c#", true, CultureInfo.InvariantCulture)) language = enumCompileType.cs; if (Script.StartsWith("//vb", true, CultureInfo.InvariantCulture)) { language = enumCompileType.vb; // We need to remove //vb, it won't compile with that Script = Script.Substring(4, Script.Length - 4); } if (Script.StartsWith("//lsl", true, CultureInfo.InvariantCulture)) language = enumCompileType.lsl; if (Script.StartsWith("//js", true, CultureInfo.InvariantCulture)) language = enumCompileType.js; if (Script.StartsWith("//yp", true, CultureInfo.InvariantCulture)) language = enumCompileType.yp; if (!AllowedCompilers.ContainsKey(language.ToString())) { // Not allowed to compile to this language! string errtext = String.Empty; errtext += "The compiler for language \"" + language.ToString() + "\" is not in list of allowed compilers. Script will not be executed!"; throw new Exception(errtext); } if (m_scriptEngine.World.Permissions.CanCompileScript(ownerUUID, (int)language) == false) { // Not allowed to compile to this language! string errtext = String.Empty; errtext += ownerUUID + " is not in list of allowed users for this scripting language. Script will not be executed!"; throw new Exception(errtext); } string compileScript = Script; if (language == enumCompileType.lsl) { // Its LSL, convert it to C# LSL_Converter = (ICodeConverter)new CSCodeGenerator(); compileScript = LSL_Converter.Convert(Script); // copy converter warnings into our warnings. foreach (string warning in LSL_Converter.GetWarnings()) { AddWarning(warning); } linemap = ((CSCodeGenerator)LSL_Converter).PositionMap; // Write the linemap to a file and save it in our dictionary for next time. m_lineMaps[assembly] = linemap; WriteMapFile(assembly + ".map", linemap); } if (language == enumCompileType.yp) { // Its YP, convert it to C# compileScript = YP_Converter.Convert(Script); } switch (language) { case enumCompileType.cs: case enumCompileType.lsl: compileScript = CreateCSCompilerScript(compileScript); break; case enumCompileType.vb: compileScript = CreateVBCompilerScript(compileScript); break; // case enumCompileType.js: // compileScript = CreateJSCompilerScript(compileScript); // break; case enumCompileType.yp: compileScript = CreateYPCompilerScript(compileScript); break; } assembly = CompileFromDotNetText(compileScript, language, asset, assembly); return; } public string[] GetWarnings() { return m_warnings.ToArray(); } private void AddWarning(string warning) { if (!m_warnings.Contains(warning)) { m_warnings.Add(warning); } } // private static string CreateJSCompilerScript(string compileScript) // { // compileScript = String.Empty + // "import OpenSim.Region.ScriptEngine.Shared; import System.Collections.Generic;\r\n" + // "package SecondLife {\r\n" + // "class Script extends OpenSim.Region.ScriptEngine.Shared.ScriptBase.ScriptBaseClass { \r\n" + // compileScript + // "} }\r\n"; // return compileScript; // } private static string CreateCSCompilerScript(string compileScript) { compileScript = String.Empty + "using OpenSim.Region.ScriptEngine.Shared; using System.Collections.Generic;\r\n" + String.Empty + "namespace SecondLife { " + String.Empty + "public class Script : OpenSim.Region.ScriptEngine.Shared.ScriptBase.ScriptBaseClass { \r\n" + @"public Script() { } " + compileScript + "} }\r\n"; return compileScript; } private static string CreateYPCompilerScript(string compileScript) { compileScript = String.Empty + "using OpenSim.Region.ScriptEngine.Shared.YieldProlog; " + "using OpenSim.Region.ScriptEngine.Shared; using System.Collections.Generic;\r\n" + String.Empty + "namespace SecondLife { " + String.Empty + "public class Script : OpenSim.Region.ScriptEngine.Shared.ScriptBase.ScriptBaseClass { \r\n" + //@"public Script() { } " + @"static OpenSim.Region.ScriptEngine.Shared.YieldProlog.YP YP=null; " + @"public Script() { YP= new OpenSim.Region.ScriptEngine.Shared.YieldProlog.YP(); } " + compileScript + "} }\r\n"; return compileScript; } private static string CreateVBCompilerScript(string compileScript) { compileScript = String.Empty + "Imports OpenSim.Region.ScriptEngine.Shared: Imports System.Collections.Generic: " + String.Empty + "NameSpace SecondLife:" + String.Empty + "Public Class Script: Inherits OpenSim.Region.ScriptEngine.Shared.ScriptBase.ScriptBaseClass: " + "\r\nPublic Sub New()\r\nEnd Sub: " + compileScript + ":End Class :End Namespace\r\n"; return compileScript; } /// <summary> /// Compile .NET script to .Net assembly (.dll) /// </summary> /// <param name="Script">CS script</param> /// <returns>Filename to .dll assembly</returns> internal string CompileFromDotNetText(string Script, enumCompileType lang, string asset, string assembly) { string ext = "." + lang.ToString(); // Output assembly name scriptCompileCounter++; try { File.Delete(assembly); } catch (Exception e) // NOTLEGIT - Should be just FileIOException { throw new Exception("Unable to delete old existing " + "script-file before writing new. Compile aborted: " + e.ToString()); } // DEBUG - write source to disk if (WriteScriptSourceToDebugFile) { string srcFileName = FilePrefix + "_source_" + Path.GetFileNameWithoutExtension(assembly) + ext; try { File.WriteAllText(Path.Combine(Path.Combine( ScriptEnginesPath, m_scriptEngine.World.RegionInfo.RegionID.ToString()), srcFileName), Script); } catch (Exception ex) //NOTLEGIT - Should be just FileIOException { m_log.Error("[Compiler]: Exception while " + "trying to write script source to file \"" + srcFileName + "\": " + ex.ToString()); } } // Do actual compile CompilerParameters parameters = new CompilerParameters(); parameters.IncludeDebugInformation = true; string rootPath = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory); parameters.ReferencedAssemblies.Add(Path.Combine(rootPath, "OpenSim.Region.ScriptEngine.Shared.dll")); parameters.ReferencedAssemblies.Add(Path.Combine(rootPath, "OpenSim.Region.ScriptEngine.Shared.Api.Runtime.dll")); if (lang == enumCompileType.yp) { parameters.ReferencedAssemblies.Add(Path.Combine(rootPath, "OpenSim.Region.ScriptEngine.Shared.YieldProlog.dll")); } parameters.GenerateExecutable = false; parameters.OutputAssembly = assembly; parameters.IncludeDebugInformation = CompileWithDebugInformation; //parameters.WarningLevel = 1; // Should be 4? parameters.TreatWarningsAsErrors = false; CompilerResults results; switch (lang) { case enumCompileType.vb: results = VBcodeProvider.CompileAssemblyFromSource( parameters, Script); break; case enumCompileType.cs: case enumCompileType.lsl: bool complete = false; bool retried = false; do { lock (CScodeProvider) { results = CScodeProvider.CompileAssemblyFromSource( parameters, Script); } // Deal with an occasional segv in the compiler. // Rarely, if ever, occurs twice in succession. // Line # == 0 and no file name are indications that // this is a native stack trace rather than a normal // error log. if (results.Errors.Count > 0) { if (!retried && (results.Errors[0].FileName == null || results.Errors[0].FileName == String.Empty) && results.Errors[0].Line == 0) { // System.Console.WriteLine("retrying failed compilation"); retried = true; } else { complete = true; } } else { complete = true; } } while (!complete); break; // case enumCompileType.js: // results = JScodeProvider.CompileAssemblyFromSource( // parameters, Script); // break; case enumCompileType.yp: results = YPcodeProvider.CompileAssemblyFromSource( parameters, Script); break; default: throw new Exception("Compiler is not able to recongnize " + "language type \"" + lang.ToString() + "\""); } // Check result // Go through errors // // WARNINGS AND ERRORS // bool hadErrors = false; string errtext = String.Empty; if (results.Errors.Count > 0) { foreach (CompilerError CompErr in results.Errors) { string severity = CompErr.IsWarning ? "Warning" : "Error"; KeyValuePair<int, int> lslPos; // Show 5 errors max, but check entire list for errors if (severity == "Error") { lslPos = FindErrorPosition(CompErr.Line, CompErr.Column, m_lineMaps[assembly]); string text = CompErr.ErrorText; // Use LSL type names if (lang == enumCompileType.lsl) text = ReplaceTypes(CompErr.ErrorText); // The Second Life viewer's script editor begins // countingn lines and columns at 0, so we subtract 1. errtext += String.Format("({0},{1}): {4} {2}: {3}\n", lslPos.Key - 1, lslPos.Value - 1, CompErr.ErrorNumber, text, severity); hadErrors = true; } } } if (hadErrors) { throw new Exception(errtext); } // On today's highly asynchronous systems, the result of // the compile may not be immediately apparent. Wait a // reasonable amount of time before giving up on it. if (!File.Exists(assembly)) { for (int i = 0; i < 20 && !File.Exists(assembly); i++) { System.Threading.Thread.Sleep(250); } // One final chance... if (!File.Exists(assembly)) { errtext = String.Empty; errtext += "No compile error. But not able to locate compiled file."; throw new Exception(errtext); } } // m_log.DebugFormat("[Compiler] Compiled new assembly "+ // "for {0}", asset); // Because windows likes to perform exclusive locks, we simply // write out a textual representation of the file here // // Read the binary file into a buffer // FileInfo fi = new FileInfo(assembly); if (fi == null) { errtext = String.Empty; errtext += "No compile error. But not able to stat file."; throw new Exception(errtext); } Byte[] data = new Byte[fi.Length]; try { FileStream fs = File.Open(assembly, FileMode.Open, FileAccess.Read); fs.Read(data, 0, data.Length); fs.Close(); } catch (Exception) { errtext = String.Empty; errtext += "No compile error. But not able to open file."; throw new Exception(errtext); } // Convert to base64 // string filetext = System.Convert.ToBase64String(data); System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding(); Byte[] buf = enc.GetBytes(filetext); FileStream sfs = File.Create(assembly + ".text"); sfs.Write(buf, 0, buf.Length); sfs.Close(); return assembly; } private class kvpSorter : IComparer<KeyValuePair<int, int>> { public int Compare(KeyValuePair<int, int> a, KeyValuePair<int, int> b) { return a.Key.CompareTo(b.Key); } } public static KeyValuePair<int, int> FindErrorPosition(int line, int col, Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> positionMap) { if (positionMap == null || positionMap.Count == 0) return new KeyValuePair<int, int>(line, col); KeyValuePair<int, int> ret = new KeyValuePair<int, int>(); if (positionMap.TryGetValue(new KeyValuePair<int, int>(line, col), out ret)) return ret; List<KeyValuePair<int, int>> sorted = new List<KeyValuePair<int, int>>(positionMap.Keys); sorted.Sort(new kvpSorter()); int l = 1; int c = 1; foreach (KeyValuePair<int, int> cspos in sorted) { if (cspos.Key >= line) { if (cspos.Key > line) return new KeyValuePair<int, int>(l, c); if (cspos.Value > col) return new KeyValuePair<int, int>(l, c); c = cspos.Value; if (c == 0) c++; } else { l = cspos.Key; } } return new KeyValuePair<int, int>(l, c); } string ReplaceTypes(string message) { message = message.Replace( "OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString", "string"); message = message.Replace( "OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger", "integer"); message = message.Replace( "OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat", "float"); message = message.Replace( "OpenSim.Region.ScriptEngine.Shared.LSL_Types.list", "list"); return message; } private static void WriteMapFile(string filename, Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> linemap) { string mapstring = String.Empty; foreach (KeyValuePair<KeyValuePair<int, int>, KeyValuePair<int, int>> kvp in linemap) { KeyValuePair<int, int> k = kvp.Key; KeyValuePair<int, int> v = kvp.Value; mapstring += String.Format("{0},{1},{2},{3}\n", k.Key, k.Value, v.Key, v.Value); } System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding(); Byte[] mapbytes = enc.GetBytes(mapstring); FileStream mfs = File.Create(filename); mfs.Write(mapbytes, 0, mapbytes.Length); mfs.Close(); } private static Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> ReadMapFile(string filename) { Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> linemap; try { StreamReader r = File.OpenText(filename); linemap = new Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>(); string line; while ((line = r.ReadLine()) != null) { String[] parts = line.Split(new Char[] { ',' }); int kk = System.Convert.ToInt32(parts[0]); int kv = System.Convert.ToInt32(parts[1]); int vk = System.Convert.ToInt32(parts[2]); int vv = System.Convert.ToInt32(parts[3]); KeyValuePair<int, int> k = new KeyValuePair<int, int>(kk, kv); KeyValuePair<int, int> v = new KeyValuePair<int, int>(vk, vv); linemap[k] = v; } } catch { linemap = new Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>(); } return linemap; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using static Elasticsearch.Net.AuditEvent; namespace Elasticsearch.Net { public class RequestPipeline : IRequestPipeline { private readonly IConnectionConfigurationValues _settings; private readonly IConnection _connection; private readonly IConnectionPool _connectionPool; private readonly IDateTimeProvider _dateTimeProvider; private readonly IMemoryStreamFactory _memoryStreamFactory; private IRequestParameters RequestParameters { get; } private IRequestConfiguration RequestConfiguration { get; } public DateTime StartedOn { get; } public List<Audit> AuditTrail { get; } = new List<Audit>(); private int _retried = 0; public int Retried => _retried; public RequestPipeline( IConnectionConfigurationValues configurationValues, IDateTimeProvider dateTimeProvider, IMemoryStreamFactory memoryStreamFactory, IRequestParameters requestParameters) { this._settings = configurationValues; this._connectionPool = this._settings.ConnectionPool; this._connection = this._settings.Connection; this._dateTimeProvider = dateTimeProvider; this._memoryStreamFactory = memoryStreamFactory; this.RequestParameters = requestParameters; this.RequestConfiguration = requestParameters?.RequestConfiguration; this.StartedOn = dateTimeProvider.Now(); } public int MaxRetries => this.RequestConfiguration?.ForceNode != null ? 0 : Math.Min(this.RequestConfiguration?.MaxRetries ?? this._settings.MaxRetries.GetValueOrDefault(int.MaxValue), this._connectionPool.MaxRetries); public bool FirstPoolUsageNeedsSniffing => (!this.RequestConfiguration?.DisableSniff).GetValueOrDefault(true) && this._connectionPool.SupportsReseeding && this._settings.SniffsOnStartup && !this._connectionPool.SniffedOnStartup; public bool SniffsOnConnectionFailure => (!this.RequestConfiguration?.DisableSniff).GetValueOrDefault(true) && this._connectionPool.SupportsReseeding && this._settings.SniffsOnConnectionFault; public bool SniffsOnStaleCluster => (!this.RequestConfiguration?.DisableSniff).GetValueOrDefault(true) && this._connectionPool.SupportsReseeding && this._settings.SniffInformationLifeSpan.HasValue; public bool StaleClusterState { get { if (!SniffsOnStaleCluster) return false; // ReSharper disable once PossibleInvalidOperationException // already checked by SniffsOnStaleCluster var sniffLifeSpan = this._settings.SniffInformationLifeSpan.Value; var now = this._dateTimeProvider.Now(); var lastSniff = this._connectionPool.LastUpdate; return sniffLifeSpan < (now - lastSniff); } } private bool PingDisabled(Node node) => (this.RequestConfiguration?.DisablePing).GetValueOrDefault(false) || this._settings.DisablePings || !this._connectionPool.SupportsPinging || !node.IsResurrected; TimeSpan PingTimeout => this.RequestConfiguration?.PingTimeout ?? this._settings.PingTimeout ?? (this._connectionPool.UsingSsl ? ConnectionConfiguration.DefaultPingTimeoutOnSSL : ConnectionConfiguration.DefaultPingTimeout); TimeSpan RequestTimeout => this.RequestConfiguration?.RequestTimeout ?? this._settings.RequestTimeout; public bool IsTakingTooLong { get { var timeout = this._settings.MaxRetryTimeout.GetValueOrDefault(this.RequestTimeout); var now = this._dateTimeProvider.Now(); //we apply a soft margin so that if a request timesout at 59 seconds when the maximum is 60 we also abort. var margin = (timeout.TotalMilliseconds / 100.0) * 98; var marginTimeSpan = TimeSpan.FromMilliseconds(margin); var timespanCall = (now - this.StartedOn); var tookToLong = timespanCall >= marginTimeSpan; return tookToLong; } } public bool Refresh { get; private set; } public bool DepleededRetries => this.Retried >= this.MaxRetries + 1 || this.IsTakingTooLong; private Auditable Audit(AuditEvent type) => new Auditable(type, this.AuditTrail, this._dateTimeProvider); public void MarkDead(Node node) { var deadUntil = this._dateTimeProvider.DeadTime(node.FailedAttempts, this._settings.DeadTimeout, this._settings.MaxDeadTimeout); node.MarkDead(deadUntil); this._retried++; } public void MarkAlive(Node node) => node.MarkAlive(); public void FirstPoolUsage(SemaphoreSlim semaphore) { if (!this.FirstPoolUsageNeedsSniffing) return; if (!semaphore.Wait(this._settings.RequestTimeout)) throw new PipelineException(PipelineFailure.CouldNotStartSniffOnStartup, (Exception)null); if (!this.FirstPoolUsageNeedsSniffing) return; try { using (this.Audit(SniffOnStartup)) { this.Sniff(); this._connectionPool.SniffedOnStartup = true; } } finally { semaphore.Release(); } } public async Task FirstPoolUsageAsync(SemaphoreSlim semaphore, CancellationToken cancellationToken) { if (!this.FirstPoolUsageNeedsSniffing) return; var success = await semaphore.WaitAsync(this._settings.RequestTimeout, cancellationToken).ConfigureAwait(false); if (!success) throw new PipelineException(PipelineFailure.CouldNotStartSniffOnStartup, (Exception)null); if (!this.FirstPoolUsageNeedsSniffing) return; try { using (this.Audit(SniffOnStartup)) { await this.SniffAsync(cancellationToken).ConfigureAwait(false); this._connectionPool.SniffedOnStartup = true; } } finally { semaphore.Release(); } } public void SniffOnStaleCluster() { if (!StaleClusterState) return; using (this.Audit(AuditEvent.SniffOnStaleCluster)) { this.Sniff(); this._connectionPool.SniffedOnStartup = true; } } public async Task SniffOnStaleClusterAsync(CancellationToken cancellationToken) { if (!StaleClusterState) return; using (this.Audit(AuditEvent.SniffOnStaleCluster)) { await this.SniffAsync(cancellationToken).ConfigureAwait(false); this._connectionPool.SniffedOnStartup = true; } } public IEnumerable<Node> NextNode() { if (this.RequestConfiguration?.ForceNode != null) { yield return new Node(this.RequestConfiguration.ForceNode); yield break; } //This for loop allows to break out of the view state machine if we need to //force a refresh (after reseeding connectionpool). We have a hardcoded limit of only //allowing 100 of these refreshes per call var refreshed = false; for (var i = 0; i < 100; i++) { if (this.DepleededRetries) yield break; foreach (var node in this._connectionPool .CreateView((e, n)=> { using (new Auditable(e, this.AuditTrail, this._dateTimeProvider) { Node = n }) {} }) .TakeWhile(node => !this.DepleededRetries)) { yield return node; if (!this.Refresh) continue; this.Refresh = false; refreshed = true; break; } //unless a refresh was requested we will not iterate over more then a single view. //keep in mind refreshes are also still bound to overall maxretry count/timeout. if (!refreshed) break; } } private RequestData CreatePingRequestData(Node node, Auditable audit) { audit.Node = node; var requestOverrides = new RequestConfiguration { PingTimeout = this.PingTimeout, RequestTimeout = this.RequestTimeout, BasicAuthenticationCredentials = this._settings.BasicAuthenticationCredentials, EnableHttpPipelining = this.RequestConfiguration?.EnableHttpPipelining ?? this._settings.HttpPipeliningEnabled, ForceNode = this.RequestConfiguration?.ForceNode }; IRequestParameters requestParameters = new RootNodeInfoRequestParameters { }; requestParameters.RequestConfiguration = requestOverrides; return new RequestData(HttpMethod.HEAD, "/", null, this._settings, requestParameters, this._memoryStreamFactory) { Node = node }; } public void Ping(Node node) { if (PingDisabled(node)) return; using (var audit = this.Audit(PingSuccess)) { try { var pingData = CreatePingRequestData(node, audit); var response = this._connection.Request<VoidResponse>(pingData); ThrowBadAuthPipelineExceptionWhenNeeded(response); //ping should not silently accept bad but valid http responses if (!response.Success) throw new PipelineException(pingData.OnFailurePipelineFailure) { Response = response }; } catch (Exception e) { var response = (e as PipelineException)?.Response; audit.Event = PingFailure; audit.Exception = e; throw new PipelineException(PipelineFailure.PingFailure, e) { Response = response }; } } } public async Task PingAsync(Node node, CancellationToken cancellationToken) { if (PingDisabled(node)) return; using (var audit = this.Audit(PingSuccess)) { try { var pingData = CreatePingRequestData(node, audit); var response = await this._connection.RequestAsync<VoidResponse>(pingData, cancellationToken).ConfigureAwait(false); ThrowBadAuthPipelineExceptionWhenNeeded(response); //ping should not silently accept bad but valid http responses if (!response.Success) throw new PipelineException(pingData.OnFailurePipelineFailure) { Response = response }; } catch (Exception e) { var response = (e as PipelineException)?.Response; audit.Event = PingFailure; audit.Exception = e; throw new PipelineException(PipelineFailure.PingFailure, e) { Response = response }; } } } private void ThrowBadAuthPipelineExceptionWhenNeeded(IApiCallDetails response) { if (response.HttpStatusCode == 401) throw new PipelineException(PipelineFailure.BadAuthentication, response.OriginalException) { Response = response }; } public string SniffPath => "_nodes/_all/settings?flat_settings&timeout=" + this.PingTimeout.ToTimeUnit(); public IEnumerable<Node> SniffNodes => this._connectionPool .CreateView((e, n)=> { using (new Auditable(e, this.AuditTrail, this._dateTimeProvider) { Node = n }) {} }) .ToList() .OrderBy(n => n.MasterEligible ? n.Uri.Port : int.MaxValue); public void SniffOnConnectionFailure() { if (!this.SniffsOnConnectionFailure) return; using (this.Audit(SniffOnFail)) this.Sniff(); } public async Task SniffOnConnectionFailureAsync(CancellationToken cancellationToken) { if (!this.SniffsOnConnectionFailure) return; using (this.Audit(SniffOnFail)) await this.SniffAsync(cancellationToken).ConfigureAwait(false); } public void Sniff() { var path = this.SniffPath; var exceptions = new List<Exception>(); foreach (var node in this.SniffNodes) { using (var audit = this.Audit(SniffSuccess)) { audit.Node = node; try { var requestData = new RequestData(HttpMethod.GET, path, null, this._settings, (IRequestParameters)null, this._memoryStreamFactory) { Node = node }; var response = this._connection.Request<SniffResponse>(requestData); ThrowBadAuthPipelineExceptionWhenNeeded(response); //sniff should not silently accept bad but valid http responses if (!response.Success) throw new PipelineException(requestData.OnFailurePipelineFailure) { Response = response }; var nodes = response.Body.ToNodes(this._connectionPool.UsingSsl); this._connectionPool.Reseed(nodes); this.Refresh = true; return; } catch (Exception e) { audit.Event = SniffFailure; audit.Exception = e; exceptions.Add(e); continue; } } } throw new PipelineException(PipelineFailure.SniffFailure, new AggregateException(exceptions)); } public async Task SniffAsync(CancellationToken cancellationToken) { var path = this.SniffPath; var exceptions = new List<Exception>(); foreach (var node in this.SniffNodes) { using (var audit = this.Audit(SniffSuccess)) { audit.Node = node; try { var requestData = new RequestData(HttpMethod.GET, path, null, this._settings, (IRequestParameters)null, this._memoryStreamFactory) { Node = node }; var response = await this._connection.RequestAsync<SniffResponse>(requestData, cancellationToken).ConfigureAwait(false); ThrowBadAuthPipelineExceptionWhenNeeded(response); //sniff should not silently accept bad but valid http responses if (!response.Success) throw new PipelineException(requestData.OnFailurePipelineFailure) { Response = response }; this._connectionPool.Reseed(response.Body.ToNodes(this._connectionPool.UsingSsl)); this.Refresh = true; return; } catch (Exception e) { audit.Event = SniffFailure; audit.Exception = e; exceptions.Add(e); continue; } } } throw new PipelineException(PipelineFailure.SniffFailure, new AggregateException(exceptions)); } public ElasticsearchResponse<TReturn> CallElasticsearch<TReturn>(RequestData requestData) where TReturn : class { using (var audit = this.Audit(HealthyResponse)) { audit.Node = requestData.Node; audit.Path = requestData.Path; ElasticsearchResponse<TReturn> response = null; try { response = this._connection.Request<TReturn>(requestData); response.AuditTrail = this.AuditTrail; ThrowBadAuthPipelineExceptionWhenNeeded(response); if (!response.Success) audit.Event = requestData.OnFailureAuditEvent; return response; } catch (Exception e) { (response as ElasticsearchResponse<Stream>)?.Body?.Dispose(); audit.Event = requestData.OnFailureAuditEvent; audit.Exception = e; throw; } } } public async Task<ElasticsearchResponse<TReturn>> CallElasticsearchAsync<TReturn>(RequestData requestData, CancellationToken cancellationToken) where TReturn : class { using (var audit = this.Audit(HealthyResponse)) { audit.Node = requestData.Node; audit.Path = requestData.Path; ElasticsearchResponse<TReturn> response = null; try { response = await this._connection.RequestAsync<TReturn>(requestData, cancellationToken).ConfigureAwait(false); response.AuditTrail = this.AuditTrail; ThrowBadAuthPipelineExceptionWhenNeeded(response); if (!response.Success) audit.Event = requestData.OnFailureAuditEvent; return response; } catch (Exception e) { (response as ElasticsearchResponse<Stream>)?.Body?.Dispose(); audit.Event = requestData.OnFailureAuditEvent; audit.Exception = e; throw; } } } public void BadResponse<TReturn>(ref ElasticsearchResponse<TReturn> response, RequestData data, List<PipelineException> pipelineExceptions) where TReturn : class { var callDetails = response ?? pipelineExceptions.LastOrDefault()?.Response; var pipelineFailure = data.OnFailurePipelineFailure; if (pipelineExceptions.HasAny()) pipelineFailure = pipelineExceptions.Last().FailureReason; var innerException = pipelineExceptions.HasAny() ? new AggregateException(pipelineExceptions) : callDetails?.OriginalException; var exceptionMessage = innerException?.Message ?? "Could not complete the request to Elasticsearch."; if (this.IsTakingTooLong) { pipelineFailure = PipelineFailure.MaxTimeoutReached; this.Audit(MaxTimeoutReached); exceptionMessage = "Maximum timout reached while retrying request"; } else if (this.Retried >= this.MaxRetries && this.MaxRetries > 0) { pipelineFailure = PipelineFailure.MaxRetriesReached; this.Audit(MaxRetriesReached); exceptionMessage = "Maximum number of retries reached."; } var clientException = new ElasticsearchClientException(pipelineFailure, exceptionMessage, innerException) { Request = data, Response = callDetails, AuditTrail = this.AuditTrail }; if (_settings.ThrowExceptions) { this._settings.OnRequestCompleted?.Invoke(clientException.Response); throw clientException; } if (response == null) { response = new ResponseBuilder<TReturn>(data) { StatusCode = callDetails?.HttpStatusCode, Exception = clientException }.ToResponse(); } if (callDetails?.ResponseBodyInBytes != null && response.ResponseBodyInBytes == null) response.ResponseBodyInBytes = callDetails.ResponseBodyInBytes; if (callDetails?.ServerError != null && response.ServerError == null) response.ServerError = callDetails.ServerError; response.AuditTrail = this.AuditTrail; } void IDisposable.Dispose() => this.Dispose(); protected virtual void Dispose() { } } }
//------------------------------------------------------------------------------ // <copyright file="Roles.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.Security { using System.Web; using System.Web.Configuration; using System.Web.Management; using System.Security.Principal; using System.Security.Permissions; using System.Globalization; using System.Runtime.Serialization; using System.Collections; using System.Configuration.Provider; using System.Configuration; using System.Web.Hosting; using System.Threading; using System.Web.Util; using System.Collections.Specialized; using System.Web.Compilation; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> // This has no hosting permission demands because of DevDiv Bugs 31461: ClientAppSvcs: ASP.net Provider support static public class Roles { static public RoleProvider Provider { get { EnsureEnabled(); if (s_Provider == null) { throw new InvalidOperationException(SR.GetString(SR.Def_role_provider_not_found)); } return s_Provider; } } static public RoleProviderCollection Providers { get { EnsureEnabled(); return s_Providers;} } static public string CookieName { get { Initialize(); return s_CookieName; }} static public bool CacheRolesInCookie { get { Initialize(); return s_CacheRolesInCookie; }} static public int CookieTimeout { get { Initialize(); return s_CookieTimeout; }} static public string CookiePath { get { Initialize(); return s_CookiePath; }} static public bool CookieRequireSSL { get { Initialize(); return s_CookieRequireSSL; }} static public bool CookieSlidingExpiration { get { Initialize(); return s_CookieSlidingExpiration; }} static public CookieProtection CookieProtectionValue { get { Initialize(); return s_CookieProtection; }} static public bool CreatePersistentCookie { get { Initialize(); return s_CreatePersistentCookie; } } static public string Domain { get { Initialize(); return s_Domain; } } static public int MaxCachedResults { get { Initialize(); return s_MaxCachedResults; } } static public bool Enabled { get { if (HostingEnvironment.IsHosted && !HttpRuntime.HasAspNetHostingPermission(AspNetHostingPermissionLevel.Low)) return false; if (!s_Initialized && !s_EnabledSet) { RoleManagerSection config = RuntimeConfig.GetAppConfig().RoleManager; s_Enabled = config.Enabled; s_EnabledSet = true; } return s_Enabled; } set { BuildManager.ThrowIfPreAppStartNotRunning(); s_Enabled = value; s_EnabledSet = true; } } static public string ApplicationName { get { return Provider.ApplicationName; } set { Provider.ApplicationName = value; } } // authorization static public bool IsUserInRole(string username, string roleName) { if (HostingEnvironment.IsHosted && EtwTrace.IsTraceEnabled(EtwTraceLevel.Information, EtwTraceFlags.AppSvc) && HttpContext.Current != null) EtwTrace.Trace(EtwTraceType.ETW_TYPE_ROLE_BEGIN, HttpContext.Current.WorkerRequest); EnsureEnabled(); bool isUserInRole = false; bool isRolePrincipal = false; try { SecUtility.CheckParameter(ref roleName, true, true, true, 0, "roleName"); SecUtility.CheckParameter(ref username, true, false, true, 0, "username"); if (username.Length < 1) return false; IPrincipal user = GetCurrentUser(); if (user != null && user is RolePrincipal && ((RolePrincipal)user).ProviderName == Provider.Name && StringUtil.EqualsIgnoreCase(username, user.Identity.Name)) isUserInRole = user.IsInRole(roleName); else isUserInRole = Provider.IsUserInRole(username, roleName); return isUserInRole; } finally { if (HostingEnvironment.IsHosted && EtwTrace.IsTraceEnabled(EtwTraceLevel.Information, EtwTraceFlags.AppSvc) && HttpContext.Current != null) { if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.AppSvc)) { string status = SR.Resources.GetString(isUserInRole ? SR.Etw_Success : SR.Etw_Failure, CultureInfo.InstalledUICulture); EtwTrace.Trace(EtwTraceType.ETW_TYPE_ROLE_IS_USER_IN_ROLE, HttpContext.Current.WorkerRequest, isRolePrincipal ? "RolePrincipal" : Provider.GetType().FullName, username, roleName, status); } EtwTrace.Trace(EtwTraceType.ETW_TYPE_ROLE_END, HttpContext.Current.WorkerRequest, isRolePrincipal ? "RolePrincipal" : Provider.GetType().FullName, username); } } } static public bool IsUserInRole(string roleName) { return IsUserInRole(GetCurrentUserName(), roleName); } static public string[] GetRolesForUser (string username){ if (HostingEnvironment.IsHosted && EtwTrace.IsTraceEnabled(EtwTraceLevel.Information, EtwTraceFlags.AppSvc) && HttpContext.Current != null) EtwTrace.Trace(EtwTraceType.ETW_TYPE_ROLE_BEGIN, HttpContext.Current.WorkerRequest); EnsureEnabled(); string[] roles = null; bool isRolePrincipal = false; try { SecUtility.CheckParameter(ref username, true, false, true, 0, "username"); if (username.Length < 1) { roles = new string[0]; return roles; } IPrincipal user = GetCurrentUser(); if (user != null && user is RolePrincipal && ((RolePrincipal)user).ProviderName == Provider.Name && StringUtil.EqualsIgnoreCase(username, user.Identity.Name)) { roles = ((RolePrincipal)user).GetRoles(); isRolePrincipal = true; } else { roles = Provider.GetRolesForUser(username); } return roles; } finally { if (HostingEnvironment.IsHosted && EtwTrace.IsTraceEnabled(EtwTraceLevel.Information, EtwTraceFlags.AppSvc) && HttpContext.Current != null) { if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.AppSvc)) { string roleNames = null; if (roles != null && roles.Length > 0) roleNames = roles[0]; for (int i = 1; i < roles.Length; i++) roleNames += "," + roles[i]; EtwTrace.Trace(EtwTraceType.ETW_TYPE_ROLE_GET_USER_ROLES, HttpContext.Current.WorkerRequest, isRolePrincipal ? "RolePrincipal" : Provider.GetType().FullName, username, roleNames, null); } EtwTrace.Trace(EtwTraceType.ETW_TYPE_ROLE_END, HttpContext.Current.WorkerRequest, isRolePrincipal ? "RolePrincipal" : Provider.GetType().FullName, username); } } } static public string[] GetRolesForUser (){ return GetRolesForUser(GetCurrentUserName()); } // role administration // static public string[] GetUsersInRole(string roleName){ EnsureEnabled(); SecUtility.CheckParameter(ref roleName, true, true, true, 0, "roleName"); return Provider.GetUsersInRole(roleName); } static public void CreateRole(string roleName){ EnsureEnabled(); SecUtility.CheckParameter(ref roleName, true, true, true, 0, "roleName"); Provider.CreateRole(roleName); } static public bool DeleteRole(string roleName, bool throwOnPopulatedRole){ EnsureEnabled(); SecUtility.CheckParameter(ref roleName, true, true, true, 0, "roleName"); bool roleDeleted = Provider.DeleteRole(roleName, throwOnPopulatedRole); try { RolePrincipal user = GetCurrentUser() as RolePrincipal; if (user != null && user.ProviderName == Provider.Name && user.IsRoleListCached && user.IsInRole(roleName)) user.SetDirty(); } catch { } return roleDeleted; } static public bool DeleteRole(string roleName) { return DeleteRole(roleName, true); } static public bool RoleExists(string roleName){ EnsureEnabled(); SecUtility.CheckParameter(ref roleName, true, true, true, 0, "roleName"); return Provider.RoleExists(roleName); } static public void AddUserToRole(string username, string roleName){ EnsureEnabled(); SecUtility.CheckParameter(ref roleName, true, true, true, 0, "roleName"); SecUtility.CheckParameter(ref username, true, true, true, 0, "username"); Provider.AddUsersToRoles(new string [] {username}, new string [] {roleName}); try { RolePrincipal user = GetCurrentUser() as RolePrincipal; if (user != null && user.ProviderName == Provider.Name && user.IsRoleListCached && StringUtil.EqualsIgnoreCase(user.Identity.Name, username)) user.SetDirty(); } catch { } } static public void AddUserToRoles(string username, string[] roleNames){ EnsureEnabled(); SecUtility.CheckParameter(ref username, true, true, true, 0, "username"); SecUtility.CheckArrayParameter( ref roleNames, true, true, true, 0, "roleNames"); Provider.AddUsersToRoles(new string [] {username}, roleNames); try { RolePrincipal user = GetCurrentUser() as RolePrincipal; if (user != null && user.ProviderName == Provider.Name && user.IsRoleListCached && StringUtil.EqualsIgnoreCase(user.Identity.Name, username)) user.SetDirty(); } catch { } } static public void AddUsersToRole(string[] usernames, string roleName){ EnsureEnabled(); SecUtility.CheckParameter(ref roleName, true, true, true, 0, "roleName"); SecUtility.CheckArrayParameter( ref usernames, true, true, true, 0, "usernames"); Provider.AddUsersToRoles(usernames, new string [] {roleName}); try { RolePrincipal user = GetCurrentUser() as RolePrincipal; if (user != null && user.ProviderName == Provider.Name && user.IsRoleListCached) foreach(string username in usernames) if (StringUtil.EqualsIgnoreCase(user.Identity.Name, username)) { user.SetDirty(); break; } } catch { } } static public void AddUsersToRoles(string[] usernames, string [] roleNames){ EnsureEnabled(); SecUtility.CheckArrayParameter( ref roleNames, true, true, true, 0, "roleNames"); SecUtility.CheckArrayParameter( ref usernames, true, true, true, 0, "usernames"); Provider.AddUsersToRoles(usernames, roleNames); try { RolePrincipal user = GetCurrentUser() as RolePrincipal; if (user != null && user.ProviderName == Provider.Name && user.IsRoleListCached) foreach (string username in usernames) if (StringUtil.EqualsIgnoreCase(user.Identity.Name, username)) { user.SetDirty(); break; } } catch { } } static public void RemoveUserFromRole(string username, string roleName){ EnsureEnabled(); SecUtility.CheckParameter(ref roleName, true, true, true, 0, "roleName"); SecUtility.CheckParameter(ref username, true, true, true, 0, "username"); Provider.RemoveUsersFromRoles(new string [] {username}, new string [] {roleName}); try { RolePrincipal user = GetCurrentUser() as RolePrincipal; if (user != null && user.ProviderName == Provider.Name && user.IsRoleListCached && StringUtil.EqualsIgnoreCase(user.Identity.Name, username)) user.SetDirty(); } catch { } } static public void RemoveUserFromRoles(string username, string[] roleNames){ EnsureEnabled(); SecUtility.CheckParameter(ref username, true, true, true, 0, "username"); SecUtility.CheckArrayParameter( ref roleNames, true, true, true, 0, "roleNames"); Provider.RemoveUsersFromRoles(new string [] {username}, roleNames); try { RolePrincipal user = GetCurrentUser() as RolePrincipal; if (user != null && user.ProviderName == Provider.Name && user.IsRoleListCached && StringUtil.EqualsIgnoreCase(user.Identity.Name, username)) user.SetDirty(); } catch { } } static public void RemoveUsersFromRole(string[] usernames, string roleName){ EnsureEnabled(); SecUtility.CheckParameter(ref roleName, true, true, true, 0, "roleName"); SecUtility.CheckArrayParameter( ref usernames, true, true, true, 0, "usernames"); Provider.RemoveUsersFromRoles(usernames, new string[] { roleName }); try { RolePrincipal user = GetCurrentUser() as RolePrincipal; if (user != null && user.ProviderName == Provider.Name && user.IsRoleListCached) foreach (string username in usernames) if (StringUtil.EqualsIgnoreCase(user.Identity.Name, username)) { user.SetDirty(); break; } } catch { } } static public void RemoveUsersFromRoles(string[] usernames, string [] roleNames){ EnsureEnabled(); SecUtility.CheckArrayParameter( ref roleNames, true, true, true, 0, "roleNames"); SecUtility.CheckArrayParameter( ref usernames, true, true, true, 0, "usernames"); Provider.RemoveUsersFromRoles(usernames, roleNames); try { RolePrincipal user = GetCurrentUser() as RolePrincipal; if (user != null && user.ProviderName == Provider.Name && user.IsRoleListCached) foreach (string username in usernames) if (StringUtil.EqualsIgnoreCase(user.Identity.Name, username)) { user.SetDirty(); break; } } catch { } } public static string[] GetAllRoles() { EnsureEnabled(); return Provider.GetAllRoles(); } public static void DeleteCookie() { EnsureEnabled(); if (CookieName == null || CookieName.Length < 1) return; HttpContext context = HttpContext.Current; if (context == null || !context.Request.Browser.Cookies) return; string cookieValue = String.Empty; if (context.Request.Browser["supportsEmptyStringInCookieValue"] == "false") cookieValue = "NoCookie"; HttpCookie cookie = new HttpCookie(CookieName, cookieValue); cookie.HttpOnly = true; cookie.Path = CookiePath; cookie.Domain = Domain; cookie.Expires = new System.DateTime(1999, 10, 12); cookie.Secure = CookieRequireSSL; context.Response.Cookies.RemoveCookie(CookieName); context.Response.Cookies.Add(cookie); } static public string[] FindUsersInRole(string roleName, string usernameToMatch) { EnsureEnabled(); SecUtility.CheckParameter(ref roleName, true, true, true, 0, "roleName"); SecUtility.CheckParameter( ref usernameToMatch, true, true, false, 0, "usernameToMatch"); return Provider.FindUsersInRole(roleName, usernameToMatch); } static private void EnsureEnabled() { Initialize(); if (!s_Enabled) throw new ProviderException(SR.GetString(SR.Roles_feature_not_enabled)); } static private void Initialize() { if (s_Initialized) { if (s_InitializeException != null) { throw s_InitializeException; } if (s_InitializedDefaultProvider) { return; } } lock (s_lock) { if (s_Initialized) { if (s_InitializeException != null) { throw s_InitializeException; } if (s_InitializedDefaultProvider) { return; } } try { if (HostingEnvironment.IsHosted) HttpRuntime.CheckAspNetHostingPermission(AspNetHostingPermissionLevel.Low, SR.Feature_not_supported_at_this_level); RoleManagerSection settings = RuntimeConfig.GetAppConfig().RoleManager; //s_InitializeException = new ProviderException(SR.GetString(SR.Roles_feature_not_enabled)); if (!s_EnabledSet) { s_Enabled = settings.Enabled; } s_CookieName = settings.CookieName; s_CacheRolesInCookie = settings.CacheRolesInCookie; s_CookieTimeout = (int)settings.CookieTimeout.TotalMinutes; s_CookiePath = settings.CookiePath; s_CookieRequireSSL = settings.CookieRequireSSL; s_CookieSlidingExpiration = settings.CookieSlidingExpiration; s_CookieProtection = settings.CookieProtection; s_Domain = settings.Domain; s_CreatePersistentCookie = settings.CreatePersistentCookie; s_MaxCachedResults = settings.MaxCachedResults; if (s_Enabled) { // Instantiate providers only if feature is enabled if (s_MaxCachedResults < 0) { throw new ProviderException(SR.GetString(SR.Value_must_be_non_negative_integer, "maxCachedResults")); } InitializeSettings(settings); InitializeDefaultProvider(settings); } } catch (Exception e) { s_InitializeException = e; } s_Initialized = true; } if (s_InitializeException != null) throw s_InitializeException; } private static void InitializeSettings(RoleManagerSection settings) { if (!s_Initialized) { s_Providers = new RoleProviderCollection(); if (HostingEnvironment.IsHosted) { ProvidersHelper.InstantiateProviders(settings.Providers, s_Providers, typeof(RoleProvider)); } else { foreach (ProviderSettings ps in settings.Providers) { Type t = Type.GetType(ps.Type, true, true); if (!typeof(RoleProvider).IsAssignableFrom(t)) throw new ArgumentException(SR.GetString(SR.Provider_must_implement_type, typeof(RoleProvider).ToString())); RoleProvider provider = (RoleProvider)Activator.CreateInstance(t); NameValueCollection pars = ps.Parameters; NameValueCollection cloneParams = new NameValueCollection(pars.Count, StringComparer.Ordinal); foreach (string key in pars) cloneParams[key] = pars[key]; provider.Initialize(ps.Name, cloneParams); s_Providers.Add(provider); } } } } private static void InitializeDefaultProvider(RoleManagerSection settings) { bool canInitializeDefaultProvider = (!HostingEnvironment.IsHosted || BuildManager.PreStartInitStage == PreStartInitStage.AfterPreStartInit); if (!s_InitializedDefaultProvider && canInitializeDefaultProvider) { Debug.Assert(s_Providers != null); s_Providers.SetReadOnly(); if (settings.DefaultProvider == null) { s_InitializeException = new ProviderException(SR.GetString(SR.Def_role_provider_not_specified)); } else { try { s_Provider = s_Providers[settings.DefaultProvider]; } catch { } } if (s_Provider == null) { s_InitializeException = new ConfigurationErrorsException(SR.GetString(SR.Def_role_provider_not_found), settings.ElementInformation.Properties["defaultProvider"].Source, settings.ElementInformation.Properties["defaultProvider"].LineNumber); } s_InitializedDefaultProvider = true; } } static private RoleProvider s_Provider; static private bool s_Enabled; static private string s_CookieName; static private bool s_CacheRolesInCookie; static private int s_CookieTimeout; static private string s_CookiePath; static private bool s_CookieRequireSSL; static private bool s_CookieSlidingExpiration; static private CookieProtection s_CookieProtection; static private string s_Domain; static private bool s_Initialized; static private bool s_InitializedDefaultProvider; static private bool s_EnabledSet; static private RoleProviderCollection s_Providers; private static Exception s_InitializeException = null; private static bool s_CreatePersistentCookie; private static object s_lock = new object(); private static int s_MaxCachedResults = 25; private static string GetCurrentUserName() { IPrincipal user = GetCurrentUser(); if (user == null || user.Identity == null) return String.Empty; else return user.Identity.Name; } private static IPrincipal GetCurrentUser() { if (HostingEnvironment.IsHosted) { HttpContext cur = HttpContext.Current; if (cur != null) return cur.User; } return Thread.CurrentPrincipal; } } //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // This has no hosting permission demands because of DevDiv Bugs 31461: ClientAppSvcs: ASP.net Provider support public sealed class RoleProviderCollection : ProviderCollection { public override void Add(ProviderBase provider) { if( provider == null ) { throw new ArgumentNullException( "provider" ); } if( !( provider is RoleProvider ) ) { throw new ArgumentException(SR.GetString(SR.Provider_must_implement_type, typeof(RoleProvider).ToString()), "provider"); } base.Add(provider); } new public RoleProvider this[string name] { get { return (RoleProvider) base[name]; } } public void CopyTo(RoleProvider [] array, int index) { base.CopyTo(array, index); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; namespace System.Net.Http.Headers { public class RangeItemHeaderValue : ICloneable { private long? _from; private long? _to; public long? From { get { return _from; } } public long? To { get { return _to; } } public RangeItemHeaderValue(long? from, long? to) { if (!from.HasValue && !to.HasValue) { throw new ArgumentException(SR.net_http_headers_invalid_range); } if (from.HasValue && (from.Value < 0)) { throw new ArgumentOutOfRangeException(nameof(from)); } if (to.HasValue && (to.Value < 0)) { throw new ArgumentOutOfRangeException(nameof(to)); } if (from.HasValue && to.HasValue && (from.Value > to.Value)) { throw new ArgumentOutOfRangeException(nameof(from)); } _from = from; _to = to; } private RangeItemHeaderValue(RangeItemHeaderValue source) { Debug.Assert(source != null); _from = source._from; _to = source._to; } public override string ToString() { if (!_from.HasValue) { return "-" + _to.Value.ToString(NumberFormatInfo.InvariantInfo); } else if (!_to.HasValue) { return _from.Value.ToString(NumberFormatInfo.InvariantInfo) + "-"; } return _from.Value.ToString(NumberFormatInfo.InvariantInfo) + "-" + _to.Value.ToString(NumberFormatInfo.InvariantInfo); } public override bool Equals(object obj) { RangeItemHeaderValue other = obj as RangeItemHeaderValue; if (other == null) { return false; } return ((_from == other._from) && (_to == other._to)); } public override int GetHashCode() { if (!_from.HasValue) { return _to.GetHashCode(); } else if (!_to.HasValue) { return _from.GetHashCode(); } return _from.GetHashCode() ^ _to.GetHashCode(); } // Returns the length of a range list. E.g. "1-2, 3-4, 5-6" adds 3 ranges to 'rangeCollection'. Note that empty // list segments are allowed, e.g. ",1-2, , 3-4,,". internal static int GetRangeItemListLength(string input, int startIndex, ICollection<RangeItemHeaderValue> rangeCollection) { Debug.Assert(rangeCollection != null); Debug.Assert(startIndex >= 0); Contract.Ensures((Contract.Result<int>() == 0) || (rangeCollection.Count > 0), "If we can parse the string, then we expect to have at least one range item."); if ((string.IsNullOrEmpty(input)) || (startIndex >= input.Length)) { return 0; } // Empty segments are allowed, so skip all delimiter-only segments (e.g. ", ,"). bool separatorFound = false; int current = HeaderUtilities.GetNextNonEmptyOrWhitespaceIndex(input, startIndex, true, out separatorFound); // It's OK if we didn't find leading separator characters. Ignore 'separatorFound'. if (current == input.Length) { return 0; } RangeItemHeaderValue range = null; while (true) { int rangeLength = GetRangeItemLength(input, current, out range); if (rangeLength == 0) { return 0; } rangeCollection.Add(range); current = current + rangeLength; current = HeaderUtilities.GetNextNonEmptyOrWhitespaceIndex(input, current, true, out separatorFound); // If the string is not consumed, we must have a delimiter, otherwise the string is not a valid // range list. if ((current < input.Length) && !separatorFound) { return 0; } if (current == input.Length) { return current - startIndex; } } } internal static int GetRangeItemLength(string input, int startIndex, out RangeItemHeaderValue parsedValue) { Debug.Assert(startIndex >= 0); // This parser parses number ranges: e.g. '1-2', '1-', '-2'. parsedValue = null; if (string.IsNullOrEmpty(input) || (startIndex >= input.Length)) { return 0; } // Caller must remove leading whitespace. If not, we'll return 0. int current = startIndex; // Try parse the first value of a value pair. int fromStartIndex = current; int fromLength = HttpRuleParser.GetNumberLength(input, current, false); if (fromLength > HttpRuleParser.MaxInt64Digits) { return 0; } current = current + fromLength; current = current + HttpRuleParser.GetWhitespaceLength(input, current); // After the first value, the '-' character must follow. if ((current == input.Length) || (input[current] != '-')) { // We need a '-' character otherwise this can't be a valid range. return 0; } current++; // skip the '-' character current = current + HttpRuleParser.GetWhitespaceLength(input, current); int toStartIndex = current; int toLength = 0; // If we didn't reach the end of the string, try parse the second value of the range. if (current < input.Length) { toLength = HttpRuleParser.GetNumberLength(input, current, false); if (toLength > HttpRuleParser.MaxInt64Digits) { return 0; } current = current + toLength; current = current + HttpRuleParser.GetWhitespaceLength(input, current); } if ((fromLength == 0) && (toLength == 0)) { return 0; // At least one value must be provided in order to be a valid range. } // Try convert first value to int64 long from = 0; if ((fromLength > 0) && !HeaderUtilities.TryParseInt64(input.Substring(fromStartIndex, fromLength), out from)) { return 0; } // Try convert second value to int64 long to = 0; if ((toLength > 0) && !HeaderUtilities.TryParseInt64(input.Substring(toStartIndex, toLength), out to)) { return 0; } // 'from' must not be greater than 'to' if ((fromLength > 0) && (toLength > 0) && (from > to)) { return 0; } parsedValue = new RangeItemHeaderValue((fromLength == 0 ? (long?)null : (long?)from), (toLength == 0 ? (long?)null : (long?)to)); return current - startIndex; } object ICloneable.Clone() { return new RangeItemHeaderValue(this); } } }
//------------------------------------------------------------------------------ // <copyright file="HtmlElement.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ using System; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.Drawing.Printing; using System.IO; using System.Net; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; namespace System.Windows.Forms { /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")] public sealed class HtmlElement { internal static readonly object EventClick = new object(); internal static readonly object EventDoubleClick = new object(); internal static readonly object EventDrag = new object(); internal static readonly object EventDragEnd = new object(); internal static readonly object EventDragLeave = new object(); internal static readonly object EventDragOver = new object(); internal static readonly object EventFocusing = new object(); internal static readonly object EventGotFocus = new object(); internal static readonly object EventLosingFocus = new object(); internal static readonly object EventLostFocus = new object(); internal static readonly object EventKeyDown = new object(); internal static readonly object EventKeyPress = new object(); internal static readonly object EventKeyUp = new object(); internal static readonly object EventMouseDown = new object(); internal static readonly object EventMouseEnter = new object(); internal static readonly object EventMouseLeave = new object(); internal static readonly object EventMouseMove = new object(); internal static readonly object EventMouseOver = new object(); internal static readonly object EventMouseUp = new object(); private UnsafeNativeMethods.IHTMLElement htmlElement; private HtmlShimManager shimManager; [PermissionSet(SecurityAction.Demand, Name = "FullTrust")] internal HtmlElement(HtmlShimManager shimManager, UnsafeNativeMethods.IHTMLElement element) { this.htmlElement = element; Debug.Assert(this.NativeHtmlElement != null, "The element object should implement IHTMLElement"); this.shimManager = shimManager; } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.All"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public HtmlElementCollection All { get { UnsafeNativeMethods.IHTMLElementCollection iHTMLElementCollection = this.NativeHtmlElement.GetAll() as UnsafeNativeMethods.IHTMLElementCollection; return iHTMLElementCollection != null ? new HtmlElementCollection(shimManager, iHTMLElementCollection) : new HtmlElementCollection(shimManager); } } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.Children"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public HtmlElementCollection Children { get { UnsafeNativeMethods.IHTMLElementCollection iHTMLElementCollection = this.NativeHtmlElement.GetChildren() as UnsafeNativeMethods.IHTMLElementCollection; return iHTMLElementCollection != null ? new HtmlElementCollection(shimManager, iHTMLElementCollection) : new HtmlElementCollection(shimManager); } } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.CanHaveChildren"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public bool CanHaveChildren { get { return ((UnsafeNativeMethods.IHTMLElement2)this.NativeHtmlElement).CanHaveChildren(); } } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.ClientRectangle"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public Rectangle ClientRectangle { get { UnsafeNativeMethods.IHTMLElement2 htmlElement2 = (UnsafeNativeMethods.IHTMLElement2)this.NativeHtmlElement; return new Rectangle(htmlElement2.ClientLeft(), htmlElement2.ClientTop(), htmlElement2.ClientWidth(), htmlElement2.ClientHeight()); } } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.Document"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public HtmlDocument Document { get { UnsafeNativeMethods.IHTMLDocument iHTMLDocument = this.NativeHtmlElement.GetDocument() as UnsafeNativeMethods.IHTMLDocument; return iHTMLDocument != null ? new HtmlDocument(shimManager, iHTMLDocument) : null; } } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.Enabled"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public bool Enabled { get { return !(((UnsafeNativeMethods.IHTMLElement3)this.NativeHtmlElement).GetDisabled()); } set { ((UnsafeNativeMethods.IHTMLElement3)this.NativeHtmlElement).SetDisabled(!value); } } private HtmlElementShim ElementShim { get { if (ShimManager != null) { HtmlElementShim shim = ShimManager.GetElementShim(this); if (shim == null) { shimManager.AddElementShim(this); shim = ShimManager.GetElementShim(this); } return shim; } return null; } } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.FirstChild"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public HtmlElement FirstChild { get { UnsafeNativeMethods.IHTMLElement iHtmlElement = null; UnsafeNativeMethods.IHTMLDOMNode iHtmlDomNode = this.NativeHtmlElement as UnsafeNativeMethods.IHTMLDOMNode; if( iHtmlDomNode != null ) { iHtmlElement = iHtmlDomNode.FirstChild() as UnsafeNativeMethods.IHTMLElement; } return iHtmlElement != null ? new HtmlElement(shimManager, iHtmlElement) : null; } } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.Id"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public string Id { [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] get { return this.NativeHtmlElement.GetId(); } set { this.NativeHtmlElement.SetId(value); } } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.InnerHtml"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public string InnerHtml { get { return this.NativeHtmlElement.GetInnerHTML(); } set { try { this.NativeHtmlElement.SetInnerHTML(value); } catch (COMException ex) { if (ex.ErrorCode == unchecked((int)0x800a0258)) { throw new NotSupportedException(SR.GetString(SR.HtmlElementPropertyNotSupported)); } throw; } } } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.InnerText"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public string InnerText { get { return this.NativeHtmlElement.GetInnerText(); } set { try { this.NativeHtmlElement.SetInnerText(value); } catch (COMException ex) { if (ex.ErrorCode == unchecked((int)0x800a0258)) { throw new NotSupportedException(SR.GetString(SR.HtmlElementPropertyNotSupported)); } throw; } } } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.Name"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public string Name { get { return this.GetAttribute("Name"); } set { this.SetAttribute("Name", value); } } private UnsafeNativeMethods.IHTMLElement NativeHtmlElement { get { return this.htmlElement; } } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.NextSibling"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public HtmlElement NextSibling { get { UnsafeNativeMethods.IHTMLElement iHtmlElement = null; UnsafeNativeMethods.IHTMLDOMNode iHtmlDomNode = this.NativeHtmlElement as UnsafeNativeMethods.IHTMLDOMNode; if( iHtmlDomNode != null ) { iHtmlElement = iHtmlDomNode.NextSibling() as UnsafeNativeMethods.IHTMLElement; } return iHtmlElement != null ? new HtmlElement(shimManager, iHtmlElement) : null; } } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.OffsetRectangle"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public Rectangle OffsetRectangle { get { return new Rectangle(this.NativeHtmlElement.GetOffsetLeft(), this.NativeHtmlElement.GetOffsetTop(), this.NativeHtmlElement.GetOffsetWidth(), this.NativeHtmlElement.GetOffsetHeight()); } } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.OffsetParent"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public HtmlElement OffsetParent { get { UnsafeNativeMethods.IHTMLElement iHtmlElement = this.NativeHtmlElement.GetOffsetParent(); return iHtmlElement != null ? new HtmlElement(shimManager, iHtmlElement) : null; } } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.OuterHtml"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public string OuterHtml { get { return this.NativeHtmlElement.GetOuterHTML(); } set { try { this.NativeHtmlElement.SetOuterHTML(value); } catch (COMException ex) { if (ex.ErrorCode == unchecked((int)0x800a0258)) { throw new NotSupportedException(SR.GetString(SR.HtmlElementPropertyNotSupported)); } throw; } } } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.OuterText"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public string OuterText { get { return this.NativeHtmlElement.GetOuterText(); } set { try { this.NativeHtmlElement.SetOuterText(value); } catch (COMException ex) { if (ex.ErrorCode == unchecked((int)0x800a0258)) { throw new NotSupportedException(SR.GetString(SR.HtmlElementPropertyNotSupported)); } throw; } } } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.Parent"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public HtmlElement Parent { get { UnsafeNativeMethods.IHTMLElement iHtmlElement = this.NativeHtmlElement.GetParentElement(); return iHtmlElement != null ? new HtmlElement(shimManager, iHtmlElement) : null; } } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.ScrollRectangle"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public Rectangle ScrollRectangle { get { UnsafeNativeMethods.IHTMLElement2 htmlElement2 = (UnsafeNativeMethods.IHTMLElement2)this.NativeHtmlElement; return new Rectangle(htmlElement2.GetScrollLeft(), htmlElement2.GetScrollTop(), htmlElement2.GetScrollWidth(), htmlElement2.GetScrollHeight()); } } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.ScrollLeft"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public int ScrollLeft { get { return ((UnsafeNativeMethods.IHTMLElement2)this.NativeHtmlElement).GetScrollLeft(); } set { ((UnsafeNativeMethods.IHTMLElement2)this.NativeHtmlElement).SetScrollLeft(value); } } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.ScrollTop"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public int ScrollTop { get { return ((UnsafeNativeMethods.IHTMLElement2)this.NativeHtmlElement).GetScrollTop(); } set { ((UnsafeNativeMethods.IHTMLElement2)this.NativeHtmlElement).SetScrollTop(value); } } private HtmlShimManager ShimManager { get { return shimManager; } } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.Style"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public string Style { get { return this.NativeHtmlElement.GetStyle().GetCssText(); } set { this.NativeHtmlElement.GetStyle().SetCssText(value); } } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.TagName"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public string TagName { get { return this.NativeHtmlElement.GetTagName(); } } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.TabIndex"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public short TabIndex { get { return ((UnsafeNativeMethods.IHTMLElement2)this.NativeHtmlElement).GetTabIndex(); } set { ((UnsafeNativeMethods.IHTMLElement2)this.NativeHtmlElement).SetTabIndex(value); } } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.DomElement"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public object DomElement { get { return this.NativeHtmlElement; } } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.AppendChild"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public HtmlElement AppendChild(HtmlElement newElement) { return this.InsertAdjacentElement(HtmlElementInsertionOrientation.BeforeEnd, newElement); } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.AttachEventHandler"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void AttachEventHandler(string eventName, EventHandler eventHandler) { ElementShim.AttachEventHandler(eventName, eventHandler); } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.DetachEventHandler"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void DetachEventHandler(string eventName, EventHandler eventHandler) { ElementShim.DetachEventHandler(eventName, eventHandler); } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.Focus"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Focus() { try { ((UnsafeNativeMethods.IHTMLElement2)this.NativeHtmlElement).Focus(); } catch (COMException ex) { if (ex.ErrorCode == unchecked((int)0x800a083e)) { throw new NotSupportedException(SR.GetString(SR.HtmlElementMethodNotSupported)); } throw; } } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.GetAttribute"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] public string GetAttribute(string attributeName) { object oAttributeValue = this.NativeHtmlElement.GetAttribute(attributeName, 0); return oAttributeValue == null ? "" : oAttributeValue.ToString(); } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.GetElementsByTagName"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public HtmlElementCollection GetElementsByTagName(string tagName) { UnsafeNativeMethods.IHTMLElementCollection iHTMLElementCollection = ((UnsafeNativeMethods.IHTMLElement2)this.NativeHtmlElement).GetElementsByTagName(tagName); return iHTMLElementCollection != null ? new HtmlElementCollection(shimManager, iHTMLElementCollection) : new HtmlElementCollection(shimManager); } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.InsertAdjacentElement"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public HtmlElement InsertAdjacentElement(HtmlElementInsertionOrientation orient, HtmlElement newElement) { UnsafeNativeMethods.IHTMLElement iHtmlElement = ((UnsafeNativeMethods.IHTMLElement2)this.NativeHtmlElement).InsertAdjacentElement(orient.ToString(), (UnsafeNativeMethods.IHTMLElement)newElement.DomElement); return iHtmlElement != null ? new HtmlElement(shimManager, iHtmlElement) : null; } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.InvokeMember"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public object InvokeMember(string methodName) { return InvokeMember(methodName, null); } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.InvokeMember"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public object InvokeMember(string methodName, params object[] parameter) { object retVal = null; NativeMethods.tagDISPPARAMS dp = new NativeMethods.tagDISPPARAMS(); dp.rgvarg = IntPtr.Zero; try { UnsafeNativeMethods.IDispatch scriptObject = this.NativeHtmlElement as UnsafeNativeMethods.IDispatch; if (scriptObject != null) { Guid g = Guid.Empty; string[] names = new string[] { methodName }; int[] dispids = new int[] { NativeMethods.ActiveX.DISPID_UNKNOWN }; int hr = scriptObject.GetIDsOfNames(ref g, names, 1, SafeNativeMethods.GetThreadLCID(), dispids); if (NativeMethods.Succeeded(hr) && (dispids[0] != NativeMethods.ActiveX.DISPID_UNKNOWN)) { // Reverse the arg order below so that parms are read properly thru IDispatch. (bug 187662) if (parameter != null) { // Reverse the parm order so that they read naturally after IDispatch. (bug 187662) Array.Reverse(parameter); } dp.rgvarg = (parameter == null) ? IntPtr.Zero : HtmlDocument.ArrayToVARIANTVector(parameter); dp.cArgs = (parameter == null) ? 0 : parameter.Length; dp.rgdispidNamedArgs = IntPtr.Zero; dp.cNamedArgs = 0; object[] retVals = new object[1]; hr = scriptObject.Invoke(dispids[0], ref g, SafeNativeMethods.GetThreadLCID(), NativeMethods.DISPATCH_METHOD, dp, retVals, new NativeMethods.tagEXCEPINFO(), null); if (hr == NativeMethods.S_OK) { retVal = retVals[0]; } } } } catch (Exception ex) { if (ClientUtils.IsSecurityOrCriticalException(ex)) { throw; } } finally { if (dp.rgvarg != IntPtr.Zero) { HtmlDocument.FreeVARIANTVector(dp.rgvarg, parameter.Length); } } return retVal; } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.RemoveFocus"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void RemoveFocus() { ((UnsafeNativeMethods.IHTMLElement2)this.NativeHtmlElement).Blur(); } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.RaiseEvent"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> // PM review done [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] public void RaiseEvent(string eventName) { ((UnsafeNativeMethods.IHTMLElement3)this.NativeHtmlElement).FireEvent(eventName, IntPtr.Zero); } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.ScrollIntoView"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void ScrollIntoView(bool alignWithTop) { this.NativeHtmlElement.ScrollIntoView((object)alignWithTop); } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.SetAttribute"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void SetAttribute(string attributeName, string value) { try { this.NativeHtmlElement.SetAttribute(attributeName, (object)value, 0); } catch (COMException comException) { if (comException.ErrorCode == unchecked((int)0x80020009)) { throw new NotSupportedException(SR.GetString(SR.HtmlElementAttributeNotSupported)); } throw; } } // // Events: // /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.Click"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public event HtmlElementEventHandler Click { add { ElementShim.AddHandler(EventClick, value); } remove { ElementShim.RemoveHandler(EventClick, value); } } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.DoubleClick"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public event HtmlElementEventHandler DoubleClick { add { ElementShim.AddHandler(EventDoubleClick, value); } remove { ElementShim.RemoveHandler(EventDoubleClick, value); } } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.Drag"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public event HtmlElementEventHandler Drag { add { ElementShim.AddHandler(EventDrag, value); } remove { ElementShim.RemoveHandler(EventDrag, value); } } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.DragEnd"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public event HtmlElementEventHandler DragEnd { add { ElementShim.AddHandler(EventDragEnd, value); } remove { ElementShim.RemoveHandler(EventDragEnd, value); } } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.Drag"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public event HtmlElementEventHandler DragLeave { add { ElementShim.AddHandler(EventDragLeave, value); } remove { ElementShim.RemoveHandler(EventDragLeave, value); } } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.DragOver"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public event HtmlElementEventHandler DragOver { add { ElementShim.AddHandler(EventDragOver, value); } remove { ElementShim.RemoveHandler(EventDragOver, value); } } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.Focusing"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public event HtmlElementEventHandler Focusing { add { ElementShim.AddHandler(EventFocusing, value); } remove { ElementShim.RemoveHandler(EventFocusing, value); } } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.Focus"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public event HtmlElementEventHandler GotFocus { add { ElementShim.AddHandler(EventGotFocus, value); } remove { ElementShim.RemoveHandler(EventGotFocus, value); } } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.LosingFocus"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public event HtmlElementEventHandler LosingFocus { add { ElementShim.AddHandler(EventLosingFocus, value); } remove { ElementShim.RemoveHandler(EventLosingFocus, value); } } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.LostFocus"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public event HtmlElementEventHandler LostFocus { add { ElementShim.AddHandler(EventLostFocus, value); } remove { ElementShim.RemoveHandler(EventLostFocus, value); } } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.KeyDown"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public event HtmlElementEventHandler KeyDown { add { ElementShim.AddHandler(EventKeyDown, value); } remove { ElementShim.RemoveHandler(EventKeyDown, value); } } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.KeyPress"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public event HtmlElementEventHandler KeyPress { add { ElementShim.AddHandler(EventKeyPress, value); } remove { ElementShim.RemoveHandler(EventKeyPress, value); } } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.KeyUp"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public event HtmlElementEventHandler KeyUp { add { ElementShim.AddHandler(EventKeyUp, value); } remove { ElementShim.RemoveHandler(EventKeyUp, value); } } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.MouseMove"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public event HtmlElementEventHandler MouseMove { add { ElementShim.AddHandler(EventMouseMove, value); } remove { ElementShim.RemoveHandler(EventMouseMove, value); } } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.MouseDown"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public event HtmlElementEventHandler MouseDown { add { ElementShim.AddHandler(EventMouseDown, value); } remove { ElementShim.RemoveHandler(EventMouseDown, value); } } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.MouseOver"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public event HtmlElementEventHandler MouseOver { add { ElementShim.AddHandler(EventMouseOver, value); } remove { ElementShim.RemoveHandler(EventMouseOver, value); } } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.MouseUp"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public event HtmlElementEventHandler MouseUp { add { ElementShim.AddHandler(EventMouseUp, value); } remove { ElementShim.RemoveHandler(EventMouseUp, value); } } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.MouseEnter"]/*' /> /// <devdoc> /// <para>Fires when the mouse enters the element</para> /// </devdoc> public event HtmlElementEventHandler MouseEnter { add { ElementShim.AddHandler(EventMouseEnter, value); } remove { ElementShim.RemoveHandler(EventMouseEnter, value); } } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.MouseLeave"]/*' /> /// <devdoc> /// <para>Fires when the mouse leaves the element</para> /// </devdoc> public event HtmlElementEventHandler MouseLeave { add { ElementShim.AddHandler(EventMouseLeave, value); } remove { ElementShim.RemoveHandler(EventMouseLeave, value); } } // // Private classes: // [ClassInterface(ClassInterfaceType.None)] private class HTMLElementEvents2 : StandardOleMarshalObject, /*Enforce calling back on the same thread*/ UnsafeNativeMethods.DHTMLElementEvents2, UnsafeNativeMethods.DHTMLAnchorEvents2, UnsafeNativeMethods.DHTMLAreaEvents2, UnsafeNativeMethods.DHTMLButtonElementEvents2, UnsafeNativeMethods.DHTMLControlElementEvents2, UnsafeNativeMethods.DHTMLFormElementEvents2, UnsafeNativeMethods.DHTMLFrameSiteEvents2, UnsafeNativeMethods.DHTMLImgEvents2, UnsafeNativeMethods.DHTMLInputFileElementEvents2, UnsafeNativeMethods.DHTMLInputImageEvents2, UnsafeNativeMethods.DHTMLInputTextElementEvents2, UnsafeNativeMethods.DHTMLLabelEvents2, UnsafeNativeMethods.DHTMLLinkElementEvents2, UnsafeNativeMethods.DHTMLMapEvents2, UnsafeNativeMethods.DHTMLMarqueeElementEvents2, UnsafeNativeMethods.DHTMLOptionButtonElementEvents2, UnsafeNativeMethods.DHTMLSelectElementEvents2, UnsafeNativeMethods.DHTMLStyleElementEvents2, UnsafeNativeMethods.DHTMLTableEvents2, UnsafeNativeMethods.DHTMLTextContainerEvents2, UnsafeNativeMethods.DHTMLScriptEvents2 { private HtmlElement parent; public HTMLElementEvents2(HtmlElement htmlElement) { this.parent = htmlElement; } private void FireEvent(object key, EventArgs e) { if (this.parent != null) { parent.ElementShim.FireEvent(key, e); } } public bool onclick(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); FireEvent(HtmlElement.EventClick, e); return e.ReturnValue; } public bool ondblclick(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); FireEvent(HtmlElement.EventDoubleClick, e); return e.ReturnValue; } public bool onkeypress(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); FireEvent(HtmlElement.EventKeyPress, e); return e.ReturnValue; } public void onkeydown(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); FireEvent(HtmlElement.EventKeyDown, e); } public void onkeyup(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); FireEvent(HtmlElement.EventKeyUp, e); } public void onmouseover(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); FireEvent(HtmlElement.EventMouseOver, e); } public void onmousemove(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); FireEvent(HtmlElement.EventMouseMove, e); } public void onmousedown(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); FireEvent(HtmlElement.EventMouseDown, e); } public void onmouseup(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); FireEvent(HtmlElement.EventMouseUp, e); } public void onmouseenter(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); FireEvent(HtmlElement.EventMouseEnter, e); } public void onmouseleave(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); FireEvent(HtmlElement.EventMouseLeave, e); } public bool onerrorupdate(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } public void onfocus(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); FireEvent(HtmlElement.EventGotFocus, e); } public bool ondrag(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); FireEvent(HtmlElement.EventDrag, e); return e.ReturnValue; } public void ondragend(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); FireEvent(HtmlElement.EventDragEnd, e); } public void ondragleave(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); FireEvent(HtmlElement.EventDragLeave, e); } public bool ondragover(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); FireEvent(HtmlElement.EventDragOver, e); return e.ReturnValue; } public void onfocusin(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); FireEvent(HtmlElement.EventFocusing, e); } public void onfocusout(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); FireEvent(HtmlElement.EventLosingFocus, e); } public void onblur(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); FireEvent(HtmlElement.EventLostFocus, e); } public void onresizeend(UnsafeNativeMethods.IHTMLEventObj evtObj) { } public bool onresizestart(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } public bool onhelp(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } public void onmouseout(UnsafeNativeMethods.IHTMLEventObj evtObj) { } public bool onselectstart(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } public void onfilterchange(UnsafeNativeMethods.IHTMLEventObj evtObj) { } public bool ondragstart(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } public bool onbeforeupdate(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } public void onafterupdate(UnsafeNativeMethods.IHTMLEventObj evtObj) { } public bool onrowexit(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } public void onrowenter(UnsafeNativeMethods.IHTMLEventObj evtObj) { } public void ondatasetchanged(UnsafeNativeMethods.IHTMLEventObj evtObj) { } public void ondataavailable(UnsafeNativeMethods.IHTMLEventObj evtObj) { } public void ondatasetcomplete(UnsafeNativeMethods.IHTMLEventObj evtObj) { } public void onlosecapture(UnsafeNativeMethods.IHTMLEventObj evtObj) { } public void onpropertychange(UnsafeNativeMethods.IHTMLEventObj evtObj) { } public void onscroll(UnsafeNativeMethods.IHTMLEventObj evtObj) { } public void onresize(UnsafeNativeMethods.IHTMLEventObj evtObj) { } public bool ondragenter(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } public bool ondrop(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } public bool onbeforecut(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } public bool oncut(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } public bool onbeforecopy(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } public bool oncopy(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } public bool onbeforepaste(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } public bool onpaste(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } public bool oncontextmenu(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } public void onrowsdelete(UnsafeNativeMethods.IHTMLEventObj evtObj) { } public void onrowsinserted(UnsafeNativeMethods.IHTMLEventObj evtObj) { } public void oncellchange(UnsafeNativeMethods.IHTMLEventObj evtObj) { } public void onreadystatechange(UnsafeNativeMethods.IHTMLEventObj evtObj) { } public void onlayoutcomplete(UnsafeNativeMethods.IHTMLEventObj evtObj) { } public void onpage(UnsafeNativeMethods.IHTMLEventObj evtObj) { } public void onactivate(UnsafeNativeMethods.IHTMLEventObj evtObj) { } public void ondeactivate(UnsafeNativeMethods.IHTMLEventObj evtObj) { } public bool onbeforedeactivate(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } public bool onbeforeactivate(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } public void onmove(UnsafeNativeMethods.IHTMLEventObj evtObj) { } public bool oncontrolselect(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } public bool onmovestart(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } public void onmoveend(UnsafeNativeMethods.IHTMLEventObj evtObj) { } public bool onmousewheel(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } public bool onchange(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } public void onselect(UnsafeNativeMethods.IHTMLEventObj evtObj) { } public void onload(UnsafeNativeMethods.IHTMLEventObj evtObj) { } public void onerror(UnsafeNativeMethods.IHTMLEventObj evtObj) { } public void onabort(UnsafeNativeMethods.IHTMLEventObj evtObj) { } public bool onsubmit(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } public bool onreset(UnsafeNativeMethods.IHTMLEventObj evtObj) { HtmlElementEventArgs e = new HtmlElementEventArgs(parent.ShimManager, evtObj); return e.ReturnValue; } public void onchange_void(UnsafeNativeMethods.IHTMLEventObj evtObj) { } public void onbounce(UnsafeNativeMethods.IHTMLEventObj evtObj) { } public void onfinish(UnsafeNativeMethods.IHTMLEventObj evtObj) { } public void onstart(UnsafeNativeMethods.IHTMLEventObj evtObj) { } } ///<devdoc> /// HtmlElementShim - this is the glue between the DOM eventing mechanisms /// and our CLR callbacks. /// /// HTMLElementEvents2: we create an IConnectionPoint (via ConnectionPointCookie) between us and MSHTML and it calls back /// on our an instance of HTMLElementEvents2. The HTMLElementEvents2 class then fires the event. /// ///</devdoc> internal class HtmlElementShim : HtmlShim { private static Type[] dispInterfaceTypes = {typeof(UnsafeNativeMethods.DHTMLElementEvents2), typeof(UnsafeNativeMethods.DHTMLAnchorEvents2), typeof(UnsafeNativeMethods.DHTMLAreaEvents2), typeof(UnsafeNativeMethods.DHTMLButtonElementEvents2), typeof(UnsafeNativeMethods.DHTMLControlElementEvents2), typeof(UnsafeNativeMethods.DHTMLFormElementEvents2), typeof(UnsafeNativeMethods.DHTMLFrameSiteEvents2), typeof(UnsafeNativeMethods.DHTMLImgEvents2), typeof(UnsafeNativeMethods.DHTMLInputFileElementEvents2), typeof(UnsafeNativeMethods.DHTMLInputImageEvents2), typeof(UnsafeNativeMethods.DHTMLInputTextElementEvents2), typeof(UnsafeNativeMethods.DHTMLLabelEvents2), typeof(UnsafeNativeMethods.DHTMLLinkElementEvents2), typeof(UnsafeNativeMethods.DHTMLMapEvents2), typeof(UnsafeNativeMethods.DHTMLMarqueeElementEvents2), typeof(UnsafeNativeMethods.DHTMLOptionButtonElementEvents2), typeof(UnsafeNativeMethods.DHTMLSelectElementEvents2), typeof(UnsafeNativeMethods.DHTMLStyleElementEvents2), typeof(UnsafeNativeMethods.DHTMLTableEvents2), typeof(UnsafeNativeMethods.DHTMLTextContainerEvents2), typeof(UnsafeNativeMethods.DHTMLScriptEvents2)}; private AxHost.ConnectionPointCookie cookie; // To hook up events from the native HtmlElement private HtmlElement htmlElement; private UnsafeNativeMethods.IHTMLWindow2 associatedWindow = null; public HtmlElementShim(HtmlElement element) { this.htmlElement = element; // snap our associated window so we know when to disconnect. if (this.htmlElement != null) { HtmlDocument doc = this.htmlElement.Document; if (doc != null) { HtmlWindow window = doc.Window; if (window != null) { associatedWindow = window.NativeHtmlWindow; } } } } public UnsafeNativeMethods.IHTMLElement NativeHtmlElement { get { return htmlElement.NativeHtmlElement; } } internal HtmlElement Element { get { return htmlElement; } } public override UnsafeNativeMethods.IHTMLWindow2 AssociatedWindow { get { return associatedWindow; } } /// Support IHTMLElement2.AttachEventHandler public override void AttachEventHandler(string eventName, System.EventHandler eventHandler) { // IE likes to call back on an IDispatch of DISPID=0 when it has an event, // the HtmlToClrEventProxy helps us fake out the CLR so that we can call back on // our EventHandler properly. HtmlToClrEventProxy proxy = AddEventProxy(eventName, eventHandler); bool success = ((UnsafeNativeMethods.IHTMLElement2)this.NativeHtmlElement).AttachEvent(eventName, proxy); Debug.Assert(success, "failed to add event"); } public override void ConnectToEvents() { if (cookie == null || !cookie.Connected) { for (int i = 0; i < dispInterfaceTypes.Length && this.cookie == null; i++) { this.cookie = new AxHost.ConnectionPointCookie(this.NativeHtmlElement, new HTMLElementEvents2(htmlElement), dispInterfaceTypes[i], /*throwException*/ false); if (!cookie.Connected) { cookie = null; } } } } /// Support IHTMLElement2.DetachHandler public override void DetachEventHandler(string eventName, System.EventHandler eventHandler) { HtmlToClrEventProxy proxy = RemoveEventProxy(eventHandler); if (proxy != null) { ((UnsafeNativeMethods.IHTMLElement2)this.NativeHtmlElement).DetachEvent(eventName, proxy); } } public override void DisconnectFromEvents() { if (this.cookie != null) { this.cookie.Disconnect(); this.cookie = null; } } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (htmlElement != null) { Marshal.FinalReleaseComObject(htmlElement.NativeHtmlElement); } htmlElement = null; } protected override object GetEventSender() { return htmlElement; } } #region operators /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.operatorEQ"]/*' /> [SuppressMessage("Microsoft.Design", "CA1046:DoNotOverrideOperatorEqualsOnReferenceTypes")] public static bool operator ==(HtmlElement left, HtmlElement right) { //Not equal if only one's null. if (object.ReferenceEquals(left, null) != object.ReferenceEquals(right, null)) { return false; } //Equal if both are null. if (object.ReferenceEquals(left, null)) { return true; } //Neither are null. Get the IUnknowns and compare them. IntPtr leftPtr = IntPtr.Zero; IntPtr rightPtr = IntPtr.Zero; try { leftPtr = Marshal.GetIUnknownForObject(left.NativeHtmlElement); rightPtr = Marshal.GetIUnknownForObject(right.NativeHtmlElement); return leftPtr == rightPtr; } finally { if (leftPtr != IntPtr.Zero) { Marshal.Release(leftPtr); } if (rightPtr != IntPtr.Zero) { Marshal.Release(rightPtr); } } } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.operatorNE"]/*' /> public static bool operator !=(HtmlElement left, HtmlElement right) { return !(left == right); } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.GetHashCode"]/*' /> public override int GetHashCode() { return htmlElement == null ? 0 : htmlElement.GetHashCode(); } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElement.Equals"]/*' /> public override bool Equals(object obj) { //If obj isn't an HtmlElement, we want Equals to return false. this will //never be null, so now it will return false as expected (not throw). return this == (obj as HtmlElement); } #endregion } /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElementInsertionOrientation"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public enum HtmlElementInsertionOrientation { /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElementInsertionOrientation.BeforeBegin"]/*' /> BeforeBegin, /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElementInsertionOrientation.AfterBegin"]/*' /> AfterBegin, /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElementInsertionOrientation.BeforeEnd"]/*' /> BeforeEnd, /// <include file='doc\HtmlElement.uex' path='docs/doc[@for="HtmlElementInsertionOrientation.AfterEnd"]/*' /> AfterEnd } }
using System; using System.Diagnostics; using System.Drawing; using System.Runtime.InteropServices; using System.Windows.Forms; using Palaso.Email; using Palaso.Reporting; using System.Threading; using System.Collections.Generic; using System.Text; namespace Palaso.UI.WindowsForms.Reporting { /// <summary> /// Display exception reporting dialog. /// NOTE: It is recommended to call one of Palaso.Reporting.ErrorReport.Report(Non)Fatal* /// methods instead of instantiating this class. /// </summary> public class ExceptionReportingDialog : Form { #region Local structs private struct ExceptionReportingData { public ExceptionReportingData(string message, string messageBeforeStack, Exception error, StackTrace stackTrace, Form owningForm, int threadId) { Message = message; MessageBeforeStack = messageBeforeStack; Error = error; StackTrace = stackTrace; OwningForm = owningForm; ThreadId = threadId; } public string Message; public string MessageBeforeStack; public Exception Error; public Form OwningForm; public StackTrace StackTrace; public int ThreadId; } #endregion #region Member variables private Label label3; private TextBox _details; private TextBox _pleaseHelpText; private TextBox m_reproduce; private bool _isLethal; private Button _sendAndCloseButton; private TextBox _notificationText; private TextBox textBox1; private ComboBox _methodCombo; private Button _privacyNoticeButton; private Label _emailAddress; private static bool s_doIgnoreReport; /// <summary> /// Stack with exception data. /// </summary> /// <remarks>When an exception occurs on a background thread ideally it should be handled /// by the application. However, not all applications are always implemented to do it /// that way, so we need a safe fall back that doesn't pop up a dialog from a (non-UI) /// background thread. /// /// This implementation creates a control on the UI thread /// (WinFormsExceptionHandler.ControlOnUIThread) in order to be able to check /// if invoke is required. When an exception occurs on a background thread we push the /// exception data to an exception data stack and try to invoke the exception dialog on /// the UI thread. In case that the UI thread already shows an exception dialog we skip /// the exception (similar to the behavior we already have when we get an exception on /// the UI thread while displaying the exception dialog). Otherwise we display the /// exception dialog, appending the messages from the exception data stack.</remarks> private static Stack<ExceptionReportingData> s_reportDataStack = new Stack<ExceptionReportingData>(); #endregion protected ExceptionReportingDialog(bool isLethal) { _isLethal = isLethal; } #region IDisposable override /// <summary> /// Check to see if the object has been disposed. /// All public Properties and Methods should call this /// before doing anything else. /// </summary> public void CheckDisposed() { if (IsDisposed) { throw new ObjectDisposedException(String.Format("'{0}' in use after being disposed.", GetType().Name)); } } /// <summary> /// Executes in two distinct scenarios. /// /// 1. If disposing is true, the method has been called directly /// or indirectly by a user's code via the Dispose method. /// Both managed and unmanaged resources can be disposed. /// /// 2. If disposing is false, the method has been called by the /// runtime from inside the finalizer and you should not reference (access) /// other managed objects, as they already have been garbage collected. /// Only unmanaged resources can be disposed. /// </summary> /// <param name="disposing"></param> /// <remarks> /// If any exceptions are thrown, that is fine. /// If the method is being done in a finalizer, it will be ignored. /// If it is thrown by client code calling Dispose, /// it needs to be handled by fixing the bug. /// /// If subclasses override this method, they should call the base implementation. /// </remarks> protected override void Dispose(bool disposing) { //Debug.WriteLineIf(!disposing, "****************** " + GetType().Name + " 'disposing' is false. ******************"); // Must not be run more than once. if (IsDisposed) { return; } if (disposing) { // Dispose managed resources here. } // Dispose unmanaged resources here, whether disposing is true or false. base.Dispose(disposing); } #endregion IDisposable override #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ExceptionReportingDialog)); this.m_reproduce = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this._details = new System.Windows.Forms.TextBox(); this._sendAndCloseButton = new System.Windows.Forms.Button(); this._pleaseHelpText = new System.Windows.Forms.TextBox(); this._notificationText = new System.Windows.Forms.TextBox(); this.textBox1 = new System.Windows.Forms.TextBox(); this._methodCombo = new System.Windows.Forms.ComboBox(); this._privacyNoticeButton = new System.Windows.Forms.Button(); this._emailAddress = new System.Windows.Forms.Label(); this.SuspendLayout(); // // m_reproduce // this.m_reproduce.AcceptsReturn = true; this.m_reproduce.AcceptsTab = true; resources.ApplyResources(this.m_reproduce, "m_reproduce"); this.m_reproduce.Name = "m_reproduce"; // // label3 // resources.ApplyResources(this.label3, "label3"); this.label3.Name = "label3"; // // _details // resources.ApplyResources(this._details, "_details"); this._details.BackColor = System.Drawing.SystemColors.ControlLightLight; this._details.Name = "_details"; this._details.ReadOnly = true; // // _sendAndCloseButton // resources.ApplyResources(this._sendAndCloseButton, "_sendAndCloseButton"); this._sendAndCloseButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this._sendAndCloseButton.Name = "_sendAndCloseButton"; this._sendAndCloseButton.Click += new System.EventHandler(this.btnClose_Click); // // _pleaseHelpText // resources.ApplyResources(this._pleaseHelpText, "_pleaseHelpText"); this._pleaseHelpText.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); this._pleaseHelpText.BorderStyle = System.Windows.Forms.BorderStyle.None; this._pleaseHelpText.ForeColor = System.Drawing.Color.Black; this._pleaseHelpText.Name = "_pleaseHelpText"; this._pleaseHelpText.ReadOnly = true; // // _notificationText // resources.ApplyResources(this._notificationText, "_notificationText"); this._notificationText.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); this._notificationText.BorderStyle = System.Windows.Forms.BorderStyle.None; this._notificationText.ForeColor = System.Drawing.Color.Black; this._notificationText.Name = "_notificationText"; this._notificationText.ReadOnly = true; // // textBox1 // resources.ApplyResources(this.textBox1, "textBox1"); this.textBox1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); this.textBox1.BorderStyle = System.Windows.Forms.BorderStyle.None; this.textBox1.ForeColor = System.Drawing.Color.Black; this.textBox1.Name = "textBox1"; this.textBox1.ReadOnly = true; // // _methodCombo // resources.ApplyResources(this._methodCombo, "_methodCombo"); this._methodCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this._methodCombo.FormattingEnabled = true; this._methodCombo.Name = "_methodCombo"; this._methodCombo.SelectedIndexChanged += new System.EventHandler(this._methodCombo_SelectedIndexChanged); // // _privacyNoticeButton // resources.ApplyResources(this._privacyNoticeButton, "_privacyNoticeButton"); this._privacyNoticeButton.Image = global::Palaso.UI.WindowsForms.Properties.Resources.spy16x16; this._privacyNoticeButton.Name = "_privacyNoticeButton"; this._privacyNoticeButton.UseVisualStyleBackColor = true; this._privacyNoticeButton.Click += new System.EventHandler(this._privacyNoticeButton_Click); // // _emailAddress // resources.ApplyResources(this._emailAddress, "_emailAddress"); this._emailAddress.ForeColor = System.Drawing.Color.DimGray; this._emailAddress.Name = "_emailAddress"; // // ExceptionReportingDialog // this.AcceptButton = this._sendAndCloseButton; resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); this.ControlBox = false; this.Controls.Add(this._emailAddress); this.Controls.Add(this._privacyNoticeButton); this.Controls.Add(this._methodCombo); this.Controls.Add(this.textBox1); this.Controls.Add(this.m_reproduce); this.Controls.Add(this._notificationText); this.Controls.Add(this._pleaseHelpText); this.Controls.Add(this._details); this.Controls.Add(this.label3); this.Controls.Add(this._sendAndCloseButton); this.KeyPreview = true; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "ExceptionReportingDialog"; this.TopMost = true; this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.ExceptionReportingDialog_KeyPress); this.ResumeLayout(false); this.PerformLayout(); } private void SetupMethodCombo() { _methodCombo.Items.Clear(); _methodCombo.Items.Add(new ReportingMethod("Send using my email program", "&Email", "mapiWithPopup", SendViaEmail)); _methodCombo.Items.Add(new ReportingMethod("Copy to clipboard", "&Copy", "clipboard", PutOnClipboard)); } class ReportingMethod { private readonly string _label; public readonly string CloseButtonLabel; public readonly string Id; public readonly Func<bool> Method; public ReportingMethod(string label, string closeButtonLabel, string id, Func<bool> method) { _label = label; CloseButtonLabel = closeButtonLabel; Id = id; Method = method; } public override string ToString() { return _label; } } #endregion /// ------------------------------------------------------------------------------------ /// <summary> /// show a dialog or output to the error log, as appropriate. /// </summary> /// <param name="error">the exception you want to report</param> /// ------------------------------------------------------------------------------------ internal static void ReportException(Exception error) { ReportException(error, null); } /// <summary> /// /// </summary> /// <param name="error"></param> /// <param name="parent"></param> internal static void ReportException(Exception error, Form parent) { ReportException(error, null, true); } /// ------------------------------------------------------------------------------------ /// <summary> /// show a dialog or output to the error log, as appropriate. /// </summary> /// <param name="error">the exception you want to report</param> /// <param name="parent">the parent form that this error belongs to (i.e. the form /// show modally on)</param> /// ------------------------------------------------------------------------------------ /// <param name="isLethal"></param> internal static void ReportException(Exception error, Form parent, bool isLethal) { if (s_doIgnoreReport) { lock (s_reportDataStack) { s_reportDataStack.Push(new ExceptionReportingData(null, null, error, null, parent, Thread.CurrentThread.ManagedThreadId)); } return; // ignore message if we are showing from a previous error } using (ExceptionReportingDialog dlg = new ExceptionReportingDialog(isLethal)) { dlg.Report(error, parent); } } internal static void ReportMessage(string message, StackTrace stack, bool isLethal) { if (s_doIgnoreReport) { lock (s_reportDataStack) { s_reportDataStack.Push(new ExceptionReportingData(message, null, null, stack, null, Thread.CurrentThread.ManagedThreadId)); } return; // ignore message if we are showing from a previous error } using (ExceptionReportingDialog dlg = new ExceptionReportingDialog(isLethal)) { dlg.Report(message, string.Empty, stack, null); } } internal static void ReportMessage(string message, Exception error, bool isLethal) { if (s_doIgnoreReport) { lock (s_reportDataStack) { s_reportDataStack.Push(new ExceptionReportingData(message, null, error, null, null, Thread.CurrentThread.ManagedThreadId)); } return; // ignore message if we are showing from a previous error } using (ExceptionReportingDialog dlg = new ExceptionReportingDialog(isLethal)) { dlg.Report(message, null, error,null); } } protected void GatherData() { _details.Text += Environment.NewLine + "To Reproduce: " + m_reproduce.Text + Environment.NewLine; } public void Report(Exception error, Form owningForm) { Report(null,null, error, owningForm); } public void Report(string message, string messageBeforeStack, Exception error, Form owningForm) { lock (s_reportDataStack) { s_reportDataStack.Push(new ExceptionReportingData(message, messageBeforeStack, error, null, owningForm, Thread.CurrentThread.ManagedThreadId)); } if (WinFormsExceptionHandler.InvokeRequired) { // we got called from a background thread. WinFormsExceptionHandler.ControlOnUIThread.Invoke( new Action(ReportInternal)); return; } ReportInternal(); } public void Report(string message, string messageBeforeStack, StackTrace stackTrace, Form owningForm) { lock (s_reportDataStack) { s_reportDataStack.Push(new ExceptionReportingData(message, messageBeforeStack, null, stackTrace, owningForm, Thread.CurrentThread.ManagedThreadId)); } if (WinFormsExceptionHandler.InvokeRequired) { // we got called from a background thread. WinFormsExceptionHandler.ControlOnUIThread.Invoke( new Action(ReportInternal)); return; } ReportInternal(); } private void ReportInternal() { // This method will/should always be called on the UI thread Debug.Assert(!WinFormsExceptionHandler.InvokeRequired); ExceptionReportingData reportingData; lock (s_reportDataStack) { if (s_reportDataStack.Count <= 0) return; reportingData = s_reportDataStack.Pop(); } ReportExceptionToAnalytics(reportingData); if (s_doIgnoreReport) return; // ignore message if we are showing from a previous error PrepareDialog(); if(!string.IsNullOrEmpty(reportingData.Message)) _notificationText.Text = reportingData.Message; var bldr = new StringBuilder(); var innerMostException = FormatMessage(bldr, reportingData); bldr.Append(AddMessagesFromBackgroundThreads()); _details.Text += bldr.ToString(); Debug.WriteLine(_details.Text); var error = reportingData.Error; if (error != null) { if (innerMostException != null) { error = innerMostException; } try { Logger.WriteEvent("Got exception " + error.GetType().Name); } catch (Exception err) { //We have more than one report of dieing while logging an exception. _details.Text += "****Could not write to log (" + err.Message + ")" + Environment.NewLine; _details.Text += "Was trying to log the exception: " + error.Message + Environment.NewLine; _details.Text += "Recent events:" + Environment.NewLine; _details.Text += Logger.MinorEventsLog; } } else { try { Logger.WriteEvent("Got error message " + reportingData.Message); } catch (Exception err) { //We have more than one report of dieing while logging an exception. _details.Text += "****Could not write to log (" + err.Message + ")" + Environment.NewLine; } } ShowReportDialogIfAppropriate(reportingData.OwningForm); } private static void ReportExceptionToAnalytics(ExceptionReportingData reportingData) { try { if (!string.IsNullOrEmpty(reportingData.Message)) UsageReporter.ReportExceptionString(reportingData.Message); else if (reportingData.Error != null) UsageReporter.ReportException(reportingData.Error); } catch { //swallow } } private static string AddMessagesFromBackgroundThreads() { var bldr = new StringBuilder(); for (bool messageOnStack = AddNextMessageFromStack(bldr); messageOnStack;) messageOnStack = AddNextMessageFromStack(bldr); return bldr.ToString(); } private static bool AddNextMessageFromStack(StringBuilder bldr) { ExceptionReportingData data; lock (s_reportDataStack) { if (s_reportDataStack.Count <= 0) return false; data = s_reportDataStack.Pop(); } ReportExceptionToAnalytics(data); bldr.AppendLine("---------------------------------"); bldr.AppendFormat("The following exception occurred on a different thread ({0}) at about the same time:", data.ThreadId); bldr.AppendLine(); bldr.AppendLine(); FormatMessage(bldr, data); return true; } private static Exception FormatMessage(StringBuilder bldr, ExceptionReportingData data) { if (!string.IsNullOrEmpty(data.Message)) { bldr.Append("Message (not an exception): "); bldr.AppendLine(data.Message); bldr.AppendLine(); } if (!string.IsNullOrEmpty(data.MessageBeforeStack)) { bldr.AppendLine(data.MessageBeforeStack); } if (data.Error != null) { Exception innerMostException = null; bldr.Append(ErrorReport.GetHiearchicalExceptionInfo(data.Error, ref innerMostException)); //if the exception had inner exceptions, show the inner-most exception first, since that is usually the one //we want the developer to read. if (innerMostException != null) { var oldText = bldr.ToString(); bldr.Clear(); bldr.AppendLine("Inner-most exception:"); bldr.AppendLine(ErrorReport.GetExceptionText(innerMostException)); bldr.AppendLine(); bldr.AppendLine("Full, hierarchical exception contents:"); bldr.Append(oldText); } AddErrorReportingPropertiesToDetails(bldr); return innerMostException; } if (data.StackTrace != null) { bldr.AppendLine("--Stack--"); bldr.AppendLine(data.StackTrace.ToString()); } return null; } private static void AddErrorReportingPropertiesToDetails(StringBuilder bldr) { bldr.AppendLine(); bldr.AppendLine("--Error Reporting Properties--"); foreach (string label in ErrorReport.Properties.Keys) { bldr.Append(label); bldr.Append(": "); bldr.AppendLine(ErrorReport.Properties[label]); } bldr.AppendLine(); bldr.AppendLine("--Log--"); try { bldr.Append(Logger.LogText); } catch (Exception err) { //We have more than one report of dieing while logging an exception. bldr.AppendLine("****Could not read from log: " + err.Message); } } private void PrepareDialog() { CheckDisposed(); Font = SystemFonts.MessageBoxFont; // // Required for Windows Form Designer support // InitializeComponent(); _emailAddress.Text = ErrorReport.EmailAddress; SetupMethodCombo(); foreach (ReportingMethod method in _methodCombo.Items) { if (ErrorReportSettings.Default.ReportingMethod == method.Id) { SelectedMethod = method; break; } } if (!_isLethal) { BackColor = Color.FromArgb(255, 255, 192); //yellow _notificationText.Text = "Take Courage. It'll work out."; _notificationText.BackColor = BackColor; _pleaseHelpText.BackColor = BackColor; textBox1.BackColor = BackColor; } SetupCloseButtonText(); } private void ShowReportDialogIfAppropriate(Form owningForm) { if (ErrorReport.IsOkToInteractWithUser) { s_doIgnoreReport = true; ShowDialog(owningForm); s_doIgnoreReport = false; } else //the test environment already prohibits dialogs but will save the contents of assertions in some log. { Debug.Fail(_details.Text); } } /// ------------------------------------------------------------------------------------ /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> /// ------------------------------------------------------------------------------------ private void btnClose_Click(object sender, EventArgs e) { ErrorReportSettings.Default.ReportingMethod = ((ReportingMethod) (_methodCombo.SelectedItem)).Id; ErrorReportSettings.Default.Save(); if (ModifierKeys.Equals(Keys.Shift)) { return; } GatherData(); // Clipboard.SetDataObject(_details.Text, true); if (SelectedMethod.Method()) { CloseUp(); } else { PutOnClipboard(); CloseUp(); } } private bool PutOnClipboard() { if (ErrorReport.EmailAddress != null) { _details.Text = String.Format("Please e-mail this to {0} {1}", ErrorReport.EmailAddress, _details.Text); } #if MONO try { // Workaround for Xamarin bug #4959. Eberhard had a mono fix for that bug // but it doesn't work with FW (or Palaso) -- he couldn't figure out why not. // This is a dirty hack but at least it works :-) var clipboardAtom = gdk_atom_intern("CLIPBOARD", true); var clipboard = gtk_clipboard_get(clipboardAtom); if (clipboard != IntPtr.Zero) { gtk_clipboard_set_text(clipboard, _details.Text, -1); gtk_clipboard_store(clipboard); } } catch { // ignore any errors - most likely because gtk isn't installed? return false; } #else Clipboard.SetDataObject(_details.Text, true); #endif return true; } #if MONO // Workaround for Xamarin bug #4959 [DllImport("libgdk-x11-2.0")] internal extern static IntPtr gdk_atom_intern(string atomName, bool onlyIfExists); [DllImport("libgtk-x11-2.0")] internal extern static IntPtr gtk_clipboard_get(IntPtr atom); [DllImport("libgtk-x11-2.0")] internal extern static void gtk_clipboard_store(IntPtr clipboard); [DllImport("libgtk-x11-2.0")] internal extern static void gtk_clipboard_set_text(IntPtr clipboard, [MarshalAs(UnmanagedType.LPStr)] string text, int len); #endif private bool SendViaEmail() { try { var emailProvider = EmailProviderFactory.PreferredEmailProvider(); var emailMessage = emailProvider.CreateMessage(); emailMessage.To.Add(ErrorReport.EmailAddress); emailMessage.Subject = ErrorReport.EmailSubject; emailMessage.Body = _details.Text; if (emailMessage.Send(emailProvider)) { CloseUp(); return true; } } catch (Exception) { //swallow it and go to the alternate method } try { //EmailMessage msg = new EmailMessage(); // This currently does not work. The main issue seems to be the length of the error report. mailto // apparently has some limit on the length of the message, and we are exceeding that. var emailProvider = EmailProviderFactory.PreferredEmailProvider(); var emailMessage = emailProvider.CreateMessage(); emailMessage.To.Add(ErrorReport.EmailAddress); emailMessage.Subject = ErrorReport.EmailSubject; if (Environment.OSVersion.Platform == PlatformID.Unix) { emailMessage.Body = _details.Text; } else { PutOnClipboard(); emailMessage.Body = "<Details of the crash have been copied to the clipboard. Please paste them here>"; } if (emailMessage.Send(emailProvider)) { CloseUp(); return true; } } catch (Exception error) { PutOnClipboard(); ErrorReport.NotifyUserOfProblem(error, "This program wasn't able to get your email program, if you have one, to send the error message. " + "The contents of the error message has been placed on your Clipboard."); return false; } return false; } private void CloseUp() { if (!_isLethal || ModifierKeys.Equals(Keys.Shift)) { try { Logger.WriteEvent("Error Dialog: Continuing..."); } catch (Exception) { //really can't handle an embedded error related to logging } Close(); return; } try { Logger.WriteEvent("Error Dialog: Exiting..."); } catch (Exception) { //really can't handle an embedded error related to logging } Process.GetCurrentProcess().Kill(); } /// ------------------------------------------------------------------------------------ /// <summary> /// Shows the attempt to continue label if the shift key is pressed /// </summary> /// <param name="e"></param> /// ------------------------------------------------------------------------------------ protected override void OnKeyDown(KeyEventArgs e) { if (e.KeyCode == Keys.ShiftKey && Visible) { _sendAndCloseButton.Text = "Continue"; } base.OnKeyDown(e); } /// ------------------------------------------------------------------------------------ /// <summary> /// Hides the attempt to continue label if the shift key is pressed /// </summary> /// <param name="e"></param> /// ------------------------------------------------------------------------------------ protected override void OnKeyUp(KeyEventArgs e) { if (e.KeyCode == Keys.ShiftKey && Visible) { SetupCloseButtonText(); } base.OnKeyUp(e); } private void OnJustExit_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { CloseUp(); } private void _methodCombo_SelectedIndexChanged(object sender, EventArgs e) { SetupCloseButtonText(); } private void SetupCloseButtonText() { _sendAndCloseButton.Text = SelectedMethod.CloseButtonLabel; if (!_isLethal) { // _dontSendEmailLink.Text = "Don't Send Email"; } else { _sendAndCloseButton.Text += " and Exit"; } } private ReportingMethod SelectedMethod { get { return ((ReportingMethod) _methodCombo.SelectedItem); } set { _methodCombo.SelectedItem = value; } } private void _privacyNoticeButton_Click(object sender, EventArgs e) { MessageBox.Show( @"If you don't care who reads your bug report, you can skip this notice. When you submit a crash report or other issue, the contents of your email go in our issue tracking system, ""jira"", which is available via the web at http://jira.palaso.org/issues. This is the normal way to handle issues in an open-source project. Our issue-tracking system is not searchable by those without an account. Therefore, someone searching via Google will not find your bug reports. However, anyone can make an account and then read what you sent us. So if you have something private to say, please send it to one of the developers privately with a note that you don't want the issue in our issue tracking system. If need be, we'll make some kind of sanitized place-holder for your issue so that we don't lose it. ", "Privacy Notice"); } private void ExceptionReportingDialog_KeyPress(object sender, KeyPressEventArgs e) { if(e.KeyChar== 27)//ESCAPE { CloseUp(); } } } }
using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Data.SqlServerCe; using System.Collections; using System.Windows.Forms; using DowUtils; namespace Factotum{ public enum ComponentSectionEnum : short { UsMain = 0, UsExt = 1, DsMain = 2, DsExt = 3, Br = 4, BrExt = 5 } public class EAdditionalMeasurement : IEntity { public static event EventHandler<EntityChangedEventArgs> Changed; protected virtual void OnChanged(Guid? ID) { // Copy to a temporary variable to be thread-safe. EventHandler<EntityChangedEventArgs> temp = Changed; if (temp != null) temp(this, new EntityChangedEventArgs(ID)); } // Mapped database columns // Use Guid?s for Primary Keys and foreign keys (whether they're nullable or not). // Use int?, decimal?, etc for numbers (whether they're nullable or not). // Strings, images, etc, are reference types already private Guid? AdmDBid; private string AdmName; private Guid? AdmDstID; private string AdmDescription; private decimal? AdmThickness; private bool AdmIncludeInStats; private short? AdmComponentSection; // Textbox limits // field size is 20, but limit to 14 for nice report fit public static int AdmNameCharLimit = 14; // field size is currently 255, but limit to 44, so it fits on the report nicely. public static int AdmDescriptionCharLimit = 65; public static int AdmThicknessCharLimit = 7; // Field-specific error message strings (normally just needed for textbox data) private string AdmNameErrMsg; private string AdmDescriptionErrMsg; private string AdmThicknessErrMsg; // Form level validation message private string AdmErrMsg; //-------------------------------------------------------- // Field Properties //-------------------------------------------------------- // Primary key accessor public Guid? ID { get { return AdmDBid; } } public string AdditionalMeasurementName { get { return AdmName; } set { AdmName = Util.NullifyEmpty(value); } } public Guid? AdditionalMeasurementDstID { get { return AdmDstID; } set { AdmDstID = value; } } public string AdditionalMeasurementDescription { get { return AdmDescription; } set { AdmDescription = Util.NullifyEmpty(value); } } public decimal? AdditionalMeasurementThickness { get { return AdmThickness; } set { AdmThickness = value; } } public bool AdditionalMeasurementIncludeInStats { get { return AdmIncludeInStats; } set { AdmIncludeInStats = value; } } public short? AdditionalMeasurementComponentSection { get { return AdmComponentSection; } set { AdmComponentSection = value; } } // Array of ComponentSections for combo box binding static public ComponentSection[] GetComponentSectionsArray() { return new ComponentSection[] { new ComponentSection(null, "N/A"), new ComponentSection((short?)ComponentSectionEnum.UsMain,"Upstream Main"), new ComponentSection((short?)ComponentSectionEnum.UsExt,"Upstream Ext."), new ComponentSection((short?)ComponentSectionEnum.DsMain,"Downstream Main"), new ComponentSection((short?)ComponentSectionEnum.DsExt,"Downstream Ext."), new ComponentSection((short?)ComponentSectionEnum.Br,"Branch"), new ComponentSection((short?)ComponentSectionEnum.BrExt,"Branch Ext.") }; } //----------------------------------------------------------------- // Field Level Error Messages. // Include one for every text column // In cases where we need to ensure data consistency, we may need // them for other types. //----------------------------------------------------------------- public string AdditionalMeasurementNameErrMsg { get { return AdmNameErrMsg; } } public string AdditionalMeasurementDescriptionErrMsg { get { return AdmDescriptionErrMsg; } } public string AdditionalMeasurementThicknessErrMsg { get { return AdmThicknessErrMsg; } } //-------------------------------------- // Form level Error Message //-------------------------------------- public string AdditionalMeasurementErrMsg { get { return AdmErrMsg; } set { AdmErrMsg = Util.NullifyEmpty(value); } } //-------------------------------------- // Textbox Name Length Validation //-------------------------------------- public bool AdditionalMeasurementNameLengthOk(string s) { if (s == null) return true; if (s.Length > AdmNameCharLimit) { AdmNameErrMsg = string.Format("Additional Measurement Names cannot exceed {0} characters", AdmNameCharLimit); return false; } else { AdmNameErrMsg = null; return true; } } public bool AdditionalMeasurementDescriptionLengthOk(string s) { if (s == null) return true; if (s.Length > AdmDescriptionCharLimit) { AdmDescriptionErrMsg = string.Format("Additional Measurement Descriptions cannot exceed {0} characters", AdmDescriptionCharLimit); return false; } else { AdmDescriptionErrMsg = null; return true; } } public bool AdditionalMeasurementThicknessLengthOk(string s) { if (s == null) return true; if (s.Length > AdmThicknessCharLimit) { AdmThicknessErrMsg = string.Format("Additional Measurement Thicknesss cannot exceed {0} characters", AdmThicknessCharLimit); return false; } else { AdmThicknessErrMsg = null; return true; } } //-------------------------------------- // Field-Specific Validation // sets and clears error messages //-------------------------------------- public bool AdditionalMeasurementNameValid(string name) { if (!AdditionalMeasurementNameLengthOk(name)) return false; // KEEP, MODIFY OR REMOVE THIS AS REQUIRED // YOU MAY NEED THE NAME TO BE UNIQUE FOR A SPECIFIC PARENT, ETC.. if (NameExists(name, AdmDBid)) { AdmNameErrMsg = "That Additional Measurement Name is already in use."; return false; } AdmNameErrMsg = null; return true; } public bool AdditionalMeasurementDescriptionValid(string value) { if (!AdditionalMeasurementDescriptionLengthOk(value)) return false; AdmDescriptionErrMsg = null; return true; } public bool AdditionalMeasurementThicknessValid(string value) { if (Util.IsNullOrEmpty(value)) { AdmThicknessErrMsg = null; return true; } decimal result; if (decimal.TryParse(value, out result) && result > 0 && result < 100) { AdmThicknessErrMsg = null; return true; } AdmThicknessErrMsg = string.Format("Please enter a positive number less than 100"); return false; } //-------------------------------------- // Constructors //-------------------------------------- // Default constructor. Field defaults must be set here. // Any defaults set by the database will be overridden. public EAdditionalMeasurement() { this.AdmIncludeInStats = true; } // Constructor which loads itself from the supplied id. // If the id is null, this gives the same result as using the default constructor. public EAdditionalMeasurement(Guid? id) : this() { Load(id); } //-------------------------------------- // Public Methods //-------------------------------------- //---------------------------------------------------- // Load the object from the database given a Guid? //---------------------------------------------------- public void Load(Guid? id) { if (id == null) return; SqlCeCommand cmd = Globals.cnn.CreateCommand(); SqlCeDataReader dr; cmd.CommandType = CommandType.Text; cmd.CommandText = @"Select AdmDBid, AdmName, AdmDstID, AdmDescription, AdmThickness, AdmIncludeInStats, AdmComponentSection from AdditionalMeasurements where AdmDBid = @p0"; cmd.Parameters.Add(new SqlCeParameter("@p0", id)); if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); dr = cmd.ExecuteReader(); // The query should return one record. // If it doesn't return anything (no match) the object is not affected if (dr.Read()) { // For all nullable values, replace dbNull with null AdmDBid = (Guid?)dr[0]; AdmName = (string)dr[1]; AdmDstID = (Guid?)dr[2]; AdmDescription = (string)Util.NullForDbNull(dr[3]); AdmThickness = (decimal?)Util.NullForDbNull(dr[4]); AdmIncludeInStats = (bool)dr[5]; AdmComponentSection = (short?)Util.NullForDbNull(dr[6]); } dr.Close(); } //-------------------------------------- // Save the current record if it's valid //-------------------------------------- public Guid? Save() { if (!Valid()) { // Note: We're returning null if we fail, // so don't just assume you're going to get your id back // and set your id to the result of this function call. return null; } SqlCeCommand cmd = Globals.cnn.CreateCommand(); cmd.CommandType = CommandType.Text; if (ID == null) { // we are inserting a new record // first ask the database for a new Guid cmd.CommandText = "Select Newid()"; if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); AdmDBid = (Guid?)(cmd.ExecuteScalar()); // Replace any nulls with dbnull cmd.Parameters.AddRange(new SqlCeParameter[] { new SqlCeParameter("@p0", AdmDBid), new SqlCeParameter("@p1", AdmName), new SqlCeParameter("@p2", AdmDstID), new SqlCeParameter("@p3", Util.DbNullForNull(AdmDescription)), new SqlCeParameter("@p4", Util.DbNullForNull(AdmThickness)), new SqlCeParameter("@p5", AdmIncludeInStats), new SqlCeParameter("@p6", Util.DbNullForNull(AdmComponentSection)) }); cmd.CommandText = @"Insert Into AdditionalMeasurements ( AdmDBid, AdmName, AdmDstID, AdmDescription, AdmThickness, AdmIncludeInStats, AdmComponentSection ) values (@p0,@p1,@p2,@p3,@p4,@p5,@p6)"; if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); if (cmd.ExecuteNonQuery() != 1) { throw new Exception("Unable to insert Additional Measurements row"); } } else { // we are updating an existing record // Replace any nulls with dbnull cmd.Parameters.AddRange(new SqlCeParameter[] { new SqlCeParameter("@p0", AdmDBid), new SqlCeParameter("@p1", AdmName), new SqlCeParameter("@p2", AdmDstID), new SqlCeParameter("@p3", Util.DbNullForNull(AdmDescription)), new SqlCeParameter("@p4", Util.DbNullForNull(AdmThickness)), new SqlCeParameter("@p5", AdmIncludeInStats), new SqlCeParameter("@p6", Util.DbNullForNull(AdmComponentSection))}); cmd.CommandText = @"Update AdditionalMeasurements set AdmName = @p1, AdmDstID = @p2, AdmDescription = @p3, AdmThickness = @p4, AdmIncludeInStats = @p5, AdmComponentSection = @p6 Where AdmDBid = @p0"; if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); if (cmd.ExecuteNonQuery() != 1) { throw new Exception("Unable to update Additional Measurements row"); } } OnChanged(ID); return ID; } //-------------------------------------- // Validate the current record //-------------------------------------- // Make this public so that the UI can check validation itself // if it chooses to do so. This is also called by the Save function. public bool Valid() { // First check each field to see if it's valid from the UI perspective if (!AdditionalMeasurementNameValid(AdditionalMeasurementName)) return false; if (!AdditionalMeasurementDescriptionValid(AdditionalMeasurementDescription)) return false; // Check form to make sure all required fields have been filled in if (!RequiredFieldsFilled()) return false; // Check for incorrect field interactions... return true; } //-------------------------------------- // Delete the current record //-------------------------------------- public bool Delete(bool promptUser) { // If the current object doesn't reference a database record, there's nothing to do. if (AdmDBid == null) { AdditionalMeasurementErrMsg = "Unable to delete. Record not found."; return false; } DialogResult rslt = DialogResult.None; if (promptUser) { rslt = MessageBox.Show("Are you sure?", "Factotum: Deleting...", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); } if (!promptUser || rslt == DialogResult.OK) { SqlCeCommand cmd = Globals.cnn.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = @"Delete from AdditionalMeasurements where AdmDBid = @p0"; cmd.Parameters.Add("@p0", AdmDBid); if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); int rowsAffected = cmd.ExecuteNonQuery(); // Todo: figure out how I really want to do this. // Is there a problem with letting the database try to do cascading deletes? // How should the user be notified of the problem?? if (rowsAffected < 1) { AdditionalMeasurementErrMsg = "Unable to delete. Please try again later."; return false; } else { OnChanged(ID); return true; } } else { return false; } } //-------------------------------------------------------------------- // Static listing methods which return collections of additionalmeasurements //-------------------------------------------------------------------- // This helper function builds the collection for you based on the flags you send it // I originally had a flag that would let you indicate inactive items by appending '(inactive)' // to the name. This was a bad idea, because sometimes the objects in this collection // will get modified and saved back to the database -- with the extra text appended to the name. public static EAdditionalMeasurementCollection ListByNameForInspection(Guid InspectionID) { EAdditionalMeasurement additionalmeasurement; EAdditionalMeasurementCollection additionalmeasurements = new EAdditionalMeasurementCollection(); SqlCeCommand cmd = Globals.cnn.CreateCommand(); cmd.CommandType = CommandType.Text; string qry = @"Select AdmDBid, AdmName, AdmDstID, AdmDescription, AdmThickness, AdmIncludeInStats, AdmComponentSection from AdditionalMeasurements inner join Dsets on AdmDstID = DstDBid"; qry += " where DstIspID = @p1"; qry += " order by AdmName"; cmd.CommandText = qry; cmd.Parameters.Add("@p1", InspectionID); SqlCeDataReader dr; if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); dr = cmd.ExecuteReader(); // Build new objects and add them to the collection while (dr.Read()) { additionalmeasurement = new EAdditionalMeasurement((Guid?)dr[0]); additionalmeasurement.AdmName = (string)(dr[1]); additionalmeasurement.AdmDstID = (Guid?)(dr[2]); additionalmeasurement.AdmDescription = (string)Util.NullForDbNull(dr[3]); additionalmeasurement.AdmThickness = (decimal?)Util.NullForDbNull(dr[4]); additionalmeasurement.AdmIncludeInStats = (bool)(dr[5]); additionalmeasurement.AdmComponentSection = (short?)(dr[6]); additionalmeasurements.Add(additionalmeasurement); } // Finish up dr.Close(); return additionalmeasurements; } // Get a Default data view with all columns that a user would likely want to see. // You can bind this view to a DataGridView, hide the columns you don't need, filter, etc. // I decided not to indicate inactive in the names of inactive items. The 'user' // can always show the inactive column if they wish. public static DataView GetDefaultDataViewForDset(Guid? dsetID) { DataSet ds = new DataSet(); DataView dv; SqlCeDataAdapter da = new SqlCeDataAdapter(); SqlCeCommand cmd = Globals.cnn.CreateCommand(); cmd.CommandType = CommandType.Text; // Changing the booleans to 'Yes' and 'No' eliminates the silly checkboxes and // makes the column sortable. // You'll likely want to modify this query further, joining in other tables, etc. string qry = @"Select AdmDBid as ID, AdmName as AdditionalMeasurementName, AdmDstID as AdditionalMeasurementDstID, AdmDescription as AdditionalMeasurementDescription, AdmThickness as AdditionalMeasurementThickness, CASE WHEN AdmIncludeInStats = 0 THEN 'No' ELSE 'Yes' END as AdditionalMeasurementIncludeInStats, CASE WHEN AdmComponentSection = 0 THEN 'Upstream Main' WHEN AdmComponentSection = 1 THEN 'Upstream Ext.' WHEN AdmComponentSection = 2 THEN 'Downstream Main' WHEN AdmComponentSection = 3 THEN 'Downstream Ext.' WHEN AdmComponentSection = 4 THEN 'Branch' WHEN AdmComponentSection = 5 THEN 'Branch Ext.' ELSE 'N/A' END as AdditionalMeasurementComponentSection from AdditionalMeasurements Where AdmDstID = @p1"; cmd.CommandText = qry; cmd.Parameters.Add("@p1", dsetID == null ? Guid.Empty : dsetID); da.SelectCommand = cmd; if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); da.Fill(ds); dv = new DataView(ds.Tables[0]); return dv; } //-------------------------------------- // Private utilities //-------------------------------------- // Check if the name exists for any records besides the current one // This is used to show an error when the user tabs away from the field. // We don't want to show an error if the user has left the field blank. // If it's a required field, we'll catch it when the user hits save. private bool NameExists(string name, Guid? id) { if (Util.IsNullOrEmpty(name)) return false; SqlCeCommand cmd = Globals.cnn.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.Parameters.Add(new SqlCeParameter("@p1", name)); cmd.Parameters.Add(new SqlCeParameter("@p2", AdmDstID)); if (id == null) { cmd.CommandText = "Select AdmDBid from AdditionalMeasurements where AdmName = @p1 and AdmDstID = @p2"; } else { cmd.CommandText = "Select AdmDBid from AdditionalMeasurements where AdmName = @p1 and AdmDstID = @p2 and AdmDBid != @p0"; cmd.Parameters.Add(new SqlCeParameter("@p0", id)); } if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); object val = cmd.ExecuteScalar(); bool exists = (val != null); return exists; } // Check for required fields, setting the individual error messages private bool RequiredFieldsFilled() { bool allFilled = true; if (AdditionalMeasurementName == null) { AdmNameErrMsg = "A unique Additional Measurement Name is required"; allFilled = false; } else { AdmNameErrMsg = null; } return allFilled; } } //-------------------------------------- // AdditionalMeasurement Collection class //-------------------------------------- public class EAdditionalMeasurementCollection : CollectionBase { //this event is fired when the collection's items have changed public event EventHandler Changed; //this is the constructor of the collection. public EAdditionalMeasurementCollection() { } //the indexer of the collection public EAdditionalMeasurement this[int index] { get { return (EAdditionalMeasurement)this.List[index]; } } //this method fires the Changed event. protected virtual void OnChanged(EventArgs e) { if (Changed != null) { Changed(this, e); } } public bool ContainsID(Guid? ID) { if (ID == null) return false; foreach (EAdditionalMeasurement additionalmeasurement in InnerList) { if (additionalmeasurement.ID == ID) return true; } return false; } //returns the index of an item in the collection public int IndexOf(EAdditionalMeasurement item) { return InnerList.IndexOf(item); } //adds an item to the collection public void Add(EAdditionalMeasurement item) { this.List.Add(item); OnChanged(EventArgs.Empty); } //inserts an item in the collection at a specified index public void Insert(int index, EAdditionalMeasurement item) { this.List.Insert(index, item); OnChanged(EventArgs.Empty); } //removes an item from the collection. public void Remove(EAdditionalMeasurement item) { this.List.Remove(item); OnChanged(EventArgs.Empty); } } public class ComponentSection { private short? id; public short? ID { get { return id; } set { id = value; } } private string name; public string Name { get { return name; } set { name = value; } } public ComponentSection(short? ID, string Name) { this.id = ID; this.name = Name; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace System.IO { /// <summary> /// Wrapper to help with path normalization. /// </summary> internal class PathHelper { // Can't be over 8.3 and be a short name private const int MaxShortName = 12; private const char LastAnsi = (char)255; private const char Delete = (char)127; /// <summary> /// Normalize the given path. /// </summary> /// <remarks> /// Normalizes via Win32 GetFullPathName(). Will also trim initial /// spaces if the path is determined to be rooted. /// /// Note that invalid characters will be checked after the path is normalized, which could remove bad characters. (C:\|\..\a.txt -- C:\a.txt) /// </remarks> /// <param name="path">Path to normalize</param> /// <param name="checkInvalidCharacters">True to check for invalid characters</param> /// <param name="expandShortPaths">Attempt to expand short paths if true</param> /// <exception cref="ArgumentException">Thrown if the path is an illegal UNC (does not contain a full server/share) or contains illegal characters.</exception> /// <exception cref="PathTooLongException">Thrown if the path or a path segment exceeds the filesystem limits.</exception> /// <exception cref="FileNotFoundException">Thrown if Windows returns ERROR_FILE_NOT_FOUND. (See Win32Marshal.GetExceptionForWin32Error)</exception> /// <exception cref="DirectoryNotFoundException">Thrown if Windows returns ERROR_PATH_NOT_FOUND. (See Win32Marshal.GetExceptionForWin32Error)</exception> /// <exception cref="UnauthorizedAccessException">Thrown if Windows returns ERROR_ACCESS_DENIED. (See Win32Marshal.GetExceptionForWin32Error)</exception> /// <exception cref="IOException">Thrown if Windows returns an error that doesn't map to the above. (See Win32Marshal.GetExceptionForWin32Error)</exception> /// <returns>Normalized path</returns> internal static string Normalize(string path, bool checkInvalidCharacters, bool expandShortPaths) { // Get the full path StringBuffer fullPath = new StringBuffer(PathInternal.MaxShortPath); try { GetFullPathName(path, ref fullPath); // Checking path validity used to happen before getting the full path name. To avoid additional input allocation // (to trim trailing whitespace) we now do it after the Win32 call. This will allow legitimate paths through that // used to get kicked back (notably segments with invalid characters might get removed via ".."). // // There is no way that GetLongPath can invalidate the path so we'll do this (cheaper) check before we attempt to // expand short file names. // Scan the path for: // // - Illegal path characters. // - Invalid UNC paths like \\, \\server, \\server\. // As the path could be > 30K, we'll combine the validity scan. None of these checks are performed by the Win32 // GetFullPathName() API. bool possibleShortPath = false; bool foundTilde = false; // We can get UNCs as device paths through this code (e.g. \\.\UNC\), we won't validate them as there isn't // an easy way to normalize without extensive cost (we'd have to hunt down the canonical name for any device // path that contains UNC or to see if the path was doing something like \\.\GLOBALROOT\Device\Mup\, // \\.\GLOBAL\UNC\, \\.\GLOBALROOT\GLOBAL??\UNC\, etc. bool specialPath = fullPath.Length > 1 && fullPath[0] == '\\' && fullPath[1] == '\\'; bool isDevice = PathInternal.IsDevice(ref fullPath); bool possibleBadUnc = specialPath && !isDevice; int index = specialPath ? 2 : 0; int lastSeparator = specialPath ? 1 : 0; int segmentLength; char current; while (index < fullPath.Length) { current = fullPath[index]; // Try to skip deeper analysis. '?' and higher are valid/ignorable except for '\', '|', and '~' if (current < '?' || current == '\\' || current == '|' || current == '~') { switch (current) { case '|': case '>': case '<': case '\"': if (checkInvalidCharacters) throw new ArgumentException(SR.Argument_InvalidPathChars); foundTilde = false; break; case '~': foundTilde = true; break; case '\\': segmentLength = index - lastSeparator - 1; lastSeparator = index; if (foundTilde) { if (segmentLength <= MaxShortName) { // Possibly a short path. possibleShortPath = true; } foundTilde = false; } if (possibleBadUnc) { // If we're at the end of the path and this is the first separator, we're missing the share. // Otherwise we're good, so ignore UNC tracking from here. if (index == fullPath.Length - 1) throw new ArgumentException(SR.Format(SR.Arg_PathIllegalUNC_Path, fullPath.ToString())); else possibleBadUnc = false; } break; default: if (checkInvalidCharacters && current < ' ') throw new ArgumentException(SR.Argument_InvalidPathChars, nameof(path)); break; } } index++; } if (possibleBadUnc) throw new ArgumentException(SR.Format(SR.Arg_PathIllegalUNC_Path, fullPath.ToString())); segmentLength = fullPath.Length - lastSeparator - 1; if (foundTilde && segmentLength <= MaxShortName) possibleShortPath = true; // Check for a short filename path and try and expand it. Technically you don't need to have a tilde for a short name, but // this is how we've always done this. This expansion is costly so we'll continue to let other short paths slide. if (expandShortPaths && possibleShortPath) { return TryExpandShortFileName(ref fullPath, originalPath: path); } else { if (fullPath.Length == path.Length && fullPath.StartsWith(path)) { // If we have the exact same string we were passed in, don't bother to allocate another string from the StringBuilder. return path; } else { return fullPath.ToString(); } } } finally { // Clear the buffer fullPath.Free(); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsDosUnc(ref StringBuffer buffer) { return !PathInternal.IsDevice(ref buffer) && buffer.Length > 1 && buffer[0] == '\\' && buffer[1] == '\\'; } private static unsafe void GetFullPathName(string path, ref StringBuffer fullPath) { // If the string starts with an extended prefix we would need to remove it from the path before we call GetFullPathName as // it doesn't root extended paths correctly. We don't currently resolve extended paths, so we'll just assert here. Debug.Assert(PathInternal.IsPartiallyQualified(path) || !PathInternal.IsExtended(path)); // Historically we would skip leading spaces *only* if the path started with a drive " C:" or a UNC " \\" int startIndex = PathInternal.PathStartSkip(path); fixed (char* pathStart = path) { uint result = 0; while ((result = Interop.Kernel32.GetFullPathNameW(pathStart + startIndex, (uint)fullPath.Capacity, fullPath.UnderlyingArray, IntPtr.Zero)) > fullPath.Capacity) { // Reported size is greater than the buffer size. Increase the capacity. fullPath.EnsureCapacity(checked((int)result)); } if (result == 0) { // Failure, get the error and throw int errorCode = Marshal.GetLastWin32Error(); if (errorCode == 0) errorCode = Interop.Errors.ERROR_BAD_PATHNAME; throw Win32Marshal.GetExceptionForWin32Error(errorCode, path); } fullPath.Length = checked((int)result); } } private static int GetInputBuffer(ref StringBuffer content, bool isDosUnc, ref StringBuffer buffer) { int length = content.Length; length += isDosUnc ? PathInternal.UncExtendedPrefixLength - PathInternal.UncPrefixLength : PathInternal.DevicePrefixLength; buffer.EnsureCapacity(length + 1); if (isDosUnc) { // Put the extended UNC prefix (\\?\UNC\) in front of the path buffer.CopyFrom(bufferIndex: 0, source: PathInternal.UncExtendedPathPrefix); // Copy the source buffer over after the existing UNC prefix content.CopyTo( bufferIndex: PathInternal.UncPrefixLength, destination: ref buffer, destinationIndex: PathInternal.UncExtendedPrefixLength, count: content.Length - PathInternal.UncPrefixLength); // Return the prefix difference return PathInternal.UncExtendedPrefixLength - PathInternal.UncPrefixLength; } else { int prefixSize = PathInternal.ExtendedPathPrefix.Length; buffer.CopyFrom(bufferIndex: 0, source: PathInternal.ExtendedPathPrefix); content.CopyTo(bufferIndex: 0, destination: ref buffer, destinationIndex: prefixSize, count: content.Length); return prefixSize; } } private static string TryExpandShortFileName(ref StringBuffer outputBuffer, string originalPath) { // We guarantee we'll expand short names for paths that only partially exist. As such, we need to find the part of the path that actually does exist. To // avoid allocating like crazy we'll create only one input array and modify the contents with embedded nulls. Debug.Assert(!PathInternal.IsPartiallyQualified(ref outputBuffer), "should have resolved by now"); // We'll have one of a few cases by now (the normalized path will have already: // // 1. Dos path (C:\) // 2. Dos UNC (\\Server\Share) // 3. Dos device path (\\.\C:\, \\?\C:\) // // We want to put the extended syntax on the front if it doesn't already have it, which may mean switching from \\.\. // // Note that we will never get \??\ here as GetFullPathName() does not recognize \??\ and will return it as C:\??\ (or whatever the current drive is). int rootLength = PathInternal.GetRootLength(ref outputBuffer); bool isDevice = PathInternal.IsDevice(ref outputBuffer); StringBuffer inputBuffer = new StringBuffer(0); try { bool isDosUnc = false; int rootDifference = 0; bool wasDotDevice = false; // Add the extended prefix before expanding to allow growth over MAX_PATH if (isDevice) { // We have one of the following (\\?\ or \\.\) inputBuffer.Append(ref outputBuffer); if (outputBuffer[2] == '.') { wasDotDevice = true; inputBuffer[2] = '?'; } } else { isDosUnc = IsDosUnc(ref outputBuffer); rootDifference = GetInputBuffer(ref outputBuffer, isDosUnc, ref inputBuffer); } rootLength += rootDifference; int inputLength = inputBuffer.Length; bool success = false; int foundIndex = inputBuffer.Length - 1; while (!success) { uint result = Interop.Kernel32.GetLongPathNameW(inputBuffer.UnderlyingArray, outputBuffer.UnderlyingArray, (uint)outputBuffer.Capacity); // Replace any temporary null we added if (inputBuffer[foundIndex] == '\0') inputBuffer[foundIndex] = '\\'; if (result == 0) { // Look to see if we couldn't find the file int error = Marshal.GetLastWin32Error(); if (error != Interop.Errors.ERROR_FILE_NOT_FOUND && error != Interop.Errors.ERROR_PATH_NOT_FOUND) { // Some other failure, give up break; } // We couldn't find the path at the given index, start looking further back in the string. foundIndex--; for (; foundIndex > rootLength && inputBuffer[foundIndex] != '\\'; foundIndex--) ; if (foundIndex == rootLength) { // Can't trim the path back any further break; } else { // Temporarily set a null in the string to get Windows to look further up the path inputBuffer[foundIndex] = '\0'; } } else if (result > outputBuffer.Capacity) { // Not enough space. The result count for this API does not include the null terminator. outputBuffer.EnsureCapacity(checked((int)result)); result = Interop.Kernel32.GetLongPathNameW(inputBuffer.UnderlyingArray, outputBuffer.UnderlyingArray, (uint)outputBuffer.Capacity); } else { // Found the path success = true; outputBuffer.Length = checked((int)result); if (foundIndex < inputLength - 1) { // It was a partial find, put the non-existent part of the path back outputBuffer.Append(ref inputBuffer, foundIndex, inputBuffer.Length - foundIndex); } } } // Strip out the prefix and return the string ref StringBuffer bufferToUse = ref Choose(success, ref outputBuffer, ref inputBuffer); // Switch back from \\?\ to \\.\ if necessary if (wasDotDevice) bufferToUse[2] = '.'; string returnValue = null; int newLength = (int)(bufferToUse.Length - rootDifference); if (isDosUnc) { // Need to go from \\?\UNC\ to \\?\UN\\ bufferToUse[PathInternal.UncExtendedPrefixLength - PathInternal.UncPrefixLength] = '\\'; } // We now need to strip out any added characters at the front of the string if (bufferToUse.SubstringEquals(originalPath, rootDifference, newLength)) { // Use the original path to avoid allocating returnValue = originalPath; } else { returnValue = bufferToUse.Substring(rootDifference, newLength); } return returnValue; } finally { inputBuffer.Free(); } } // Helper method to workaround lack of operator ? support for ref values private static ref StringBuffer Choose(bool condition, ref StringBuffer s1, ref StringBuffer s2) { if (condition) return ref s1; else return ref s2; } } }
namespace Mapack { using System; /// <summary>Singular Value Decomposition for a rectangular matrix.</summary> /// <remarks> /// For an m-by-n matrix <c>A</c> with <c>m >= n</c>, the singular value decomposition is /// an m-by-n orthogonal matrix <c>U</c>, an n-by-n diagonal matrix <c>S</c>, and /// an n-by-n orthogonal matrix <c>V</c> so that <c>A = U * S * V'</c>. /// The singular values, <c>sigma[k] = S[k,k]</c>, are ordered so that /// <c>sigma[0] >= sigma[1] >= ... >= sigma[n-1]</c>. /// The singular value decompostion always exists, so the constructor will /// never fail. The matrix condition number and the effective numerical /// rank can be computed from this decomposition. /// </remarks> public class SingularValueDecomposition { private Matrix U; private Matrix V; private double[] s; // singular values private int m; private int n; /// <summary>Construct singular value decomposition.</summary> public SingularValueDecomposition(Matrix value) { if (value == null) { throw new ArgumentNullException("value"); } Matrix copy = (Matrix) value.Clone(); double[][] a = copy.Array; m = value.Rows; n = value.Columns; int nu = Math.Min(m,n); s = new double [Math.Min(m+1,n)]; U = new Matrix(m, nu); V = new Matrix(n, n); double[][] u = U.Array; double[][] v = V.Array; double[] e = new double [n]; double[] work = new double [m]; bool wantu = true; bool wantv = true; // Reduce A to bidiagonal form, storing the diagonal elements in s and the super-diagonal elements in e. int nct = Math.Min(m-1,n); int nrt = Math.Max(0,Math.Min(n-2,m)); for (int k = 0; k < Math.Max(nct,nrt); k++) { if (k < nct) { // Compute the transformation for the k-th column and place the k-th diagonal in s[k]. // Compute 2-norm of k-th column without under/overflow. s[k] = 0; for (int i = k; i < m; i++) { s[k] = Hypotenuse(s[k],a[i][k]); } if (s[k] != 0.0) { if (a[k][k] < 0.0) { s[k] = -s[k]; } for (int i = k; i < m; i++) { a[i][k] /= s[k]; } a[k][k] += 1.0; } s[k] = -s[k]; } for (int j = k+1; j < n; j++) { if ((k < nct) & (s[k] != 0.0)) { // Apply the transformation. double t = 0; for (int i = k; i < m; i++) t += a[i][k]*a[i][j]; t = -t/a[k][k]; for (int i = k; i < m; i++) a[i][j] += t*a[i][k]; } // Place the k-th row of A into e for the subsequent calculation of the row transformation. e[j] = a[k][j]; } if (wantu & (k < nct)) { // Place the transformation in U for subsequent back // multiplication. for (int i = k; i < m; i++) u[i][k] = a[i][k]; } if (k < nrt) { // Compute the k-th row transformation and place the k-th super-diagonal in e[k]. // Compute 2-norm without under/overflow. e[k] = 0; for (int i = k+1; i < n; i++) { e[k] = Hypotenuse(e[k],e[i]); } if (e[k] != 0.0) { if (e[k+1] < 0.0) e[k] = -e[k]; for (int i = k+1; i < n; i++) e[i] /= e[k]; e[k+1] += 1.0; } e[k] = -e[k]; if ((k+1 < m) & (e[k] != 0.0)) { // Apply the transformation. for (int i = k+1; i < m; i++) work[i] = 0.0; for (int j = k+1; j < n; j++) for (int i = k+1; i < m; i++) work[i] += e[j]*a[i][j]; for (int j = k+1; j < n; j++) { double t = -e[j]/e[k+1]; for (int i = k+1; i < m; i++) a[i][j] += t*work[i]; } } if (wantv) { // Place the transformation in V for subsequent back multiplication. for (int i = k+1; i < n; i++) v[i][k] = e[i]; } } } // Set up the final bidiagonal matrix or order p. int p = Math.Min(n,m+1); if (nct < n) s[nct] = a[nct][nct]; if (m < p) s[p-1] = 0.0; if (nrt+1 < p) e[nrt] = a[nrt][p-1]; e[p-1] = 0.0; // If required, generate U. if (wantu) { for (int j = nct; j < nu; j++) { for (int i = 0; i < m; i++) u[i][j] = 0.0; u[j][j] = 1.0; } for (int k = nct-1; k >= 0; k--) { if (s[k] != 0.0) { for (int j = k+1; j < nu; j++) { double t = 0; for (int i = k; i < m; i++) t += u[i][k]*u[i][j]; t = -t/u[k][k]; for (int i = k; i < m; i++) u[i][j] += t*u[i][k]; } for (int i = k; i < m; i++ ) u[i][k] = -u[i][k]; u[k][k] = 1.0 + u[k][k]; for (int i = 0; i < k-1; i++) u[i][k] = 0.0; } else { for (int i = 0; i < m; i++) u[i][k] = 0.0; u[k][k] = 1.0; } } } // If required, generate V. if (wantv) { for (int k = n-1; k >= 0; k--) { if ((k < nrt) & (e[k] != 0.0)) { for (int j = k+1; j < nu; j++) { double t = 0; for (int i = k+1; i < n; i++) t += v[i][k]*v[i][j]; t = -t/v[k+1][k]; for (int i = k+1; i < n; i++) v[i][j] += t*v[i][k]; } } for (int i = 0; i < n; i++) v[i][k] = 0.0; v[k][k] = 1.0; } } // Main iteration loop for the singular values. int pp = p-1; int iter = 0; double eps = Math.Pow(2.0,-52.0); while (p > 0) { int k,kase; // Here is where a test for too many iterations would go. // This section of the program inspects for // negligible elements in the s and e arrays. On // completion the variables kase and k are set as follows. // kase = 1 if s(p) and e[k-1] are negligible and k<p // kase = 2 if s(k) is negligible and k<p // kase = 3 if e[k-1] is negligible, k<p, and s(k), ..., s(p) are not negligible (qr step). // kase = 4 if e(p-1) is negligible (convergence). for (k = p-2; k >= -1; k--) { if (k == -1) break; if (Math.Abs(e[k]) <= eps*(Math.Abs(s[k]) + Math.Abs(s[k+1]))) { e[k] = 0.0; break; } } if (k == p-2) { kase = 4; } else { int ks; for (ks = p-1; ks >= k; ks--) { if (ks == k) break; double t = (ks != p ? Math.Abs(e[ks]) : 0.0) + (ks != k+1 ? Math.Abs(e[ks-1]) : 0.0); if (Math.Abs(s[ks]) <= eps*t) { s[ks] = 0.0; break; } } if (ks == k) kase = 3; else if (ks == p-1) kase = 1; else { kase = 2; k = ks; } } k++; // Perform the task indicated by kase. switch (kase) { // Deflate negligible s(p). case 1: { double f = e[p-2]; e[p-2] = 0.0; for (int j = p-2; j >= k; j--) { double t = Hypotenuse(s[j],f); double cs = s[j]/t; double sn = f/t; s[j] = t; if (j != k) { f = -sn*e[j-1]; e[j-1] = cs*e[j-1]; } if (wantv) { for (int i = 0; i < n; i++) { t = cs*v[i][j] + sn*v[i][p-1]; v[i][p-1] = -sn*v[i][j] + cs*v[i][p-1]; v[i][j] = t; } } } } break; // Split at negligible s(k). case 2: { double f = e[k-1]; e[k-1] = 0.0; for (int j = k; j < p; j++) { double t = Hypotenuse(s[j],f); double cs = s[j]/t; double sn = f/t; s[j] = t; f = -sn*e[j]; e[j] = cs*e[j]; if (wantu) { for (int i = 0; i < m; i++) { t = cs*u[i][j] + sn*u[i][k-1]; u[i][k-1] = -sn*u[i][j] + cs*u[i][k-1]; u[i][j] = t; } } } } break; // Perform one qr step. case 3: { // Calculate the shift. double scale = Math.Max(Math.Max(Math.Max(Math.Max(Math.Abs(s[p-1]),Math.Abs(s[p-2])),Math.Abs(e[p-2])), Math.Abs(s[k])),Math.Abs(e[k])); double sp = s[p-1]/scale; double spm1 = s[p-2]/scale; double epm1 = e[p-2]/scale; double sk = s[k]/scale; double ek = e[k]/scale; double b = ((spm1 + sp)*(spm1 - sp) + epm1*epm1)/2.0; double c = (sp*epm1)*(sp*epm1); double shift = 0.0; if ((b != 0.0) | (c != 0.0)) { shift = Math.Sqrt(b*b + c); if (b < 0.0) shift = -shift; shift = c/(b + shift); } double f = (sk + sp)*(sk - sp) + shift; double g = sk*ek; // Chase zeros. for (int j = k; j < p-1; j++) { double t = Hypotenuse(f,g); double cs = f/t; double sn = g/t; if (j != k) e[j-1] = t; f = cs*s[j] + sn*e[j]; e[j] = cs*e[j] - sn*s[j]; g = sn*s[j+1]; s[j+1] = cs*s[j+1]; if (wantv) { for (int i = 0; i < n; i++) { t = cs*v[i][j] + sn*v[i][j+1]; v[i][j+1] = -sn*v[i][j] + cs*v[i][j+1]; v[i][j] = t; } } t = Hypotenuse(f, g); cs = f/t; sn = g/t; s[j] = t; f = cs*e[j] + sn*s[j+1]; s[j+1] = -sn*e[j] + cs*s[j+1]; g = sn*e[j+1]; e[j+1] = cs*e[j+1]; if (wantu && (j < m-1)) { for (int i = 0; i < m; i++) { t = cs*u[i][j] + sn*u[i][j+1]; u[i][j+1] = -sn*u[i][j] + cs*u[i][j+1]; u[i][j] = t; } } } e[p-2] = f; iter = iter + 1; } break; // Convergence. case 4: { // Make the singular values positive. if (s[k] <= 0.0) { s[k] = (s[k] < 0.0 ? -s[k] : 0.0); if (wantv) for (int i = 0; i <= pp; i++) v[i][k] = -v[i][k]; } // Order the singular values. while (k < pp) { if (s[k] >= s[k+1]) break; double t = s[k]; s[k] = s[k+1]; s[k+1] = t; if (wantv && (k < n-1)) for (int i = 0; i < n; i++) { t = v[i][k+1]; v[i][k+1] = v[i][k]; v[i][k] = t; } if (wantu && (k < m-1)) for (int i = 0; i < m; i++) { t = u[i][k+1]; u[i][k+1] = u[i][k]; u[i][k] = t; } k++; } iter = 0; p--; } break; } } } /// <summary>Returns the condition number <c>max(S) / min(S)</c>.</summary> public double Condition { get { return s[0] / s[Math.Min(m, n) - 1]; } } /// <summary>Returns the Two norm.</summary> public double Norm2 { get { return s[0]; } } /// <summary>Returns the effective numerical matrix rank.</summary> /// <value>Number of non-negligible singular values.</value> public int Rank { get { double eps = Math.Pow(2.0,-52.0); double tol = Math.Max(m, n) * s[0] * eps; int r = 0; for (int i = 0; i < s.Length; i++) { if (s[i] > tol) { r++; } } return r; } } /// <summary>Return the one-dimensional array of singular values.</summary> public double[] Diagonal { get { return this.s; } } private static double Hypotenuse(double a, double b) { if (Math.Abs(a) > Math.Abs(b)) { double r = b / a; return Math.Abs(a) * Math.Sqrt(1 + r * r); } if (b != 0) { double r = a / b; return Math.Abs(b) * Math.Sqrt(1 + r * r); } return 0.0; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Kemel.Orm.Schema; using System.CodeDom; using Kemel.Orm.Constants; using Kemel.Orm.Entity.Attributes; namespace Kemel.Orm.DataBase.CodeDom { public class EntityGen : BaseGen { public EntityGen(GenConfig config) { base.Config = config; } public const string EntityNameSpace = "Entity"; public const string EntitySufix = "_Entity"; public override GenType Type { get { return GenType.Entity; } } public void GenerateEntity(string nameSpace) { CodeTypeDeclaration typeDeclaration = this.GetEntityDeclaration(); CodeCompileUnit compilerUnit = this.GetUnit(typeDeclaration, nameSpace, this.Config.CurrentItem.Schema.SchemaType); this.Config.CurrentItem.Classes.EntityClass = this.GetStringFromUnit(compilerUnit); } public void GenerateNormalEntity() { string nameSpace = string.Concat(this.BaseNameSpaceWithDot, EntityNameSpace); this.GenerateEntity(nameSpace); } public void GenerateProcedureEntity() { string nameSpace = string.Concat(this.BaseNameSpaceWithDot, ProcedureNameSpace, Punctuation.DOT, EntityNameSpace); this.GenerateEntity(nameSpace); } public void GenerateViewEntity() { string nameSpace = string.Concat(this.BaseNameSpaceWithDot, ViewNameSpace, Punctuation.DOT, EntityNameSpace); this.GenerateEntity(nameSpace); } public void GenerateFunctionEntity() { string nameSpace = string.Concat(this.BaseNameSpaceWithDot, FunctionNameSpace, Punctuation.DOT, EntityNameSpace); this.GenerateEntity(nameSpace); } private CodeTypeDeclaration GetEntityDeclaration() { TableSchema schema = this.Config.CurrentItem.Schema; this.Config.CurrentItem.Classes.EntityFileName = string.Concat(schema.Name, EntitySufix); CodeTypeDeclaration classDeclare = new CodeTypeDeclaration(this.Config.CurrentItem.Classes.EntityFileName); if (schema.SchemaType != SchemaType.None) { classDeclare.CustomAttributes.Add( new CodeAttributeDeclaration( "TableSchemaType", new CodeAttributeArgument( new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(new CodeTypeReference(typeof(SchemaType), CodeTypeReferenceOptions.GlobalReference)), Enum.GetName(typeof(SchemaType), schema.SchemaType) ) ))); } classDeclare.IsPartial = true; classDeclare.BaseTypes.Add(typeof(Kemel.Orm.Entity.EntityBase)); foreach (ColumnSchema column in schema.Columns) { if (!column.IgnoreColumn) { this.AddFieldAndProperty(classDeclare, column); } } return classDeclare; } private void AddFieldAndProperty(CodeTypeDeclaration classDeclare, ColumnSchema column) { CodeMemberField field = this.GetField(column); classDeclare.Members.Add(field); classDeclare.Members.Add(this.GetProperty(column, field)); } private CodeMemberField GetField(ColumnSchema column) { CodeMemberField field = new CodeMemberField(); field.Name = string.Concat("f_", column.Name.ToLower()); field.Type = new CodeTypeReference(column.Type); field.Attributes = MemberAttributes.Private; return field; } private CodeMemberProperty GetProperty(ColumnSchema column, CodeMemberField field) { SchemaType schemaType = column.Parent.SchemaType; CodeMemberProperty property = new CodeMemberProperty(); property.Name = column.Name; property.Type = new CodeTypeReference(column.Type); property.Attributes = MemberAttributes.Public; property.HasGet = property.HasSet = true; property.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, column.Name)); property.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, column.Name)); CodeFieldReferenceExpression codeField = new CodeFieldReferenceExpression( new CodeThisReferenceExpression(), field.Name); property.GetStatements.Add(new CodeMethodReturnStatement(codeField)); property.SetStatements.Add( new CodeAssignStatement(codeField, new CodePropertySetValueReferenceExpression())); #region schemaType == SchemaType.Table || schemaType == SchemaType.None if (schemaType == SchemaType.Table || schemaType == SchemaType.None) { #region Comments property.Comments.Add(new CodeCommentStatement("<summary>", true)); if (column.IsPrimaryKey) property.Comments.Add(new CodeCommentStatement(Properties.Resources.IsPrimaryKeyInformation, true)); if (column.IsIdentity) property.Comments.Add(new CodeCommentStatement(Properties.Resources.IsIdentityInformation, true)); property.Comments.Add( new CodeCommentStatement(column.AllowNull ? Properties.Resources.AllowNullInformation : Properties.Resources.NotAllowNullInformation, true) ); property.Comments.Add(new CodeCommentStatement("</summary>", true)); #endregion property.CustomAttributes.Add( new CodeAttributeDeclaration( "Identity", new CodeAttributeArgument(new CodePrimitiveExpression(column.IsIdentity)))); property.CustomAttributes.Add( new CodeAttributeDeclaration( "PrimaryKey", new CodeAttributeArgument(new CodePrimitiveExpression(column.IsPrimaryKey)))); property.CustomAttributes.Add( new CodeAttributeDeclaration( "AllowNull", new CodeAttributeArgument(new CodePrimitiveExpression(column.AllowNull)))); if (column.IsLogicalExclusionColumn) { property.CustomAttributes.Add( new CodeAttributeDeclaration( "LogicalExclusionColumn")); } if (column.IsForeignKey) { property.CustomAttributes.Add( new CodeAttributeDeclaration( "ForeignKey", new CodeAttributeArgument( new CodeTypeOfExpression(string.Concat(column.ReferenceTableName, EntitySufix))))); } } #endregion if (schemaType == SchemaType.Procedure) { CodeExpression paramDir = new CodeFieldReferenceExpression ( new CodeTypeReferenceExpression(typeof(System.Data.ParameterDirection)), column.ParamDirection.ToString() ); property.CustomAttributes.Add( new CodeAttributeDeclaration( "ParameterDirection", new CodeAttributeArgument(paramDir))); } if (column.IgnoreColumn) { property.CustomAttributes.Add( new CodeAttributeDeclaration( "IgnoreProperty")); } switch (column.DBType) { case System.Data.DbType.AnsiString: case System.Data.DbType.AnsiStringFixedLength: case System.Data.DbType.String: case System.Data.DbType.StringFixedLength: case System.Data.DbType.Xml: property.CustomAttributes.Add( new CodeAttributeDeclaration( "MaxLength", new CodeAttributeArgument(new CodePrimitiveExpression(column.MaxLength)))); break; } return property; } public void GenerateEntityDefinition() { string nameSpace = string.Concat(this.BaseNameSpaceWithDot, EntityNameSpace); this.GenerateDefinitionDeclaration(nameSpace); } public void GenerateProcedureEntityDefinition() { string nameSpace = string.Concat(this.BaseNameSpaceWithDot, ProcedureNameSpace, Punctuation.DOT, EntityNameSpace); this.GenerateDefinitionDeclaration(nameSpace); } public void GenerateViewEntityDefinition() { string nameSpace = string.Concat(this.BaseNameSpaceWithDot, ViewNameSpace, Punctuation.DOT, EntityNameSpace); this.GenerateDefinitionDeclaration(nameSpace); } public void GenerateFunctionEntityDefinition() { string nameSpace = string.Concat(this.BaseNameSpaceWithDot, FunctionNameSpace, Punctuation.DOT, EntityNameSpace); this.GenerateDefinitionDeclaration(nameSpace); } public void GenerateEntityExtension() { string nameSpace = string.Concat(this.BaseNameSpaceWithDot, EntityNameSpace); this.GenerateExtensionDeclaration(nameSpace); } public void GenerateProcedureEntityExtension() { string nameSpace = string.Concat(this.BaseNameSpaceWithDot, ProcedureNameSpace, Punctuation.DOT, EntityNameSpace); this.GenerateExtensionDeclaration(nameSpace); } public void GenerateViewEntityExtension() { string nameSpace = string.Concat(this.BaseNameSpaceWithDot, ViewNameSpace, Punctuation.DOT, EntityNameSpace); this.GenerateExtensionDeclaration(nameSpace); } public void GenerateFunctionEntityExtension() { string nameSpace = string.Concat(this.BaseNameSpaceWithDot, FunctionNameSpace, Punctuation.DOT, EntityNameSpace); this.GenerateExtensionDeclaration(nameSpace); } public void GenerateDefinitionDeclaration(string nameSpace) { CodeTypeDeclaration typeDeclaration = this.GetDefinitionDeclaration(); CodeCompileUnit compilerUnit = this.GetUnit(typeDeclaration, nameSpace, this.Config.CurrentItem.Schema.SchemaType); this.Config.CurrentItem.Classes.DefinitionClass = this.GetStringFromUnit(compilerUnit); } public void GenerateExtensionDeclaration(string nameSpace) { CodeTypeDeclaration typeDeclaration = this.GetExtensionDeclaration(); CodeCompileUnit compilerUnit = this.GetUnit(typeDeclaration, nameSpace, this.Config.CurrentItem.Schema.SchemaType); this.Config.CurrentItem.Classes.ExtensionClass = this.GetStringFromUnit(compilerUnit); } private CodeTypeDeclaration GetDefinitionDeclaration() { TableSchema schema = this.Config.CurrentItem.Schema; CodeTypeDeclaration classDeclare = new CodeTypeDeclaration(this.Config.CurrentItem.Classes.EntityFileName); classDeclare.IsPartial = true; CodeTypeDeclaration definitionDeclare = new CodeTypeDeclaration("Definition"); classDeclare.Members.Add(definitionDeclare); CodeMemberField field = new CodeMemberField(typeof(string), "TABLE_NAME"); field.Attributes = MemberAttributes.Const | MemberAttributes.Public; field.InitExpression = new CodePrimitiveExpression(schema.Name); definitionDeclare.Members.Add(field); foreach (ColumnSchema column in schema.Columns) { if (!column.IgnoreColumn) { field = new CodeMemberField(typeof(string), column.Name.ToUpper()); field.Attributes = MemberAttributes.Const | MemberAttributes.Public; field.InitExpression = new CodePrimitiveExpression(column.Name); definitionDeclare.Members.Add(field); } } return classDeclare; } private CodeTypeDeclaration GetExtensionDeclaration() { TableSchema schema = this.Config.CurrentItem.Schema; CodeTypeDeclaration classDeclare = new CodeTypeDeclaration(this.Config.CurrentItem.Classes.EntityFileName); classDeclare.IsPartial = true; CodeTypeDeclaration extensionDeclare = new CodeTypeDeclaration("Extension"); classDeclare.Members.Add(extensionDeclare); CodeMemberField field; foreach (ColumnSchema column in schema.Columns) { if (column.IgnoreColumn) { this.AddFieldAndProperty(classDeclare, column); field = new CodeMemberField(typeof(string), column.Name.ToUpper()); field.Attributes = MemberAttributes.Const | MemberAttributes.Public; field.InitExpression = new CodePrimitiveExpression(column.Name); extensionDeclare.Members.Add(field); } } return classDeclare; } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Blob; using MS.Test.Common.MsTestLib; using StorageTestLib; using Storage = Microsoft.WindowsAzure.Storage.Blob; namespace CLITest.Util { public class CloudBlobUtil { private CloudStorageAccount account; private CloudBlobClient client; private Random random; private const int PageBlobUnitSize = 512; private static List<string> HttpsCopyHosts; public string ContainerName { get; private set; } public string BlobName { get; private set; } public ICloudBlob Blob { get; private set; } public CloudBlobContainer Container { get; private set; } private CloudBlobUtil() { } /// <summary> /// init cloud blob util /// </summary> /// <param name="account">storage account</param> public CloudBlobUtil(CloudStorageAccount account) { this.account = account; client = account.CreateCloudBlobClient(); random = new Random(); } /// <summary> /// Create a random container with a random blob /// </summary> public void SetupTestContainerAndBlob() { ContainerName = Utility.GenNameString("container"); BlobName = Utility.GenNameString("blob"); CloudBlobContainer container = CreateContainer(ContainerName); Blob = CreateRandomBlob(container, BlobName); Container = container; } /// <summary> /// clean test container and blob /// </summary> public void CleanupTestContainerAndBlob() { if (String.IsNullOrEmpty(ContainerName)) { return; } RemoveContainer(ContainerName); ContainerName = string.Empty; BlobName = string.Empty; Blob = null; Container = null; } /// <summary> /// create a container with random properties and metadata /// </summary> /// <param name="containerName">container name</param> /// <returns>the created container object with properties and metadata</returns> public CloudBlobContainer CreateContainer(string containerName = "") { if (String.IsNullOrEmpty(containerName)) { containerName = Utility.GenNameString("container"); } CloudBlobContainer container = client.GetContainerReference(containerName); container.CreateIfNotExists(); //there is no properties to set container.FetchAttributes(); int minMetaCount = 1; int maxMetaCount = 5; int minMetaValueLength = 10; int maxMetaValueLength = 20; int count = random.Next(minMetaCount, maxMetaCount); for (int i = 0; i < count; i++) { string metaKey = Utility.GenNameString("metatest"); int valueLength = random.Next(minMetaValueLength, maxMetaValueLength); string metaValue = Utility.GenNameString("metavalue-", valueLength); container.Metadata.Add(metaKey, metaValue); } container.SetMetadata(); Test.Info(string.Format("create container '{0}'", containerName)); return container; } public CloudBlobContainer CreateContainer(string containerName, BlobContainerPublicAccessType permission) { CloudBlobContainer container = CreateContainer(containerName); BlobContainerPermissions containerPermission = new BlobContainerPermissions(); containerPermission.PublicAccess = permission; container.SetPermissions(containerPermission); return container; } /// <summary> /// create mutiple containers /// </summary> /// <param name="containerNames">container names list</param> /// <returns>a list of container object</returns> public List<CloudBlobContainer> CreateContainer(List<string> containerNames) { List<CloudBlobContainer> containers = new List<CloudBlobContainer>(); foreach (string name in containerNames) { containers.Add(CreateContainer(name)); } containers = containers.OrderBy(container => container.Name).ToList(); return containers; } /// <summary> /// remove specified container /// </summary> /// <param name="containerName">container name</param> public void RemoveContainer(string containerName) { CloudBlobContainer container = client.GetContainerReference(containerName); container.DeleteIfExists(); Test.Info(string.Format("remove container '{0}'", containerName)); } /// <summary> /// remove a list containers /// </summary> /// <param name="containerNames">container names</param> public void RemoveContainer(List<string> containerNames) { foreach (string name in containerNames) { try { RemoveContainer(name); } catch (Exception e) { Test.Warn(string.Format("Can't remove container {0}. Exception: {1}", name, e.Message)); } } } /// <summary> /// create a new page blob with random properties and metadata /// </summary> /// <param name="container">CloudBlobContainer object</param> /// <param name="blobName">blob name</param> /// <returns>ICloudBlob object</returns> public ICloudBlob CreatePageBlob(CloudBlobContainer container, string blobName) { CloudPageBlob pageBlob = container.GetPageBlobReference(blobName); int size = random.Next(1, 10) * PageBlobUnitSize; pageBlob.Create(size); byte[] buffer = new byte[size]; string md5sum = Convert.ToBase64String(Helper.GetMD5(buffer)); pageBlob.Properties.ContentMD5 = md5sum; GenerateBlobPropertiesAndMetaData(pageBlob); Test.Info(string.Format("create page blob '{0}' in container '{1}'", blobName, container.Name)); return pageBlob; } /// <summary> /// create a block blob with random properties and metadata /// </summary> /// <param name="container">CloudBlobContainer object</param> /// <param name="blobName">Block blob name</param> /// <returns>ICloudBlob object</returns> public ICloudBlob CreateBlockBlob(CloudBlobContainer container, string blobName) { CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobName); int maxBlobSize = 1024 * 1024; string md5sum = string.Empty; int blobSize = random.Next(maxBlobSize); byte[] buffer = new byte[blobSize]; using (MemoryStream ms = new MemoryStream(buffer)) { random.NextBytes(buffer); //ms.Read(buffer, 0, buffer.Length); blockBlob.UploadFromStream(ms); md5sum = Convert.ToBase64String(Helper.GetMD5(buffer)); } blockBlob.Properties.ContentMD5 = md5sum; GenerateBlobPropertiesAndMetaData(blockBlob); Test.Info(string.Format("create block blob '{0}' in container '{1}'", blobName, container.Name)); return blockBlob; } /// <summary> /// generate random blob properties and metadata /// </summary> /// <param name="blob">ICloudBlob object</param> private void GenerateBlobPropertiesAndMetaData(ICloudBlob blob) { blob.Properties.ContentEncoding = Utility.GenNameString("encoding"); blob.Properties.ContentLanguage = Utility.GenNameString("lang"); int minMetaCount = 1; int maxMetaCount = 5; int minMetaValueLength = 10; int maxMetaValueLength = 20; int count = random.Next(minMetaCount, maxMetaCount); for (int i = 0; i < count; i++) { string metaKey = Utility.GenNameString("metatest"); int valueLength = random.Next(minMetaValueLength, maxMetaValueLength); string metaValue = Utility.GenNameString("metavalue-", valueLength); blob.Metadata.Add(metaKey, metaValue); } blob.SetProperties(); blob.SetMetadata(); blob.FetchAttributes(); } /// <summary> /// Create a blob with specified blob type /// </summary> /// <param name="container">CloudBlobContainer object</param> /// <param name="blobName">Blob name</param> /// <param name="type">Blob type</param> /// <returns>ICloudBlob object</returns> public ICloudBlob CreateBlob(CloudBlobContainer container, string blobName, Storage.BlobType type) { if (type == Microsoft.WindowsAzure.Storage.Blob.BlobType.BlockBlob) { return CreateBlockBlob(container, blobName); } else { return CreatePageBlob(container, blobName); } } /// <summary> /// create a list of blobs with random properties/metadata/blob type /// </summary> /// <param name="container">CloudBlobContainer object</param> /// <param name="blobName">a list of blob names</param> /// <returns>a list of cloud page blobs</returns> public List<ICloudBlob> CreateRandomBlob(CloudBlobContainer container, List<string> blobNames) { List<ICloudBlob> blobs = new List<ICloudBlob>(); foreach (string blobName in blobNames) { blobs.Add(CreateRandomBlob(container, blobName)); } blobs = blobs.OrderBy(blob => blob.Name).ToList(); return blobs; } public List<ICloudBlob> CreateRandomBlob(CloudBlobContainer container) { int count = random.Next(1, 5); List<string> blobNames = new List<string>(); for (int i = 0; i < count; i++) { blobNames.Add(Utility.GenNameString("blob")); } return CreateRandomBlob(container, blobNames); } /// <summary> /// Create a list of blobs with random properties/metadata/blob type /// </summary> /// <param name="container">CloudBlobContainer object</param> /// <param name="blobName">Blob name</param> /// <returns>ICloudBlob object</returns> public ICloudBlob CreateRandomBlob(CloudBlobContainer container, string blobName) { int switchKey = 0; switchKey = random.Next(2); if (switchKey == 0) { return CreatePageBlob(container, blobName); } else { return CreateBlockBlob(container, blobName); } } /// <summary> /// convert blob name into valid file name /// </summary> /// <param name="blobName">blob name</param> /// <returns>valid file name</returns> public string ConvertBlobNameToFileName(string blobName, string dir, DateTimeOffset? snapshotTime = null) { string fileName = blobName; //replace dirctionary Dictionary<string, string> replaceRules = new Dictionary<string, string>() { {"/", "\\"} }; foreach (KeyValuePair<string, string> rule in replaceRules) { fileName = fileName.Replace(rule.Key, rule.Value); } if (snapshotTime != null) { int index = fileName.LastIndexOf('.'); string prefix = string.Empty; string postfix = string.Empty; string timeStamp = string.Format("{0:u}", snapshotTime.Value); timeStamp = timeStamp.Replace(":", string.Empty).TrimEnd(new char[] { 'Z' }); if (index == -1) { prefix = fileName; postfix = string.Empty; } else { prefix = fileName.Substring(0, index); postfix = fileName.Substring(index); } fileName = string.Format("{0} ({1}){2}", prefix, timeStamp, postfix); } return Path.Combine(dir, fileName); } public string ConvertFileNameToBlobName(string fileName) { return fileName.Replace('\\', '/'); } /// <summary> /// list all the existing containers /// </summary> /// <returns>a list of cloudblobcontainer object</returns> public List<CloudBlobContainer> GetExistingContainers() { ContainerListingDetails details = ContainerListingDetails.All; return client.ListContainers(string.Empty, details).ToList(); } /// <summary> /// get the number of existing container /// </summary> /// <returns></returns> public int GetExistingContainerCount() { return GetExistingContainers().Count; } public static void PackContainerCompareData(CloudBlobContainer container, Dictionary<string, object> dic) { BlobContainerPermissions permissions = container.GetPermissions(); dic["PublicAccess"] = permissions.PublicAccess; dic["Permission"] = permissions; dic["LastModified"] = container.Properties.LastModified; } public static void PackBlobCompareData(ICloudBlob blob, Dictionary<string, object> dic) { dic["Length"] = blob.Properties.Length; dic["ContentType"] = blob.Properties.ContentType; dic["LastModified"] = blob.Properties.LastModified; dic["SnapshotTime"] = blob.SnapshotTime; } public static string ConvertCopySourceUri(string uri) { if (HttpsCopyHosts == null) { HttpsCopyHosts = new List<string>(); string httpsHosts = Test.Data.Get("HttpsCopyHosts"); string[] hosts = httpsHosts.Split(); foreach (string host in hosts) { if (!String.IsNullOrWhiteSpace(host)) { HttpsCopyHosts.Add(host); } } } //Azure always use https to copy from these hosts such windows.net bool useHttpsCopy = HttpsCopyHosts.Any(host => uri.IndexOf(host) != -1); if (useHttpsCopy) { return uri.Replace("http://", "https://"); } else { return uri; } } public static bool WaitForCopyOperationComplete(ICloudBlob destBlob, int maxRetry = 100) { int retryCount = 0; int sleepInterval = 1000; //ms if (destBlob == null) { return false; } do { if (retryCount > 0) { Test.Info(String.Format("{0}th check current copy state and it's {1}. Wait for copy completion", retryCount, destBlob.CopyState.Status)); } Thread.Sleep(sleepInterval); destBlob.FetchAttributes(); retryCount++; } while (destBlob.CopyState.Status == CopyStatus.Pending && retryCount < maxRetry); Test.Info(String.Format("Final Copy status is {0}", destBlob.CopyState.Status)); return destBlob.CopyState.Status != CopyStatus.Pending; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.11.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsBodyComplex { using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Models; /// <summary> /// Array operations. /// </summary> public partial class Array : IServiceOperations<AutoRestComplexTestService>, IArray { /// <summary> /// Initializes a new instance of the Array class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> public Array(AutoRestComplexTestService client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the AutoRestComplexTestService /// </summary> public AutoRestComplexTestService Client { get; private set; } /// <summary> /// Get complex types with array property /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse<ArrayWrapper>> GetValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "GetValid", tracingParameters); } // Construct URL var url = new Uri(this.Client.BaseUri, "/complex/array/valid").ToString(); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { if (httpRequest.Headers.Contains(header.Key)) { httpRequest.Headers.Remove(header.Key); } httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); } } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse<ArrayWrapper>(); result.Request = httpRequest; result.Response = httpResponse; // Deserialize Response if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<ArrayWrapper>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Put complex types with array property /// </summary> /// <param name='complexBody'> /// Please put an array with 4 items: "1, 2, 3, 4", "", null, "&amp;S#$(*Y", /// "The quick brown fox jumps over the lazy dog" /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse> PutValidWithHttpMessagesAsync(ArrayWrapper complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (complexBody == null) { throw new ValidationException(ValidationRules.CannotBeNull, "complexBody"); } // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("complexBody", complexBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "PutValid", tracingParameters); } // Construct URL var url = new Uri(this.Client.BaseUri, "/complex/array/valid").ToString(); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("PUT"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { if (httpRequest.Headers.Contains(header.Key)) { httpRequest.Headers.Remove(header.Key); } httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); } } // Serialize Request string requestContent = JsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse(); result.Request = httpRequest; result.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Get complex types with array property which is empty /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse<ArrayWrapper>> GetEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "GetEmpty", tracingParameters); } // Construct URL var url = new Uri(this.Client.BaseUri, "/complex/array/empty").ToString(); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { if (httpRequest.Headers.Contains(header.Key)) { httpRequest.Headers.Remove(header.Key); } httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); } } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse<ArrayWrapper>(); result.Request = httpRequest; result.Response = httpResponse; // Deserialize Response if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<ArrayWrapper>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Put complex types with array property which is empty /// </summary> /// <param name='complexBody'> /// Please put an empty array /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse> PutEmptyWithHttpMessagesAsync(ArrayWrapper complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (complexBody == null) { throw new ValidationException(ValidationRules.CannotBeNull, "complexBody"); } // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("complexBody", complexBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "PutEmpty", tracingParameters); } // Construct URL var url = new Uri(this.Client.BaseUri, "/complex/array/empty").ToString(); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("PUT"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { if (httpRequest.Headers.Contains(header.Key)) { httpRequest.Headers.Remove(header.Key); } httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); } } // Serialize Request string requestContent = JsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse(); result.Request = httpRequest; result.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Get complex types with array property while server doesn't provide a /// response payload /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse<ArrayWrapper>> GetNotProvidedWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "GetNotProvided", tracingParameters); } // Construct URL var url = new Uri(this.Client.BaseUri, "/complex/array/notprovided").ToString(); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { if (httpRequest.Headers.Contains(header.Key)) { httpRequest.Headers.Remove(header.Key); } httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); } } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse<ArrayWrapper>(); result.Request = httpRequest; result.Response = httpResponse; // Deserialize Response if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<ArrayWrapper>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } } }
using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; namespace Keen.Core { /// <summary> /// Helps with performing HTTP operations destined for a Keen API endpoint. Helper methods in /// this class will add appropriate headers and config to use the underlying HttpClient /// in the way expected by the Keen IO API. This class should be long-lived and all public /// methods are thread-safe, so ideal usage is to configure it once for a given base URL and /// reuse it with relative resources to send requests for the duration of the app or module. /// </summary> internal class KeenHttpClient : IKeenHttpClient { private static readonly string JSON_CONTENT_TYPE = "application/json"; private static readonly string AUTH_HEADER_KEY = "Authorization"; // We don't destroy this manually. Whatever code provides the HttpClient directly or via an // IHttpClientProvider should be sure to handle its lifetime. private readonly HttpClient _httpClient = null; internal KeenHttpClient(HttpClient httpClient) { _httpClient = httpClient; } internal static string GetRelativeUrl(string projectId, string resource) { return $"projects/{projectId}/{resource}"; } /// <summary> /// Create and send a GET request to the given relative resource using the given key for /// authentication. /// </summary> /// <param name="resource">The relative resource to GET. Must be properly formatted as a /// relative Uri.</param> /// <param name="authKey">The key to use for authenticating this request.</param> /// <returns>The response message.</returns> public Task<HttpResponseMessage> GetAsync(string resource, string authKey) { var url = new Uri(resource, UriKind.Relative); return GetAsync(url, authKey); } /// <summary> /// Create and send a GET request to the given relative resource using the given key for /// authentication. /// </summary> /// <param name="resource">The relative resource to GET.</param> /// <param name="authKey">The key to use for authenticating this request.</param> /// <returns>The response message.</returns> public Task<HttpResponseMessage> GetAsync(Uri resource, string authKey) { KeenHttpClient.RequireAuthKey(authKey); HttpRequestMessage get = CreateRequest(HttpMethod.Get, resource, authKey); return _httpClient.SendAsync(get); } // TODO : Instead of (or in addition to) string, also accept HttpContent content and/or // JObject content? /// <summary> /// Create and send a POST request with the given content to the given relative resource /// using the given key for authentication. /// </summary> /// <param name="resource">The relative resource to POST. Must be properly formatted as a /// relative Uri.</param> /// <param name="authKey">The key to use for authenticating this request.</param> /// <param name="content">The POST body to send.</param> /// <returns>The response message.</returns> public Task<HttpResponseMessage> PostAsync(string resource, string authKey, string content) { var url = new Uri(resource, UriKind.Relative); return PostAsync(url, authKey, content); } /// <summary> /// Create and send a POST request with the given content to the given relative resource /// using the given key for authentication. /// </summary> /// <param name="resource">The relative resource to POST.</param> /// <param name="authKey">The key to use for authenticating this request.</param> /// <param name="content">The POST body to send.</param> /// <returns>The response message.</returns> public Task<HttpResponseMessage> PostAsync(Uri resource, string authKey, string content) { return DispatchWithContentAsync(HttpMethod.Post, resource, authKey, content); } /// <summary> /// Create and send a DELETE request to the given relative resource using the given key for /// authentication. /// </summary> /// <param name="resource">The relative resource to DELETE. Must be properly formatted as a /// relative Uri.</param> /// <param name="authKey">The key to use for authenticating this request.</param> /// <returns>The response message.</returns> public Task<HttpResponseMessage> DeleteAsync(string resource, string authKey) { var url = new Uri(resource, UriKind.Relative); return DeleteAsync(url, authKey); } /// <summary> /// Create and send a DELETE request to the given relative resource using the given key for /// authentication. /// </summary> /// <param name="resource">The relative resource to DELETE.</param> /// <param name="authKey">The key to use for authenticating this request.</param> /// <returns>The response message.</returns> public Task<HttpResponseMessage> DeleteAsync(Uri resource, string authKey) { KeenHttpClient.RequireAuthKey(authKey); HttpRequestMessage delete = CreateRequest(HttpMethod.Delete, resource, authKey); return _httpClient.SendAsync(delete); } /// <summary> /// Create and send a PUT request with the given content to the given relative resource /// using the given key for authentication. /// </summary> /// <param name="resource">The relative resource to PUT. Must be properly formatted as a /// relative Uri.</param> /// <param name="authKey">The key to use for authenticating this request.</param> /// <param name="content">The PUT body to send.</param> /// <returns>The response message.</returns> public Task<HttpResponseMessage> PutAsync(string resource, string authKey, string content) { var url = new Uri(resource, UriKind.Relative); return PutAsync(url, authKey, content); } /// <summary> /// Create and send a PUT request with the given content to the given relative resource /// using the given key for authentication. /// </summary> /// <param name="resource">The relative resource to PUT. Must be properly formatted as a /// relative Uri.</param> /// <param name="authKey">The key to use for authenticating this request.</param> /// <param name="content">The PUT body to send.</param> /// <returns>The response message.</returns> public Task<HttpResponseMessage> PutAsync(Uri resource, string authKey, string content) { return DispatchWithContentAsync(HttpMethod.Put, resource, authKey, content); } private async Task<HttpResponseMessage> DispatchWithContentAsync(HttpMethod httpMethod, Uri resource, string authKey, string content) { KeenHttpClient.RequireAuthKey(authKey); if (string.IsNullOrWhiteSpace(content)) { // Technically, we can encode an empty string or whitespace, but why? For now // we use GET for querying. If we ever need to POST with no content, we should // reorganize the logic below to never create/set the content stream. throw new ArgumentNullException(nameof(content), "Unexpected empty content."); } // If we switch PCL profiles, instead use MediaTypeFormatters (or ObjectContent<T>)?, // like here?: https://msdn.microsoft.com/en-us/library/system.net.http.httpclientextensions.putasjsonasync(v=vs.118).aspx using (var contentStream = new StreamContent(new MemoryStream(Encoding.UTF8.GetBytes(content)))) { // TODO : Make sure this is the same as Add("content-type", "application/json") contentStream.Headers.ContentType = new MediaTypeHeaderValue(KeenHttpClient.JSON_CONTENT_TYPE); HttpRequestMessage request = CreateRequest(httpMethod, resource, authKey); request.Content = contentStream; return await _httpClient.SendAsync(request).ConfigureAwait(false); // TODO : Should we do the KeenUtil.CheckApiErrorCode() here? // TODO : Should we check the if (!responseMsg.IsSuccessStatusCode) here too? // TODO : If we centralize error checking in this class we could have variations // of these helpers that return string or JToken or JArray or JObject. It might // also be nice for those options to optionally hand back the raw // HttpResponseMessage in an out param if desired? // TODO : Use CallerMemberNameAttribute to print error messages? // http://stackoverflow.com/questions/3095696/how-do-i-get-the-calling-method-name-and-type-using-reflection?noredirect=1&lq=1 } } private static HttpRequestMessage CreateRequest(HttpMethod verb, Uri resource, string authKey) { var request = new HttpRequestMessage() { RequestUri = resource, Method = verb }; request.Headers.Add(KeenHttpClient.AUTH_HEADER_KEY, authKey); return request; } private static void RequireAuthKey(string authKey) { if (string.IsNullOrWhiteSpace(authKey)) { throw new ArgumentNullException(nameof(authKey), "Auth key is required."); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void AddSaturateSByte() { var test = new SimpleBinaryOpTest__AddSaturateSByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__AddSaturateSByte { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(SByte[] inArray1, SByte[] inArray2, SByte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<SByte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<SByte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<SByte> _fld1; public Vector128<SByte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__AddSaturateSByte testClass) { var result = Sse2.AddSaturate(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__AddSaturateSByte testClass) { fixed (Vector128<SByte>* pFld1 = &_fld1) fixed (Vector128<SByte>* pFld2 = &_fld2) { var result = Sse2.AddSaturate( Sse2.LoadVector128((SByte*)(pFld1)), Sse2.LoadVector128((SByte*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static SByte[] _data1 = new SByte[Op1ElementCount]; private static SByte[] _data2 = new SByte[Op2ElementCount]; private static Vector128<SByte> _clsVar1; private static Vector128<SByte> _clsVar2; private Vector128<SByte> _fld1; private Vector128<SByte> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__AddSaturateSByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); } public SimpleBinaryOpTest__AddSaturateSByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } _dataTable = new DataTable(_data1, _data2, new SByte[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.AddSaturate( Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.AddSaturate( Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.AddSaturate( Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.AddSaturate), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.AddSaturate), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.AddSaturate), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.AddSaturate( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<SByte>* pClsVar1 = &_clsVar1) fixed (Vector128<SByte>* pClsVar2 = &_clsVar2) { var result = Sse2.AddSaturate( Sse2.LoadVector128((SByte*)(pClsVar1)), Sse2.LoadVector128((SByte*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr); var result = Sse2.AddSaturate(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr)); var result = Sse2.AddSaturate(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr)); var result = Sse2.AddSaturate(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__AddSaturateSByte(); var result = Sse2.AddSaturate(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__AddSaturateSByte(); fixed (Vector128<SByte>* pFld1 = &test._fld1) fixed (Vector128<SByte>* pFld2 = &test._fld2) { var result = Sse2.AddSaturate( Sse2.LoadVector128((SByte*)(pFld1)), Sse2.LoadVector128((SByte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.AddSaturate(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<SByte>* pFld1 = &_fld1) fixed (Vector128<SByte>* pFld2 = &_fld2) { var result = Sse2.AddSaturate( Sse2.LoadVector128((SByte*)(pFld1)), Sse2.LoadVector128((SByte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.AddSaturate(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse2.AddSaturate( Sse2.LoadVector128((SByte*)(&test._fld1)), Sse2.LoadVector128((SByte*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<SByte> op1, Vector128<SByte> op2, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(SByte[] left, SByte[] right, SByte[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (Sse2Verify.AddSaturate(left[0], right[0], result[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (Sse2Verify.AddSaturate(left[i], right[i], result[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.AddSaturate)}<SByte>(Vector128<SByte>, Vector128<SByte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Reflection; using System.Reflection.Emit; using System.Collections; using System.Collections.Generic; using Xunit; namespace System.Reflection.Emit.Tests { public class ModuleBuilderDefineEnum { private static Type[] s_builtInIntegerTypes = new Type[] { typeof(byte), typeof(SByte), typeof(Int16), typeof(ushort), typeof(int), typeof(uint), typeof(long), typeof(ulong) }; [Fact] public void TestWithValueType() { List<object> myArray = new List<object>(); myArray = GetVisibilityAttr(true); foreach (TypeAttributes current in myArray) { foreach (Type integerType in s_builtInIntegerTypes) { VerificationHelper(current, integerType); } } } [Fact] public void TestForNonVisibilityAttributes() { List<object> myArray = new List<object>(); myArray = GetVisibilityAttr(false); foreach (TypeAttributes current in myArray) { string name = "MyEnum"; VerificationHelperNegative(name, current, typeof(int), true); } } [Fact] public void TestForAlreadyExistingEnumWithSameName() { List<object> myArray = new List<object>(); myArray = GetVisibilityAttr(true); foreach (TypeAttributes current in myArray) { string name = "MyEnum"; VerificationHelperNegative(name, current, typeof(object), false); } } [Fact] public void TestWithNullName() { List<object> myArray = new List<object>(); myArray = GetVisibilityAttr(true); foreach (TypeAttributes current in myArray) { string name = null; VerificationHelperNegative(name, current, typeof(object), typeof(ArgumentNullException)); } } [Fact] public void TestWithEmptyName() { List<object> myArray = new List<object>(); myArray = GetVisibilityAttr(true); foreach (TypeAttributes current in myArray) { string name = string.Empty; VerificationHelperNegative(name, current, typeof(object), typeof(ArgumentException)); } } [Fact] public void TestWithIncorrectVisibilityAttributes() { List<object> myArray = new List<object>(); myArray = GetNestVisibilityAttr(true); foreach (TypeAttributes current in myArray) { string name = "MyEnum"; VerificationHelperNegative(name, current, typeof(object), true); } } [Fact] public void TestWithReferenceType() { List<object> myArray = new List<object>(); myArray = GetVisibilityAttr(true); foreach (TypeAttributes current in myArray) { VerificationHelperNegative("MyEnum", current, typeof(string), typeof(TypeLoadException)); } } private ModuleBuilder GetModuleBuilder() { ModuleBuilder myModuleBuilder; AssemblyBuilder myAssemblyBuilder; // Get the current application domain for the current thread. AssemblyName myAssemblyName = new AssemblyName(); myAssemblyName.Name = "TempAssembly"; // Define a dynamic assembly in the current domain. myAssemblyBuilder = AssemblyBuilder.DefineDynamicAssembly (myAssemblyName, AssemblyBuilderAccess.Run); // Define a dynamic module in "TempAssembly" assembly. myModuleBuilder = TestLibrary.Utilities.GetModuleBuilder(myAssemblyBuilder, "Module1"); return myModuleBuilder; } private List<object> GetNestVisibilityAttr(bool flag) { List<object> myArray = new List<object>(); if (JudgeVisibilityMaskAttributes(TypeAttributes.NestedAssembly, flag)) myArray.Add(TypeAttributes.NestedAssembly); if (JudgeVisibilityMaskAttributes(TypeAttributes.NestedFamANDAssem, flag)) myArray.Add(TypeAttributes.NestedFamANDAssem); if (JudgeVisibilityMaskAttributes(TypeAttributes.NestedFamily, flag)) myArray.Add(TypeAttributes.NestedFamily); if (JudgeVisibilityMaskAttributes(TypeAttributes.NestedFamANDAssem, flag)) myArray.Add(TypeAttributes.NestedFamANDAssem); if (JudgeVisibilityMaskAttributes(TypeAttributes.NestedFamORAssem, flag)) myArray.Add(TypeAttributes.NestedFamORAssem); if (JudgeVisibilityMaskAttributes(TypeAttributes.NestedPrivate, flag)) myArray.Add(TypeAttributes.NestedPrivate); if (JudgeVisibilityMaskAttributes(TypeAttributes.NestedPublic, flag)) myArray.Add(TypeAttributes.NestedPublic); return myArray; } private List<object> GetVisibilityAttr(bool flag) { List<object> myArray = new List<object>(); if (JudgeVisibilityMaskAttributes(TypeAttributes.Abstract, flag)) myArray.Add(TypeAttributes.Abstract); if (JudgeVisibilityMaskAttributes(TypeAttributes.AnsiClass, flag)) myArray.Add(TypeAttributes.AnsiClass); if (JudgeVisibilityMaskAttributes(TypeAttributes.AutoClass, flag)) myArray.Add(TypeAttributes.AutoClass); if (JudgeVisibilityMaskAttributes(TypeAttributes.AutoLayout, flag)) myArray.Add(TypeAttributes.AutoLayout); if (JudgeVisibilityMaskAttributes(TypeAttributes.BeforeFieldInit, flag)) myArray.Add(TypeAttributes.BeforeFieldInit); if (JudgeVisibilityMaskAttributes(TypeAttributes.Class, flag)) myArray.Add(TypeAttributes.Class); if (JudgeVisibilityMaskAttributes(TypeAttributes.ClassSemanticsMask, flag)) myArray.Add(TypeAttributes.ClassSemanticsMask); if (JudgeVisibilityMaskAttributes(TypeAttributes.CustomFormatClass, flag)) myArray.Add(TypeAttributes.CustomFormatClass); if (JudgeVisibilityMaskAttributes(TypeAttributes.CustomFormatMask, flag)) myArray.Add(TypeAttributes.CustomFormatMask); if (JudgeVisibilityMaskAttributes(TypeAttributes.ExplicitLayout, flag)) myArray.Add(TypeAttributes.ExplicitLayout); if (JudgeVisibilityMaskAttributes(TypeAttributes.HasSecurity, flag)) myArray.Add(TypeAttributes.HasSecurity); if (JudgeVisibilityMaskAttributes(TypeAttributes.Import, flag)) myArray.Add(TypeAttributes.Import); if (JudgeVisibilityMaskAttributes(TypeAttributes.Interface, flag)) myArray.Add(TypeAttributes.Interface); if (JudgeVisibilityMaskAttributes(TypeAttributes.LayoutMask, flag)) myArray.Add(TypeAttributes.LayoutMask); if (JudgeVisibilityMaskAttributes(TypeAttributes.NotPublic, flag)) myArray.Add(TypeAttributes.NotPublic); if (JudgeVisibilityMaskAttributes(TypeAttributes.Public, flag)) myArray.Add(TypeAttributes.Public); if (JudgeVisibilityMaskAttributes(TypeAttributes.RTSpecialName, flag)) myArray.Add(TypeAttributes.RTSpecialName); if (JudgeVisibilityMaskAttributes(TypeAttributes.Sealed, flag)) myArray.Add(TypeAttributes.Sealed); if (JudgeVisibilityMaskAttributes(TypeAttributes.SequentialLayout, flag)) myArray.Add(TypeAttributes.SequentialLayout); if (JudgeVisibilityMaskAttributes(TypeAttributes.Serializable, flag)) myArray.Add(TypeAttributes.Serializable); if (JudgeVisibilityMaskAttributes(TypeAttributes.SpecialName, flag)) myArray.Add(TypeAttributes.SpecialName); if (JudgeVisibilityMaskAttributes(TypeAttributes.StringFormatMask, flag)) myArray.Add(TypeAttributes.StringFormatMask); if (JudgeVisibilityMaskAttributes(TypeAttributes.UnicodeClass, flag)) myArray.Add(TypeAttributes.UnicodeClass); return myArray; } private bool JudgeVisibilityMaskAttributes(TypeAttributes visibility, bool flag) { if (flag) { if ((visibility & ~TypeAttributes.VisibilityMask) == 0) return true; else return false; } else { if ((visibility & ~TypeAttributes.VisibilityMask) != 0) return true; else return false; } } private void VerificationHelper(TypeAttributes myTypeAttribute, Type mytype) { ModuleBuilder myModuleBuilder = GetModuleBuilder(); // Define a enumeration type with name 'MyEnum' in the 'TempModule'. EnumBuilder myEnumBuilder = myModuleBuilder.DefineEnum("MyEnum", myTypeAttribute, mytype); Assert.True(myEnumBuilder.IsEnum); Assert.Equal(myEnumBuilder.FullName, "MyEnum"); myEnumBuilder.CreateTypeInfo().AsType(); } private void VerificationHelperNegative(string name, TypeAttributes myTypeAttribute, Type mytype, bool flag) { ModuleBuilder myModuleBuilder = GetModuleBuilder(); // Define a enumeration type with name 'MyEnum' in the 'TempModule'. Assert.Throws<ArgumentException>(() => { EnumBuilder myEnumBuilder = myModuleBuilder.DefineEnum(name, myTypeAttribute, mytype); if (!flag) { myEnumBuilder = myModuleBuilder.DefineEnum(name, myTypeAttribute, typeof(int)); } }); } private void VerificationHelperNegative(string name, TypeAttributes myTypeAttribute, Type mytype, Type expectedException) { ModuleBuilder myModuleBuilder = GetModuleBuilder(); // Define a enumeration type with name 'MyEnum' in the 'TempModule'. Action test = () => { EnumBuilder myEnumBuilder = myModuleBuilder.DefineEnum(name, myTypeAttribute, mytype); myEnumBuilder.CreateTypeInfo().AsType(); }; Assert.Throws(expectedException, test); } } public class Container1 { public class Nested { private Container1 _parent; public Nested() { } public Nested(Container1 parent) { _parent = parent; } } } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using LibGit2Sharp.Core; using LibGit2Sharp.Core.Handles; namespace LibGit2Sharp { /// <summary> /// Provides access to configuration variables for a repository. /// </summary> public class Configuration : IDisposable, IEnumerable<ConfigurationEntry<string>> { private readonly FilePath globalConfigPath; private readonly FilePath xdgConfigPath; private readonly FilePath systemConfigPath; private readonly Repository repository; private ConfigurationSafeHandle configHandle; /// <summary> /// Needed for mocking purposes. /// </summary> protected Configuration() { } internal Configuration(Repository repository, string globalConfigurationFileLocation, string xdgConfigurationFileLocation, string systemConfigurationFileLocation) { this.repository = repository; globalConfigPath = globalConfigurationFileLocation ?? Proxy.git_config_find_global(); xdgConfigPath = xdgConfigurationFileLocation ?? Proxy.git_config_find_xdg(); systemConfigPath = systemConfigurationFileLocation ?? Proxy.git_config_find_system(); Init(); } private void Init() { configHandle = Proxy.git_config_new(); if (repository != null) { //TODO: push back this logic into libgit2. // As stated by @carlosmn "having a helper function to load the defaults and then allowing you // to modify it before giving it to git_repository_open_ext() would be a good addition, I think." // -- Agreed :) string repoConfigLocation = Path.Combine(repository.Info.Path, "config"); Proxy.git_config_add_file_ondisk(configHandle, repoConfigLocation, ConfigurationLevel.Local); Proxy.git_repository_set_config(repository.Handle, configHandle); } if (globalConfigPath != null) { Proxy.git_config_add_file_ondisk(configHandle, globalConfigPath, ConfigurationLevel.Global); } if (xdgConfigPath != null) { Proxy.git_config_add_file_ondisk(configHandle, xdgConfigPath, ConfigurationLevel.Xdg); } if (systemConfigPath != null) { Proxy.git_config_add_file_ondisk(configHandle, systemConfigPath, ConfigurationLevel.System); } } /// <summary> /// Access configuration values without a repository. Generally you want to access configuration via an instance of <see cref="Repository"/> instead. /// </summary> /// <param name="globalConfigurationFileLocation">Path to a Global configuration file. If null, the default path for a global configuration file will be probed.</param> /// <param name="xdgConfigurationFileLocation">Path to a XDG configuration file. If null, the default path for a XDG configuration file will be probed.</param> /// <param name="systemConfigurationFileLocation">Path to a System configuration file. If null, the default path for a system configuration file will be probed.</param> public Configuration(string globalConfigurationFileLocation = null, string xdgConfigurationFileLocation = null, string systemConfigurationFileLocation = null) : this(null, globalConfigurationFileLocation, xdgConfigurationFileLocation, systemConfigurationFileLocation) { } /// <summary> /// Determines which configuration file has been found. /// </summary> public virtual bool HasConfig(ConfigurationLevel level) { using (ConfigurationSafeHandle snapshot = Snapshot ()) using (ConfigurationSafeHandle handle = RetrieveConfigurationHandle(level, false, snapshot)) { return handle != null; } } #region IDisposable Members /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// Saves any open configuration files. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion /// <summary> /// Unset a configuration variable (key and value). /// </summary> /// <param name="key">The key to unset.</param> /// <param name="level">The configuration file which should be considered as the target of this operation</param> public virtual void Unset(string key, ConfigurationLevel level = ConfigurationLevel.Local) { Ensure.ArgumentNotNullOrEmptyString(key, "key"); using (ConfigurationSafeHandle h = RetrieveConfigurationHandle(level, true, configHandle)) { Proxy.git_config_delete(h, key); } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> protected virtual void Dispose(bool disposing) { configHandle.SafeDispose(); } /// <summary> /// Get a configuration value for a key. Keys are in the form 'section.name'. /// <para> /// The same escalation logic than in git.git will be used when looking for the key in the config files: /// - local: the Git file in the current repository /// - global: the Git file specific to the current interactive user (usually in `$HOME/.gitconfig`) /// - xdg: another Git file specific to the current interactive user (usually in `$HOME/.config/git/config`) /// - system: the system-wide Git file /// /// The first occurence of the key will be returned. /// </para> /// <para> /// For example in order to get the value for this in a .git\config file: /// /// <code> /// [core] /// bare = true /// </code> /// /// You would call: /// /// <code> /// bool isBare = repo.Config.Get&lt;bool&gt;("core.bare").Value; /// </code> /// </para> /// </summary> /// <typeparam name="T">The configuration value type</typeparam> /// <param name="key">The key</param> /// <returns>The <see cref="ConfigurationEntry{T}"/>, or null if not set</returns> public virtual ConfigurationEntry<T> Get<T>(string key) { Ensure.ArgumentNotNullOrEmptyString(key, "key"); using (ConfigurationSafeHandle snapshot = Snapshot()) { return Proxy.git_config_get_entry<T>(snapshot, key); } } /// <summary> /// Get a configuration value for a key. Keys are in the form 'section.name'. /// <para> /// For example in order to get the value for this in a .git\config file: /// /// <code> /// [core] /// bare = true /// </code> /// /// You would call: /// /// <code> /// bool isBare = repo.Config.Get&lt;bool&gt;("core.bare").Value; /// </code> /// </para> /// </summary> /// <typeparam name="T">The configuration value type</typeparam> /// <param name="key">The key</param> /// <param name="level">The configuration file into which the key should be searched for</param> /// <returns>The <see cref="ConfigurationEntry{T}"/>, or null if not set</returns> public virtual ConfigurationEntry<T> Get<T>(string key, ConfigurationLevel level) { Ensure.ArgumentNotNullOrEmptyString(key, "key"); using (ConfigurationSafeHandle snapshot = Snapshot()) using (ConfigurationSafeHandle handle = RetrieveConfigurationHandle(level, false, snapshot)) { if (handle == null) { return null; } return Proxy.git_config_get_entry<T>(handle, key); } } /// <summary> /// Set a configuration value for a key. Keys are in the form 'section.name'. /// <para> /// For example in order to set the value for this in a .git\config file: /// /// [test] /// boolsetting = true /// /// You would call: /// /// repo.Config.Set("test.boolsetting", true); /// </para> /// </summary> /// <typeparam name="T">The configuration value type</typeparam> /// <param name="key">The key parts</param> /// <param name="value">The value</param> /// <param name="level">The configuration file which should be considered as the target of this operation</param> public virtual void Set<T>(string key, T value, ConfigurationLevel level = ConfigurationLevel.Local) { Ensure.ArgumentNotNull(value, "value"); Ensure.ArgumentNotNullOrEmptyString(key, "key"); using (ConfigurationSafeHandle h = RetrieveConfigurationHandle(level, true, configHandle)) { if (!configurationTypedUpdater.ContainsKey(typeof(T))) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Generic Argument of type '{0}' is not supported.", typeof(T).FullName)); } configurationTypedUpdater[typeof(T)](key, value, h); } } /// <summary> /// Find configuration entries matching <paramref name="regexp"/>. /// </summary> /// <param name="regexp">A regular expression.</param> /// <param name="level">The configuration file into which the key should be searched for.</param> /// <returns>Matching entries.</returns> public virtual IEnumerable<ConfigurationEntry<string>> Find(string regexp, ConfigurationLevel level = ConfigurationLevel.Local) { Ensure.ArgumentNotNullOrEmptyString(regexp, "regexp"); using (ConfigurationSafeHandle snapshot = Snapshot()) using (ConfigurationSafeHandle h = RetrieveConfigurationHandle(level, true, snapshot)) { return Proxy.git_config_iterator_glob(h, regexp, BuildConfigEntry).ToList(); } } private ConfigurationSafeHandle RetrieveConfigurationHandle(ConfigurationLevel level, bool throwIfStoreHasNotBeenFound, ConfigurationSafeHandle fromHandle) { ConfigurationSafeHandle handle = null; if (fromHandle != null) { handle = Proxy.git_config_open_level(fromHandle, level); } if (handle == null && throwIfStoreHasNotBeenFound) { throw new LibGit2SharpException( string.Format(CultureInfo.InvariantCulture, "No {0} configuration file has been found.", Enum.GetName(typeof(ConfigurationLevel), level))); } return handle; } private static Action<string, object, ConfigurationSafeHandle> GetUpdater<T>(Action<ConfigurationSafeHandle, string, T> setter) { return (key, val, handle) => setter(handle, key, (T)val); } private readonly static IDictionary<Type, Action<string, object, ConfigurationSafeHandle>> configurationTypedUpdater = new Dictionary<Type, Action<string, object, ConfigurationSafeHandle>> { { typeof(int), GetUpdater<int>(Proxy.git_config_set_int32) }, { typeof(long), GetUpdater<long>(Proxy.git_config_set_int64) }, { typeof(bool), GetUpdater<bool>(Proxy.git_config_set_bool) }, { typeof(string), GetUpdater<string>(Proxy.git_config_set_string) }, }; /// <summary> /// Returns an enumerator that iterates through the configuration entries. /// </summary> /// <returns>An <see cref="IEnumerator{T}"/> object that can be used to iterate through the configuration entries.</returns> public virtual IEnumerator<ConfigurationEntry<string>> GetEnumerator() { return BuildConfigEntries().GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return ((IEnumerable<ConfigurationEntry<string>>)this).GetEnumerator(); } private IEnumerable<ConfigurationEntry<string>> BuildConfigEntries() { return Proxy.git_config_foreach(configHandle, BuildConfigEntry); } private static ConfigurationEntry<string> BuildConfigEntry(IntPtr entryPtr) { var entry = entryPtr.MarshalAs<GitConfigEntry>(); return new ConfigurationEntry<string>(LaxUtf8Marshaler.FromNative(entry.namePtr), LaxUtf8Marshaler.FromNative(entry.valuePtr), (ConfigurationLevel)entry.level); } /// <summary> /// Builds a <see cref="Signature"/> based on current configuration. /// <para> /// Name is populated from the user.name setting, and is "unknown" if unspecified. /// Email is populated from the user.email setting, and is built from /// <see cref="Environment.UserName"/> and <see cref="Environment.UserDomainName"/> if unspecified. /// </para> /// <para> /// The same escalation logic than in git.git will be used when looking for the key in the config files: /// - local: the Git file in the current repository /// - global: the Git file specific to the current interactive user (usually in `$HOME/.gitconfig`) /// - xdg: another Git file specific to the current interactive user (usually in `$HOME/.config/git/config`) /// - system: the system-wide Git file /// </para> /// </summary> /// <param name="now">The timestamp to use for the <see cref="Signature"/>.</param> /// <returns>The signature.</returns> public virtual Signature BuildSignature(DateTimeOffset now) { return BuildSignature(now, false); } internal Signature BuildSignature(DateTimeOffset now, bool shouldThrowIfNotFound) { const string userNameKey = "user.name"; var name = this.GetValueOrDefault<string>(userNameKey); var normalizedName = NormalizeUserSetting(shouldThrowIfNotFound, userNameKey, name, () => "unknown"); const string userEmailKey = "user.email"; var email = this.GetValueOrDefault<string>(userEmailKey); var normalizedEmail = NormalizeUserSetting(shouldThrowIfNotFound, userEmailKey, email, () => string.Format( CultureInfo.InvariantCulture, "{0}@{1}", Environment.UserName, Environment.UserDomainName)); return new Signature(normalizedName, normalizedEmail, now); } private string NormalizeUserSetting(bool shouldThrowIfNotFound, string entryName, string currentValue, Func<string> defaultValue) { if (!string.IsNullOrEmpty(currentValue)) { return currentValue; } string message = string.Format("Configuration value '{0}' is missing or invalid.", entryName); if (shouldThrowIfNotFound) { throw new LibGit2SharpException(message); } Log.Write(LogLevel.Warning, message); return defaultValue(); } private ConfigurationSafeHandle Snapshot() { return Proxy.git_config_snapshot(configHandle); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Data; using System.Text; using SubSonic.DataProviders; using SubSonic.Extensions; using System.Linq.Expressions; using SubSonic.Schema; using SubSonic.Repository; using System.Data.Common; using SubSonic.SqlGeneration.Schema; namespace Solution.DataAccess.DataModel { /// <summary> /// A class which represents the USERAUTHORITY table in the HKHR Database. /// </summary> public partial class USERAUTHORITY: IActiveRecord { #region Built-in testing static TestRepository<USERAUTHORITY> _testRepo; static void SetTestRepo(){ _testRepo = _testRepo ?? new TestRepository<USERAUTHORITY>(new Solution.DataAccess.DataModel.HKHRDB()); } public static void ResetTestRepo(){ _testRepo = null; SetTestRepo(); } public static void Setup(List<USERAUTHORITY> testlist){ SetTestRepo(); foreach (var item in testlist) { _testRepo._items.Add(item); } } public static void Setup(USERAUTHORITY item) { SetTestRepo(); _testRepo._items.Add(item); } public static void Setup(int testItems) { SetTestRepo(); for(int i=0;i<testItems;i++){ USERAUTHORITY item=new USERAUTHORITY(); _testRepo._items.Add(item); } } public bool TestMode = false; #endregion IRepository<USERAUTHORITY> _repo; ITable tbl; bool _isNew; public bool IsNew(){ return _isNew; } public void SetIsLoaded(bool isLoaded){ _isLoaded=isLoaded; if(isLoaded) OnLoaded(); } public void SetIsNew(bool isNew){ _isNew=isNew; } bool _isLoaded; public bool IsLoaded(){ return _isLoaded; } List<IColumn> _dirtyColumns; public bool IsDirty(){ return _dirtyColumns.Count>0; } public List<IColumn> GetDirtyColumns (){ return _dirtyColumns; } Solution.DataAccess.DataModel.HKHRDB _db; public USERAUTHORITY(string connectionString, string providerName) { _db=new Solution.DataAccess.DataModel.HKHRDB(connectionString, providerName); Init(); } void Init(){ TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase); _dirtyColumns=new List<IColumn>(); if(TestMode){ USERAUTHORITY.SetTestRepo(); _repo=_testRepo; }else{ _repo = new SubSonicRepository<USERAUTHORITY>(_db); } tbl=_repo.GetTable(); SetIsNew(true); OnCreated(); } public USERAUTHORITY(){ _db=new Solution.DataAccess.DataModel.HKHRDB(); Init(); } public void ORMapping(IDataRecord dataRecord) { IReadRecord readRecord = SqlReadRecord.GetIReadRecord(); readRecord.DataRecord = dataRecord; Id = readRecord.get_int("Id",null); GROUPS = readRecord.get_string("GROUPS",null); node = readRecord.get_string("node",null); ToolNo = readRecord.get_string("ToolNo",null); TYPE = readRecord.get_string("TYPE",null); RECORD_BY = readRecord.get_string("RECORD_BY",null); RECORD_DATE = readRecord.get_datetime("RECORD_DATE",null); EDIT_BY = readRecord.get_string("EDIT_BY",null); EDIT_DATE = readRecord.get_datetime("EDIT_DATE",null); } partial void OnCreated(); partial void OnLoaded(); partial void OnSaved(); partial void OnChanged(); public IList<IColumn> Columns{ get{ return tbl.Columns; } } public USERAUTHORITY(Expression<Func<USERAUTHORITY, bool>> expression):this() { SetIsLoaded(_repo.Load(this,expression)); } internal static IRepository<USERAUTHORITY> GetRepo(string connectionString, string providerName){ Solution.DataAccess.DataModel.HKHRDB db; if(String.IsNullOrEmpty(connectionString)){ db=new Solution.DataAccess.DataModel.HKHRDB(); }else{ db=new Solution.DataAccess.DataModel.HKHRDB(connectionString, providerName); } IRepository<USERAUTHORITY> _repo; if(db.TestMode){ USERAUTHORITY.SetTestRepo(); _repo=_testRepo; }else{ _repo = new SubSonicRepository<USERAUTHORITY>(db); } return _repo; } internal static IRepository<USERAUTHORITY> GetRepo(){ return GetRepo("",""); } public static USERAUTHORITY SingleOrDefault(Expression<Func<USERAUTHORITY, bool>> expression) { var repo = GetRepo(); var results=repo.Find(expression); USERAUTHORITY single=null; if(results.Count() > 0){ single=results.ToList()[0]; single.OnLoaded(); single.SetIsLoaded(true); single.SetIsNew(false); } return single; } public static USERAUTHORITY SingleOrDefault(Expression<Func<USERAUTHORITY, bool>> expression,string connectionString, string providerName) { var repo = GetRepo(connectionString,providerName); var results=repo.Find(expression); USERAUTHORITY single=null; if(results.Count() > 0){ single=results.ToList()[0]; } return single; } public static bool Exists(Expression<Func<USERAUTHORITY, bool>> expression,string connectionString, string providerName) { return All(connectionString,providerName).Any(expression); } public static bool Exists(Expression<Func<USERAUTHORITY, bool>> expression) { return All().Any(expression); } public static IList<USERAUTHORITY> Find(Expression<Func<USERAUTHORITY, bool>> expression) { var repo = GetRepo(); return repo.Find(expression).ToList(); } public static IList<USERAUTHORITY> Find(Expression<Func<USERAUTHORITY, bool>> expression,string connectionString, string providerName) { var repo = GetRepo(connectionString,providerName); return repo.Find(expression).ToList(); } public static IQueryable<USERAUTHORITY> All(string connectionString, string providerName) { return GetRepo(connectionString,providerName).GetAll(); } public static IQueryable<USERAUTHORITY> All() { return GetRepo().GetAll(); } public static PagedList<USERAUTHORITY> GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) { return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize); } public static PagedList<USERAUTHORITY> GetPaged(string sortBy, int pageIndex, int pageSize) { return GetRepo().GetPaged(sortBy, pageIndex, pageSize); } public static PagedList<USERAUTHORITY> GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) { return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize); } public static PagedList<USERAUTHORITY> GetPaged(int pageIndex, int pageSize) { return GetRepo().GetPaged(pageIndex, pageSize); } public string KeyName() { return "Id"; } public object KeyValue() { return this.Id; } public void SetKeyValue(object value) { if (value != null && value!=DBNull.Value) { var settable = value.ChangeTypeTo<int>(); this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null); } } public override string ToString(){ var sb = new StringBuilder(); sb.Append("Id=" + Id + "; "); sb.Append("GROUPS=" + GROUPS + "; "); sb.Append("node=" + node + "; "); sb.Append("ToolNo=" + ToolNo + "; "); sb.Append("TYPE=" + TYPE + "; "); sb.Append("RECORD_BY=" + RECORD_BY + "; "); sb.Append("RECORD_DATE=" + RECORD_DATE + "; "); sb.Append("EDIT_BY=" + EDIT_BY + "; "); sb.Append("EDIT_DATE=" + EDIT_DATE + "; "); return sb.ToString(); } public override bool Equals(object obj){ if(obj.GetType()==typeof(USERAUTHORITY)){ USERAUTHORITY compare=(USERAUTHORITY)obj; return compare.KeyValue()==this.KeyValue(); }else{ return base.Equals(obj); } } public override int GetHashCode() { return this.Id; } public string DescriptorValue() { return this.GROUPS.ToString(); } public string DescriptorColumn() { return "GROUPS"; } public static string GetKeyColumn() { return "Id"; } public static string GetDescriptorColumn() { return "GROUPS"; } #region ' Foreign Keys ' #endregion int _Id; /// <summary> /// /// </summary> [SubSonicPrimaryKey] public int Id { get { return _Id; } set { if(_Id!=value || _isLoaded){ _Id=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Id"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } string _GROUPS; /// <summary> /// /// </summary> public string GROUPS { get { return _GROUPS; } set { if(_GROUPS!=value || _isLoaded){ _GROUPS=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="GROUPS"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } string _node; /// <summary> /// /// </summary> public string node { get { return _node; } set { if(_node!=value || _isLoaded){ _node=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="node"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } string _ToolNo; /// <summary> /// /// </summary> public string ToolNo { get { return _ToolNo; } set { if(_ToolNo!=value || _isLoaded){ _ToolNo=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ToolNo"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } string _TYPE; /// <summary> /// /// </summary> public string TYPE { get { return _TYPE; } set { if(_TYPE!=value || _isLoaded){ _TYPE=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="TYPE"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } string _RECORD_BY; /// <summary> /// /// </summary> public string RECORD_BY { get { return _RECORD_BY; } set { if(_RECORD_BY!=value || _isLoaded){ _RECORD_BY=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="RECORD_BY"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } DateTime? _RECORD_DATE; /// <summary> /// /// </summary> public DateTime? RECORD_DATE { get { return _RECORD_DATE; } set { if(_RECORD_DATE!=value || _isLoaded){ _RECORD_DATE=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="RECORD_DATE"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } string _EDIT_BY; /// <summary> /// /// </summary> public string EDIT_BY { get { return _EDIT_BY; } set { if(_EDIT_BY!=value || _isLoaded){ _EDIT_BY=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="EDIT_BY"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } DateTime? _EDIT_DATE; /// <summary> /// /// </summary> public DateTime? EDIT_DATE { get { return _EDIT_DATE; } set { if(_EDIT_DATE!=value || _isLoaded){ _EDIT_DATE=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="EDIT_DATE"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } public DbCommand GetUpdateCommand() { if(TestMode) return _db.DataProvider.CreateCommand(); else return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand(); } public DbCommand GetInsertCommand() { if(TestMode) return _db.DataProvider.CreateCommand(); else return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand(); } public DbCommand GetDeleteCommand() { if(TestMode) return _db.DataProvider.CreateCommand(); else return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand(); } public void Update(){ Update(_db.DataProvider); } public void Update(IDataProvider provider){ if(this._dirtyColumns.Count>0){ _repo.Update(this,provider); _dirtyColumns.Clear(); } OnSaved(); } public void Add(){ Add(_db.DataProvider); } public void Add(IDataProvider provider){ var key=KeyValue(); if(key==null){ var newKey=_repo.Add(this,provider); this.SetKeyValue(newKey); }else{ _repo.Add(this,provider); } SetIsNew(false); OnSaved(); } public void Save() { Save(_db.DataProvider); } public void Save(IDataProvider provider) { if (_isNew) { Add(provider); } else { Update(provider); } } public void Delete(IDataProvider provider) { _repo.Delete(KeyValue()); } public void Delete() { Delete(_db.DataProvider); } public static void Delete(Expression<Func<USERAUTHORITY, bool>> expression) { var repo = GetRepo(); repo.DeleteMany(expression); } public void Load(IDataReader rdr) { Load(rdr, true); } public void Load(IDataReader rdr, bool closeReader) { if (rdr.Read()) { try { rdr.Load(this); SetIsNew(false); SetIsLoaded(true); } catch { SetIsLoaded(false); throw; } }else{ SetIsLoaded(false); } if (closeReader) rdr.Dispose(); } } }
#region Copyright //////////////////////////////////////////////////////////////////////////////// // The following FIT Protocol software provided may be used with FIT protocol // devices only and remains the copyrighted property of Dynastream Innovations Inc. // The software is being provided on an "as-is" basis and as an accommodation, // and therefore all warranties, representations, or guarantees of any kind // (whether express, implied or statutory) including, without limitation, // warranties of merchantability, non-infringement, or fitness for a particular // purpose, are specifically disclaimed. // // Copyright 2015 Dynastream Innovations Inc. //////////////////////////////////////////////////////////////////////////////// // ****WARNING**** This file is auto-generated! Do NOT edit this file. // Profile Version = 16.10Release // Tag = development-akw-16.10.00-0 //////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.IO; namespace FickleFrostbite.FIT { /// <summary> /// Implements the DeviceInfo profile message. /// </summary> public class DeviceInfoMesg : Mesg { #region Fields static class DeviceTypeSubfield { public static ushort AntplusDeviceType = 0; public static ushort AntDeviceType = 1; public static ushort Subfields = 2; public static ushort Active = Fit.SubfieldIndexActiveSubfield; public static ushort MainField = Fit.SubfieldIndexMainField; } static class ProductSubfield { public static ushort GarminProduct = 0; public static ushort Subfields = 1; public static ushort Active = Fit.SubfieldIndexActiveSubfield; public static ushort MainField = Fit.SubfieldIndexMainField; } #endregion #region Constructors public DeviceInfoMesg() : base(Profile.mesgs[Profile.DeviceInfoIndex]) { } public DeviceInfoMesg(Mesg mesg) : base(mesg) { } #endregion // Constructors #region Methods ///<summary> /// Retrieves the Timestamp field /// Units: s</summary> /// <returns>Returns DateTime representing the Timestamp field</returns> public DateTime GetTimestamp() { return TimestampToDateTime((uint?)GetFieldValue(253, 0, Fit.SubfieldIndexMainField)); } /// <summary> /// Set Timestamp field /// Units: s</summary> /// <param name="timestamp_">Nullable field value to be set</param> public void SetTimestamp(DateTime timestamp_) { SetFieldValue(253, 0, timestamp_.GetTimeStamp(), Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the DeviceIndex field</summary> /// <returns>Returns nullable byte representing the DeviceIndex field</returns> public byte? GetDeviceIndex() { return (byte?)GetFieldValue(0, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set DeviceIndex field</summary> /// <param name="deviceIndex_">Nullable field value to be set</param> public void SetDeviceIndex(byte? deviceIndex_) { SetFieldValue(0, 0, deviceIndex_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the DeviceType field</summary> /// <returns>Returns nullable byte representing the DeviceType field</returns> public byte? GetDeviceType() { return (byte?)GetFieldValue(1, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set DeviceType field</summary> /// <param name="deviceType_">Nullable field value to be set</param> public void SetDeviceType(byte? deviceType_) { SetFieldValue(1, 0, deviceType_, Fit.SubfieldIndexMainField); } /// <summary> /// Retrieves the AntplusDeviceType subfield</summary> /// <returns>Nullable byte representing the AntplusDeviceType subfield</returns> public byte? GetAntplusDeviceType() { return (byte?)GetFieldValue(1, 0, DeviceTypeSubfield.AntplusDeviceType); } /// <summary> /// /// Set AntplusDeviceType subfield</summary> /// <param name="antplusDeviceType">Subfield value to be set</param> public void SetAntplusDeviceType(byte? antplusDeviceType) { SetFieldValue(1, 0, antplusDeviceType, DeviceTypeSubfield.AntplusDeviceType); } /// <summary> /// Retrieves the AntDeviceType subfield</summary> /// <returns>Nullable byte representing the AntDeviceType subfield</returns> public byte? GetAntDeviceType() { return (byte?)GetFieldValue(1, 0, DeviceTypeSubfield.AntDeviceType); } /// <summary> /// /// Set AntDeviceType subfield</summary> /// <param name="antDeviceType">Subfield value to be set</param> public void SetAntDeviceType(byte? antDeviceType) { SetFieldValue(1, 0, antDeviceType, DeviceTypeSubfield.AntDeviceType); } ///<summary> /// Retrieves the Manufacturer field</summary> /// <returns>Returns nullable ushort representing the Manufacturer field</returns> public ushort? GetManufacturer() { return (ushort?)GetFieldValue(2, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set Manufacturer field</summary> /// <param name="manufacturer_">Nullable field value to be set</param> public void SetManufacturer(ushort? manufacturer_) { SetFieldValue(2, 0, manufacturer_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the SerialNumber field</summary> /// <returns>Returns nullable uint representing the SerialNumber field</returns> public uint? GetSerialNumber() { return (uint?)GetFieldValue(3, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set SerialNumber field</summary> /// <param name="serialNumber_">Nullable field value to be set</param> public void SetSerialNumber(uint? serialNumber_) { SetFieldValue(3, 0, serialNumber_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Product field</summary> /// <returns>Returns nullable ushort representing the Product field</returns> public ushort? GetProduct() { return (ushort?)GetFieldValue(4, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set Product field</summary> /// <param name="product_">Nullable field value to be set</param> public void SetProduct(ushort? product_) { SetFieldValue(4, 0, product_, Fit.SubfieldIndexMainField); } /// <summary> /// Retrieves the GarminProduct subfield</summary> /// <returns>Nullable ushort representing the GarminProduct subfield</returns> public ushort? GetGarminProduct() { return (ushort?)GetFieldValue(4, 0, ProductSubfield.GarminProduct); } /// <summary> /// /// Set GarminProduct subfield</summary> /// <param name="garminProduct">Subfield value to be set</param> public void SetGarminProduct(ushort? garminProduct) { SetFieldValue(4, 0, garminProduct, ProductSubfield.GarminProduct); } ///<summary> /// Retrieves the SoftwareVersion field</summary> /// <returns>Returns nullable float representing the SoftwareVersion field</returns> public float? GetSoftwareVersion() { return (float?)GetFieldValue(5, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set SoftwareVersion field</summary> /// <param name="softwareVersion_">Nullable field value to be set</param> public void SetSoftwareVersion(float? softwareVersion_) { SetFieldValue(5, 0, softwareVersion_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the HardwareVersion field</summary> /// <returns>Returns nullable byte representing the HardwareVersion field</returns> public byte? GetHardwareVersion() { return (byte?)GetFieldValue(6, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set HardwareVersion field</summary> /// <param name="hardwareVersion_">Nullable field value to be set</param> public void SetHardwareVersion(byte? hardwareVersion_) { SetFieldValue(6, 0, hardwareVersion_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the CumOperatingTime field /// Units: s /// Comment: Reset by new battery or charge.</summary> /// <returns>Returns nullable uint representing the CumOperatingTime field</returns> public uint? GetCumOperatingTime() { return (uint?)GetFieldValue(7, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set CumOperatingTime field /// Units: s /// Comment: Reset by new battery or charge.</summary> /// <param name="cumOperatingTime_">Nullable field value to be set</param> public void SetCumOperatingTime(uint? cumOperatingTime_) { SetFieldValue(7, 0, cumOperatingTime_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the BatteryVoltage field /// Units: V</summary> /// <returns>Returns nullable float representing the BatteryVoltage field</returns> public float? GetBatteryVoltage() { return (float?)GetFieldValue(10, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set BatteryVoltage field /// Units: V</summary> /// <param name="batteryVoltage_">Nullable field value to be set</param> public void SetBatteryVoltage(float? batteryVoltage_) { SetFieldValue(10, 0, batteryVoltage_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the BatteryStatus field</summary> /// <returns>Returns nullable byte representing the BatteryStatus field</returns> public byte? GetBatteryStatus() { return (byte?)GetFieldValue(11, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set BatteryStatus field</summary> /// <param name="batteryStatus_">Nullable field value to be set</param> public void SetBatteryStatus(byte? batteryStatus_) { SetFieldValue(11, 0, batteryStatus_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the SensorPosition field /// Comment: Indicates the location of the sensor</summary> /// <returns>Returns nullable BodyLocation enum representing the SensorPosition field</returns> public BodyLocation? GetSensorPosition() { object obj = GetFieldValue(18, 0, Fit.SubfieldIndexMainField); BodyLocation? value = obj == null ? (BodyLocation?)null : (BodyLocation)obj; return value; } /// <summary> /// Set SensorPosition field /// Comment: Indicates the location of the sensor</summary> /// <param name="sensorPosition_">Nullable field value to be set</param> public void SetSensorPosition(BodyLocation? sensorPosition_) { SetFieldValue(18, 0, sensorPosition_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Descriptor field /// Comment: Used to describe the sensor or location</summary> /// <returns>Returns byte[] representing the Descriptor field</returns> public byte[] GetDescriptor() { return (byte[])GetFieldValue(19, 0, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Descriptor field /// Comment: Used to describe the sensor or location</summary> /// <returns>Returns String representing the Descriptor field</returns> public String GetDescriptorAsString() { return Encoding.UTF8.GetString((byte[])GetFieldValue(19, 0, Fit.SubfieldIndexMainField)); } ///<summary> /// Set Descriptor field /// Comment: Used to describe the sensor or location</summary> /// <returns>Returns String representing the Descriptor field</returns> public void SetDescriptor(String descriptor_) { SetFieldValue(19, 0, System.Text.Encoding.UTF8.GetBytes(descriptor_), Fit.SubfieldIndexMainField); } /// <summary> /// Set Descriptor field /// Comment: Used to describe the sensor or location</summary> /// <param name="descriptor_">field value to be set</param> public void SetDescriptor(byte[] descriptor_) { SetFieldValue(19, 0, descriptor_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the AntTransmissionType field</summary> /// <returns>Returns nullable byte representing the AntTransmissionType field</returns> public byte? GetAntTransmissionType() { return (byte?)GetFieldValue(20, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set AntTransmissionType field</summary> /// <param name="antTransmissionType_">Nullable field value to be set</param> public void SetAntTransmissionType(byte? antTransmissionType_) { SetFieldValue(20, 0, antTransmissionType_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the AntDeviceNumber field</summary> /// <returns>Returns nullable ushort representing the AntDeviceNumber field</returns> public ushort? GetAntDeviceNumber() { return (ushort?)GetFieldValue(21, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set AntDeviceNumber field</summary> /// <param name="antDeviceNumber_">Nullable field value to be set</param> public void SetAntDeviceNumber(ushort? antDeviceNumber_) { SetFieldValue(21, 0, antDeviceNumber_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the AntNetwork field</summary> /// <returns>Returns nullable AntNetwork enum representing the AntNetwork field</returns> public AntNetwork? GetAntNetwork() { object obj = GetFieldValue(22, 0, Fit.SubfieldIndexMainField); AntNetwork? value = obj == null ? (AntNetwork?)null : (AntNetwork)obj; return value; } /// <summary> /// Set AntNetwork field</summary> /// <param name="antNetwork_">Nullable field value to be set</param> public void SetAntNetwork(AntNetwork? antNetwork_) { SetFieldValue(22, 0, antNetwork_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the SourceType field</summary> /// <returns>Returns nullable SourceType enum representing the SourceType field</returns> public SourceType? GetSourceType() { object obj = GetFieldValue(25, 0, Fit.SubfieldIndexMainField); SourceType? value = obj == null ? (SourceType?)null : (SourceType)obj; return value; } /// <summary> /// Set SourceType field</summary> /// <param name="sourceType_">Nullable field value to be set</param> public void SetSourceType(SourceType? sourceType_) { SetFieldValue(25, 0, sourceType_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the ProductName field /// Comment: Optional free form string to indicate the devices name or model</summary> /// <returns>Returns byte[] representing the ProductName field</returns> public byte[] GetProductName() { return (byte[])GetFieldValue(27, 0, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the ProductName field /// Comment: Optional free form string to indicate the devices name or model</summary> /// <returns>Returns String representing the ProductName field</returns> public String GetProductNameAsString() { return Encoding.UTF8.GetString((byte[])GetFieldValue(27, 0, Fit.SubfieldIndexMainField)); } ///<summary> /// Set ProductName field /// Comment: Optional free form string to indicate the devices name or model</summary> /// <returns>Returns String representing the ProductName field</returns> public void SetProductName(String productName_) { SetFieldValue(27, 0, System.Text.Encoding.UTF8.GetBytes(productName_), Fit.SubfieldIndexMainField); } /// <summary> /// Set ProductName field /// Comment: Optional free form string to indicate the devices name or model</summary> /// <param name="productName_">field value to be set</param> public void SetProductName(byte[] productName_) { SetFieldValue(27, 0, productName_, Fit.SubfieldIndexMainField); } #endregion // Methods } // Class } // namespace
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Concurrent; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; namespace System.Net.Sockets { internal sealed unsafe class SocketAsyncEngine { // // Encapsulates a particular SocketAsyncContext object's access to a SocketAsyncEngine. // public readonly struct Token { private readonly SocketAsyncEngine _engine; private readonly IntPtr _handle; public Token(SocketAsyncContext context) { AllocateToken(context, out _engine, out _handle); } public bool WasAllocated { get { return _engine != null; } } public void Free() { if (WasAllocated) { _engine.FreeHandle(_handle); } } public bool TryRegister(SafeSocketHandle socket, out Interop.Error error) { Debug.Assert(WasAllocated, "Expected WasAllocated to be true"); return _engine.TryRegister(socket, _handle, out error); } } private const int EventBufferCount = #if DEBUG 32; #else 1024; #endif private static readonly object s_lock = new object(); // In debug builds, force there to be 2 engines. In release builds, use half the number of processors when // there are at least 6. The lower bound is to avoid using multiple engines on systems which aren't servers. #pragma warning disable CA1802 // const works for debug, but needs to be static readonly for release private static readonly int s_engineCount = #if DEBUG 2; #else Environment.ProcessorCount >= 6 ? Environment.ProcessorCount / 2 : 1; #endif #pragma warning restore CA1802 // // The current engines. We replace an engine when it runs out of "handle" values. // Must be accessed under s_lock. // private static readonly SocketAsyncEngine[] s_currentEngines = new SocketAsyncEngine[s_engineCount]; private static int s_allocateFromEngine = 0; private readonly IntPtr _port; private readonly Interop.Sys.SocketEvent* _buffer; // // The read and write ends of a native pipe, used to signal that this instance's event loop should stop // processing events. // private readonly int _shutdownReadPipe; private readonly int _shutdownWritePipe; // // Each SocketAsyncContext is associated with a particular "handle" value, used to identify that // SocketAsyncContext when events are raised. These handle values are never reused, because we do not have // a way to ensure that we will never see an event for a socket/handle that has been freed. Instead, we // allocate monotonically increasing handle values up to some limit; when we would exceed that limit, // we allocate a new SocketAsyncEngine (and thus a new event port) and start the handle values over at zero. // Thus we can uniquely identify a given SocketAsyncContext by the *pair* {SocketAsyncEngine, handle}, // and avoid any issues with misidentifying the target of an event we read from the port. // #if DEBUG // // In debug builds, force rollover to new SocketAsyncEngine instances so that code doesn't go untested, since // it's very unlikely that the "real" limits will ever be reached in test code. // private static readonly IntPtr MaxHandles = (IntPtr)(EventBufferCount * 2); #else // // In release builds, we use *very* high limits. No 64-bit process running on release builds should ever // reach the handle limit for a single event port, and even 32-bit processes should see this only very rarely. // private static readonly IntPtr MaxHandles = IntPtr.Size == 4 ? (IntPtr)int.MaxValue : (IntPtr)long.MaxValue; #endif private static readonly IntPtr MinHandlesForAdditionalEngine = s_engineCount == 1 ? MaxHandles : (IntPtr)32; // // Sentinel handle value to identify events from the "shutdown pipe," used to signal an event loop to stop // processing events. // private static readonly IntPtr ShutdownHandle = (IntPtr)(-1); // // The next handle value to be allocated for this event port. // Must be accessed under s_lock. // private IntPtr _nextHandle; // // Count of handles that have been allocated for this event port, but not yet freed. // Must be accessed under s_lock. // private IntPtr _outstandingHandles; // // Maps handle values to SocketAsyncContext instances. // private readonly ConcurrentDictionary<IntPtr, SocketAsyncContext> _handleToContextMap = new ConcurrentDictionary<IntPtr, SocketAsyncContext>(); // // True if we've reached the handle value limit for this event port, and thus must allocate a new event port // on the next handle allocation. // private bool IsFull { get { return _nextHandle == MaxHandles; } } // True if we've don't have sufficient active sockets to allow allocating a new engine. private bool HasLowNumberOfSockets { get { return IntPtr.Size == 4 ? _outstandingHandles.ToInt32() < MinHandlesForAdditionalEngine.ToInt32() : _outstandingHandles.ToInt64() < MinHandlesForAdditionalEngine.ToInt64(); } } // // Allocates a new {SocketAsyncEngine, handle} pair. // private static void AllocateToken(SocketAsyncContext context, out SocketAsyncEngine engine, out IntPtr handle) { lock (s_lock) { engine = s_currentEngines[s_allocateFromEngine]; if (engine == null) { // We minimize the number of engines on applications that have a low number of concurrent sockets. for (int i = 0; i < s_allocateFromEngine; i++) { var previousEngine = s_currentEngines[i]; if (previousEngine == null || previousEngine.HasLowNumberOfSockets) { s_allocateFromEngine = i; engine = previousEngine; break; } } if (engine == null) { s_currentEngines[s_allocateFromEngine] = engine = new SocketAsyncEngine(); } } handle = engine.AllocateHandle(context); if (engine.IsFull) { // We'll need to create a new event port for the next handle. s_currentEngines[s_allocateFromEngine] = null; } // Round-robin to the next engine once we have sufficient sockets on this one. if (!engine.HasLowNumberOfSockets) { s_allocateFromEngine = (s_allocateFromEngine + 1) % s_engineCount; } } } private IntPtr AllocateHandle(SocketAsyncContext context) { Debug.Assert(Monitor.IsEntered(s_lock), "Expected s_lock to be held"); Debug.Assert(!IsFull, "Expected !IsFull"); IntPtr handle = _nextHandle; _handleToContextMap.TryAdd(handle, context); _nextHandle = IntPtr.Add(_nextHandle, 1); _outstandingHandles = IntPtr.Add(_outstandingHandles, 1); Debug.Assert(handle != ShutdownHandle, $"Expected handle != ShutdownHandle: {handle}"); return handle; } private void FreeHandle(IntPtr handle) { Debug.Assert(handle != ShutdownHandle, $"Expected handle != ShutdownHandle: {handle}"); bool shutdownNeeded = false; lock (s_lock) { if (_handleToContextMap.TryRemove(handle, out _)) { _outstandingHandles = IntPtr.Subtract(_outstandingHandles, 1); Debug.Assert(_outstandingHandles.ToInt64() >= 0, $"Unexpected _outstandingHandles: {_outstandingHandles}"); // // If we've allocated all possible handles for this instance, and freed them all, then // we don't need the event loop any more, and can reclaim resources. // if (IsFull && _outstandingHandles == IntPtr.Zero) { shutdownNeeded = true; } } } // // Signal shutdown outside of the lock to reduce contention. // if (shutdownNeeded) { RequestEventLoopShutdown(); } } private SocketAsyncEngine() { _port = (IntPtr)(-1); _shutdownReadPipe = -1; _shutdownWritePipe = -1; try { // // Create the event port and buffer // Interop.Error err = Interop.Sys.CreateSocketEventPort(out _port); if (err != Interop.Error.SUCCESS) { throw new InternalException(err); } err = Interop.Sys.CreateSocketEventBuffer(EventBufferCount, out _buffer); if (err != Interop.Error.SUCCESS) { throw new InternalException(err); } // // Create the pipe for signaling shutdown, and register for "read" events for the pipe. Now writing // to the pipe will send an event to the event loop. // int* pipeFds = stackalloc int[2]; int pipeResult = Interop.Sys.Pipe(pipeFds, Interop.Sys.PipeFlags.O_CLOEXEC); if (pipeResult != 0) { throw new InternalException(pipeResult); } _shutdownReadPipe = pipeFds[Interop.Sys.ReadEndOfPipe]; _shutdownWritePipe = pipeFds[Interop.Sys.WriteEndOfPipe]; err = Interop.Sys.TryChangeSocketEventRegistration(_port, (IntPtr)_shutdownReadPipe, Interop.Sys.SocketEvents.None, Interop.Sys.SocketEvents.Read, ShutdownHandle); if (err != Interop.Error.SUCCESS) { throw new InternalException(err); } // // Start the event loop on its own thread. // bool suppressFlow = !ExecutionContext.IsFlowSuppressed(); try { if (suppressFlow) ExecutionContext.SuppressFlow(); Task.Factory.StartNew( s => ((SocketAsyncEngine)s).EventLoop(), this, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); } finally { if (suppressFlow) ExecutionContext.RestoreFlow(); } } catch { FreeNativeResources(); throw; } } private void EventLoop() { try { bool shutdown = false; while (!shutdown) { int numEvents = EventBufferCount; Interop.Error err = Interop.Sys.WaitForSocketEvents(_port, _buffer, &numEvents); if (err != Interop.Error.SUCCESS) { throw new InternalException(err); } // The native shim is responsible for ensuring this condition. Debug.Assert(numEvents > 0, $"Unexpected numEvents: {numEvents}"); for (int i = 0; i < numEvents; i++) { IntPtr handle = _buffer[i].Data; if (handle == ShutdownHandle) { shutdown = true; } else { Debug.Assert(handle.ToInt64() < MaxHandles.ToInt64(), $"Unexpected values: handle={handle}, MaxHandles={MaxHandles}"); _handleToContextMap.TryGetValue(handle, out SocketAsyncContext context); if (context != null) { context.HandleEvents(_buffer[i].Events); context = null; } } } } FreeNativeResources(); } catch (Exception e) { Environment.FailFast("Exception thrown from SocketAsyncEngine event loop: " + e.ToString(), e); } } private void RequestEventLoopShutdown() { // // Write to the pipe, which will wake up the event loop and cause it to exit. // byte b = 1; int bytesWritten = Interop.Sys.Write(_shutdownWritePipe, &b, 1); if (bytesWritten != 1) { throw new InternalException(bytesWritten); } } private void FreeNativeResources() { if (_shutdownReadPipe != -1) { Interop.Sys.Close((IntPtr)_shutdownReadPipe); } if (_shutdownWritePipe != -1) { Interop.Sys.Close((IntPtr)_shutdownWritePipe); } if (_buffer != null) { Interop.Sys.FreeSocketEventBuffer(_buffer); } if (_port != (IntPtr)(-1)) { Interop.Sys.CloseSocketEventPort(_port); } } private bool TryRegister(SafeSocketHandle socket, IntPtr handle, out Interop.Error error) { error = Interop.Sys.TryChangeSocketEventRegistration(_port, socket, Interop.Sys.SocketEvents.None, Interop.Sys.SocketEvents.Read | Interop.Sys.SocketEvents.Write, handle); return error == Interop.Error.SUCCESS; } } }
#region Disclaimer/Info /////////////////////////////////////////////////////////////////////////////////////////////////// // Subtext WebLog // // Subtext is an open source weblog system that is a fork of the .TEXT // weblog system. // // For updated news and information please visit http://subtextproject.com/ // Subtext is hosted at Google Code at http://code.google.com/p/subtext/ // The development mailing list is at subtext@googlegroups.com // // This project is licensed under the BSD license. See the License.txt file for more information. /////////////////////////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Web; using System.Web.Mvc; using System.Web.UI.WebControls; using Subtext.Extensibility; using Subtext.Framework; using Subtext.Framework.Components; using Subtext.Framework.Configuration; using Subtext.Framework.Routing; using Subtext.Framework.Services; using Subtext.Framework.Text; using Subtext.Framework.Tracking; using Subtext.Web.Admin.Pages; using Subtext.Web.Admin.WebUI; using Subtext.Web.Controls; using Subtext.Web.Properties; using Subtext.Web.UI.Controls; namespace Subtext.Web.Admin.UserControls { public partial class EntryEditor : BaseControl { private const string CategoryTypeViewStateKey = "CategoryType"; int? _postId; /// <summary> /// Gets or sets the type of the entry. /// </summary> /// <value>The type of the entry.</value> public PostType EntryType { get { if (ViewState["PostType"] != null) { return (PostType)ViewState["PostType"]; } return PostType.None; } set { ViewState["PostType"] = value; } } public int? PostId { get { if (_postId == null) { string postIdText = Request.QueryString["PostId"]; int postId; if (int.TryParse(postIdText, out postId)) { _postId = postId; } } return _postId; } } public CategoryType CategoryType { get { if (ViewState[CategoryTypeViewStateKey] != null) { return (CategoryType)ViewState[CategoryTypeViewStateKey]; } throw new InvalidOperationException(Resources.InvalidOperation_CategoryTypeNotSet); } set { ViewState[CategoryTypeViewStateKey] = value; } } //This is true if we came from a pencil edit link while viewing the post //from outside the admin tool. private bool ReturnToOriginalPost { get { return (Request.QueryString["return-to-post"] == "true"); } } protected override void OnLoad(EventArgs e) { if (!IsPostBack) { BindCategoryList(); SetEditorMode(); if (PostId != null) { BindPostEdit(); } else { BindPostCreate(); } } base.OnLoad(e); } private void BindCategoryList() { cklCategories.DataSource = Repository.GetCategories(CategoryType, ActiveFilter.None); cklCategories.DataValueField = "Id"; cklCategories.DataTextField = "Title"; cklCategories.DataBind(); } private void SetConfirmation() { var confirmPage = (ConfirmationPage)Page; confirmPage.IsInEdit = true; confirmPage.Message = Resources.Message_YouWillLoseUnsavedContent; lkbPost.Attributes.Add("OnClick", ConfirmationPage.BypassFunctionName); lkUpdateCategories.Attributes.Add("OnClick", ConfirmationPage.BypassFunctionName); lkbCancel.Attributes.Add("OnClick", ConfirmationPage.BypassFunctionName); } private void BindPostCreate() { txbTitle.Text = string.Empty; richTextEditor.Text = string.Empty; SetConfirmation(); SetDefaultPublishOptions(); PopulateMimeTypeDropDown(); } private void SetDefaultPublishOptions() { chkMainSyndication.Checked = true; ckbPublished.Checked = true; chkDisplayHomePage.Checked = true; chkComments.Checked = Config.CurrentBlog.CommentsEnabled; } private void BindPostEdit() { Debug.Assert(PostId != null, "PostId Should not be null when we call this"); SetConfirmation(); Entry entry = GetEntryForEditing(PostId.Value); if (entry == null) { ReturnToOrigin(null); return; } txbTitle.Text = entry.Title; if (!entry.DatePublishedUtc.IsNull() && entry.DatePublishedUtc > DateTime.UtcNow) { txtPostDate.Text = entry.DateSyndicated.ToString(CultureInfo.CurrentCulture); } VirtualPath entryUrl = Url.EntryUrl(entry); if (entryUrl != null) { hlEntryLink.NavigateUrl = entryUrl; hlEntryLink.Text = entryUrl.ToFullyQualifiedUrl(Config.CurrentBlog).ToString(); hlEntryLink.Attributes.Add("title", "view: " + entry.Title); } else hlEntryLink.Text = "This post has not been published yet, so it doesn't have an URL"; PopulateMimeTypeDropDown(); //Enclosures if (entry.Enclosure != null) { Enclosure.Collapsed = false; txbEnclosureTitle.Text = entry.Enclosure.Title; txbEnclosureUrl.Text = entry.Enclosure.Url; txbEnclosureSize.Text = entry.Enclosure.Size.ToString(); if (ddlMimeType.Items.FindByText(entry.Enclosure.MimeType) != null) { ddlMimeType.SelectedValue = entry.Enclosure.MimeType; } else { ddlMimeType.SelectedValue = "other"; txbEnclosureOtherMimetype.Text = entry.Enclosure.MimeType; } ddlAddToFeed.SelectedValue = entry.Enclosure.AddToFeed.ToString().ToLower(); ddlDisplayOnPost.SelectedValue = entry.Enclosure.ShowWithPost.ToString().ToLower(); } chkComments.Checked = entry.AllowComments; chkCommentsClosed.Checked = entry.CommentingClosed; SetCommentControls(); if (entry.CommentingClosedByAge) { chkCommentsClosed.Enabled = false; } chkDisplayHomePage.Checked = entry.DisplayOnHomePage; chkMainSyndication.Checked = entry.IncludeInMainSyndication; chkSyndicateDescriptionOnly.Checked = entry.SyndicateDescriptionOnly; chkIsAggregated.Checked = entry.IsAggregated; // Advanced Options txbEntryName.Text = entry.EntryName; txbExcerpt.Text = entry.Description; SetEditorText(entry.Body); ckbPublished.Checked = entry.IsActive; BindCategoryList(); for (int i = 0; i < cklCategories.Items.Count; i++) { cklCategories.Items[i].Selected = false; } ICollection<Link> postCategories = Repository.GetLinkCollectionByPostId(PostId.Value); if (postCategories.Count > 0) { foreach (Link postCategory in postCategories) { ListItem categoryItem = cklCategories.Items.FindByValue(postCategory.CategoryId.ToString(CultureInfo.InvariantCulture)); if (categoryItem == null) { throw new InvalidOperationException( string.Format(Resources.EntryEditor_CouldNotFindCategoryInList, postCategory.CategoryId, cklCategories.Items.Count)); } categoryItem.Selected = true; } } SetEditorMode(); Advanced.Collapsed = !Preferences.AlwaysExpandAdvanced; var adminMasterPage = Page.Master as AdminPageTemplate; if (adminMasterPage != null) { string title = string.Format(CultureInfo.InvariantCulture, Resources.EntryEditor_EditingTitle, CategoryType == CategoryType.StoryCollection ? Resources.Label_Article : Resources.Label_Post, entry.Title); adminMasterPage.Title = title; } if (entry.HasEntryName) { Advanced.Collapsed = false; txbEntryName.Text = entry.EntryName; } } private void PopulateMimeTypeDropDown() { ddlMimeType.Items.Add(new ListItem(Resources.Label_Choose, "none")); foreach (string key in MimeTypesMapper.Mappings.List) { ddlMimeType.Items.Add(new ListItem(MimeTypesMapper.Mappings.List[key], MimeTypesMapper.Mappings.List[key])); } ddlMimeType.Items.Add(new ListItem(Resources.Label_Other, "other")); } private void SetCommentControls() { if (!Blog.CommentsEnabled) { chkComments.Enabled = false; chkCommentsClosed.Enabled = false; } } public void EditNewEntry() { SetConfirmation(); } private void ReturnToOrigin(string message) { if (ReturnToOriginalPost && PostId != null) { // We came from outside the post, let's go there. Entry updatedEntry = Repository.GetEntry(PostId.Value, true /*activeOnly*/, false /*includeCategories*/); if (updatedEntry != null) { Response.Redirect(Url.EntryUrl(updatedEntry)); } } else { string url = "Default.aspx"; if (!String.IsNullOrEmpty(message)) { url += "?message=" + HttpUtility.UrlEncode(message); } Response.Redirect(url); } } private void UpdatePost() { DateTime postDate = NullValue.NullDateTime; vCustomPostDate.IsValid = string.IsNullOrEmpty(txtPostDate.Text) || DateTime.TryParse(txtPostDate.Text, out postDate); EnableEnclosureValidation(EnclosureEnabled()); if (Page.IsValid) { string successMessage = Constants.RES_SUCCESSNEW; try { Entry entry; if (PostId == null) { ValidateEntryTypeIsNotNone(EntryType); entry = new Entry(EntryType); } else { entry = GetEntryForEditing(PostId.Value); if (entry.PostType != EntryType) { EntryType = entry.PostType; } } entry.Title = txbTitle.Text; entry.Body = richTextEditor.Xhtml; entry.Author = Config.CurrentBlog.Author; entry.Email = Config.CurrentBlog.Email; entry.BlogId = Config.CurrentBlog.Id; //Enclosure int enclosureId = 0; if (entry.Enclosure != null) { enclosureId = entry.Enclosure.Id; } if (EnclosureEnabled()) { if (entry.Enclosure == null) { entry.Enclosure = new Enclosure(); } Enclosure enc = entry.Enclosure; enc.Title = txbEnclosureTitle.Text; enc.Url = txbEnclosureUrl.Text; enc.MimeType = ddlMimeType.SelectedValue.Equals("other") ? txbEnclosureOtherMimetype.Text : ddlMimeType.SelectedValue; long size; Int64.TryParse(txbEnclosureSize.Text, out size); enc.Size = size; enc.AddToFeed = Boolean.Parse(ddlAddToFeed.SelectedValue); enc.ShowWithPost = Boolean.Parse(ddlDisplayOnPost.SelectedValue); } else { entry.Enclosure = null; } // Advanced options entry.IsActive = ckbPublished.Checked; entry.AllowComments = chkComments.Checked; entry.CommentingClosed = chkCommentsClosed.Checked; entry.DisplayOnHomePage = chkDisplayHomePage.Checked; entry.IncludeInMainSyndication = chkMainSyndication.Checked; entry.SyndicateDescriptionOnly = chkSyndicateDescriptionOnly.Checked; entry.IsAggregated = chkIsAggregated.Checked; entry.EntryName = txbEntryName.Text.NullIfEmpty(); entry.Description = txbExcerpt.Text.NullIfEmpty(); entry.Categories.Clear(); ReplaceSelectedCategoryNames(entry.Categories); if (!postDate.IsNull()) { entry.DatePublishedUtc = Blog.TimeZone.ToUtc(postDate); } if (PostId != null) { successMessage = Constants.RES_SUCCESSEDIT; entry.DateModifiedUtc = DateTime.UtcNow; entry.Id = PostId.Value; var entryPublisher = SubtextContext.ServiceLocator.GetService<IEntryPublisher>(); entryPublisher.Publish(entry); if (entry.Enclosure == null && enclosureId != 0) { Repository.DeleteEnclosure(enclosureId); } else if (entry.Enclosure != null && entry.Enclosure.Id != 0) { Repository.Update(entry.Enclosure); } else if (entry.Enclosure != null && entry.Enclosure.Id == 0) { entry.Enclosure.EntryId = entry.Id; Repository.Create(entry.Enclosure); } UpdateCategories(); } else { var entryPublisher = SubtextContext.ServiceLocator.GetService<IEntryPublisher>(); _postId = entryPublisher.Publish(entry); NotificationServices.Run(entry, Blog, Url); if (entry.Enclosure != null) { entry.Enclosure.EntryId = PostId.Value; Repository.Create(entry.Enclosure); } UpdateCategories(); AddCommunityCredits(entry); } } catch (Exception ex) { Messages.ShowError(String.Format(Constants.RES_EXCEPTION, Constants.RES_FAILUREEDIT, ex.Message)); successMessage = string.Empty; } //Prepared success messages were reset in the catch block because of some error on posting the content if (!String.IsNullOrEmpty(successMessage)) { ReturnToOrigin(successMessage); } } } [CoverageExclude] private static void ValidateEntryTypeIsNotNone(PostType entryType) { Debug.Assert(entryType != PostType.None, "The entry type is none. This should be impossible!"); } private bool EnclosureEnabled() { if (!String.IsNullOrEmpty(txbEnclosureUrl.Text)) { return true; } if (!String.IsNullOrEmpty(txbEnclosureTitle.Text)) { return true; } if (!String.IsNullOrEmpty(txbEnclosureSize.Text)) { return true; } return ddlMimeType.SelectedIndex > 0; } private void EnableEnclosureValidation(bool enabled) { valEncSizeRequired.Enabled = enabled; valEncUrlRequired.Enabled = enabled; valEncMimeTypeRequired.Enabled = enabled; valEncOtherMimetypeRequired.Enabled = enabled && ddlMimeType.SelectedValue.Equals("other"); } private void ReplaceSelectedCategoryNames(ICollection<string> sc) { sc.Clear(); foreach (ListItem item in cklCategories.Items) { if (item.Selected) { sc.Add(item.Text); } } } private string UpdateCategories() { try { if (PostId != null) { string successMessage = Constants.RES_SUCCESSCATEGORYUPDATE; var al = new List<int>(); foreach (ListItem item in cklCategories.Items) { if (item.Selected) { al.Add(int.Parse(item.Value)); } } Repository.SetEntryCategoryList(PostId.Value, al); return successMessage; } Messages.ShowError(Constants.RES_FAILURECATEGORYUPDATE + Resources.EntryEditor_ProblemEditingPostCategories); } catch (Exception ex) { Messages.ShowError(String.Format(Constants.RES_EXCEPTION, Constants.RES_FAILUREEDIT, ex.Message)); } return null; } private void SetEditorMode() { if (CategoryType == CategoryType.StoryCollection) { chkDisplayHomePage.Visible = false; chkIsAggregated.Visible = false; chkMainSyndication.Visible = false; chkSyndicateDescriptionOnly.Visible = false; } } private void SetEditorText(string bodyValue) { richTextEditor.Text = bodyValue; } override protected void OnInit(EventArgs e) { InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { lkbPost.Click += OnUpdatePostClick; lkUpdateCategories.Click += OnUpdateCategoriesClick; lkbCancel.Click += OnCancelClick; } private void OnCancelClick(object sender, EventArgs e) { if (PostId != null && ReturnToOriginalPost) { // We came from outside the post, let's go there. Entry updatedEntry = Repository.GetEntry(PostId.Value, true /* activeOnly */, false /* includeCategories */); if (updatedEntry != null) { Response.Redirect(Url.EntryUrl(updatedEntry)); return; } } ReturnToOrigin(null); } private void OnUpdatePostClick(object sender, EventArgs e) { UpdatePost(); } private void OnUpdateCategoriesClick(object sender, EventArgs e) { string successMessage = UpdateCategories(); if (successMessage != null) { ReturnToOrigin(successMessage); } } protected void richTextEditor_Error(object sender, RichTextEditorErrorEventArgs e) { Messages.ShowError(String.Format(Constants.RES_EXCEPTION, "TODO...", e.Exception.Message)); } private void AddCommunityCredits(Entry entry) { try { CommunityCreditNotification.AddCommunityCredits(entry, Url, Blog); } catch (CommunityCreditNotificationException ex) { Messages.ShowError(String.Format(Constants.RES_EXCEPTION, Resources.EntryEditor_ErrorSendingToCommunityCredits, ex.Message)); } catch (Exception ex) { Messages.ShowError(String.Format(Constants.RES_EXCEPTION, Resources.EntryEditor_ErrorSendingToCommunityCredits, ex.Message)); } } private Entry GetEntryForEditing(int id) { var entry = Repository.GetEntry(id, false /*activeOnly*/, false /*includeCategories*/); entry.Blog = Blog; return entry; } } }
//----------------------------------------------------------------------- // <copyright file="GraphInterpreterSpecKit.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Akka.Actor; using Akka.Event; using Akka.Streams.Implementation; using Akka.Streams.Implementation.Fusing; using Akka.Streams.Stage; using Akka.Streams.TestKit.Tests; using Xunit.Abstractions; namespace Akka.Streams.Tests.Implementation.Fusing { public class GraphInterpreterSpecKit : AkkaSpec { public GraphInterpreterSpecKit(ITestOutputHelper output = null) : base(output) { } public abstract class BaseBuilder { private GraphInterpreter _interpreter; private readonly ILoggingAdapter _logger; protected BaseBuilder(ActorSystem system) { _logger = Logging.GetLogger(system, "InterpreterSpecKit"); } public GraphInterpreter Interpreter => _interpreter; public void StepAll() { Interpreter.Execute(int.MaxValue); } public void Step() { Interpreter.Execute(1); } public class Upstream : GraphInterpreter.UpstreamBoundaryStageLogic { private readonly Outlet<int> _out; public Upstream() { _out = new Outlet<int>("up") { Id = 0 }; } public override Outlet Out => _out; } public class Downstream : GraphInterpreter.DownstreamBoundaryStageLogic { private readonly Inlet<int> _in; public Downstream() { _in = new Inlet<int>("up") { Id = 0 }; } public override Inlet In => _in; } public class AssemblyBuilder { private readonly ILoggingAdapter _logger; private readonly Action<GraphInterpreter> _interpreterSetter; private readonly IList<IGraphStageWithMaterializedValue<Shape, object>> _stages; private readonly IList<Tuple<GraphInterpreter.UpstreamBoundaryStageLogic, Inlet>> _upstreams = new List<Tuple<GraphInterpreter.UpstreamBoundaryStageLogic, Inlet>>(); private readonly IList<Tuple<Outlet, GraphInterpreter.DownstreamBoundaryStageLogic>> _downstreams = new List<Tuple<Outlet, GraphInterpreter.DownstreamBoundaryStageLogic>>(); private readonly IList<Tuple<Outlet, Inlet>> _connections = new List<Tuple<Outlet, Inlet>>(); public AssemblyBuilder(ILoggingAdapter logger, Action<GraphInterpreter> interpreterSetter, IEnumerable<IGraphStageWithMaterializedValue<Shape, object>> stages) { _logger = logger; _interpreterSetter = interpreterSetter; _stages = stages.ToArray(); } public AssemblyBuilder Connect<T>(GraphInterpreter.UpstreamBoundaryStageLogic upstream, Inlet<T> inlet) { _upstreams.Add(new Tuple<GraphInterpreter.UpstreamBoundaryStageLogic, Inlet>(upstream, inlet)); return this; } public AssemblyBuilder Connect<T>(Outlet<T> outlet, GraphInterpreter.DownstreamBoundaryStageLogic downstream) { _downstreams.Add(new Tuple<Outlet, GraphInterpreter.DownstreamBoundaryStageLogic>(outlet, downstream)); return this; } public AssemblyBuilder Connect<T>(Outlet<T> outlet, Inlet<T> inlet) { _connections.Add(new Tuple<Outlet, Inlet>(outlet, inlet)); return this; } public GraphAssembly BuildAssembly() { var ins = _upstreams.Select(u => u.Item2).Concat(_connections.Select(c => c.Item2)).ToArray(); var outs = _connections.Select(c => c.Item1).Concat(_downstreams.Select(d => d.Item1)).ToArray(); var inOwners = ins.Select( inlet => _stages.Select((s, i) => new {Stage = s, Index = i}) .First(s => s.Stage.Shape.Inlets.Contains(inlet)) .Index).ToArray(); var outOwners = outs.Select( outlet => _stages.Select((s, i) => new {Stage = s, Index = i}) .First(s => s.Stage.Shape.Outlets.Contains(outlet)) .Index); return new GraphAssembly(_stages.ToArray(), Enumerable.Repeat(Attributes.None, _stages.Count).ToArray(), ins.Concat(Enumerable.Repeat<Inlet>(null, _downstreams.Count)).ToArray(), inOwners.Concat(Enumerable.Repeat(-1, _downstreams.Count)).ToArray(), Enumerable.Repeat<Outlet>(null, _upstreams.Count).Concat(outs).ToArray(), Enumerable.Repeat(-1, _upstreams.Count).Concat(outOwners).ToArray()); } public void Init() { var assembly = BuildAssembly(); var mat = assembly.Materialize(Attributes.None, assembly.Stages.Select(s => s.Module).ToArray(), new Dictionary<IModule, object>(), s => { }); var inHandlers = mat.Item1; var outHandlers = mat.Item2; var logics = mat.Item3; var interpreter = new GraphInterpreter(assembly, NoMaterializer.Instance, _logger, inHandlers, outHandlers, logics, (l, o, a) => {}, false); var i = 0; foreach (var upstream in _upstreams) { interpreter.AttachUpstreamBoundary(i++, upstream.Item1); } i = 0; foreach (var downstream in _downstreams) { interpreter.AttachDownstreamBoundary((i++) + _upstreams.Count + _connections.Count, downstream.Item2); } interpreter.Init(null); _interpreterSetter(interpreter); } } public void ManualInit(GraphAssembly assembly) { var mat = assembly.Materialize(Attributes.None, assembly.Stages.Select(s => s.Module).ToArray(), new Dictionary<IModule, object>(), s => { }); var inHandlers = mat.Item1; var outHandlers = mat.Item2; var logics = mat.Item3; _interpreter = new GraphInterpreter(assembly, NoMaterializer.Instance, _logger, inHandlers, outHandlers, logics, (l, o, a) => {}, false); } public AssemblyBuilder Builder(params IGraphStageWithMaterializedValue<Shape, object>[] stages) { return new AssemblyBuilder(_logger, interpreter => _interpreter = interpreter, stages); } } public class BaseBuilderSetup<T> : BaseBuilder { public BaseBuilderSetup(ActorSystem system) : base(system) { } public GraphInterpreter Build(GraphInterpreter.UpstreamBoundaryStageLogic upstream, GraphStage<FlowShape<T, T>>[] ops, GraphInterpreter.DownstreamBoundaryStageLogic downstream) { var b = Builder(ops).Connect(upstream, ops[0].Shape.Inlet); for (var i = 0; i < ops.Length - 1; i++) b.Connect(ops[i].Shape.Outlet, ops[i + 1].Shape.Inlet); b.Connect(ops[ops.Length - 1].Shape.Outlet, downstream); b.Init(); return Interpreter; } } public class TestSetup : BaseBuilder { #region Test Events public interface ITestEvent { GraphStageLogic Source { get; } } public class OnComplete : ITestEvent { public GraphStageLogic Source { get; } public OnComplete(GraphStageLogic source) { Source = source; } protected bool Equals(OnComplete other) { return Equals(Source, other.Source); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != GetType()) return false; return Equals((OnComplete) obj); } public override int GetHashCode() { return Source?.GetHashCode() ?? 0; } } public class Cancel : ITestEvent { public GraphStageLogic Source { get; } public Cancel(GraphStageLogic source) { Source = source; } protected bool Equals(Cancel other) { return Equals(Source, other.Source); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != GetType()) return false; return Equals((Cancel) obj); } public override int GetHashCode() { return Source?.GetHashCode() ?? 0; } } public class OnError : ITestEvent { public GraphStageLogic Source { get; } public Exception Cause { get; } public OnError(GraphStageLogic source, Exception cause) { Source = source; Cause = cause; } protected bool Equals(OnError other) { return Equals(Source, other.Source) && Equals(Cause, other.Cause); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != GetType()) return false; return Equals((OnError) obj); } public override int GetHashCode() { unchecked { return ((Source?.GetHashCode() ?? 0)*397) ^ (Cause?.GetHashCode() ?? 0); } } } public class OnNext : ITestEvent { public GraphStageLogic Source { get; } public object Element { get; } public OnNext(GraphStageLogic source, object element) { Source = source; Element = element; } protected bool Equals(OnNext other) { return Equals(Source, other.Source) && Equals(Element, other.Element); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != GetType()) return false; return Equals((OnNext) obj); } public override int GetHashCode() { unchecked { return ((Source?.GetHashCode() ?? 0)*397) ^ (Element?.GetHashCode() ?? 0); } } } public class RequestOne : ITestEvent { public GraphStageLogic Source { get; } public RequestOne(GraphStageLogic source) { Source = source; } protected bool Equals(RequestOne other) { return Equals(Source, other.Source); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != GetType()) return false; return Equals((RequestOne) obj); } public override int GetHashCode() { return Source?.GetHashCode() ?? 0; } } public class RequestAnother : ITestEvent { public GraphStageLogic Source { get; } public RequestAnother(GraphStageLogic source) { Source = source; } protected bool Equals(RequestAnother other) { return Equals(Source, other.Source); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != GetType()) return false; return Equals((RequestAnother) obj); } public override int GetHashCode() { return Source?.GetHashCode() ?? 0; } } public class PreStart : ITestEvent { public GraphStageLogic Source { get; } public PreStart(GraphStageLogic source) { Source = source; } protected bool Equals(PreStart other) { return Equals(Source, other.Source); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != GetType()) return false; return Equals((PreStart) obj); } public override int GetHashCode() { return Source?.GetHashCode() ?? 0; } } public class PostStop : ITestEvent { public GraphStageLogic Source { get; } public PostStop(GraphStageLogic source) { Source = source; } protected bool Equals(PostStop other) { return Equals(Source, other.Source); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != GetType()) return false; return Equals((PostStop) obj); } public override int GetHashCode() { return Source?.GetHashCode() ?? 0; } } #endregion public TestSetup(ActorSystem system) : base(system) { } public ISet<ITestEvent> LastEvent = new HashSet<ITestEvent>(); public ISet<ITestEvent> LastEvents() { var result = LastEvent; ClearEvents(); return result; } public void ClearEvents() { LastEvent = new HashSet<ITestEvent>(); } public UpstreamProbe<T> NewUpstreamProbe<T>(string name) { return new UpstreamProbe<T>(this, name); } public DownstreamProbe<T> NewDownstreamProbe<T>(string name) { return new DownstreamProbe<T>(this, name); } public class UpstreamProbe<T> : GraphInterpreter.UpstreamBoundaryStageLogic { private readonly string _name; public UpstreamProbe(TestSetup setup, string name) { _name = name; Out = new Outlet<T>("out") {Id = 0}; var probe = this; SetHandler(Out, () => setup.LastEvent.Add(new RequestOne(probe)), () => setup.LastEvent.Add(new Cancel(probe))); } public sealed override Outlet Out { get; } public void OnNext(T element, int eventLimit = int.MaxValue) { if (GraphInterpreter.IsDebug) Console.WriteLine($"----- NEXT: {this} {element}"); Push(Out, element); Interpreter.Execute(eventLimit); } public void OnComplete(int eventLimit = int.MaxValue) { if (GraphInterpreter.IsDebug) Console.WriteLine($"----- COMPLETE: {this}"); Complete(Out); Interpreter.Execute(eventLimit); } public void OnFailure(int eventLimit = int.MaxValue, Exception ex = null) { if (GraphInterpreter.IsDebug) Console.WriteLine($"----- FAIL: {this}"); Fail(Out, ex); Interpreter.Execute(eventLimit); } public override string ToString() { return _name; } } public class DownstreamProbe<T> : GraphInterpreter.DownstreamBoundaryStageLogic { private readonly string _name; public DownstreamProbe(TestSetup setup, string name) { _name = name; In = new Inlet<T>("in") {Id = 0}; var probe = this; SetHandler(In, () => setup.LastEvent.Add(new OnNext(probe, Grab<T>(In))), () => setup.LastEvent.Add(new OnComplete(probe)), ex => setup.LastEvent.Add(new OnError(probe, ex))); } public sealed override Inlet In { get; } public void RequestOne(int eventLimit = int.MaxValue) { if (GraphInterpreter.IsDebug) Console.WriteLine($"----- REQ: {this}"); Pull<T>(In); Interpreter.Execute(eventLimit); } public void Cancel(int eventLimit = int.MaxValue) { if (GraphInterpreter.IsDebug) Console.WriteLine($"----- CANCEL: {this}"); Cancel(In); Interpreter.Execute(eventLimit); } public override string ToString() { return _name; } } } public class PortTestSetup : TestSetup { public UpstreamPortProbe<int> Out { get; } public DownstreamPortProbe<int> In { get; } private readonly GraphAssembly _assembly = new GraphAssembly(new IGraphStageWithMaterializedValue<Shape, object>[0], new Attributes[0], new Inlet[] {null}, new[] {-1}, new Outlet[] {null}, new[] {-1}); public PortTestSetup(ActorSystem system) : base(system) { Out = new UpstreamPortProbe<int>(this); In = new DownstreamPortProbe<int>(this); ManualInit(_assembly); Interpreter.AttachDownstreamBoundary(0, In); Interpreter.AttachUpstreamBoundary(0, Out); Interpreter.Init(null); } public class UpstreamPortProbe<T> : UpstreamProbe<T> { public UpstreamPortProbe(TestSetup setup) : base(setup, "upstreamPort") { } public bool IsAvailable() { return IsAvailable(Out); } public bool IsClosed() { return IsClosed(Out); } public void Push(T element) { Push(Out, element); } public void Complete() { Complete(Out); } public void Fail(Exception ex) { Fail(Out, ex); } } public class DownstreamPortProbe<T> : DownstreamProbe<T> { public DownstreamPortProbe(TestSetup setup) : base(setup, "downstreamPort") { var probe = this; SetHandler(In, () => { // Modified onPush that does not Grab() automatically the element. This access some internals. var internalEvent = Interpreter.ConnectionSlots[PortToConn[In.Id]]; if (internalEvent is GraphInterpreter.Failed) ((PortTestSetup) setup).LastEvent.Add(new OnNext(probe, ((GraphInterpreter.Failed) internalEvent).PreviousElement)); else ((PortTestSetup) setup).LastEvent.Add(new OnNext(probe, internalEvent)); }, () => ((PortTestSetup) setup).LastEvent.Add(new OnComplete(probe)), ex => ((PortTestSetup) setup).LastEvent.Add(new OnError(probe, ex)) ); } public bool IsAvailable() { return IsAvailable(In); } public bool HasBeenPulled() { return HasBeenPulled(In); } public bool IsClosed() { return IsClosed(In); } public void Pull() { Pull<T>(In); } public void Cancel() { Cancel(In); } public T Grab() { return Grab<T>(In); } } } public class FailingStageSetup : TestSetup { public UpstreamPortProbe<int> Upstream { get; } public DownstreamPortProbe<int> Downstream { get; } private bool _failOnNextEvent; private bool _failOnPostStop; private readonly Inlet<int> _stageIn; private readonly Outlet<int> _stageOut; private readonly FlowShape<int, int> _stageShape; // Must be lazy because I turned this stage "inside-out" therefore changin initialization order // to make tests a bit more readable public Lazy<GraphStageLogic> Stage { get; } public FailingStageSetup(ActorSystem system, bool initFailOnNextEvent = false) : base(system) { Upstream = new UpstreamPortProbe<int>(this); Downstream = new DownstreamPortProbe<int>(this); _failOnNextEvent = initFailOnNextEvent; _failOnPostStop = false; _stageIn = new Inlet<int>("sandwitch.in"); _stageOut = new Outlet<int>("sandwitch.out"); _stageShape = new FlowShape<int, int>(_stageIn, _stageOut); Stage = new Lazy<GraphStageLogic>(() => new FailingGraphStageLogic(this, _stageShape)); GraphStage<FlowShape<int, int>> sandwitchStage = new SandwitchStage(this); Builder(sandwitchStage) .Connect(Upstream, _stageIn) .Connect(_stageOut, Downstream) .Init(); } public void FailOnNextEvent() { _failOnNextEvent = true; } public void FailOnPostStop() { _failOnPostStop = true; } public Exception TestException() { return new TestException("test"); } public class FailingGraphStageLogic : GraphStageLogic { private readonly FailingStageSetup _setup; public FailingGraphStageLogic(FailingStageSetup setup, Shape shape) : base(shape) { _setup = setup; SetHandler(setup._stageIn, () => MayFail(() => Push(setup._stageOut, Grab(setup._stageIn))), () => MayFail(CompleteStage), ex => MayFail(() => FailStage(ex))); SetHandler(setup._stageOut, () => MayFail(() => Pull(setup._stageIn)), () => MayFail(CompleteStage)); } private void MayFail(Action task) { if (!_setup._failOnNextEvent) task(); else { _setup._failOnNextEvent = false; throw _setup.TestException(); } } public override void PreStart() { MayFail(() => _setup.LastEvent.Add(new PreStart(this))); } public override void PostStop() { if (!_setup._failOnPostStop) _setup.LastEvent.Add(new PostStop(this)); else throw _setup.TestException(); } public override string ToString() { return "stage"; } } public class SandwitchStage : GraphStage<FlowShape<int, int>> { private readonly FailingStageSetup _setup; public SandwitchStage(FailingStageSetup setup) { _setup = setup; } public override FlowShape<int, int> Shape => _setup._stageShape; protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) { return _setup.Stage.Value; } public override string ToString() { return "stage"; } } public class UpstreamPortProbe<T> : UpstreamProbe<T> { public UpstreamPortProbe(TestSetup setup) : base(setup, "upstreamPort") { } public void Push(T element) { Push(Out, element); } public void Complete() { Complete(Out); } public void Fail(Exception ex) { Fail(Out, ex); } } public class DownstreamPortProbe<T> : DownstreamProbe<T> { public DownstreamPortProbe(TestSetup setup) : base(setup, "downstreamPort") { } public void Pull() { Pull<T>(In); } public void Cancel() { Cancel(In); } } } public abstract class OneBoundedSetup : BaseBuilder { #region Test Events public interface ITestEvent { } public class OnComplete : ITestEvent { protected bool Equals(OnComplete other) { return true; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != typeof (OnComplete)) return false; return Equals((OnComplete) obj); } public override int GetHashCode() { return 0; } } public class Cancel : ITestEvent { protected bool Equals(Cancel other) { return true; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != typeof (Cancel)) return false; return Equals((Cancel) obj); } public override int GetHashCode() { return 0; } } public class OnError : ITestEvent { public Exception Cause { get; } public OnError(Exception cause) { Cause = cause; } protected bool Equals(OnError other) { return Equals(Cause, other.Cause); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != GetType()) return false; return Equals((OnError) obj); } public override int GetHashCode() { return Cause?.GetHashCode() ?? 0; } } public class OnNext : ITestEvent { public object Element { get; } public OnNext(object element) { Element = element; } protected bool Equals(OnNext other) { return Element is IEnumerable ? ((IEnumerable) Element).Cast<object>().SequenceEqual(((IEnumerable) other.Element).Cast<object>()) : Equals(Element, other.Element); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != GetType()) return false; return Equals((OnNext) obj); } public override int GetHashCode() { return Element?.GetHashCode() ?? 0; } } public class RequestOne : ITestEvent { protected bool Equals(RequestOne other) { return true; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != typeof (RequestOne)) return false; return Equals((RequestOne) obj); } public override int GetHashCode() { return 0; } } public class RequestAnother : ITestEvent { protected bool Equals(RequestAnother other) { return true; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != typeof (RequestAnother)) return false; return Equals((RequestAnother) obj); } public override int GetHashCode() { return 0; } } #endregion protected OneBoundedSetup(ActorSystem system) : base(system) { } protected ISet<ITestEvent> LastEvent { get; private set; } = new HashSet<ITestEvent>(); public ISet<ITestEvent> LastEvents() { var events = LastEvent; LastEvent = new HashSet<ITestEvent>(); return events; } protected abstract void Run(); public class UpstreamOneBoundedProbe<T> : GraphInterpreter.UpstreamBoundaryStageLogic { private readonly OneBoundedSetup _setup; public UpstreamOneBoundedProbe(OneBoundedSetup setup) { _setup = setup; Out = new Outlet<T>("out") {Id = 0}; SetHandler(Out, () => { if (setup.LastEvent.OfType<RequestOne>().Any()) setup.LastEvent.Add(new RequestAnother()); else setup.LastEvent.Add(new RequestOne()); }, () => setup.LastEvent.Add(new Cancel())); } public override Outlet Out { get; } public void OnNext(T element) { Push(Out, element); _setup.Run(); } public void OnComplete() { Complete(Out); _setup.Run(); } public void OnNextAndComplete(T element) { Push(Out, element); Complete(Out); _setup.Run(); } public void OnError(Exception ex) { Fail(Out, ex); _setup.Run(); } } public class DownstreamOneBoundedPortProbe<T> : GraphInterpreter.DownstreamBoundaryStageLogic { private readonly OneBoundedSetup _setup; public DownstreamOneBoundedPortProbe(OneBoundedSetup setup) { _setup = setup; In = new Inlet<T>("in") {Id = 0}; SetHandler(In, () => { setup.LastEvent.Add(new OnNext(Grab<object>(In))); }, () => setup.LastEvent.Add(new OnComplete()), ex => setup.LastEvent.Add(new OnError(ex))); } public override Inlet In { get; } public void RequestOne() { Pull<T>(In); _setup.Run(); } public void Cancel() { Cancel(In); _setup.Run(); } } } public class OneBoundedSetup<TIn, TOut> : OneBoundedSetup { public OneBoundedSetup(ActorSystem system, params IGraphStageWithMaterializedValue<Shape, object>[] ops) : base(system) { Ops = ops; Upstream = new UpstreamOneBoundedProbe<TIn>(this); Downstream = new DownstreamOneBoundedPortProbe<TOut>(this); Initialize(); Run(); // Detached stages need the prefetch } public IGraphStageWithMaterializedValue<Shape, object>[] Ops { get; } public new UpstreamOneBoundedProbe<TIn> Upstream { get; } public new DownstreamOneBoundedPortProbe<TOut> Downstream { get; } protected sealed override void Run() { Interpreter.Execute(int.MaxValue); } private void Initialize() { var attributes = Enumerable.Repeat(Attributes.None, Ops.Length).ToArray(); var ins = new Inlet[Ops.Length + 1]; var inOwners = new int[Ops.Length + 1]; var outs = new Outlet[Ops.Length + 1]; var outOwners = new int[Ops.Length + 1]; ins[Ops.Length] = null; inOwners[Ops.Length] = GraphInterpreter.Boundary; outs[0] = null; outOwners[0] = GraphInterpreter.Boundary; for (int i = 0; i < Ops.Length; i++) { var shape = (IFlowShape) Ops[i].Shape; ins[i] = shape.Inlet; inOwners[i] = i; outs[i + 1] = shape.Outlet; outOwners[i + 1] = i; } ManualInit(new GraphAssembly(Ops, attributes, ins, inOwners, outs, outOwners)); Interpreter.AttachUpstreamBoundary(0, Upstream); Interpreter.AttachDownstreamBoundary(Ops.Length, Downstream); Interpreter.Init(null); } } public class OneBoundedSetup<T> : OneBoundedSetup<T, T> { public OneBoundedSetup(ActorSystem system, params IGraphStageWithMaterializedValue<Shape, object>[] ops) : base(system, ops) { } } public PushPullGraphStage<TIn, TOut> ToGraphStage<TIn, TOut>(IStage<TIn, TOut> stage) { var s = stage; return new PushPullGraphStage<TIn, TOut>(_ => s, Attributes.None); } public IGraphStageWithMaterializedValue<Shape, object>[] ToGraphStage<TIn, TOut>(IStage<TIn, TOut>[] stages) { return stages.Select(ToGraphStage).Cast<IGraphStageWithMaterializedValue<Shape, object>>().ToArray(); } public void WithTestSetup(Action<TestSetup, Func<ISet<TestSetup.ITestEvent>>> spec) { var setup = new TestSetup(Sys); spec(setup, setup.LastEvents); } public void WithTestSetup( Action <TestSetup, Func<IGraphStageWithMaterializedValue<Shape, object>, BaseBuilder.AssemblyBuilder>, Func<ISet<TestSetup.ITestEvent>>> spec) { var setup = new TestSetup(Sys); spec(setup, g => setup.Builder(g), setup.LastEvents); } public void WithTestSetup( Action <TestSetup, Func<IGraphStageWithMaterializedValue<Shape, object>[], BaseBuilder.AssemblyBuilder>, Func<ISet<TestSetup.ITestEvent>>> spec) { var setup = new TestSetup(Sys); spec(setup, setup.Builder, setup.LastEvents); } public void WithOneBoundedSetup<T>(IStage<T, T> op, Action <Func<ISet<OneBoundedSetup.ITestEvent>>, OneBoundedSetup.UpstreamOneBoundedProbe<T>, OneBoundedSetup.DownstreamOneBoundedPortProbe<T>> spec) { WithOneBoundedSetup<T>(ToGraphStage(op), spec); } public void WithOneBoundedSetup<T>(IStage<T, T>[] ops, Action <Func<ISet<OneBoundedSetup.ITestEvent>>, OneBoundedSetup.UpstreamOneBoundedProbe<T>, OneBoundedSetup.DownstreamOneBoundedPortProbe<T>> spec) { WithOneBoundedSetup<T>(ToGraphStage(ops), spec); } public void WithOneBoundedSetup<T>(IGraphStageWithMaterializedValue<Shape, object> op, Action <Func<ISet<OneBoundedSetup.ITestEvent>>, OneBoundedSetup.UpstreamOneBoundedProbe<T>, OneBoundedSetup.DownstreamOneBoundedPortProbe<T>> spec) { WithOneBoundedSetup<T>(new[] {op}, spec); } public void WithOneBoundedSetup<T>(IGraphStageWithMaterializedValue<Shape, object>[] ops, Action <Func<ISet<OneBoundedSetup.ITestEvent>>, OneBoundedSetup.UpstreamOneBoundedProbe<T>, OneBoundedSetup.DownstreamOneBoundedPortProbe<T>> spec) { var setup = new OneBoundedSetup<T>(Sys, ops); spec(setup.LastEvents, setup.Upstream, setup.Downstream); } public void WithOneBoundedSetup<TIn, TOut>(IGraphStageWithMaterializedValue<Shape, object> op, Action <Func<ISet<OneBoundedSetup.ITestEvent>>, OneBoundedSetup.UpstreamOneBoundedProbe<TIn>, OneBoundedSetup.DownstreamOneBoundedPortProbe<TOut>> spec) { WithOneBoundedSetup(new[] {op}, spec); } public void WithOneBoundedSetup<TIn, TOut>(IGraphStageWithMaterializedValue<Shape, object>[] ops, Action <Func<ISet<OneBoundedSetup.ITestEvent>>, OneBoundedSetup.UpstreamOneBoundedProbe<TIn>, OneBoundedSetup.DownstreamOneBoundedPortProbe<TOut>> spec) { var setup = new OneBoundedSetup<TIn, TOut>(Sys, ops); spec(setup.LastEvents, setup.Upstream, setup.Downstream); } public void WithBaseBuilderSetup<T>(GraphStage<FlowShape<T, T>>[] ops, Action<GraphInterpreter> spec) { var interpreter = new BaseBuilderSetup<T>(Sys).Build(new BaseBuilder.Upstream(), ops, new BaseBuilder.Downstream()); spec(interpreter); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using VersionOne.SDK.ObjectModel.Filters; using VersionOne.SDK.ObjectModel.List; namespace VersionOne.SDK.ObjectModel { /// <summary> /// Abstract representation of entities in the VersionOne system /// </summary> public abstract class Entity { /// <summary> /// V1Instance this entity belongs to /// </summary> protected V1Instance Instance { get { return instance; } } private readonly V1Instance instance; /// <summary> /// Constructor used to represent an entity that does exist in the VersionOne System /// </summary> /// <param name="id">Unique ID of this entity</param> /// <param name="instance">Instance this entity belongs to</param> internal Entity(AssetID id, V1Instance instance) { assetID = id; this.instance = instance; } /// <summary> /// Constructor used to represent an entity that does not exist yet in the VersionOne System /// </summary> internal Entity(V1Instance instance) { stubAssetID = new StubAssetID(); this.instance = instance; } /// <summary> /// Unique ID of this entity /// </summary> public AssetID ID { get { return assetID; } } private AssetID assetID; private StubAssetID stubAssetID; internal object InstanceKey { get { return assetID ?? (object) stubAssetID; } } #region Common Attributes /// <summary> /// Date this entity was last changed in UTC /// </summary> public DateTime ChangeDate { get { var date = Get<DateTime>("ChangeDateUTC", false); date = new DateTime(date.Ticks, DateTimeKind.Utc); return date.ToLocalTime(); } } /// <summary> /// Comment entered when this entity was last updated /// </summary> public string ChangeComment { get { return Get<string>("ChangeComment", false); } } /// <summary> /// Member or user that last changed this entity /// </summary> public Member ChangedBy { get { return GetRelation<Member>("ChangedBy", false); } } /// <summary> /// Date this entity was created in UTC /// </summary> public DateTime CreateDate { get { var date = Get<DateTime>("CreateDateUTC", true); date = new DateTime(date.Ticks, DateTimeKind.Utc); return date.ToLocalTime(); } } /// <summary> /// Comment entered when this entity was created /// </summary> public string CreateComment { get { return Get<string>("CreateComment", true); } } /// <summary> /// Member or user that created this entity /// </summary> public Member CreatedBy { get { return GetRelation<Member>("CreatedBy", true); } } #endregion internal string GetEntityURL() { return instance.GetEntityURL(this); } /// <summary> /// Gets a simple value by name for this entity /// </summary> /// <typeparam name="T">The type of the attribute.</typeparam> /// <param name="name">Name of the attribute.</param> /// <returns>An attribute value.</returns> internal T Get<T>(string name) { return instance.GetProperty<T>(this, name, true); } /// <summary> /// Gets a simple value by name for this entity. Ignore cache if cachable is false /// </summary> /// <typeparam name="T">The type of the attribute.</typeparam> /// <param name="name">Name of the attribute.</param> /// <param name="cachable">False if the attribute should not be cached.</param> /// <returns>An attribute value.</returns> internal T Get<T>(string name, bool cachable) { return instance.GetProperty<T>(this, name, cachable); } /// <summary> /// Sets a simple value by name for this entity /// </summary> /// <typeparam name="T">The type of the attribute.</typeparam> /// <param name="name">Name of the attribute.</param> /// <param name="value">The value to set the attribute to.</param> internal void Set<T>(string name, T value) { instance.SetProperty(this, name, value); } /// <summary> /// Clears a cached property value. /// </summary> /// <param name="name">Name of the property; /// if null, all properties will be cleared from cache.</param> internal void ClearCache(string name) { instance.ClearCache(this, name); } /// <summary> /// Get a total of an attribute thru a multi-relation possibly slicing by a filter /// </summary> /// <param name="multiRelationName"></param> /// <param name="filter"></param> /// <param name="numericAttributeName"></param> /// <returns></returns> internal double? GetSum(string multiRelationName, EntityFilter filter, string numericAttributeName) { return instance.GetSum(this, multiRelationName, filter, numericAttributeName); } /// <summary> /// Get a read-only attachment stream for this entity. /// </summary> /// <returns></returns> internal Stream GetReadStream() { return instance.GetReadStream(this); } /// <summary> /// Gets a write-enabled attachment stream for this entity. /// </summary> /// <returns></returns> internal Stream GetWriteStream() { return instance.GetWriteStream(this); } /// <summary> /// Complete saving a write-enabled attachment stream for this entity. /// </summary> internal void CommitWriteStream(string contentType) { instance.CommitWriteStream(this, contentType); } /// <summary> /// Get Rank attribute for this Entity. /// </summary> /// <typeparam name="T">My type.</typeparam> /// <param name="attributeName">Name of the Rank attribute.</param> /// <returns>A Rank object.</returns> internal Rank<T> GetRank<T>(string attributeName) where T : Entity { return instance.GetRank<T>(this, attributeName); } /// <summary> /// Get a relation by name for this entity /// </summary> /// <typeparam name="T">The type of the related asset.</typeparam> /// <param name="name">Name of the relation attribute.</param> /// <returns>The related asset.</returns> internal T GetRelation<T>(string name) where T : Entity { return GetRelation<T>(name, true); } /// <summary> /// Get a relation by name for this entity. Ignore cache if cachable is false /// </summary> /// <typeparam name="T">The type of the related asset.</typeparam> /// <param name="name">Name of the relation attribute.</param> /// <param name="cachable">False if should not be cached.</param> /// <returns>The related asset.</returns> internal T GetRelation<T>(string name, bool cachable) where T : Entity { return instance.GetRelation<T>(this, name, cachable); } /// <summary> /// Sets a relation by name for this entity /// </summary> /// <typeparam name="T">The type of the related asset.</typeparam> /// <param name="name">Name of the relation attribute.</param> /// <param name="value">What to set the relation attribute to.</param> internal void SetRelation<T>(string name, T value) where T : Entity { instance.SetRelation(this, name, value); } /// <summary> /// Get a multi-value relation by name for this entity /// </summary> /// <typeparam name="T">The type of the related asset.</typeparam> /// <param name="name">Name of the relation attribute.</param> /// <returns>IEntityCollection of T</returns> internal EntityCollection<T> GetMultiRelation<T>(string name) where T : Entity { return GetMultiRelation<T>(name, true); } /// <summary> /// Get a multi-value relation by name for this entity. Ignore cache if cachable is false /// </summary> /// <typeparam name="T">The type of the related asset.</typeparam> /// <param name="name">Name of the relation attribute.</param> /// <param name="cachable">False if should not be cached.</param> /// <returns>IEntityCollection of T</returns> internal EntityCollection<T> GetMultiRelation<T>(string name, bool cachable) where T : Entity { return instance.GetMultiRelation<T>(this, name, cachable); } /// <summary> /// Save any changes to this entity to the VersionOne System with a comment /// </summary> /// <exception cref="DataException">Thrown when a rule or security violation has occurred.</exception> public void Save(string comment) { assetID = instance.Commit(this, comment); stubAssetID = null; } /// <summary> /// Save any changes to this entity to the VersionOne System /// </summary> /// /// <exception cref="DataException">Thrown when a rule or security violation has occurred.</exception> public void Save() { Save(null); } #region Object overrides /// <summary> /// Override Equals /// </summary> /// <param name="obj"></param> /// <returns></returns> public override bool Equals(object obj) { Entity other = obj as Entity; if (other == null) return false; if (ReferenceEquals(this, other)) return true; return assetID == other.assetID && stubAssetID == other.stubAssetID; } /// <summary> /// Override Equals /// </summary> /// <returns></returns> public override int GetHashCode() { return InstanceKey.GetHashCode(); } /// <summary> /// Returns the AssetID token for the Entity. /// </summary> /// <returns>AssetID token for the Entity</returns> public override string ToString() { return ID.ToString(); } /// <summary> /// Overload equal equal operator /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns></returns> public static bool operator ==(Entity a, Entity b) { if(ReferenceEquals(a, null) || ReferenceEquals(b, null)) { return ReferenceEquals(a, null) && ReferenceEquals(b, null); } return a.Equals(b); } /// <summary> /// Overload not equal operator /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns></returns> public static bool operator !=(Entity a, Entity b) { return !(a == b); } #endregion internal T GetListRelation<T>(string name) where T : ListValue { return GetRelation<T>(name, true); } /// <summary> /// Sets a List relation by name. /// </summary> /// <typeparam name="T">The Entity Type that represents the List Type</typeparam> /// <param name="attributeName">The name of the Relation Attribute</param> /// <param name="value">The name of the List value to be set in the relation</param> internal void SetListRelation<T>(string attributeName, string value) where T : ListValue { Instance.SetListRelation<T>(this, attributeName, value); } /// <summary> /// Gets the value of a Relation to a Custom List Type /// </summary> /// <param name="attributeName">The name of the relation attribute</param> /// <returns>A <see cref="CustomListValue"/> representing the related Custom List Type, or null.</returns> internal CustomListValue GetCustomListValue(string attributeName) { return Instance.GetCustomRelation(this, attributeName); } internal void SetCustomListRelation(string name, string value) { Instance.SetCustomListRelation(this, name, value); } internal bool ContainsAttribute(string attributeName) { return instance.AttributeExists(this, attributeName); } #region Nested Custom Attribute Intrastructure Classes internal class SimpleCustomAttributeDictionary : ICustomAttributeDictionary { private readonly Entity entity; public SimpleCustomAttributeDictionary(Entity entity) { this.entity = entity; } public object this[string attributeName] { get { return entity.Get<object>("Custom_" + attributeName); } set { entity.Set("Custom_" + attributeName, value); } } public double? GetNumeric(string attributeName) { return (double?) this[attributeName]; } public bool? GetBool(string attributeName) { return (bool) this[attributeName]; } public DateTime? GetDate(string attributeName) { return (DateTime) this[attributeName]; } public string GetString(string attributeName) { return (string) this[attributeName]; } public bool ContainsKey(string attributeName) { return entity.ContainsAttribute("Custom_" + attributeName); } } internal class ListCustomAttributeDictionary : ICustomDropdownDictionary { private readonly Entity entity; public ListCustomAttributeDictionary(Entity entity) { this.entity = entity; } public IListValueProperty this[string attributeName] { get { return new CustomListValueProperty(entity, attributeName); } } public bool ContainsKey(string attributeName) { return entity.ContainsAttribute("Custom_" + attributeName); } } #endregion #region List Relation Infrastructure internal IEnumerable<T> GetListTypeValues<T>() where T : ListValue { return Instance.Get.ListTypeValues<T>(); } internal abstract class BaseListValueProperty<T> : IListValueProperty where T : ListValue { protected readonly Entity entity; protected readonly string attributeName; public override string ToString() { return CurrentValue; } internal BaseListValueProperty(Entity entity, string attributeName) { this.entity = entity; this.attributeName = attributeName; } public abstract string CurrentValue { get; set; } public string[] AllValues { get { return Items.Select(value => value.Name).ToArray(); } } protected abstract IEnumerable<T> Items { get; } public bool IsValid(string value) { return value == null || Items.Any(item => item.Name == value); } public abstract void ClearCurrentValue(); } internal class ListValueProperty<T> : BaseListValueProperty<T> where T : ListValue { internal ListValueProperty(Entity entity, string attributeName) : base(entity, attributeName) {} public override string CurrentValue { get { var value = SelectedValue; return value != null ? value.ToString() : null; } set { entity.SetListRelation<T>(attributeName, value); } } public IEnumerable<T> GetValues() { return entity.GetListTypeValues<T>(); } protected override IEnumerable<T> Items { get { return GetValues(); } } private T SelectedValue { get { return entity.GetListRelation<T>(attributeName); } } public override void ClearCurrentValue() { entity.SetRelation<T>(attributeName, null); } } internal class CustomListValueProperty : BaseListValueProperty<CustomListValue> { public CustomListValueProperty(Entity entity, string attributeName) : base(entity, "Custom_" + attributeName) { } public override string CurrentValue { get { var value = entity.GetCustomListValue(attributeName); return value != null ? value.Name : null; } set { entity.SetCustomListRelation(attributeName, value); } } public IEnumerable<CustomListValue> GetValues() { return entity.GetCustomListTypeValues(attributeName); } protected override IEnumerable<CustomListValue> Items { get { return GetValues(); } } public override void ClearCurrentValue() { entity.SetRelation<CustomListValue>(attributeName, null); } } #endregion /// <summary> /// Rank this entity above other entity. /// </summary> /// <param name="other"></param> /// <param name="attributeName"></param> internal void RankAbove(Entity other, string attributeName) { Instance.RankAbove(this, other, attributeName); } /// <summary> /// Rank this entity below other entity. /// </summary> /// <param name="other"></param> /// <param name="attributeName"></param> internal void RankBelow(Entity other, string attributeName) { Instance.RankBelow(this, other, attributeName); } /// <summary> /// Get a list value for this entity by name /// </summary> /// <typeparam name="T"></typeparam> /// <param name="name"></param> /// <returns></returns> internal IListValueProperty GetListValue<T>(string name) where T : ListValue { return new ListValueProperty<T>(this, name); } /// <summary> /// Gets a list of possible Custom List Type values for a relationship attribute /// </summary> /// <param name="attributeName">The "friendly" name of the attribute.</param> /// <returns></returns> internal IEnumerable<CustomListValue> GetCustomListTypeValues(string attributeName) { return Instance.GetCustomListTypeValues(this, attributeName); } } }
#region Copyright notice and license // Copyright 2015 gRPC authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Threading; using System.Threading.Tasks; using Grpc.Core.Logging; using Grpc.Core.Profiling; using Grpc.Core.Utils; namespace Grpc.Core.Internal { /// <summary> /// Manages client side native call lifecycle. /// </summary> internal class AsyncCall<TRequest, TResponse> : AsyncCallBase<TRequest, TResponse>, IUnaryResponseClientCallback, IReceivedStatusOnClientCallback, IReceivedResponseHeadersCallback { static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<AsyncCall<TRequest, TResponse>>(); readonly CallInvocationDetails<TRequest, TResponse> details; readonly INativeCall injectedNativeCall; // for testing bool registeredWithChannel; // Dispose of to de-register cancellation token registration CancellationTokenRegistration cancellationTokenRegistration; // Completion of a pending unary response if not null. TaskCompletionSource<TResponse> unaryResponseTcs; // Completion of a streaming response call if not null. TaskCompletionSource<object> streamingResponseCallFinishedTcs; // TODO(jtattermusch): this field could be lazy-initialized (only if someone requests the response headers). // Response headers set here once received. TaskCompletionSource<Metadata> responseHeadersTcs = new TaskCompletionSource<Metadata>(); // Set after status is received. Used for both unary and streaming response calls. ClientSideStatus? finishedStatus; public AsyncCall(CallInvocationDetails<TRequest, TResponse> callDetails) : base(callDetails.RequestMarshaller.ContextualSerializer, callDetails.ResponseMarshaller.ContextualDeserializer) { this.details = callDetails.WithOptions(callDetails.Options.Normalize()); this.initialMetadataSent = true; // we always send metadata at the very beginning of the call. } /// <summary> /// This constructor should only be used for testing. /// </summary> public AsyncCall(CallInvocationDetails<TRequest, TResponse> callDetails, INativeCall injectedNativeCall) : this(callDetails) { this.injectedNativeCall = injectedNativeCall; } // TODO: this method is not Async, so it shouldn't be in AsyncCall class, but // it is reusing fair amount of code in this class, so we are leaving it here. /// <summary> /// Blocking unary request - unary response call. /// </summary> public TResponse UnaryCall(TRequest msg) { var profiler = Profilers.ForCurrentThread(); using (profiler.NewScope("AsyncCall.UnaryCall")) using (CompletionQueueSafeHandle cq = CompletionQueueSafeHandle.CreateSync()) { bool callStartedOk = false; try { unaryResponseTcs = new TaskCompletionSource<TResponse>(); lock (myLock) { GrpcPreconditions.CheckState(!started); started = true; Initialize(cq); halfcloseRequested = true; readingDone = true; } using (var serializationScope = DefaultSerializationContext.GetInitializedThreadLocalScope()) using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers)) { var payload = UnsafeSerialize(msg, serializationScope.Context); // do before metadata array? var ctx = details.Channel.Environment.BatchContextPool.Lease(); try { call.StartUnary(ctx, payload, GetWriteFlagsForCall(), metadataArray, details.Options.Flags); callStartedOk = true; var ev = cq.Pluck(ctx.Handle); bool success = (ev.success != 0); try { using (profiler.NewScope("AsyncCall.UnaryCall.HandleBatch")) { HandleUnaryResponse(success, ctx.GetReceivedStatusOnClient(), ctx.GetReceivedMessageReader(), ctx.GetReceivedInitialMetadata()); } } catch (Exception e) { Logger.Error(e, "Exception occurred while invoking completion delegate."); } } finally { ctx.Recycle(); } } } finally { if (!callStartedOk) { lock (myLock) { OnFailedToStartCallLocked(); } } } // Once the blocking call returns, the result should be available synchronously. // Note that GetAwaiter().GetResult() doesn't wrap exceptions in AggregateException. return unaryResponseTcs.Task.GetAwaiter().GetResult(); } } /// <summary> /// Starts a unary request - unary response call. /// </summary> public Task<TResponse> UnaryCallAsync(TRequest msg) { lock (myLock) { bool callStartedOk = false; try { GrpcPreconditions.CheckState(!started); started = true; Initialize(details.Channel.CompletionQueue); halfcloseRequested = true; readingDone = true; using (var serializationScope = DefaultSerializationContext.GetInitializedThreadLocalScope()) { var payload = UnsafeSerialize(msg, serializationScope.Context); unaryResponseTcs = new TaskCompletionSource<TResponse>(); using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers)) { call.StartUnary(UnaryResponseClientCallback, payload, GetWriteFlagsForCall(), metadataArray, details.Options.Flags); callStartedOk = true; } } return unaryResponseTcs.Task; } finally { if (!callStartedOk) { OnFailedToStartCallLocked(); } } } } /// <summary> /// Starts a streamed request - unary response call. /// Use StartSendMessage and StartSendCloseFromClient to stream requests. /// </summary> public Task<TResponse> ClientStreamingCallAsync() { lock (myLock) { bool callStartedOk = false; try { GrpcPreconditions.CheckState(!started); started = true; Initialize(details.Channel.CompletionQueue); readingDone = true; unaryResponseTcs = new TaskCompletionSource<TResponse>(); using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers)) { call.StartClientStreaming(UnaryResponseClientCallback, metadataArray, details.Options.Flags); callStartedOk = true; } return unaryResponseTcs.Task; } finally { if (!callStartedOk) { OnFailedToStartCallLocked(); } } } } /// <summary> /// Starts a unary request - streamed response call. /// </summary> public void StartServerStreamingCall(TRequest msg) { lock (myLock) { bool callStartedOk = false; try { GrpcPreconditions.CheckState(!started); started = true; Initialize(details.Channel.CompletionQueue); halfcloseRequested = true; receiveResponseHeadersPending = true; using (var serializationScope = DefaultSerializationContext.GetInitializedThreadLocalScope()) { var payload = UnsafeSerialize(msg, serializationScope.Context); streamingResponseCallFinishedTcs = new TaskCompletionSource<object>(); using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers)) { call.StartServerStreaming(ReceivedStatusOnClientCallback, payload, GetWriteFlagsForCall(), metadataArray, details.Options.Flags); callStartedOk = true; } } call.StartReceiveInitialMetadata(ReceivedResponseHeadersCallback); } finally { if (!callStartedOk) { OnFailedToStartCallLocked(); } } } } /// <summary> /// Starts a streaming request - streaming response call. /// Use StartSendMessage and StartSendCloseFromClient to stream requests. /// </summary> public void StartDuplexStreamingCall() { lock (myLock) { bool callStartedOk = false; try { GrpcPreconditions.CheckState(!started); started = true; receiveResponseHeadersPending = true; Initialize(details.Channel.CompletionQueue); streamingResponseCallFinishedTcs = new TaskCompletionSource<object>(); using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers)) { call.StartDuplexStreaming(ReceivedStatusOnClientCallback, metadataArray, details.Options.Flags); callStartedOk = true; } call.StartReceiveInitialMetadata(ReceivedResponseHeadersCallback); } finally { if (!callStartedOk) { OnFailedToStartCallLocked(); } } } } /// <summary> /// Sends a streaming request. Only one pending send action is allowed at any given time. /// </summary> public Task SendMessageAsync(TRequest msg, WriteFlags writeFlags) { return SendMessageInternalAsync(msg, writeFlags); } /// <summary> /// Receives a streaming response. Only one pending read action is allowed at any given time. /// </summary> public Task<TResponse> ReadMessageAsync() { return ReadMessageInternalAsync(); } /// <summary> /// Sends halfclose, indicating client is done with streaming requests. /// Only one pending send action is allowed at any given time. /// </summary> public Task SendCloseFromClientAsync() { lock (myLock) { GrpcPreconditions.CheckState(started); var earlyResult = CheckSendPreconditionsClientSide(); if (earlyResult != null) { return earlyResult; } if (disposed || finished) { // In case the call has already been finished by the serverside, // the halfclose has already been done implicitly, so just return // completed task here. halfcloseRequested = true; return TaskUtils.CompletedTask; } call.StartSendCloseFromClient(SendCompletionCallback); halfcloseRequested = true; streamingWriteTcs = new TaskCompletionSource<object>(); return streamingWriteTcs.Task; } } /// <summary> /// Get the task that completes once if streaming response call finishes with ok status and throws RpcException with given status otherwise. /// </summary> public Task StreamingResponseCallFinishedTask { get { return streamingResponseCallFinishedTcs.Task; } } /// <summary> /// Get the task that completes once response headers are received. /// </summary> public Task<Metadata> ResponseHeadersAsync { get { return responseHeadersTcs.Task; } } /// <summary> /// Gets the resulting status if the call has already finished. /// Throws InvalidOperationException otherwise. /// </summary> public Status GetStatus() { lock (myLock) { GrpcPreconditions.CheckState(finishedStatus.HasValue, "Status can only be accessed once the call has finished."); return finishedStatus.Value.Status; } } /// <summary> /// Gets the trailing metadata if the call has already finished. /// Throws InvalidOperationException otherwise. /// </summary> public Metadata GetTrailers() { lock (myLock) { GrpcPreconditions.CheckState(finishedStatus.HasValue, "Trailers can only be accessed once the call has finished."); return finishedStatus.Value.Trailers; } } public CallInvocationDetails<TRequest, TResponse> Details { get { return this.details; } } protected override void OnAfterReleaseResourcesLocked() { if (registeredWithChannel) { details.Channel.RemoveCallReference(this); registeredWithChannel = false; } } protected override void OnAfterReleaseResourcesUnlocked() { // If cancellation callback is in progress, this can block // so we need to do this outside of call's lock to prevent // deadlock. // See https://github.com/grpc/grpc/issues/14777 // See https://github.com/dotnet/corefx/issues/14903 cancellationTokenRegistration.Dispose(); } protected override bool IsClient { get { return true; } } protected override Exception GetRpcExceptionClientOnly() { return new RpcException(finishedStatus.Value.Status, finishedStatus.Value.Trailers); } protected override Task CheckSendAllowedOrEarlyResult() { var earlyResult = CheckSendPreconditionsClientSide(); if (earlyResult != null) { return earlyResult; } if (finishedStatus.HasValue) { // throwing RpcException if we already received status on client // side makes the most sense. // Note that this throws even for StatusCode.OK. // Writing after the call has finished is not a programming error because server can close // the call anytime, so don't throw directly, but let the write task finish with an error. var tcs = new TaskCompletionSource<object>(); tcs.SetException(new RpcException(finishedStatus.Value.Status, finishedStatus.Value.Trailers)); return tcs.Task; } return null; } private Task CheckSendPreconditionsClientSide() { GrpcPreconditions.CheckState(!halfcloseRequested, "Request stream has already been completed."); GrpcPreconditions.CheckState(streamingWriteTcs == null, "Only one write can be pending at a time."); if (cancelRequested) { // Return a cancelled task. var tcs = new TaskCompletionSource<object>(); tcs.SetCanceled(); return tcs.Task; } return null; } private void Initialize(CompletionQueueSafeHandle cq) { var call = CreateNativeCall(cq); details.Channel.AddCallReference(this); registeredWithChannel = true; InitializeInternal(call); RegisterCancellationCallback(); } private void OnFailedToStartCallLocked() { ReleaseResources(); // We need to execute the hook that disposes the cancellation token // registration, but it cannot be done from under a lock. // To make things simple, we just schedule the unregistering // on a threadpool. // - Once the native call is disposed, the Cancel() calls are ignored anyway // - We don't care about the overhead as OnFailedToStartCallLocked() only happens // when something goes very bad when initializing a call and that should // never happen when gRPC is used correctly. ThreadPool.QueueUserWorkItem((state) => OnAfterReleaseResourcesUnlocked()); } private INativeCall CreateNativeCall(CompletionQueueSafeHandle cq) { if (injectedNativeCall != null) { return injectedNativeCall; // allows injecting a mock INativeCall in tests. } var parentCall = details.Options.PropagationToken.AsImplOrNull()?.ParentCall ?? CallSafeHandle.NullInstance; var credentials = details.Options.Credentials; using (var nativeCredentials = credentials != null ? credentials.ToNativeCredentials() : null) { var result = details.Channel.Handle.CreateCall( parentCall, ContextPropagationTokenImpl.DefaultMask, cq, details.Method, details.Host, Timespec.FromDateTime(details.Options.Deadline.Value), nativeCredentials); return result; } } // Make sure that once cancellationToken for this call is cancelled, Cancel() will be called. private void RegisterCancellationCallback() { cancellationTokenRegistration = RegisterCancellationCallbackForToken(details.Options.CancellationToken); } /// <summary> /// Gets WriteFlags set in callDetails.Options.WriteOptions /// </summary> private WriteFlags GetWriteFlagsForCall() { var writeOptions = details.Options.WriteOptions; return writeOptions != null ? writeOptions.Flags : default(WriteFlags); } /// <summary> /// Handles receive status completion for calls with streaming response. /// </summary> private void HandleReceivedResponseHeaders(bool success, Metadata responseHeaders) { // TODO(jtattermusch): handle success==false bool releasedResources; lock (myLock) { receiveResponseHeadersPending = false; releasedResources = ReleaseResourcesIfPossible(); } if (releasedResources) { OnAfterReleaseResourcesUnlocked(); } responseHeadersTcs.SetResult(responseHeaders); } /// <summary> /// Handler for unary response completion. /// </summary> private void HandleUnaryResponse(bool success, ClientSideStatus receivedStatus, IBufferReader receivedMessageReader, Metadata responseHeaders) { // NOTE: because this event is a result of batch containing GRPC_OP_RECV_STATUS_ON_CLIENT, // success will be always set to true. TaskCompletionSource<object> delayedStreamingWriteTcs = null; TResponse msg = default(TResponse); var deserializeException = TryDeserialize(receivedMessageReader, out msg); bool releasedResources; lock (myLock) { finished = true; if (deserializeException != null && receivedStatus.Status.StatusCode == StatusCode.OK) { receivedStatus = new ClientSideStatus(DeserializeResponseFailureStatus, receivedStatus.Trailers); } finishedStatus = receivedStatus; if (isStreamingWriteCompletionDelayed) { delayedStreamingWriteTcs = streamingWriteTcs; streamingWriteTcs = null; } releasedResources = ReleaseResourcesIfPossible(); } if (releasedResources) { OnAfterReleaseResourcesUnlocked(); } responseHeadersTcs.SetResult(responseHeaders); if (delayedStreamingWriteTcs != null) { delayedStreamingWriteTcs.SetException(GetRpcExceptionClientOnly()); } var status = receivedStatus.Status; if (status.StatusCode != StatusCode.OK) { unaryResponseTcs.SetException(new RpcException(status, receivedStatus.Trailers)); return; } unaryResponseTcs.SetResult(msg); } /// <summary> /// Handles receive status completion for calls with streaming response. /// </summary> private void HandleFinished(bool success, ClientSideStatus receivedStatus) { // NOTE: because this event is a result of batch containing GRPC_OP_RECV_STATUS_ON_CLIENT, // success will be always set to true. TaskCompletionSource<object> delayedStreamingWriteTcs = null; bool releasedResources; bool origCancelRequested; lock (myLock) { finished = true; finishedStatus = receivedStatus; if (isStreamingWriteCompletionDelayed) { delayedStreamingWriteTcs = streamingWriteTcs; streamingWriteTcs = null; } releasedResources = ReleaseResourcesIfPossible(); origCancelRequested = cancelRequested; } if (releasedResources) { OnAfterReleaseResourcesUnlocked(); } if (delayedStreamingWriteTcs != null) { delayedStreamingWriteTcs.SetException(GetRpcExceptionClientOnly()); } var status = receivedStatus.Status; if (status.StatusCode != StatusCode.OK) { streamingResponseCallFinishedTcs.SetException(new RpcException(status, receivedStatus.Trailers)); if (status.StatusCode == StatusCode.Cancelled || origCancelRequested) { // Make sure the exception set to the Task is observed, // otherwise this can trigger "Unobserved exception" when the response stream // is not read until its end and the task created by the TCS is garbage collected. // See https://github.com/grpc/grpc/issues/17458 var _ = streamingResponseCallFinishedTcs.Task.Exception; } return; } streamingResponseCallFinishedTcs.SetResult(null); } IUnaryResponseClientCallback UnaryResponseClientCallback => this; void IUnaryResponseClientCallback.OnUnaryResponseClient(bool success, ClientSideStatus receivedStatus, IBufferReader receivedMessageReader, Metadata responseHeaders) { HandleUnaryResponse(success, receivedStatus, receivedMessageReader, responseHeaders); } IReceivedStatusOnClientCallback ReceivedStatusOnClientCallback => this; void IReceivedStatusOnClientCallback.OnReceivedStatusOnClient(bool success, ClientSideStatus receivedStatus) { HandleFinished(success, receivedStatus); } IReceivedResponseHeadersCallback ReceivedResponseHeadersCallback => this; void IReceivedResponseHeadersCallback.OnReceivedResponseHeaders(bool success, Metadata responseHeaders) { HandleReceivedResponseHeaders(success, responseHeaders); } } }
// Copyright (c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using Microsoft.WindowsAzure.Management.HDInsight.Contracts.May2014; namespace Microsoft.WindowsAzure.Management.HDInsight { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Runtime.Serialization; using System.Text; using System.Xml; using System.Xml.Linq; using System.Security.Cryptography.X509Certificates; using Microsoft.WindowsAzure.Management.HDInsight.ClusterProvisioning; using Microsoft.WindowsAzure.Management.HDInsight.ClusterProvisioning.Data; using Microsoft.WindowsAzure.Management.HDInsight.ClusterProvisioning.VersionFinder; using Microsoft.WindowsAzure.Management.HDInsight.Framework.Core.Library; using Microsoft.WindowsAzure.Management.HDInsight.Framework.Core.Library.DynamicXml.Reader; using Microsoft.WindowsAzure.Management.HDInsight.Framework.Core.Library.DynamicXml.Writer; using Microsoft.WindowsAzure.Management.HDInsight.Framework.Core.Library.Json; /// <summary> /// Converts data from objects into payloads. /// </summary> [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "This complexity is needed to handle all the types in the submit payload.")] internal class PayloadConverter : IPayloadConverter { private const string WindowsAzureNamespace = "http://schemas.microsoft.com/windowsazure"; private static readonly XName CloudServicesElementName = XName.Get("CloudServices", WindowsAzureNamespace); private static readonly XName CloudServiceElementName = XName.Get("CloudService", WindowsAzureNamespace); private static readonly XName GeoRegionElementName = XName.Get("GeoRegion", WindowsAzureNamespace); private static readonly XName ResourceElementName = XName.Get("Resource", WindowsAzureNamespace); private static readonly XName ResourceProviderNamespaceElementName = XName.Get("ResourceProviderNamespace", WindowsAzureNamespace); private static readonly XName TypeElementName = XName.Get("Type", WindowsAzureNamespace); private static readonly XName IntrinsicSettingItemElementName = XName.Get("IntrinsicSettings", WindowsAzureNamespace); private static readonly XName NameElementName = XName.Get("Name", WindowsAzureNamespace); private static readonly XName SubStateElementName = XName.Get("SubState", WindowsAzureNamespace); private static readonly XName OutputItemElementName = XName.Get("OutputItem", WindowsAzureNamespace); private static readonly XName KeyElementName = XName.Get("Key", WindowsAzureNamespace); private static readonly XName ValueElementName = XName.Get("Value", WindowsAzureNamespace); private static readonly XName OperationStatusElementName = XName.Get("OperationStatus", WindowsAzureNamespace); private static readonly XName ErrorElementName = XName.Get("Error", WindowsAzureNamespace); private static readonly XName HttpCodeElementName = XName.Get("HttpCode", WindowsAzureNamespace); private static readonly XName MessageElementName = XName.Get("Message", WindowsAzureNamespace); private const string ClusterUserName = "ClusterUsername"; private const string ExtendedErrorElementName = "ExtendedErrorMessage"; private const string NodesCount = "NodesCount"; private const string ConnectionUrl = "ConnectionURL"; private const string CreatedDate = "CreatedDate"; private const string VersionName = "Version"; private const string HttpUserName = "Http_Username"; private const string RdpUserName = "RDP_Username"; private const string HttpPassword = "Http_Password"; private const string BlobContainersElementName = "BlobContainers"; private const string Create = "Create"; private const string SchemaVersion20 = "2.0"; private const string WorkerNodeRoleName = "WorkerNodeRole"; private const string HeadNodeRoleName = "HeadNodeRole"; private const string ClusterTypePropertyName = "Type"; private const string HadoopAndHBaseType = "MR,HBase"; private const string HadoopAndStormType = "MR,Storm"; private const string HadoopAndSparkType = "MR,Spark"; private const string ContainersResourceType = "containers"; /// <summary> /// Provides the namespace for the May2013 contracts. /// </summary> public const string May2013 = "http://schemas.microsoft.com/hdinsight/2013/05/management"; /// <summary> /// Provides the namespace for the System contracts. /// </summary> public const string System = "http://schemas.datacontract.org/2004/07/System"; internal static string SerializeHttpConnectivityRequest(UserChangeRequestOperationType type, string username, string password, DateTimeOffset experation) { Help.DoNothing(experation); if (username.IsNull()) { username = string.Empty; } if (password.IsNull()) { password = string.Empty; } dynamic dynaXml = DynaXmlBuilder.Create(false, Formatting.None); dynaXml.xmlns(May2013) .HttpUserChangeRequest .b .Operation(type.ToString()) .Username(username) .Password(password) .d .End(); return dynaXml.ToString(); } /// <summary> /// Serializes a connectivity request. /// </summary> /// <param name="type">Operation type.</param> /// <param name="userName">User name.</param> /// <param name="password">Password for service.</param> /// <param name="expiration">Date when this service access expires.</param> /// <returns>A Serialized connectivity request.</returns> internal static string SerializeRdpConnectivityRequest(UserChangeRequestOperationType type, string userName, string password, DateTimeOffset expiration) { if (userName.IsNull()) { userName = string.Empty; } if (password.IsNull()) { password = string.Empty; } dynamic dynaXml = DynaXmlBuilder.Create(false, Formatting.None); dynaXml.xmlns(May2013) .xmlns.a(System) .RdpUserChangeRequest .b .Operation(type.ToString()) .Username(userName) .Password(password) .ExpirationDate .b .xmlns.a.DateTime(expiration.DateTime.ToString("o", CultureInfo.InvariantCulture)) .xmlns.a.OffsetMinutes(expiration.Offset.TotalMinutes) .d .d .End(); return dynaXml.ToString(); } /// <inheritdoc /> public PayloadResponse<UserChangeRequestStatus> DeserializeConnectivityStatus(string payload) { XmlDocument doc = new XmlDocument(); using (var stream = payload.ToUtf8Stream()) using (var reader = XmlReader.Create(stream)) { doc.Load(reader); } var manager = new DynaXmlNamespaceTable(doc); PayloadResponse<UserChangeRequestStatus> result = new PayloadResponse<UserChangeRequestStatus>(); var node = doc.SelectSingleNode("/def:PassthroughResponse/def:Data", manager.NamespaceManager); if (node.IsNotNull()) { result.Data = new UserChangeRequestStatus(); var data = node; node = data.SelectSingleNode("def:State", manager.NamespaceManager); UserChangeRequestOperationStatus status; if (node.IsNull() || !UserChangeRequestOperationStatus.TryParse(node.InnerText, out status)) { throw new SerializationException("Unable to deserialize the server response."); } result.Data.State = status; node = data.SelectSingleNode("def:UserType", manager.NamespaceManager); UserChangeRequestUserType userType; if (node.IsNull() || !UserChangeRequestUserType.TryParse(node.InnerText, out userType)) { throw new SerializationException("Unable to deserialize the server response."); } result.Data.UserType = userType; node = data.SelectSingleNode("def:OperationType", manager.NamespaceManager); UserChangeRequestOperationType operationType; if (node.IsNull() || !UserChangeRequestOperationType.TryParse(node.InnerText, out operationType)) { throw new SerializationException("Unable to deserialize the server response."); } result.Data.OperationType = operationType; node = data.SelectSingleNode("def:RequestIssueDate", manager.NamespaceManager); DateTime requestTime; if (node.IsNull() || !DateTime.TryParse(node.InnerText, out requestTime)) { throw new SerializationException("Unable to deserialize the server response."); } result.Data.RequestIssueDate = requestTime.ToUniversalTime(); node = data.SelectSingleNode("def:Error", manager.NamespaceManager); result.Data.ErrorDetails = this.GetErrorDetails(node, manager.NamespaceManager); } node = doc.SelectSingleNode("/def:PassthroughResponse/def:Error", manager.NamespaceManager); result.ErrorDetails = this.GetErrorDetails(node, manager.NamespaceManager); return result; } private PayloadErrorDetails GetErrorDetails(XmlNode root, XmlNamespaceManager manager) { PayloadErrorDetails details = null; if (root.HasChildNodes) { details = new PayloadErrorDetails(); HttpStatusCode statusCode; var node = root.SelectSingleNode("def:StatusCode", manager); if (node.IsNull() || !HttpStatusCode.TryParse(node.InnerText, out statusCode)) { throw new SerializationException("Unable to parse the Status Code of the Error Details."); } details.StatusCode = statusCode; node = root.SelectSingleNode("def:ErrorId", manager); if (node.IsNull()) { throw new SerializationException("Unable to parse the error id of the Error response component."); } details.ErrorId = node.InnerText; node = root.SelectSingleNode("def:ErrorMessage", manager); if (node.IsNull()) { throw new SerializationException("Unable to parse the error message of the Error response component."); } details.ErrorMessage = node.InnerText; } return details; } /// <summary> /// Deserializes a Connectivity Response. /// </summary> /// <param name="payload">The payload.</param> /// <returns> /// A PayloadResponse object with the operation id for the data. /// </returns> public PayloadResponse<Guid> DeserializeConnectivityResponse(string payload) { XmlDocument doc = new XmlDocument(); using (var stream = payload.ToUtf8Stream()) using (var reader = XmlReader.Create(stream)) { doc.Load(reader); } var manager = new DynaXmlNamespaceTable(doc); PayloadResponse<Guid> result = new PayloadResponse<Guid>(); var node = doc.SelectSingleNode("/def:PassthroughResponse/def:Data", manager.NamespaceManager); if (node.IsNotNull() && node.InnerText.IsNotNullOrEmpty()) { var text = node.InnerText; Guid guid; if (!Guid.TryParse(text, out guid)) { throw new SerializationException("Unable to deserialize the server response."); } result.Data = guid; } node = doc.SelectSingleNode("/def:PassthroughResponse/def:Error", manager.NamespaceManager); result.ErrorDetails = this.GetErrorDetails(node, manager.NamespaceManager); return result; } /// <inheritdoc /> public Collection<ClusterDetails> DeserializeListContainersResult(string payload, string deploymentNamespace, Guid subscriptionId) { var data = this.DeserializeHDInsightClusterList(payload, deploymentNamespace, subscriptionId); return new Collection<ClusterDetails>(data.ToList()); } /// <inheritdoc /> public string SerializeClusterCreateRequestV3(ClusterCreateParametersV2 cluster) { Contracts.May2014.ClusterCreateParameters ccp = null; if (cluster.ClusterType == ClusterType.HBase) { ccp = HDInsightClusterRequestGenerator.Create3XClusterForMapReduceAndHBaseTemplate(cluster); } else if (cluster.ClusterType == ClusterType.Storm) { ccp = HDInsightClusterRequestGenerator.Create3XClusterForMapReduceAndStormTemplate(cluster); } else if (cluster.ClusterType == ClusterType.Spark) { ccp = HDInsightClusterRequestGenerator.Create3XClusterForMapReduceAndSparkTemplate(cluster); } else if (cluster.ClusterType == ClusterType.Hadoop) { ccp = HDInsightClusterRequestGenerator.Create3XClusterFromMapReduceTemplate(cluster); } else { throw new InvalidDataException("Invalid cluster type"); } return this.CreateClusterRequest_ToInternalV3(ccp); } /// <inheritdoc /> public string SerializeClusterCreateRequest(ClusterCreateParametersV2 cluster) { return this.CreateClusterRequest_ToInternal(cluster); } [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "This is a result of interface flowing and not a true measure of complexity.")] private string CreateClusterRequest_ToInternal(ClusterCreateParametersV2 cluster) { dynamic dynaXml = DynaXmlBuilder.Create(false, Formatting.None); // The RP translates 1 XL into 2 L for SU 4 and up. // This is done as part of the HA improvement where in the RP would never // create clusters without 2 nodes for SU 4 release (May '14) and up. var headnodeCount = cluster.HeadNodeSize.Equals(VmSize.ExtraLarge.ToString()) ? 1 : 2; dynaXml.xmlns("http://schemas.microsoft.com/windowsazure") .Resource .b .SchemaVersion(SchemaVersion20) .IntrinsicSettings .b .xmlns(May2013) .ClusterContainer .b .Deployment .b .AdditionalStorageAccounts .b .d .ClusterPassword(cluster.Password) .ClusterUsername(cluster.UserName) .Roles .b .ClusterRole .b .Count(headnodeCount) .RoleType(ClusterRoleType.HeadNode) .VMSize(cluster.HeadNodeSize) .d .ClusterRole .b .Count(cluster.ClusterSizeInNodes) .RoleType(ClusterRoleType.DataNode) .VMSize(cluster.DataNodeSize) .d .d .Version(cluster.Version) .d .DeploymentAction(Create) .ClusterName(cluster.Name) .Region(cluster.Location) .StorageAccounts .b .BlobContainerReference .b .AccountName(cluster.DefaultStorageAccountName) .BlobContainerName(cluster.DefaultStorageContainer) .Key(cluster.DefaultStorageAccountKey) .d .sp("asv") .d .Settings .b .Core .b .sp("coresettings") .d .d .b .Hdfs .b .sp("hdfssettings") .d .d .b .MapReduce .b .sp("mapreduceconfiguration") .sp("mapreducecapacityschedulerconfiguration") .d .d .b .Hive .b .sp("hivesettings") .sp("hiveresources") .d .Oozie .b .sp("ooziesettings") .sp("oozieadditionalsharedlibraries") .sp("ooziesharedexecutables") .d .Yarn .b .sp("yarnsettings") .d .d .d .d .d .End(); dynaXml.rp("asv"); foreach (var asv in cluster.AdditionalStorageAccounts) { this.AddStorageAccount(dynaXml, asv, "deploymentcontainer"); } this.AddConfigurationOptions(dynaXml, cluster.CoreConfiguration, "coresettings"); this.AddConfigurationOptions(dynaXml, cluster.HdfsConfiguration, "hdfssettings"); this.AddConfigurationOptions(dynaXml, cluster.YarnConfiguration, "yarnsettings"); if (cluster.MapReduceConfiguration != null) { this.AddConfigurationOptions(dynaXml, cluster.MapReduceConfiguration.ConfigurationCollection, "mapreduceconfiguration"); this.AddConfigurationOptions(dynaXml, cluster.MapReduceConfiguration.CapacitySchedulerConfigurationCollection, "mapreducecapacityschedulerconfiguration"); } this.AddConfigurationOptions(dynaXml, cluster.HiveConfiguration.ConfigurationCollection, "hivesettings"); this.SerializeOozieConfiguration(cluster, dynaXml); this.SerializeHiveConfiguration(cluster, dynaXml); string xml; using (var stream = new MemoryStream()) using (var reader = new StreamReader(stream)) { dynaXml.Save(stream); stream.Position = 0; xml = reader.ReadToEnd(); } return xml; } private string CreateClusterRequest_ToInternalV3(Contracts.May2014.ClusterCreateParameters ccp) { var ccpAsXmlString = ccp.SerializeAndOptionallyWriteToStream(); var doc = new XmlDocument(); using (var stringReader = new StringReader(ccpAsXmlString)) { using (var reader = XmlReader.Create(stringReader)) { doc.Load(reader); } } var resource = new RDFEResource { SchemaVersion = "3.0", IntrinsicSettings = new XmlNode[] { doc.DocumentElement } }; using (var str = new MemoryStream()) { var serializer = new DataContractSerializer(typeof(RDFEResource)); serializer.WriteObject(str, resource); str.Position = 0; using (var reader = new StreamReader(str)) { return reader.ReadToEnd(); } } } private void SerializeHiveConfiguration(ClusterCreateParametersV2 cluster, dynamic dynaXml) { if (cluster.HiveConfiguration.AdditionalLibraries != null) { dynaXml.rp("hiveresources") .AdditionalLibraries.b.AccountName(cluster.HiveConfiguration.AdditionalLibraries.Name) .BlobContainerName(cluster.HiveConfiguration.AdditionalLibraries.Container) .Key(cluster.HiveConfiguration.AdditionalLibraries.Key) .d.End(); } if (cluster.HiveMetastore != null) { dynaXml.rp("hivesettings") .Catalog.b.DatabaseName(cluster.HiveMetastore.Database) .Password(cluster.HiveMetastore.Password) .Server(cluster.HiveMetastore.Server) .Username(cluster.HiveMetastore.User) .d.End(); } } private void SerializeOozieConfiguration(ClusterCreateParametersV2 cluster, dynamic dynaXml) { this.AddConfigurationOptions(dynaXml, cluster.OozieConfiguration.ConfigurationCollection, "ooziesettings"); if (cluster.OozieConfiguration.AdditionalSharedLibraries != null) { dynaXml.rp("oozieadditionalsharedlibraries") .AdditionalSharedLibraries .b .AccountName(cluster.OozieConfiguration.AdditionalSharedLibraries.Name) .BlobContainerName(cluster.OozieConfiguration.AdditionalSharedLibraries.Container) .Key(cluster.OozieConfiguration.AdditionalSharedLibraries.Key) .d.End(); } if (cluster.OozieConfiguration.AdditionalActionExecutorLibraries != null) { dynaXml.rp("ooziesharedexecutables") .AdditionalActionExecutorLibraries .b .AccountName(cluster.OozieConfiguration.AdditionalActionExecutorLibraries.Name) .BlobContainerName(cluster.OozieConfiguration.AdditionalActionExecutorLibraries.Container) .Key(cluster.OozieConfiguration.AdditionalActionExecutorLibraries.Key) .d.End(); } this.SerializeOozieMetastore(cluster, dynaXml); } private void SerializeOozieMetastore(ClusterCreateParametersV2 cluster, dynamic dynaXml) { if (cluster.OozieMetastore != null) { dynaXml.rp("ooziesettings") .Catalog.b.DatabaseName(cluster.OozieMetastore.Database) .Password(cluster.OozieMetastore.Password) .Server(cluster.OozieMetastore.Server) .Username(cluster.OozieMetastore.User) .d.End(); } } private void AddStorageAccount(dynamic dynaXml, WabStorageAccountConfiguration asv, string containerName) { dynaXml.BlobContainerReference .b .AccountName(asv.Name) .BlobContainerName(containerName) .Key(asv.Key) .d.End(); } private void AddConfigurationOptions(dynamic dynaXml, ConfigValuesCollection configProperties, string sectionName) { if (configProperties.Any()) { var configurationElement = dynaXml.rp(sectionName).Configuration.b; foreach (var configPropety in configProperties) { configurationElement.Property.b.Name(configPropety.Key).Value(configPropety.Value).d.End(); } configurationElement.d.End(); } } internal IEnumerable<ClusterDetails> DeserializeHDInsightClusterList(string payload, string deploymentNamespace, Guid subscriptionId) { payload.ArgumentNotNullOrEmpty("payload"); var payloadDocument = XDocument.Parse(payload); var clusterList = new List<ClusterDetails>(); var clusterEnumerable = from cloudServices in payloadDocument.Elements(CloudServicesElementName) from cloudService in cloudServices.Elements(CloudServiceElementName) let geoRegion = cloudService.Element(GeoRegionElementName) from resource in cloudService.Descendants(ResourceElementName) let resourceNamespace = this.GetStringValue(resource, ResourceProviderNamespaceElementName) let intrinsicSettings = this.GetIntrinsicSettings(resource) let storageAccounts = this.GetStorageAccounts(resource, intrinsicSettings) let rdfeResourceType = this.GetStringValue(resource, TypeElementName) where resourceNamespace == deploymentNamespace && rdfeResourceType.Equals(ContainersResourceType, StringComparison.OrdinalIgnoreCase) let versionString = this.GetClusterProperty(resource, intrinsicSettings, VersionName) select new ClusterDetails() { Name = this.GetStringValue(resource, NameElementName), Location = geoRegion.Value, StateString = this.GetStringValue(resource, SubStateElementName), RdpUserName = this.GetClusterProperty(resource, intrinsicSettings, RdpUserName), HttpUserName = this.GetClusterProperty(resource, intrinsicSettings, HttpUserName), HttpPassword = this.GetClusterProperty(resource, intrinsicSettings, HttpPassword), ClusterSizeInNodes = this.ExtractClusterPropertyIntValue(resource, intrinsicSettings, NodesCount), ConnectionUrl = this.GetClusterProperty(resource, intrinsicSettings, ConnectionUrl), CreatedDate = this.ExtractClusterPropertyDateTimeValue(resource, intrinsicSettings, CreatedDate), Version = versionString, VersionStatus = VersionFinderClient.GetVersionStatus(versionString), DefaultStorageAccount = this.GetDefaultStorageAccount(storageAccounts), AdditionalStorageAccounts = this.GetAdditionalStorageAccounts(storageAccounts), VersionNumber = this.ConvertStringToVersion(versionString), Error = this.DeserializeClusterError(resource), SubscriptionId = subscriptionId, ClusterType = this.GetClusterType(resource, intrinsicSettings) }; clusterList.AddRange(clusterEnumerable); return clusterList; } internal ClusterType GetClusterType(XElement resource, IEnumerable<KeyValuePair<string, string>> intrinsicSettings) { string clusterType = this.GetClusterProperty(resource, intrinsicSettings, ClusterTypePropertyName); if (clusterType != null && clusterType.Equals(HadoopAndHBaseType)) { return ClusterType.HBase; } else if (clusterType != null && clusterType.Equals(HadoopAndStormType)) { return ClusterType.Storm; } else if (clusterType != null && clusterType.Equals(HadoopAndSparkType)) { return ClusterType.Spark; } return ClusterType.Hadoop; } // Get a certificate object from a string property encoded as base 64. private static X509Certificate2 GetCertificate(string property) { if (string.IsNullOrEmpty(property)) { return null; } var bytes = Convert.FromBase64String(property); return new X509Certificate2(bytes); } private IEnumerable<WabStorageAccountConfiguration> GetAdditionalStorageAccounts(IEnumerable<WabStorageAccountConfiguration> storageAccounts) { return storageAccounts.Skip(1); } private WabStorageAccountConfiguration GetDefaultStorageAccount(IEnumerable<WabStorageAccountConfiguration> storageAccounts) { return storageAccounts.FirstOrDefault(); } private IEnumerable<WabStorageAccountConfiguration> GetStorageAccounts(XElement resource, IEnumerable<KeyValuePair<string, string>> intrinsicSettings) { var blobContainerSerializedJson = this.GetClusterProperty(resource, intrinsicSettings, BlobContainersElementName); if (blobContainerSerializedJson.IsNullOrEmpty()) { return Enumerable.Empty<WabStorageAccountConfiguration>(); } return this.GetStorageAccountsFromJson(blobContainerSerializedJson); } /// <summary> /// Converts an HDInsight version string to a Version object. /// </summary> /// <param name="version"> /// The version string. /// </param> /// <returns> /// A version object that represents the components of the version string. /// </returns> public Version ConvertStringToVersion(string version) { if (version.IsNotNullOrEmpty()) { version.ArgumentNotNullOrEmpty("version"); if (version.IsNotNullOrEmpty()) { Version outVersion = new Version(); if (Version.TryParse(version, out outVersion)) { return outVersion; } else { string[] parts = version.Split('.'); int major; int minor; int build; int rev; if (parts.Length >= 4 && int.TryParse(parts[0], out major) && int.TryParse(parts[1], out minor) && int.TryParse(parts[2], out build) && int.TryParse(parts[3], out rev)) { return new Version(major, minor, build, rev); } } return outVersion; } } return new Version(); } internal ClusterErrorStatus DeserializeClusterError(XElement resource) { resource.ArgumentNotNull("resource"); var operationStatusElement = resource.Element(OperationStatusElementName); if (operationStatusElement == null) { return null; } string errorMessage; ClusterErrorStatus clusterErrorStatus = null; var errorElement = operationStatusElement.Element(ErrorElementName); var extendedErrorElement = this.ExtractResourceOutputStringValue(resource, ExtendedErrorElementName); if (errorElement != null) { var errorType = this.GetStringValue(operationStatusElement, TypeElementName); var httpCode = int.Parse(this.GetStringValue(errorElement, HttpCodeElementName), CultureInfo.InvariantCulture); errorMessage = this.GetStringValue(errorElement, MessageElementName); clusterErrorStatus = new ClusterErrorStatus(httpCode, errorMessage, errorType); } if (extendedErrorElement.IsNotNullOrEmpty()) { if (clusterErrorStatus == null) { clusterErrorStatus = new ClusterErrorStatus(); } clusterErrorStatus.Message = extendedErrorElement; } return clusterErrorStatus; } internal int ExtractClusterPropertyIntValue(XElement resource, IEnumerable<KeyValuePair<string, string>> intrinsicSettings, string name) { int intValue; var intString = this.GetClusterProperty(resource, intrinsicSettings, name); if (int.TryParse(intString, NumberStyles.None, CultureInfo.InvariantCulture, out intValue)) { return intValue; } return 0; } internal DateTime ExtractClusterPropertyDateTimeValue(XElement resource, IEnumerable<KeyValuePair<string, string>> intrinsicSettings, string name) { DateTime outputDateTime; var dateTimeString = this.GetClusterProperty(resource, intrinsicSettings, name); if (DateTime.TryParse(dateTimeString, CultureInfo.InvariantCulture, DateTimeStyles.None, out outputDateTime)) { return outputDateTime; } return DateTime.MinValue; } internal string GetClusterProperty(XElement resource, IEnumerable<KeyValuePair<string, string>> intrinsicSettings, string intrinsicSettingPropertyName) { return GetClusterProperty(resource, intrinsicSettings, intrinsicSettingPropertyName, intrinsicSettingPropertyName); } internal string GetClusterProperty(XElement resource, IEnumerable<KeyValuePair<string, string>> intrinsicSettings, string intrinsicSettingPropertyName, string outputItemPropertyName) { var intrinsicSettingsList = intrinsicSettings.ToList(); if (intrinsicSettingsList.Any(setting => setting.Key == intrinsicSettingPropertyName)) { var valueFromIntrinsicSetting = intrinsicSettingsList.First(setting => setting.Key == intrinsicSettingPropertyName); return valueFromIntrinsicSetting.Value; } return this.ExtractResourceOutputStringValue(resource, outputItemPropertyName); } internal string ExtractResourceOutputStringValue(XElement resource, string name) { var outputItemValue = from outputItem in resource.Descendants(OutputItemElementName) let outputItemName = this.GetStringValue(outputItem, KeyElementName) where outputItemName == name select this.GetStringValue(outputItem, ValueElementName); return outputItemValue.FirstOrDefault(); } internal IEnumerable<KeyValuePair<string, string>> GetIntrinsicSettings(XElement resource) { var intrinsicSettingsElement = resource.Descendants(IntrinsicSettingItemElementName).FirstOrDefault(); if (intrinsicSettingsElement != null) { return this.GetOutputItemsFromJson(intrinsicSettingsElement.Value); } return Enumerable.Empty<KeyValuePair<string, string>>(); } private IEnumerable<KeyValuePair<string, string>> GetOutputItemsFromJson(string value) { var outputItems = new List<KeyValuePair<string, string>>(); var bytes = Encoding.UTF8.GetBytes(value); using (var memoryStream = new MemoryStream(bytes)) { var jsonParser = new JsonParser(memoryStream); var jsonItem = jsonParser.ParseNext(); var jsonArray = jsonItem as JsonArray; if (jsonArray == null) { return Enumerable.Empty<KeyValuePair<string, string>>(); } for (int index = 0; index < jsonArray.Count(); index++) { var outputItem = jsonArray.GetIndex(index); var keyProperty = this.GetJsonStringValue(outputItem.GetProperty("Key")); var valueProperty = this.GetJsonStringValue(outputItem.GetProperty("Value")); outputItems.Add(new KeyValuePair<string, string>(keyProperty, valueProperty)); } } return outputItems; } private IEnumerable<WabStorageAccountConfiguration> GetStorageAccountsFromJson(string value) { var storageAccounts = new List<WabStorageAccountConfiguration>(); var bytes = Encoding.UTF8.GetBytes(value); using (var memoryStream = new MemoryStream(bytes)) { var jsonParser = new JsonParser(memoryStream); var jsonItem = jsonParser.ParseNext(); var jsonArray = jsonItem as JsonArray; if (jsonArray == null) { return Enumerable.Empty<WabStorageAccountConfiguration>(); } for (int index = 0; index < jsonArray.Count(); index++) { var outputItem = jsonArray.GetIndex(index); var key = this.GetJsonStringValue(outputItem.GetProperty("Key")); var account = this.GetJsonStringValue(outputItem.GetProperty("AccountName")); var container = this.GetJsonStringValue(outputItem.GetProperty("Container")); storageAccounts.Add(new WabStorageAccountConfiguration(account, key, container)); } } return storageAccounts; } private string GetJsonStringValue(JsonItem item) { string value; item.TryGetValue(out value); return value; } internal string GetStringValue(XElement element, XName elementName) { element.ArgumentNotNull("element"); var childElement = element.Element(elementName); return childElement != null ? childElement.Value : string.Empty; } } }
using System; using System.Collections.Generic; using System.Linq; using VRageMath; using Sandbox.ModAPI; using VRage.ModAPI; using VRage.Utils; using VRage.Game; using VRage; using VRage.Game.ModAPI; using NaniteConstructionSystem.Entities.Beacons; namespace NaniteConstructionSystem.Particles { public class NaniteParticle { private bool m_cancel; public bool IsCancelled { get { return m_cancel; } } private bool m_complete; public bool IsCompleted { get { return m_complete; } } private IMyCubeBlock m_source; public IMyCubeBlock SourceBlock { get { return m_source; } } private object m_destination; public object Destination { get { return m_destination; } } private List<Vector3D> m_previousPoints; private Vector4 m_startColor; private Vector4 m_endColor; private int m_tailLength; private float m_scale; private Vector3D m_position; private int m_startTime; private List<ParticleRelativePath> m_paths; private int m_lifeTime; public int StartTime { get { return m_startTime; } } public int LifeTime { get { return m_lifeTime; } } public NaniteParticle(int lifeTime, IMyCubeBlock source, object destination, Vector4 startColor, Vector4 endColor, int tailLength, float scale) { m_previousPoints = new List<Vector3D>(); m_source = source; m_destination = destination; m_startColor = startColor; m_endColor = endColor; m_tailLength = tailLength; m_scale = scale; m_cancel = false; m_lifeTime = lifeTime; m_paths = new List<ParticleRelativePath>(); } public void Start() { float size = 1.75f; /* if(m_destination is IMySlimBlock) { var slim = (IMySlimBlock)m_destination; if (slim.FatBlock != null) { var destBlock = (IMyCubeBlock)slim.FatBlock; size = destBlock.LocalVolume.Radius; } } */ m_paths.Add(new ParticleRelativePath(m_source, m_destination, 10, 0.3f)); m_paths.Add(new ParticleRelativePath(m_destination, m_destination, 6, size)); m_paths.Add(new ParticleRelativePath(m_destination, m_source, 10, 1f, true)); m_position = GetSourcePosition(); m_startTime = (int)MyAPIGateway.Session.ElapsedPlayTime.TotalMilliseconds; } public void StartMining(IMyTerminalBlock miningHammer) { float size = 1.75f; m_paths.Add(new ParticleRelativePath(m_source, miningHammer, 16, 1f, true)); m_paths.Add(new ParticleRelativePath(miningHammer, miningHammer, 6, size)); m_paths.Add(new ParticleRelativePath(miningHammer, m_destination, 10, 0.3f)); m_paths.Add(new ParticleRelativePath(m_destination, m_destination, 6, size)); m_paths.Add(new ParticleRelativePath(m_destination, miningHammer, 10, 0.3f)); m_paths.Add(new ParticleRelativePath(miningHammer, m_source, 10, 1f, true)); m_position = GetSourcePosition(); m_startTime = (int)MyAPIGateway.Session.ElapsedPlayTime.TotalMilliseconds; } public void Update() { try { if (MyAPIGateway.Session.Player == null) return; if (m_paths.Count == 0) return; foreach (var item in m_paths) item.Update(); Vector3D newPosition = m_position; double globalRatio = GetGlobalRatio(); var pointCount = GetPathPointCount() - 1; int pathIndex = 1 + (int)(globalRatio * pointCount); float localRatio = (float)(globalRatio * pointCount - Math.Truncate(globalRatio * pointCount)); Vector3D catmullPosition = Vector3D.CatmullRom(GetPathPoint(pathIndex - 1), GetPathPoint(pathIndex), GetPathPoint(pathIndex + 1), GetPathPoint(pathIndex + 2), localRatio); if (catmullPosition.IsValid()) newPosition = catmullPosition; m_previousPoints.Add(m_position); m_position = newPosition; } catch (Exception ex) { Logging.Instance.WriteLine(string.Format("Update Exception: {0} - {1} {2}", ex.ToString(), m_paths.Count, GetPathPointCount())); } } public void Draw() { if (MyAPIGateway.Session.Player == null) return; try { var scale = m_scale; float width = scale / 1.66f; float height = scale; Vector4 drawColor = GetColor(); if (m_previousPoints.Count > 0) { Vector3D previousPoint = m_position; int count = 0; for (int r = m_previousPoints.Count - 1; r >= 1; r--) { Vector3D processPoint = m_previousPoints[r]; if (previousPoint != processPoint) { Vector4 color = drawColor * (1f - (count / (float)m_tailLength)); Vector3D direction = Vector3D.Normalize(previousPoint - processPoint); var length = (float)(previousPoint - processPoint).Length(); var modifiedLength = length * 3f; var modifiedWidth = width * (1f - (count / (float)m_tailLength)); if (modifiedLength > 0f && Vector3D.DistanceSquared(processPoint, MyAPIGateway.Session.Player.GetPosition()) < 50f * 50f) { if (modifiedLength <= 2f) MyTransparentGeometry.AddLineBillboard(MyStringId.GetOrCompute("Firefly"), color, processPoint, direction, modifiedLength, modifiedWidth); else { MyTransparentGeometry.AddLineBillboard(MyStringId.GetOrCompute("Firefly"), color, processPoint, direction, modifiedLength / 2f, modifiedWidth); if (count >= m_tailLength / 3) break; } } } previousPoint = processPoint; count++; if (count >= m_tailLength) break; } } } catch (Exception ex) { Logging.Instance.WriteLine(string.Format("Draw Exception: {0}", ex.ToString())); } } private Vector4 GetColor() { Vector4 drawColor = m_startColor; int localIndex = 0; int listIndex = 0; GetCurrentIndices(out localIndex, out listIndex); if (listIndex == 1) // orbiting { Vector4 drawColorDiff = (m_endColor - m_startColor) / m_paths[listIndex].GetPointCount(); drawColor = drawColor + drawColorDiff * localIndex; } else if (listIndex >= m_paths.Count - 1 && m_paths.Count > 1) // || listIndex > 3) // returning { drawColor = m_endColor; } else if (m_cancel) { drawColor = new Vector4(0.95f, 0.45f, 0.45f, 0.75f); } else if (m_complete) { drawColor = new Vector4(0.45f, 0.95f, 0.45f, 0.75f); //drawColor = m_endColor; } return drawColor; } public void Complete(bool cancel = false) { if (m_complete) return; m_complete = true; m_cancel = cancel; int currentIndex = GetCurrentListIndex(); if ((m_paths.Count == 3 && currentIndex < 2 && m_paths.Count > 2) || (m_paths.Count == 6 && currentIndex < 4 && m_paths.Count > 2)) { if (m_paths.Count == 3) { for (int r = 0; r < 3; r++) m_paths.RemoveAt(0); } else { for (int r = 0; r < 6; r++) m_paths.RemoveAt(0); } CreateCompletePath(currentIndex); int timeRemaining = m_lifeTime - ((int)MyAPIGateway.Session.ElapsedPlayTime.TotalMilliseconds - m_startTime); m_lifeTime = Math.Min(20000, Math.Max(8000, timeRemaining)); m_startTime = (int)MyAPIGateway.Session.ElapsedPlayTime.TotalMilliseconds; } } private void CreateCompletePath(int currentIndex) { List<Vector3D> pushList = null; if (m_previousPoints.Count < 3) return; var position = m_position; pushList = new List<Vector3D>(); pushList.Add(position); if (currentIndex == 1 && m_previousPoints.Count > 0) { Vector3D normal = VRage.Utils.MyUtils.GetRandomVector3Normalized(); BoundingSphereD sphere = new BoundingSphereD(position, 3); pushList.Add(MyUtils.GetRandomBorderPosition(ref sphere)); pushList.Add(MyUtils.GetRandomBorderPosition(ref sphere)); } m_paths.Add(new ParticleRelativePath(position, m_source, 10, 0.6f, true, pushList)); } private Vector3D GetSourcePosition() { return Vector3D.Transform(new Vector3D(0f, 1.5f, 0f), m_source.WorldMatrix); } private Vector3D GetDestinationPosition() { if (m_destination is IMySlimBlock) { var destination = (IMySlimBlock)m_destination; if (destination.FatBlock != null) return destination.FatBlock.PositionComp.GetPosition(); var size = destination.CubeGrid.GridSizeEnum == MyCubeSize.Small ? 0.5f : 2.5f; var destinationPosition = new Vector3D(destination.Position * size); return Vector3D.Transform(destinationPosition, destination.CubeGrid.WorldMatrix); } else if(m_destination is IMyEntity) { return ((IMyEntity)m_destination).GetPosition(); } else if(m_destination is NaniteMiningItem) { return (m_destination as NaniteMiningItem).Position; } else if(m_destination is IMyPlayer) { var destinationPosition = new Vector3D(0f, 2f, 0f); var targetPosition = Vector3D.Transform(destinationPosition, (m_destination as IMyPlayer).Controller.ControlledEntity.Entity.WorldMatrix); return targetPosition; //return (m_destination as IMyPlayer).GetPosition(); } return Vector3D.Zero; } private double GetGlobalRatio() { return MathHelper.Clamp((double)((int)MyAPIGateway.Session.ElapsedPlayTime.TotalMilliseconds - m_startTime) / (double)m_lifeTime, 0.0, 1.0); } private int GetPathPointCount() { int count = 0; for (int r = 0; r < m_paths.Count; r++) { var path = m_paths[r]; count += path.GetPointCount(); } return count; } private void GetCurrentIndices(out int localIndex, out int listIndex) { double globalRatio = GetGlobalRatio(); var pointCount = GetPathPointCount() - 1; int pathIndex = 1 + (int)(globalRatio * pointCount); ParticleRelativePath path = null; localIndex = 0; listIndex = 0; GetRelativePath(pathIndex, out path, out localIndex, out listIndex); } private int GetCurrentListIndex() { double globalRatio = GetGlobalRatio(); var pointCount = GetPathPointCount() - 1; int pathIndex = 1 + (int)(globalRatio * pointCount); ParticleRelativePath path = null; int localIndex = 0; int listIndex = 0; GetRelativePath(pathIndex, out path, out localIndex, out listIndex); if (path == null) return 0; return listIndex; } private Vector3D GetPathPoint(int index) { ParticleRelativePath path = null; int localIndex = 0; int listIndex = 0; GetRelativePath(index, out path, out localIndex, out listIndex); if (path == null) return m_paths[m_paths.Count() - 1].GetPoint(m_paths[m_paths.Count() - 1].GetPointCount()); Vector3D point = path.GetPoint(localIndex); return point; } private void GetRelativePath(int index, out ParticleRelativePath particlePath, out int localIndex, out int listIndex) { particlePath = null; localIndex = 0; listIndex = 0; if (m_paths.Count < 1) return; if (index < 0 || index >= GetPathPointCount()) return; int pointSum = 0; for (int r = 0; r < m_paths.Count; r++) { var pathList = m_paths[r]; listIndex = r; float ratio = (float)(index + 1) / (pointSum + pathList.GetPointCount()); if (ratio <= 1.0f) break; pointSum += pathList.GetPointCount(); } particlePath = m_paths[listIndex]; localIndex = index - pointSum; } } }
using System; using System.Collections; using System.Collections.Generic; using JetBrains.Annotations; using OpenMLTD.MilliSim.Core; namespace OpenMLTD.MilliSim.Foundation { /// <inheritdoc /> /// <summary> /// An update-safe collection for base game components. /// </summary> public sealed partial class BaseGameComponentCollection : IList<IBaseGameComponent> { /// <summary> /// Creates a new <see cref="BaseGameComponentCollection"/> for <see cref="IBaseGameComponentContainer"/>. /// </summary> /// <param name="container">The <see cref="IBaseGameComponentContainer"/> to create this instance for.</param> internal BaseGameComponentCollection([NotNull] IBaseGameComponentContainer container) : this(container, null) { } /// <summary> /// Creates a new <see cref="BaseGameComponentCollection"/> for <see cref="IBaseGameComponentContainer"/> with a list of <see cref="IBaseGameComponent"/>s. /// </summary> /// <param name="container">The <see cref="IBaseGameComponentContainer"/> to create this instance for.</param> /// <param name="components">Initial components.</param> internal BaseGameComponentCollection([NotNull] IBaseGameComponentContainer container, [CanBeNull, ItemNotNull] IReadOnlyList<IBaseGameComponent> components) { Container = container ?? throw new ArgumentNullException(nameof(container)); _components = components == null ? new List<IBaseGameComponent>() : new List<IBaseGameComponent>(components); } /// <summary> /// Gets the <see cref="IBaseGameComponentContainer"/> associated with this instance. /// </summary> [NotNull] public IBaseGameComponentContainer Container { get; } public IEnumerator<IBaseGameComponent> GetEnumerator() { return new Enumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// Suspends the update process. /// </summary> public void SuspendUpdate() { _updateSuspended = true; } /// <summary> /// Resumes the update process. /// </summary> public void ResumeUpdate() { _updateSuspended = false; if (_activeEnumeratorCount == 0) { ExecutePendingQueue(); } } public void Add(IBaseGameComponent item) { EnsureNotReadOnly(); if (HasActiveEnumerators || _updateSuspended) { var entry = new PendingEntry { Operation = Operation.Add, Item = item }; _pendingQueue.Enqueue(entry); } else { if (!_components.Contains(item)) { _components.Add(item); } } } public void Clear() { EnsureNotReadOnly(); if (HasActiveEnumerators || _updateSuspended) { var entry = new PendingEntry { Operation = Operation.Clear }; _pendingQueue.Enqueue(entry); } else { _components.Clear(); } } public bool Contains(IBaseGameComponent item) { return _components.Contains(item); } public void CopyTo(IBaseGameComponent[] array, int arrayIndex) { _components.CopyTo(array, arrayIndex); } public bool Remove(IBaseGameComponent item) { EnsureNotReadOnly(); if (HasActiveEnumerators || _updateSuspended) { var canBeDeleted = ValidateComponentDeletion(item); if (canBeDeleted) { var entry = new PendingEntry { Operation = Operation.Remove, Item = item }; _pendingQueue.Enqueue(entry); } return canBeDeleted; } else { return _components.Remove(item); } } public int Count => _components.Count; public bool IsReadOnly { get; set; } public int IndexOf(IBaseGameComponent item) { return _components.IndexOf(item); } public void Insert(int index, IBaseGameComponent item) { EnsureNotReadOnly(); if (HasActiveEnumerators || _updateSuspended) { var entry = new PendingEntry { Operation = Operation.Insert, Index = index, Item = item }; _pendingQueue.Enqueue(entry); } else { var lastIndex = _components.IndexOf(item); if (lastIndex < 0) { _components.Insert(index, item); } else { if (lastIndex < index) { --index; } _components.RemoveAt(lastIndex); _components.Insert(index, item); } } } public void RemoveAt(int index) { EnsureNotReadOnly(); if (HasActiveEnumerators || _updateSuspended) { var entry = new PendingEntry { Operation = Operation.RemoveAt, Index = index }; _pendingQueue.Enqueue(entry); } else { _components.RemoveAt(index); } } public IBaseGameComponent this[int index] { get => _components[index]; set => _components[index] = value; } public override string ToString() { var baseString = base.ToString(); var c1 = _components.Count; var c2 = _pendingQueue.Count; return $"{baseString} (Count = {c1}, Pending = {c2})"; } /// <summary> /// Gets a <see cref="bool"/> indicating whether there are pending entries in the update queue. /// </summary> public bool HasPendingEntries => _pendingQueue.Count > 0; /// <summary> /// Executes pending queue and updates the collection. /// </summary> public void ExecutePendingQueue() { if (!HasPendingEntries) { return; } if (_activeEnumeratorCount > 0 || _updateSuspended) { return; } ExecutePendingQueue(_components, _pendingQueue); } private static IList<IBaseGameComponent> ExecutePendingQueue(IList<IBaseGameComponent> c, Queue<PendingEntry> q) { while (q.Count > 0) { var entry = q.Dequeue(); switch (entry.Operation) { case Operation.Add: if (!c.Contains(entry.Item)) { c.Add(entry.Item); } break; case Operation.Insert: { var index = entry.Index; var item = entry.Item; var lastIndex = c.IndexOf(item); if (lastIndex < 0) { c.Insert(index, item); } else { if (lastIndex < index) { --index; } c.RemoveAt(lastIndex); c.Insert(index, item); } break; } case Operation.Remove: c.Remove(entry.Item); break; case Operation.RemoveAt: c.RemoveAt(entry.Index); break; case Operation.Clear: c.Clear(); break; default: throw new ArgumentOutOfRangeException(); } } return c; } private bool ValidateComponentDeletion([CanBeNull] IBaseGameComponent item) { if (!HasPendingEntries) { return _components.Contains(item); } IList<IBaseGameComponent> c = new List<IBaseGameComponent>(_components); var q = new Queue<PendingEntry>(_pendingQueue); c = ExecutePendingQueue(c, q); return c.Contains(item); } private void EnsureNotReadOnly() { if (IsReadOnly) { throw new InvalidOperationException("You cannot apply this operation when ComponentCollection is read-only."); } } private bool HasActiveEnumerators => _activeEnumeratorCount > 0; private readonly IList<IBaseGameComponent> _components; private int _activeEnumeratorCount; private readonly Queue<PendingEntry> _pendingQueue = new Queue<PendingEntry>(); private readonly SimpleUsingLock _enumeratorLock = new SimpleUsingLock(); private bool _updateSuspended; } }
/* * This file is part of UniERM ReportDesigner, based on reportFU by Josh Wilson, * the work of Kim Sheffield and the fyiReporting project. * * Prior Copyrights: * _________________________________________________________ * |Copyright (C) 2010 devFU Pty Ltd, Josh Wilson and Others| * | (http://reportfu.org) | * ========================================================= * _________________________________________________________ * |Copyright (C) 2004-2008 fyiReporting Software, LLC | * |For additional information, email info@fyireporting.com | * |or visit the website www.fyiReporting.com. | * ========================================================= * * License: * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; using System.Xml; using System.Text; namespace Reporting.RdlDesign { /// <summary> /// Sorting specification /// </summary> internal class SortingCtl : System.Windows.Forms.UserControl, IProperty { private DesignXmlDraw _Draw; private XmlNode _SortingParent; private DataGridViewTextBoxColumn dgtbExpr; private DataGridViewCheckBoxColumn dgtbDir; private System.Windows.Forms.Button bDelete; private System.Windows.Forms.Button bUp; private System.Windows.Forms.Button bDown; private System.Windows.Forms.DataGridView dgSorting; private System.Windows.Forms.Button bValueExpr; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; internal SortingCtl(DesignXmlDraw dxDraw, XmlNode sortingParent) { _Draw = dxDraw; _SortingParent = sortingParent; // This call is required by the Windows.Forms Form Designer. InitializeComponent(); // Initialize form using the style node values InitValues(); } private void InitValues() { // Initialize the DataGrid columns dgtbExpr = new DataGridViewTextBoxColumn(); dgtbDir = new DataGridViewCheckBoxColumn(); dgSorting.Columns.Add(dgtbExpr); dgSorting.Columns.Add(dgtbDir); // // dgtbExpr // dgtbExpr.HeaderText = "Sort Expression"; dgtbExpr.Width = 240; // Get the parent's dataset name // string dataSetName = _Draw.GetDataSetNameValue(_SortingParent); // // string[] fields = _Draw.GetFields(dataSetName, true); // if (fields != null) // dgtbExpr.CB.Items.AddRange(fields); // // dgtbDir // dgtbDir.HeaderText = "Sort Ascending"; dgtbDir.Width = 90; XmlNode sorts = _Draw.GetNamedChildNode(_SortingParent, "Sorting"); if (sorts != null) foreach (XmlNode sNode in sorts.ChildNodes) { if (sNode.NodeType != XmlNodeType.Element || sNode.Name != "SortBy") continue; dgSorting.Rows.Add(_Draw.GetElementValue(sNode, "SortExpression", ""), _Draw.GetElementValue(sNode, "Direction", "Ascending") == "Ascending"); } if (dgSorting.Rows.Count == 0) dgSorting.Rows.Add("", true); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.dgSorting = new System.Windows.Forms.DataGridView(); this.bDelete = new System.Windows.Forms.Button(); this.bUp = new System.Windows.Forms.Button(); this.bDown = new System.Windows.Forms.Button(); this.bValueExpr = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.dgSorting)).BeginInit(); this.SuspendLayout(); // // dgSorting // this.dgSorting.Location = new System.Drawing.Point(8, 8); this.dgSorting.Name = "dgSorting"; this.dgSorting.Size = new System.Drawing.Size(376, 264); this.dgSorting.TabIndex = 0; // // bDelete // this.bDelete.Location = new System.Drawing.Point(392, 40); this.bDelete.Name = "bDelete"; this.bDelete.Size = new System.Drawing.Size(48, 23); this.bDelete.TabIndex = 2; this.bDelete.Text = "Delete"; this.bDelete.Click += new System.EventHandler(this.bDelete_Click); // // bUp // this.bUp.Location = new System.Drawing.Point(392, 72); this.bUp.Name = "bUp"; this.bUp.Size = new System.Drawing.Size(48, 23); this.bUp.TabIndex = 3; this.bUp.Text = "Up"; this.bUp.Click += new System.EventHandler(this.bUp_Click); // // bDown // this.bDown.Location = new System.Drawing.Point(392, 104); this.bDown.Name = "bDown"; this.bDown.Size = new System.Drawing.Size(48, 23); this.bDown.TabIndex = 4; this.bDown.Text = "Down"; this.bDown.Click += new System.EventHandler(this.bDown_Click); // // bValueExpr // this.bValueExpr.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bValueExpr.Location = new System.Drawing.Point(392, 8); this.bValueExpr.Name = "bValueExpr"; this.bValueExpr.Size = new System.Drawing.Size(24, 21); this.bValueExpr.TabIndex = 1; this.bValueExpr.Tag = "value"; this.bValueExpr.Text = "fx"; this.bValueExpr.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bValueExpr.Click += new System.EventHandler(this.bValueExpr_Click); // // SortingCtl // this.Controls.Add(this.bValueExpr); this.Controls.Add(this.bDown); this.Controls.Add(this.bUp); this.Controls.Add(this.bDelete); this.Controls.Add(this.dgSorting); this.Name = "SortingCtl"; this.Size = new System.Drawing.Size(488, 304); ((System.ComponentModel.ISupportInitialize)(this.dgSorting)).EndInit(); this.ResumeLayout(false); } #endregion public bool IsValid() { return true; } public void Apply() { // Remove the old filters XmlNode sorts = null; _Draw.RemoveElement(_SortingParent, "Sorting"); // Loop thru and add all the filters foreach (DataGridViewRow dr in dgSorting.Rows) { string expr = dr.Cells[0].Value as string; bool dir = dr.Cells[1].Value == null? true: (bool) dr.Cells[1].Value; if (expr == null || expr.Length <= 0) continue; if (sorts == null) sorts = _Draw.CreateElement(_SortingParent, "Sorting", null); XmlNode sNode = _Draw.CreateElement(sorts, "SortBy", null); _Draw.CreateElement(sNode, "SortExpression", expr); _Draw.CreateElement(sNode, "Direction", dir?"Ascending":"Descending"); } } private void bDelete_Click(object sender, System.EventArgs e) { if (dgSorting.CurrentRow == null) return; if (!dgSorting.Rows[dgSorting.CurrentRow.Index].IsNewRow) // can't delete the new row dgSorting.Rows.RemoveAt(this.dgSorting.CurrentRow.Index); else { // just empty out the values DataGridViewRow dgrv = dgSorting.Rows[this.dgSorting.CurrentRow.Index]; dgrv.Cells[0].Value = null; dgrv.Cells[1].Value = null; } } private void bUp_Click(object sender, System.EventArgs e) { int cr = dgSorting.CurrentRow == null ? 0 : dgSorting.CurrentRow.Index; if (cr <= 0) // already at the top return; SwapRow(dgSorting.Rows[cr - 1], dgSorting.Rows[cr]); dgSorting.CurrentCell = dgSorting.Rows[cr - 1].Cells[dgSorting.CurrentCell.ColumnIndex]; } private void bDown_Click(object sender, System.EventArgs e) { int cr = dgSorting.CurrentRow == null ? 0 : dgSorting.CurrentRow.Index; if (cr < 0) // invalid index return; if (cr + 1 >= dgSorting.Rows.Count) return; // already at end SwapRow(dgSorting.Rows[cr + 1], dgSorting.Rows[cr]); dgSorting.CurrentCell = dgSorting.Rows[cr + 1].Cells[dgSorting.CurrentCell.ColumnIndex]; } private void SwapRow(DataGridViewRow tdr, DataGridViewRow fdr) { // column 1 object save = tdr.Cells[0].Value; tdr.Cells[0].Value = fdr.Cells[0].Value; fdr.Cells[0].Value = save; // column 2 save = tdr.Cells[1].Value; tdr.Cells[1].Value = fdr.Cells[1].Value; fdr.Cells[1].Value = save; return; } private void bValueExpr_Click(object sender, System.EventArgs e) { if (dgSorting.CurrentCell == null) dgSorting.Rows.Add("",true); DataGridViewCell dgc = dgSorting.CurrentCell; int cc = dgc.ColumnIndex; // >>>>>>>>>> // the only column that should be edited is the first one ( "Sort expression" ) if (cc != 0) dgc = dgSorting.CurrentCell = dgSorting.CurrentRow.Cells[0]; // <<<<<<<<<< string cv = dgc.Value as string; using (DialogExprEditor ee = new DialogExprEditor(_Draw, cv, _SortingParent, false)) { DialogResult dlgr = ee.ShowDialog(); if (dlgr == DialogResult.OK) dgc.Value = ee.Expression; } } } }
// SPDX-License-Identifier: MIT // Copyright wtfsckgh@gmail.com // Copyright iced contributors using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using Generator.Constants; using Generator.Enums; using Generator.Tables; namespace Generator { /// <summary> /// Can be implemented by classes with a <see cref="TypeGenAttribute"/> /// </summary> interface ITypeGen { void Generate(GenTypes genTypes) { } void OnGenerated(GenTypes genTypes) { } } /// <summary> /// Can be implemented by classes with a <see cref="TypeGenAttribute"/> and if so, /// its priority must be &lt; <see cref="TypeGenOrders.CreatedInstructions"/> /// </summary> interface ICreatedInstructions { double Order => double.MaxValue; void OnCreatedInstructions(GenTypes genTypes, HashSet<EnumValue> filteredCodeValues); } sealed class GenTypes { readonly Dictionary<TypeId, EnumType> enums; readonly Dictionary<TypeId, ConstantsType> constants; readonly Dictionary<TypeId, object> objs; bool canGetCodeEnum; public GeneratorOptions Options { get; } public GeneratorDirs Dirs { get; } public GenTypes(GeneratorOptions options, GeneratorDirs dirs) { canGetCodeEnum = false; Options = options; Dirs = dirs; constants = new Dictionary<TypeId, ConstantsType>(); objs = new Dictionary<TypeId, object>(); var assembly = GetType().Assembly; enums = CreateEnumsDict(assembly); CallTypeGens(assembly); } static Dictionary<TypeId, EnumType> CreateEnumsDict(Assembly assembly) { var allTypeIds = typeof(TypeIds).GetFields().Select(a => (TypeId)a.GetValue(null)!).ToHashSet(); var enums = new Dictionary<TypeId, EnumType>(); foreach (var type in assembly.GetTypes()) { var ca = type.GetCustomAttribute<EnumAttribute>(false); if (ca is null) continue; if (!allTypeIds.Contains(ca.TypeId)) throw new InvalidOperationException(); allTypeIds.Remove(ca.TypeId); var flags = EnumTypeFlags.None; if (ca.Public) flags |= EnumTypeFlags.Public; if (ca.NoInitialize) flags |= EnumTypeFlags.NoInitialize; if (ca.Flags) flags |= EnumTypeFlags.Flags; var values = type.GetFields().Where(a => a.IsLiteral).Select(a => new EnumValue(GetValue(a.GetValue(null)), a.Name, CommentAttribute.GetDocumentation(a), DeprecatedAttribute.GetDeprecatedInfo(a))).ToArray(); var enumType = new EnumType(ca.Name, ca.TypeId, ca.Documentation, values, flags); enums.Add(ca.TypeId, enumType); } return enums; } static uint GetValue(object? value) { if (value is null) throw new InvalidOperationException(); return Type.GetTypeCode(value.GetType().GetEnumUnderlyingType()) switch { TypeCode.SByte => (uint)(sbyte)value, TypeCode.Byte => (byte)value, TypeCode.Int16 => (uint)(short)value, TypeCode.UInt16 => (ushort)value, TypeCode.Int32 => (uint)(int)value, TypeCode.UInt32 => (uint)value, _ => throw new InvalidOperationException(), }; } public EnumType this[TypeId id] { get { if (!enums.TryGetValue(id, out var enumType)) throw new InvalidOperationException($"Enum type {id} doesn't exist"); return enumType; } } public ConstantsType GetConstantsType(TypeId id) { if (!constants.TryGetValue(id, out var constantsType)) throw new InvalidOperationException($"Constants type {id} doesn't exist"); return constantsType; } void CallTypeGens(Assembly assembly) { var typeGens = new List<(Type type, TypeGenAttribute ca)>(); foreach (var type in assembly.GetTypes()) { var ca = type.GetCustomAttribute<TypeGenAttribute>(false); if (ca is null) continue; typeGens.Add((type, ca)); } typeGens.Sort((a, b) => { int c = a.ca.Order.CompareTo(b.ca.Order); if (c != 0) return c; Debug.Assert(a.type.FullName is not null); Debug.Assert(b.type.FullName is not null); return StringComparer.Ordinal.Compare(a.type.FullName, b.type.FullName); }); var created = new List<object>(); int index = 0; CallTypeGens(created, typeGens, ref index, order => order < TypeGenOrders.PreCreateInstructions); canGetCodeEnum = true; CallTypeGens(created, typeGens, ref index, order => order < TypeGenOrders.CreatedInstructions); var (origCodeValues, removedCodeHash, codeHash) = FilterCode(); AddObject(TypeIds.OrigCodeValues, origCodeValues); AddObject(TypeIds.RemovedCodeValues, removedCodeHash); foreach (var ci in created.OfType<ICreatedInstructions>().OrderBy(a => a.Order)) ci.OnCreatedInstructions(this, codeHash); int createdCount = created.Count; CallTypeGens(created, typeGens, ref index, order => true); for (int i = createdCount; i < created.Count; i++) { if (created[i] is ICreatedInstructions) throw new InvalidOperationException($"Can't impl {nameof(ICreatedInstructions)}, update the {nameof(TypeGenAttribute)} order"); } for (int i = 0; i < created.Count; i++) { if (created[i] is ITypeGen tg) tg.OnGenerated(this); } } void CallTypeGens(List<object> created, List<(Type type, TypeGenAttribute ca)> typeGens, ref int index, Func<double, bool> checkOrder) { for (; index < typeGens.Count; index++) { var typeGen = typeGens[index]; if (!checkOrder(typeGen.ca.Order)) break; var ctor = typeGen.type.GetTypeInfo().DeclaredConstructors.FirstOrDefault(c => c.GetParameters().Length == 1 && c.GetParameters()[0].ParameterType == typeof(GenTypes)); if (ctor is null) throw new InvalidOperationException($"{typeGen.type} needs a constructor with a {nameof(GenTypes)} argument"); var gen = ctor.Invoke(new object[] { this }); if (gen is null) throw new InvalidOperationException(); created.Add(gen); if (gen is ITypeGen tg) tg.Generate(this); } } (EnumValue[] origCodeValues, HashSet<EnumValue> removedCodeHash, HashSet<EnumValue> codeHash) FilterCode() { var defs = GetObject<InstructionDefs>(TypeIds.InstructionDefs).GetDefsPreFiltered(); var newCodeValues = new List<EnumValue>(); var removedCodeHash = new HashSet<EnumValue>(); foreach (var def in defs) { if (ShouldInclude(def)) newCodeValues.Add(def.Code); else removedCodeHash.Add(def.Code); } var code = this[TypeIds.Code]; var origCodeValues = code.Values.ToArray(); code.ResetValues(newCodeValues.ToArray()); return (origCodeValues, removedCodeHash, newCodeValues.ToHashSet()); } bool ShouldInclude(InstructionDef def) { switch (def.Encoding) { case EncodingKind.Legacy: break; case EncodingKind.VEX: if (!Options.IncludeVEX) return false; break; case EncodingKind.EVEX: if (!Options.IncludeEVEX) return false; break; case EncodingKind.XOP: if (!Options.IncludeXOP) return false; break; case EncodingKind.D3NOW: if (!Options.Include3DNow) return false; break; default: throw new InvalidOperationException(); } if (Options.IncludeCpuid.Count != 0) { foreach (var cpuid in def.Cpuid) { if (Options.IncludeCpuid.Contains(cpuid.RawName)) return true; } return false; } if (Options.ExcludeCpuid.Count != 0) { foreach (var cpuid in def.Cpuid) { if (Options.ExcludeCpuid.Contains(cpuid.RawName)) return false; } } return true; } public void Add(EnumType enumType) => enums.Add(enumType.TypeId, enumType); public void Add(ConstantsType constantsType) => constants.Add(constantsType.TypeId, constantsType); public void AddObject(TypeId id, object obj) => objs.Add(id, obj); public T GetObject<T>(TypeId id) { if (!canGetCodeEnum && id == TypeIds.Code) throw new InvalidOperationException($"Can't read Code value yet. Update the class' {nameof(TypeGenAttribute)} order"); if (objs.TryGetValue(id, out var obj)) { if (obj is T t) return t; throw new InvalidOperationException($"{id} is not a {typeof(T).FullName}"); } throw new InvalidOperationException($"{id} doesn't exist"); } public EnumValue[] GetKeptCodeValues(params Code[] values) { var origCode = GetObject<EnumValue[]>(TypeIds.OrigCodeValues); var removed = GetObject<HashSet<EnumValue>>(TypeIds.RemovedCodeValues); return values.Select(a => origCode[(int)a]).Where(a => !removed.Contains(a)).ToArray(); } } }
// (c) Copyright 2012 Hewlett-Packard Development Company, L.P. // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Threading; using HpToolsLauncher.Properties; using Mercury.TD.Client.Ota.QC9; //using Mercury.TD.Client.Ota.Api; namespace HpToolsLauncher { public class AlmTestSetsRunner : RunnerBase, IDisposable { QcRunMode m_runMode = QcRunMode.RUN_LOCAL; double m_timeout = -1; bool m_blnConnected = false; ITDConnection2 tdConnection = null; List<string> colTestSets = new List<string>(); string m_runHost = null; string m_qcServer = null; string m_qcUser = null; string m_qcProject = null; string m_qcDomain = null; public bool Connected { get { return m_blnConnected; } set { m_blnConnected = value; } } public List<string> TestSets { get { return colTestSets; } set { colTestSets = value; } } public QcRunMode RunMode { get { return m_runMode; } set { m_runMode = value; } } public double Timeout { get { return m_timeout; } set { m_timeout = value; } } public string RunHost { get { return m_runHost; } set { m_runHost = value; } } public ITDConnection2 TdConnection { get { if (tdConnection == null) CreateTdConnection(); return tdConnection; } set { tdConnection = value; } } /// <summary> /// constructor /// </summary> /// <param name="qcServer"></param> /// <param name="qcUser"></param> /// <param name="qcPassword"></param> /// <param name="qcDomain"></param> /// <param name="qcProject"></param> /// <param name="intQcTimeout"></param> /// <param name="enmQcRunMode"></param> /// <param name="runHost"></param> /// <param name="qcTestSets"></param> public AlmTestSetsRunner(string qcServer, string qcUser, string qcPassword, string qcDomain, string qcProject, double intQcTimeout, QcRunMode enmQcRunMode, string runHost, List<string> qcTestSets) { Timeout = intQcTimeout; RunMode = enmQcRunMode; RunHost = runHost; m_qcServer = qcServer; m_qcUser = qcUser; m_qcProject = qcProject; m_qcDomain = qcDomain; Connected = ConnectToProject(qcServer, qcUser, qcPassword, qcDomain, qcProject); TestSets = qcTestSets; if (!Connected) { Environment.Exit((int)Launcher.ExitCodeEnum.Failed); } } /// <summary> /// destructor - ensures dispose of connection /// </summary> ~AlmTestSetsRunner() { Dispose(false); } /// <summary> /// runs the tests given to the object. /// </summary> /// <returns></returns> public override TestSuiteRunResults Run() { if (!Connected) return null; TestSuiteRunResults activeRunDesc = new TestSuiteRunResults(); //find all the testSets under if given some folders in our list try { FindAllTestSetsUnderFolders(); } catch (Exception ex) { ConsoleWriter.WriteErrLine(string.Format(Resources.AlmRunnerErrorBadQcInstallation, ex.Message, ex.StackTrace)); return null; } //run all the TestSets foreach (string testset in TestSets) { string testset1 = testset.TrimEnd("\\".ToCharArray()); int pos = testset1.LastIndexOf('\\'); string tsDir = ""; string tsName = testset1; if (pos != -1) { tsDir = testset1.Substring(0, pos).Trim("\\".ToCharArray()); tsName = testset1.Substring(pos, testset1.Length - pos).Trim("\\".ToCharArray()); } TestSuiteRunResults desc = RunTestSet(tsDir, tsName, Timeout, RunMode, RunHost); if (desc != null) activeRunDesc.AppendResults(desc); } return activeRunDesc; } /// <summary> /// creats a connection to Qc /// </summary> private void CreateTdConnection() { Type type = Type.GetTypeFromProgID("TDApiOle80.TDConnection"); if (type == null) { ConsoleWriter.WriteLine(GetAlmNotInstalledError()); Environment.Exit((int)Launcher.ExitCodeEnum.Failed); } try { object conn = Activator.CreateInstance(type); this.tdConnection = conn as ITDConnection2; } catch (FileNotFoundException ex) { ConsoleWriter.WriteLine(GetAlmNotInstalledError()); Environment.Exit((int)Launcher.ExitCodeEnum.Failed); } } /// <summary> /// finds all folders in the TestSet list, scans their tree and adds all sets under the given folders /// updates the TestSets by expanding the folders, and removing them, so only Test sets remain in the collection /// </summary> private void FindAllTestSetsUnderFolders() { List<string> extraSetsList = new List<string>(); List<string> removeSetsList = new List<string>(); var tsTreeManager = (ITestSetTreeManager)tdConnection.TestSetTreeManager; //go over all the testsets / testSetFolders and check which is which foreach (string testsetOrFolder in TestSets) { //try getting the folder ITestSetFolder tsFolder = GetFolder("Root\\" + testsetOrFolder.TrimEnd("\\".ToCharArray())); //if it exists it's a folder and should be traversed to find all sets if (tsFolder != null) { removeSetsList.Add(testsetOrFolder); List<string> setList = GetAllTestSetsFromDirTree(tsFolder); extraSetsList.AddRange(setList); } } TestSets.RemoveAll((a) => removeSetsList.Contains(a)); TestSets.AddRange(extraSetsList); } /// <summary> /// recursively find all testsets in the qc directory tree, starting from a given folder /// </summary> /// <param name="tsFolder"></param> /// <param name="tsTreeManager"></param> /// <returns></returns> private List<string> GetAllTestSetsFromDirTree(ITestSetFolder tsFolder) { List<string> retVal = new List<string>(); List children = tsFolder.FindChildren(""); List testSets = tsFolder.FindTestSets(""); if (testSets != null) { foreach (ITestSet childSet in testSets) { string tsPath = childSet.TestSetFolder.Path; tsPath = tsPath.Substring(5).Trim("\\".ToCharArray()); string tsFullPath = tsPath + "\\" + childSet.Name; retVal.Add(tsFullPath.TrimEnd()); } } if (children != null) { foreach (ITestSetFolder childFolder in children) { GetAllTestSetsFromDirTree(childFolder); } } return retVal; } /// <summary> /// get a QC folder /// </summary> /// <param name="testset"></param> /// <returns>the folder object</returns> private ITestSetFolder GetFolder(string testset) { var tsTreeManager = (ITestSetTreeManager)tdConnection.TestSetTreeManager; ITestSetFolder tsFolder = null; try { tsFolder = (ITestSetFolder)tsTreeManager.get_NodeByPath(testset); } catch (Exception ex) { return null; } return tsFolder; } /// <summary> /// gets test index given it's name /// </summary> /// <param name="strName"></param> /// <param name="results"></param> /// <returns></returns> public int GetIdxByTestName(string strName, TestSuiteRunResults results) { TestRunResults res = null; int retVal = -1; for (int i = 0; i < results.TestRuns.Count(); ++i) { res = results.TestRuns[i]; if (res != null && res.TestName == strName) { retVal = i; break; } } return retVal; } /// <summary> /// returns a description of the failure /// </summary> /// <param name="p_Test"></param> /// <returns></returns> private string GenerateFailedLog(IRun p_Test) { try { StepFactory sf = p_Test.StepFactory as StepFactory; if (sf == null) return ""; IList stepList = sf.NewList("") as IList; if (stepList == null) return ""; //var stList = p_Test.StepFactory.NewList(""); //string l_szReturn = ""; string l_szFailedMessage = ""; //' loop on each step in the steps foreach (IStep s in stepList) { if (s.Status == "Failed") l_szFailedMessage += s["ST_DESCRIPTION"] + "'\n\r"; } return l_szFailedMessage; } catch { return ""; } } /// <summary> /// writes a summary of the test run after it's over /// </summary> /// <param name="prevTest"></param> private string GetTestInstancesString(ITestSet set) { string retVal = ""; try { TSTestFactory factory = set.TSTestFactory; List list = factory.NewList(""); if (list == null) return ""; foreach (ITSTest testInstance in list) { retVal += testInstance.ID + ","; } retVal.TrimEnd(", \n".ToCharArray()); } catch (Exception ex) { } return retVal; } /// <summary> /// runs a test set with given parameters (and a valid connection to the QC server) /// </summary> /// <param name="tsFolderName">testSet folder name</param> /// <param name="tsName">testSet name</param> /// <param name="timeout">-1 for unlimited, or number of miliseconds</param> /// <param name="runMode">run on LocalMachine or remote</param> /// <param name="runHost">if run on remote machine - remote machine name</param> /// <returns></returns> public TestSuiteRunResults RunTestSet(string tsFolderName, string tsName, double timeout, QcRunMode runMode, string runHost) { string currentTestSetInstances = ""; TestSuiteRunResults runDesc = new TestSuiteRunResults(); TestRunResults activeTestDesc = null; var tsFactory = tdConnection.TestSetFactory; var tsTreeManager = (ITestSetTreeManager)tdConnection.TestSetTreeManager; List tsList = null; string tsPath = "Root\\" + tsFolderName; ITestSetFolder tsFolder = null; bool isTestPath = false; string testName = ""; string testSuiteName = tsName; try { tsFolder = (ITestSetFolder)tsTreeManager.get_NodeByPath(tsPath); isTestPath = false; } catch (COMException ex) { //not found tsFolder = null; } // test set not found, try to find specific test by path if(tsFolder == null) { // if test set path was not found, the path may points to specific test // remove the test name and try find test set with parent path try { int pos = tsPath.LastIndexOf("\\") + 1; testName = testSuiteName; testSuiteName = tsPath.Substring(pos, tsPath.Length - pos); tsPath = tsPath.Substring(0, pos - 1); tsFolder = (ITestSetFolder)tsTreeManager.get_NodeByPath(tsPath); isTestPath = true; } catch (COMException ex) { tsFolder = null; } } if (tsFolder == null) { //node wasn't found, folder = null ConsoleWriter.WriteErrLine(string.Format(Resources.AlmRunnerNoSuchFolder, tsFolder)); //this will make sure run will fail at the end. (since there was an error) Launcher.ExitCode = Launcher.ExitCodeEnum.Failed; return null; } else { tsList = tsFolder.FindTestSets(testSuiteName); } if (tsList == null) { ConsoleWriter.WriteLine(string.Format(Resources.AlmRunnerCantFindTest, testSuiteName)); //this will make sure run will fail at the end. (since there was an error) Launcher.ExitCode = Launcher.ExitCodeEnum.Failed; return null; } ITestSet targetTestSet = null; foreach (ITestSet ts in tsList) { string tempName = ts.Name; if (tempName.Equals(testSuiteName, StringComparison.InvariantCultureIgnoreCase)) { targetTestSet = ts; break; } } if (targetTestSet == null) { ConsoleWriter.WriteLine(string.Format(Resources.AlmRunnerCantFindTest, testSuiteName)); //this will make sure run will fail at the end. (since there was an error) Launcher.ExitCode = Launcher.ExitCodeEnum.Failed; return null; } ConsoleWriter.WriteLine(Resources.GeneralDoubleSeperator); ConsoleWriter.WriteLine(Resources.AlmRunnerStartingExecution); ConsoleWriter.WriteLine(string.Format(Resources.AlmRunnerDisplayTest, testSuiteName, targetTestSet.ID)); ITSScheduler Scheduler = null; try { //need to run this to install everything needed http://AlmServer:8080/qcbin/start_a.jsp?common=true //start the scheduler Scheduler = targetTestSet.StartExecution(""); } catch (Exception ex) { Scheduler = null; } try { currentTestSetInstances = GetTestInstancesString(targetTestSet); } catch (Exception ex) { } if (Scheduler == null) { Console.WriteLine(GetAlmNotInstalledError()); //proceeding with program execution is tasteless, since nothing will run without a properly installed QC. Environment.Exit((int)Launcher.ExitCodeEnum.Failed); } TSTestFactory tsTestFactory = targetTestSet.TSTestFactory; ITDFilter2 tdFilter = tsTestFactory.Filter; tdFilter["TC_CYCLE_ID"] = targetTestSet.ID.ToString(); IList tList = tsTestFactory.NewList(tdFilter.Text); if (isTestPath) { // index starts from 1 !!! int tListCount = 0; tListCount = tList.Count; // must loop from end to begin for (int index = tListCount; index > 0; index--) { string tListIndexName = tList[index].Name; string tListIndexTestName = tList[index].TestName; if (!string.IsNullOrEmpty(tListIndexName) && !string.IsNullOrEmpty(testName) && !testName.Equals(tListIndexName)) { tList.Remove(index); } } } try { //set up for the run depending on where the test instances are to execute switch (runMode) { case QcRunMode.RUN_LOCAL: // run all tests on the local machine Scheduler.RunAllLocally = true; break; case QcRunMode.RUN_REMOTE: // run tests on a specified remote machine Scheduler.TdHostName = runHost; break; // RunAllLocally must not be set for remote invocation of tests. As such, do not do this: Scheduler.RunAllLocally = False case QcRunMode.RUN_PLANNED_HOST: // run on the hosts as planned in the test set Scheduler.RunAllLocally = false; break; } } catch (Exception ex) { ConsoleWriter.WriteLine(string.Format(Resources.AlmRunnerProblemWithHost, ex.Message)); } ConsoleWriter.WriteLine(Resources.AlmRunnerNumTests + tList.Count); int i = 1; foreach (ITSTest3 test in tList) { string runOnHost = runHost; if (runMode == QcRunMode.RUN_PLANNED_HOST) runOnHost = test.HostName; //if host isn't taken from QC (PLANNED) and not from the test definition (REMOTE), take it from LOCAL (machineName) string hostName = runOnHost; if (runMode == QcRunMode.RUN_LOCAL) { hostName = Environment.MachineName; } ConsoleWriter.WriteLine(string.Format(Resources.AlmRunnerDisplayTestRunOnHost, i, test.Name, hostName)); Scheduler.RunOnHost[test.ID] = runOnHost; var testResults = new TestRunResults(); testResults.TestName = test.Name; runDesc.TestRuns.Add(testResults); i = i + 1; } if (tList.Count == 0) { ConsoleWriter.WriteErrLine("Specified test not found on ALM, please check your test path."); //this will make sure run will fail at the end. (since there was an error) Launcher.ExitCode = Launcher.ExitCodeEnum.Failed; return null; } Stopwatch sw = Stopwatch.StartNew(); try { //tests are actually run Scheduler.Run(tList); } catch (Exception ex) { ConsoleWriter.WriteLine(Resources.AlmRunnerRunError + ex.Message); } ConsoleWriter.WriteLine(Resources.AlmRunnerSchedStarted + DateTime.Now.ToString(Launcher.DateFormat)); ConsoleWriter.WriteLine(Resources.SingleSeperator); IExecutionStatus executionStatus = Scheduler.ExecutionStatus; bool tsExecutionFinished = false; ITSTest prevTest = null; ITSTest currentTest = null; string abortFilename = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\stop" + Launcher.UniqueTimeStamp + ".txt"; //wait for the tests to end ("normally" or because of the timeout) while ((tsExecutionFinished == false) && (timeout == -1 || sw.Elapsed.TotalSeconds < timeout)) { executionStatus.RefreshExecStatusInfo("all", true); tsExecutionFinished = executionStatus.Finished; if (System.IO.File.Exists(abortFilename)) { break; } for (int j = 1; j <= executionStatus.Count; ++j) { TestExecStatus testExecStatusObj = executionStatus[j]; currentTest = targetTestSet.TSTestFactory[testExecStatusObj.TSTestId]; if (currentTest == null) { ConsoleWriter.WriteLine(string.Format("currentTest is null for test.{0} during execution", j)); continue; } activeTestDesc = UpdateTestStatus(runDesc, targetTestSet, testExecStatusObj, true); if (activeTestDesc.PrevTestState != activeTestDesc.TestState) { TestState tstate = activeTestDesc.TestState; if (tstate == TestState.Running) { //currentTest = targetTestSet.TSTestFactory[testExecStatusObj.TSTestId]; int testIndex = GetIdxByTestName(currentTest.Name, runDesc); int prevRunId = GetTestRunId(currentTest); runDesc.TestRuns[testIndex].PrevRunId = prevRunId; //closing previous test if (prevTest != null) { WriteTestRunSummary(prevTest); } //starting new test prevTest = currentTest; //assign the new test the consol writer so it will gather the output ConsoleWriter.ActiveTestRun = runDesc.TestRuns[testIndex]; ConsoleWriter.WriteLine(DateTime.Now.ToString(Launcher.DateFormat) + " Running: " + currentTest.Name); //tell user that the test is running ConsoleWriter.WriteLine(DateTime.Now.ToString(Launcher.DateFormat) + " Running test: " + activeTestDesc.TestName + ", Test id: " + testExecStatusObj.TestId + ", Test instance id: " + testExecStatusObj.TSTestId); //start timing the new test run string foldername = ""; ITestSetFolder folder = targetTestSet.TestSetFolder as ITestSetFolder; if (folder != null) foldername = folder.Name.Replace(".", "_"); //the test group is it's test set. (dots are problematic since jenkins parses them as seperators between packadge and class) activeTestDesc.TestGroup = foldername + "\\" + targetTestSet.Name; activeTestDesc.TestGroup = activeTestDesc.TestGroup.Replace(".", "_"); } TestState enmState = GetTsStateFromQcState(testExecStatusObj.Status as string); string statusString = enmState.ToString(); if (enmState == TestState.Running) { ConsoleWriter.WriteLine(string.Format(Resources.AlmRunnerStat, activeTestDesc.TestName, testExecStatusObj.TSTestId, statusString)); } else if (enmState != TestState.Waiting) { ConsoleWriter.WriteLine(string.Format(Resources.AlmRunnerStatWithMessage, activeTestDesc.TestName, testExecStatusObj.TSTestId, statusString, testExecStatusObj.Message)); } if (System.IO.File.Exists(abortFilename)) { break; } } } //wait 0.2 seconds Thread.Sleep(200); //check for abortion if (System.IO.File.Exists(abortFilename)) { _blnRunCancelled = true; ConsoleWriter.WriteLine(Resources.GeneralStopAborted); //stop all test instances in this testSet. Scheduler.Stop(currentTestSetInstances); ConsoleWriter.WriteLine(Resources.GeneralAbortedByUser); //stop working Environment.Exit((int)Launcher.ExitCodeEnum.Aborted); } } //check status for each test if (timeout == -1 || sw.Elapsed.TotalSeconds < timeout) { //close last test if (prevTest != null) { WriteTestRunSummary(prevTest); } //done with all tests, stop collecting output in the testRun object. ConsoleWriter.ActiveTestRun = null; for (int k = 1; k <= executionStatus.Count; ++k) { if (System.IO.File.Exists(abortFilename)) { break; } TestExecStatus testExecStatusObj = executionStatus[k]; currentTest = targetTestSet.TSTestFactory[testExecStatusObj.TSTestId]; if (currentTest == null) { ConsoleWriter.WriteLine(string.Format("currentTest is null for test.{0} after whole execution", k)); continue; } activeTestDesc = UpdateTestStatus(runDesc, targetTestSet, testExecStatusObj, false); UpdateCounters(activeTestDesc, runDesc); //currentTest = targetTestSet.TSTestFactory[testExecStatusObj.TSTestId]; string testPath = "Root\\" + tsFolderName + "\\" + testSuiteName + "\\" + activeTestDesc.TestName; activeTestDesc.TestPath = testPath; } //update the total runtime runDesc.TotalRunTime = sw.Elapsed; ConsoleWriter.WriteLine(string.Format(Resources.AlmRunnerTestsetDone, testSuiteName, DateTime.Now.ToString(Launcher.DateFormat))); } else { _blnRunCancelled = true; ConsoleWriter.WriteLine(Resources.GeneralTimedOut); Launcher.ExitCode = Launcher.ExitCodeEnum.Aborted; } return runDesc; } /// <summary> /// writes a summary of the test run after it's over /// </summary> /// <param name="prevTest"></param> private void WriteTestRunSummary(ITSTest prevTest) { int prevRunId = ConsoleWriter.ActiveTestRun.PrevRunId; int runid = GetTestRunId(prevTest); if (runid > prevRunId) { string stepsString = GetTestStepsDescFromQc(prevTest); if (string.IsNullOrWhiteSpace(stepsString) && ConsoleWriter.ActiveTestRun.TestState != TestState.Error) stepsString = GetTestRunLog(prevTest); if (!string.IsNullOrWhiteSpace(stepsString)) ConsoleWriter.WriteLine(stepsString); string linkStr = GetTestRunLink(prevTest, runid); ConsoleWriter.WriteLine("\n" + string.Format(Resources.AlmRunnerDisplayLink, linkStr)); } ConsoleWriter.WriteLine(DateTime.Now.ToString(Launcher.DateFormat) + " " + Resources.AlmRunnerTestCompleteCaption + " " + prevTest.Name + ((runid > prevRunId) ? ", " + Resources.AlmRunnerRunIdCaption + " " + runid : "") + "\n-------------------------------------------------------------------------------------------------------"); } /// <summary> /// gets a link string for the test run in Qc /// </summary> /// <param name="prevTest"></param> /// <param name="runid"></param> /// <returns></returns> private string GetTestRunLink(ITSTest prevTest, int runid) { bool oldQc = CheckIsOldQc(); bool useSSL = (m_qcServer.Contains("https://")); ITestSet set = prevTest.TestSet; string testRunLink = useSSL ? ("tds://" + m_qcProject + "." + m_qcDomain + "." + m_qcServer.Replace("https://", "") + "/TestLabModule-000000003649890581?EntityType=IRun&EntityID=" + runid) : ("td://" + m_qcProject + "." + m_qcDomain + "." + m_qcServer.Replace("http://", "") + "/TestLabModule-000000003649890581?EntityType=IRun&EntityID=" + runid); string testRunLinkQc10 = useSSL ? ("tds://" + m_qcProject + "." + m_qcDomain + "." + m_qcServer.Replace("https://", "") + "/Test%20Lab?Action=FindRun&TestSetID=" + set.ID + "&TestInstanceID=" + prevTest.ID + "&RunID=" + runid) : ("td://" + m_qcProject + "." + m_qcDomain + "." + m_qcServer.Replace("http://", "") + "/Test%20Lab?Action=FindRun&TestSetID=" + set.ID + "&TestInstanceID=" + prevTest.ID + "&RunID=" + runid); string linkStr = (oldQc ? testRunLinkQc10 : testRunLink); return linkStr; } private string GetAlmNotInstalledError() { return "Could not create scheduler, please verify ALM client installation on run machine by downloading and in installing the add-in form: " + GetQcCommonInstallationURl(m_qcServer); } /// <summary> /// summerizes test steps after test has run /// </summary> /// <param name="test"></param> /// <returns>a string containing descriptions of step states and messags</returns> string GetTestStepsDescFromQc(ITSTest test) { StringBuilder sb = new StringBuilder(); try { //get runs for the test RunFactory rfactory = test.RunFactory; List runs = rfactory.NewList(""); if (runs.Count == 0) return ""; //get steps from run StepFactory stepFact = runs[runs.Count].StepFactory; List steps = stepFact.NewList(""); if (steps.Count == 0) return ""; //go over steps and format a string foreach (IStep step in steps) { sb.Append("Step: " + step.Name); if (!string.IsNullOrWhiteSpace(step.Status)) sb.Append(", Status: " + step.Status); string desc = step["ST_DESCRIPTION"] as string; if (!string.IsNullOrEmpty(desc)) { desc = "\n\t" + desc.Trim().Replace("\n", "\t").Replace("\r", ""); if (!string.IsNullOrWhiteSpace(desc)) sb.AppendLine(desc); } } } catch (Exception ex) { sb.AppendLine("Exception while reading step data: " + ex.Message); } return sb.ToString().TrimEnd(); } private void UpdateCounters(TestRunResults test, TestSuiteRunResults testSuite) { if (test.TestState != TestState.Running && test.TestState != TestState.Waiting && test.TestState != TestState.Unknown) ++testSuite.NumTests; if (test.TestState == TestState.Failed) ++testSuite.NumFailures; if (test.TestState == TestState.Error) ++testSuite.NumErrors; } /// <summary> /// translate the qc states into a state enum /// </summary> /// <param name="qcTestStatus"></param> /// <returns></returns> private TestState GetTsStateFromQcState(string qcTestStatus) { if (qcTestStatus == null) return TestState.Unknown; switch (qcTestStatus) { case "Waiting": return TestState.Waiting; case "Error": return TestState.Error; case "No Run": return TestState.NoRun; case "Running": case "Connecting": return TestState.Running; case "Success": case "Finished": case "FinishedPassed": return TestState.Passed; case "FinishedFailed": return TestState.Failed; } return TestState.Unknown; } /// <summary> /// updates the test status in our list of tests /// </summary> /// <param name="targetTestSet"></param> /// <param name="testExecStatusObj"></param> private TestRunResults UpdateTestStatus(TestSuiteRunResults runResults, ITestSet targetTestSet, TestExecStatus testExecStatusObj, bool onlyUpdateState) { TestRunResults qTest = null; ITSTest currentTest = null; try { //find the test for the given status object currentTest = targetTestSet.TSTestFactory[testExecStatusObj.TSTestId]; if (currentTest == null) { return qTest; } //find the test in our list int testIndex = GetIdxByTestName(currentTest.Name, runResults); qTest = runResults.TestRuns[testIndex]; if (qTest.TestType == null) { qTest.TestType = GetTestType(currentTest); } //update the state qTest.PrevTestState = qTest.TestState; qTest.TestState = GetTsStateFromQcState(testExecStatusObj.Status); if (!onlyUpdateState) { try { //duration and status are updated according to the run qTest.Runtime = TimeSpan.FromSeconds(currentTest.LastRun.Field("RN_DURATION")); } catch { //a problem getting duration, maybe the test isn't done yet - don't stop the flow.. } switch (qTest.TestState) { case TestState.Failed: qTest.FailureDesc = GenerateFailedLog(currentTest.LastRun); if (string.IsNullOrWhiteSpace(qTest.FailureDesc)) qTest.FailureDesc = testExecStatusObj.Status + " : " + testExecStatusObj.Message; break; case TestState.Error: qTest.ErrorDesc = testExecStatusObj.Status + " : " + testExecStatusObj.Message; break; default: break; } //check qc version for link type bool oldQc = CheckIsOldQc(); //string testLink = "<a href=\"testdirector:mydtqc01.isr.hp.com:8080/qcbin," + m_qcProject + "," + m_qcDomain + "," + targetTestSet.Name+ ";test-instance:" + testExecStatusObj.TestInstance + "\"> Alm link</a>"; string serverURl = m_qcServer.TrimEnd("/".ToCharArray()); if (serverURl.ToLower().StartsWith("http://")) serverURl = serverURl.Substring(7); //string testLinkInLabQc10 = "td://" + m_qcProject + "." + m_qcDomain + "." + m_qcServer.Replace("http://", "") + "/Test%20Lab?Action=FindTestInstance&TestSetID=" + targetTestSet.ID + "&TestInstanceID=" + testExecStatusObj.TSTestId; //string testLinkInLab = "td://" + m_qcProject + "." + m_qcDomain + "." + m_qcServer.Replace("http://", "") + "/TestLabModule-000000003649890581?EntityType=ITestInstance&EntityID=" + testExecStatusObj.TSTestId; int runid = GetTestRunId(currentTest); string linkStr = GetTestRunLink(currentTest, runid); string statusString = GetTsStateFromQcState(testExecStatusObj.Status as string).ToString(); ConsoleWriter.WriteLine(string.Format(Resources.AlmRunnerTestStat, currentTest.Name, statusString, testExecStatusObj.Message, linkStr)); runResults.TestRuns[testIndex] = qTest; } } catch (Exception ex) { ConsoleWriter.WriteLine(string.Format(Resources.AlmRunnerErrorGettingStat, currentTest.Name, ex.Message)); } return qTest; } /// <summary> /// gets the runId for the given test /// </summary> /// <param name="currentTest">a test instance</param> /// <returns>the run id</returns> private static int GetTestRunId(ITSTest currentTest) { int runid = -1; IRun lastrun = currentTest.LastRun as IRun; if (lastrun != null) runid = lastrun.ID; return runid; } /// <summary> /// retrieves the run logs for the test when the steps are not reported to Qc (like in ST) /// </summary> /// <param name="currentTest"></param> /// <returns>the test run log</returns> private string GetTestRunLog(ITSTest currentTest) { string TestLog = "log\\vtd_user.log"; IRun lastrun = currentTest.LastRun as IRun; string retVal = ""; if (lastrun != null) { try { IExtendedStorage storage = lastrun.ExtendedStorage as IExtendedStorage; List list; bool wasFatalError; var path = storage.LoadEx(TestLog, true, out list, out wasFatalError); string logPath = Path.Combine(path, TestLog); if (File.Exists(logPath)) { retVal = File.ReadAllText(logPath).TrimEnd(); } } catch { retVal = ""; } } retVal = ConsoleWriter.FilterXmlProblematicChars(retVal); return retVal; } /// <summary> /// checks Qc version (used for link format, 10 and smaller is old) /// </summary> /// <returns>true if this QC is an old one</returns> private bool CheckIsOldQc() { string ver = null; int intver = -1; string build = null; TdConnection.GetTDVersion(out ver, out build); bool oldQc = false; if (ver != null) { int.TryParse(ver, out intver); if (intver <= 10) oldQc = true; } else { oldQc = true; } return oldQc; } /// <summary> /// gets the type for a QC test /// </summary> /// <param name="currentTest"></param> /// <returns></returns> private string GetTestType(dynamic currentTest) { string ttype = currentTest.Test.Type; if (ttype.ToUpper() == "SERVICE-TEST") { ttype = TestType.ST.ToString(); } else { ttype = TestType.QTP.ToString(); } return ttype; } /// <summary> /// connects to QC and logs in /// </summary> /// <param name="QCServerURL"></param> /// <param name="QCLogin"></param> /// <param name="QCPass"></param> /// <param name="QCDomain"></param> /// <param name="QCProject"></param> /// <returns></returns> public bool ConnectToProject(string QCServerURL, string QCLogin, string QCPass, string QCDomain, string QCProject) { if (string.IsNullOrWhiteSpace(QCServerURL) || string.IsNullOrWhiteSpace(QCLogin) || string.IsNullOrWhiteSpace(QCDomain) || string.IsNullOrWhiteSpace(QCProject)) { ConsoleWriter.WriteLine(Resources.AlmRunnerConnParamEmpty); return false; } try { TdConnection.InitConnectionEx(QCServerURL); } catch (Exception ex) { ConsoleWriter.WriteLine(ex.Message); } if (!TdConnection.Connected) { ConsoleWriter.WriteErrLine(string.Format(Resources.AlmRunnerServerUnreachable, QCServerURL)); return false; } try { TdConnection.Login(QCLogin, QCPass); } catch (Exception ex) { ConsoleWriter.WriteLine(ex.Message); } if (!TdConnection.LoggedIn) { ConsoleWriter.WriteErrLine(Resources.AlmRunnerErrorAuthorization); return false; } try { TdConnection.Connect(QCDomain, QCProject); } catch (Exception ex) { } if (!TdConnection.ProjectConnected) { ConsoleWriter.WriteErrLine(Resources.AlmRunnerErrorConnectToProj); return false; } return true; } private string GetQcCommonInstallationURl(string QCServerURL) { return QCServerURL + "/TDConnectivity_index.html"; } #region IDisposable Members public void Dispose(bool managed) { if (Connected) { tdConnection.Disconnect(); Marshal.ReleaseComObject(tdConnection); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion } public class QCFailure { public string Name { get; set; } public string Desc { get; set; } } public enum QcRunMode { RUN_LOCAL, RUN_REMOTE, RUN_PLANNED_HOST } }
/* * Copyright (C) Sony Computer Entertainment America LLC. * All Rights Reserved. */ using System; using System.Collections; using ActiproSoftware.SyntaxEditor; namespace Sce.Sled.SyntaxEditor.Intellisense.Lua.Parser { /// <summary> /// Represents a <c>Simple</c> lexical parser implementation. /// </summary> class LuatLexicalParser : IMergableLexicalParser { private Hashtable keywords = new Hashtable(); ///////////////////////////////////////////////////////////////////////////////////////////////////// // OBJECT ///////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Initializes a new instance of the <c>LuatLexicalParser</c> class. /// </summary> public LuatLexicalParser() { // Initialize keywords for (int index = (int)LuatTokenId.KeywordStart + 1; index < (int)LuatTokenId.KeywordEnd; index++) keywords.Add(LuatTokenId.GetTokenKey(index).ToLowerInvariant(), index); } ///////////////////////////////////////////////////////////////////////////////////////////////////// // PUBLIC PROCEDURES ///////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Returns a single-character <see cref="ITokenLexicalParseData"/> representing the lexical parse data for the /// default token in the <see cref="ILexicalState"/> and seeks forward one position in the <see cref="ITextBufferReader"/> /// </summary> /// <param name="reader">An <see cref="ITextBufferReader"/> that is reading a text source.</param> /// <param name="lexicalState">The <see cref="ILexicalState"/> that specifies the current context.</param> /// <returns>The <see cref="ITokenLexicalParseData"/> for default text in the <see cref="ILexicalState"/>.</returns> public ITokenLexicalParseData GetLexicalStateDefaultTokenLexicalParseData(ITextBufferReader reader, ILexicalState lexicalState) { reader.Read(); return new LexicalStateAndIDTokenLexicalParseData(lexicalState, (byte)lexicalState.DefaultTokenID); } /// <summary> /// Performs a lexical parse to return the next <see cref="ITokenLexicalParseData"/> /// from a <see cref="ITextBufferReader"/> and seeks past it if there is a match. /// </summary> /// <param name="reader">An <see cref="ITextBufferReader"/> that is reading a text source.</param> /// <param name="lexicalState">The <see cref="ILexicalState"/> that specifies the current context.</param> /// <param name="lexicalParseData">Returns the next <see cref="ITokenLexicalParseData"/> from a <see cref="ITextBufferReader"/>.</param> /// <returns>A <see cref="MatchType"/> indicating the type of match that was made.</returns> public MatchType GetNextTokenLexicalParseData(ITextBufferReader reader, ILexicalState lexicalState, ref ITokenLexicalParseData lexicalParseData) { // Initialize int tokenID = LuatTokenId.Invalid; if ( reader.IsAtEnd ) { lexicalParseData = new LexicalStateAndIDTokenLexicalParseData(lexicalState, (byte)LuatTokenId.DocumentEnd); return MatchType.ExactMatch; } // Get the next character char ch = reader.Read(); // If the character is a letter or digit... if ((Char.IsLetter(ch) || (ch == '_'))) { // Parse the identifier tokenID = this.ParseIdentifier(reader, ch); } else if ((ch != '\n') && (Char.IsWhiteSpace(ch))) { while ((reader.Peek() != '\n') && (Char.IsWhiteSpace(reader.Peek()))) reader.Read(); tokenID = LuatTokenId.Whitespace; } else { tokenID = LuatTokenId.Invalid; switch (ch) { case ',': tokenID = LuatTokenId.Comma; break; case '(': tokenID = LuatTokenId.OpenParenthesis; break; case ')': tokenID = LuatTokenId.CloseParenthesis; break; case ';': tokenID = LuatTokenId.SemiColon; break; case ':': tokenID = LuatTokenId.Colon; break; case '\n': case '\r': // Line terminator tokenID = LuatTokenId.LineTerminator; break; case '{': tokenID = LuatTokenId.OpenCurlyBrace; break; case '}': tokenID = LuatTokenId.CloseCurlyBrace; break; case '\"': tokenID = this.ParseString( reader, '\"' ); break; case '\'': tokenID = this.ParseString( reader, '\'' ); break; case '-': if ( reader.Peek(1) != '-' ) { tokenID = LuatTokenId.Subtraction; break; } reader.Read(); if ( reader.Peek(1) != '[' || reader.Peek(2) != '[' ) { tokenID = this.ParseSingleLineComment(reader); } else { reader.Read(); reader.Read(); tokenID = this.ParseMultiLineComment( reader ); } break; case '<': if (reader.Peek() == '=') { reader.Read(); tokenID = LuatTokenId.LessThanEqual; } else { tokenID = LuatTokenId.LessThan; } break; case '>': if (reader.Peek() == '=') { reader.Read(); tokenID = LuatTokenId.GreaterThanEqual; } else { tokenID = LuatTokenId.GreaterThan; } break; case '~': if (reader.Peek() == '=') { reader.Read(); tokenID = LuatTokenId.Inequality; } break; case '=': if (reader.Peek() == '=') { reader.Read(); tokenID = LuatTokenId.Equality; } else { tokenID = LuatTokenId.Assignment; } break; case '!': if (reader.Peek() == '=') { reader.Read(); tokenID = LuatTokenId.Inequality; } break; case '+': tokenID = LuatTokenId.Addition; break; case '/': tokenID = LuatTokenId.Division; break; case '*': tokenID = LuatTokenId.Multiplication; break; case '^': tokenID = LuatTokenId.Hat; break; case '#': tokenID = LuatTokenId.Hash; break; case '%': tokenID = LuatTokenId.Modulus; break; case '.': tokenID = LuatTokenId.Dot; if (reader.Peek() == '.') { reader.Read(); tokenID = LuatTokenId.DoubleDot; } if (reader.Peek() == '.') { reader.Read(); tokenID = LuatTokenId.TripleDot; } break; case '[': tokenID = LuatTokenId.OpenSquareBracket; break; case ']': tokenID = LuatTokenId.CloseSquareBracket; break; default: if ((ch >= '0') && (ch <= '9')) { // Parse the number tokenID = this.ParseNumber(reader, ch); } break; } } if (tokenID != LuatTokenId.Invalid) { lexicalParseData = new LexicalStateAndIDTokenLexicalParseData(lexicalState, (byte)tokenID); return MatchType.ExactMatch; } else { reader.ReadReverse(); return MatchType.NoMatch; } } /// <summary> /// Parses an identifier. /// </summary> /// <param name="reader">An <see cref="ITextBufferReader"/> that is reading a text source.</param> /// <param name="ch">The first character of the identifier.</param> /// <returns>The ID of the token that was matched.</returns> protected virtual int ParseIdentifier(ITextBufferReader reader, char ch) { // Get the entire word int startOffset = reader.Offset - 1; while (!reader.IsAtEnd) { // Accept namespaced identifiers if ( reader.Peek( 1 ) == ':' && reader.Peek( 2 ) == ':' && char.IsLetterOrDigit( reader.Peek( 3 ) ) ) { reader.Read(); reader.Read(); reader.Read(); continue; } char ch2 = reader.Read(); // NOTE: This could be improved by supporting \u escape sequences if ((!char.IsLetterOrDigit(ch2)) && (ch2 != '_')) { reader.ReadReverse(); break; } } // Determine if the word is a keyword if (Char.IsLetter(ch)) { object value = keywords[reader.GetSubstring(startOffset, reader.Offset - startOffset)]; if (value != null) return (int)value; else return LuatTokenId.Identifier; } else return LuatTokenId.Identifier; } /// <summary> /// Parses a multiple line comment. /// </summary> /// <param name="reader">An <see cref="ITextBufferReader"/> that is reading a text source.</param> /// <returns>The ID of the token that was matched.</returns> protected virtual int ParseMultiLineComment(ITextBufferReader reader) { while (reader.Offset + 2 < reader.Length) { if ( ( reader.Peek(1) == ']' && reader.Peek(2) == ']' ) ) { reader.Read(); reader.Read(); break; } reader.Read(); } return LuatTokenId.MultiLineComment; } /// <summary> /// Parses a number. /// </summary> /// <param name="reader">An <see cref="ITextBufferReader"/> that is reading a text source.</param> /// <param name="ch">The first character of the number.</param> /// <returns>The ID of the token that was matched.</returns> protected virtual int ParseNumber(ITextBufferReader reader, char ch) { Char c = reader.Peek(); bool bParsedDot = false; while (Char.IsNumber(c) || c == '.') { if (c == '.') { // Only handle a single '.' if (bParsedDot) { return LuatTokenId.Number; } bParsedDot = true; } reader.Read(); c = reader.Peek(); } return LuatTokenId.Number; } /// <summary> /// Parses a single line comment. /// </summary> /// <param name="reader">An <see cref="ITextBufferReader"/> that is reading a text source.</param> /// <returns>The ID of the token that was matched.</returns> protected virtual int ParseSingleLineComment(ITextBufferReader reader) { while ((!reader.IsAtEnd) && (reader.Peek() != '\n')) reader.Read(); return LuatTokenId.SingleLineComment; } /// <summary> /// Parses a string. /// </summary> /// <param name="reader">An <see cref="ITextBufferReader"/> that is reading a text source.</param> /// <returns>The ID of the token that was matched.</returns> protected virtual int ParseString(ITextBufferReader reader, char quote ) { Char c0 = '\0'; Char c1 = reader.Read(); while ( !( reader.IsAtEnd || ( c1 == quote && c0 != '\\' ) ) ) { c0 = c1; c1 = reader.Read(); } return LuatTokenId.String; } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Text; using System.Collections.Generic; using System.Diagnostics; using Microsoft.Win32; using System.Diagnostics.Contracts; namespace Tests { public class DisableAssertUI { static DisableAssertUI() { for (int i = 0; i < System.Diagnostics.Debug.Listeners.Count; i++) { System.Diagnostics.DefaultTraceListener dtl = System.Diagnostics.Debug.Listeners[i] as System.Diagnostics.DefaultTraceListener; if (dtl != null) dtl.AssertUiEnabled = false; } } } [TestClass] public class RewriterTest : DisableAssertUI{ #region Test Management [ClassInitialize] public static void ClassInitialize (TestContext context) { } [ClassCleanup] public static void ClassCleanup () { } [TestInitialize] public void TestInitialize () { } [TestCleanup] public void TestCleanup () { } #endregion Test Management #region Tests /// <summary> /// Runs PEVerify on the rewritten Tests.dll. /// </summary> [TestMethod] public void PEVerifyRewrittenTest() { string codebase = typeof(RewriterTest).Assembly.CodeBase; codebase = codebase.Replace("#", "%23"); Uri codebaseUri = new Uri(codebase); string path = "\"" + codebaseUri.LocalPath + "\""; object winsdkfolder = Registry.GetValue(@"HKEY_LOCAL_MACHINE\Software\Microsoft\Microsoft SDKs\Windows", "CurrentInstallFolder", null); string peVerifyPath; if (winsdkfolder == null) { peVerifyPath = Environment.ExpandEnvironmentVariables(@"%ProgramFiles%\Microsoft Visual Studio 8\Common7\IDE\PEVerify.exe"); } else { peVerifyPath = (string)winsdkfolder + @"bin\peverify.exe"; } string commandlineargs = "-unique " + path; // Use "-unique" to reduce the number of output lines ProcessStartInfo i = new ProcessStartInfo(peVerifyPath, commandlineargs); i.RedirectStandardOutput = true; i.UseShellExecute = false; using (Process p = Process.Start(i)) { // A readtoend() call is suggested by a blog pointed to on the WaitForExit(miliscnds) page in MSDN. // Otherwise sometimes we may hit the time out. string s1 = p.StandardOutput.ReadToEnd(); bool b = p.WaitForExit(1000); string s = p.StandardOutput.ReadToEnd(); Assert.IsTrue(b, "PEVerify timed out."); Assert.AreEqual(0, p.ExitCode, "PEVerify returned an errorcode of {0}.{1}", p.ExitCode, s1 + s); } } [TestMethod] public void PEVerifyTests00() { PEVerify("Tests00.dll"); } [TestMethod] public void PEVerifyTests01() { PEVerify("Tests01.dll"); } [TestMethod] public void PEVerifyTests02() { PEVerify("Tests02.dll"); } [TestMethod] public void PEVerifyTests03() { PEVerify("Tests03.dll"); } [TestMethod] public void PEVerifyTests04() { PEVerify("Tests04.dll"); } [TestMethod] public void PEVerifyTests10() { PEVerify("Tests10.dll"); } [TestMethod] public void PEVerifyTests11() { PEVerify("Tests11.dll"); } [TestMethod] public void PEVerifyTests12() { PEVerify("Tests12.dll"); } [TestMethod] public void PEVerifyTests13() { PEVerify("Tests13.dll"); } [TestMethod] public void PEVerifyTests14() { PEVerify("Tests14.dll"); } [TestMethod] public void PEVerifyTests20() { PEVerify("Tests20.dll"); } [TestMethod] public void PEVerifyTests21() { PEVerify("Tests21.dll"); } [TestMethod] public void PEVerifyTests22() { PEVerify("Tests22.dll"); } [TestMethod] public void PEVerifyTests23() { PEVerify("Tests23.dll"); } [TestMethod] public void PEVerifyTests24() { PEVerify("Tests24.dll"); } private static void PEVerify(string assemblyFile) { var path = @"..\..\..\Foxtrot\Tests\bin\Debug"; var oldCWD = Environment.CurrentDirectory; try { Environment.CurrentDirectory = path; object winsdkfolder = Registry.GetValue(@"HKEY_LOCAL_MACHINE\Software\Microsoft\Microsoft SDKs\Windows", "CurrentInstallFolder", null); string peVerifyPath; if (winsdkfolder == null) { peVerifyPath = Environment.ExpandEnvironmentVariables(@"%ProgramFiles%\Microsoft Visual Studio 8\Common7\IDE\PEVerify.exe"); } else { peVerifyPath = (string)winsdkfolder + @"bin\peverify.exe"; } ProcessStartInfo i = new ProcessStartInfo(peVerifyPath, "/unique " + assemblyFile); i.RedirectStandardOutput = true; i.UseShellExecute = false; i.CreateNoWindow = true; using (Process p = Process.Start(i)) { Assert.IsTrue(p.WaitForExit(10000), "PEVerify timed out."); Assert.AreEqual(0, p.ExitCode, "PEVerify returned an errorcode of {0}.{1}", p.ExitCode, p.StandardOutput.ReadToEnd()); } } finally { Environment.CurrentDirectory = oldCWD; } } #endregion Tests #region Test code with disjunctions public class Disjunctions { public static void TestRequiresDisjunction1(string arg, int index) { Contract.Requires(arg == null || arg.Length > index || index < 0); } public static void TestRequiresDisjunction2(string arg, int index) { Contract.Requires<ArgumentException>(arg == null || arg.Length > index || index < 0); } public static void TestRequiresDisjunction3(string arg, int index) { if (arg == null || arg.Length > index || index < 0) { throw new ArgumentException(); } Contract.EndContractBlock(); } public static void TestEnsuresDisjunction1(string arg, int index) { Contract.Ensures(arg == null || arg.Length > index || index < 0); } public static void TestEnsuresDisjunction2(string arg, int index) { Contract.EnsuresOnThrow<ArgumentException>(arg == null || arg.Length > index || index < 0); } public string _arg; public int _index; [ContractInvariantMethod] private void ObjectInvariant() { Contract.Invariant(_arg == null || _arg.Length > _index || _index < 0); } public static void TestAssertDisjunction1(string arg, int index) { Contract.Assert(arg == null || arg.Length > index || index < 0); } public static void TestAssumeDisjunction1(string arg, int index) { Contract.Assume(arg == null || arg.Length > index || index < 0); } } #endregion } } namespace TypeParameterWritingTest { public abstract class nHibernateSql2005Dal<TType1, TType2> : IDal<TType1, TType2> { TEntity IDal<TType1, TType2>.Load<TEntity, TKey>(TKey key) { return default(TEntity); } TEntity IDal<TType1, TType2>.Load<TEntity, TKey>(TEntity key) { return default(TEntity); } TType1 IDal<TType1, TType2>.Load<TEntity, TKey>(TType1 key) { return default(TType1); } TType1 IDal<TType1, TType2>.Load<TEntity, TKey>(TType2 key) { return default(TType1); } TType2 IDal<TType1, TType2>.Load<TEntity, TKey>(TKey key, bool b) { throw new NotImplementedException(); } TType2 IDal<TType1, TType2>.Load<TEntity, TKey>(TEntity key, bool b) { throw new NotImplementedException(); } TKey IDal<TType1, TType2>.Load<TEntity, TKey>(TType1 key, bool b) { throw new NotImplementedException(); } TKey IDal<TType1, TType2>.Load<TEntity, TKey>(TType2 key, bool b) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Reflection.Emit; using System.Threading; namespace Mvc.JQuery.DataTables.DynamicLinq { public class ClassFactory { public static readonly ClassFactory Instance = new ClassFactory(); static ClassFactory() { } // Trigger lazy initialization of static fields ModuleBuilder module; Dictionary<Signature, Type> classes; int classCount; ReaderWriterLock rwLock; private ClassFactory() { AssemblyName name = new AssemblyName("DynamicClasses"); AssemblyBuilder assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run); #if ENABLE_LINQ_PARTIAL_TRUST new ReflectionPermission(PermissionState.Unrestricted).Assert(); #endif try { module = assembly.DefineDynamicModule("Module"); } finally { #if ENABLE_LINQ_PARTIAL_TRUST PermissionSet.RevertAssert(); #endif } classes = new Dictionary<Signature, Type>(); rwLock = new ReaderWriterLock(); } public Type GetDynamicClass(IEnumerable<DynamicProperty> properties) { rwLock.AcquireReaderLock(Timeout.Infinite); try { Signature signature = new Signature(properties); Type type; if (!classes.TryGetValue(signature, out type)) { type = CreateDynamicClass(signature.properties); classes.Add(signature, type); } return type; } finally { rwLock.ReleaseReaderLock(); } } public Type GetDynamicClass(IEnumerable<DynamicProperty> properties, Type resultType = null, Type baseType = null) { rwLock.AcquireReaderLock(Timeout.Infinite); try { Signature signature = new Signature(properties); Type type; if (!classes.TryGetValue(signature, out type)) { if (resultType == null) type = CreateDynamicClass(signature.properties); else { type = CreateDynamicClass(signature.properties, resultType, baseType); } classes.Add(signature, type); } return type; } finally { rwLock.ReleaseReaderLock(); } } Type CreateDynamicClass(DynamicProperty[] properties) { LockCookie cookie = rwLock.UpgradeToWriterLock(Timeout.Infinite); try { string typeName = "DynamicClass" + (classCount + 1); #if ENABLE_LINQ_PARTIAL_TRUST new ReflectionPermission(PermissionState.Unrestricted).Assert(); #endif try { TypeBuilder tb = this.module.DefineType(typeName, TypeAttributes.Class | TypeAttributes.Public, typeof(object)); FieldInfo[] fields = GenerateProperties(tb, properties); GenerateEquals(tb, fields); GenerateGetHashCode(tb, fields); Type result = tb.CreateType(); return result; } finally { #if ENABLE_LINQ_PARTIAL_TRUST PermissionSet.RevertAssert(); #endif } } finally { classCount++; rwLock.DowngradeFromWriterLock(ref cookie); } } Type CreateDynamicClass(DynamicProperty[] properties, Type resultType, Type baseType = null) { LockCookie cookie = rwLock.UpgradeToWriterLock(Timeout.Infinite); try { string typeName = "DynamicClass" + (classCount + 1); #if ENABLE_LINQ_PARTIAL_TRUST new ReflectionPermission(PermissionState.Unrestricted).Assert(); #endif try { TypeBuilder tb = null; if (baseType != null) { tb = this.module.DefineType(typeName, TypeAttributes.Class | TypeAttributes.Public, baseType); } else { tb = this.module.DefineType(typeName, TypeAttributes.Class | TypeAttributes.Public, typeof(object)); } tb.AddInterfaceImplementation(resultType); FieldInfo[] fields = GenerateProperties(tb, properties, resultType); GenerateEquals(tb, fields); GenerateGetHashCode(tb, fields); Type result = tb.CreateType(); return result; } finally { #if ENABLE_LINQ_PARTIAL_TRUST PermissionSet.RevertAssert(); #endif } } finally { classCount++; rwLock.DowngradeFromWriterLock(ref cookie); } } FieldInfo[] GenerateProperties(TypeBuilder tb, DynamicProperty[] properties, Type returnType = null) { FieldInfo[] fields = new FieldBuilder[properties.Length]; for (int i = 0; i < properties.Length; i++) { DynamicProperty dp = properties[i]; PrintPropertyInfo(dp); FieldBuilder fb = tb.DefineField("_" + dp.Name, dp.Type, FieldAttributes.Private); PropertyBuilder pb = tb.DefineProperty(dp.Name, PropertyAttributes.HasDefault, dp.Type, null); if (dp.CustomAttributeBuilder != null) pb.SetCustomAttribute(dp.CustomAttributeBuilder); MethodBuilder mbGet = tb.DefineMethod("get_" + dp.Name, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig | MethodAttributes.Virtual, dp.Type, Type.EmptyTypes); ILGenerator genGet = mbGet.GetILGenerator(); genGet.Emit(OpCodes.Ldarg_0); genGet.Emit(OpCodes.Ldfld, fb); genGet.Emit(OpCodes.Ret); if (returnType != null) { var returnTypeMi = returnType.GetMethod(mbGet.Name); if (returnTypeMi != null) tb.DefineMethodOverride(mbGet, returnTypeMi); } MethodBuilder mbSet = tb.DefineMethod("set_" + dp.Name, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig | MethodAttributes.Virtual, null, new Type[] { dp.Type }); ILGenerator genSet = mbSet.GetILGenerator(); genSet.Emit(OpCodes.Ldarg_0); genSet.Emit(OpCodes.Ldarg_1); genSet.Emit(OpCodes.Stfld, fb); genSet.Emit(OpCodes.Ret); if (returnType != null) { var returnTypeMi = returnType.GetMethod(mbSet.Name); if (returnTypeMi != null) tb.DefineMethodOverride(mbSet, returnTypeMi); } pb.SetGetMethod(mbGet); pb.SetSetMethod(mbSet); fields[i] = fb; } return fields; } [Conditional("DEBUG")] void PrintPropertyInfo(DynamicProperty dp) { Debug.WriteLine(String.Format("Building Property {0} of Type {1}", dp.Name, dp.Type.Name)); } void GenerateEquals(TypeBuilder tb, FieldInfo[] fields) { MethodBuilder mb = tb.DefineMethod("Equals", MethodAttributes.Public | MethodAttributes.ReuseSlot | MethodAttributes.Virtual | MethodAttributes.HideBySig, typeof(bool), new Type[] { typeof(object) }); ILGenerator gen = mb.GetILGenerator(); LocalBuilder other = gen.DeclareLocal(tb); Label next = gen.DefineLabel(); gen.Emit(OpCodes.Ldarg_1); gen.Emit(OpCodes.Isinst, tb); gen.Emit(OpCodes.Stloc, other); gen.Emit(OpCodes.Ldloc, other); gen.Emit(OpCodes.Brtrue_S, next); gen.Emit(OpCodes.Ldc_I4_0); gen.Emit(OpCodes.Ret); gen.MarkLabel(next); foreach (FieldInfo field in fields) { Type ft = field.FieldType; Type ct = typeof(EqualityComparer<>).MakeGenericType(ft); next = gen.DefineLabel(); gen.EmitCall(OpCodes.Call, ct.GetMethod("get_Default"), null); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldfld, field); gen.Emit(OpCodes.Ldloc, other); gen.Emit(OpCodes.Ldfld, field); gen.EmitCall(OpCodes.Callvirt, ct.GetMethod("Equals", new Type[] { ft, ft }), null); gen.Emit(OpCodes.Brtrue_S, next); gen.Emit(OpCodes.Ldc_I4_0); gen.Emit(OpCodes.Ret); gen.MarkLabel(next); } gen.Emit(OpCodes.Ldc_I4_1); gen.Emit(OpCodes.Ret); } void GenerateGetHashCode(TypeBuilder tb, FieldInfo[] fields) { MethodBuilder mb = tb.DefineMethod("GetHashCode", MethodAttributes.Public | MethodAttributes.ReuseSlot | MethodAttributes.Virtual | MethodAttributes.HideBySig, typeof(int), Type.EmptyTypes); ILGenerator gen = mb.GetILGenerator(); gen.Emit(OpCodes.Ldc_I4_0); foreach (FieldInfo field in fields) { Type ft = field.FieldType; Type ct = typeof(EqualityComparer<>).MakeGenericType(ft); gen.EmitCall(OpCodes.Call, ct.GetMethod("get_Default"), null); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldfld, field); gen.EmitCall(OpCodes.Callvirt, ct.GetMethod("GetHashCode", new Type[] { ft }), null); gen.Emit(OpCodes.Xor); } gen.Emit(OpCodes.Ret); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Xml; using OpenMetaverse; using log4net; using OpenSim.Framework; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Physics.Manager; namespace OpenSim.Region.Framework.Scenes.Serialization { /// <summary> /// Static methods to serialize and deserialize scene objects to and from XML /// </summary> public class SceneXmlLoader { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public static void LoadPrimsFromXml(Scene scene, string fileName, bool newIDS, Vector3 loadOffset) { XmlDocument doc = new XmlDocument(); XmlNode rootNode; if (fileName.StartsWith("http:") || File.Exists(fileName)) { XmlTextReader reader = new XmlTextReader(fileName); reader.WhitespaceHandling = WhitespaceHandling.None; doc.Load(reader); reader.Close(); rootNode = doc.FirstChild; foreach (XmlNode aPrimNode in rootNode.ChildNodes) { SceneObjectGroup obj = SceneObjectSerializer.FromOriginalXmlFormat(aPrimNode.OuterXml); if (newIDS) { obj.ResetIDs(); } //if we want this to be a import method then we need new uuids for the object to avoid any clashes //obj.RegenerateFullIDs(); scene.AddNewSceneObject(obj, true); } } else { throw new Exception("Could not open file " + fileName + " for reading"); } } public static void SavePrimsToXml(Scene scene, string fileName) { FileStream file = new FileStream(fileName, FileMode.Create); StreamWriter stream = new StreamWriter(file); int primCount = 0; stream.WriteLine("<scene>\n"); List<EntityBase> EntityList = scene.GetEntities(); foreach (EntityBase ent in EntityList) { if (ent is SceneObjectGroup) { stream.WriteLine(SceneObjectSerializer.ToOriginalXmlFormat((SceneObjectGroup)ent)); primCount++; } } stream.WriteLine("</scene>\n"); stream.Close(); file.Close(); } public static string SaveGroupToXml2(SceneObjectGroup grp) { return SceneObjectSerializer.ToXml2Format(grp); } public static SceneObjectGroup DeserializeGroupFromXml2(string xmlString) { XmlDocument doc = new XmlDocument(); XmlNode rootNode; XmlTextReader reader = new XmlTextReader(new StringReader(xmlString)); reader.WhitespaceHandling = WhitespaceHandling.None; doc.Load(reader); reader.Close(); rootNode = doc.FirstChild; // This is to deal with neighbouring regions that are still surrounding the group xml with the <scene> // tag. It should be possible to remove the first part of this if statement once we go past 0.5.9 (or // when some other changes forces all regions to upgrade). // This might seem rather pointless since prim crossing from this revision to an earlier revision remains // broken. But it isn't much work to accomodate the old format here. if (rootNode.LocalName.Equals("scene")) { foreach (XmlNode aPrimNode in rootNode.ChildNodes) { // There is only ever one prim. This oddity should be removeable post 0.5.9 return SceneObjectSerializer.FromXml2Format(aPrimNode.OuterXml); } return null; } else { return SceneObjectSerializer.FromXml2Format(rootNode.OuterXml); } } /// <summary> /// Load prims from the xml2 format /// </summary> /// <param name="scene"></param> /// <param name="fileName"></param> public static void LoadPrimsFromXml2(Scene scene, string fileName) { LoadPrimsFromXml2(scene, new XmlTextReader(fileName), false); } /// <summary> /// Load prims from the xml2 format /// </summary> /// <param name="scene"></param> /// <param name="reader"></param> /// <param name="startScripts"></param> public static void LoadPrimsFromXml2(Scene scene, TextReader reader, bool startScripts) { LoadPrimsFromXml2(scene, new XmlTextReader(reader), startScripts); } /// <summary> /// Load prims from the xml2 format. This method will close the reader /// </summary> /// <param name="scene"></param> /// <param name="reader"></param> /// <param name="startScripts"></param> protected static void LoadPrimsFromXml2(Scene scene, XmlTextReader reader, bool startScripts) { XmlDocument doc = new XmlDocument(); reader.WhitespaceHandling = WhitespaceHandling.None; doc.Load(reader); reader.Close(); XmlNode rootNode = doc.FirstChild; ICollection<SceneObjectGroup> sceneObjects = new List<SceneObjectGroup>(); foreach (XmlNode aPrimNode in rootNode.ChildNodes) { SceneObjectGroup obj = CreatePrimFromXml2(scene, aPrimNode.OuterXml); if (obj != null && startScripts) sceneObjects.Add(obj); } foreach (SceneObjectGroup sceneObject in sceneObjects) { sceneObject.CreateScriptInstances(0, true, scene.DefaultScriptEngine, 0); } } /// <summary> /// Create a prim from the xml2 representation. /// </summary> /// <param name="scene"></param> /// <param name="xmlData"></param> /// <returns>The scene object created. null if the scene object already existed</returns> protected static SceneObjectGroup CreatePrimFromXml2(Scene scene, string xmlData) { SceneObjectGroup obj = SceneObjectSerializer.FromXml2Format(xmlData); if (scene.AddRestoredSceneObject(obj, true, false)) return obj; else return null; } public static void SavePrimsToXml2(Scene scene, string fileName) { List<EntityBase> EntityList = scene.GetEntities(); SavePrimListToXml2(EntityList, fileName); } public static void SavePrimsToXml2(Scene scene, TextWriter stream, Vector3 min, Vector3 max) { List<EntityBase> EntityList = scene.GetEntities(); SavePrimListToXml2(EntityList, stream, min, max); } public static void SaveNamedPrimsToXml2(Scene scene, string primName, string fileName) { m_log.InfoFormat( "[SERIALISER]: Saving prims with name {0} in xml2 format for region {1} to {2}", primName, scene.RegionInfo.RegionName, fileName); List<EntityBase> entityList = scene.GetEntities(); List<EntityBase> primList = new List<EntityBase>(); foreach (EntityBase ent in entityList) { if (ent is SceneObjectGroup) { if (ent.Name == primName) { primList.Add(ent); } } } SavePrimListToXml2(primList, fileName); } public static void SavePrimListToXml2(List<EntityBase> entityList, string fileName) { FileStream file = new FileStream(fileName, FileMode.Create); try { StreamWriter stream = new StreamWriter(file); try { SavePrimListToXml2(entityList, stream, Vector3.Zero, Vector3.Zero); } finally { stream.Close(); } } finally { file.Close(); } } public static void SavePrimListToXml2(List<EntityBase> entityList, TextWriter stream, Vector3 min, Vector3 max) { int primCount = 0; stream.WriteLine("<scene>\n"); foreach (EntityBase ent in entityList) { if (ent is SceneObjectGroup) { SceneObjectGroup g = (SceneObjectGroup)ent; if (!min.Equals(Vector3.Zero) || !max.Equals(Vector3.Zero)) { Vector3 pos = g.RootPart.GetWorldPosition(); if (min.X > pos.X || min.Y > pos.Y || min.Z > pos.Z) continue; if (max.X < pos.X || max.Y < pos.Y || max.Z < pos.Z) continue; } stream.WriteLine(SceneObjectSerializer.ToXml2Format(g)); primCount++; } } stream.WriteLine("</scene>\n"); stream.Flush(); } } }
namespace Petstore { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// StorageAccountsOperations operations. /// </summary> public partial interface IStorageAccountsOperations { /// <summary> /// Checks that account name is valid and is not in use. /// </summary> /// <param name='accountName'> /// The name of the storage account within the specified resource /// group. Storage account names must be between 3 and 24 characters in /// length and use numbers and lower-case letters only. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<CheckNameAvailabilityResult>> CheckNameAvailabilityWithHttpMessagesAsync(StorageAccountCheckNameAvailabilityParameters accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Asynchronously creates a new storage account with the specified /// parameters. Existing accounts cannot be updated with this API and /// should instead use the Update Storage Account API. If an account is /// already created and subsequent PUT request is issued with exact /// same set of properties, then HTTP 200 would be returned. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource /// group. Storage account names must be between 3 and 24 characters in /// length and use numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// The parameters to provide for the created account. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<StorageAccount>> CreateWithHttpMessagesAsync(string resourceGroupName, string accountName, StorageAccountCreateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a storage account in Microsoft Azure. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource /// group. Storage account names must be between 3 and 24 characters in /// length and use numbers and lower-case letters only. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Returns the properties for the specified storage account including /// but not limited to name, account type, location, and account /// status. The ListKeys operation should be used to retrieve storage /// keys. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource /// group. Storage account names must be between 3 and 24 characters in /// length and use numbers and lower-case letters only. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<StorageAccount>> GetPropertiesWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Updates the account type or tags for a storage account. It can also /// be used to add a custom domain (note that custom domains cannot be /// added via the Create operation). Only one custom domain is /// supported per storage account. In order to replace a custom domain, /// the old value must be cleared before a new value may be set. To /// clear a custom domain, simply update the custom domain with empty /// string. Then call update again with the new cutsom domain name. The /// update API can only be used to update one of tags, accountType, or /// customDomain per call. To update multiple of these properties, call /// the API multiple times with one change per call. This call does not /// change the storage keys for the account. If you want to change /// storage account keys, use the RegenerateKey operation. The location /// and name of the storage account cannot be changed after creation. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource /// group. Storage account names must be between 3 and 24 characters in /// length and use numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// The parameters to update on the account. Note that only one /// property can be changed at a time using this API. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<StorageAccount>> UpdateWithHttpMessagesAsync(string resourceGroupName, string accountName, StorageAccountUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists the access keys for the specified storage account. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='accountName'> /// The name of the storage account. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<StorageAccountKeys>> ListKeysWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists all the storage accounts available under the subscription. /// Note that storage keys are not returned; use the ListKeys operation /// for this. /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IEnumerable<StorageAccount>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists all the storage accounts available under the given resource /// group. Note that storage keys are not returned; use the ListKeys /// operation for this. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IEnumerable<StorageAccount>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Regenerates the access keys for the specified storage account. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource /// group. Storage account names must be between 3 and 24 characters in /// length and use numbers and lower-case letters only. /// </param> /// <param name='regenerateKey'> /// Specifies name of the key which should be regenerated. key1 or key2 /// for the default keys /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<StorageAccountKeys>> RegenerateKeyWithHttpMessagesAsync(string resourceGroupName, string accountName, StorageAccountRegenerateKeyParameters regenerateKey, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Asynchronously creates a new storage account with the specified /// parameters. Existing accounts cannot be updated with this API and /// should instead use the Update Storage Account API. If an account is /// already created and subsequent PUT request is issued with exact /// same set of properties, then HTTP 200 would be returned. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource /// group. Storage account names must be between 3 and 24 characters in /// length and use numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// The parameters to provide for the created account. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<StorageAccount>> BeginCreateWithHttpMessagesAsync(string resourceGroupName, string accountName, StorageAccountCreateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Copyright (c) 2009 Novell, Inc. (http://www.novell.com) // // Authors: // Mike Gorse <mgorse@novell.com> // using System; using System.Collections.Generic; using NDesk.DBus; using org.freedesktop.DBus; namespace Atspi { public class DeviceEventController { private volatile static DeviceEventController instance; private static object sync = new Object (); private IDeviceEventController proxy; public static DeviceEventController Instance { get { return instance; } } public DeviceEventController () { lock (sync) { if (instance == null) instance = this; else throw new Exception ("Attempt to create a second device event controller"); } ObjectPath op = new ObjectPath ("/org/a11y/atspi/registry/deviceeventcontroller"); proxy = Registry.Bus.GetObject<IDeviceEventController> ("org.a11y.atspi.Registry", op); } public static void Terminate () { lock (sync) { instance = null; } } public bool Register (KeystrokeListener listener) { ObjectPath op = new ObjectPath (listener.Path); EventListenerMode mode = new EventListenerMode (listener.Synchronous, listener.Preemptive, listener.Global); return proxy.RegisterKeystrokeListener (op, listener.Keys, listener.Mask, listener.Types, mode); } public bool Register (MouseListener listener) { ObjectPath op = new ObjectPath (listener.Path); return proxy.RegisterDeviceEventListener (op, listener.Types); } public void Deregister (KeystrokeListener listener) { ObjectPath op = new ObjectPath (listener.Path); proxy.DeregisterKeystrokeListener (op, listener.Keys, listener.Mask, listener.Types); } public void Deregister (MouseListener listener) { ObjectPath op = new ObjectPath (listener.Path); proxy.DeregisterDeviceEventListener (op, listener.Types); } public bool NotifyListenersSync (DeviceEvent ev) { return proxy.NotifyListenersSync (ev); } public void NotifyListenersAsync (DeviceEvent ev) { proxy.NotifyListenersAsync (ev); } public void GenerateKeyboardEvent (int keycode, string keystring, KeySynthType type) { proxy.GenerateKeyboardEvent (keycode, keystring, type); } public void GenerateMouseEvent (int x, int y, string eventName) { proxy.GenerateMouseEvent (x, y, eventName); } } public abstract class DeviceEventListener : IDeviceEventListener { private static int lastId = 0; private static Dictionary<int, DeviceEventListener> mappings = new Dictionary<int, DeviceEventListener> (); private int id; public DeviceEventListener () : base () { DeviceEventListener l; while (mappings.TryGetValue (++lastId, out l)); id = lastId; Registry.Bus.Register (new ObjectPath (Path), this); mappings [id] = this; } internal string Path { get { return "/org/a11y/atspi/Listeners/" + id; } } public abstract bool NotifyEvent (DeviceEvent ev); } public abstract class KeystrokeListener: DeviceEventListener { private KeyDefinition [] keys; private ControllerEventMask mask; private EventType types; private bool synchronous; private bool preemptive; private bool global; private bool registered; public bool Register (KeyDefinition [] keys, ControllerEventMask mask, EventType types, bool synchronous, bool preemptive, bool global) { Deregister (); this.keys = keys; this.mask = mask; this.types = types; this.synchronous = synchronous; this.preemptive = preemptive; this.global = global; registered = DeviceEventController.Instance.Register (this); return registered; } public void Deregister () { if (!registered) return; DeviceEventController.Instance.Deregister (this); } public KeyDefinition [] Keys { get { return keys; } } public ControllerEventMask Mask { get { return mask; } } public EventType Types { get { return types; } } public bool Synchronous { get { return synchronous; } } public bool Preemptive { get { return preemptive; } } public bool Global { get { return global; } } public bool Registered { get { return registered; } } } public abstract class MouseListener: DeviceEventListener { private EventType types; private bool registered; public bool Register (EventType types) { Deregister (); this.types = types; registered = DeviceEventController.Instance.Register (this); return registered; } public void Deregister () { if (!registered) return; DeviceEventController.Instance.Deregister (this); } public EventType Types { get { return types; } } public bool Registered { get { return registered; } } } public struct EventListenerMode { public bool Synchronous; public bool Preemptive; public bool Global; public EventListenerMode (bool synchronous, bool preemptive, bool global) { this.Synchronous = synchronous; this.Preemptive = preemptive; this.Global = global; } } public struct KeyDefinition { public int keycode; public int keysym; public string keystring; public int unused; // An empty key set is a special case; means all keys public static KeyDefinition [] All = new KeyDefinition [0]; } [System.Flags] public enum ControllerEventMask : uint { Alt = 0x0008, Mod1 = 0x0008, Mod2 = 0x0010, Mod3 = 0x0020, Mod4 = 0x0040, Mod5 = 0x0080, Button1 = 0x0100, Button2 = 0x0200, Button3 = 0x0400, Button4 = 0x0800, Button5 = 0x0100, Control = 0x0004, Shift = 0x0001, ShiftLock = 0x0002, NumLock = 0x4000, Unmodified = 0 } [System.Flags] public enum EventType : uint { All = 0, KeyPressed = 0x01, KeyReleased = 0x02, ButtonPressed = 0x04, ButtonReleased = 0x08 } [System.Flags] public enum KeyModifier : uint { Shift = 1, ShiftLock = 2, Control = 4, Alt = 8, Meta = 16, Meta2 = 32, Meta3 = 64 } public struct DeviceEvent { public uint Type; public int Id; public uint HwCode; public KeyModifier Modifiers; public int Timestamp; public string EventString; public bool IsText; } public enum KeySynthType : uint { KeyPress, KeyRelease, KeyPressRelease, KeySym, KeyString } [Interface ("org.a11y.atspi.DeviceEventController")] interface IDeviceEventController : Introspectable { bool RegisterKeystrokeListener (ObjectPath listener, KeyDefinition [] keys, ControllerEventMask mask, EventType types, EventListenerMode mode); void DeregisterKeystrokeListener (ObjectPath listener, KeyDefinition [] keys, ControllerEventMask mask, EventType types); bool RegisterDeviceEventListener (ObjectPath listener, EventType types); void DeregisterDeviceEventListener (ObjectPath listener, EventType types); bool NotifyListenersSync (DeviceEvent ev); void NotifyListenersAsync (DeviceEvent ev); void GenerateKeyboardEvent (int keycode, string keystring, KeySynthType type); void GenerateMouseEvent (int x, int y, string eventName); } [Interface ("org.a11y.atspi.DeviceEventListener")] interface IDeviceEventListener { bool NotifyEvent (DeviceEvent ev); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #if netcoreapp || uap #define HAVE_STORE_ISOPEN #endif using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using Xunit; namespace System.Security.Cryptography.X509Certificates.Tests { public class X509StoreTests : RemoteExecutorTestBase { [Fact] public static void OpenMyStore() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) { store.Open(OpenFlags.ReadOnly); Assert.Equal("My", store.Name); } } [Fact] public static void Constructor_DefaultStoreName() { using (X509Store store = new X509Store(StoreLocation.CurrentUser)) { Assert.Equal("MY", store.Name); } } #if HAVE_STORE_ISOPEN [Fact] public static void Constructor_IsNotOpen() { using (X509Store store = new X509Store(StoreLocation.CurrentUser)) { Assert.False(store.IsOpen); } } #endif [Fact] public static void Constructor_DefaultStoreLocation() { using (X509Store store = new X509Store(StoreName.My)) { Assert.Equal(StoreLocation.CurrentUser, store.Location); } using (X509Store store = new X509Store("My")) { Assert.Equal(StoreLocation.CurrentUser, store.Location); } } [PlatformSpecific(TestPlatforms.Windows | TestPlatforms.OSX)] // Not supported via OpenSSL [Fact] public static void Constructor_StoreHandle() { using (X509Store store1 = new X509Store(StoreName.My, StoreLocation.CurrentUser)) { store1.Open(OpenFlags.ReadOnly); bool hadCerts; using (var coll = new ImportedCollection(store1.Certificates)) { // Use >1 instead of >0 in case the one is an ephemeral accident. hadCerts = coll.Collection.Count > 1; Assert.True(coll.Collection.Count >= 0); } using (X509Store store2 = new X509Store(store1.StoreHandle)) { using (var coll = new ImportedCollection(store2.Certificates)) { if (hadCerts) { // Use InRange here instead of True >= 0 so that the error message // is different, and we can diagnose a bit of what state we might have been in. Assert.InRange(coll.Collection.Count, 1, int.MaxValue); } else { Assert.True(coll.Collection.Count >= 0); } } } } } [PlatformSpecific(TestPlatforms.AnyUnix & ~TestPlatforms.OSX)] // API not supported via OpenSSL [Fact] public static void Constructor_StoreHandle_Unix() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) { store.Open(OpenFlags.ReadOnly); Assert.Equal(IntPtr.Zero, store.StoreHandle); } Assert.Throws<PlatformNotSupportedException>(() => new X509Chain(IntPtr.Zero)); } #if HAVE_STORE_ISOPEN [Fact] public static void Constructor_OpenFlags() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser, OpenFlags.ReadOnly)) { Assert.True(store.IsOpen); } } [Fact] public static void Constructor_OpenFlags_StoreName() { using (X509Store store = new X509Store("My", StoreLocation.CurrentUser, OpenFlags.ReadOnly)) { Assert.True(store.IsOpen); } } [Fact] public static void Constructor_OpenFlags_OpenAnyway() { using (X509Store store = new X509Store("My", StoreLocation.CurrentUser, OpenFlags.ReadOnly)) { store.Open(OpenFlags.ReadOnly); Assert.True(store.IsOpen); } } [Fact] public static void Constructor_OpenFlags_NonExistingStoreName_Throws() { Assert.ThrowsAny<CryptographicException>(() => new X509Store(new Guid().ToString("D"), StoreLocation.CurrentUser, OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly) ); } #endif [PlatformSpecific(TestPlatforms.Windows | TestPlatforms.OSX)] // StoreHandle not supported via OpenSSL [Fact] public static void TestDispose() { X509Store store; using (store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) { store.Open(OpenFlags.ReadOnly); Assert.NotEqual(IntPtr.Zero, store.StoreHandle); } Assert.Throws<CryptographicException>(() => store.StoreHandle); } [Fact] public static void ReadMyCertificates() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) { store.Open(OpenFlags.ReadOnly); using (var coll = new ImportedCollection(store.Certificates)) { int certCount = coll.Collection.Count; // This assert is just so certCount appears to be used, the test really // is that store.get_Certificates didn't throw. Assert.True(certCount >= 0); } } } [Fact] public static void OpenNotExistent() { using (X509Store store = new X509Store(Guid.NewGuid().ToString("N"), StoreLocation.CurrentUser)) { Assert.ThrowsAny<CryptographicException>(() => store.Open(OpenFlags.OpenExistingOnly)); } } #if HAVE_STORE_ISOPEN [Fact] public static void Open_IsOpenTrue() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) { store.Open(OpenFlags.ReadOnly); Assert.True(store.IsOpen); } } [Fact] public static void Dispose_IsOpenFalse() { X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly); store.Dispose(); Assert.False(store.IsOpen); } [Fact] public static void ReOpen_IsOpenTrue() { X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly); store.Close(); store.Open(OpenFlags.ReadOnly); Assert.True(store.IsOpen); } #endif [Fact] public static void AddReadOnlyThrows() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) using (X509Certificate2 cert = new X509Certificate2(TestData.MsCertificate)) { store.Open(OpenFlags.ReadOnly); using (var coll = new ImportedCollection(store.Certificates)) { // Add only throws when it has to do work. If, for some reason, this certificate // is already present in the CurrentUser\My store, we can't really test this // functionality. if (!coll.Collection.Contains(cert)) { Assert.ThrowsAny<CryptographicException>(() => store.Add(cert)); } } } } [Fact] public static void AddDisposedThrowsCryptographicException() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) using (X509Certificate2 cert = new X509Certificate2(TestData.MsCertificate)) { store.Open(OpenFlags.ReadWrite); cert.Dispose(); Assert.Throws<CryptographicException>(() => store.Add(cert)); } } [Fact] public static void AddReadOnlyThrowsWhenCertificateExists() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) { store.Open(OpenFlags.ReadOnly); X509Certificate2 toAdd = null; // Look through the certificates to find one with no private key to call add on. // (The private key restriction is so that in the event of an "accidental success" // that no potential permissions would be modified) using (var coll = new ImportedCollection(store.Certificates)) { foreach (X509Certificate2 cert in coll.Collection) { if (!cert.HasPrivateKey) { toAdd = cert; break; } } if (toAdd != null) { Assert.ThrowsAny<CryptographicException>(() => store.Add(toAdd)); } } } } [Fact] public static void RemoveReadOnlyThrowsWhenFound() { // This test is unfortunate, in that it will mostly never test. // In order to do so it would have to open the store ReadWrite, put in a known value, // and call Remove on a ReadOnly copy. // // Just calling Remove on the first item found could also work (when the store isn't empty), // but if it fails the cost is too high. // // So what's the purpose of this test, you ask? To record why we're not unit testing it. // And someone could test it manually if they wanted. using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) using (X509Certificate2 cert = new X509Certificate2(TestData.MsCertificate)) { store.Open(OpenFlags.ReadOnly); using (var coll = new ImportedCollection(store.Certificates)) { if (coll.Collection.Contains(cert)) { Assert.ThrowsAny<CryptographicException>(() => store.Remove(cert)); } } } } [Fact] public static void RemoveReadOnlyNonExistingDoesNotThrow() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) using (X509Certificate2 cert = new X509Certificate2(TestData.MsCertificate)) { store.Open(OpenFlags.ReadOnly); store.Remove(cert); } } [Fact] public static void RemoveDisposedIsIgnored() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) using (X509Certificate2 cert = new X509Certificate2(TestData.MsCertificate)) { store.Open(OpenFlags.ReadWrite); cert.Dispose(); store.Remove(cert); } } /* Placeholder information for these tests until they can be written to run reliably. * Currently such tests would create physical files (Unix) and\or certificates (Windows) * which can collide with other running tests that use the same cert, or from a * test suite running more than once at the same time on the same machine. * Ideally, we use a GUID-named store to aoiv collitions with proper cleanup on Unix and Windows * and\or have lower testing hooks or use Microsoft Fakes Framework to redirect * and encapsulate the actual storage logic so it can be tested, along with mock exceptions * to verify exception handling. * See issue https://github.com/dotnet/corefx/issues/12833 * and https://github.com/dotnet/corefx/issues/12223 [Fact] public static void TestAddAndRemove() {} [Fact] public static void TestAddRangeAndRemoveRange() {} */ [Fact] public static void EnumerateClosedIsEmpty() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) { int count = store.Certificates.Count; Assert.Equal(0, count); } } [Fact] public static void AddClosedThrows() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) using (X509Certificate2 cert = new X509Certificate2(TestData.MsCertificate)) { Assert.ThrowsAny<CryptographicException>(() => store.Add(cert)); } } [Fact] public static void RemoveClosedThrows() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) using (X509Certificate2 cert = new X509Certificate2(TestData.MsCertificate)) { Assert.ThrowsAny<CryptographicException>(() => store.Remove(cert)); } } [Fact] [PlatformSpecific(TestPlatforms.Windows | TestPlatforms.OSX)] public static void OpenMachineMyStore_Supported() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine)) { store.Open(OpenFlags.ReadOnly); } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix & ~TestPlatforms.OSX)] public static void OpenMachineMyStore_NotSupported() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine)) { Exception e = Assert.Throws<CryptographicException>(() => store.Open(OpenFlags.ReadOnly)); Assert.NotNull(e.InnerException); Assert.IsType<PlatformNotSupportedException>(e.InnerException); } } [Theory] [PlatformSpecific(TestPlatforms.AnyUnix & ~TestPlatforms.OSX)] [InlineData(OpenFlags.ReadOnly, false)] [InlineData(OpenFlags.MaxAllowed, false)] [InlineData(OpenFlags.ReadWrite, true)] public static void OpenMachineRootStore_Permissions(OpenFlags permissions, bool shouldThrow) { using (X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine)) { if (shouldThrow) { Exception e = Assert.Throws<CryptographicException>(() => store.Open(permissions)); Assert.NotNull(e.InnerException); Assert.IsType<PlatformNotSupportedException>(e.InnerException); } else { // Assert.DoesNotThrow store.Open(permissions); } } } [Fact] public static void MachineRootStore_NonEmpty() { // This test will fail on systems where the administrator has gone out of their // way to prune the trusted CA list down below this threshold. // // As of 2016-01-25, Ubuntu 14.04 has 169, and CentOS 7.1 has 175, so that'd be // quite a lot of pruning. // // And as of 2016-01-29 we understand the Homebrew-installed root store, with 180. const int MinimumThreshold = 5; using (X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine)) { store.Open(OpenFlags.ReadOnly); using (var storeCerts = new ImportedCollection(store.Certificates)) { int certCount = storeCerts.Collection.Count; Assert.InRange(certCount, MinimumThreshold, int.MaxValue); } } } [Theory] [PlatformSpecific(TestPlatforms.Windows | TestPlatforms.OSX)] [InlineData(StoreLocation.CurrentUser, true)] [InlineData(StoreLocation.LocalMachine, true)] [InlineData(StoreLocation.CurrentUser, false)] [InlineData(StoreLocation.LocalMachine, false)] public static void EnumerateDisallowedStore(StoreLocation location, bool useEnum) { X509Store store = useEnum ? new X509Store(StoreName.Disallowed, location) // Non-normative casing, proving that we aren't case-sensitive (Windows isn't) : new X509Store("disallowed", location); using (store) { store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); using (var storeCerts = new ImportedCollection(store.Certificates)) { // That's all. We enumerated it. // There might not even be data in it. } } } [Theory] [PlatformSpecific(TestPlatforms.AnyUnix & ~TestPlatforms.OSX)] [InlineData(false, OpenFlags.ReadOnly)] [InlineData(true, OpenFlags.ReadOnly)] [InlineData(false, OpenFlags.ReadWrite)] [InlineData(true, OpenFlags.ReadWrite)] [InlineData(false, OpenFlags.MaxAllowed)] [InlineData(true, OpenFlags.MaxAllowed)] public static void UnixCannotOpenMachineDisallowedStore(bool useEnum, OpenFlags openFlags) { X509Store store = useEnum ? new X509Store(StoreName.Disallowed, StoreLocation.LocalMachine) // Non-normative casing, proving that we aren't case-sensitive (Windows isn't) : new X509Store("disallowed", StoreLocation.LocalMachine); using (store) { Exception e = Assert.Throws<CryptographicException>(() => store.Open(openFlags)); Assert.NotNull(e.InnerException); Assert.IsType<PlatformNotSupportedException>(e.InnerException); Assert.Equal(e.Message, e.InnerException.Message); } } [Theory] [PlatformSpecific(TestPlatforms.AnyUnix & ~TestPlatforms.OSX)] [InlineData(false, OpenFlags.ReadOnly)] [InlineData(true, OpenFlags.ReadOnly)] [InlineData(false, OpenFlags.ReadWrite)] [InlineData(true, OpenFlags.ReadWrite)] [InlineData(false, OpenFlags.MaxAllowed)] [InlineData(true, OpenFlags.MaxAllowed)] public static void UnixCannotModifyDisallowedStore(bool useEnum, OpenFlags openFlags) { X509Store store = useEnum ? new X509Store(StoreName.Disallowed, StoreLocation.CurrentUser) // Non-normative casing, proving that we aren't case-sensitive (Windows isn't) : new X509Store("disallowed", StoreLocation.CurrentUser); using (store) using (X509Certificate2 cert = new X509Certificate2(TestData.Rsa384CertificatePemBytes)) { store.Open(openFlags); Exception e = Assert.Throws<CryptographicException>(() => store.Add(cert)); if (openFlags == OpenFlags.ReadOnly) { Assert.Null(e.InnerException); } else { Assert.NotNull(e.InnerException); Assert.IsType<PlatformNotSupportedException>(e.InnerException); Assert.Equal(e.Message, e.InnerException.Message); } Assert.Equal(0, store.Certificates.Count); } } #if Unix [Fact] [PlatformSpecific(TestPlatforms.Linux)] // Windows/OSX doesn't use SSL_CERT_{DIR,FILE}. private void X509Store_MachineStoreLoadSkipsInvalidFiles() { // We create a folder for our machine store and use it by setting SSL_CERT_{DIR,FILE}. // In the store we'll add some invalid files, but we start and finish with a valid file. // This is to account for the order in which the store is populated. string sslCertDir = GetTestFilePath(); Directory.CreateDirectory(sslCertDir); // Valid file. File.WriteAllBytes(Path.Combine(sslCertDir, "0.pem"), TestData.SelfSigned1PemBytes); // File with invalid content. File.WriteAllText(Path.Combine(sslCertDir, "1.pem"), "This is not a valid cert"); // File which is not readable by the current user. string unreadableFileName = Path.Combine(sslCertDir, "2.pem"); File.WriteAllBytes(unreadableFileName, TestData.SelfSigned2PemBytes); Assert.Equal(0, chmod(unreadableFileName, 0)); // Valid file. File.WriteAllBytes(Path.Combine(sslCertDir, "3.pem"), TestData.SelfSigned3PemBytes); var psi = new ProcessStartInfo(); psi.Environment.Add("SSL_CERT_DIR", sslCertDir); psi.Environment.Add("SSL_CERT_FILE", "/nonexisting"); RemoteInvoke(() => { using (var store = new X509Store(StoreName.Root, StoreLocation.LocalMachine)) { store.Open(OpenFlags.OpenExistingOnly); // Check nr of certificates in store. Assert.Equal(2, store.Certificates.Count); } return SuccessExitCode; }, new RemoteInvokeOptions { StartInfo = psi }).Dispose(); } [DllImport("libc")] private static extern int chmod(string path, int mode); #endif } }
using Microsoft.VisualStudio.Debugger.Interop; using nanoFramework.Tools.Debugger; using System; using System.Runtime.InteropServices; namespace nanoFramework.Tools.VisualStudio.Debugger { // This Guid needs to match PortSupplierCLSID [ComVisible(true), Guid("78E48437-246C-4CA2-B66F-4B65AEED8500")] public class DebugPortSupplier : IDebugPortSupplier2, IDebugPortSupplierEx2, IDebugPortSupplierDescription2 { // This Guid needs to match PortSupplierGuid public static Guid PortSupplierGuid = new Guid("D7240956-FE4A-4324-93C9-C56975AF351E"); private static DebugPortSupplierPrivate s_portSupplier; private class DebugPortSupplierPrivate : DebugPortSupplier { private DebugPort[] _ports; private IDebugCoreServer2 _server; public DebugPortSupplierPrivate() : base(true) { _ports = new DebugPort[] { //new DebugPort(PortFilter.Emulator, this), new DebugPort(PortFilter.Usb, this), //new DebugPort(PortFilter.Serial, this), //new DebugPort(PortFilter.TcpIp, this), }; } public override DebugPort FindPort(string name) { for(int i = 0; i < _ports.Length; i++) { DebugPort port = _ports[i]; if (String.Compare(port.Name, name, true) == 0) { return port; } } return null; } public override DebugPort[] Ports { get {return (DebugPort[])_ports.Clone();} } public override IDebugCoreServer2 CoreServer { [System.Diagnostics.DebuggerHidden] get { return _server; } } private DebugPort DebugPortFromPortFilter(PortFilter portFilter) { foreach (DebugPort port in _ports) { if (port.PortFilter == portFilter) return port; } return null; } #region IDebugPortSupplier2 Members new public int GetPortSupplierId(out Guid pguidPortSupplier) { pguidPortSupplier = DebugPortSupplier.PortSupplierGuid; return COM_HResults.S_OK; } new public int EnumPorts(out IEnumDebugPorts2 ppEnum) { ppEnum = new CorDebugEnum(_ports, typeof(IDebugPort2), typeof(IEnumDebugPorts2)); return COM_HResults.S_OK; } new public int AddPort(IDebugPortRequest2 pRequest, out IDebugPort2 ppPort) { string name; pRequest.GetPortName(out name); ppPort = FindPort(name); if (ppPort == null) { DebugPort port = _ports[(int)PortFilter.TcpIp]; //hack, hack. Abusing the Attach to dialog box to force the NetworkDevice port to //look for a nanoCLR process if (port.TryAddProcess(name) != null) { ppPort = port; } } return COM_HResults.BOOL_TO_HRESULT_FAIL( ppPort != null ); } new public int GetPort(ref Guid guidPort, out IDebugPort2 ppPort) { ppPort = null; foreach (DebugPort port in _ports) { if (guidPort.Equals(port.PortId)) { ppPort = port; break; } } return COM_HResults.S_OK; } #endregion #region IDebugPortSupplierEx2 Members new public int SetServer(IDebugCoreServer2 pServer) { _server = pServer; return COM_HResults.S_OK; } #endregion } private DebugPortSupplier( bool fPrivate ) { } public DebugPortSupplier() { lock (typeof(DebugPortSupplier)) { if(s_portSupplier == null) { s_portSupplier = new DebugPortSupplierPrivate(); } } } public virtual DebugPort[] Ports { get { return s_portSupplier.Ports; } } public virtual DebugPort FindPort(string name) { return s_portSupplier.FindPort(name); } public virtual IDebugCoreServer2 CoreServer { get { return s_portSupplier.CoreServer; } } #region IDebugPortSupplierEx2 Members public int SetServer(IDebugCoreServer2 pServer) { return s_portSupplier.SetServer(pServer); } #endregion #region IDebugPortSupplier2 Members public int GetPortSupplierId(out Guid pguidPortSupplier) { return s_portSupplier.GetPortSupplierId(out pguidPortSupplier); } public int RemovePort(IDebugPort2 pPort) { return COM_HResults.E_NOTIMPL; } public int CanAddPort() { return COM_HResults.S_FALSE; } public int GetPortSupplierName(out string name) { name = ".NET nanoFramework Device"; return COM_HResults.S_OK; } public int EnumPorts(out IEnumDebugPorts2 ppEnum) { return s_portSupplier.EnumPorts(out ppEnum); } public int AddPort(IDebugPortRequest2 pRequest, out IDebugPort2 ppPort) { return s_portSupplier.AddPort(pRequest, out ppPort); } public int GetPort(ref Guid guidPort, out IDebugPort2 ppPort) { return s_portSupplier.GetPort(ref guidPort, out ppPort); } #endregion #region IDebugPortSupplierDescription2 Members int IDebugPortSupplierDescription2.GetDescription(enum_PORT_SUPPLIER_DESCRIPTION_FLAGS[] pdwFlags, out string pbstrText) { pbstrText = "Use this transport to connect to all nanoFramework devices."; return COM_HResults.S_OK; } #endregion } }
using RootSystem = System; using System.Linq; using System.Collections.Generic; namespace Windows.Kinect { // // Windows.Kinect.MultiSourceFrameReader // public sealed partial class MultiSourceFrameReader : RootSystem.IDisposable, Helper.INativeWrapper { internal RootSystem.IntPtr _pNative; RootSystem.IntPtr Helper.INativeWrapper.nativePtr { get { return _pNative; } } // Constructors and Finalizers internal MultiSourceFrameReader(RootSystem.IntPtr pNative) { _pNative = pNative; Windows_Kinect_MultiSourceFrameReader_AddRefObject(ref _pNative); } ~MultiSourceFrameReader() { Dispose(false); } [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern void Windows_Kinect_MultiSourceFrameReader_ReleaseObject(ref RootSystem.IntPtr pNative); [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern void Windows_Kinect_MultiSourceFrameReader_AddRefObject(ref RootSystem.IntPtr pNative); private void Dispose(bool disposing) { if (_pNative == RootSystem.IntPtr.Zero) { return; } __EventCleanup(); Helper.NativeObjectCache.RemoveObject<MultiSourceFrameReader>(_pNative); if (disposing) { Windows_Kinect_MultiSourceFrameReader_Dispose(_pNative); } Windows_Kinect_MultiSourceFrameReader_ReleaseObject(ref _pNative); _pNative = RootSystem.IntPtr.Zero; } // Public Properties [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern Windows.Kinect.FrameSourceTypes Windows_Kinect_MultiSourceFrameReader_get_FrameSourceTypes(RootSystem.IntPtr pNative); public Windows.Kinect.FrameSourceTypes FrameSourceTypes { get { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("MultiSourceFrameReader"); } return Windows_Kinect_MultiSourceFrameReader_get_FrameSourceTypes(_pNative); } } [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern bool Windows_Kinect_MultiSourceFrameReader_get_IsPaused(RootSystem.IntPtr pNative); [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern void Windows_Kinect_MultiSourceFrameReader_put_IsPaused(RootSystem.IntPtr pNative, bool isPaused); public bool IsPaused { get { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("MultiSourceFrameReader"); } return Windows_Kinect_MultiSourceFrameReader_get_IsPaused(_pNative); } set { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("MultiSourceFrameReader"); } Windows_Kinect_MultiSourceFrameReader_put_IsPaused(_pNative, value); Helper.ExceptionHelper.CheckLastError(); } } [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern RootSystem.IntPtr Windows_Kinect_MultiSourceFrameReader_get_KinectSensor(RootSystem.IntPtr pNative); public Windows.Kinect.KinectSensor KinectSensor { get { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("MultiSourceFrameReader"); } RootSystem.IntPtr objectPointer = Windows_Kinect_MultiSourceFrameReader_get_KinectSensor(_pNative); Helper.ExceptionHelper.CheckLastError(); if (objectPointer == RootSystem.IntPtr.Zero) { return null; } return Helper.NativeObjectCache.CreateOrGetObject<Windows.Kinect.KinectSensor>(objectPointer, n => new Windows.Kinect.KinectSensor(n)); } } // Events private static RootSystem.Runtime.InteropServices.GCHandle _Windows_Kinect_MultiSourceFrameArrivedEventArgs_Delegate_Handle; [RootSystem.Runtime.InteropServices.UnmanagedFunctionPointer(RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)] private delegate void _Windows_Kinect_MultiSourceFrameArrivedEventArgs_Delegate(RootSystem.IntPtr args, RootSystem.IntPtr pNative); private static Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Windows.Kinect.MultiSourceFrameArrivedEventArgs>>> Windows_Kinect_MultiSourceFrameArrivedEventArgs_Delegate_callbacks = new Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Windows.Kinect.MultiSourceFrameArrivedEventArgs>>>(); [AOT.MonoPInvokeCallbackAttribute(typeof(_Windows_Kinect_MultiSourceFrameArrivedEventArgs_Delegate))] private static void Windows_Kinect_MultiSourceFrameArrivedEventArgs_Delegate_Handler(RootSystem.IntPtr result, RootSystem.IntPtr pNative) { List<RootSystem.EventHandler<Windows.Kinect.MultiSourceFrameArrivedEventArgs>> callbackList = null; Windows_Kinect_MultiSourceFrameArrivedEventArgs_Delegate_callbacks.TryGetValue(pNative, out callbackList); lock(callbackList) { var objThis = Helper.NativeObjectCache.GetObject<MultiSourceFrameReader>(pNative); var args = new Windows.Kinect.MultiSourceFrameArrivedEventArgs(result); foreach(var func in callbackList) { Helper.EventPump.Instance.Enqueue(() => { try { func(objThis, args); } catch { } }); } } } [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern void Windows_Kinect_MultiSourceFrameReader_add_MultiSourceFrameArrived(RootSystem.IntPtr pNative, _Windows_Kinect_MultiSourceFrameArrivedEventArgs_Delegate eventCallback, bool unsubscribe); public event RootSystem.EventHandler<Windows.Kinect.MultiSourceFrameArrivedEventArgs> MultiSourceFrameArrived { add { Helper.EventPump.EnsureInitialized(); Windows_Kinect_MultiSourceFrameArrivedEventArgs_Delegate_callbacks.TryAddDefault(_pNative); var callbackList = Windows_Kinect_MultiSourceFrameArrivedEventArgs_Delegate_callbacks[_pNative]; lock (callbackList) { callbackList.Add(value); if(callbackList.Count == 1) { var del = new _Windows_Kinect_MultiSourceFrameArrivedEventArgs_Delegate(Windows_Kinect_MultiSourceFrameArrivedEventArgs_Delegate_Handler); _Windows_Kinect_MultiSourceFrameArrivedEventArgs_Delegate_Handle = RootSystem.Runtime.InteropServices.GCHandle.Alloc(del); Windows_Kinect_MultiSourceFrameReader_add_MultiSourceFrameArrived(_pNative, del, false); } } } remove { if (_pNative == RootSystem.IntPtr.Zero) { return; } Windows_Kinect_MultiSourceFrameArrivedEventArgs_Delegate_callbacks.TryAddDefault(_pNative); var callbackList = Windows_Kinect_MultiSourceFrameArrivedEventArgs_Delegate_callbacks[_pNative]; lock (callbackList) { callbackList.Remove(value); if(callbackList.Count == 0) { Windows_Kinect_MultiSourceFrameReader_add_MultiSourceFrameArrived(_pNative, Windows_Kinect_MultiSourceFrameArrivedEventArgs_Delegate_Handler, true); _Windows_Kinect_MultiSourceFrameArrivedEventArgs_Delegate_Handle.Free(); } } } } private static RootSystem.Runtime.InteropServices.GCHandle _Windows_Data_PropertyChangedEventArgs_Delegate_Handle; [RootSystem.Runtime.InteropServices.UnmanagedFunctionPointer(RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)] private delegate void _Windows_Data_PropertyChangedEventArgs_Delegate(RootSystem.IntPtr args, RootSystem.IntPtr pNative); private static Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs>>> Windows_Data_PropertyChangedEventArgs_Delegate_callbacks = new Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs>>>(); [AOT.MonoPInvokeCallbackAttribute(typeof(_Windows_Data_PropertyChangedEventArgs_Delegate))] private static void Windows_Data_PropertyChangedEventArgs_Delegate_Handler(RootSystem.IntPtr result, RootSystem.IntPtr pNative) { List<RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs>> callbackList = null; Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryGetValue(pNative, out callbackList); lock(callbackList) { var objThis = Helper.NativeObjectCache.GetObject<MultiSourceFrameReader>(pNative); var args = new Windows.Data.PropertyChangedEventArgs(result); foreach(var func in callbackList) { Helper.EventPump.Instance.Enqueue(() => { try { func(objThis, args); } catch { } }); } } } [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern void Windows_Kinect_MultiSourceFrameReader_add_PropertyChanged(RootSystem.IntPtr pNative, _Windows_Data_PropertyChangedEventArgs_Delegate eventCallback, bool unsubscribe); public event RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs> PropertyChanged { add { Helper.EventPump.EnsureInitialized(); Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryAddDefault(_pNative); var callbackList = Windows_Data_PropertyChangedEventArgs_Delegate_callbacks[_pNative]; lock (callbackList) { callbackList.Add(value); if(callbackList.Count == 1) { var del = new _Windows_Data_PropertyChangedEventArgs_Delegate(Windows_Data_PropertyChangedEventArgs_Delegate_Handler); _Windows_Data_PropertyChangedEventArgs_Delegate_Handle = RootSystem.Runtime.InteropServices.GCHandle.Alloc(del); Windows_Kinect_MultiSourceFrameReader_add_PropertyChanged(_pNative, del, false); } } } remove { if (_pNative == RootSystem.IntPtr.Zero) { return; } Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryAddDefault(_pNative); var callbackList = Windows_Data_PropertyChangedEventArgs_Delegate_callbacks[_pNative]; lock (callbackList) { callbackList.Remove(value); if(callbackList.Count == 0) { Windows_Kinect_MultiSourceFrameReader_add_PropertyChanged(_pNative, Windows_Data_PropertyChangedEventArgs_Delegate_Handler, true); _Windows_Data_PropertyChangedEventArgs_Delegate_Handle.Free(); } } } } // Public Methods [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern RootSystem.IntPtr Windows_Kinect_MultiSourceFrameReader_AcquireLatestFrame(RootSystem.IntPtr pNative); public Windows.Kinect.MultiSourceFrame AcquireLatestFrame() { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("MultiSourceFrameReader"); } RootSystem.IntPtr objectPointer = Windows_Kinect_MultiSourceFrameReader_AcquireLatestFrame(_pNative); Helper.ExceptionHelper.CheckLastError(); if (objectPointer == RootSystem.IntPtr.Zero) { return null; } return Helper.NativeObjectCache.CreateOrGetObject<Windows.Kinect.MultiSourceFrame>(objectPointer, n => new Windows.Kinect.MultiSourceFrame(n)); } [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern void Windows_Kinect_MultiSourceFrameReader_Dispose(RootSystem.IntPtr pNative); public void Dispose() { if (_pNative == RootSystem.IntPtr.Zero) { return; } Dispose(true); RootSystem.GC.SuppressFinalize(this); } private void __EventCleanup() { { Windows_Kinect_MultiSourceFrameArrivedEventArgs_Delegate_callbacks.TryAddDefault(_pNative); var callbackList = Windows_Kinect_MultiSourceFrameArrivedEventArgs_Delegate_callbacks[_pNative]; lock (callbackList) { if (callbackList.Count > 0) { callbackList.Clear(); if (_pNative != RootSystem.IntPtr.Zero) { Windows_Kinect_MultiSourceFrameReader_add_MultiSourceFrameArrived(_pNative, Windows_Kinect_MultiSourceFrameArrivedEventArgs_Delegate_Handler, true); } _Windows_Kinect_MultiSourceFrameArrivedEventArgs_Delegate_Handle.Free(); } } } { Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryAddDefault(_pNative); var callbackList = Windows_Data_PropertyChangedEventArgs_Delegate_callbacks[_pNative]; lock (callbackList) { if (callbackList.Count > 0) { callbackList.Clear(); if (_pNative != RootSystem.IntPtr.Zero) { Windows_Kinect_MultiSourceFrameReader_add_PropertyChanged(_pNative, Windows_Data_PropertyChangedEventArgs_Delegate_Handler, true); } _Windows_Data_PropertyChangedEventArgs_Delegate_Handle.Free(); } } } } } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; namespace _4PosBackOffice.NET { [Microsoft.VisualBasic.CompilerServices.DesignerGenerated()] partial class frmStockTransferItem { #region "Windows Form Designer generated code " [System.Diagnostics.DebuggerNonUserCode()] public frmStockTransferItem() : base() { KeyPress += frmStockTransferItem_KeyPress; //This call is required by the Windows Form Designer. InitializeComponent(); } //Form overrides dispose to clean up the component list. [System.Diagnostics.DebuggerNonUserCode()] protected override void Dispose(bool Disposing) { if (Disposing) { if ((components != null)) { components.Dispose(); } } base.Dispose(Disposing); } //Required by the Windows Form Designer private System.ComponentModel.IContainer components; public System.Windows.Forms.ToolTip ToolTip1; private System.Windows.Forms.TextBox withEventsField_txtQtyT; public System.Windows.Forms.TextBox txtQtyT { get { return withEventsField_txtQtyT; } set { if (withEventsField_txtQtyT != null) { withEventsField_txtQtyT.TextChanged -= txtQtyT_TextChanged; withEventsField_txtQtyT.KeyPress -= txtQtyT_KeyPress; withEventsField_txtQtyT.Enter -= txtQtyT_Enter; withEventsField_txtQtyT.Leave -= txtQtyT_Leave; } withEventsField_txtQtyT = value; if (withEventsField_txtQtyT != null) { withEventsField_txtQtyT.TextChanged += txtQtyT_TextChanged; withEventsField_txtQtyT.KeyPress += txtQtyT_KeyPress; withEventsField_txtQtyT.Enter += txtQtyT_Enter; withEventsField_txtQtyT.Leave += txtQtyT_Leave; } } } public System.Windows.Forms.TextBox txtPSize; public System.Windows.Forms.TextBox txtPack; private System.Windows.Forms.TextBox withEventsField_txtPriceS; public System.Windows.Forms.TextBox txtPriceS { get { return withEventsField_txtPriceS; } set { if (withEventsField_txtPriceS != null) { withEventsField_txtPriceS.Enter -= txtPriceS_Enter; withEventsField_txtPriceS.Leave -= txtPriceS_Leave; } withEventsField_txtPriceS = value; if (withEventsField_txtPriceS != null) { withEventsField_txtPriceS.Enter += txtPriceS_Enter; withEventsField_txtPriceS.Leave += txtPriceS_Leave; } } } private System.Windows.Forms.TextBox withEventsField_txtQty; public System.Windows.Forms.TextBox txtQty { get { return withEventsField_txtQty; } set { if (withEventsField_txtQty != null) { withEventsField_txtQty.KeyPress -= txtQty_KeyPress; withEventsField_txtQty.Enter -= txtQty_Enter; withEventsField_txtQty.Leave -= txtQty_Leave; } withEventsField_txtQty = value; if (withEventsField_txtQty != null) { withEventsField_txtQty.KeyPress += txtQty_KeyPress; withEventsField_txtQty.Enter += txtQty_Enter; withEventsField_txtQty.Leave += txtQty_Leave; } } } private System.Windows.Forms.TextBox withEventsField_txtPrice; public System.Windows.Forms.TextBox txtPrice { get { return withEventsField_txtPrice; } set { if (withEventsField_txtPrice != null) { withEventsField_txtPrice.Enter -= txtPrice_Enter; withEventsField_txtPrice.KeyPress -= txtPrice_KeyPress; withEventsField_txtPrice.Leave -= txtPrice_Leave; } withEventsField_txtPrice = value; if (withEventsField_txtPrice != null) { withEventsField_txtPrice.Enter += txtPrice_Enter; withEventsField_txtPrice.KeyPress += txtPrice_KeyPress; withEventsField_txtPrice.Leave += txtPrice_Leave; } } } public System.Windows.Forms.ComboBox cmbQuantity; private System.Windows.Forms.Button withEventsField_cmdPack; public System.Windows.Forms.Button cmdPack { get { return withEventsField_cmdPack; } set { if (withEventsField_cmdPack != null) { withEventsField_cmdPack.Click -= cmdPack_Click; } withEventsField_cmdPack = value; if (withEventsField_cmdPack != null) { withEventsField_cmdPack.Click += cmdPack_Click; } } } private System.Windows.Forms.Button withEventsField_cmdCancel; public System.Windows.Forms.Button cmdCancel { get { return withEventsField_cmdCancel; } set { if (withEventsField_cmdCancel != null) { withEventsField_cmdCancel.Click -= cmdCancel_Click; } withEventsField_cmdCancel = value; if (withEventsField_cmdCancel != null) { withEventsField_cmdCancel.Click += cmdCancel_Click; } } } private System.Windows.Forms.Button withEventsField_cmdClose; public System.Windows.Forms.Button cmdClose { get { return withEventsField_cmdClose; } set { if (withEventsField_cmdClose != null) { withEventsField_cmdClose.Click -= cmdClose_Click; } withEventsField_cmdClose = value; if (withEventsField_cmdClose != null) { withEventsField_cmdClose.Click += cmdClose_Click; } } } public System.Windows.Forms.Panel picButtons; public System.Windows.Forms.Label _LBL_6; public System.Windows.Forms.Label _LBL_4; public System.Windows.Forms.Label Label2; public System.Windows.Forms.Label lblPComp; public System.Windows.Forms.Label lblSComp; public System.Windows.Forms.Label lblStockItemS; public System.Windows.Forms.Label _LBL_5; public System.Windows.Forms.Label _LBL_0; public System.Windows.Forms.Label _LBL_3; public System.Windows.Forms.Label _LBL_2; public System.Windows.Forms.Label _LBL_1; public System.Windows.Forms.Label lblStockItem; public Microsoft.VisualBasic.PowerPacks.RectangleShape _Shape1_2; public Microsoft.VisualBasic.PowerPacks.RectangleShape _Shape1_0; //Public WithEvents LBL As Microsoft.VisualBasic.Compatibility.VB6.LabelArray public RectangleShapeArray Shape1; public Microsoft.VisualBasic.PowerPacks.ShapeContainer ShapeContainer1; //NOTE: The following procedure is required by the Windows Form Designer //It can be modified using the Windows Form Designer. //Do not modify it using the code editor. [System.Diagnostics.DebuggerStepThrough()] private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmStockTransferItem)); this.components = new System.ComponentModel.Container(); this.ToolTip1 = new System.Windows.Forms.ToolTip(components); this.ShapeContainer1 = new Microsoft.VisualBasic.PowerPacks.ShapeContainer(); this.txtQtyT = new System.Windows.Forms.TextBox(); this.txtPSize = new System.Windows.Forms.TextBox(); this.txtPack = new System.Windows.Forms.TextBox(); this.txtPriceS = new System.Windows.Forms.TextBox(); this.txtQty = new System.Windows.Forms.TextBox(); this.txtPrice = new System.Windows.Forms.TextBox(); this.cmbQuantity = new System.Windows.Forms.ComboBox(); this.picButtons = new System.Windows.Forms.Panel(); this.cmdPack = new System.Windows.Forms.Button(); this.cmdCancel = new System.Windows.Forms.Button(); this.cmdClose = new System.Windows.Forms.Button(); this._LBL_6 = new System.Windows.Forms.Label(); this._LBL_4 = new System.Windows.Forms.Label(); this.Label2 = new System.Windows.Forms.Label(); this.lblPComp = new System.Windows.Forms.Label(); this.lblSComp = new System.Windows.Forms.Label(); this.lblStockItemS = new System.Windows.Forms.Label(); this._LBL_5 = new System.Windows.Forms.Label(); this._LBL_0 = new System.Windows.Forms.Label(); this._LBL_3 = new System.Windows.Forms.Label(); this._LBL_2 = new System.Windows.Forms.Label(); this._LBL_1 = new System.Windows.Forms.Label(); this.lblStockItem = new System.Windows.Forms.Label(); this._Shape1_2 = new Microsoft.VisualBasic.PowerPacks.RectangleShape(); this._Shape1_0 = new Microsoft.VisualBasic.PowerPacks.RectangleShape(); //Me.LBL = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components) this.Shape1 = new RectangleShapeArray(components); this.picButtons.SuspendLayout(); this.SuspendLayout(); this.ToolTip1.Active = true; //CType(Me.LBL, System.ComponentModel.ISupportInitialize).BeginInit() ((System.ComponentModel.ISupportInitialize)this.Shape1).BeginInit(); this.BackColor = System.Drawing.Color.FromArgb(224, 224, 224); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Text = "Edit Stock Transfer Item"; this.ClientSize = new System.Drawing.Size(400, 249); this.Location = new System.Drawing.Point(3, 22); this.ControlBox = false; this.KeyPreview = true; this.MaximizeBox = false; this.MinimizeBox = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Enabled = true; this.Cursor = System.Windows.Forms.Cursors.Default; this.RightToLeft = System.Windows.Forms.RightToLeft.No; this.HelpButton = false; this.WindowState = System.Windows.Forms.FormWindowState.Normal; this.Name = "frmStockTransferItem"; this.txtQtyT.AutoSize = false; this.txtQtyT.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.txtQtyT.Size = new System.Drawing.Size(67, 19); this.txtQtyT.Location = new System.Drawing.Point(96, 97); this.txtQtyT.TabIndex = 20; this.txtQtyT.Text = "0"; this.txtQtyT.AcceptsReturn = true; this.txtQtyT.BackColor = System.Drawing.SystemColors.Window; this.txtQtyT.CausesValidation = true; this.txtQtyT.Enabled = true; this.txtQtyT.ForeColor = System.Drawing.SystemColors.WindowText; this.txtQtyT.HideSelection = true; this.txtQtyT.ReadOnly = false; this.txtQtyT.MaxLength = 0; this.txtQtyT.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtQtyT.Multiline = false; this.txtQtyT.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtQtyT.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtQtyT.TabStop = true; this.txtQtyT.Visible = true; this.txtQtyT.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.txtQtyT.Name = "txtQtyT"; this.txtPSize.AutoSize = false; this.txtPSize.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; this.txtPSize.Enabled = false; this.txtPSize.Size = new System.Drawing.Size(27, 19); this.txtPSize.Location = new System.Drawing.Point(184, 97); this.txtPSize.TabIndex = 19; this.txtPSize.Text = "1"; this.txtPSize.AcceptsReturn = true; this.txtPSize.BackColor = System.Drawing.SystemColors.Window; this.txtPSize.CausesValidation = true; this.txtPSize.ForeColor = System.Drawing.SystemColors.WindowText; this.txtPSize.HideSelection = true; this.txtPSize.ReadOnly = false; this.txtPSize.MaxLength = 0; this.txtPSize.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtPSize.Multiline = false; this.txtPSize.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtPSize.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtPSize.TabStop = true; this.txtPSize.Visible = true; this.txtPSize.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.txtPSize.Name = "txtPSize"; this.txtPack.AutoSize = false; this.txtPack.Size = new System.Drawing.Size(41, 19); this.txtPack.Location = new System.Drawing.Point(352, 160); this.txtPack.TabIndex = 17; this.txtPack.Text = "0"; this.txtPack.AcceptsReturn = true; this.txtPack.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this.txtPack.BackColor = System.Drawing.SystemColors.Window; this.txtPack.CausesValidation = true; this.txtPack.Enabled = true; this.txtPack.ForeColor = System.Drawing.SystemColors.WindowText; this.txtPack.HideSelection = true; this.txtPack.ReadOnly = false; this.txtPack.MaxLength = 0; this.txtPack.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtPack.Multiline = false; this.txtPack.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtPack.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtPack.TabStop = true; this.txtPack.Visible = true; this.txtPack.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.txtPack.Name = "txtPack"; this.txtPriceS.AutoSize = false; this.txtPriceS.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.txtPriceS.Enabled = false; this.txtPriceS.Size = new System.Drawing.Size(91, 19); this.txtPriceS.Location = new System.Drawing.Point(291, 234); this.txtPriceS.TabIndex = 9; this.txtPriceS.Text = "0.00"; this.txtPriceS.Visible = false; this.txtPriceS.AcceptsReturn = true; this.txtPriceS.BackColor = System.Drawing.SystemColors.Window; this.txtPriceS.CausesValidation = true; this.txtPriceS.ForeColor = System.Drawing.SystemColors.WindowText; this.txtPriceS.HideSelection = true; this.txtPriceS.ReadOnly = false; this.txtPriceS.MaxLength = 0; this.txtPriceS.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtPriceS.Multiline = false; this.txtPriceS.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtPriceS.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtPriceS.TabStop = true; this.txtPriceS.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.txtPriceS.Name = "txtPriceS"; this.txtQty.AutoSize = false; this.txtQty.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.txtQty.Size = new System.Drawing.Size(67, 19); this.txtQty.Location = new System.Drawing.Point(316, 97); this.txtQty.ReadOnly = true; this.txtQty.TabIndex = 8; this.txtQty.Text = "0"; this.txtQty.AcceptsReturn = true; this.txtQty.BackColor = System.Drawing.SystemColors.Window; this.txtQty.CausesValidation = true; this.txtQty.Enabled = true; this.txtQty.ForeColor = System.Drawing.SystemColors.WindowText; this.txtQty.HideSelection = true; this.txtQty.MaxLength = 0; this.txtQty.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtQty.Multiline = false; this.txtQty.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtQty.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtQty.TabStop = true; this.txtQty.Visible = true; this.txtQty.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.txtQty.Name = "txtQty"; this.txtPrice.AutoSize = false; this.txtPrice.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.txtPrice.Enabled = false; this.txtPrice.Size = new System.Drawing.Size(91, 19); this.txtPrice.Location = new System.Drawing.Point(293, 121); this.txtPrice.TabIndex = 4; this.txtPrice.Text = "0.00"; this.txtPrice.AcceptsReturn = true; this.txtPrice.BackColor = System.Drawing.SystemColors.Window; this.txtPrice.CausesValidation = true; this.txtPrice.ForeColor = System.Drawing.SystemColors.WindowText; this.txtPrice.HideSelection = true; this.txtPrice.ReadOnly = false; this.txtPrice.MaxLength = 0; this.txtPrice.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtPrice.Multiline = false; this.txtPrice.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtPrice.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtPrice.TabStop = true; this.txtPrice.Visible = true; this.txtPrice.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.txtPrice.Name = "txtPrice"; this.cmbQuantity.Size = new System.Drawing.Size(79, 21); this.cmbQuantity.Location = new System.Drawing.Point(184, 96); this.cmbQuantity.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cmbQuantity.TabIndex = 3; this.cmbQuantity.Visible = false; this.cmbQuantity.BackColor = System.Drawing.SystemColors.Window; this.cmbQuantity.CausesValidation = true; this.cmbQuantity.Enabled = true; this.cmbQuantity.ForeColor = System.Drawing.SystemColors.WindowText; this.cmbQuantity.IntegralHeight = true; this.cmbQuantity.Cursor = System.Windows.Forms.Cursors.Default; this.cmbQuantity.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmbQuantity.Sorted = false; this.cmbQuantity.TabStop = true; this.cmbQuantity.Name = "cmbQuantity"; this.picButtons.Dock = System.Windows.Forms.DockStyle.Top; this.picButtons.BackColor = System.Drawing.Color.Blue; this.picButtons.Size = new System.Drawing.Size(400, 39); this.picButtons.Location = new System.Drawing.Point(0, 0); this.picButtons.TabIndex = 0; this.picButtons.TabStop = false; this.picButtons.CausesValidation = true; this.picButtons.Enabled = true; this.picButtons.ForeColor = System.Drawing.SystemColors.ControlText; this.picButtons.Cursor = System.Windows.Forms.Cursors.Default; this.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No; this.picButtons.Visible = true; this.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.picButtons.Name = "picButtons"; this.cmdPack.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdPack.Text = "Break / Build P&ack"; this.cmdPack.Size = new System.Drawing.Size(105, 29); this.cmdPack.Location = new System.Drawing.Point(88, 3); this.cmdPack.TabIndex = 18; this.cmdPack.TabStop = false; this.cmdPack.BackColor = System.Drawing.SystemColors.Control; this.cmdPack.CausesValidation = true; this.cmdPack.Enabled = true; this.cmdPack.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdPack.Cursor = System.Windows.Forms.Cursors.Default; this.cmdPack.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdPack.Name = "cmdPack"; this.cmdCancel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdCancel.Text = "&Undo"; this.cmdCancel.Size = new System.Drawing.Size(73, 29); this.cmdCancel.Location = new System.Drawing.Point(8, 3); this.cmdCancel.TabIndex = 16; this.cmdCancel.TabStop = false; this.cmdCancel.BackColor = System.Drawing.SystemColors.Control; this.cmdCancel.CausesValidation = true; this.cmdCancel.Enabled = true; this.cmdCancel.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdCancel.Cursor = System.Windows.Forms.Cursors.Default; this.cmdCancel.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdCancel.Name = "cmdCancel"; this.cmdClose.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdClose.Text = "E&xit"; this.cmdClose.Size = new System.Drawing.Size(73, 29); this.cmdClose.Location = new System.Drawing.Point(312, 3); this.cmdClose.TabIndex = 1; this.cmdClose.TabStop = false; this.cmdClose.BackColor = System.Drawing.SystemColors.Control; this.cmdClose.CausesValidation = true; this.cmdClose.Enabled = true; this.cmdClose.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdClose.Cursor = System.Windows.Forms.Cursors.Default; this.cmdClose.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdClose.Name = "cmdClose"; this._LBL_6.TextAlign = System.Drawing.ContentAlignment.TopRight; this._LBL_6.Text = "Item Qty:"; this._LBL_6.Size = new System.Drawing.Size(42, 13); this._LBL_6.Location = new System.Drawing.Point(52, 99); this._LBL_6.TabIndex = 22; this._LBL_6.BackColor = System.Drawing.Color.Transparent; this._LBL_6.Enabled = true; this._LBL_6.ForeColor = System.Drawing.SystemColors.ControlText; this._LBL_6.Cursor = System.Windows.Forms.Cursors.Default; this._LBL_6.RightToLeft = System.Windows.Forms.RightToLeft.No; this._LBL_6.UseMnemonic = true; this._LBL_6.Visible = true; this._LBL_6.AutoSize = true; this._LBL_6.BorderStyle = System.Windows.Forms.BorderStyle.None; this._LBL_6.Name = "_LBL_6"; this._LBL_4.TextAlign = System.Drawing.ContentAlignment.TopRight; this._LBL_4.Text = "x"; this._LBL_4.Size = new System.Drawing.Size(8, 16); this._LBL_4.Location = new System.Drawing.Point(170, 98); this._LBL_4.TabIndex = 21; this._LBL_4.BackColor = System.Drawing.Color.Transparent; this._LBL_4.Enabled = true; this._LBL_4.ForeColor = System.Drawing.SystemColors.ControlText; this._LBL_4.Cursor = System.Windows.Forms.Cursors.Default; this._LBL_4.RightToLeft = System.Windows.Forms.RightToLeft.No; this._LBL_4.UseMnemonic = true; this._LBL_4.Visible = true; this._LBL_4.AutoSize = true; this._LBL_4.BorderStyle = System.Windows.Forms.BorderStyle.None; this._LBL_4.Name = "_LBL_4"; this.Label2.Text = "Please verify products from both locations"; this.Label2.ForeColor = System.Drawing.Color.FromArgb(192, 0, 0); this.Label2.Size = new System.Drawing.Size(296, 23); this.Label2.Location = new System.Drawing.Point(56, 160); this.Label2.TabIndex = 15; this.Label2.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.Label2.BackColor = System.Drawing.Color.Transparent; this.Label2.Enabled = true; this.Label2.Cursor = System.Windows.Forms.Cursors.Default; this.Label2.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label2.UseMnemonic = true; this.Label2.Visible = true; this.Label2.AutoSize = false; this.Label2.BorderStyle = System.Windows.Forms.BorderStyle.None; this.Label2.Name = "Label2"; this.lblPComp.Text = "Promotion Name:"; this.lblPComp.Size = new System.Drawing.Size(352, 24); this.lblPComp.Location = new System.Drawing.Point(16, 52); this.lblPComp.TabIndex = 14; this.lblPComp.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.lblPComp.BackColor = System.Drawing.Color.Transparent; this.lblPComp.Enabled = true; this.lblPComp.ForeColor = System.Drawing.SystemColors.ControlText; this.lblPComp.Cursor = System.Windows.Forms.Cursors.Default; this.lblPComp.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblPComp.UseMnemonic = true; this.lblPComp.Visible = true; this.lblPComp.AutoSize = false; this.lblPComp.BorderStyle = System.Windows.Forms.BorderStyle.None; this.lblPComp.Name = "lblPComp"; this.lblSComp.Text = "Promotion Name:"; this.lblSComp.Size = new System.Drawing.Size(360, 24); this.lblSComp.Location = new System.Drawing.Point(16, 192); this.lblSComp.TabIndex = 13; this.lblSComp.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.lblSComp.BackColor = System.Drawing.Color.Transparent; this.lblSComp.Enabled = true; this.lblSComp.ForeColor = System.Drawing.SystemColors.ControlText; this.lblSComp.Cursor = System.Windows.Forms.Cursors.Default; this.lblSComp.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblSComp.UseMnemonic = true; this.lblSComp.Visible = true; this.lblSComp.AutoSize = false; this.lblSComp.BorderStyle = System.Windows.Forms.BorderStyle.None; this.lblSComp.Name = "lblSComp"; this.lblStockItemS.Text = "Label1"; this.lblStockItemS.Size = new System.Drawing.Size(286, 17); this.lblStockItemS.Location = new System.Drawing.Point(98, 216); this.lblStockItemS.TabIndex = 12; this.lblStockItemS.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.lblStockItemS.BackColor = System.Drawing.SystemColors.Control; this.lblStockItemS.Enabled = true; this.lblStockItemS.ForeColor = System.Drawing.SystemColors.ControlText; this.lblStockItemS.Cursor = System.Windows.Forms.Cursors.Default; this.lblStockItemS.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblStockItemS.UseMnemonic = true; this.lblStockItemS.Visible = true; this.lblStockItemS.AutoSize = false; this.lblStockItemS.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblStockItemS.Name = "lblStockItemS"; this._LBL_5.TextAlign = System.Drawing.ContentAlignment.TopRight; this._LBL_5.Text = "Stock Item Name:"; this._LBL_5.Size = new System.Drawing.Size(85, 13); this._LBL_5.Location = new System.Drawing.Point(10, 184); this._LBL_5.TabIndex = 11; this._LBL_5.BackColor = System.Drawing.Color.Transparent; this._LBL_5.Enabled = true; this._LBL_5.ForeColor = System.Drawing.SystemColors.ControlText; this._LBL_5.Cursor = System.Windows.Forms.Cursors.Default; this._LBL_5.RightToLeft = System.Windows.Forms.RightToLeft.No; this._LBL_5.UseMnemonic = true; this._LBL_5.Visible = true; this._LBL_5.AutoSize = true; this._LBL_5.BorderStyle = System.Windows.Forms.BorderStyle.None; this._LBL_5.Name = "_LBL_5"; this._LBL_0.TextAlign = System.Drawing.ContentAlignment.TopRight; this._LBL_0.Text = "Price:"; this._LBL_0.Size = new System.Drawing.Size(27, 13); this._LBL_0.Location = new System.Drawing.Point(260, 237); this._LBL_0.TabIndex = 10; this._LBL_0.Visible = false; this._LBL_0.BackColor = System.Drawing.Color.Transparent; this._LBL_0.Enabled = true; this._LBL_0.ForeColor = System.Drawing.SystemColors.ControlText; this._LBL_0.Cursor = System.Windows.Forms.Cursors.Default; this._LBL_0.RightToLeft = System.Windows.Forms.RightToLeft.No; this._LBL_0.UseMnemonic = true; this._LBL_0.AutoSize = true; this._LBL_0.BorderStyle = System.Windows.Forms.BorderStyle.None; this._LBL_0.Name = "_LBL_0"; this._LBL_3.TextAlign = System.Drawing.ContentAlignment.TopRight; this._LBL_3.Text = "Cost Price (singles) :"; this._LBL_3.Size = new System.Drawing.Size(95, 13); this._LBL_3.Location = new System.Drawing.Point(194, 124); this._LBL_3.TabIndex = 7; this._LBL_3.BackColor = System.Drawing.Color.Transparent; this._LBL_3.Enabled = true; this._LBL_3.ForeColor = System.Drawing.SystemColors.ControlText; this._LBL_3.Cursor = System.Windows.Forms.Cursors.Default; this._LBL_3.RightToLeft = System.Windows.Forms.RightToLeft.No; this._LBL_3.UseMnemonic = true; this._LBL_3.Visible = true; this._LBL_3.AutoSize = true; this._LBL_3.BorderStyle = System.Windows.Forms.BorderStyle.None; this._LBL_3.Name = "_LBL_3"; this._LBL_2.TextAlign = System.Drawing.ContentAlignment.TopRight; this._LBL_2.Text = "Total Qty:"; this._LBL_2.Size = new System.Drawing.Size(46, 13); this._LBL_2.Location = new System.Drawing.Point(268, 99); this._LBL_2.TabIndex = 6; this._LBL_2.BackColor = System.Drawing.Color.Transparent; this._LBL_2.Enabled = true; this._LBL_2.ForeColor = System.Drawing.SystemColors.ControlText; this._LBL_2.Cursor = System.Windows.Forms.Cursors.Default; this._LBL_2.RightToLeft = System.Windows.Forms.RightToLeft.No; this._LBL_2.UseMnemonic = true; this._LBL_2.Visible = true; this._LBL_2.AutoSize = true; this._LBL_2.BorderStyle = System.Windows.Forms.BorderStyle.None; this._LBL_2.Name = "_LBL_2"; this._LBL_1.TextAlign = System.Drawing.ContentAlignment.TopRight; this._LBL_1.Text = "Stock Item Name:"; this._LBL_1.Size = new System.Drawing.Size(85, 13); this._LBL_1.Location = new System.Drawing.Point(10, 79); this._LBL_1.TabIndex = 5; this._LBL_1.BackColor = System.Drawing.Color.Transparent; this._LBL_1.Enabled = true; this._LBL_1.ForeColor = System.Drawing.SystemColors.ControlText; this._LBL_1.Cursor = System.Windows.Forms.Cursors.Default; this._LBL_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this._LBL_1.UseMnemonic = true; this._LBL_1.Visible = true; this._LBL_1.AutoSize = true; this._LBL_1.BorderStyle = System.Windows.Forms.BorderStyle.None; this._LBL_1.Name = "_LBL_1"; this.lblStockItem.Text = "Label1"; this.lblStockItem.Size = new System.Drawing.Size(286, 17); this.lblStockItem.Location = new System.Drawing.Point(98, 79); this.lblStockItem.TabIndex = 2; this.lblStockItem.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.lblStockItem.BackColor = System.Drawing.SystemColors.Control; this.lblStockItem.Enabled = true; this.lblStockItem.ForeColor = System.Drawing.SystemColors.ControlText; this.lblStockItem.Cursor = System.Windows.Forms.Cursors.Default; this.lblStockItem.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblStockItem.UseMnemonic = true; this.lblStockItem.Visible = true; this.lblStockItem.AutoSize = false; this.lblStockItem.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblStockItem.Name = "lblStockItem"; this._Shape1_2.BackColor = System.Drawing.Color.FromArgb(192, 192, 255); this._Shape1_2.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque; this._Shape1_2.Size = new System.Drawing.Size(383, 104); this._Shape1_2.Location = new System.Drawing.Point(7, 48); this._Shape1_2.BorderColor = System.Drawing.SystemColors.WindowText; this._Shape1_2.BorderStyle = System.Drawing.Drawing2D.DashStyle.Solid; this._Shape1_2.BorderWidth = 1; this._Shape1_2.FillColor = System.Drawing.Color.Black; this._Shape1_2.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Transparent; this._Shape1_2.Visible = true; this._Shape1_2.Name = "_Shape1_2"; this._Shape1_0.BackColor = System.Drawing.Color.FromArgb(192, 192, 255); this._Shape1_0.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque; this._Shape1_0.Size = new System.Drawing.Size(383, 56); this._Shape1_0.Location = new System.Drawing.Point(7, 184); this._Shape1_0.BorderColor = System.Drawing.SystemColors.WindowText; this._Shape1_0.BorderStyle = System.Drawing.Drawing2D.DashStyle.Solid; this._Shape1_0.BorderWidth = 1; this._Shape1_0.FillColor = System.Drawing.Color.Black; this._Shape1_0.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Transparent; this._Shape1_0.Visible = true; this._Shape1_0.Name = "_Shape1_0"; this.Controls.Add(txtQtyT); this.Controls.Add(txtPSize); this.Controls.Add(txtPack); this.Controls.Add(txtPriceS); this.Controls.Add(txtQty); this.Controls.Add(txtPrice); this.Controls.Add(cmbQuantity); this.Controls.Add(picButtons); this.Controls.Add(_LBL_6); this.Controls.Add(_LBL_4); this.Controls.Add(Label2); this.Controls.Add(lblPComp); this.Controls.Add(lblSComp); this.Controls.Add(lblStockItemS); this.Controls.Add(_LBL_5); this.Controls.Add(_LBL_0); this.Controls.Add(_LBL_3); this.Controls.Add(_LBL_2); this.Controls.Add(_LBL_1); this.Controls.Add(lblStockItem); this.ShapeContainer1.Shapes.Add(_Shape1_2); this.ShapeContainer1.Shapes.Add(_Shape1_0); this.Controls.Add(ShapeContainer1); this.picButtons.Controls.Add(cmdPack); this.picButtons.Controls.Add(cmdCancel); this.picButtons.Controls.Add(cmdClose); //Me.LBL.SetIndex(_LBL_6, CType(6, Short)) //Me.LBL.SetIndex(_LBL_4, CType(4, Short)) //Me.LBL.SetIndex(_LBL_5, CType(5, Short)) //Me.LBL.SetIndex(_LBL_0, CType(0, Short)) //Me.LBL.SetIndex(_LBL_3, CType(3, Short)) //Me.LBL.SetIndex(_LBL_2, CType(2, Short)) //Me.LBL.SetIndex(_LBL_1, CType(1, Short)) this.Shape1.SetIndex(_Shape1_2, Convert.ToInt16(2)); this.Shape1.SetIndex(_Shape1_0, Convert.ToInt16(0)); ((System.ComponentModel.ISupportInitialize)this.Shape1).EndInit(); //CType(Me.LBL, System.ComponentModel.ISupportInitialize).EndInit() this.picButtons.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion } }