context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Copyright 2005-2012 Moonfire Games // Released under the MIT license // http://mfgames.com/mfgames-cil/license using System; using System.Text.RegularExpressions; namespace MfGames { /// <summary> /// Implements a full-featured version parsing and comparison class. This, like /// <see cref="string">String</see> is an immutable class. Any methods that would /// somehow change a field instead return a new ExtendedVersion object. /// </summary> [Serializable] public class ExtendedVersion { #region Methods /// <summary> /// A Debian-like parsing of version numbers that encodes the /// operation into the string. For example, "&gt; 2.3.4" would be /// true if the ExtendedVersion object was 2.3.5 but not 2.3.3 or 2.3.4. /// /// The following operations are allowed: /// "&lt;", "&lt;=", "=", "&gt;", "&gt;=" /// /// There may be any number of spaces between the op and the version. /// </summary> public bool Compare(string operation) { // Pull out the parts using substrings. string op; string ver; if (operation.StartsWith(">=")) { op = ">="; ver = operation.Substring(2).Trim(); } else if (operation.StartsWith("<=")) { op = "<="; ver = operation.Substring(2).Trim(); } else if (operation.StartsWith("<")) { op = "<"; ver = operation.Substring(1).Trim(); } else if (operation.StartsWith(">")) { op = ">"; ver = operation.Substring(1).Trim(); } else if (operation.StartsWith("=")) { op = "="; ver = operation.Substring(1).Trim(); } else { return false; } // Check the op var v = new ExtendedVersion(ver); switch (op) { case "<": return this < v; case "<=": return this <= v; case "=": return this == v; case ">": return this > v; case ">=": return this >= v; default: throw new Exception("Cannot identify operation: " + op); } } /// <summary> /// Determines if the object is equal to the current one. In cases /// where the object is not a ExtendedVersion class, it returns false. /// </summary> public override bool Equals(object obj) { try { var v = obj as ExtendedVersion; return this == v; } catch { return false; } } /// <summary> /// Overrides the hash code for the version, which is based on all /// the version parts. /// </summary> public override int GetHashCode() { return ToString().GetHashCode(); } /// <summary> /// Returns the text version of the string. /// </summary> public override string ToString() { return version; } #endregion #region Operators /// <summary> /// Determines if the two versions are syntactically equal. If all /// the version parts are identical, then so is the entire version. /// </summary> public static bool operator ==(ExtendedVersion v1, ExtendedVersion v2) { return v1.ToString() == v2.ToString(); } /// <summary> /// Determines if the first version is greater than the second /// version. See the &lt; operator for more conditions. /// </summary> public static bool operator >(ExtendedVersion v1, ExtendedVersion v2) { // Just do the reverse, its easier return v2 < v1; } /// <summary> /// Determines if the first version is greater than or equal to /// the second version. See the &lt; operator for more conditions. /// </summary> public static bool operator >=(ExtendedVersion v1, ExtendedVersion v2) { // Just do the reverse, its easier return v1 == v2 || v2 < v1; } /// <summary> /// Determines if the two versions are syntactically equal. If all /// the version parts are identical, then so is the entire version. /// </summary> public static bool operator !=(ExtendedVersion v1, ExtendedVersion v2) { return v1.ToString() != v2.ToString(); } /// <summary> /// Determines if the first is less than the second one. There are /// some conditions where a version is neither less than or greater /// than another version, specifcally with version parts that have /// text in it. /// </summary> public static bool operator <(ExtendedVersion v1, ExtendedVersion v2) { // Make sure v1 has the less parts, for simplicicity. bool swapped = false; if (v1.numerics.Length > v2.numerics.Length) { ExtendedVersion v3 = v2; v2 = v1; v1 = v3; swapped = true; } // Go through the various parts for (int i = 0; i < v1.numerics.Length; i++) { // Get the parts int num1 = v1.numerics[i]; string str1 = v1.strings[i]; int num2 = v2.numerics[i]; string str2 = v2.strings[i]; // Make sure strings match. If they do not, then the versions // will never match. if (str1 != str2) { return swapped; } // Compare the numbers. If num1 is less than num2, then the // rest of the version will be less. If it is the reverse, // return it. if (num1 < num2) { return !swapped; } if (num1 > num2) { return swapped; } } // We never got something that explicitly was less or invalid, // so assume false (equals). return swapped; } /// <summary> /// Determines if the first version is less than or equal to /// the second version. See the &lt; operator for more conditions. /// </summary> public static bool operator <=(ExtendedVersion v1, ExtendedVersion v2) { // Just do the reverse, its easier return v1 == v2 || v1 < v2; } #endregion #region Constructors /// <summary> /// Constructs an empty version with a version of zero ("0"). /// </summary> public ExtendedVersion() : this("0") { } /// <summary> /// Constructs a version using the given string as the /// version. This breaks up the version into version parts (broken /// down by periods (".") and slashes ("-"). A version part /// consists of a number, followed optionally by a string. If the /// version cannot be parsed, it throws an MfGamesException. /// </summary> public ExtendedVersion(string version) { // Check for null and blank if (version == null || version.Trim() == "") { throw new Exception("Cannot parse a null or blank version"); } // Save the string version and remove the spaces this.version = version = version.Trim(); // Check for spaces if (RegexSpace.IsMatch(version)) { throw new Exception("Versions cannot have whitespace"); } // Split the version into parts. We also allocate the space for // everything before parsing. string[] parts = version.Split('.', '-'); numerics = new int[parts.Length]; strings = new string[parts.Length]; for (int i = 0; i < parts.Length; i++) { // Check for match and sanity checking if (!RegexPart.IsMatch(parts[i])) { throw new Exception( "Cannot parse part '" + parts[i] + "' of '" + version + "'"); } // Pull out the parts Match match = RegexPart.Match(parts[i]); string strNumber = match.Groups[1].Value; strings[i] = match.Groups[2].Value; try { // Try to parse the integer numerics[i] = Int32.Parse(strNumber); } catch { throw new Exception("Cannot numerically parse '" + parts[i] + "'"); } } } #endregion #region Fields /// <summary> /// Contains the simple matcher for string (number, followed /// by... stuff) /// </summary> private static readonly Regex RegexPart = new Regex(@"(\d+)([\d\w]*)"); /// <summary> /// Contains the regex for whitespace matching. /// </summary> private static readonly Regex RegexSpace = new Regex(@"\s"); /// <summary> /// Contains the numeric parts of the version /// </summary> private readonly int[] numerics; /// <summary> /// Contains the string parts of the version. /// </summary> private readonly string[] strings; /// <summary> /// Contains the string version. /// </summary> private readonly string version; #endregion } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System; using System.Management.Automation.Host; using Dbg = System.Management.Automation.Diagnostics; namespace Microsoft.PowerShell { /// <summary> /// /// ProgressPane is a class that represents the "window" in which outstanding activities for which the host has received /// progress updates are shown. /// ///</summary> internal class ProgressPane { /// <summary> /// /// Constructs a new instance. /// /// </summary> /// <param name="ui"> /// /// An implementation of the PSHostRawUserInterface with which the pane will be shown and hidden. /// /// </param> internal ProgressPane(ConsoleHostUserInterface ui) { if (ui == null) throw new ArgumentNullException("ui"); _ui = ui; _rawui = ui.RawUI; } /// <summary> /// /// Indicates whether the pane is visible on the screen buffer or not. /// /// </summary> /// <value> /// /// true if the pane is visible, false if not. /// ///</value> internal bool IsShowing { get { return (_savedRegion != null); } } /// <summary> /// /// Shows the pane in the screen buffer. Saves off the content of the region of the buffer that will be overwritten so /// that it can be restored again. /// /// </summary> internal void Show() { if (!IsShowing) { // Get temporary reference to the progress region since it can be // changed at any time by a call to WriteProgress. BufferCell[,] tempProgressRegion = _progressRegion; if (tempProgressRegion == null) { return; } // The location where we show ourselves is always relative to the screen buffer's current window position. int rows = tempProgressRegion.GetLength(0); int cols = tempProgressRegion.GetLength(1); _location = _rawui.WindowPosition; // We have to show the progress pane in the first column, as the screen buffer at any point might contain // a CJK double-cell characters, which makes it impractical to try to find a position where the pane would // not slice a character. Column 0 is the only place where we know for sure we can place the pane. _location.X = 0; _location.Y = Math.Min(_location.Y + 2, _bufSize.Height); #if UNIX // replace the saved region in the screen buffer with our progress display _location = _rawui.CursorPosition; //set the cursor position back to the beginning of the region to overwrite write-progress //if the cursor is at the bottom, back it up to overwrite the previous write progress if (_location.Y >= _rawui.BufferSize.Height - rows) { Console.Out.Write('\n'); if (_location.Y >= rows) { _location.Y -= rows; } } _rawui.CursorPosition = _location; #else // Save off the current contents of the screen buffer in the region that we will occupy _savedRegion = _rawui.GetBufferContents( new Rectangle(_location.X, _location.Y, _location.X + cols - 1, _location.Y + rows - 1)); #endif // replace the saved region in the screen buffer with our progress display _rawui.SetBufferContents(_location, tempProgressRegion); } } /// <summary> /// /// Hides the pane by restoring the saved contents of the region of the buffer that the pane occupies. If the pane is /// not showing, then does nothing. /// /// </summary> internal void Hide() { if (IsShowing) { // It would be nice if we knew that the saved region could be kept for the next time Show is called, but alas, // we have no way of knowing if the screen buffer has changed since we were hidden. By "no good way" I mean that // detecting a change would be at least as expensive as chucking the savedRegion and rebuilding it. And it would // be very complicated. _rawui.SetBufferContents(_location, _savedRegion); _savedRegion = null; } } /// <summary> /// /// Updates the pane with the rendering of the supplied PendingProgress, and shows it. /// /// </summary> /// <param name="pendingProgress"> /// /// A PendingProgress instance that represents the outstanding activities that should be shown. /// /// </param> internal void Show(PendingProgress pendingProgress) { Dbg.Assert(pendingProgress != null, "pendingProgress may not be null"); _bufSize = _rawui.BufferSize; // In order to keep from slicing any CJK double-cell characters that might be present in the screen buffer, // we use the full width of the buffer. int maxWidth = _bufSize.Width; int maxHeight = Math.Max(5, _rawui.WindowSize.Height / 3); string[] contents = pendingProgress.Render(maxWidth, maxHeight, _rawui); if (contents == null) { // There's nothing to show. Hide(); _progressRegion = null; return; } // NTRAID#Windows OS Bugs-1061752-2004/12/15-sburns should read a skin setting here... BufferCell[,] newRegion = _rawui.NewBufferCellArray(contents, _ui.ProgressForegroundColor, _ui.ProgressBackgroundColor); Dbg.Assert(newRegion != null, "NewBufferCellArray has failed!"); if (_progressRegion == null) { // we've never shown this pane before. _progressRegion = newRegion; Show(); } else { // We have shown the pane before. We have to be smart about when we restore the saved region to minimize // flicker. We need to decide if the new contents will change the dimensions of the progress pane // currently being shown. If it will, then restore the saved region, and show the new one. Otherwise, // just blast the new one on top of the last one shown. // We're only checking size, not content, as we assume that the content will always change upon receipt // of a new ProgressRecord. That's not guaranteed, of course, but it's a good bet. So checking content // would usually result in detection of a change, so why bother? bool sizeChanged = (newRegion.GetLength(0) != _progressRegion.GetLength(0)) || (newRegion.GetLength(1) != _progressRegion.GetLength(1)) ? true : false; _progressRegion = newRegion; if (sizeChanged) { if (IsShowing) { Hide(); } Show(); } else { _rawui.SetBufferContents(_location, _progressRegion); } } } private Coordinates _location = new Coordinates(0, 0); private Size _bufSize; private BufferCell[,] _savedRegion; private BufferCell[,] _progressRegion; private PSHostRawUserInterface _rawui; private ConsoleHostUserInterface _ui; } } // namespace
/* ==================================================================== 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 NPOI.DDF { using System; using System.IO; using System.Text; using NPOI.Util; using ICSharpCode.SharpZipLib.Zip.Compression; using ICSharpCode.SharpZipLib.Zip.Compression.Streams; /// <summary> /// Used to dump the contents of escher records to a PrintStream. /// @author Glen Stampoultzis (glens at apache.org) /// </summary> public class EscherDump { public EscherDump() { } /// <summary> /// Decodes the escher stream from a byte array and dumps the results to /// a print stream. /// </summary> /// <param name="data">The data array containing the escher records.</param> /// <param name="offset">The starting offset within the data array.</param> /// <param name="size">The number of bytes to Read.</param> public void Dump(byte[] data, int offset, int size) { IEscherRecordFactory recordFactory = new DefaultEscherRecordFactory(); int pos = offset; while (pos < offset + size) { EscherRecord r = recordFactory.CreateRecord(data, pos); int bytesRead = r.FillFields(data, pos, recordFactory); Console.WriteLine(r.ToString()); pos += bytesRead; } } /// <summary> /// This version of dump is a translation from the open office escher dump routine. /// </summary> /// <param name="maxLength">The number of bytes to Read</param> /// <param name="in1">An input stream to Read from.</param> public void DumpOld(long maxLength, Stream in1) { long remainingBytes = maxLength; short options; // 4 bits for the version and 12 bits for the instance short recordId; int recordBytesRemaining; // including enclosing records StringBuilder stringBuf = new StringBuilder(); short nDumpSize; String recordName; bool atEOF = false; while (!atEOF && (remainingBytes > 0)) { stringBuf = new StringBuilder(); options = LittleEndian.ReadShort(in1); recordId = LittleEndian.ReadShort(in1); recordBytesRemaining = LittleEndian.ReadInt(in1); remainingBytes -= 2 + 2 + 4; switch (recordId) { case unchecked((short)0xF000): recordName = "MsofbtDggContainer"; break; case unchecked((short)0xF006): recordName = "MsofbtDgg"; break; case unchecked((short)0xF016): recordName = "MsofbtCLSID"; break; case unchecked((short)0xF00B): recordName = "MsofbtOPT"; break; case unchecked((short)0xF11A): recordName = "MsofbtColorMRU"; break; case unchecked((short)0xF11E): recordName = "MsofbtSplitMenuColors"; break; case unchecked((short)0xF001): recordName = "MsofbtBstoreContainer"; break; case unchecked((short)0xF007): recordName = "MsofbtBSE"; break; case unchecked((short)0xF002): recordName = "MsofbtDgContainer"; break; case unchecked((short)0xF008): recordName = "MsofbtDg"; break; case unchecked((short)0xF118): recordName = "MsofbtRegroupItem"; break; case unchecked((short)0xF120): recordName = "MsofbtColorScheme"; break; case unchecked((short)0xF003): recordName = "MsofbtSpgrContainer"; break; case unchecked((short)0xF004): recordName = "MsofbtSpContainer"; break; case unchecked((short)0xF009): recordName = "MsofbtSpgr"; break; case unchecked((short)0xF00A): recordName = "MsofbtSp"; break; case unchecked((short)0xF00C): recordName = "MsofbtTextbox"; break; case unchecked((short)0xF00D): recordName = "MsofbtClientTextbox"; break; case unchecked((short)0xF00E): recordName = "MsofbtAnchor"; break; case unchecked((short)0xF00F): recordName = "MsofbtChildAnchor"; break; case unchecked((short)0xF010): recordName = "MsofbtClientAnchor"; break; case unchecked((short)0xF011): recordName = "MsofbtClientData"; break; case unchecked((short)0xF11F): recordName = "MsofbtOleObject"; break; case unchecked((short)0xF11D): recordName = "MsofbtDeletedPspl"; break; case unchecked((short)0xF005): recordName = "MsofbtSolverContainer"; break; case unchecked((short)0xF012): recordName = "MsofbtConnectorRule"; break; case unchecked((short)0xF013): recordName = "MsofbtAlignRule"; break; case unchecked((short)0xF014): recordName = "MsofbtArcRule"; break; case unchecked((short)0xF015): recordName = "MsofbtClientRule"; break; case unchecked((short)0xF017): recordName = "MsofbtCalloutRule"; break; case unchecked((short)0xF119): recordName = "MsofbtSelection"; break; case unchecked((short)0xF122): recordName = "MsofbtUDefProp"; break; default: if (recordId >= unchecked((short)0xF018) && recordId <= unchecked((short)0xF117)) recordName = "MsofbtBLIP"; else if ((options & (short)0x000F) == (short)0x000F) recordName = "UNKNOWN container"; else recordName = "UNKNOWN ID"; break; } stringBuf.Append(" "); stringBuf.Append(HexDump.ToHex(recordId)); stringBuf.Append(" ").Append(recordName).Append(" ["); stringBuf.Append(HexDump.ToHex(options)); stringBuf.Append(','); stringBuf.Append(HexDump.ToHex(recordBytesRemaining)); stringBuf.Append("] instance: "); stringBuf.Append(HexDump.ToHex(((short)(options >> 4)))); Console.WriteLine(stringBuf.ToString()); if (recordId == (unchecked((short)0xF007)) && 36 <= remainingBytes && 36 <= recordBytesRemaining) { // BSE, FBSE // ULONG nP = pIn->GetRecPos(); byte n8; // short n16; // int n32; stringBuf = new StringBuilder(" btWin32: "); n8 = (byte)in1.ReadByte(); stringBuf.Append(HexDump.ToHex(n8)); stringBuf.Append(GetBlipType(n8)); stringBuf.Append(" btMacOS: "); n8 = (byte)in1.ReadByte(); stringBuf.Append(HexDump.ToHex(n8)); stringBuf.Append(GetBlipType(n8)); Console.WriteLine(stringBuf.ToString()); Console.WriteLine(" rgbUid:"); HexDump.Dump(in1, 0, 16); Console.Write(" tag: "); OutHex(2, in1); Console.WriteLine(); Console.Write(" size: "); OutHex(4, in1); Console.WriteLine(); Console.Write(" cRef: "); OutHex(4, in1); Console.WriteLine(); Console.Write(" offs: "); OutHex(4, in1); Console.WriteLine(); Console.Write(" usage: "); OutHex(4, in1); Console.WriteLine(); Console.Write(" cbName: "); OutHex(4, in1); Console.WriteLine(); Console.Write(" unused2: "); OutHex(4, in1); Console.WriteLine(); Console.Write(" unused3: "); OutHex(4, in1); Console.WriteLine(); // subtract the number of bytes we've Read remainingBytes -= 36; //n -= pIn->GetRecPos() - nP; recordBytesRemaining = 0; // loop to MsofbtBLIP } else if (recordId == unchecked((short)0xF010) && 0x12 <= remainingBytes && 0x12 <= recordBytesRemaining) { // ClientAnchor //ULONG nP = pIn->GetRecPos(); // short n16; Console.Write(" Flag: "); OutHex(2, in1); Console.WriteLine(); Console.Write(" Col1: "); OutHex(2, in1); Console.Write(" dX1: "); OutHex(2, in1); Console.Write(" Row1: "); OutHex(2, in1); Console.Write(" dY1: "); OutHex(2, in1); Console.WriteLine(); Console.Write(" Col2: "); OutHex(2, in1); Console.Write(" dX2: "); OutHex(2, in1); Console.Write(" Row2: "); OutHex(2, in1); Console.Write(" dY2: "); OutHex(2, in1); Console.WriteLine(); remainingBytes -= 18; recordBytesRemaining -= 18; } else if (recordId == unchecked((short)0xF00B) || recordId == unchecked((short)0xF122)) { // OPT int nComplex = 0; Console.WriteLine(" PROPID VALUE"); while (recordBytesRemaining >= 6 + nComplex && remainingBytes >= 6 + nComplex) { short n16; int n32; n16 = LittleEndian.ReadShort(in1); n32 = LittleEndian.ReadInt(in1); recordBytesRemaining -= 6; remainingBytes -= 6; Console.Write(" "); Console.Write(HexDump.ToHex(n16)); Console.Write(" ("); int propertyId = n16 & (short)0x3FFF; Console.Write(" " + propertyId); if ((n16 & unchecked((short)0x8000)) == 0) { if ((n16 & (short)0x4000) != 0) Console.Write(", fBlipID"); Console.Write(") "); Console.Write(HexDump.ToHex(n32)); if ((n16 & (short)0x4000) == 0) { Console.Write(" ("); Console.Write(Dec1616(n32)); Console.Write(')'); Console.Write(" {" + PropertyName((short)propertyId) + "}"); } Console.WriteLine(); } else { Console.Write(", fComplex) "); Console.Write(HexDump.ToHex(n32)); Console.Write(" - Complex prop len"); Console.WriteLine(" {" + PropertyName((short)propertyId) + "}"); nComplex += n32; } } // complex property data while ((nComplex & remainingBytes) > 0) { nDumpSize = (nComplex > (int)remainingBytes) ? (short)remainingBytes : (short)nComplex; HexDump.Dump(in1, 0, nDumpSize); nComplex -= nDumpSize; recordBytesRemaining -= nDumpSize; remainingBytes -= nDumpSize; } } else if (recordId == (unchecked((short)0xF012))) { Console.Write(" Connector rule: "); Console.Write(LittleEndian.ReadInt(in1)); Console.Write(" ShapeID A: "); Console.Write(LittleEndian.ReadInt(in1)); Console.Write(" ShapeID B: "); Console.Write(LittleEndian.ReadInt(in1)); Console.Write(" ShapeID connector: "); Console.Write(LittleEndian.ReadInt(in1)); Console.Write(" Connect pt A: "); Console.Write(LittleEndian.ReadInt(in1)); Console.Write(" Connect pt B: "); Console.WriteLine(LittleEndian.ReadInt(in1)); recordBytesRemaining -= 24; remainingBytes -= 24; } else if (recordId >= unchecked((short)0xF018) && recordId < unchecked((short)0xF117)) { Console.WriteLine(" Secondary UID: "); HexDump.Dump(in1, 0, 16); Console.WriteLine(" Cache of size: " + HexDump.ToHex(LittleEndian.ReadInt(in1))); Console.WriteLine(" Boundary top: " + HexDump.ToHex(LittleEndian.ReadInt(in1))); Console.WriteLine(" Boundary left: " + HexDump.ToHex(LittleEndian.ReadInt(in1))); Console.WriteLine(" Boundary width: " + HexDump.ToHex(LittleEndian.ReadInt(in1))); Console.WriteLine(" Boundary height: " + HexDump.ToHex(LittleEndian.ReadInt(in1))); Console.WriteLine(" X: " + HexDump.ToHex(LittleEndian.ReadInt(in1))); Console.WriteLine(" Y: " + HexDump.ToHex(LittleEndian.ReadInt(in1))); Console.WriteLine(" Cache of saved size: " + HexDump.ToHex(LittleEndian.ReadInt(in1))); Console.WriteLine(" Compression Flag: " + HexDump.ToHex((byte)in1.ReadByte())); Console.WriteLine(" Filter: " + HexDump.ToHex((byte)in1.ReadByte())); Console.WriteLine(" Data (after decompression): "); recordBytesRemaining -= 34 + 16; remainingBytes -= 34 + 16; nDumpSize = (recordBytesRemaining > (int)remainingBytes) ? (short)remainingBytes : (short)recordBytesRemaining; byte[] buf = new byte[nDumpSize]; int Read = in1.Read(buf,0,buf.Length); while (Read != -1 && Read < nDumpSize) Read += in1.Read(buf, Read, buf.Length); using (MemoryStream bin = new MemoryStream(buf)) { Inflater inflater = new Inflater(false); using (InflaterInputStream zIn = new InflaterInputStream(bin, inflater)) { int bytesToDump = -1; HexDump.Dump(zIn, 0, bytesToDump); recordBytesRemaining -= nDumpSize; remainingBytes -= nDumpSize; } } } bool isContainer = (options & (short)0x000F) == (short)0x000F; if (isContainer && remainingBytes >= 0) { // Container if (recordBytesRemaining <= (int)remainingBytes) Console.WriteLine(" completed within"); else Console.WriteLine(" continued elsewhere"); } else if (remainingBytes >= 0) // -> 0x0000 ... 0x0FFF { nDumpSize = (recordBytesRemaining > (int)remainingBytes) ? (short)remainingBytes : (short)recordBytesRemaining; if (nDumpSize != 0) { HexDump.Dump(in1, 0, nDumpSize); remainingBytes -= nDumpSize; } } else Console.WriteLine(" >> OVERRUN <<"); } } private class PropName { public PropName(int id, String name) { this.id = id; this.name = name; } public int id; public String name; } /// <summary> /// Returns a property name given a property id. This is used only by the /// old escher dump routine. /// </summary> /// <param name="propertyId">The property number for the name</param> /// <returns>A descriptive name.</returns> private String PropertyName(short propertyId) { PropName[] props = new PropName[] { new PropName(4, "transform.rotation"), new PropName(119, "protection.lockrotation"), new PropName(120, "protection.lockaspectratio"), new PropName(121, "protection.lockposition"), new PropName(122, "protection.lockagainstselect"), new PropName(123, "protection.lockcropping"), new PropName(124, "protection.lockvertices"), new PropName(125, "protection.locktext"), new PropName(126, "protection.lockadjusthandles"), new PropName(127, "protection.lockagainstgrouping"), new PropName(128, "text.textid"), new PropName(129, "text.textleft"), new PropName(130, "text.texttop"), new PropName(131, "text.textright"), new PropName(132, "text.textbottom"), new PropName(133, "text.wraptext"), new PropName(134, "text.scaletext"), new PropName(135, "text.anchortext"), new PropName(136, "text.textflow"), new PropName(137, "text.fontrotation"), new PropName(138, "text.idofnextshape"), new PropName(139, "text.bidir"), new PropName(187, "text.singleclickselects"), new PropName(188, "text.usehostmargins"), new PropName(189, "text.rotatetextwithshape"), new PropName(190, "text.sizeshapetofittext"), new PropName(191, "text.sizetexttofitshape"), new PropName(192, "geotext.unicode"), new PropName(193, "geotext.rtftext"), new PropName(194, "geotext.alignmentoncurve"), new PropName(195, "geotext.defaultpointsize"), new PropName(196, "geotext.textspacing"), new PropName(197, "geotext.fontfamilyname"), new PropName(240, "geotext.reverseroworder"), new PropName(241, "geotext.hastexteffect"), new PropName(242, "geotext.rotatecharacters"), new PropName(243, "geotext.kerncharacters"), new PropName(244, "geotext.tightortrack"), new PropName(245, "geotext.stretchtofitshape"), new PropName(246, "geotext.charboundingbox"), new PropName(247, "geotext.scaletextonpath"), new PropName(248, "geotext.stretchcharheight"), new PropName(249, "geotext.nomeasurealongpath"), new PropName(250, "geotext.boldfont"), new PropName(251, "geotext.italicfont"), new PropName(252, "geotext.underlinefont"), new PropName(253, "geotext.shadowfont"), new PropName(254, "geotext.smallcapsfont"), new PropName(255, "geotext.strikethroughfont"), new PropName(256, "blip.cropfromtop"), new PropName(257, "blip.cropfrombottom"), new PropName(258, "blip.cropfromleft"), new PropName(259, "blip.cropfromright"), new PropName(260, "blip.bliptodisplay"), new PropName(261, "blip.blipfilename"), new PropName(262, "blip.blipflags"), new PropName(263, "blip.transparentcolor"), new PropName(264, "blip.contrastSetting"), new PropName(265, "blip.brightnessSetting"), new PropName(266, "blip.gamma"), new PropName(267, "blip.pictureid"), new PropName(268, "blip.doublemod"), new PropName(269, "blip.picturefillmod"), new PropName(270, "blip.pictureline"), new PropName(271, "blip.printblip"), new PropName(272, "blip.printblipfilename"), new PropName(273, "blip.printflags"), new PropName(316, "blip.nohittestpicture"), new PropName(317, "blip.picturegray"), new PropName(318, "blip.picturebilevel"), new PropName(319, "blip.pictureactive"), new PropName(320, "geometry.left"), new PropName(321, "geometry.top"), new PropName(322, "geometry.right"), new PropName(323, "geometry.bottom"), new PropName(324, "geometry.shapepath"), new PropName(325, "geometry.vertices"), new PropName(326, "geometry.segmentinfo"), new PropName(327, "geometry.adjustvalue"), new PropName(328, "geometry.adjust2value"), new PropName(329, "geometry.adjust3value"), new PropName(330, "geometry.adjust4value"), new PropName(331, "geometry.adjust5value"), new PropName(332, "geometry.adjust6value"), new PropName(333, "geometry.adjust7value"), new PropName(334, "geometry.adjust8value"), new PropName(335, "geometry.adjust9value"), new PropName(336, "geometry.adjust10value"), new PropName(378, "geometry.shadowOK"), new PropName(379, "geometry.3dok"), new PropName(380, "geometry.lineok"), new PropName(381, "geometry.geotextok"), new PropName(382, "geometry.fillshadeshapeok"), new PropName(383, "geometry.fillok"), new PropName(384, "fill.filltype"), new PropName(385, "fill.fillcolor"), new PropName(386, "fill.fillopacity"), new PropName(387, "fill.fillbackcolor"), new PropName(388, "fill.backopacity"), new PropName(389, "fill.crmod"), new PropName(390, "fill.patterntexture"), new PropName(391, "fill.blipfilename"), new PropName(392, "fill.blipflags"), new PropName(393, "fill.width"), new PropName(394, "fill.height"), new PropName(395, "fill.angle"), new PropName(396, "fill.focus"), new PropName(397, "fill.toleft"), new PropName(398, "fill.totop"), new PropName(399, "fill.toright"), new PropName(400, "fill.tobottom"), new PropName(401, "fill.rectleft"), new PropName(402, "fill.recttop"), new PropName(403, "fill.rectright"), new PropName(404, "fill.rectbottom"), new PropName(405, "fill.dztype"), new PropName(406, "fill.shadepReset"), new PropName(407, "fill.shadecolors"), new PropName(408, "fill.originx"), new PropName(409, "fill.originy"), new PropName(410, "fill.shapeoriginx"), new PropName(411, "fill.shapeoriginy"), new PropName(412, "fill.shadetype"), new PropName(443, "fill.filled"), new PropName(444, "fill.hittestfill"), new PropName(445, "fill.shape"), new PropName(446, "fill.userect"), new PropName(447, "fill.nofillhittest"), new PropName(448, "linestyle.color"), new PropName(449, "linestyle.opacity"), new PropName(450, "linestyle.backcolor"), new PropName(451, "linestyle.crmod"), new PropName(452, "linestyle.linetype"), new PropName(453, "linestyle.fillblip"), new PropName(454, "linestyle.fillblipname"), new PropName(455, "linestyle.fillblipflags"), new PropName(456, "linestyle.fillwidth"), new PropName(457, "linestyle.fillheight"), new PropName(458, "linestyle.filldztype"), new PropName(459, "linestyle.linewidth"), new PropName(460, "linestyle.linemiterlimit"), new PropName(461, "linestyle.linestyle"), new PropName(462, "linestyle.linedashing"), new PropName(463, "linestyle.linedashstyle"), new PropName(464, "linestyle.linestartarrowhead"), new PropName(465, "linestyle.lineendarrowhead"), new PropName(466, "linestyle.linestartarrowwidth"), new PropName(467, "linestyle.lineestartarrowLength"), new PropName(468, "linestyle.lineendarrowwidth"), new PropName(469, "linestyle.lineendarrowLength"), new PropName(470, "linestyle.linejoinstyle"), new PropName(471, "linestyle.lineendcapstyle"), new PropName(507, "linestyle.arrowheadsok"), new PropName(508, "linestyle.anyline"), new PropName(509, "linestyle.hitlinetest"), new PropName(510, "linestyle.linefillshape"), new PropName(511, "linestyle.nolinedrawdash"), new PropName(512, "shadowstyle.type"), new PropName(513, "shadowstyle.color"), new PropName(514, "shadowstyle.highlight"), new PropName(515, "shadowstyle.crmod"), new PropName(516, "shadowstyle.opacity"), new PropName(517, "shadowstyle.offsetx"), new PropName(518, "shadowstyle.offsety"), new PropName(519, "shadowstyle.secondoffsetx"), new PropName(520, "shadowstyle.secondoffsety"), new PropName(521, "shadowstyle.scalextox"), new PropName(522, "shadowstyle.scaleytox"), new PropName(523, "shadowstyle.scalextoy"), new PropName(524, "shadowstyle.scaleytoy"), new PropName(525, "shadowstyle.perspectivex"), new PropName(526, "shadowstyle.perspectivey"), new PropName(527, "shadowstyle.weight"), new PropName(528, "shadowstyle.originx"), new PropName(529, "shadowstyle.originy"), new PropName(574, "shadowstyle.shadow"), new PropName(575, "shadowstyle.shadowobsured"), new PropName(576, "perspective.type"), new PropName(577, "perspective.offsetx"), new PropName(578, "perspective.offsety"), new PropName(579, "perspective.scalextox"), new PropName(580, "perspective.scaleytox"), new PropName(581, "perspective.scalextoy"), new PropName(582, "perspective.scaleytox"), new PropName(583, "perspective.perspectivex"), new PropName(584, "perspective.perspectivey"), new PropName(585, "perspective.weight"), new PropName(586, "perspective.originx"), new PropName(587, "perspective.originy"), new PropName(639, "perspective.perspectiveon"), new PropName(640, "3d.specularamount"), new PropName(661, "3d.diffuseamount"), new PropName(662, "3d.shininess"), new PropName(663, "3d.edGethickness"), new PropName(664, "3d.extrudeforward"), new PropName(665, "3d.extrudebackward"), new PropName(666, "3d.extrudeplane"), new PropName(667, "3d.extrusioncolor"), new PropName(648, "3d.crmod"), new PropName(700, "3d.3deffect"), new PropName(701, "3d.metallic"), new PropName(702, "3d.useextrusioncolor"), new PropName(703, "3d.lightface"), new PropName(704, "3dstyle.yrotationangle"), new PropName(705, "3dstyle.xrotationangle"), new PropName(706, "3dstyle.rotationaxisx"), new PropName(707, "3dstyle.rotationaxisy"), new PropName(708, "3dstyle.rotationaxisz"), new PropName(709, "3dstyle.rotationangle"), new PropName(710, "3dstyle.rotationcenterx"), new PropName(711, "3dstyle.rotationcentery"), new PropName(712, "3dstyle.rotationcenterz"), new PropName(713, "3dstyle.rendermode"), new PropName(714, "3dstyle.tolerance"), new PropName(715, "3dstyle.xviewpoint"), new PropName(716, "3dstyle.yviewpoint"), new PropName(717, "3dstyle.zviewpoint"), new PropName(718, "3dstyle.originx"), new PropName(719, "3dstyle.originy"), new PropName(720, "3dstyle.skewangle"), new PropName(721, "3dstyle.skewamount"), new PropName(722, "3dstyle.ambientintensity"), new PropName(723, "3dstyle.keyx"), new PropName(724, "3dstyle.keyy"), new PropName(725, "3dstyle.keyz"), new PropName(726, "3dstyle.keyintensity"), new PropName(727, "3dstyle.fillx"), new PropName(728, "3dstyle.filly"), new PropName(729, "3dstyle.fillz"), new PropName(730, "3dstyle.fillintensity"), new PropName(763, "3dstyle.constrainrotation"), new PropName(764, "3dstyle.rotationcenterauto"), new PropName(765, "3dstyle.parallel"), new PropName(766, "3dstyle.keyharsh"), new PropName(767, "3dstyle.fillharsh"), new PropName(769, "shape.master"), new PropName(771, "shape.connectorstyle"), new PropName(772, "shape.blackandwhiteSettings"), new PropName(773, "shape.wmodepurebw"), new PropName(774, "shape.wmodebw"), new PropName(826, "shape.oleicon"), new PropName(827, "shape.preferrelativeresize"), new PropName(828, "shape.lockshapetype"), new PropName(830, "shape.deleteattachedobject"), new PropName(831, "shape.backgroundshape"), new PropName(832, "callout.callouttype"), new PropName(833, "callout.xycalloutgap"), new PropName(834, "callout.calloutangle"), new PropName(835, "callout.calloutdroptype"), new PropName(836, "callout.calloutdropspecified"), new PropName(837, "callout.calloutLengthspecified"), new PropName(889, "callout.iscallout"), new PropName(890, "callout.calloutaccentbar"), new PropName(891, "callout.callouttextborder"), new PropName(892, "callout.calloutminusx"), new PropName(893, "callout.calloutminusy"), new PropName(894, "callout.dropauto"), new PropName(895, "callout.Lengthspecified"), new PropName(896, "groupshape.shapename"), new PropName(897, "groupshape.description"), new PropName(898, "groupshape.hyperlink"), new PropName(899, "groupshape.wrappolygonvertices"), new PropName(900, "groupshape.wrapdistleft"), new PropName(901, "groupshape.wrapdisttop"), new PropName(902, "groupshape.wrapdistright"), new PropName(903, "groupshape.wrapdistbottom"), new PropName(904, "groupshape.regroupid"), new PropName(953, "groupshape.editedwrap"), new PropName(954, "groupshape.behinddocument"), new PropName(955, "groupshape.ondblclicknotify"), new PropName(956, "groupshape.isbutton"), new PropName(957, "groupshape.1dadjustment"), new PropName(958, "groupshape.hidden"), new PropName(959, "groupshape.print"), }; for (int i = 0; i < props.Length; i++) { if (props[i].id == propertyId) { return props[i].name; } } return "unknown property"; } /// <summary> /// Returns the blip description given a blip id. /// </summary> /// <param name="b">blip id</param> /// <returns> A description.</returns> private String GetBlipType(byte b) { switch (b) { case 0: return " ERROR"; case 1: return " UNKNOWN"; case 2: return " EMF"; case 3: return " WMF"; case 4: return " PICT"; case 5: return " JPEG"; case 6: return " PNG"; case 7: return " DIB"; default: if (b < 32) return " NotKnown"; else return " Client"; } } /// <summary> /// Straight conversion from OO. Converts a type of float. /// </summary> /// <param name="n32">The N32.</param> /// <returns></returns> private String Dec1616(int n32) { String result = ""; result += (short)(n32 >> 16); result += '.'; result += (short)(n32 & 0xFFFF); return result; } /// <summary> /// Dumps out a hex value by Reading from a input stream. /// </summary> /// <param name="bytes">How many bytes this hex value consists of.</param> /// <param name="in1">The stream to Read the hex value from.</param> private void OutHex(int bytes, Stream in1) { switch (bytes) { case 1: Console.Write(HexDump.ToHex((byte)in1.ReadByte())); break; case 2: Console.Write(HexDump.ToHex(LittleEndian.ReadShort(in1))); break; case 4: Console.Write(HexDump.ToHex(LittleEndian.ReadInt(in1))); break; default: throw new IOException("Unable to output variable of that width"); } } /// <summary> /// Dumps the specified record size. /// </summary> /// <param name="recordSize">Size of the record.</param> /// <param name="data">The data.</param> public void Dump(int recordSize, byte[] data) { // ByteArrayInputStream is = new ByteArrayInputStream( data ); // dump( recordSize, is, out ); Dump(data, 0, recordSize); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/bigtable/admin/v2/bigtable_instance_admin.proto // Original file comments: // Copyright 2016 Google 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. // #region Designer generated code using System; using System.Threading; using System.Threading.Tasks; using Grpc.Core; namespace Google.Bigtable.Admin.V2 { /// <summary> /// Service for creating, configuring, and deleting Cloud Bigtable Instances and /// Clusters. Provides access to the Instance and Cluster schemas only, not the /// tables metadata or data stored in those tables. /// </summary> public static class BigtableInstanceAdmin { static readonly string __ServiceName = "google.bigtable.admin.v2.BigtableInstanceAdmin"; static readonly Marshaller<global::Google.Bigtable.Admin.V2.CreateInstanceRequest> __Marshaller_CreateInstanceRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Bigtable.Admin.V2.CreateInstanceRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.LongRunning.Operation> __Marshaller_Operation = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.LongRunning.Operation.Parser.ParseFrom); static readonly Marshaller<global::Google.Bigtable.Admin.V2.GetInstanceRequest> __Marshaller_GetInstanceRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Bigtable.Admin.V2.GetInstanceRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Bigtable.Admin.V2.Instance> __Marshaller_Instance = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Bigtable.Admin.V2.Instance.Parser.ParseFrom); static readonly Marshaller<global::Google.Bigtable.Admin.V2.ListInstancesRequest> __Marshaller_ListInstancesRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Bigtable.Admin.V2.ListInstancesRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Bigtable.Admin.V2.ListInstancesResponse> __Marshaller_ListInstancesResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Bigtable.Admin.V2.ListInstancesResponse.Parser.ParseFrom); static readonly Marshaller<global::Google.Bigtable.Admin.V2.DeleteInstanceRequest> __Marshaller_DeleteInstanceRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Bigtable.Admin.V2.DeleteInstanceRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Protobuf.WellKnownTypes.Empty> __Marshaller_Empty = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Protobuf.WellKnownTypes.Empty.Parser.ParseFrom); static readonly Marshaller<global::Google.Bigtable.Admin.V2.CreateClusterRequest> __Marshaller_CreateClusterRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Bigtable.Admin.V2.CreateClusterRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Bigtable.Admin.V2.GetClusterRequest> __Marshaller_GetClusterRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Bigtable.Admin.V2.GetClusterRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Bigtable.Admin.V2.Cluster> __Marshaller_Cluster = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Bigtable.Admin.V2.Cluster.Parser.ParseFrom); static readonly Marshaller<global::Google.Bigtable.Admin.V2.ListClustersRequest> __Marshaller_ListClustersRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Bigtable.Admin.V2.ListClustersRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Bigtable.Admin.V2.ListClustersResponse> __Marshaller_ListClustersResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Bigtable.Admin.V2.ListClustersResponse.Parser.ParseFrom); static readonly Marshaller<global::Google.Bigtable.Admin.V2.DeleteClusterRequest> __Marshaller_DeleteClusterRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Bigtable.Admin.V2.DeleteClusterRequest.Parser.ParseFrom); static readonly Method<global::Google.Bigtable.Admin.V2.CreateInstanceRequest, global::Google.LongRunning.Operation> __Method_CreateInstance = new Method<global::Google.Bigtable.Admin.V2.CreateInstanceRequest, global::Google.LongRunning.Operation>( MethodType.Unary, __ServiceName, "CreateInstance", __Marshaller_CreateInstanceRequest, __Marshaller_Operation); static readonly Method<global::Google.Bigtable.Admin.V2.GetInstanceRequest, global::Google.Bigtable.Admin.V2.Instance> __Method_GetInstance = new Method<global::Google.Bigtable.Admin.V2.GetInstanceRequest, global::Google.Bigtable.Admin.V2.Instance>( MethodType.Unary, __ServiceName, "GetInstance", __Marshaller_GetInstanceRequest, __Marshaller_Instance); static readonly Method<global::Google.Bigtable.Admin.V2.ListInstancesRequest, global::Google.Bigtable.Admin.V2.ListInstancesResponse> __Method_ListInstances = new Method<global::Google.Bigtable.Admin.V2.ListInstancesRequest, global::Google.Bigtable.Admin.V2.ListInstancesResponse>( MethodType.Unary, __ServiceName, "ListInstances", __Marshaller_ListInstancesRequest, __Marshaller_ListInstancesResponse); static readonly Method<global::Google.Bigtable.Admin.V2.Instance, global::Google.Bigtable.Admin.V2.Instance> __Method_UpdateInstance = new Method<global::Google.Bigtable.Admin.V2.Instance, global::Google.Bigtable.Admin.V2.Instance>( MethodType.Unary, __ServiceName, "UpdateInstance", __Marshaller_Instance, __Marshaller_Instance); static readonly Method<global::Google.Bigtable.Admin.V2.DeleteInstanceRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_DeleteInstance = new Method<global::Google.Bigtable.Admin.V2.DeleteInstanceRequest, global::Google.Protobuf.WellKnownTypes.Empty>( MethodType.Unary, __ServiceName, "DeleteInstance", __Marshaller_DeleteInstanceRequest, __Marshaller_Empty); static readonly Method<global::Google.Bigtable.Admin.V2.CreateClusterRequest, global::Google.LongRunning.Operation> __Method_CreateCluster = new Method<global::Google.Bigtable.Admin.V2.CreateClusterRequest, global::Google.LongRunning.Operation>( MethodType.Unary, __ServiceName, "CreateCluster", __Marshaller_CreateClusterRequest, __Marshaller_Operation); static readonly Method<global::Google.Bigtable.Admin.V2.GetClusterRequest, global::Google.Bigtable.Admin.V2.Cluster> __Method_GetCluster = new Method<global::Google.Bigtable.Admin.V2.GetClusterRequest, global::Google.Bigtable.Admin.V2.Cluster>( MethodType.Unary, __ServiceName, "GetCluster", __Marshaller_GetClusterRequest, __Marshaller_Cluster); static readonly Method<global::Google.Bigtable.Admin.V2.ListClustersRequest, global::Google.Bigtable.Admin.V2.ListClustersResponse> __Method_ListClusters = new Method<global::Google.Bigtable.Admin.V2.ListClustersRequest, global::Google.Bigtable.Admin.V2.ListClustersResponse>( MethodType.Unary, __ServiceName, "ListClusters", __Marshaller_ListClustersRequest, __Marshaller_ListClustersResponse); static readonly Method<global::Google.Bigtable.Admin.V2.Cluster, global::Google.LongRunning.Operation> __Method_UpdateCluster = new Method<global::Google.Bigtable.Admin.V2.Cluster, global::Google.LongRunning.Operation>( MethodType.Unary, __ServiceName, "UpdateCluster", __Marshaller_Cluster, __Marshaller_Operation); static readonly Method<global::Google.Bigtable.Admin.V2.DeleteClusterRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_DeleteCluster = new Method<global::Google.Bigtable.Admin.V2.DeleteClusterRequest, global::Google.Protobuf.WellKnownTypes.Empty>( MethodType.Unary, __ServiceName, "DeleteCluster", __Marshaller_DeleteClusterRequest, __Marshaller_Empty); /// <summary>Service descriptor</summary> public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::Google.Bigtable.Admin.V2.BigtableInstanceAdminReflection.Descriptor.Services[0]; } } /// <summary>Base class for server-side implementations of BigtableInstanceAdmin</summary> public abstract class BigtableInstanceAdminBase { /// <summary> /// Create an instance within a project. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.LongRunning.Operation> CreateInstance(global::Google.Bigtable.Admin.V2.CreateInstanceRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Gets information about an instance. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Bigtable.Admin.V2.Instance> GetInstance(global::Google.Bigtable.Admin.V2.GetInstanceRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Lists information about instances in a project. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Bigtable.Admin.V2.ListInstancesResponse> ListInstances(global::Google.Bigtable.Admin.V2.ListInstancesRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Updates an instance within a project. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Bigtable.Admin.V2.Instance> UpdateInstance(global::Google.Bigtable.Admin.V2.Instance request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Delete an instance from a project. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> DeleteInstance(global::Google.Bigtable.Admin.V2.DeleteInstanceRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Creates a cluster within an instance. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.LongRunning.Operation> CreateCluster(global::Google.Bigtable.Admin.V2.CreateClusterRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Gets information about a cluster. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Bigtable.Admin.V2.Cluster> GetCluster(global::Google.Bigtable.Admin.V2.GetClusterRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Lists information about clusters in an instance. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Bigtable.Admin.V2.ListClustersResponse> ListClusters(global::Google.Bigtable.Admin.V2.ListClustersRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Updates a cluster within an instance. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.LongRunning.Operation> UpdateCluster(global::Google.Bigtable.Admin.V2.Cluster request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Deletes a cluster from an instance. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> DeleteCluster(global::Google.Bigtable.Admin.V2.DeleteClusterRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } } /// <summary>Client for BigtableInstanceAdmin</summary> public class BigtableInstanceAdminClient : ClientBase<BigtableInstanceAdminClient> { /// <summary>Creates a new client for BigtableInstanceAdmin</summary> /// <param name="channel">The channel to use to make remote calls.</param> public BigtableInstanceAdminClient(Channel channel) : base(channel) { } /// <summary>Creates a new client for BigtableInstanceAdmin that uses a custom <c>CallInvoker</c>.</summary> /// <param name="callInvoker">The callInvoker to use to make remote calls.</param> public BigtableInstanceAdminClient(CallInvoker callInvoker) : base(callInvoker) { } /// <summary>Protected parameterless constructor to allow creation of test doubles.</summary> protected BigtableInstanceAdminClient() : base() { } /// <summary>Protected constructor to allow creation of configured clients.</summary> /// <param name="configuration">The client configuration.</param> protected BigtableInstanceAdminClient(ClientBaseConfiguration configuration) : base(configuration) { } /// <summary> /// Create an instance within a project. /// </summary> public virtual global::Google.LongRunning.Operation CreateInstance(global::Google.Bigtable.Admin.V2.CreateInstanceRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CreateInstance(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Create an instance within a project. /// </summary> public virtual global::Google.LongRunning.Operation CreateInstance(global::Google.Bigtable.Admin.V2.CreateInstanceRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_CreateInstance, null, options, request); } /// <summary> /// Create an instance within a project. /// </summary> public virtual AsyncUnaryCall<global::Google.LongRunning.Operation> CreateInstanceAsync(global::Google.Bigtable.Admin.V2.CreateInstanceRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CreateInstanceAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Create an instance within a project. /// </summary> public virtual AsyncUnaryCall<global::Google.LongRunning.Operation> CreateInstanceAsync(global::Google.Bigtable.Admin.V2.CreateInstanceRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_CreateInstance, null, options, request); } /// <summary> /// Gets information about an instance. /// </summary> public virtual global::Google.Bigtable.Admin.V2.Instance GetInstance(global::Google.Bigtable.Admin.V2.GetInstanceRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetInstance(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets information about an instance. /// </summary> public virtual global::Google.Bigtable.Admin.V2.Instance GetInstance(global::Google.Bigtable.Admin.V2.GetInstanceRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetInstance, null, options, request); } /// <summary> /// Gets information about an instance. /// </summary> public virtual AsyncUnaryCall<global::Google.Bigtable.Admin.V2.Instance> GetInstanceAsync(global::Google.Bigtable.Admin.V2.GetInstanceRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetInstanceAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets information about an instance. /// </summary> public virtual AsyncUnaryCall<global::Google.Bigtable.Admin.V2.Instance> GetInstanceAsync(global::Google.Bigtable.Admin.V2.GetInstanceRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetInstance, null, options, request); } /// <summary> /// Lists information about instances in a project. /// </summary> public virtual global::Google.Bigtable.Admin.V2.ListInstancesResponse ListInstances(global::Google.Bigtable.Admin.V2.ListInstancesRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListInstances(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists information about instances in a project. /// </summary> public virtual global::Google.Bigtable.Admin.V2.ListInstancesResponse ListInstances(global::Google.Bigtable.Admin.V2.ListInstancesRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ListInstances, null, options, request); } /// <summary> /// Lists information about instances in a project. /// </summary> public virtual AsyncUnaryCall<global::Google.Bigtable.Admin.V2.ListInstancesResponse> ListInstancesAsync(global::Google.Bigtable.Admin.V2.ListInstancesRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListInstancesAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists information about instances in a project. /// </summary> public virtual AsyncUnaryCall<global::Google.Bigtable.Admin.V2.ListInstancesResponse> ListInstancesAsync(global::Google.Bigtable.Admin.V2.ListInstancesRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ListInstances, null, options, request); } /// <summary> /// Updates an instance within a project. /// </summary> public virtual global::Google.Bigtable.Admin.V2.Instance UpdateInstance(global::Google.Bigtable.Admin.V2.Instance request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return UpdateInstance(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Updates an instance within a project. /// </summary> public virtual global::Google.Bigtable.Admin.V2.Instance UpdateInstance(global::Google.Bigtable.Admin.V2.Instance request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_UpdateInstance, null, options, request); } /// <summary> /// Updates an instance within a project. /// </summary> public virtual AsyncUnaryCall<global::Google.Bigtable.Admin.V2.Instance> UpdateInstanceAsync(global::Google.Bigtable.Admin.V2.Instance request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return UpdateInstanceAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Updates an instance within a project. /// </summary> public virtual AsyncUnaryCall<global::Google.Bigtable.Admin.V2.Instance> UpdateInstanceAsync(global::Google.Bigtable.Admin.V2.Instance request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_UpdateInstance, null, options, request); } /// <summary> /// Delete an instance from a project. /// </summary> public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteInstance(global::Google.Bigtable.Admin.V2.DeleteInstanceRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return DeleteInstance(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Delete an instance from a project. /// </summary> public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteInstance(global::Google.Bigtable.Admin.V2.DeleteInstanceRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_DeleteInstance, null, options, request); } /// <summary> /// Delete an instance from a project. /// </summary> public virtual AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteInstanceAsync(global::Google.Bigtable.Admin.V2.DeleteInstanceRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return DeleteInstanceAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Delete an instance from a project. /// </summary> public virtual AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteInstanceAsync(global::Google.Bigtable.Admin.V2.DeleteInstanceRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_DeleteInstance, null, options, request); } /// <summary> /// Creates a cluster within an instance. /// </summary> public virtual global::Google.LongRunning.Operation CreateCluster(global::Google.Bigtable.Admin.V2.CreateClusterRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CreateCluster(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates a cluster within an instance. /// </summary> public virtual global::Google.LongRunning.Operation CreateCluster(global::Google.Bigtable.Admin.V2.CreateClusterRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_CreateCluster, null, options, request); } /// <summary> /// Creates a cluster within an instance. /// </summary> public virtual AsyncUnaryCall<global::Google.LongRunning.Operation> CreateClusterAsync(global::Google.Bigtable.Admin.V2.CreateClusterRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CreateClusterAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates a cluster within an instance. /// </summary> public virtual AsyncUnaryCall<global::Google.LongRunning.Operation> CreateClusterAsync(global::Google.Bigtable.Admin.V2.CreateClusterRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_CreateCluster, null, options, request); } /// <summary> /// Gets information about a cluster. /// </summary> public virtual global::Google.Bigtable.Admin.V2.Cluster GetCluster(global::Google.Bigtable.Admin.V2.GetClusterRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetCluster(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets information about a cluster. /// </summary> public virtual global::Google.Bigtable.Admin.V2.Cluster GetCluster(global::Google.Bigtable.Admin.V2.GetClusterRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetCluster, null, options, request); } /// <summary> /// Gets information about a cluster. /// </summary> public virtual AsyncUnaryCall<global::Google.Bigtable.Admin.V2.Cluster> GetClusterAsync(global::Google.Bigtable.Admin.V2.GetClusterRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetClusterAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets information about a cluster. /// </summary> public virtual AsyncUnaryCall<global::Google.Bigtable.Admin.V2.Cluster> GetClusterAsync(global::Google.Bigtable.Admin.V2.GetClusterRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetCluster, null, options, request); } /// <summary> /// Lists information about clusters in an instance. /// </summary> public virtual global::Google.Bigtable.Admin.V2.ListClustersResponse ListClusters(global::Google.Bigtable.Admin.V2.ListClustersRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListClusters(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists information about clusters in an instance. /// </summary> public virtual global::Google.Bigtable.Admin.V2.ListClustersResponse ListClusters(global::Google.Bigtable.Admin.V2.ListClustersRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ListClusters, null, options, request); } /// <summary> /// Lists information about clusters in an instance. /// </summary> public virtual AsyncUnaryCall<global::Google.Bigtable.Admin.V2.ListClustersResponse> ListClustersAsync(global::Google.Bigtable.Admin.V2.ListClustersRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListClustersAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists information about clusters in an instance. /// </summary> public virtual AsyncUnaryCall<global::Google.Bigtable.Admin.V2.ListClustersResponse> ListClustersAsync(global::Google.Bigtable.Admin.V2.ListClustersRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ListClusters, null, options, request); } /// <summary> /// Updates a cluster within an instance. /// </summary> public virtual global::Google.LongRunning.Operation UpdateCluster(global::Google.Bigtable.Admin.V2.Cluster request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return UpdateCluster(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Updates a cluster within an instance. /// </summary> public virtual global::Google.LongRunning.Operation UpdateCluster(global::Google.Bigtable.Admin.V2.Cluster request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_UpdateCluster, null, options, request); } /// <summary> /// Updates a cluster within an instance. /// </summary> public virtual AsyncUnaryCall<global::Google.LongRunning.Operation> UpdateClusterAsync(global::Google.Bigtable.Admin.V2.Cluster request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return UpdateClusterAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Updates a cluster within an instance. /// </summary> public virtual AsyncUnaryCall<global::Google.LongRunning.Operation> UpdateClusterAsync(global::Google.Bigtable.Admin.V2.Cluster request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_UpdateCluster, null, options, request); } /// <summary> /// Deletes a cluster from an instance. /// </summary> public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteCluster(global::Google.Bigtable.Admin.V2.DeleteClusterRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return DeleteCluster(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Deletes a cluster from an instance. /// </summary> public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteCluster(global::Google.Bigtable.Admin.V2.DeleteClusterRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_DeleteCluster, null, options, request); } /// <summary> /// Deletes a cluster from an instance. /// </summary> public virtual AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteClusterAsync(global::Google.Bigtable.Admin.V2.DeleteClusterRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return DeleteClusterAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Deletes a cluster from an instance. /// </summary> public virtual AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteClusterAsync(global::Google.Bigtable.Admin.V2.DeleteClusterRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_DeleteCluster, null, options, request); } protected override BigtableInstanceAdminClient NewInstance(ClientBaseConfiguration configuration) { return new BigtableInstanceAdminClient(configuration); } } /// <summary>Creates service definition that can be registered with a server</summary> public static ServerServiceDefinition BindService(BigtableInstanceAdminBase serviceImpl) { return ServerServiceDefinition.CreateBuilder() .AddMethod(__Method_CreateInstance, serviceImpl.CreateInstance) .AddMethod(__Method_GetInstance, serviceImpl.GetInstance) .AddMethod(__Method_ListInstances, serviceImpl.ListInstances) .AddMethod(__Method_UpdateInstance, serviceImpl.UpdateInstance) .AddMethod(__Method_DeleteInstance, serviceImpl.DeleteInstance) .AddMethod(__Method_CreateCluster, serviceImpl.CreateCluster) .AddMethod(__Method_GetCluster, serviceImpl.GetCluster) .AddMethod(__Method_ListClusters, serviceImpl.ListClusters) .AddMethod(__Method_UpdateCluster, serviceImpl.UpdateCluster) .AddMethod(__Method_DeleteCluster, serviceImpl.DeleteCluster).Build(); } } } #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; using System.Collections.Generic; #if !ES_BUILD_AGAINST_DOTNET_V35 using Contract = System.Diagnostics.Contracts.Contract; #else using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract; #endif #if ES_BUILD_STANDALONE namespace Microsoft.Diagnostics.Tracing #else namespace System.Diagnostics.Tracing #endif { /// <summary> /// TraceLogging: used when implementing a custom TraceLoggingTypeInfo. /// Non-generic base class for TraceLoggingTypeInfo&lt;DataType>. Do not derive /// from this class. Instead, derive from TraceLoggingTypeInfo&lt;DataType>. /// </summary> internal abstract class TraceLoggingTypeInfo { private readonly string name; private readonly EventKeywords keywords; private readonly EventLevel level = (EventLevel)(-1); private readonly EventOpcode opcode = (EventOpcode)(-1); private readonly EventTags tags; private readonly Type dataType; private readonly Func<object, PropertyValue> propertyValueFactory; internal TraceLoggingTypeInfo(Type dataType) { if (dataType == null) { throw new ArgumentNullException("dataType"); } Contract.EndContractBlock(); this.name = dataType.Name; this.dataType = dataType; this.propertyValueFactory = PropertyValue.GetFactory(dataType); } internal TraceLoggingTypeInfo( Type dataType, string name, EventLevel level, EventOpcode opcode, EventKeywords keywords, EventTags tags) { if (dataType == null) { throw new ArgumentNullException("dataType"); } if (name == null) { throw new ArgumentNullException("eventName"); } Contract.EndContractBlock(); Statics.CheckName(name); this.name = name; this.keywords = keywords; this.level = level; this.opcode = opcode; this.tags = tags; this.dataType = dataType; this.propertyValueFactory = PropertyValue.GetFactory(dataType); } /// <summary> /// Gets the name to use for the event if this type is the top-level type, /// or the name to use for an implicitly-named field. /// Never null. /// </summary> public string Name { get { return this.name; } } /// <summary> /// Gets the event level associated with this type. Any value in the range 0..255 /// is an associated event level. Any value outside the range 0..255 is invalid and /// indicates that this type has no associated event level. /// </summary> public EventLevel Level { get { return this.level; } } /// <summary> /// Gets the event opcode associated with this type. Any value in the range 0..255 /// is an associated event opcode. Any value outside the range 0..255 is invalid and /// indicates that this type has no associated event opcode. /// </summary> public EventOpcode Opcode { get { return this.opcode; } } /// <summary> /// Gets the keyword(s) associated with this type. /// </summary> public EventKeywords Keywords { get { return this.keywords; } } /// <summary> /// Gets the event tags associated with this type. /// </summary> public EventTags Tags { get { return this.tags; } } internal Type DataType { get { return this.dataType; } } internal Func<object, PropertyValue> PropertyValueFactory { get { return this.propertyValueFactory; } } /// <summary> /// When overridden by a derived class, writes the metadata (schema) for /// this type. Note that the sequence of operations in WriteMetadata should be /// essentially identical to the sequence of operations in /// WriteData/WriteObjectData. Otherwise, the metadata and data will not match, /// which may cause trouble when decoding the event. /// </summary> /// <param name="collector"> /// The object that collects metadata for this object's type. Metadata is written /// by calling methods on the collector object. Note that if the type contains /// sub-objects, the implementation of this method may need to call the /// WriteMetadata method for the type of the sub-object, e.g. by calling /// TraceLoggingTypeInfo&lt;SubType&gt;.Instance.WriteMetadata(...). /// </param> /// <param name="name"> /// The name of the property that contains an object of this type, or null if this /// object is being written as a top-level object of an event. Typical usage /// is to pass this value to collector.AddGroup. /// </param> /// <param name="format"> /// The format attribute for the field that contains an object of this type. /// </param> public abstract void WriteMetadata( TraceLoggingMetadataCollector collector, string name, EventFieldFormat format); /// <summary> /// Refer to TraceLoggingTypeInfo.WriteObjectData for information about this /// method. /// </summary> /// <param name="collector"> /// Refer to TraceLoggingTypeInfo.WriteObjectData for information about this /// method. /// </param> /// <param name="value"> /// Refer to TraceLoggingTypeInfo.WriteObjectData for information about this /// method. /// </param> public abstract void WriteData( TraceLoggingDataCollector collector, PropertyValue value); /// <summary> /// Fetches the event parameter data for internal serialization. /// </summary> /// <param name="value"></param> /// <returns></returns> public virtual object GetData(object value) { return value; } [ThreadStatic] // per-thread cache to avoid synchronization private static Dictionary<Type, TraceLoggingTypeInfo> threadCache; public static TraceLoggingTypeInfo GetInstance(Type type, List<Type> recursionCheck) { var cache = threadCache ?? (threadCache = new Dictionary<Type, TraceLoggingTypeInfo>()); TraceLoggingTypeInfo instance; if (!cache.TryGetValue(type, out instance)) { if (recursionCheck == null) recursionCheck = new List<Type>(); var recursionCheckCount = recursionCheck.Count; instance = Statics.CreateDefaultTypeInfo(type, recursionCheck); cache[type] = instance; recursionCheck.RemoveRange(recursionCheckCount, recursionCheck.Count - recursionCheckCount); } return instance; } } }
using System; using System.Diagnostics; using System.IO; using System.Numerics; using System.Reflection; using System.Windows; using System.Windows.Input; using SharpDX.D3DCompiler; using SharpDX.Direct3D; using SharpDX.Direct3D11; using SharpDX.DXGI; namespace PhysX.Samples.Engine { public delegate void UpdateEventHandler(TimeSpan elapsed); public class Engine { public event UpdateEventHandler OnUpdate; public event EventHandler OnDraw; private Action<SceneDesc> _sceneDescCallback; private Keyboard _keyboard; private VisualizationEffect _visualizationEffect; private RenderTargetView _backBuffer; private DepthStencilView _depthBuffer; private SwapChain _swapChain; private SharpDX.Direct3D11.Buffer _userPrimitivesBuffer; private InputLayout _inputLayout; // TODO: Clean up this class public Engine(Action<SceneDesc> sceneDescCallback = null) { _sceneDescCallback = sceneDescCallback; Window = new SampleWindow(); Window.Show(); _keyboard = new Keyboard(this); _keyboard.OnKeyDown += _keyboard_OnKeyDown; InitalizeGraphics(); InitalizePhysics(); Mouse.SetCursor(Cursors.None); } private void _keyboard_OnKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Space) { ShootSphere(); } } private void ShootSphere() { const float force = 5000; var cameraPos = Camera.Position.AsPhysX(); var cameraDir = Camera.Direction.AsPhysX(); var material = this.Scene.Physics.CreateMaterial(0.1f, 0.5f, 0.5f); var rigidActor = this.Scene.Physics.CreateRigidDynamic(); var sphereGeom = new SphereGeometry(2); var boxShape = RigidActorExt.CreateExclusiveShape(rigidActor, sphereGeom, material, null); rigidActor.GlobalPose = Matrix4x4.CreateTranslation(cameraPos); rigidActor.SetMassAndUpdateInertia(100); this.Scene.AddActor(rigidActor); rigidActor.AddForceAtLocalPosition(cameraDir * force, new System.Numerics.Vector3(0, 0, 0), ForceMode.Impulse, true); } private void InitalizeGraphics() { if (Window.RenderCanvasHandle == IntPtr.Zero) throw new InvalidOperationException(); var swapChainDesc = new SwapChainDescription() { BufferCount = 1, IsWindowed = true, OutputHandle = Window.RenderCanvasHandle, SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput, ModeDescription = new ModeDescription() { Format = Format.R8G8B8A8_UNorm, Width = (int)Window.RenderCanvasSize.Width, Height = (int)Window.RenderCanvasSize.Height, RefreshRate = new Rational(60, 1) }, SampleDescription = new SampleDescription(1, 0) }; SharpDX.Direct3D11.Device device; try { SharpDX.Direct3D11.Device.CreateWithSwapChain(DriverType.Warp, DeviceCreationFlags.None, swapChainDesc, out device, out _swapChain); GraphicsDevice = device; } catch { throw new Exception("Failed to create graphics device. Do you have DirectX 11?"); } // Create a view of our render target, which is the 'back buffer' of the swap chain we just created { using (var resource = SharpDX.Direct3D11.Resource.FromSwapChain<Texture2D>(_swapChain, 0)) { _backBuffer = new RenderTargetView(device, resource); } // Use it device.ImmediateContext.OutputMerger.SetTargets(_backBuffer); } CreateDepthStencil(); LoadVisualizationEffect(); // Allocate a large buffer to write the PhysX visualization vertices into // There's more optimized ways of doing this, but for this sample a large buffer will do _userPrimitivesBuffer = new SharpDX.Direct3D11.Buffer(GraphicsDevice, VertexPositionColor.SizeInBytes * 50000, ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, VertexPositionColor.SizeInBytes); } private void CreateDepthStencil() { var stencilDesc = new Texture2DDescription() { Width = (int)Window.RenderCanvasSize.Width, Height = (int)Window.RenderCanvasSize.Height, MipLevels = 1, ArraySize = 1, Format = Format.D32_Float, SampleDescription = new SampleDescription() { Count = 1, Quality = 0 }, Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }; var depthBufferTexture = new Texture2D(GraphicsDevice, stencilDesc); _depthBuffer = new DepthStencilView(this.GraphicsDevice, depthBufferTexture); } private void LoadVisualizationEffect() { string engineDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string visEffectFile = Path.Combine(engineDir, @"Shaders\VisualizationEffect.fx"); var shaderByteCode = ShaderBytecode.CompileFromFile(visEffectFile, "fx_5_0", ShaderFlags.Debug); var effect = new Effect(this.GraphicsDevice, shaderByteCode); _visualizationEffect = new VisualizationEffect() { Effect = effect, World = effect.GetVariableByName("World").AsMatrix(), View = effect.GetVariableByName("View").AsMatrix(), Projection = effect.GetVariableByName("Projection").AsMatrix(), RenderScenePass0 = effect.GetTechniqueByName("RenderScene").GetPassByIndex(0) }; // Vertex structure the shader is expecting - very basic sample, just Position and Color. var elements = new[] { new InputElement("Position", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("Color", 0, Format.R32G32B32A32_Float, 16, 0) }; _inputLayout = new InputLayout(this.GraphicsDevice, _visualizationEffect.RenderScenePass0.Description.Signature, elements); } public void InitalizePhysics() { // Construct engine objects this.Camera = new Camera(this); // Construct physics objects ErrorOutput errorOutput = new ErrorOutput(); Foundation foundation = new Foundation(errorOutput); var pvd = new VisualDebugger.Pvd(foundation); this.Physics = new Physics(foundation, true, pvd); this.Scene = this.Physics.CreateScene(CreateSceneDesc(foundation)); this.Scene.SetVisualizationParameter(VisualizationParameter.Scale, 2.0f); this.Scene.SetVisualizationParameter(VisualizationParameter.CollisionShapes, true); this.Scene.SetVisualizationParameter(VisualizationParameter.JointLocalFrames, true); this.Scene.SetVisualizationParameter(VisualizationParameter.JointLimits, true); this.Scene.SetVisualizationParameter(VisualizationParameter.ActorAxes, true); // Connect to the PhysX Visual Debugger (if the PVD application is running) this.Physics.Pvd.Connect("localhost"); CreateGroundPlane(); } protected virtual SceneDesc CreateSceneDesc(Foundation foundation) { #if GPU var cudaContext = new CudaContextManager(foundation); #endif var sceneDesc = new SceneDesc { Gravity = new Vector3(0, -9.81f, 0), #if GPU GpuDispatcher = cudaContext.GpuDispatcher, #endif FilterShader = new SampleFilterShader() }; #if GPU sceneDesc.Flags |= SceneFlag.EnableGpuDynamics; sceneDesc.BroadPhaseType |= BroadPhaseType.Gpu; #endif _sceneDescCallback?.Invoke(sceneDesc); return sceneDesc; } private void CreateGroundPlane() { var groundPlaneMaterial = this.Scene.Physics.CreateMaterial(0.1f, 0.1f, 0.1f); var groundPlane = this.Scene.Physics.CreateRigidStatic(); groundPlane.Name = "Ground Plane"; groundPlane.GlobalPose = Matrix4x4.CreateFromAxisAngle(new System.Numerics.Vector3(0, 0, 1), (float)System.Math.PI / 2); var planeGeom = new PlaneGeometry(); RigidActorExt.CreateExclusiveShape(groundPlane, planeGeom, groundPlaneMaterial, null); this.Scene.AddActor(groundPlane); } public void Run() { Window.Show(); Window.Focus(); var frameTimer = Stopwatch.StartNew(); // Not an ideal render loop, but it will do for this sample while (true) { if (!Window.IsActive) { System.Windows.Forms.Application.DoEvents(); System.Threading.Thread.Sleep(50); continue; } Draw(); // 60fps = 1/60 = 16.67 ms/frame if (frameTimer.Elapsed >= TimeSpan.FromMilliseconds(16.67)) { Update(frameTimer.Elapsed); frameTimer.Restart(); System.Windows.Forms.Application.DoEvents(); } } } private void Update(TimeSpan elapsed) { this.FrameTime = elapsed; // Update Physics this.Scene.Simulate((float)elapsed.TotalSeconds); this.Scene.FetchResults(block: true); this.Camera.Update(elapsed); if (OnUpdate != null) OnUpdate(elapsed); } private void Draw() { this.GraphicsDevice.ImmediateContext.OutputMerger.SetTargets(_depthBuffer, _backBuffer); // Clear to a nice blue colour :) this.GraphicsDevice.ImmediateContext.ClearRenderTargetView(_backBuffer, new SharpDX.Color4(0.27f, 0.51f, 0.71f, 1)); this.GraphicsDevice.ImmediateContext.ClearDepthStencilView(_depthBuffer, DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil, 1, 0); this.GraphicsDevice.ImmediateContext.Rasterizer.SetViewports(new[] { (SharpDX.Mathematics.Interop.RawViewportF)this.Camera.Viewport }, 1); DrawDebug(this.Scene.GetRenderBuffer()); if (OnDraw != null) OnDraw(this, null); _swapChain.Present(0, PresentFlags.None); } private void DrawDebug(RenderBuffer data) { var pass = _visualizationEffect.RenderScenePass0; _visualizationEffect.World.SetMatrix(SharpDX.Matrix.Identity); _visualizationEffect.View.SetMatrix(this.Camera.View); _visualizationEffect.Projection.SetMatrix(this.Camera.Projection); this.GraphicsDevice.ImmediateContext.InputAssembler.InputLayout = _inputLayout; pass.Apply(this.GraphicsDevice.ImmediateContext); if (data.NumberOfPoints > 0) { var vertices = new VertexPositionColor[data.Points.Length]; for (int i = 0; i < data.Points.Length; i++) { var point = data.Points[i]; vertices[i * 2 + 0] = new VertexPositionColor(point.Point.As<SharpDX.Vector3>(), Color.FromArgb(point.Color)); } DrawVertices(vertices, PrimitiveTopology.PointList); } if (data.NumberOfLines > 0) { var vertices = new VertexPositionColor[data.Lines.Length * 2]; for (int x = 0; x < data.Lines.Length; x++) { DebugLine line = data.Lines[x]; vertices[x * 2 + 0] = new VertexPositionColor(line.Point0.As<SharpDX.Vector3>(), Color.FromArgb(line.Color0)); vertices[x * 2 + 1] = new VertexPositionColor(line.Point1.As<SharpDX.Vector3>(), Color.FromArgb(line.Color1)); } DrawVertices(vertices, PrimitiveTopology.LineList); } if (data.NumberOfTriangles > 0) { var vertices = new VertexPositionColor[data.Triangles.Length * 3]; for (int x = 0; x < data.Triangles.Length; x++) { DebugTriangle triangle = data.Triangles[x]; vertices[x * 3 + 0] = new VertexPositionColor(triangle.Point0.As<SharpDX.Vector3>(), Color.FromArgb(triangle.Color0)); vertices[x * 3 + 1] = new VertexPositionColor(triangle.Point1.As<SharpDX.Vector3>(), Color.FromArgb(triangle.Color1)); vertices[x * 3 + 2] = new VertexPositionColor(triangle.Point2.As<SharpDX.Vector3>(), Color.FromArgb(triangle.Color2)); } DrawVertices(vertices, PrimitiveTopology.TriangleList); } } private void PopulatePrimitivesBuffer(VertexPositionColor[] vertices) { var dataBox = this.GraphicsDevice.ImmediateContext.MapSubresource(_userPrimitivesBuffer, 0, MapMode.WriteDiscard, SharpDX.Direct3D11.MapFlags.None); SharpDX.Utilities.Write(IntPtr.Add(dataBox.DataPointer, 0), vertices, 0, vertices.Length); this.GraphicsDevice.ImmediateContext.UnmapSubresource(_userPrimitivesBuffer, 0); } private void DrawVertices(VertexPositionColor[] vertices, PrimitiveTopology top) { PopulatePrimitivesBuffer(vertices); this.GraphicsDevice.ImmediateContext.InputAssembler.PrimitiveTopology = top; this.GraphicsDevice.ImmediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(_userPrimitivesBuffer, VertexPositionColor.SizeInBytes, 0)); this.GraphicsDevice.ImmediateContext.Draw(vertices.Length, 0); } public void DrawSimple(SharpDX.Direct3D11.Buffer vertexBuffer, SharpDX.Direct3D11.Buffer indexBuffer, int indexCount) { this.GraphicsDevice.ImmediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, 0, 0)); this.GraphicsDevice.ImmediateContext.InputAssembler.SetIndexBuffer(indexBuffer, Format.R32_UInt, 0); this.GraphicsDevice.ImmediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.LineList; this.GraphicsDevice.ImmediateContext.DrawIndexed(indexCount, 0, 0); } // public Camera Camera { get; private set; } public Physics Physics { get; private set; } public Scene Scene { get; private set; } public SharpDX.Direct3D11.Device GraphicsDevice { get; private set; } public SampleWindow Window { get; private set; } public Keyboard Keyboard => _keyboard; public TimeSpan FrameTime { get; private set; } } }
// 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.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; using size_t = System.IntPtr; using libcurl = Interop.libcurl; using PollFlags = Interop.libc.PollFlags; internal static partial class Interop { internal static partial class libcurl { internal sealed class SafeCurlMultiHandle : SafeHandle { private bool _pollCancelled = true; private readonly int[] _specialFds = new int[2]; private readonly HashSet<int> _fdSet = new HashSet<int>(); private int _requestCount = 0; private Timer _timer; internal bool PollCancelled { get { return _pollCancelled; } set { _pollCancelled = value; } } internal int RequestCount { get { return _requestCount; } set { _requestCount = value; } } internal Timer Timer { get { return _timer; } set { _timer = value; } } public SafeCurlMultiHandle() : base(IntPtr.Zero, true) { unsafe { fixed(int* fds = _specialFds) { while (Interop.CheckIo(Interop.Sys.Pipe(fds))); } } } public override bool IsInvalid { get { return this.handle == IntPtr.Zero; } } public static void DisposeAndClearHandle(ref SafeCurlMultiHandle curlHandle) { if (curlHandle != null) { curlHandle.Dispose(); curlHandle = null; } } internal void PollFds(List<libc.pollfd> readyFds) { int count; libc.pollfd[] pollFds; readyFds.Clear(); lock (this) { // TODO: Avoid the allocation when count is in 100s count = _fdSet.Count + 1; pollFds = new libc.pollfd[count]; // Always include special fd in the poll set. This is used to // return from the poll in case any fds have been added or // removed to the set of fds being polled. This prevents starvation // in case current set of fds have no activity but the new fd // is ready for a read/write. The special fd is the read end of a pipe // Whenever an fd is added/removed in _fdSet, a write happens to the // write end of the pipe thus causing the poll to return. pollFds[0].fd = _specialFds[Interop.Sys.ReadEndOfPipe]; pollFds[0].events = PollFlags.POLLIN; int i = 1; foreach (int fd in _fdSet) { pollFds[i].fd = fd; pollFds[i].events = PollFlags.POLLIN | PollFlags.POLLOUT; i++; } } unsafe { fixed (libc.pollfd* fds = pollFds) { int numFds = libc.poll(fds, (uint)count, -1); if (numFds <= 0) { Debug.Assert(numFds != 0); // Since timeout is infinite // TODO: How to handle errors? throw new InvalidOperationException("Poll failure: " + Marshal.GetLastWin32Error()); } lock (this) { if (0 == _requestCount) { return; } } // Check for any fdset changes if (fds[0].revents != 0) { if (ReadSpecialFd(fds[0].revents) < 0) { // TODO: How to handle errors? throw new InvalidOperationException("Cannot read data: " + Marshal.GetLastWin32Error()); } numFds--; } // Now check for events on the remaining fds for (int i = 1; i < count && numFds > 0; i++) { if (fds[i].revents == 0) { continue; } readyFds.Add(fds[i]); numFds--; } } } } internal void SignalFdSetChange(int fd, bool isRemove) { Debug.Assert(Monitor.IsEntered(this)); // If there is no valid fd, the poll still needs to be unblocked if (-1 != fd) { bool changed = isRemove ? _fdSet.Remove(fd) : _fdSet.Add(fd); if (!changed) { return; } } unsafe { // Write to special fd byte* dummyBytes = stackalloc byte[1]; if ((int)libc.write(_specialFds[Interop.Sys.WriteEndOfPipe], dummyBytes, (size_t)1) <= 0) { // TODO: How to handle errors? throw new InvalidOperationException("Cannot write data: " + Marshal.GetLastWin32Error()); } } } protected override void Dispose(bool disposing) { if (disposing) { if (null != _timer) { _timer.Dispose(); } } base.Dispose(disposing); } protected override bool ReleaseHandle() { Debug.Assert(0 == _fdSet.Count); Debug.Assert(0 == _requestCount); Debug.Assert(_pollCancelled); Interop.Sys.Close(_specialFds[Interop.Sys.ReadEndOfPipe]); Interop.Sys.Close(_specialFds[Interop.Sys.WriteEndOfPipe]); libcurl.curl_multi_cleanup(this.handle); return true; } private int ReadSpecialFd(PollFlags revents) { PollFlags badEvents = PollFlags.POLLERR | PollFlags.POLLHUP | PollFlags.POLLNVAL; if ((revents & badEvents) != 0) { return -1; } Debug.Assert((revents & PollFlags.POLLIN) != 0); int pipeReadFd = _specialFds[Interop.Sys.ReadEndOfPipe]; int bytesRead = 0; unsafe { do { // Read available data from the pipe int bufferLength = 1024; byte* dummyBytes = stackalloc byte[bufferLength]; int numBytes = (int)libc.read(pipeReadFd, dummyBytes, (size_t)bufferLength); if (numBytes <= 0) { return -1; } bytesRead += numBytes; // Check if more data is available PollFlags outFlags; int retVal = libc.poll(pipeReadFd, PollFlags.POLLIN, 0, out outFlags); if (retVal < 0) { return -1; } else if (0 == retVal) { break; } } while (true); } return bytesRead; } } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // // RuntimeHelpers // This class defines a set of static methods that provide support for compilers. // // Date: April 2000 // namespace System.Runtime.CompilerServices { using System; using System.Security; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.ConstrainedExecution; using System.Security.Permissions; using System.Threading; using System.Runtime.Versioning; using System.Diagnostics.Contracts; public static class RuntimeHelpers { [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void InitializeArray(Array array,RuntimeFieldHandle fldHandle); // GetObjectValue is intended to allow value classes to be manipulated as 'Object' // but have aliasing behavior of a value class. The intent is that you would use // this function just before an assignment to a variable of type 'Object'. If the // value being assigned is a mutable value class, then a shallow copy is returned // (because value classes have copy semantics), but otherwise the object itself // is returned. // // Note: VB calls this method when they're about to assign to an Object // or pass it as a parameter. The goal is to make sure that boxed // value types work identical to unboxed value types - ie, they get // cloned when you pass them around, and are always passed by value. // Of course, reference types are not cloned. // [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern Object GetObjectValue(Object obj); // RunClassConstructor causes the class constructor for the given type to be triggered // in the current domain. After this call returns, the class constructor is guaranteed to // have at least been started by some thread. In the absence of class constructor // deadlock conditions, the call is further guaranteed to have completed. // // This call will generate an exception if the specified class constructor threw an // exception when it ran. [System.Security.SecuritySafeCritical] [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _RunClassConstructor(RuntimeType type); public static void RunClassConstructor(RuntimeTypeHandle type) { _RunClassConstructor(type.GetRuntimeType()); } // RunModuleConstructor causes the module constructor for the given type to be triggered // in the current domain. After this call returns, the module constructor is guaranteed to // have at least been started by some thread. In the absence of module constructor // deadlock conditions, the call is further guaranteed to have completed. // // This call will generate an exception if the specified module constructor threw an // exception when it ran. [System.Security.SecuritySafeCritical] [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _RunModuleConstructor(System.Reflection.RuntimeModule module); public static void RunModuleConstructor(ModuleHandle module) { _RunModuleConstructor(module.GetRuntimeModule()); } [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static unsafe extern void _PrepareMethod(IRuntimeMethodInfo method, IntPtr* pInstantiation, int cInstantiation); [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] internal static extern void _CompileMethod(IRuntimeMethodInfo method); // Simple (instantiation not required) method. [System.Security.SecurityCritical] // auto-generated_required public static void PrepareMethod(RuntimeMethodHandle method) { unsafe { _PrepareMethod(method.GetMethodInfo(), null, 0); } } // Generic method or method with generic class with specific instantiation. [System.Security.SecurityCritical] // auto-generated_required public static void PrepareMethod(RuntimeMethodHandle method, RuntimeTypeHandle[] instantiation) { unsafe { int length; IntPtr[] instantiationHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(instantiation, out length); fixed (IntPtr* pInstantiation = instantiationHandles) { _PrepareMethod(method.GetMethodInfo(), pInstantiation, length); GC.KeepAlive(instantiation); } } } // This method triggers a given delegate to be prepared. This involves preparing the // delegate's Invoke method and preparing the target of that Invoke. In the case of // a multi-cast delegate, we rely on the fact that each individual component was prepared // prior to the Combine. In other words, this service does not navigate through the // entire multicasting list. // If our own reliable event sinks perform the Combine (for example AppDomain.DomainUnload), // then the result is fully prepared. But if a client calls Combine himself and then // then adds that combination to e.g. AppDomain.DomainUnload, then the client is responsible // for his own preparation. [System.Security.SecurityCritical] // auto-generated_required [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void PrepareDelegate(Delegate d); // See comment above for PrepareDelegate // // PrepareContractedDelegate weakens this a bit by only assuring that we prepare // delegates which also have a ReliabilityContract. This is useful for services that // want to provide opt-in reliability, generally some random event sink providing // always reliable semantics to random event handlers that are likely to have not // been written with relability in mind is a lost cause anyway. // // NOTE: that for the NGen case you can sidestep the required ReliabilityContract // by using the [PrePrepareMethod] attribute. [System.Security.SecurityCritical] // auto-generated_required [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void PrepareContractedDelegate(Delegate d); [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern int GetHashCode(Object o); [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] public new static extern bool Equals(Object o1, Object o2); public static int OffsetToStringData { // This offset is baked in by string indexer intrinsic, so there is no harm // in getting it baked in here as well. [System.Runtime.Versioning.NonVersionable] get { // Number of bytes from the address pointed to by a reference to // a String to the first 16-bit character in the String. Skip // over the MethodTable pointer, & String // length. Of course, the String reference points to the memory // after the [....] block, so don't count that. // This property allows C#'s fixed statement to work on Strings. // On 64 bit platforms, this should be 12 (8+4) and on 32 bit 8 (4+4). #if WIN32 return 8; #else return 12; #endif // WIN32 } } // This method ensures that there is sufficient stack to execute the average Framework function. // If there is not enough stack, then it throws System.InsufficientExecutionStackException. // Note: this method is not part of the CER support, and is not to be confused with ProbeForSufficientStack // below. [System.Security.SecuritySafeCritical] [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static extern void EnsureSufficientExecutionStack(); [System.Security.SecurityCritical] // auto-generated_required [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public static extern void ProbeForSufficientStack(); // This method is a marker placed immediately before a try clause to mark the corresponding catch and finally blocks as // constrained. There's no code here other than the probe because most of the work is done at JIT time when we spot a call to this routine. [System.Security.SecurityCritical] // auto-generated_required [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public static void PrepareConstrainedRegions() { ProbeForSufficientStack(); } // When we detect a CER with no calls, we can point the JIT to this non-probing version instead // as we don't need to probe. [System.Security.SecurityCritical] // auto-generated_required [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public static void PrepareConstrainedRegionsNoOP() { } #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif public delegate void TryCode(Object userData); #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif public delegate void CleanupCode(Object userData, bool exceptionThrown); [System.Security.SecurityCritical] // auto-generated_required [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData); #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif [PrePrepareMethod] internal static void ExecuteBackoutCodeHelper(Object backoutCode, Object userData, bool exceptionThrown) { ((CleanupCode)backoutCode)(userData, exceptionThrown); } } }
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace Contoso.Core.JavaScriptCustomization.AppWeb { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted app. /// </summary> /// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns> public string GetDatabaseConnectionString() { string dbConnectionString = null; using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost()) { if (clientContext != null) { var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext); clientContext.ExecuteQuery(); dbConnectionString = result.Value; } } if (dbConnectionString == null) { const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging"; var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey]; dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null; } return dbConnectionString; } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey])) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.Scripting.Metadata { internal enum PEMagic : ushort { PEMagic32 = 0x010B, PEMagic64 = 0x020B, } internal enum MetadataStreamKind { Illegal, Compressed, UnCompressed, } internal enum MetadataTokenType { Module = 0x00000000, TypeRef = 0x01000000, TypeDef = 0x02000000, FieldDef = 0x04000000, MethodDef = 0x06000000, ParamDef = 0x08000000, InterfaceImpl = 0x09000000, MemberRef = 0x0a000000, CustomAttribute = 0x0c000000, Permission = 0x0e000000, Signature = 0x11000000, Event = 0x14000000, Property = 0x17000000, ModuleRef = 0x1a000000, TypeSpec = 0x1b000000, Assembly = 0x20000000, AssemblyRef = 0x23000000, File = 0x26000000, ExportedType = 0x27000000, ManifestResource = 0x28000000, NestedClass = 0x29000000, GenericPar = 0x2a000000, MethodSpec = 0x2b000000, GenericParamConstraint = 0x2c000000, String = 0x70000000, Name = 0x71000000, BaseType = 0x72000000, Invalid = 0x7FFFFFFF, } internal enum TableMask : ulong { Module = 0x0000000000000001UL << 0x00, TypeRef = 0x0000000000000001UL << 0x01, TypeDef = 0x0000000000000001UL << 0x02, FieldPtr = 0x0000000000000001UL << 0x03, Field = 0x0000000000000001UL << 0x04, MethodPtr = 0x0000000000000001UL << 0x05, Method = 0x0000000000000001UL << 0x06, ParamPtr = 0x0000000000000001UL << 0x07, Param = 0x0000000000000001UL << 0x08, InterfaceImpl = 0x0000000000000001UL << 0x09, MemberRef = 0x0000000000000001UL << 0x0A, Constant = 0x0000000000000001UL << 0x0B, CustomAttribute = 0x0000000000000001UL << 0x0C, FieldMarshal = 0x0000000000000001UL << 0x0D, DeclSecurity = 0x0000000000000001UL << 0x0E, ClassLayout = 0x0000000000000001UL << 0x0F, FieldLayout = 0x0000000000000001UL << 0x10, StandAloneSig = 0x0000000000000001UL << 0x11, EventMap = 0x0000000000000001UL << 0x12, EventPtr = 0x0000000000000001UL << 0x13, Event = 0x0000000000000001UL << 0x14, PropertyMap = 0x0000000000000001UL << 0x15, PropertyPtr = 0x0000000000000001UL << 0x16, Property = 0x0000000000000001UL << 0x17, MethodSemantics = 0x0000000000000001UL << 0x18, MethodImpl = 0x0000000000000001UL << 0x19, ModuleRef = 0x0000000000000001UL << 0x1A, TypeSpec = 0x0000000000000001UL << 0x1B, ImplMap = 0x0000000000000001UL << 0x1C, FieldRva = 0x0000000000000001UL << 0x1D, EnCLog = 0x0000000000000001UL << 0x1E, EnCMap = 0x0000000000000001UL << 0x1F, Assembly = 0x0000000000000001UL << 0x20, AssemblyProcessor = 0x0000000000000001UL << 0x21, AssemblyOS = 0x0000000000000001UL << 0x22, AssemblyRef = 0x0000000000000001UL << 0x23, AssemblyRefProcessor = 0x0000000000000001UL << 0x24, AssemblyRefOS = 0x0000000000000001UL << 0x25, File = 0x0000000000000001UL << 0x26, ExportedType = 0x0000000000000001UL << 0x27, ManifestResource = 0x0000000000000001UL << 0x28, NestedClass = 0x0000000000000001UL << 0x29, GenericParam = 0x0000000000000001UL << 0x2A, MethodSpec = 0x0000000000000001UL << 0x2B, GenericParamConstraint = 0x0000000000000001UL << 0x2C, SortedTablesMask = TableMask.ClassLayout | TableMask.Constant | TableMask.CustomAttribute | TableMask.DeclSecurity | TableMask.FieldLayout | TableMask.FieldMarshal | TableMask.FieldRva | TableMask.GenericParam | TableMask.GenericParamConstraint | TableMask.ImplMap | TableMask.InterfaceImpl | TableMask.MethodImpl | TableMask.MethodSemantics | TableMask.NestedClass, CompressedStreamNotAllowedMask = TableMask.FieldPtr | TableMask.MethodPtr | TableMask.ParamPtr | TableMask.EventPtr | TableMask.PropertyPtr | TableMask.EnCLog | TableMask.EnCMap, V1_0_TablesMask = TableMask.Module | TableMask.TypeRef | TableMask.TypeDef | TableMask.FieldPtr | TableMask.Field | TableMask.MethodPtr | TableMask.Method | TableMask.ParamPtr | TableMask.Param | TableMask.InterfaceImpl | TableMask.MemberRef | TableMask.Constant | TableMask.CustomAttribute | TableMask.FieldMarshal | TableMask.DeclSecurity | TableMask.ClassLayout | TableMask.FieldLayout | TableMask.StandAloneSig | TableMask.EventMap | TableMask.EventPtr | TableMask.Event | TableMask.PropertyMap | TableMask.PropertyPtr | TableMask.Property | TableMask.MethodSemantics | TableMask.MethodImpl | TableMask.ModuleRef | TableMask.TypeSpec | TableMask.ImplMap | TableMask.FieldRva | TableMask.EnCLog | TableMask.EnCMap | TableMask.Assembly | TableMask.AssemblyRef | TableMask.File | TableMask.ExportedType | TableMask.ManifestResource | TableMask.NestedClass, V1_1_TablesMask = TableMask.Module | TableMask.TypeRef | TableMask.TypeDef | TableMask.FieldPtr | TableMask.Field | TableMask.MethodPtr | TableMask.Method | TableMask.ParamPtr | TableMask.Param | TableMask.InterfaceImpl | TableMask.MemberRef | TableMask.Constant | TableMask.CustomAttribute | TableMask.FieldMarshal | TableMask.DeclSecurity | TableMask.ClassLayout | TableMask.FieldLayout | TableMask.StandAloneSig | TableMask.EventMap | TableMask.EventPtr | TableMask.Event | TableMask.PropertyMap | TableMask.PropertyPtr | TableMask.Property | TableMask.MethodSemantics | TableMask.MethodImpl | TableMask.ModuleRef | TableMask.TypeSpec | TableMask.ImplMap | TableMask.FieldRva | TableMask.EnCLog | TableMask.EnCMap | TableMask.Assembly | TableMask.AssemblyRef | TableMask.File | TableMask.ExportedType | TableMask.ManifestResource | TableMask.NestedClass, V2_0_TablesMask = TableMask.Module | TableMask.TypeRef | TableMask.TypeDef | TableMask.FieldPtr | TableMask.Field | TableMask.MethodPtr | TableMask.Method | TableMask.ParamPtr | TableMask.Param | TableMask.InterfaceImpl | TableMask.MemberRef | TableMask.Constant | TableMask.CustomAttribute | TableMask.FieldMarshal | TableMask.DeclSecurity | TableMask.ClassLayout | TableMask.FieldLayout | TableMask.StandAloneSig | TableMask.EventMap | TableMask.EventPtr | TableMask.Event | TableMask.PropertyMap | TableMask.PropertyPtr | TableMask.Property | TableMask.MethodSemantics | TableMask.MethodImpl | TableMask.ModuleRef | TableMask.TypeSpec | TableMask.ImplMap | TableMask.FieldRva | TableMask.EnCLog | TableMask.EnCMap | TableMask.Assembly | TableMask.AssemblyRef | TableMask.File | TableMask.ExportedType | TableMask.ManifestResource | TableMask.NestedClass | TableMask.GenericParam | TableMask.MethodSpec | TableMask.GenericParamConstraint, } internal enum HeapSizeFlag : byte { StringHeapLarge = 0x01, // 4 byte uint indexes used for string heap offsets GUIDHeapLarge = 0x02, // 4 byte uint indexes used for GUID heap offsets BlobHeapLarge = 0x04, // 4 byte uint indexes used for Blob heap offsets EnCDeltas = 0x20, // Indicates only EnC Deltas are present DeletedMarks = 0x80, // Indicates metadata might contain items marked deleted } internal enum MethodSemanticsFlags : ushort { Setter = 0x0001, Getter = 0x0002, Other = 0x0004, AddOn = 0x0008, RemoveOn = 0x0010, Fire = 0x0020, } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1028:EnumStorageShouldBeInt32")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1027:MarkEnumsWithFlags")] public enum ElementType : byte { End = 0x00, Void = 0x01, Boolean = 0x02, Char = 0x03, Int8 = 0x04, UInt8 = 0x05, Int16 = 0x06, UInt16 = 0x07, Int32 = 0x08, UInt32 = 0x09, Int64 = 0x0a, UInt64 = 0x0b, Single = 0x0c, Double = 0x0d, String = 0x0e, Pointer = 0x0f, ByReference = 0x10, ValueType = 0x11, Class = 0x12, GenericTypeParameter = 0x13, Array = 0x14, GenericTypeInstance = 0x15, TypedReference = 0x16, IntPtr = 0x18, UIntPtr = 0x19, FunctionPointer = 0x1b, Object = 0x1c, Vector = 0x1d, GenericMethodParameter = 0x1e, RequiredModifier = 0x1f, OptionalModifier = 0x20, Internal = 0x21, Max = 0x22, Modifier = 0x40, Sentinel = 0x41, Pinned = 0x45, // SingleHFA = 0x54, // What is this? // DoubleHFA = 0x55, // What is this? } // TODO: merge with MetadataSignature public static class SignatureHeader { public const byte DefaultCall = 0x00; public const byte CCall = 0x01; public const byte StdCall = 0x02; public const byte ThisCall = 0x03; public const byte FastCall = 0x04; public const byte VarArgCall = 0x05; public const byte Field = 0x06; public const byte LocalVar = 0x07; public const byte Property = 0x08; //public const byte UnManaged = 0x09; // Not used as of now in CLR public const byte GenericInstance = 0x0A; //public const byte NativeVarArg = 0x0B; // Not used as of now in CLR public const byte Max = 0x0C; public const byte CallingConventionMask = 0x0F; public const byte HasThis = 0x20; public const byte ExplicitThis = 0x40; public const byte Generic = 0x10; public static bool IsMethodSignature(byte signatureHeader) { return (signatureHeader & SignatureHeader.CallingConventionMask) <= SignatureHeader.VarArgCall; } public static bool IsVarArgCallSignature(byte signatureHeader) { return (signatureHeader & SignatureHeader.CallingConventionMask) == SignatureHeader.VarArgCall; } public static bool IsFieldSignature(byte signatureHeader) { return (signatureHeader & SignatureHeader.CallingConventionMask) == SignatureHeader.Field; } public static bool IsLocalVarSignature(byte signatureHeader) { return (signatureHeader & SignatureHeader.CallingConventionMask) == SignatureHeader.LocalVar; } public static bool IsPropertySignature(byte signatureHeader) { return (signatureHeader & SignatureHeader.CallingConventionMask) == SignatureHeader.Property; } public static bool IsGenericInstanceSignature(byte signatureHeader) { return (signatureHeader & SignatureHeader.CallingConventionMask) == SignatureHeader.GenericInstance; } public static bool IsExplicitThis(byte signatureHeader) { return (signatureHeader & SignatureHeader.ExplicitThis) == SignatureHeader.ExplicitThis; } public static bool IsGeneric(byte signatureHeader) { return (signatureHeader & SignatureHeader.Generic) == SignatureHeader.Generic; } } #region PEFile specific data internal static class PEFileConstants { internal const ushort DosSignature = 0x5A4D; // MZ internal const int PESignatureOffsetLocation = 0x3C; internal const uint PESignature = 0x00004550; // PE00 internal const int BasicPEHeaderSize = PESignatureOffsetLocation; internal const int SizeofCOFFFileHeader = 20; internal const int SizeofOptionalHeaderStandardFields32 = 28; internal const int SizeofOptionalHeaderStandardFields64 = 24; internal const int SizeofOptionalHeaderNTAdditionalFields32 = 68; internal const int SizeofOptionalHeaderNTAdditionalFields64 = 88; internal const int NumberofOptionalHeaderDirectoryEntries = 16; internal const int SizeofOptionalHeaderDirectoriesEntries = 64; internal const int SizeofSectionHeader = 40; internal const int SizeofSectionName = 8; internal const int SizeofResourceDirectory = 16; internal const int SizeofResourceDirectoryEntry = 8; } internal struct DirectoryEntry { internal uint RelativeVirtualAddress; internal uint Size; } internal struct OptionalHeaderDirectoryEntries { // commented fields not needed: // internal DirectoryEntry ExportTableDirectory; // internal DirectoryEntry ImportTableDirectory; internal DirectoryEntry ResourceTableDirectory; // internal DirectoryEntry ExceptionTableDirectory; // internal DirectoryEntry CertificateTableDirectory; // internal DirectoryEntry BaseRelocationTableDirectory; // internal DirectoryEntry DebugTableDirectory; // internal DirectoryEntry CopyrightTableDirectory; // internal DirectoryEntry GlobalPointerTableDirectory; // internal DirectoryEntry ThreadLocalStorageTableDirectory; // internal DirectoryEntry LoadConfigTableDirectory; // internal DirectoryEntry BoundImportTableDirectory; // internal DirectoryEntry ImportAddressTableDirectory; // internal DirectoryEntry DelayImportTableDirectory; internal DirectoryEntry COR20HeaderTableDirectory; // internal DirectoryEntry ReservedDirectory; } internal struct SectionHeader { // commented fields not needed: // internal string Name; internal uint VirtualSize; internal uint VirtualAddress; internal uint SizeOfRawData; internal uint OffsetToRawData; // internal uint RVAToRelocations; // internal uint PointerToLineNumbers; // internal ushort NumberOfRelocations; // internal ushort NumberOfLineNumbers; // internal SectionCharacteristics SectionCharacteristics; } #endregion PEFile specific data #region CLR Header Specific data internal static class COR20Constants { internal const int SizeOfCOR20Header = 72; internal const uint COR20MetadataSignature = 0x424A5342; internal const int MinimumSizeofMetadataHeader = 16; internal const int SizeofStorageHeader = 4; internal const int MinimumSizeofStreamHeader = 8; internal const string StringStreamName = "#Strings"; internal const string BlobStreamName = "#Blob"; internal const string GUIDStreamName = "#GUID"; internal const string UserStringStreamName = "#US"; internal const string CompressedMetadataTableStreamName = "#~"; internal const string UncompressedMetadataTableStreamName = "#-"; internal const int LargeStreamHeapSize = 0x0001000; } internal struct COR20Header { // internal int CountBytes; // internal ushort MajorRuntimeVersion; // internal ushort MinorRuntimeVersion; internal DirectoryEntry MetaDataDirectory; // internal COR20Flags COR20Flags; // internal uint EntryPointTokenOrRVA; internal DirectoryEntry ResourcesDirectory; internal DirectoryEntry StrongNameSignatureDirectory; // internal DirectoryEntry CodeManagerTableDirectory; // internal DirectoryEntry VtableFixupsDirectory; // internal DirectoryEntry ExportAddressTableJumpsDirectory; // internal DirectoryEntry ManagedNativeHeaderDirectory; } internal struct StorageHeader { internal ushort Flags; internal ushort NumberOfStreams; } internal struct StreamHeader { internal uint Offset; internal uint Size; internal string Name; } #endregion CLR Header Specific data #region Metadata Stream Specific data internal static class MetadataStreamConstants { internal const int SizeOfMetadataTableHeader = 24; internal const int LargeTableRowCount = 0x00010000; } internal struct MetadataTableHeader { // internal uint Reserved; internal byte MajorVersion; internal byte MinorVersion; internal HeapSizeFlag HeapSizeFlags; // internal byte RowId; internal TableMask ValidTables; internal TableMask SortedTables; internal int[] CompressedMetadataTableRowCount; // Helper methods internal int GetNumberOfTablesPresent() { const ulong MASK_01010101010101010101010101010101 = 0x5555555555555555UL; const ulong MASK_00110011001100110011001100110011 = 0x3333333333333333UL; const ulong MASK_00001111000011110000111100001111 = 0x0F0F0F0F0F0F0F0FUL; const ulong MASK_00000000111111110000000011111111 = 0x00FF00FF00FF00FFUL; const ulong MASK_00000000000000001111111111111111 = 0x0000FFFF0000FFFFUL; const ulong MASK_11111111111111111111111111111111 = 0x00000000FFFFFFFFUL; ulong count = (ulong)ValidTables; count = (count & MASK_01010101010101010101010101010101) + ((count >> 1) & MASK_01010101010101010101010101010101); count = (count & MASK_00110011001100110011001100110011) + ((count >> 2) & MASK_00110011001100110011001100110011); count = (count & MASK_00001111000011110000111100001111) + ((count >> 4) & MASK_00001111000011110000111100001111); count = (count & MASK_00000000111111110000000011111111) + ((count >> 8) & MASK_00000000111111110000000011111111); count = (count & MASK_00000000000000001111111111111111) + ((count >> 16) & MASK_00000000000000001111111111111111); count = (count & MASK_11111111111111111111111111111111) + ((count >> 32) & MASK_11111111111111111111111111111111); return (int)count; } } internal static class TypeDefOrRefTag { internal const int NumberOfBits = 2; internal const uint TypeDef = 0x00000000; internal const uint TypeRef = 0x00000001; internal const uint TypeSpec = 0x00000002; internal const uint TagMask = 0x00000003; internal const int LargeRowSize = 0x00000001 << (16 - NumberOfBits); internal const TableMask TablesReferenced = TableMask.TypeDef | TableMask.TypeRef | TableMask.TypeSpec; internal static MetadataToken ConvertToToken(uint typeDefOrRefTag) { MetadataTokenType tokenType; switch (typeDefOrRefTag & TagMask) { case TypeDef: tokenType = MetadataTokenType.TypeDef; break; case TypeRef: tokenType = MetadataTokenType.TypeRef; break; case TypeSpec: tokenType = MetadataTokenType.TypeSpec; break; default: throw new BadImageFormatException(); } return new MetadataToken(tokenType, typeDefOrRefTag >> NumberOfBits); } } internal static class HasConstantTag { internal const int NumberOfBits = 2; internal const int LargeRowSize = 0x00000001 << (16 - HasConstantTag.NumberOfBits); internal const uint Field = 0x00000000; internal const uint Param = 0x00000001; internal const uint Property = 0x00000002; internal const uint TagMask = 0x00000003; internal const TableMask TablesReferenced = TableMask.Field | TableMask.Param | TableMask.Property; internal static MetadataToken ConvertToToken(uint hasConstant) { MetadataTokenType tokenType; switch (hasConstant & TagMask) { case Field: tokenType = MetadataTokenType.FieldDef; break; case Param: tokenType = MetadataTokenType.ParamDef; break; case Property: tokenType = MetadataTokenType.Property; break; default: throw new BadImageFormatException(); } return new MetadataToken(tokenType, hasConstant >> NumberOfBits); } internal static uint ConvertToTag(MetadataToken token) { uint rowId = (uint)token.Rid; switch (token.TokenType) { case MetadataTokenType.FieldDef: return (rowId << NumberOfBits) | Field; case MetadataTokenType.ParamDef: return (rowId << NumberOfBits) | Param; case MetadataTokenType.Property: return (rowId << NumberOfBits) | Property; } return 0; } } internal static class HasCustomAttributeTag { internal const int NumberOfBits = 5; internal const int LargeRowSize = 0x00000001 << (16 - HasCustomAttributeTag.NumberOfBits); internal const uint Method = 0x00000000; internal const uint Field = 0x00000001; internal const uint TypeRef = 0x00000002; internal const uint TypeDef = 0x00000003; internal const uint Param = 0x00000004; internal const uint InterfaceImpl = 0x00000005; internal const uint MemberRef = 0x00000006; internal const uint Module = 0x00000007; internal const uint DeclSecurity = 0x00000008; internal const uint Property = 0x00000009; internal const uint Event = 0x0000000A; internal const uint StandAloneSig = 0x0000000B; internal const uint ModuleRef = 0x0000000C; internal const uint TypeSpec = 0x0000000D; internal const uint Assembly = 0x0000000E; internal const uint AssemblyRef = 0x0000000F; internal const uint File = 0x00000010; internal const uint ExportedType = 0x00000011; internal const uint ManifestResource = 0x00000012; internal const uint GenericParameter = 0x00000013; internal const uint TagMask = 0x0000001F; internal const TableMask TablesReferenced = TableMask.Method | TableMask.Field | TableMask.TypeRef | TableMask.TypeDef | TableMask.Param | TableMask.InterfaceImpl | TableMask.MemberRef | TableMask.Module | TableMask.DeclSecurity | TableMask.Property | TableMask.Event | TableMask.StandAloneSig | TableMask.ModuleRef | TableMask.TypeSpec | TableMask.Assembly | TableMask.AssemblyRef | TableMask.File | TableMask.ExportedType | TableMask.ManifestResource | TableMask.GenericParam; internal static MetadataToken ConvertToToken(uint hasCustomAttribute) { MetadataTokenType tokenType; switch (hasCustomAttribute & TagMask) { case Method: tokenType = MetadataTokenType.MethodDef; break; case Field: tokenType = MetadataTokenType.FieldDef; break; case TypeRef: tokenType = MetadataTokenType.TypeRef; break; case TypeDef: tokenType = MetadataTokenType.TypeDef; break; case Param: tokenType = MetadataTokenType.ParamDef; break; case InterfaceImpl: tokenType = MetadataTokenType.InterfaceImpl; break; case MemberRef: tokenType = MetadataTokenType.MemberRef; break; case Module: tokenType = MetadataTokenType.Module; break; case DeclSecurity: tokenType = MetadataTokenType.Permission; break; case Property: tokenType = MetadataTokenType.Property; break; case Event: tokenType = MetadataTokenType.Event; break; case StandAloneSig: tokenType = MetadataTokenType.Signature; break; case ModuleRef: tokenType = MetadataTokenType.ModuleRef; break; case TypeSpec: tokenType = MetadataTokenType.TypeSpec; break; case Assembly: tokenType = MetadataTokenType.Assembly; break; case AssemblyRef: tokenType = MetadataTokenType.AssemblyRef; break; case File: tokenType = MetadataTokenType.File; break; case ExportedType: tokenType = MetadataTokenType.ExportedType; break; case ManifestResource: tokenType = MetadataTokenType.ManifestResource; break; case GenericParameter: tokenType = MetadataTokenType.GenericPar; break; default: throw new BadImageFormatException(); } return new MetadataToken(tokenType, hasCustomAttribute >> HasCustomAttributeTag.NumberOfBits); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] internal static uint ConvertToTag(MetadataToken token) { uint rowId = (uint)token.Rid; switch (token.TokenType) { case MetadataTokenType.MethodDef: return rowId << NumberOfBits | Method; case MetadataTokenType.FieldDef: return rowId << NumberOfBits | Field; case MetadataTokenType.TypeRef: return rowId << NumberOfBits | TypeRef; case MetadataTokenType.TypeDef: return rowId << NumberOfBits | TypeDef; case MetadataTokenType.ParamDef: return rowId << NumberOfBits | Param; case MetadataTokenType.InterfaceImpl: return rowId << NumberOfBits | InterfaceImpl; case MetadataTokenType.MemberRef: return rowId << NumberOfBits | MemberRef; case MetadataTokenType.Module: return rowId << NumberOfBits | Module; case MetadataTokenType.Permission: return rowId << NumberOfBits | DeclSecurity; case MetadataTokenType.Property: return rowId << NumberOfBits | Property; case MetadataTokenType.Event: return rowId << NumberOfBits | Event; case MetadataTokenType.Signature: return rowId << NumberOfBits | StandAloneSig; case MetadataTokenType.ModuleRef: return rowId << NumberOfBits | ModuleRef; case MetadataTokenType.TypeSpec: return rowId << NumberOfBits | TypeSpec; case MetadataTokenType.Assembly: return rowId << NumberOfBits | Assembly; case MetadataTokenType.AssemblyRef: return rowId << NumberOfBits | AssemblyRef; case MetadataTokenType.File: return rowId << NumberOfBits | File; case MetadataTokenType.ExportedType: return rowId << NumberOfBits | ExportedType; case MetadataTokenType.ManifestResource: return rowId << NumberOfBits | ManifestResource; case MetadataTokenType.GenericPar: return rowId << NumberOfBits | GenericParameter; } return 0; } } internal static class HasFieldMarshalTag { internal const int NumberOfBits = 1; internal const int LargeRowSize = 0x00000001 << (16 - NumberOfBits); internal const uint Field = 0x00000000; internal const uint Param = 0x00000001; internal const uint TagMask = 0x00000001; internal const TableMask TablesReferenced = TableMask.Field | TableMask.Param; internal static MetadataToken ConvertToToken(uint hasFieldMarshal) { MetadataTokenType tokenType = (hasFieldMarshal & TagMask) == Field ? MetadataTokenType.FieldDef : MetadataTokenType.ParamDef; return new MetadataToken(tokenType, hasFieldMarshal >> NumberOfBits); } internal static uint ConvertToTag(MetadataToken token) { uint rowId = (uint)token.Rid; switch (token.TokenType) { case MetadataTokenType.FieldDef: return rowId << NumberOfBits | Field; case MetadataTokenType.ParamDef: return rowId << NumberOfBits | Param; } return 0; } } internal static class HasDeclSecurityTag { internal const int NumberOfBits = 2; internal const int LargeRowSize = 0x00000001 << (16 - NumberOfBits); internal const uint TypeDef = 0x00000000; internal const uint Method = 0x00000001; internal const uint Assembly = 0x00000002; internal const uint TagMask = 0x00000003; internal const TableMask TablesReferenced = TableMask.TypeDef | TableMask.Method | TableMask.Assembly; internal static MetadataToken ConvertToToken(uint hasDeclSecurity) { MetadataTokenType tokenType; switch (hasDeclSecurity & TagMask) { case TypeDef: tokenType = MetadataTokenType.TypeDef; break; case Method: tokenType = MetadataTokenType.MethodDef; break; case Assembly: tokenType = MetadataTokenType.Assembly; break; default: throw new BadImageFormatException(); } return new MetadataToken(tokenType, hasDeclSecurity >> NumberOfBits); } internal static uint ConvertToTag(MetadataToken token) { uint rowId = (uint)token.Rid; switch (token.TokenType) { case MetadataTokenType.TypeDef: return rowId << NumberOfBits | TypeDef; case MetadataTokenType.MethodDef:return rowId << NumberOfBits | Method; case MetadataTokenType.Assembly: return rowId << NumberOfBits | Assembly; } return 0; } } internal static class MemberRefParentTag { internal const int NumberOfBits = 3; internal const int LargeRowSize = 0x00000001 << (16 - NumberOfBits); internal const uint TypeDef = 0x00000000; internal const uint TypeRef = 0x00000001; internal const uint ModuleRef = 0x00000002; internal const uint Method = 0x00000003; internal const uint TypeSpec = 0x00000004; internal const uint TagMask = 0x00000007; internal const TableMask TablesReferenced = TableMask.TypeDef | TableMask.TypeRef | TableMask.ModuleRef | TableMask.Method | TableMask.TypeSpec; internal static MetadataToken ConvertToToken(uint memberRef) { MetadataTokenType tokenType; switch (memberRef & TagMask) { case TypeDef: tokenType = MetadataTokenType.TypeDef; break; case TypeRef: tokenType = MetadataTokenType.TypeRef; break; case ModuleRef: tokenType = MetadataTokenType.ModuleRef; break; case Method: tokenType = MetadataTokenType.MethodDef; break; case TypeSpec: tokenType = MetadataTokenType.TypeSpec; break; default: throw new BadImageFormatException(); } return new MetadataToken(tokenType, memberRef >> NumberOfBits); } } internal static class HasSemanticsTag { internal const int NumberOfBits = 1; internal const int LargeRowSize = 0x00000001 << (16 - HasSemanticsTag.NumberOfBits); internal const uint Event = 0x00000000; internal const uint Property = 0x00000001; internal const uint TagMask = 0x00000001; internal const TableMask TablesReferenced = TableMask.Event | TableMask.Property; internal static MetadataToken ConvertToToken(uint hasSemantic) { MetadataTokenType tokenType = (hasSemantic & TagMask) == Event ? MetadataTokenType.Event : MetadataTokenType.Property; return new MetadataToken(tokenType, hasSemantic >> NumberOfBits); } internal static uint ConvertEventRowIdToTag(int eventRowId) { return (uint)eventRowId << NumberOfBits | Event; } internal static uint ConvertPropertyRowIdToTag(int propertyRowId) { return (uint)propertyRowId << NumberOfBits | Property; } } internal static class MethodDefOrRefTag { internal const int NumberOfBits = 1; internal const int LargeRowSize = 0x00000001 << (16 - NumberOfBits); internal const uint TagMask = 0x00000001; internal const TableMask TablesReferenced = TableMask.Method | TableMask.MemberRef; internal static MetadataToken ConvertToToken(uint methodDefOrRef) { var tokenType = (methodDefOrRef & TagMask) == 0 ? MetadataTokenType.MethodDef : MetadataTokenType.MemberRef; return new MetadataToken(tokenType, methodDefOrRef >> NumberOfBits); } } internal static class MemberForwardedTag { internal const int NumberOfBits = 1; internal const int LargeRowSize = 0x00000001 << (16 - NumberOfBits); internal const uint Field = 0x00000000; internal const uint Method = 0x00000001; internal const uint TagMask = 0x00000001; internal const TableMask TablesReferenced = TableMask.Field | TableMask.Method; internal static MetadataToken ConvertToToken(uint memberForwarded) { var tokenType = (memberForwarded & TagMask) == 0 ? MetadataTokenType.FieldDef : MetadataTokenType.MethodDef; return new MetadataToken(tokenType, memberForwarded >> NumberOfBits); } internal static uint ConvertMethodDefRowIdToTag(int methodDefRowId) { return (uint)methodDefRowId << NumberOfBits | Method; } } internal static class ImplementationTag { internal const int NumberOfBits = 2; internal const int LargeRowSize = 0x00000001 << (16 - NumberOfBits); internal const uint File = 0x00000000; internal const uint AssemblyRef = 0x00000001; internal const uint ExportedType = 0x00000002; internal const uint TagMask = 0x00000003; internal const TableMask TablesReferenced = TableMask.File | TableMask.AssemblyRef | TableMask.ExportedType; internal static MetadataToken ConvertToToken(uint implementation) { if (implementation == 0) { return default(MetadataToken); } MetadataTokenType tokenType; switch (implementation & TagMask) { case File: tokenType = MetadataTokenType.File; break; case AssemblyRef: tokenType = MetadataTokenType.AssemblyRef; break; case ExportedType: tokenType = MetadataTokenType.ExportedType; break; default: throw new BadImageFormatException(); } return new MetadataToken(tokenType, implementation >> NumberOfBits); } } internal static class CustomAttributeTypeTag { internal const int NumberOfBits = 3; internal const int LargeRowSize = 0x00000001 << (16 - NumberOfBits); internal const uint Method = 0x00000002; internal const uint MemberRef = 0x00000003; internal const uint TagMask = 0x0000007; internal const TableMask TablesReferenced = TableMask.Method | TableMask.MemberRef; internal static MetadataToken ConvertToToken(uint customAttributeType) { MetadataTokenType tokenType; switch (customAttributeType & TagMask) { case Method: tokenType = MetadataTokenType.MethodDef; break; case MemberRef: tokenType = MetadataTokenType.MemberRef; break; default: throw new BadImageFormatException(); } return new MetadataToken(tokenType, customAttributeType >> NumberOfBits); } } internal static class ResolutionScopeTag { internal const int NumberOfBits = 2; internal const int LargeRowSize = 0x00000001 << (16 - NumberOfBits); internal const uint Module = 0x00000000; internal const uint ModuleRef = 0x00000001; internal const uint AssemblyRef = 0x00000002; internal const uint TypeRef = 0x00000003; internal const uint TagMask = 0x00000003; internal const TableMask TablesReferenced = TableMask.Module | TableMask.ModuleRef | TableMask.AssemblyRef | TableMask.TypeRef; internal static MetadataToken ConvertToToken(uint resolutionScope) { MetadataTokenType tokenType; switch (resolutionScope & TagMask) { case Module: tokenType = MetadataTokenType.Module; break; case ModuleRef: tokenType = MetadataTokenType.ModuleRef; break; case AssemblyRef: tokenType = MetadataTokenType.AssemblyRef; break; case TypeRef: tokenType = MetadataTokenType.TypeRef; break; default: throw new BadImageFormatException(); } return new MetadataToken(tokenType, resolutionScope >> NumberOfBits); } } internal static class TypeOrMethodDefTag { internal const int NumberOfBits = 1; internal const int LargeRowSize = 0x00000001 << (16 - NumberOfBits); internal const uint TypeDef = 0x00000000; internal const uint MethodDef = 0x00000001; internal const uint TagMask = 0x0000001; internal const TableMask TablesReferenced = TableMask.TypeDef | TableMask.Method; internal static MetadataToken ConvertToToken(uint typeOrMethodDef) { var tokenType = (typeOrMethodDef & TagMask) == TypeDef ? MetadataTokenType.TypeDef : MetadataTokenType.MethodDef; return new MetadataToken(tokenType, typeOrMethodDef >> NumberOfBits); } internal static uint ConvertTypeDefRowIdToTag(int typeDefRowId) { return (uint)typeDefRowId << NumberOfBits | TypeDef; } internal static uint ConvertMethodDefRowIdToTag(int methodDefRowId) { return (uint)methodDefRowId << NumberOfBits | MethodDef; } } #endregion }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * 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. * */ namespace ASC.Mail.Net.ABNF { #region usings using System; using System.IO; using System.Text; #endregion /// <summary> /// This class represent ABNF "repetition". Defined in RFC 5234 4. /// </summary> public class ABNF_Repetition { #region Members private readonly int m_Max = int.MaxValue; private readonly int m_Min; private readonly ABNF_Element m_pElement; #endregion #region Properties /// <summary> /// Gets minimum repetitions. /// </summary> public int Min { get { return m_Min; } } /// <summary> /// Gets maximum repetitions. /// </summary> public int Max { get { return m_Max; } } /// <summary> /// Gets repeated element. /// </summary> public ABNF_Element Element { get { return m_pElement; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="min">Minimum repetitions.</param> /// <param name="max">Maximum repetitions.</param> /// <param name="element">Repeated element.</param> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> /// <exception cref="ArgumentNullException">Is raised when <b>element</b> is null reference.</exception> public ABNF_Repetition(int min, int max, ABNF_Element element) { if (min < 0) { throw new ArgumentException("Argument 'min' value must be >= 0."); } if (max < 0) { throw new ArgumentException("Argument 'max' value must be >= 0."); } if (min > max) { throw new ArgumentException("Argument 'min' value must be <= argument 'max' value."); } if (element == null) { throw new ArgumentNullException("element"); } m_Min = min; m_Max = max; m_pElement = element; } #endregion #region Methods /// <summary> /// /// </summary> /// <param name="reader"></param> /// <returns></returns> public static ABNF_Repetition Parse(StringReader reader) { if (reader == null) { throw new ArgumentNullException("reader"); } /* repetition = [repeat] element repeat = 1*DIGIT / (*DIGIT "*" *DIGIT) element = rulename / group / option / char-val / num-val / prose-val */ int min = 0; int max = int.MaxValue; // --- range ------------------------------------ if (char.IsDigit((char) reader.Peek())) { StringBuilder minString = new StringBuilder(); while (char.IsDigit((char) reader.Peek())) { minString.Append((char) reader.Read()); } min = Convert.ToInt32(minString.ToString()); } if (reader.Peek() == '*') { reader.Read(); } if (char.IsDigit((char) reader.Peek())) { StringBuilder maxString = new StringBuilder(); while (char.IsDigit((char) reader.Peek())) { maxString.Append((char) reader.Read()); } max = Convert.ToInt32(maxString.ToString()); } //----------------------------------------------- // End of stream reached. if (reader.Peek() == -1) { return null; } // We have rulename. else if (char.IsLetter((char) reader.Peek())) { return new ABNF_Repetition(min, max, ABNF_RuleName.Parse(reader)); } // We have group. else if (reader.Peek() == '(') { return new ABNF_Repetition(min, max, ABFN_Group.Parse(reader)); } // We have option. else if (reader.Peek() == '[') { return new ABNF_Repetition(min, max, ABNF_Option.Parse(reader)); } // We have char-val. else if (reader.Peek() == '\"') { return new ABNF_Repetition(min, max, ABNF_CharVal.Parse(reader)); } // We have num-val. else if (reader.Peek() == '%') { // Eat '%'. reader.Read(); if (reader.Peek() == 'd') { return new ABNF_Repetition(min, max, ABNF_DecVal.Parse(reader)); } else { throw new ParseException("Invalid 'num-val' value '" + reader.ReadToEnd() + "'."); } } // We have prose-val. else if (reader.Peek() == '<') { return new ABNF_Repetition(min, max, ABNF_ProseVal.Parse(reader)); } return null; } #endregion } }
using UnityEngine; using UnityEditor; using System; using System.Xml; using System.IO; using System.Collections; using System.Collections.Generic; public class CollectibleEditorWindow : EditorWindow { public delegate void UpdateHandler(); public static event UpdateHandler onCollectibleUpdateE; static private CollectibleEditorWindow window; private static CollectibleListPrefab prefab; private static List<CollectibleTB> collectibleList=new List<CollectibleTB>(); private static string[] nameList=new string[0]; private int index=0; public static void Init () { // Get existing open window or if none, make a new one: window = (CollectibleEditorWindow)EditorWindow.GetWindow(typeof (CollectibleEditorWindow)); window.minSize=new Vector2(615, 250); window.maxSize=new Vector2(615, 251); EditorCollectibleList eCollectibleList=CollectibleManagerWindow.LoadCollectible(); prefab=eCollectibleList.prefab; collectibleList=prefab.collectibleList; nameList=eCollectibleList.nameList; int enumLength = Enum.GetValues(typeof(_EffectAttrType)).Length; effectTypeLabel=new string[enumLength]; effectTypeTooltip=new string[enumLength]; for(int i=0; i<enumLength; i++) effectTypeLabel[i]=((_EffectAttrType)i).ToString(); for(int i=0; i<enumLength; i++) effectTypeTooltip[i]=""; effectTypeTooltip[0]="Reduce target's HP"; effectTypeTooltip[1]="Restore target's HP"; effectTypeTooltip[2]="Reduce target's AP"; effectTypeTooltip[3]="Restore target's AP"; effectTypeTooltip[4]="Increase/decrease target's damage"; effectTypeTooltip[5]="Increase/decrease target's movement range"; effectTypeTooltip[6]="Increase/decrease target's attack range"; effectTypeTooltip[7]="Increase/decrease target's speed"; effectTypeTooltip[8]="Increase/decrease target's attack"; effectTypeTooltip[9]="Increase/decrease target's defend"; effectTypeTooltip[10]="Increase/decrease target's critical chance"; effectTypeTooltip[11]="Increase/decrease target's critical immunity"; effectTypeTooltip[12]="Increase/decrease target's attack per turn"; effectTypeTooltip[13]="Increase/decrease target's counter attack limit "; effectTypeTooltip[14]="Stun target, stop target from doing anything"; effectTypeTooltip[15]="Prevent target from attack"; effectTypeTooltip[16]="Prevent target from moving"; effectTypeTooltip[17]="Prevent target from using ability"; effectTypeTooltip[18]="Faction gain points"; } float startX, startY, height, spaceY;//, lW; float contentHeight; private Vector2 scrollPos; private GUIContent cont; private GUIContent[] contList; void OnGUI () { if(window==null) Init(); Rect visibleRect=new Rect(0, 0, window.position.width, window.position.height); Rect contentRect=new Rect(0, 0, window.position.width-15, contentHeight); scrollPos = GUI.BeginScrollView(visibleRect, scrollPos, contentRect); GUI.changed = false; if(GUI.Button(new Rect(window.position.width-130, 5, 120, 25), "CollectibleManager")){ this.Close(); CollectibleManagerWindow.Init(); } startX=3; startY=3; height=15; spaceY=17; if(collectibleList.Count>0) { GUI.SetNextControlName ("CollectibleSelect"); index = EditorGUI.Popup(new Rect(startX, startY, 300, height), "Collectible:", index, nameList); if(GUI.changed){ GUI.FocusControl ("CollectibleSelect"); } CollectibleTB collectible=collectibleList[index]; Effect effect=collectible.effect; EditorGUI.LabelField(new Rect(340, startY, 70, height), "Icon: "); collectible.icon=(Texture)EditorGUI.ObjectField(new Rect(380, startY, 70, 70), collectible.icon, typeof(Texture), false); effect.icon=collectible.icon; //~ cont=new GUIContent("PointCost:", "The cost of unit"); //~ unit.pointCost = EditorGUI.IntField(new Rect(startX, startY+=spaceY, 300, height), cont, unit.pointCost); cont=new GUIContent("Name:", "The name for the unit ability"); //~ EditorGUI.LabelField(new Rect(startX, startY+=20, 200, 20), "Name: "); collectible.collectibleName=EditorGUI.TextField(new Rect(startX, startY+=spaceY, 300, height), cont, collectible.collectibleName); effect.name=collectible.collectibleName; startY+=7; //~ cont=new GUIContent("Is Buff:", "Check if the collectible gives buff effect, this is merely for GUI purpose"); //~ EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), cont); //~ effect.isBuff=EditorGUI.Toggle(new Rect(startX, startY+=spaceY, 300, height), cont, effect.isBuff); cont=new GUIContent("Enable AOE:", "Check if the collectible has an area of effect (affects more than single tile)"); //~ EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), cont); collectible.enableAOE=EditorGUI.Toggle(new Rect(startX, startY+=spaceY, 300, height), cont, collectible.enableAOE); if(collectible.enableAOE){ cont=new GUIContent("AOE Range:", "The range of aoe in term of tile"); //~ EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), cont); collectible.aoeRange=EditorGUI.IntField(new Rect(startX, startY+=spaceY, 300, height), cont, collectible.aoeRange); } else startY+=spaceY; startY+=3; if(GUI.Button(new Rect(startX, startY+=spaceY, 100, height), "add effect")){ if(effect.effectAttrs.Count<4) effect.effectAttrs.Add(new EffectAttr()); else Debug.Log("Cannot have more than 4 effects"); } for(int i=0; i<effect.effectAttrs.Count; i++){ EffectAttrConfigurator(effect, i, startX, startY); startX+=135; } startX=3; //~ startY+=150; //~ EditorGUI.LabelField(new Rect(startX, startY+=5, 300, 25), "Collectible Description (for runtime UI): "); //~ collectible.effect.desp=EditorGUI.TextArea(new Rect(startX, startY+=17, window.position.width-20, 50), collectible.effect.desp); //~ startY+=60; contentHeight=startY; if (GUI.changed){ if(GUI.changed) EditorUtility.SetDirty(collectible); if(onCollectibleUpdateE!=null) onCollectibleUpdateE(); } } else{ EditorGUI.LabelField(new Rect(startX, startY, 450, height), "No Collectible has been assigned, please do so in the CollectibleManager"); } GUI.EndScrollView(); } static string[] effectTypeLabel=new string[0]; static string[] effectTypeTooltip=new string[0]; void EffectAttrConfigurator(Effect effect, int ID, float startX, float startY){ EffectAttr effectAttr=effect.effectAttrs[ID]; if(GUI.Button(new Rect(startX, startY+=18, 70, 14), "Remove")){ effect.effectAttrs.Remove(effectAttr); return; } int type=(int)effectAttr.type; cont=new GUIContent("Type:", "Type of the effect"); contList=new GUIContent[effectTypeLabel.Length]; for(int i=0; i<contList.Length; i++) contList[i]=new GUIContent(effectTypeLabel[i], effectTypeTooltip[i]); EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), cont); type = EditorGUI.Popup(new Rect(startX+40, startY, 80, 16), type, contList); effectAttr.type=(_EffectAttrType)type; if(effectAttr.type==_EffectAttrType.HPDamage || effectAttr.type==_EffectAttrType.HPGain || effectAttr.type==_EffectAttrType.APGain || effectAttr.type==_EffectAttrType.APDamage){ cont=new GUIContent("ValueMin:", "Minimum value for the effect"); EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), cont); effectAttr.value=EditorGUI.FloatField(new Rect(startX+70, startY-1, 50, 16), effectAttr.value); cont=new GUIContent("ValueMax:", "Maximum value for the effect"); EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), cont); effectAttr.valueAlt=EditorGUI.FloatField(new Rect(startX+70, startY-1, 50, 16), effectAttr.valueAlt); } else{ cont=new GUIContent("ValueMax:", "Value for the effect"); EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), cont); effectAttr.value=EditorGUI.FloatField(new Rect(startX+70, startY-1, 50, 16), effectAttr.value); } //~ if(type==1){ //~ //cont=new GUIContent("Range:", "Effective range of the ability in term of tile"); //~ //EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), "use Default Damage:"); //~ //effect.useDefaultDamageValue=EditorGUI.Toggle(new Rect(startX+120, startY-1, 50, 16), effect.useDefaultDamageValue); //~ } //~ if(type!=2 || !effectAttr.useDefaultDamageValue){ //~ //cont=new GUIContent("Range:", "Effective range of the ability in term of tile"); //~ EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), "value:"); //~ effectAttr.value=EditorGUI.FloatField(new Rect(startX+70, startY-1, 50, 16), effectAttr.value); //~ } cont=new GUIContent("Duration:", "Effective duration of the effect in term of round"); EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), cont); effectAttr.duration=EditorGUI.IntField(new Rect(startX+70, startY-1, 50, 16), effectAttr.duration); } /* void UAbConfigurator(){ int startY=315; int startX=5; GUIStyle style=new GUIStyle(); style.wordWrap=true; UnitAbility uAB=allUAbList[selectedUAbID]; cont=new GUIContent("Default Icon:", "The icon for the unit ability"); EditorGUI.LabelField(new Rect(startX, startY, 80, 20), cont); uAB.icon=(Texture)EditorGUI.ObjectField(new Rect(startX+10, startY+17, 60, 60), uAB.icon, typeof(Texture), false); startX+=100; cont=new GUIContent("Unavailable:", "The icon for the unit ability when it's unavailable (on cooldown and etc.)"); EditorGUI.LabelField(new Rect(startX, startY, 80, 34), cont); uAB.iconUnavailable=(Texture)EditorGUI.ObjectField(new Rect(startX+10, startY+17, 60, 60), uAB.iconUnavailable, typeof(Texture), false); startX+=80; //startX+=100; //cont=new GUIContent("Effect:", "The prefab intend as visual effect to spawn everytime the ability is used"); //EditorGUI.LabelField(new Rect(startX, startY, 200, 20), cont); //uAB.effect=(GameObject)EditorGUI.ObjectField(new Rect(startX+50, startY-1, 120, 17), uAB.effect, typeof(GameObject), false); startX=5; startY=390; cont=new GUIContent("Name:", "The name for the unit ability"); EditorGUI.LabelField(new Rect(startX, startY+=20, 200, 20), "Name: "); uAB.name=EditorGUI.TextField(new Rect(startX+50, startY-1, 120, 17), uAB.name); startY+=8; int type=(int)uAB.type; cont=new GUIContent("Type:", "Type of the ability"); contList=new GUIContent[abilityTypeLabel.Length]; for(int i=0; i<contList.Length; i++) contList[i]=new GUIContent(abilityTypeLabel[i], abilityTypeTooltip[i]); EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), cont); type = EditorGUI.Popup(new Rect(startX+70, startY, 100, 16), type, contList); uAB.type=(_UnitAbilityType)type; if(uAB.type!=_UnitAbilityType.SelfBuff && uAB.type!=_UnitAbilityType.SelfTile){ cont=new GUIContent("RequireTargetSelect:", "Check if a target is required for the ability, else the ability will be casted on the unit tile"); EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), cont); uAB.requireTargetSelection=EditorGUI.Toggle(new Rect(startX+155, startY-1, 20, 17), uAB.requireTargetSelection); cont=new GUIContent("enableAOE:", ""); EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), cont); uAB.enableAOE=EditorGUI.Toggle(new Rect(startX+155, startY-1, 20, 17), uAB.enableAOE); if(uAB.enableAOE){ cont=new GUIContent("aoeRange:", "Effective aoe range of the ability in term of tile, "); EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), cont); uAB.aoeRange=EditorGUI.IntField(new Rect(startX+120, startY-1, 50, 16), uAB.aoeRange); if(uAB.requireTargetSelection) uAB.aoeRange=Math.Max(0, uAB.aoeRange); else uAB.aoeRange=Math.Max(1, uAB.aoeRange); } if(uAB.requireTargetSelection){ cont=new GUIContent("Range:", "Effective range of the ability in term of tile"); EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), cont); uAB.range=EditorGUI.IntField(new Rect(startX+120, startY-1, 50, 16), uAB.range); uAB.range=Math.Max(1, uAB.range); } } cont=new GUIContent("AP Cost:", "The AP cost to use this unit ability"); EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), cont); uAB.cost=EditorGUI.IntField(new Rect(startX+120, startY-1, 50, 16), uAB.cost); cont=new GUIContent("Cooldown:", "The cooldown (in round) required before the unit ability become available again after each use"); EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), cont); uAB.cdDuration=EditorGUI.IntField(new Rect(startX+120, startY-1, 50, 16), uAB.cdDuration); cont=new GUIContent("Limit:", "The maximum amount of time the ability can be use in the game (set to -1 for infinite use)"); EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), cont); uAB.useLimit=EditorGUI.IntField(new Rect(startX+120, startY-1, 50, 16), uAB.useLimit); startY=330; startX=205; //EditorGUI.LabelField(new Rect(startX, startY, 200, 20), "AbilityEffect:"); if(GUI.Button(new Rect(startX, startY, 100, 20), "Add Effect")){ if(uAB.effectAttrs.Count<3){ uAB.effectAttrs.Add(new EffectAttr()); } } cont=new GUIContent("Delay:", "The delay in second before the effects take place (only applicable when the ability doesnt use a shoot mechanism)"); EditorGUI.LabelField(new Rect(startX+135, startY, 200, 20), cont); uAB.effectUseDelay=EditorGUI.FloatField(new Rect(startX+180, startY-1, 50, 16), uAB.effectUseDelay); startY+=7; for(int i=0; i<uAB.effectAttrs.Count; i++){ EffectConfigurator(uAB, i, startX, startY); startX+=135; } startY+=150; startX=205; cont=new GUIContent("Effect Self:", "The prefab intend as visual effect to spawn on the unit using the ability everytime the ability is used"); EditorGUI.LabelField(new Rect(startX, startY, 200, 20), cont); uAB.effectUse=(GameObject)EditorGUI.ObjectField(new Rect(startX+80, startY-1, 90, 17), uAB.effectUse, typeof(GameObject), false); cont=new GUIContent(" - Delay:", "The delay in second before the visual effect is spawned"); EditorGUI.LabelField(new Rect(startX+170, startY, 200, 20), cont); uAB.effectUseDelay=EditorGUI.FloatField(new Rect(startX+235, startY-1, 50, 16), uAB.effectUseDelay); cont=new GUIContent("Effect Target:", "The prefab intend as visual effect to spawn on the unit using the ability everytime the ability is used"); EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), cont); uAB.effectTarget=(GameObject)EditorGUI.ObjectField(new Rect(startX+80, startY-1, 90, 17), uAB.effectTarget, typeof(GameObject), false); cont=new GUIContent(" - Delay:", "The delay in second before the target visual effect is spawned"); EditorGUI.LabelField(new Rect(startX+170, startY, 200, 20), cont); uAB.effectTargetDelay=EditorGUI.FloatField(new Rect(startX+235, startY-1, 50, 16), uAB.effectTargetDelay); startY+=20; if(type!=0){ int shootMode=(int)uAB.shootMode; cont=new GUIContent("ShootMode:", "Shoot object setting for the ability if applicable"); contList=new GUIContent[shootModeLabel.Length]; for(int i=0; i<contList.Length; i++) contList[i]=new GUIContent(shootModeLabel[i], shootModeTooltip[i]); EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), cont); shootMode = EditorGUI.Popup(new Rect(startX+80, startY, 100, 16), shootMode, contList); uAB.shootMode=(_AbilityShootMode)shootMode; if(shootMode!=0){ cont=new GUIContent("ShootObject:", "The shootObject prefab to be used"); EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), cont); uAB.shootObject=(GameObject)EditorGUI.ObjectField(new Rect(startX+80, startY-1, 100, 17), uAB.shootObject, typeof(GameObject), false); } else startY+=18; } startY+=10; cont=new GUIContent("Sound Use:", "The sound to play when the ability is used"); EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), cont); uAB.soundUse=(AudioClip)EditorGUI.ObjectField(new Rect(startX+80, startY-1, 90, 17), uAB.soundUse, typeof(AudioClip), false); cont=new GUIContent("Sound Hit:", "The sound to play on the target when the ability hit it's target"); EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), cont); uAB.soundHit=(AudioClip)EditorGUI.ObjectField(new Rect(startX+80, startY-1, 90, 17), uAB.soundHit, typeof(AudioClip), false); startX=5; startY=(int)window.position.height-75; EditorGUI.LabelField(new Rect(startX, startY, 300, 25), "Ability Description (for runtime UI): "); uAB.desp=EditorGUI.TextArea(new Rect(startX, startY+17, window.position.width-10, 50), uAB.desp); } void EffectConfigurator(UnitAbility uAB, int ID, int startX, int startY){ EffectAttr effectAttr=uAB.effectAttrs[ID]; if(GUI.Button(new Rect(startX, startY+=18, 70, 14), "Remove")){ uAB.effectAttrs.Remove(effectAttr); return; } int type=(int)effectAttr.type; cont=new GUIContent("Type:", "Type of the effect"); contList=new GUIContent[effectTypeLabel.Length]; for(int i=0; i<contList.Length; i++) contList[i]=new GUIContent(effectTypeLabel[i], effectTypeTooltip[i]); EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), cont); type = EditorGUI.Popup(new Rect(startX+40, startY, 80, 16), type, contList); effectAttr.type=(_AbilityEffectType)type; if(type==1){ //cont=new GUIContent("Range:", "Effective range of the ability in term of tile"); //EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), "use Default Damage:"); //effect.useDefaultDamageValue=EditorGUI.Toggle(new Rect(startX+120, startY-1, 50, 16), effect.useDefaultDamageValue); } if(type!=2 || !effectAttr.useDefaultDamageValue){ //cont=new GUIContent("Range:", "Effective range of the ability in term of tile"); EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), "value:"); effectAttr.value=EditorGUI.FloatField(new Rect(startX+70, startY-1, 50, 16), effectAttr.value); } cont=new GUIContent("Duration:", "Effective duration of the effect in term of round"); EditorGUI.LabelField(new Rect(startX, startY+=18, 200, 20), cont); effectAttr.duration=EditorGUI.IntField(new Rect(startX+70, startY-1, 50, 16), effectAttr.duration); } */ }
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ namespace Adxstudio.Xrm.Search.Index { using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using Adxstudio.Xrm.Cms; using Adxstudio.Xrm.ContentAccess; using Adxstudio.Xrm.Core.Flighting; using Adxstudio.Xrm.Diagnostics.Trace; using Adxstudio.Xrm.Resources; using Microsoft.Xrm.Portal.Configuration; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Messages; /// <summary> /// Fetch Xml Indexer /// </summary> /// <seealso cref="Adxstudio.Xrm.Search.Index.ICrmEntityIndexer" /> public class FetchXmlIndexer : ICrmEntityIndexer { private readonly FetchXml _fetchXml; private readonly ICrmEntityIndex _index; private readonly string _titleAttributeLogicalName; private readonly FetchXmlLocaleConfig _localeConfig; public FetchXmlIndexer(ICrmEntityIndex index, XNode fetchXml, string titleAttributeLogicalName) : this(index, new FetchXml(fetchXml), titleAttributeLogicalName) { } public FetchXmlIndexer(ICrmEntityIndex index, string fetchXml, string titleAttributeLogicalName) : this(index, XDocument.Parse(fetchXml), titleAttributeLogicalName) { } internal FetchXmlIndexer(ICrmEntityIndex index, FetchXml fetchXml, string titleAttributeLogicalName) { if (index == null) { throw new ArgumentNullException("index"); } if (fetchXml == null) { throw new ArgumentNullException("fetchXml"); } if (titleAttributeLogicalName == null) { throw new ArgumentNullException("titleAttributeLogicalName"); } _index = index; _fetchXml = fetchXml; _titleAttributeLogicalName = titleAttributeLogicalName; if (!this._fetchXml.ContainsAttribute("modifiedon") && this._fetchXml.LogicalName != "annotation") { this._fetchXml.AddAttribute("modifiedon"); } if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.CmsEnabledSearching)) { if (this._fetchXml.LogicalName == "adx_blog") { if (!this._fetchXml.ContainsAttribute("adx_parentpageid")) { this._fetchXml.AddAttribute("adx_parentpageid"); } } if (this._fetchXml.LogicalName == "adx_blogpost") { if (!this._fetchXml.ContainsAttribute("adx_blogid")) { this._fetchXml.AddAttribute("adx_blogid"); } // Add the published attribute as we need it for indexing for CMS if (!this._fetchXml.ContainsAttribute("adx_published")) { this._fetchXml.AddAttribute("adx_published"); } if (!this._fetchXml.ContainsLinkEntity("adx_blog_blogpost")) { this._fetchXml.AddLinkEntity("adx_blog", "adx_blogid", "adx_blogid", "adx_blog_blogpost", "inner"); } this._fetchXml.AddLinkEntityAttribute("adx_blog_blogpost", "adx_parentpageid"); this._fetchXml.AddLinkEntityAttribute("adx_blog_blogpost", "adx_partialurl"); if (!this._fetchXml.ContainsAttribute("adx_partialurl")) { this._fetchXml.AddAttribute("adx_partialurl"); } } if (this._fetchXml.LogicalName == "adx_idea") { if (!this._fetchXml.ContainsAttribute("adx_ideaforumid")) { this._fetchXml.AddAttribute("adx_ideaforumid"); } // Add the approved flag as this is needed for indexing CMS this._fetchXml.AddConditionalStatement("and", "adx_approved", "eq", "true"); if (!this._fetchXml.ContainsLinkEntity("adx_idea_ideaforum")) { this._fetchXml.AddLinkEntity("adx_ideaforum", "adx_ideaforumid", "adx_ideaforumid", "adx_idea_ideaforum", "inner"); } this._fetchXml.AddLinkEntityAttribute("adx_idea_ideaforum", "adx_partialurl"); this._fetchXml.AddConditionalStatement("and", "adx_partialurl", "not-null", null, "adx_idea_ideaforum"); this._fetchXml.AddConditionalStatement("and", "adx_partialurl", "not-null"); this._fetchXml.AddAttribute("adx_partialurl"); } if (this._fetchXml.LogicalName == "adx_communityforumthread") { if (!this._fetchXml.ContainsAttribute("adx_forumid")) { this._fetchXml.AddAttribute("adx_forumid"); } } if (this._fetchXml.LogicalName == "adx_communityforumpost") { if (!this._fetchXml.ContainsLinkEntity("adx_communityforumpost_communityforumthread")) { this._fetchXml.AddLinkEntity("adx_communityforumthread", "adx_communityforumthreadid", "adx_forumthreadid", "adx_communityforumpost_communityforumthread", "inner"); } this._fetchXml.AddLinkEntityAttribute("adx_communityforumpost_communityforumthread", "adx_forumid"); } if (this._fetchXml.LogicalName == "adx_webfile") { if (!this._fetchXml.ContainsAttribute("adx_parentpageid")) { this._fetchXml.AddAttribute("adx_parentpageid"); } if (!this._fetchXml.ContainsAttribute("adx_partialurl")) { this._fetchXml.AddAttribute("adx_partialurl"); } } if (this._fetchXml.LogicalName == "incident") { // It is marked as Resolved (1) this._fetchXml.AddConditionalStatement("and", "statecode", "eq", "1"); this._fetchXml.AddConditionalStatement("and", "adx_publishtoweb", "eq", "1"); } // CMS filtering for KnowledgeArticles if they don't have these rules then don't add to index. if (this._fetchXml.LogicalName == "knowledgearticle") { // make sure statecode is published = 3 this._fetchXml.AddConditionalStatement("and", "statecode", "eq", "3"); this._fetchXml.AddConditionalStatement("and", "isrootarticle", "eq", "false"); this._fetchXml.AddConditionalStatement("and", "isinternal", "eq", "false"); // Add this filter for url filtering this._fetchXml.AddConditionalStatement("and", "articlepublicnumber", "not-null"); this.AddRelatedEntityFetch("connection", "connectionid", "record1id", "knowledgearticleid", "record2id", "product", "productid", "record2id", "productid"); if (this._index.DataContext.AssertEntityExists("adx_contentaccesslevel")) { this.AddRelatedEntityFetch("adx_knowledgearticlecontentaccesslevel", "adx_knowledgearticlecontentaccesslevelid", "knowledgearticleid", "knowledgearticleid", "adx_contentaccesslevelid", "adx_contentaccesslevel", "adx_contentaccesslevelid", "adx_contentaccesslevelid", "adx_contentaccesslevelid"); } } } // Add the language fields since the related fields cannot be included in a view using the savedquery editor if (_fetchXml.LogicalName == "knowledgearticle") { _fetchXml.AddLinkEntity("languagelocale", "languagelocaleid", "languagelocaleid", "language_localeid", "outer"); _fetchXml.AddLinkEntityAttribute("language_localeid", "localeid"); _fetchXml.AddLinkEntityAttribute("language_localeid", "code"); _fetchXml.AddLinkEntityAttribute("language_localeid", "region"); _fetchXml.AddLinkEntityAttribute("language_localeid", "name"); _fetchXml.AddLinkEntityAttribute("language_localeid", "language"); // This ensures we get knowledge article search result along with annotation in case knowledge article doesn't have keywords contained in annotation if (_index.DisplayNotes) { this.AddNotesLinkEntity(_index.NotesFilter); } _localeConfig = FetchXmlLocaleConfig.CreateKnowledgeArticleConfig(); } else { _localeConfig = FetchXmlLocaleConfig.CreatePortalLanguageConfig(); } if (_fetchXml.LogicalName == "annotation") { _fetchXml.AddConditionalStatement("and", "filename", "not-null"); this.AddNotesFilter(_index.NotesFilter); this.AddRelatedKnowledgeArticleAndProductFetch(); } } public bool Indexes(string entityLogicalName) { return string.Equals(_fetchXml.LogicalName, entityLogicalName, StringComparison.InvariantCultureIgnoreCase); } public IEnumerable<CrmEntityIndexDocument> GetDocuments() { ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Start"); var dataContext = _index.DataContext; var documentFactory = new FetchXmlIndexDocumentFactory(_index, _fetchXml, _titleAttributeLogicalName, _localeConfig); var currentPageFetchXml = _fetchXml; var knowledgeArticleFilter = new FetchXmlResultsFilter(); while (true) { var request = new OrganizationRequest("ExecuteFetch"); request.Parameters["FetchXml"] = currentPageFetchXml.ToString(); var response = dataContext.Execute(request); if (response == null) { throw new InvalidOperationException("Did not receive valid response from ExecuteFetchRequest."); } var fetchXmlResponse = response.Results["FetchXmlResult"] as string; if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.CmsEnabledSearching)) { if (this._fetchXml.LogicalName == "knowledgearticle") { fetchXmlResponse = knowledgeArticleFilter.Aggregate(fetchXmlResponse, "knowledgearticleid", "record2id.productid", "adx_contentaccesslevelid.adx_contentaccesslevelid", "record2id.connectionid", "annotation.filename", "annotation.notetext", "annotation.annotationid"); } if (this._fetchXml.LogicalName == "annotation") { fetchXmlResponse = knowledgeArticleFilter.Aggregate(fetchXmlResponse, "annotationid", "product.productid"); } } var resultSet = new FetchXmlResultSet(fetchXmlResponse); ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("FetchXmlResult:LogicalName={0}, Count={1}", EntityNamePrivacy.GetEntityName(this._fetchXml.LogicalName), resultSet.Count())); foreach (var document in resultSet.Select(documentFactory.GetDocument)) { yield return document; } if (resultSet.MoreRecords) { currentPageFetchXml = currentPageFetchXml.ForNextPage(resultSet.PagingCookie); } else { break; } } ADXTrace.Instance.TraceInfo(TraceCategory.Application, "End"); } private void AddRelatedEntityFetch(string intersectLinkEntityName, string intersectLinkEntityNamePrimaryAttribute, string intersectLinkEntityFrom, string intersectLinkEntityTo, string intersectLinkEntityAlias, string linkEntityName, string linkEntityFrom, string linkEntityTo, string attributeName) { var xml = @"<link-entity name='{0}' from='{1}' to='{2}' link-type='outer' alias='{3}'> <attribute name ='{4}' /> <link-entity name ='{5}' from ='{6}' to ='{7}' link-type ='outer' > <attribute name ='{8}' /> <filter > <condition attribute ='statuscode' operator='eq' value ='1' /> <condition attribute ='statecode' operator='eq' value ='0' /> </filter > </link-entity > </link-entity > "; this._fetchXml.AddLinkEntity(XElement.Parse(string.Format(xml, intersectLinkEntityName, intersectLinkEntityFrom, intersectLinkEntityTo, intersectLinkEntityAlias, intersectLinkEntityNamePrimaryAttribute, linkEntityName, linkEntityFrom, linkEntityTo, attributeName))); } private void AddRelatedKnowledgeArticleAndProductFetch() { var fetchXml = @"<link-entity name='knowledgearticle' from='knowledgearticleid' to='objectid' alias='knowledgearticle' link-type='inner'> <attribute name ='rating' /> <attribute name ='modifiedon' /> <attribute name ='knowledgearticleid' /> <link-entity name ='connection' from ='record2id' to='knowledgearticleid' link-type ='outer'> <link-entity name ='product' from ='productid' to='record1id' alias='product' link-type ='outer'> <attribute name ='productid'/> <filter > <condition attribute ='statecode' operator='eq' value ='0' /> <condition attribute ='statuscode' operator='eq' value ='1' /> </filter > </link-entity > </link-entity > </link-entity >"; this._fetchXml.AddLinkEntity(XElement.Parse(fetchXml)); } private void AddNotesFilter(string notePrefix) { var fetchXml = @"<filter> <condition attribute='notetext' operator='begins-with' value='{0}' /> </filter > "; this._fetchXml.AddLinkEntity(XElement.Parse(string.Format(fetchXml, notePrefix))); } private void AddNotesLinkEntity(string notePrefix) { var fetchXml = @"<link-entity name='annotation' from='objectid' to='knowledgearticleid' link-type='outer' alias='annotation' > <attribute name='filename' /> <attribute name='notetext' /> <attribute name='annotationid' /> <filter> <condition attribute='notetext' operator='begins-with' value='{0}' /> <condition attribute='filename' operator='not-null' /> </filter> </link-entity>"; this._fetchXml.AddLinkEntity(XElement.Parse(string.Format(fetchXml, notePrefix))); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Buffers.Operations; using System.Buffers.Text; using System.Buffers.Writer; using System.Diagnostics; using System.Text; using System.Text.Utf8; using Xunit; namespace System.Buffers.Tests { public class BasicUnitTests { private static readonly Utf8String _crlf = (Utf8String)"\r\n"; private static readonly Utf8String _eoh = (Utf8String)"\r\n\r\n"; // End Of Headers private static readonly Utf8String _http11OK = (Utf8String)"HTTP/1.1 200 OK\r\n"; private static readonly Utf8String _headerServer = (Utf8String)"Server: Custom"; private static readonly Utf8String _headerContentLength = (Utf8String)"Content-Length: "; private static readonly Utf8String _headerContentLengthZero = (Utf8String)"Content-Length: 0\r\n"; private static readonly Utf8String _headerContentTypeText = (Utf8String)"Content-Type: text/plain\r\n"; private static Utf8String _plainTextBody = (Utf8String)"Hello, World!"; private static Sink _sink = new Sink(4096); private static readonly string s_response = "HTTP/1.1 200 OK\r\nServer: Custom\r\nDate: Fri, 16 Mar 2018 10:22:15 GMT\r\nContent-Type: text/plain\r\nContent-Length: 13\r\n\r\nHello, World!"; [Fact] public void WritePlainText() { DateHeader.SetDateValues(new DateTimeOffset(2018, 3, 16, 10, 22, 15, 10, TimeSpan.FromMilliseconds(0))); _sink.Reset(); var writer = BufferWriter.Create(_sink); // HTTP 1.1 OK writer.Write(_http11OK); // Server headers writer.Write(_headerServer); // Date header writer.Write(DateHeader.HeaderBytes); // Content-Type header writer.Write(_headerContentTypeText); // Content-Length header writer.Write(_headerContentLength); writer.Write((ulong)_plainTextBody.Bytes.Length); // End of headers writer.Write(_eoh); // Body writer.Write(_plainTextBody); writer.Flush(); var result = _sink.ToString(); Assert.Equal(s_response, _sink.ToString()); } [Fact] public void BufferWriterTransform() { byte[] buffer = new byte[10]; var writer = BufferWriter.Create(buffer.AsSpan()); var transformation = new TransformationFormat(new RemoveTransformation(2)); ReadOnlyMemory<byte> value = new byte[] { 1, 2, 3 }; writer.WriteBytes(value, transformation); Assert.Equal(-1, buffer.AsSpan().IndexOf((byte)2)); } [Fact] public void WriteLineString() { _sink.Reset(); var writer = BufferWriter.Create(_sink); writer.NewLine = new byte[] { (byte)'X', (byte)'Y' }; writer.WriteLine("hello world"); writer.WriteLine("!"); writer.Flush(); var result = _sink.ToString(); Assert.Equal("hello worldXY!XY", result); } [Fact] public void WriteLineUtf8String() { _sink.Reset(); var writer = BufferWriter.Create(_sink); writer.NewLine = new byte[] { (byte)'X', (byte)'Y' }; writer.WriteLine((Utf8String)"hello world"); writer.WriteLine((Utf8String)"!"); writer.Flush(); var result = _sink.ToString(); Assert.Equal("hello worldXY!XY", result); } [Fact] public void WriteInt32Transformed() { TransformationFormat widen = new TransformationFormat(new AsciiToUtf16()); _sink.Reset(); var writer = BufferWriter.Create(_sink); writer.Write(255, widen); writer.Flush(); var result = _sink.ToStringAssumingUtf16Buffer(); Assert.Equal("255", result); } } internal class Sink : IBufferWriter<byte> { private byte[] _buffer; private int _written; public Sink(int size) { _buffer = new byte[4096]; _written = 0; } public void Reset() => _written = 0; public void Advance(int count) { _written += count; if (_written > _buffer.Length) throw new ArgumentOutOfRangeException(nameof(count)); } public Memory<byte> GetMemory(int sizeHint = 0) => _buffer.AsMemory(_written, _buffer.Length - _written); public Span<byte> GetSpan(int sizeHint = 0) => _buffer.AsSpan(_written, _buffer.Length - _written); public Span<byte> WrittenBytes => _buffer.AsSpan(0, _written); public override string ToString() { return Encoding.UTF8.GetString(_buffer, 0, _written); } public string ToStringAssumingUtf16Buffer() { return Encoding.Unicode.GetString(_buffer, 0, _written); } } internal static class DateHeader { private const int prefixLength = 8; // "\r\nDate: ".Length private const int dateTimeRLength = 29; // Wed, 14 Mar 2018 14:20:00 GMT private const int suffixLength = 2; // crlf private const int suffixIndex = dateTimeRLength + prefixLength; private static byte[] s_headerBytesMaster = new byte[prefixLength + dateTimeRLength + suffixLength]; private static byte[] s_headerBytesScratch = new byte[prefixLength + dateTimeRLength + suffixLength]; static DateHeader() { var utf8 = Encoding.ASCII.GetBytes("\r\nDate: ").AsSpan(); utf8.CopyTo(s_headerBytesMaster); utf8.CopyTo(s_headerBytesScratch); s_headerBytesMaster[suffixIndex] = (byte)'\r'; s_headerBytesMaster[suffixIndex + 1] = (byte)'\n'; s_headerBytesScratch[suffixIndex] = (byte)'\r'; s_headerBytesScratch[suffixIndex + 1] = (byte)'\n'; SetDateValues(DateTimeOffset.UtcNow); } public static ReadOnlySpan<byte> HeaderBytes => s_headerBytesMaster; public static void SetDateValues(DateTimeOffset value) { lock (s_headerBytesScratch) { if (!Utf8Formatter.TryFormat(value, s_headerBytesScratch.AsSpan(prefixLength), out int written, 'R')) { throw new Exception("date time format failed"); } Debug.Assert(written == dateTimeRLength); var temp = s_headerBytesMaster; s_headerBytesMaster = s_headerBytesScratch; s_headerBytesScratch = temp; } } } internal class AsciiToUtf16 : IBufferTransformation { public OperationStatus Execute(ReadOnlySpan<byte> input, Span<byte> output, out int consumed, out int written) { throw new NotImplementedException(); } public OperationStatus Transform(Span<byte> buffer, int dataLength, out int written) { written = dataLength * 2; if (buffer.Length < written) return OperationStatus.DestinationTooSmall; for(int i = written - 1; i > 0; i-=2) { buffer[i] = 0; buffer[i - 1] = buffer[i / 2]; } return OperationStatus.Done; } } }
using System; using System.Linq; using Shouldly; using Spk.Common.Helpers.Service; using Xunit; namespace Spk.Common.Tests.Helpers.Service { public class ServiceResultTests { [Theory] [InlineData("data result")] public void Constructor_ShouldSetData_WhenParameterProvided(string data) { // Arrange & act var sr = new ServiceResult<string>(data); // Assert sr.Data.ShouldBe(data); } [Theory] [InlineData("test")] public void SetData_ShouldSetData(string value) { // Arrange var sr = new ServiceResult<string>(); // Act sr.SetData(value); // Assert sr.Data.ShouldBe(value); } [Theory] [InlineData("error")] public void GetFirstError_ShouldReturnFirstError(string error) { // Arrange var sr = new ServiceResult(); // Act sr.AddError(error); sr.AddError("bleh"); // Assert sr.GetFirstError().ShouldBe(error); } [Theory] [InlineData("warning")] public void GetFirstWarning_ShouldReturnFirstWarning(string warning) { // Arrange var sr = new ServiceResult(); // Act sr.AddWarning(warning); sr.AddWarning("bleh"); // Assert sr.GetFirstWarning().ShouldBe(warning); } [Theory] [InlineData("test")] [InlineData("")] [InlineData(null)] public void Success_ShouldBeTrue_WhenDataIsSet(string value) { // Arrange var sr = new ServiceResult<string>(); // Act sr.SetData(value); // Assert sr.Success.ShouldBeTrue(); } [Theory] [InlineData("")] [InlineData(null)] public void AddError_ShouldArgumentNullException_WhenNullOrEmptyError(string error) { // Act & assert Assert.Throws<ArgumentException>(() => { var sr = new ServiceResult(); sr.AddError(error); }); } [Theory] [InlineData("")] [InlineData(null)] public void AddWarning_ShouldArgumentNullException_WhenNullOrEmptyError(string warning) { // Act & assert Assert.Throws<ArgumentException>(() => { var sr = new ServiceResult(); sr.AddWarning(warning); }); } [Fact] public void Constructor_WithData_ShouldInitializeErrorCollection() { // Arrange & act var sr = new ServiceResult<string>("bleh"); // Assert sr.Errors.ShouldNotBeNull(); sr.Errors.ShouldBeEmpty(); } [Fact] public void Constructor_WithData_ShouldThrow_WhenArgumentIsNull() { // Arrange & act & assert Assert.Throws<ArgumentNullException>(() => new ServiceResult<string>(null)); } [Fact] public void DefaultConstructor_ShouldInitializeErrorCollection() { // Arrange & act var sr = new ServiceResult<string>(); // Assert sr.Errors.ShouldNotBeNull(); sr.Errors.ShouldBeEmpty(); } [Fact] public void Errors_ShouldRetrieveAllErrors() { // Arrange var sr = new ServiceResult(); // Act sr.AddError("error 1"); sr.AddError("error 2"); // Assert sr.Errors.Count().ShouldBe(2); } [Fact] public void HasWarnings_ShouldBeTrue_WhenWarnings() { // Arrange var sr = new ServiceResult(); // Act sr.AddWarning("test"); // Assert sr.HasWarnings.ShouldBeTrue(); } [Fact] public void Success_ShouldBeFalse_WhenErrors() { // Arrange var sr = new ServiceResult(); // Act sr.AddError("test"); // Assert sr.Success.ShouldBeFalse(); } [Fact] public void Success_ShouldBeTrue_WhenWarnings() { // Arrange var sr = new ServiceResult(); // Act sr.AddWarning("test"); // Assert sr.Success.ShouldBeTrue(); } [Fact] public void Warnings_ShouldRetrieveAllWarnings() { // Arrange var sr = new ServiceResult(); // Act sr.AddWarning("warning 1"); sr.AddWarning("warning 2"); // Assert Assert.Collection(sr.Warnings, x => x.ShouldBe("warning 1"), x => x.ShouldBe("warning 2") ); } [Fact] public void Succeed_ShouldReturnResultWithSuccess() { // Act && assert ServiceResult.Succeed().Success.ShouldBeTrue(); } [Fact] public void Succeed_ShouldSetData() { // Act var result = ServiceResult<string>.Succeed("result"); // Assert result.ShouldBeOfType<ServiceResult<string>>(); result.Success.ShouldBeTrue(); result.Data.ShouldBe("result"); } [Fact] public void Failed_ShouldRetrieveAllErrors() { // Act var sr = ServiceResult.Failed("error 1", "error 2"); // Assert Assert.Collection(sr.Errors, x => x.ShouldBe("error 1"), x => x.ShouldBe("error 2") ); } [Fact] public void Failed_ShouldReturnWithType() { // Act && assert ServiceResult<string>.Failed("error 1", "error 2") .ShouldBeOfType<ServiceResult<string>>(); } } }
// // Copyright (c)1998-2011 Pearson Education, Inc. or its affiliate(s). // All rights reserved. // using System; using System.Collections.Generic; using System.Xml.XPath; using OpenADK.Library.Impl.Surrogates; namespace OpenADK.Library.Tools.XPath { public class SifElementPointer : AdkElementPointer { protected SifElement fSifElement; /// <summary> /// Creates a new SifElementPointer /// </summary> /// <param name="parentPointer">The parent of this pointer</param> /// <param name="element">The element being wrapped</param> /// <param name="version">The SifVersion in effect</param> public SifElementPointer( INodePointer parentPointer, SifElement element, SifVersion version ) : base( parentPointer, element, version ) { fSifElement = element; } /// <summary> /// The set of values that can be returned from the <code>getChildAddDirective<code> /// method /// </summary> public enum AddChildDirective { /// <summary> /// It is OK to add this child /// </summary> ADD, /// <summary> /// Don't add this child because the element is not repeatable and /// another already exists as a child of this element /// </summary> DONT_ADD_NOT_REPEATABLE } /// <summary> /// Use by SIFXPathContext when determining if it can add a child /// or not /// </summary> /// <param name="childName"></param> /// <returns></returns> public AddChildDirective GetAddChildDirective( string childName ) { SifElement sifElement = (SifElement) fElement; if ( sifElement.ChildCount == 0 ) { // There are no children. Don't even check for repeatability. // This child can be added. return AddChildDirective.ADD; } IElementDef candidate = GetChildDef( childName ); if ( candidate.Field ) { // Don't evaluate repeatability return AddChildDirective.ADD; } SifElement instance = sifElement.GetChild( candidate ); if ( instance == null ) { // There are no siblings of this type. This child can be // added return AddChildDirective.ADD; } if ( candidate.IsRepeatable( Version ) ) { // This element is repeatable. This child can be added return AddChildDirective.ADD; } // A sibling exists, and the element is not repeatable return AddChildDirective.DONT_ADD_NOT_REPEATABLE; } /// <summary> /// Reutrns a child def with the requested name /// </summary> /// <param name="name">The name to look up</param> /// <returns>The ElementDef representing the requested name</returns> private IElementDef GetChildDef( string name ) { IElementDef subEleDef = Adk.Dtd.LookupElementDef( fElementDef, name ); if ( subEleDef == null ) { subEleDef = Adk.Dtd.LookupElementDef( name ); if ( subEleDef == null ) throw new ArgumentException( name + " is not a recognized element of " + fElementDef.Tag( Version ) ); } return subEleDef; } /// <summary> /// One of the XPathNodeType values representing the current node. /// </summary> public override XPathNodeType NodeType { get { if ( fElement.Parent == null ) { return XPathNodeType.Root; } else { return XPathNodeType.Element; } } } /// <summary> /// When overridden in a derived class, gets a value indicating whether the current node is an empty element without an end element tag. /// </summary> public override bool IsEmptyElement { get { return !(((SifElement) fElement).ChildCount > 0 || fElement.ElementDef.HasSimpleContent); } } /// <summary> /// Returns a cloned instance of this NodePointer /// </summary> /// <returns></returns> public override INodePointer Clone() { return new SifElementPointer( Parent, fSifElement, Version ); } internal static INodePointer Create( INodePointer parent, SifElement element, SifVersion version ) { if ( version.Major < 2 ) { IElementDef fieldDef = element.ElementDef; IRenderSurrogate rs = fieldDef.GetVersionInfo( version ).GetSurrogate(); if ( rs != null ) { return rs.CreateNodePointer( parent, element, version ); } } return new SifElementPointer( parent, element, version ); } public override INodePointer CreateAttribute( SifXPathContext context, String name ) { IElementDef subEleDef = GetChildDef( name ); SifElement sifElement = (SifElement) fElement; if ( subEleDef.Field ) { SifSimpleType ssf = subEleDef.TypeConverter.GetSifSimpleType( null ); SimpleField sf = ssf.CreateField( sifElement, subEleDef ); sifElement.SetField( sf ); return SimpleFieldPointer.Create( this, sf ); } throw new ArgumentException( "Factory could not create a child node for path: " + Name + "/" + name ); } public override INodePointer CreateChild( SifXPathContext context, string name, int i ) { SifVersion version = Version; IElementDef subEleDef = GetChildDef( name ); SifFormatter formatter = Adk.Dtd.GetFormatter( version ); SifElement sifElement = (SifElement) fElement; // Check to see if this child has a render surrogate defined IRenderSurrogate rs = subEleDef.GetVersionInfo( version ).GetSurrogate(); if ( rs != null ) { return rs.CreateChild( this, formatter, version, context ); } if ( subEleDef.Field ) { SifSimpleType ssf = subEleDef.TypeConverter.GetSifSimpleType( null ); SimpleField sf = formatter.SetField( sifElement, subEleDef, ssf, version ); return SimpleFieldPointer.Create( this, sf ); } else { SifElement newEle = SifElement.Create( sifElement, subEleDef ); formatter.AddChild( sifElement, newEle, version ); return new SifElementPointer( this, newEle, version ); } } public override void SetValue( object rawValue ) { SifSimpleType sst = GetSIFSimpleTypeValue( fElementDef, rawValue ); fElement.SifValue = sst; } /// <summary> /// Returns an INodeIterator that iterates instance representing the first attribute of /// the current node; otherwise, <c>Null</c>. /// </summary> /// <returns></returns> public override INodeIterator GetAttributes() { return new AdkAttributeIterator( this ); } /// <summary> /// Returns an INodeIterator instance that iterates the children /// of the current node; otherwise, <c>Null</c>. /// </summary> /// <returns></returns> public override INodeIterator GetChildren() { SifVersion version = Version; // Get all of the Element fields and children that match the // NodeTest into a list SifFormatter formatter = Adk.Dtd.GetFormatter( version ); IList<Element> elements = formatter.GetContent( fSifElement, version ); if( elements.Count == 0 ) { return null; } else if ( elements.Count == 1 ) { Element singleChild = elements[0]; if ( singleChild is SimpleField ) { return new SingleNodeIterator( SimpleFieldPointer.Create( this, (SimpleField) singleChild ) ); } else { return new SingleNodeIterator( Create( this, (SifElement) singleChild, version ) ); } } return new AdkElementIterator( this, elements ); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RSG { /// <summary> /// Implements a non-generic C# promise, this is a promise that simply resolves without delivering a value. /// https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise /// </summary> public interface IPromise { /// <summary> /// Set the name of the promise, useful for debugging. /// </summary> IPromise WithName(string name); /// <summary> /// Completes the promise. /// onResolved is called on successful completion. /// onRejected is called on error. /// </summary> void Done(Action onResolved, Action<Exception> onRejected); /// <summary> /// Completes the promise. /// onResolved is called on successful completion. /// Adds a default error handler. /// </summary> void Done(Action onResolved); /// <summary> /// Complete the promise. Adds a default error handler. /// </summary> void Done(); /// <summary> /// Handle errors for the promise. /// </summary> IPromise Catch(Action<Exception> onRejected); /// <summary> /// Add a resolved callback that chains a value promise (optionally converting to a different value type). /// </summary> IPromise<ConvertedT> Then<ConvertedT>(Func<IPromise<ConvertedT>> onResolved); /// <summary> /// Add a resolved callback that chains a non-value promise. /// </summary> IPromise Then(Func<IPromise> onResolved); /// <summary> /// Add a resolved callback. /// </summary> IPromise Then(Action onResolved); /// <summary> /// Add a resolved callback and a rejected callback. /// The resolved callback chains a value promise (optionally converting to a different value type). /// </summary> IPromise<ConvertedT> Then<ConvertedT>(Func<IPromise<ConvertedT>> onResolved, Action<Exception> onRejected); /// <summary> /// Add a resolved callback and a rejected callback. /// The resolved callback chains a non-value promise. /// </summary> IPromise Then(Func<IPromise> onResolved, Action<Exception> onRejected); /// <summary> /// Add a resolved callback and a rejected callback. /// </summary> IPromise Then(Action onResolved, Action<Exception> onRejected); /// <summary> /// Chain an enumerable of promises, all of which must resolve. /// The resulting promise is resolved when all of the promises have resolved. /// It is rejected as soon as any of the promises have been rejected. /// </summary> IPromise ThenAll(Func<IEnumerable<IPromise>> chain); /// <summary> /// Chain an enumerable of promises, all of which must resolve. /// Converts to a non-value promise. /// The resulting promise is resolved when all of the promises have resolved. /// It is rejected as soon as any of the promises have been rejected. /// </summary> IPromise<IEnumerable<ConvertedT>> ThenAll<ConvertedT>(Func<IEnumerable<IPromise<ConvertedT>>> chain); /// <summary> /// Chain a sequence of operations using promises. /// Reutrn a collection of functions each of which starts an async operation and yields a promise. /// Each function will be called and each promise resolved in turn. /// The resulting promise is resolved after each promise is resolved in sequence. /// </summary> IPromise ThenSequence(Func<IEnumerable<Func<IPromise>>> chain); /// <summary> /// Takes a function that yields an enumerable of promises. /// Returns a promise that resolves when the first of the promises has resolved. /// </summary> IPromise ThenRace(Func<IEnumerable<IPromise>> chain); /// <summary> /// Takes a function that yields an enumerable of promises. /// Converts to a value promise. /// Returns a promise that resolves when the first of the promises has resolved. /// </summary> IPromise<ConvertedT> ThenRace<ConvertedT>(Func<IEnumerable<IPromise<ConvertedT>>> chain); } /// <summary> /// Interface for a promise that can be rejected or resolved. /// </summary> public interface IPendingPromise : IRejectable { /// <summary> /// Resolve the promise with a particular value. /// </summary> void Resolve(); } /// <summary> /// Used to list information of pending promises. /// </summary> public interface IPromiseInfo { /// <summary> /// Id of the promise. /// </summary> int Id { get; } /// <summary> /// Human-readable name for the promise. /// </summary> string Name { get; } } /// <summary> /// Arguments to the UnhandledError event. /// </summary> public class ExceptionEventArgs : EventArgs { internal ExceptionEventArgs(Exception exception) { this.Exception = exception; } public Exception Exception { get; private set; } } /// <summary> /// Implements a non-generic C# promise, this is a promise that simply resolves without delivering a value. /// https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise /// </summary> public class Promise : IPromise, IPendingPromise, IPromiseInfo { /// <summary> /// Set to true to enable tracking of promises. /// </summary> public static bool EnablePromiseTracking = false; /// <summary> /// Event raised for unhandled errors. /// For this to work you have to complete your promises with a call to Done(). /// </summary> public static event EventHandler<ExceptionEventArgs> UnhandledException; /// <summary> /// Id for the next promise that is created. /// </summary> internal static int nextPromiseId = 0; /// <summary> /// Information about pending promises. /// </summary> internal static HashSet<IPromiseInfo> pendingPromises = new HashSet<IPromiseInfo>(); /// <summary> /// Information about pending promises, useful for debugging. /// This is only populated when 'EnablePromiseTracking' is set to true. /// </summary> public static IEnumerable<IPromiseInfo> GetPendingPromises() { return pendingPromises; } /// <summary> /// The exception when the promise is rejected. /// </summary> private Exception rejectionException; /// <summary> /// Represents a handler invoked when the promise is rejected. /// </summary> public struct RejectHandler { /// <summary> /// Callback fn. /// </summary> public Action<Exception> callback; /// <summary> /// The promise that is rejected when there is an error while invoking the handler. /// </summary> public IRejectable rejectable; } /// <summary> /// Error handlers. /// </summary> private List<RejectHandler> rejectHandlers; /// <summary> /// Represents a handler invoked when the promise is resolved. /// </summary> public struct ResolveHandler { /// <summary> /// Callback fn. /// </summary> public Action callback; /// <summary> /// The promise that is rejected when there is an error while invoking the handler. /// </summary> public IRejectable rejectable; } /// <summary> /// Completed handlers that accept no value. /// </summary> private List<ResolveHandler> resolveHandlers; /// <summary> /// ID of the promise, useful for debugging. /// </summary> public int Id { get; private set; } /// <summary> /// Name of the promise, when set, useful for debugging. /// </summary> public string Name { get; private set; } /// <summary> /// Tracks the current state of the promise. /// </summary> public PromiseState CurState { get; private set; } public Promise() { this.CurState = PromiseState.Pending; if (EnablePromiseTracking) { pendingPromises.Add(this); } } public Promise(Action<Action, Action<Exception>> resolver) { this.CurState = PromiseState.Pending; if (EnablePromiseTracking) { pendingPromises.Add(this); } try { resolver( // Resolve () => Resolve(), // Reject ex => Reject(ex) ); } catch (Exception ex) { Reject(ex); } } /// <summary> /// Add a rejection handler for this promise. /// </summary> private void AddRejectHandler(Action<Exception> onRejected, IRejectable rejectable) { if (rejectHandlers == null) { rejectHandlers = new List<RejectHandler>(); } rejectHandlers.Add(new RejectHandler() { callback = onRejected, rejectable = rejectable }); } /// <summary> /// Add a resolve handler for this promise. /// </summary> private void AddResolveHandler(Action onResolved, IRejectable rejectable) { if (resolveHandlers == null) { resolveHandlers = new List<ResolveHandler>(); } resolveHandlers.Add(new ResolveHandler() { callback = onResolved, rejectable = rejectable }); } /// <summary> /// Invoke a single error handler. /// </summary> private void InvokeRejectHandler(Action<Exception> callback, IRejectable rejectable, Exception value) { try { callback(value); } catch (Exception ex) { rejectable.Reject(ex); } } /// <summary> /// Invoke a single resolve handler. /// </summary> private void InvokeResolveHandler(Action callback, IRejectable rejectable) { try { callback(); } catch (Exception ex) { rejectable.Reject(ex); } } /// <summary> /// Helper function clear out all handlers after resolution or rejection. /// </summary> private void ClearHandlers() { rejectHandlers = null; resolveHandlers = null; } /// <summary> /// Invoke all reject handlers. /// </summary> private void InvokeRejectHandlers(Exception ex) { if (rejectHandlers != null) { rejectHandlers.Each(handler => InvokeRejectHandler(handler.callback, handler.rejectable, ex)); } ClearHandlers(); } /// <summary> /// Invoke all resolve handlers. /// </summary> private void InvokeResolveHandlers() { if (resolveHandlers != null) { resolveHandlers.Each(handler => InvokeResolveHandler(handler.callback, handler.rejectable)); } ClearHandlers(); } /// <summary> /// Reject the promise with an exception. /// </summary> public void Reject(Exception ex) { if (CurState != PromiseState.Pending) { throw new ApplicationException("Attempt to reject a promise that is already in state: " + CurState + ", a promise can only be rejected when it is still in state: " + PromiseState.Pending); } rejectionException = ex; CurState = PromiseState.Rejected; if (EnablePromiseTracking) { pendingPromises.Remove(this); } InvokeRejectHandlers(ex); } /// <summary> /// Resolve the promise with a particular value. /// </summary> public void Resolve() { if (CurState != PromiseState.Pending) { throw new ApplicationException("Attempt to resolve a promise that is already in state: " + CurState + ", a promise can only be resolved when it is still in state: " + PromiseState.Pending); } CurState = PromiseState.Resolved; if (EnablePromiseTracking) { pendingPromises.Remove(this); } InvokeResolveHandlers(); } /// <summary> /// Completes the promise. /// onResolved is called on successful completion. /// onRejected is called on error. /// </summary> public void Done(Action onResolved, Action<Exception> onRejected) { var resultPromise = new Promise(); resultPromise.WithName(Name); ActionHandlers(resultPromise, onResolved, onRejected); } /// <summary> /// Completes the promise. /// onResolved is called on successful completion. /// Adds a default error handler. /// </summary> public void Done(Action onResolved) { var resultPromise = new Promise(); resultPromise.WithName(Name); ActionHandlers(resultPromise, onResolved, ex => Promise.PropagateUnhandledException(this, ex) ); } /// <summary> /// Complete the promise. Adds a defualt error handler. /// </summary> public void Done() { var resultPromise = new Promise(); resultPromise.WithName(Name); ActionHandlers(resultPromise, () => { }, ex => Promise.PropagateUnhandledException(this, ex) ); } /// <summary> /// Set the name of the promise, useful for debugging. /// </summary> public IPromise WithName(string name) { this.Name = name; return this; } /// <summary> /// Handle errors for the promise. /// </summary> public IPromise Catch(Action<Exception> onRejected) { var resultPromise = new Promise(); resultPromise.WithName(Name); Action resolveHandler = () => { resultPromise.Resolve(); }; Action<Exception> rejectHandler = ex => { onRejected(ex); resultPromise.Reject(ex); }; ActionHandlers(resultPromise, resolveHandler, rejectHandler); return resultPromise; } /// <summary> /// Add a resolved callback that chains a value promise (optionally converting to a different value type). /// </summary> public IPromise<ConvertedT> Then<ConvertedT>(Func<IPromise<ConvertedT>> onResolved) { return Then(onResolved, null); } /// <summary> /// Add a resolved callback that chains a non-value promise. /// </summary> public IPromise Then(Func<IPromise> onResolved) { return Then(onResolved, null); } /// <summary> /// Add a resolved callback. /// </summary> public IPromise Then(Action onResolved) { return Then(onResolved, null); } /// <summary> /// Add a resolved callback and a rejected callback. /// The resolved callback chains a value promise (optionally converting to a different value type). /// </summary> public IPromise<ConvertedT> Then<ConvertedT>(Func<IPromise<ConvertedT>> onResolved, Action<Exception> onRejected) { // This version of the function must supply an onResolved. // Otherwise there is now way to get the converted value to pass to the resulting promise. var resultPromise = new Promise<ConvertedT>(); resultPromise.WithName(Name); Action resolveHandler = () => { onResolved() .Then( (ConvertedT chainedValue) => resultPromise.Resolve(chainedValue), ex => resultPromise.Reject(ex) ) .Done(); }; Action<Exception> rejectHandler = ex => { if (onRejected != null) { onRejected(ex); } resultPromise.Reject(ex); }; ActionHandlers(resultPromise, resolveHandler, rejectHandler); return resultPromise; } /// <summary> /// Add a resolved callback and a rejected callback. /// The resolved callback chains a non-value promise. /// </summary> public IPromise Then(Func<IPromise> onResolved, Action<Exception> onRejected) { var resultPromise = new Promise(); resultPromise.WithName(Name); Action resolveHandler = () => { if (onResolved != null) { onResolved() .Then( () => resultPromise.Resolve(), ex => resultPromise.Reject(ex) ) .Done(); } else { resultPromise.Resolve(); } }; Action<Exception> rejectHandler = ex => { if (onRejected != null) { onRejected(ex); } resultPromise.Reject(ex); }; ActionHandlers(resultPromise, resolveHandler, rejectHandler); return resultPromise; } /// <summary> /// Add a resolved callback and a rejected callback. /// </summary> public IPromise Then(Action onResolved, Action<Exception> onRejected) { var resultPromise = new Promise(); resultPromise.WithName(Name); Action resolveHandler = () => { if (onResolved != null) { onResolved(); } resultPromise.Resolve(); }; Action<Exception> rejectHandler = ex => { if (onRejected != null) { onRejected(ex); } resultPromise.Reject(ex); }; ActionHandlers(resultPromise, resolveHandler, rejectHandler); return resultPromise; } /// <summary> /// Helper function to invoke or register resolve/reject handlers. /// </summary> private void ActionHandlers(IRejectable resultPromise, Action resolveHandler, Action<Exception> rejectHandler) { if (CurState == PromiseState.Resolved) { InvokeResolveHandler(resolveHandler, resultPromise); } else if (CurState == PromiseState.Rejected) { InvokeRejectHandler(rejectHandler, resultPromise, rejectionException); } else { AddResolveHandler(resolveHandler, resultPromise); AddRejectHandler(rejectHandler, resultPromise); } } /// <summary> /// Chain an enumerable of promises, all of which must resolve. /// The resulting promise is resolved when all of the promises have resolved. /// It is rejected as soon as any of the promises have been rejected. /// </summary> public IPromise ThenAll(Func<IEnumerable<IPromise>> chain) { return Then(() => Promise.All(chain())); } /// <summary> /// Chain an enumerable of promises, all of which must resolve. /// Converts to a non-value promise. /// The resulting promise is resolved when all of the promises have resolved. /// It is rejected as soon as any of the promises have been rejected. /// </summary> public IPromise<IEnumerable<ConvertedT>> ThenAll<ConvertedT>(Func<IEnumerable<IPromise<ConvertedT>>> chain) { return Then(() => Promise<ConvertedT>.All(chain())); } /// <summary> /// Returns a promise that resolves when all of the promises in the enumerable argument have resolved. /// Returns a promise of a collection of the resolved results. /// </summary> public static IPromise All(params IPromise[] promises) { return All((IEnumerable<IPromise>)promises); // Cast is required to force use of the other All function. } /// <summary> /// Returns a promise that resolves when all of the promises in the enumerable argument have resolved. /// Returns a promise of a collection of the resolved results. /// </summary> public static IPromise All(IEnumerable<IPromise> promises) { var promisesArray = promises.ToArray(); if (promisesArray.Length == 0) { return Promise.Resolved(); } var remainingCount = promisesArray.Length; var resultPromise = new Promise(); resultPromise.WithName("All"); promisesArray.Each((promise, index) => { promise .Catch(ex => { if (resultPromise.CurState == PromiseState.Pending) { // If a promise errorred and the result promise is still pending, reject it. resultPromise.Reject(ex); } }) .Then(() => { --remainingCount; if (remainingCount <= 0) { // This will never happen if any of the promises errorred. resultPromise.Resolve(); } }) .Done(); }); return resultPromise; } /// <summary> /// Chain a sequence of operations using promises. /// Reutrn a collection of functions each of which starts an async operation and yields a promise. /// Each function will be called and each promise resolved in turn. /// The resulting promise is resolved after each promise is resolved in sequence. /// </summary> public IPromise ThenSequence(Func<IEnumerable<Func<IPromise>>> chain) { return Then(() => Sequence(chain())); } /// <summary> /// Chain a number of operations using promises. /// Takes a number of functions each of which starts an async operation and yields a promise. /// </summary> public static IPromise Sequence(params Func<IPromise>[] fns) { return Sequence((IEnumerable<Func<IPromise>>)fns); } /// <summary> /// Chain a sequence of operations using promises. /// Takes a collection of functions each of which starts an async operation and yields a promise. /// </summary> public static IPromise Sequence(IEnumerable<Func<IPromise>> fns) { return fns.Aggregate( Promise.Resolved(), (prevPromise, fn) => { return prevPromise.Then(() => fn()); } ); } /// <summary> /// Takes a function that yields an enumerable of promises. /// Returns a promise that resolves when the first of the promises has resolved. /// </summary> public IPromise ThenRace(Func<IEnumerable<IPromise>> chain) { return Then(() => Promise.Race(chain())); } /// <summary> /// Takes a function that yields an enumerable of promises. /// Converts to a value promise. /// Returns a promise that resolves when the first of the promises has resolved. /// </summary> public IPromise<ConvertedT> ThenRace<ConvertedT>(Func<IEnumerable<IPromise<ConvertedT>>> chain) { return Then(() => Promise<ConvertedT>.Race(chain())); } /// <summary> /// Returns a promise that resolves when the first of the promises in the enumerable argument have resolved. /// Returns the value from the first promise that has resolved. /// </summary> public static IPromise Race(params IPromise[] promises) { return Race((IEnumerable<IPromise>)promises); // Cast is required to force use of the other function. } /// <summary> /// Returns a promise that resolves when the first of the promises in the enumerable argument have resolved. /// Returns the value from the first promise that has resolved. /// </summary> public static IPromise Race(IEnumerable<IPromise> promises) { var promisesArray = promises.ToArray(); if (promisesArray.Length == 0) { throw new ApplicationException("At least 1 input promise must be provided for Race"); } var resultPromise = new Promise(); resultPromise.WithName("Race"); promisesArray.Each((promise, index) => { promise .Catch(ex => { if (resultPromise.CurState == PromiseState.Pending) { // If a promise errorred and the result promise is still pending, reject it. resultPromise.Reject(ex); } }) .Then(() => { if (resultPromise.CurState == PromiseState.Pending) { resultPromise.Resolve(); } }) .Done(); }); return resultPromise; } public override string ToString() { return base.ToString() + ", State: " + CurState.ToString() + ", Res: " + (resolveHandlers != null ? resolveHandlers.Count : 0) + ", Rej: " + (rejectHandlers != null ? rejectHandlers.Count : 0); } /// <summary> /// Convert a simple value directly into a resolved promise. /// </summary> public static IPromise Resolved() { var promise = new Promise(); promise.Resolve(); return promise; } /// <summary> /// Convert an exception directly into a rejected promise. /// </summary> public static IPromise Rejected(Exception ex) { var promise = new Promise(); promise.Reject(ex); return promise; } /// <summary> /// Raises the UnhandledException event. /// </summary> internal static void PropagateUnhandledException(object sender, Exception ex) { if (UnhandledException != null) { UnhandledException(sender, new ExceptionEventArgs(ex)); } } } }
/* ==================================================================== 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 NPOI.OpenXml4Net.OPC; using System; using NPOI.SS.UserModel; using NPOI.XSSF.Model; using System.IO; using System.Text; namespace NPOI.XSSF.Extractor { /** * Implementation of a text extractor from OOXML Excel * files that uses SAX event based parsing. */ public class XSSFEventBasedExcelExtractor : POIXMLTextExtractor { private OPCPackage container; private POIXMLProperties properties; private Locale locale; private bool includeSheetNames = true; private bool formulasNotResults = false; public XSSFEventBasedExcelExtractor(String path) : this(OPCPackage.Open(path)) { } public XSSFEventBasedExcelExtractor(OPCPackage Container) : base(null) { this.container = Container; properties = new POIXMLProperties(Container); } /** * Should sheet names be included? Default is true */ public void SetIncludeSheetNames(bool includeSheetNames) { this.includeSheetNames = includeSheetNames; } /** * Should we return the formula itself, and not * the result it produces? Default is false */ public void SetFormulasNotResults(bool formulasNotResults) { this.formulasNotResults = formulasNotResults; } public void SetLocale(Locale locale) { this.locale = locale; } /** * Returns the opened OPCPackage Container. */ public OPCPackage GetPackage() { return container; } /** * Returns the core document properties */ public NPOI.POIXMLProperties.CoreProperties GetCoreProperties() { return properties.GetCoreProperties(); } /** * Returns the extended document properties */ public NPOI.POIXMLProperties.ExtendedProperties GetExtendedProperties() { return properties.GetExtendedProperties(); } /** * Returns the custom document properties */ public NPOI.POIXMLProperties.CustomProperties GetCustomProperties() { return properties.GetCustomProperties(); } /** * Processes the given sheet */ public void ProcessSheet( SheetContentsHandler sheetContentsExtractor, StylesTable styles, ReadOnlySharedStringsTable strings, InputStream sheetInputStream) { DataFormatter formatter; if (locale == null) { formatter = new DataFormatter(); } else { formatter = new DataFormatter(locale); } InputSource sheetSource = new InputSource(sheetInputStream); SAXParserFactory saxFactory = SAXParserFactory.newInstance(); try { SAXParser saxParser = saxFactory.newSAXParser(); XMLReader sheetParser = saxParser.GetXMLReader(); ContentHandler handler = new XSSFSheetXMLHandler( styles, strings, sheetContentsExtractor, formatter, formulasNotResults); sheetParser.SetContentHandler(handler); sheetParser.Parse(sheetSource); } catch (ParserConfigurationException e) { throw new RuntimeException("SAX Parser appears to be broken - " + e.GetMessage()); } } /** * Processes the file and returns the text */ public String GetText() { try { ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(container); XSSFReader xssfReader = new XSSFReader(container); StylesTable styles = xssfReader.GetStylesTable(); XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator)xssfReader.GetSheetsData(); StringBuilder text = new StringBuilder(); SheetTextExtractor sheetExtractor = new SheetTextExtractor(text); while (iter.HasNext()) { InputStream stream = iter.next(); if (includeSheetNames) { text.Append(iter.GetSheetName()); text.Append('\n'); } ProcessSheet(sheetExtractor, styles, strings, stream); stream.Close(); } return text.ToString(); } catch (IOException e) { System.err.println(e); return null; } catch (OpenXML4NetException o4je) { System.err.println(o4je); return null; } } public void Close() { if (container != null) { container.Close(); container = null; } base.close(); } protected class SheetTextExtractor : SheetContentsHandler { private StringBuilder output; private bool firstCellOfRow = true; protected SheetTextExtractor(StringBuilder output) { this.output = output; } public void startRow(int rowNum) { firstCellOfRow = true; } public void endRow() { output.Append('\n'); } public void cell(String cellRef, String formattedValue) { if (firstCellOfRow) { firstCellOfRow = false; } else { output.Append('\t'); } output.Append(formattedValue); } public void headerFooter(String text, bool IsHeader, String tagName) { // We don't include headers in the output yet, so ignore } } } }
using System; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using System.Drawing; using MonoTouch.CoreAnimation; using System.Linq; using System.Threading.Tasks; using MonoTouch.ObjCRuntime; using MonoTouch.Foundation; namespace XamarinStore { public class BasketViewController : UITableViewController { Order order; EmptyBasketView EmptyCartImageView; BottomButtonView BottomView; UILabel totalAmount; const string LONG_PRESS_SELECTOR = "HandleLongPress"; public event EventHandler Checkout; public BasketViewController (Order order) { this.Title = "Your Basket"; //This hides the back button text when you leave this View Controller this.NavigationItem.BackBarButtonItem = new UIBarButtonItem ("", UIBarButtonItemStyle.Plain, handler: null); TableView.Source = new TableViewSource (this.order = order) { RowDeleted = CheckEmpty, }; TableView.SeparatorStyle = UITableViewCellSeparatorStyle.None; TableView.RowHeight = 75; TableView.TableFooterView = new UIView (new RectangleF (0, 0, 0, BottomButtonView.Height)); var longPress = new UILongPressGestureRecognizer (this, new Selector (LONG_PRESS_SELECTOR)); longPress.MinimumPressDuration = 1.0; //seconds TableView.AddGestureRecognizer (longPress); this.View.AddSubview (BottomView = new BottomButtonView () { ButtonText = "Checkout", ButtonTapped = () => { if (Checkout != null) Checkout (this, EventArgs.Empty); } }); CheckEmpty (false); totalAmount = new UILabel () { Text = "$1,000", TextColor = UIColor.White, TextAlignment = UITextAlignment.Center, Font = UIFont.BoldSystemFontOfSize (17), }; totalAmount.SizeToFit (); this.NavigationItem.RightBarButtonItem = new UIBarButtonItem (totalAmount); UpdateTotals (); } [Export (LONG_PRESS_SELECTOR)] void HandleLongPress (UILongPressGestureRecognizer gestureRecognizer) { var p = gestureRecognizer.LocationInView (TableView); NSIndexPath indexPath = TableView.IndexPathForRowAtPoint (p); if (indexPath != null && gestureRecognizer.State == UIGestureRecognizerState.Began) { TableView.Editing = !TableView.Editing; } } public void UpdateTotals () { if (order.Products.Count == 0) { totalAmount.Text = ""; return; } var total = order.Products.Sum (x => x.Price); totalAmount.Text = total.ToString ("C"); } public override void ViewDidLayoutSubviews () { base.ViewDidLayoutSubviews (); var bound = View.Bounds; bound.Y = bound.Bottom - BottomButtonView.Height; bound.Height = BottomButtonView.Height; BottomView.Frame = bound; if (EmptyCartImageView == null) return; EmptyCartImageView.Frame = View.Bounds; } void CheckEmpty () { UpdateTotals (); CheckEmpty (true); } protected void CheckEmpty (bool animate) { if (order.Products.Count == 0) { this.View.AddSubview (EmptyCartImageView = new EmptyBasketView () { Alpha = animate ? 0f : 1f, }); this.View.BringSubviewToFront (EmptyCartImageView); if (animate) UIView.Animate (.25, () => EmptyCartImageView.Alpha = 1f); return; } if (EmptyCartImageView == null) return; EmptyCartImageView.RemoveFromSuperview (); EmptyCartImageView = null; } class TableViewSource : UITableViewSource { public Action RowDeleted { get; set; } Order order; public TableViewSource (Order order) { this.order = order; } #region implemented abstract members of UITableViewSource public override int RowsInSection (UITableView tableview, int section) { return order.Products.Count; } public override UITableViewCell GetCell (UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath) { var cell = tableView.DequeueReusableCell (ProductCell.Key) as ProductCell ?? new ProductCell (); //No need to wait to return the cell It will update when the data is ready #pragma warning disable 4014 cell.Update (order.Products [indexPath.Row]); #pragma warning restore 4014 return cell; } #endregion public override UITableViewCellEditingStyle EditingStyleForRow (UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath) { return UITableViewCellEditingStyle.Delete; } public override void CommitEditingStyle (UITableView tableView, UITableViewCellEditingStyle editingStyle, MonoTouch.Foundation.NSIndexPath indexPath) { if (editingStyle == UITableViewCellEditingStyle.Delete) { order.Remove (order.Products [indexPath.Row]); tableView.DeleteRows (new MonoTouch.Foundation.NSIndexPath[]{ indexPath }, UITableViewRowAnimation.Fade); if (RowDeleted != null) RowDeleted (); } } class ProductCell : UITableViewCell { static Lazy<UIImage> Image = new Lazy<UIImage> (() => UIImage.FromBundle ("shirt_image")); public const string Key = "productCell"; static SizeF ImageSize = new SizeF (55, 55); UILabel NameLabel; UILabel SizeLabel; UILabel ColorLabel; UILabel PriceLabel; UIView LineView; public ProductCell () : base (UITableViewCellStyle.Default, Key) { SelectionStyle = UITableViewCellSelectionStyle.None; ContentView.BackgroundColor = UIColor.Clear; ImageView.Image = Image.Value; ImageView.ContentMode = UIViewContentMode.ScaleAspectFill; ImageView.Frame = new RectangleF (PointF.Empty, ImageSize); ImageView.BackgroundColor = UIColor.Clear; ImageView.Layer.CornerRadius = 5f; ImageView.Layer.MasksToBounds = true; NameLabel = new UILabel () { Text = "Name", Font = UIFont.BoldSystemFontOfSize (17f), BackgroundColor = UIColor.Clear, TextColor = UIColor.Black, }; NameLabel.SizeToFit (); ContentView.AddSubview (NameLabel); SizeLabel = new UILabel () { Text = "Size", Font = UIFont.BoldSystemFontOfSize (12f), BackgroundColor = UIColor.Clear, TextColor = UIColor.LightGray, }; SizeLabel.SizeToFit (); ContentView.Add (SizeLabel); ColorLabel = new UILabel () { Text = "Color", Font = UIFont.BoldSystemFontOfSize (12f), BackgroundColor = UIColor.Clear, TextColor = UIColor.LightGray, }; ColorLabel.SizeToFit (); ContentView.AddSubview (ColorLabel); PriceLabel = new UILabel () { Text = "Price", Font = UIFont.BoldSystemFontOfSize (15f), BackgroundColor = UIColor.Clear, TextAlignment = UITextAlignment.Right, TextColor = Color.Blue, }; PriceLabel.SizeToFit (); AccessoryView = new UIView (new RectangleF (0, 0, PriceLabel.Frame.Width + 10, 54)) { BackgroundColor = UIColor.Clear, }; AccessoryView.AddSubview (PriceLabel); ContentView.AddSubview (LineView = new UIView () { BackgroundColor = UIColor.LightGray, }); } const float leftPadding = 15f; const float topPadding = 5f; public override void LayoutSubviews () { base.LayoutSubviews (); var bounds = ContentView.Bounds; var midY = bounds.GetMidY (); var center = new PointF (ImageSize.Width / 2 + leftPadding, midY); ImageView.Frame = new RectangleF (PointF.Empty, ImageSize); ImageView.Center = center; var x = ImageView.Frame.Right + leftPadding; var y = ImageView.Frame.Top; var labelWidth = bounds.Width - (x + (leftPadding * 2)); NameLabel.Frame = new RectangleF (x, y, labelWidth, NameLabel.Frame.Height); y = NameLabel.Frame.Bottom; SizeLabel.Frame = new RectangleF (x, y, labelWidth, SizeLabel.Frame.Height); y = SizeLabel.Frame.Bottom; ColorLabel.Frame = new RectangleF (x, y, labelWidth, ColorLabel.Frame.Height); y = ColorLabel.Frame.Bottom + topPadding; LineView.Frame = new RectangleF (0, Bounds.Height - .5f, Bounds.Width, .5f); } public async Task Update (Product product) { NameLabel.Text = product.Name; SizeLabel.Text = product.Size.Description; ColorLabel.Text = product.Color.Name; PriceLabel.Text = product.PriceDescription; var imageTask = FileCache.Download (product.ImageForSize (320)); if (!imageTask.IsCompleted) //Put default before doing the web request; ImageView.Image = Image.Value; var image = await imageTask; ImageView.Image = UIImage.FromFile (image); } } } } }
// 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 Xunit; using Xunit.Abstractions; using System.IO; using System.Xml.Schema; namespace System.Xml.Tests { //[TestCase(Name = "TC_SchemaSet_ProhibitDTD", Desc = "")] public class TC_SchemaSet_ProhibitDTD : TC_SchemaSetBase { private ITestOutputHelper _output; public TC_SchemaSet_ProhibitDTD(ITestOutputHelper output) { _output = output; } public bool bWarningCallback; public bool bErrorCallback; public int errorCount; public int warningCount; private void Initialize() { bWarningCallback = bErrorCallback = false; errorCount = warningCount = 0; } //hook up validaton callback private void ValidationCallback(object sender, ValidationEventArgs args) { switch (args.Severity) { case XmlSeverityType.Warning: _output.WriteLine("WARNING: "); bWarningCallback = true; warningCount++; break; case XmlSeverityType.Error: _output.WriteLine("ERROR: "); bErrorCallback = true; errorCount++; break; } _output.WriteLine("Exception Message:" + args.Exception.Message + "\n"); if (args.Exception.InnerException != null) { _output.WriteLine("InnerException Message:" + args.Exception.InnerException.Message + "\n"); } else { _output.WriteLine("Inner Exception is NULL\n"); } } private XmlReaderSettings GetSettings(bool prohibitDtd) { return new XmlReaderSettings { #pragma warning disable 0618 ProhibitDtd = prohibitDtd, #pragma warning restore 0618 XmlResolver = new XmlUrlResolver() }; } private XmlReader CreateReader(string xmlFile, bool prohibitDtd) { return XmlReader.Create(xmlFile, GetSettings(prohibitDtd)); } private XmlReader CreateReader(string xmlFile) { return XmlReader.Create(xmlFile); } private XmlReader CreateReader(XmlReader reader, bool prohibitDtd) { return XmlReader.Create(reader, GetSettings(prohibitDtd)); } private XmlReader CreateReader(string xmlFile, XmlSchemaSet ss, bool prohibitDTD) { var settings = GetSettings(prohibitDTD); settings.Schemas = new XmlSchemaSet(); settings.Schemas.XmlResolver = new XmlUrlResolver(); settings.Schemas.ValidationEventHandler += ValidationCallback; settings.Schemas.Add(ss); settings.ValidationType = ValidationType.Schema; settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings | XmlSchemaValidationFlags.ProcessSchemaLocation | XmlSchemaValidationFlags.ProcessIdentityConstraints | XmlSchemaValidationFlags.ProcessInlineSchema; settings.ValidationEventHandler += ValidationCallback; return XmlReader.Create(xmlFile, settings); } private XmlReader CreateReader(XmlReader reader, XmlSchemaSet ss, bool prohibitDTD) { var settings = GetSettings(prohibitDTD); settings.Schemas = new XmlSchemaSet(); settings.Schemas.XmlResolver = new XmlUrlResolver(); settings.Schemas.ValidationEventHandler += ValidationCallback; settings.Schemas.Add(ss); settings.ValidationType = ValidationType.Schema; settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings | XmlSchemaValidationFlags.ProcessSchemaLocation | XmlSchemaValidationFlags.ProcessIdentityConstraints | XmlSchemaValidationFlags.ProcessInlineSchema; settings.ValidationEventHandler += ValidationCallback; return XmlReader.Create(reader, settings); } //TEST DEFAULT VALUE FOR SCHEMA COMPILATION //[Variation(Desc = "v1- Test Default value of ProhibitDTD for Add(URL) of schema with DTD", Priority = 1)] [InlineData()] [Theory] public void v1() { Initialize(); XmlSchemaSet xss = new XmlSchemaSet(); xss.ValidationEventHandler += ValidationCallback; try { xss.Add(null, Path.Combine(TestData._Root, "bug356711_a.xsd")); } catch (XmlException e) { CError.Compare(e.Message.Contains("DTD"), true, "Some other error thrown"); return; } Assert.True(false); } //[Variation(Desc = "v2- Test Default value of ProhibitDTD for Add(XmlReader) of schema with DTD", Priority = 1)] [InlineData()] [Theory] public void v2() { Initialize(); XmlSchemaSet xss = new XmlSchemaSet(); xss.ValidationEventHandler += ValidationCallback; XmlReader r = CreateReader(Path.Combine(TestData._Root, "bug356711_a.xsd")); try { xss.Add(null, r); } catch (XmlException e) { CError.Compare(e.Message.Contains("DTD"), true, "Some other error thrown"); return; } Assert.True(false); } //[Variation(Desc = "v3- Test Default value of ProhibitDTD for Add(URL) containing xs:import for schema with DTD", Priority = 1)] [InlineData()] [Theory] public void v3() { Initialize(); XmlSchemaSet xss = new XmlSchemaSet(); xss.XmlResolver = new XmlUrlResolver(); xss.ValidationEventHandler += ValidationCallback; try { xss.Add(null, Path.Combine(TestData._Root, "bug356711.xsd")); } catch (XmlException) { Assert.True(false); //expect a validation warning for unresolvable schema location } CError.Compare(warningCount, 1, "Warning Count mismatch"); return; } //[Variation(Desc = "v4- Test Default value of ProhibitDTD for Add(XmlReader) containing xs:import for scehma with DTD", Priority = 1)] [InlineData()] [Theory] public void v4() { Initialize(); XmlSchemaSet xss = new XmlSchemaSet(); xss.XmlResolver = new XmlUrlResolver(); xss.ValidationEventHandler += ValidationCallback; XmlReader r = CreateReader(Path.Combine(TestData._Root, "bug356711.xsd")); try { xss.Add(null, r); } catch (XmlException) { Assert.True(false); //expect a validation warning for unresolvable schema location } CError.Compare(warningCount, 1, "Warning Count mismatch"); return; } [Theory] [ActiveIssue(39106)] //[Variation(Desc = "v5.2- Test Default value of ProhibitDTD for Add(TextReader) for schema with DTD", Priority = 1, Params = new object[] { "bug356711_a.xsd", 0 })] [InlineData("bug356711_a.xsd", 0)] //[Variation(Desc = "v5.1- Test Default value of ProhibitDTD for Add(TextReader) with an xs:import for schema with DTD", Priority = 1, Params = new object[] { "bug356711.xsd", 0 })] [InlineData("bug356711.xsd", 0)] public void v5(object param0, object param1) { Initialize(); XmlSchemaSet xss = new XmlSchemaSet(); xss.XmlResolver = new XmlUrlResolver(); xss.ValidationEventHandler += ValidationCallback; XmlSchema schema = XmlSchema.Read(new StreamReader(new FileStream(Path.Combine(TestData._Root, param0.ToString()), FileMode.Open, FileAccess.Read)), ValidationCallback); #pragma warning disable 0618 schema.Compile(ValidationCallback, new XmlUrlResolver()); #pragma warning restore 0618 try { xss.Add(schema); } catch (XmlException) { Assert.True(false); //expect a validation warning for unresolvable schema location } CError.Compare(warningCount, (int)param1, "Warning Count mismatch"); CError.Compare(errorCount, 0, "Error Count mismatch"); } [Theory] [ActiveIssue(39106)] //[Variation(Desc = "v6.2- Test Default value of ProhibitDTD for Add(XmlTextReader) for schema with DTD", Priority = 1, Params = new object[] { "bug356711_a.xsd" })] [InlineData("bug356711_a.xsd")] //[Variation(Desc = "v6.1- Test Default value of ProhibitDTD for Add(XmlTextReader) with an xs:import for schema with DTD", Priority = 1, Params = new object[] { "bug356711.xsd" })] [InlineData("bug356711.xsd")] public void v6(object param0) { Initialize(); XmlSchemaSet xss = new XmlSchemaSet(); xss.XmlResolver = new XmlUrlResolver(); xss.ValidationEventHandler += ValidationCallback; var reader = new XmlTextReader(Path.Combine(TestData._Root, param0.ToString())); reader.XmlResolver = new XmlUrlResolver(); XmlSchema schema = XmlSchema.Read(reader, ValidationCallback); #pragma warning disable 0618 schema.Compile(ValidationCallback); #pragma warning restore 0618 xss.Add(schema); // expect a validation warning for unresolvable schema location CError.Compare(warningCount, 0, "Warning Count mismatch"); CError.Compare(errorCount, 0, "Error Count mismatch"); } //[Variation(Desc = "v7- Test Default value of ProhibitDTD for Add(XmlReader) for schema with DTD", Priority = 1, Params = new object[] { "bug356711_a.xsd" })] [InlineData("bug356711_a.xsd")] [Theory] public void v7(object param0) { Initialize(); try { XmlSchema schema = XmlSchema.Read(CreateReader(Path.Combine(TestData._Root, param0.ToString())), ValidationCallback); #pragma warning disable 0618 schema.Compile(ValidationCallback); #pragma warning restore 0618 } catch (XmlException e) { CError.Compare(e.Message.Contains("DTD"), true, "Some other error thrown"); return; } Assert.True(false); } //[Variation(Desc = "v8- Test Default value of ProhibitDTD for Add(XmlReader) with xs:import for schema with DTD", Priority = 1, Params = new object[] { "bug356711.xsd" })] [InlineData("bug356711.xsd")] [Theory] public void v8(object param0) { Initialize(); try { XmlSchema schema = XmlSchema.Read(CreateReader(Path.Combine(TestData._Root, param0.ToString())), ValidationCallback); #pragma warning disable 0618 schema.Compile(ValidationCallback); #pragma warning restore 0618 } catch (XmlException) { Assert.True(false); //expect a validation warning for unresolvable schema location } CError.Compare(warningCount, 0, "Warning Count mismatch"); return; } //TEST CUSTOM VALUE FOR SCHEMA COMPILATION //[Variation(Desc = "v10.1- Test Custom value of ProhibitDTD for SchemaSet.Add(XmlReader) with xs:import for schema with DTD", Priority = 1, Params = new object[] { "bug356711.xsd" })] [InlineData("bug356711.xsd")] //[Variation(Desc = "v10.2- Test Custom value of ProhibitDTD for SchemaSet.Add(XmlReader) for schema with DTD", Priority = 1, Params = new object[] { "bug356711_a.xsd" })] [InlineData("bug356711_a.xsd")] [Theory] public void v10(object param0) { Initialize(); XmlSchemaSet xss = new XmlSchemaSet(); xss.XmlResolver = new XmlUrlResolver(); xss.ValidationEventHandler += ValidationCallback; XmlReader r = CreateReader(Path.Combine(TestData._Root, param0.ToString()), false); try { xss.Add(null, r); } catch (XmlException) { Assert.True(false); } CError.Compare(warningCount, 0, "Warning Count mismatch"); CError.Compare(errorCount, 0, "Warning Count mismatch"); return; } //[Variation(Desc = "v11.2- Test Custom value of ProhibitDTD for XmlSchema.Add(XmlReader) for schema with DTD", Priority = 1, Params = new object[] { "bug356711_a.xsd" })] [InlineData("bug356711_a.xsd")] //[Variation(Desc = "v11.1- Test Custom value of ProhibitDTD for XmlSchema.Add(XmlReader) with an xs:import for schema with DTD", Priority = 1, Params = new object[] { "bug356711.xsd" })] [InlineData("bug356711.xsd")] [Theory] public void v11(object param0) { Initialize(); try { XmlSchema schema = XmlSchema.Read(CreateReader(Path.Combine(TestData._Root, param0.ToString()), false), ValidationCallback); #pragma warning disable 0618 schema.Compile(ValidationCallback); #pragma warning restore 0618 } catch (XmlException) { Assert.True(false); } CError.Compare(warningCount, 0, "Warning Count mismatch"); CError.Compare(errorCount, 0, "Warning Count mismatch"); return; } //[Variation(Desc = "v12- Test with underlying reader with ProhibitDTD=true, and new Setting with True for schema with DTD", Priority = 1, Params = new object[] { "bug356711_a.xsd" })] [InlineData("bug356711_a.xsd")] [Theory] public void v12(object param0) { Initialize(); XmlSchemaSet xss = new XmlSchemaSet(); xss.ValidationEventHandler += ValidationCallback; XmlReader r = CreateReader(Path.Combine(TestData._Root, param0.ToString()), false); XmlReader r2 = CreateReader(r, true); try { xss.Add(null, r2); } catch (XmlException e) { CError.Compare(e.Message.Contains("DTD"), true, "Some other error thrown"); return; } Assert.True(false); } //[Variation(Desc = "v13- Test with underlying reader with ProhibitDTD=true, and new Setting with True for a schema with xs:import for schema with DTD", Priority = 1, Params = new object[] { "bug356711.xsd" })] [InlineData("bug356711.xsd")] [Theory] public void v13(object param0) { Initialize(); XmlSchemaSet xss = new XmlSchemaSet(); xss.XmlResolver = new XmlUrlResolver(); xss.ValidationEventHandler += ValidationCallback; XmlReader r = CreateReader(Path.Combine(TestData._Root, param0.ToString()), false); XmlReader r2 = CreateReader(r, true); try { xss.Add(null, r2); } catch (XmlException) { Assert.True(false); //expect a validation warning for unresolvable schema location } _output.WriteLine("Count: " + xss.Count); CError.Compare(warningCount, 1, "Warning Count mismatch"); return; } //[Variation(Desc = "v14 - SchemaSet.Add(XmlReader) with pDTD False ,then a SchemaSet.Add(URL) for schema with DTD", Priority = 1)] [InlineData()] [Theory] public void v14() { Initialize(); XmlSchemaSet xss = new XmlSchemaSet(); xss.XmlResolver = new XmlUrlResolver(); xss.ValidationEventHandler += ValidationCallback; XmlReader r = CreateReader(Path.Combine(TestData._Root, "bug356711.xsd"), false); try { xss.Add(null, r); CError.Compare(xss.Count, 2, "SchemaSet count mismatch!"); xss.Add(null, Path.Combine(TestData._Root, "bug356711_b.xsd")); } catch (XmlException e) { CError.Compare(e.Message.Contains("DTD"), true, "Some other error thrown"); return; } Assert.True(false); } //[Variation(Desc = "v15 - SchemaSet.Add(XmlReader) with pDTD True ,then a SchemaSet.Add(XmlReader) with pDTD False with DTD", Priority = 1)] [InlineData()] [Theory] public void v15() { Initialize(); XmlSchemaSet xss = new XmlSchemaSet(); xss.ValidationEventHandler += ValidationCallback; XmlReader r1 = CreateReader(Path.Combine(TestData._Root, "bug356711_a.xsd")); XmlReader r2 = CreateReader(Path.Combine(TestData._Root, "bug356711_b.xsd"), false); try { xss.Add(null, r1); } catch (XmlException e) { CError.Compare(e.Message.Contains("DTD"), true, "Some other error thrown"); CError.Compare(xss.Count, 0, "SchemaSet count mismatch!"); } try { xss.Add(null, r2); } catch (Exception) { Assert.True(false); } CError.Compare(xss.Count, 1, "SchemaSet count mismatch!"); return; } //TEST DEFAULT VALUE FOR INSTANCE VALIDATION //[Variation(Desc = "v20.1- Test Default value of ProhibitDTD for XML containing noNamespaceSchemaLocation for schema which contains xs:import for schema with DTD", Priority = 1, Params = new object[] { "bug356711_1.xml" })] [InlineData("bug356711_1.xml")] //[Variation(Desc = "v20.2- Test Default value of ProhibitDTD for XML containing schemaLocation for schema with DTD", Priority = 1, Params = new object[] { "bug356711_2.xml" })] [InlineData("bug356711_2.xml")] //[Variation(Desc = "v20.3- Test Default value of ProhibitDTD for XML containing Inline schema containing xs:import of a schema with DTD", Priority = 1, Params = new object[] { "bug356711_3.xml" })] [InlineData("bug356711_3.xml")] //[Variation(Desc = "v20.4- Test Default value of ProhibitDTD for XML containing Inline schema containing xs:import of a schema which has a xs:import of schema with DTD", Priority = 1, Params = new object[] { "bug356711_4.xml" })] [InlineData("bug356711_4.xml")] [Theory] public void v20(object param0) { Initialize(); XmlSchemaSet xss = new XmlSchemaSet(); xss.XmlResolver = new XmlUrlResolver(); xss.ValidationEventHandler += ValidationCallback; xss.Add(null, Path.Combine(TestData._Root, "bug356711_root.xsd")); try { XmlReader reader = CreateReader(Path.Combine(TestData._Root, param0.ToString()), xss, true); while (reader.Read()) ; } catch (XmlException) { Assert.True(false); } CError.Compare(warningCount, 2, "ProhibitDTD did not work with schemaLocation"); return; } //[Variation(Desc = "v21- Underlying XmlReader with ProhibitDTD=False and Create new Reader with ProhibitDTD=True", Priority = 1)] [InlineData()] [Theory] public void v21() { Initialize(); var xss = new XmlSchemaSet(); xss.XmlResolver = new XmlUrlResolver(); xss.ValidationEventHandler += ValidationCallback; xss.Add(null, Path.Combine(TestData._Root, "bug356711_root.xsd")); try { using (var r1 = CreateReader(Path.Combine(TestData._Root, "bug356711_1.xml"), false)) using (var r2 = CreateReader(r1, xss, true)) { while (r2.Read()) { } } } catch (XmlException) { Assert.True(false); } CError.Compare(warningCount, 2, "ProhibitDTD did not work with schemaLocation"); return; } //TEST CUSTOM VALUE FOR INSTANCE VALIDATION //[Variation(Desc = "v22.1- Test Default value of ProhibitDTD for XML containing noNamespaceSchemaLocation for schema which contains xs:import for schema with DTD", Priority = 1, Params = new object[] { "bug356711_1.xml" })] [InlineData("bug356711_1.xml")] //[Variation(Desc = "v22.2- Test Default value of ProhibitDTD for XML containing schemaLocation for schema with DTD", Priority = 1, Params = new object[] { "bug356711_2.xml" })] [InlineData("bug356711_2.xml")] //[Variation(Desc = "v22.3- Test Default value of ProhibitDTD for XML containing Inline schema containing xs:import of a schema with DTD", Priority = 1, Params = new object[] { "bug356711_3.xml" })] [InlineData("bug356711_3.xml")] //[Variation(Desc = "v22.4- Test Default value of ProhibitDTD for XML containing Inline schema containing xs:import of a schema which has a xs:import of schema with DTD", Priority = 1, Params = new object[] { "bug356711_4.xml" })] [InlineData("bug356711_4.xml")] [Theory] public void v22(object param0) { Initialize(); XmlSchemaSet xss = new XmlSchemaSet(); xss.XmlResolver = new XmlUrlResolver(); xss.ValidationEventHandler += ValidationCallback; xss.Add(null, Path.Combine(TestData._Root, "bug356711_root.xsd")); try { XmlReader reader = CreateReader(Path.Combine(TestData._Root, param0.ToString()), xss, false); while (reader.Read()) ; } catch (XmlException) { Assert.True(false); } CError.Compare(errorCount, 0, "ProhibitDTD did not work with schemaLocation"); return; } //[Variation(Desc = "v23- Underlying XmlReader with ProhibitDTD=True and Create new Reader with ProhibitDTD=False", Priority = 1)] [InlineData()] [Theory] public void v23() { Initialize(); XmlSchemaSet xss = new XmlSchemaSet(); xss.ValidationEventHandler += ValidationCallback; xss.Add(null, Path.Combine(TestData._Root, "bug356711_root.xsd")); try { XmlReader r1 = CreateReader(Path.Combine(TestData._Root, "bug356711_1.xml"), true); XmlReader r2 = CreateReader(r1, xss, false); while (r2.Read()) ; } catch (XmlException) { Assert.True(false); } CError.Compare(errorCount, 0, "ProhibitDTD did not work with schemaLocation"); return; } } }
using UnityEngine; using System.Collections.Generic; #if UNITY_EDITOR using UnityEditor; [CanEditMultipleObjects] [CustomEditor(typeof(SgtAuroraMainTex))] public class SgtAuroraMainTex_Editor : SgtEditor<SgtAuroraMainTex> { protected override void OnInspector() { var updateTexture = false; var updateApply = false; BeginError(Any(t => t.Aurora == null)); DrawDefault("Aurora", ref updateApply); EndError(); BeginError(Any(t => t.Width < 1)); DrawDefault("Width", ref updateTexture); EndError(); BeginError(Any(t => t.Height < 1)); DrawDefault("Height", ref updateTexture); EndError(); DrawDefault("Format", ref updateTexture); Separator(); DrawDefault("NoiseStrength", ref updateTexture); BeginError(Any(t => t.NoisePoints <= 0)); DrawDefault("NoisePoints", ref updateTexture); EndError(); DrawDefault("NoiseSeed", ref updateTexture); Separator(); DrawDefault("TopEase", ref updateTexture); DrawDefault("TopPower", ref updateTexture); Separator(); DrawDefault("MiddlePoint", ref updateTexture); DrawDefault("MiddleColor", ref updateTexture); DrawDefault("MiddleEase", ref updateTexture); DrawDefault("MiddlePower", ref updateTexture); Separator(); DrawDefault("BottomEase", ref updateTexture); DrawDefault("BottomPower", ref updateTexture); if (updateTexture == true) DirtyEach(t => t.UpdateTextures()); if (updateApply == true) DirtyEach(t => t.UpdateApply ()); } } #endif [ExecuteInEditMode] [AddComponentMenu(SgtHelper.ComponentMenuPrefix + "Aurora MainTex")] public class SgtAuroraMainTex : MonoBehaviour { public SgtAurora Aurora; [Tooltip("The resolution of the noise samples")] public int Width = 256; [Tooltip("The resolution of the bottom/middle/top transition")] public int Height = 64; [Tooltip("The format of this texture")] public TextureFormat Format = TextureFormat.ARGB32; [Tooltip("The strength of the noise points")] [Range(0.0f, 1.0f)] public float NoiseStrength = 0.5f; [Tooltip("The amount of noise points")] public int NoisePoints = 10; [Tooltip("The random seed used when generating this texture")] [SgtSeed] public int NoiseSeed; [Tooltip("The transition style between the top and middle")] public SgtEase.Type TopEase = SgtEase.Type.Smoothstep; [Tooltip("The transition strength between the top and middle")] public float TopPower = 1.0f; [Tooltip("The point separating the top from bottom")] [Range(0.0f, 1.0f)] public float MiddlePoint = 0.25f; [Tooltip("The base color of the aurora starting from the bottom")] public Color MiddleColor = Color.green; [Tooltip("The transition style between the bottom and top of the aurora")] public SgtEase.Type MiddleEase = SgtEase.Type.Exponential; [Tooltip("The strength of the color transition between the bottom and top")] public float MiddlePower = 4.0f; [Tooltip("The transition style between the bottom and middle")] public SgtEase.Type BottomEase = SgtEase.Type.Exponential; [Tooltip("The transition strength between the bottom and middle")] public float BottomPower = 2.0f; [System.NonSerialized] private Texture2D generatedTexture; [SerializeField] [HideInInspector] private bool startCalled; private static List<float> noisePoints = new List<float>(); public Texture2D GeneratedTexture { get { return generatedTexture; } } #if UNITY_EDITOR [ContextMenu("Export Texture")] public void ExportTexture() { var importer = SgtHelper.ExportTextureDialog(generatedTexture, "Aurora MainTex"); if (importer != null) { importer.textureCompression = TextureImporterCompression.Uncompressed; importer.alphaSource = TextureImporterAlphaSource.FromInput; importer.wrapMode = TextureWrapMode.Repeat; importer.filterMode = FilterMode.Trilinear; importer.anisoLevel = 16; importer.alphaIsTransparency = true; importer.SaveAndReimport(); } } #endif [ContextMenu("Update Textures")] public void UpdateTextures() { if (Width > 0 && Height > 0 && NoisePoints > 0) { // Destroy if invalid if (generatedTexture != null) { if (generatedTexture.width != Width || generatedTexture.height != Height || generatedTexture.format != Format) { generatedTexture = SgtHelper.Destroy(generatedTexture); } } // Create? if (generatedTexture == null) { generatedTexture = SgtHelper.CreateTempTexture2D("Aurora MainTex (Generated)", Width, Height, Format); generatedTexture.wrapMode = TextureWrapMode.Repeat; UpdateApply(); } SgtHelper.BeginRandomSeed(NoiseSeed); { noisePoints.Clear(); for (var i = 0; i < NoisePoints; i++) { noisePoints.Add(1.0f - Random.Range(0.0f, NoiseStrength)); } } SgtHelper.EndRandomSeed(); var stepX = 1.0f / (Width - 1); var stepY = 1.0f / (Height - 1); for (var y = 0; y < Height; y++) { var v = y * stepY; for (var x = 0; x < Width; x++) { var u = x * stepX; WriteTexture(u, v, x, y); } } generatedTexture.Apply(); } } private void WriteTexture(float u, float v, int x, int y) { var noise = u * NoisePoints; var noiseIndex = (int)noise; var noiseFrac = noise % 1.0f; var noiseA = noisePoints[(noiseIndex + 0) % NoisePoints]; var noiseB = noisePoints[(noiseIndex + 1) % NoisePoints]; var noiseC = noisePoints[(noiseIndex + 2) % NoisePoints]; var noiseD = noisePoints[(noiseIndex + 3) % NoisePoints]; var color = MiddleColor; if (v < MiddlePoint) { color.a = SgtEase.Evaluate(BottomEase, SgtHelper.Pow(Mathf.InverseLerp(0.0f, MiddlePoint, v), BottomPower)); } else { color.a = SgtEase.Evaluate(TopEase, SgtHelper.Pow(Mathf.InverseLerp(1.0f, MiddlePoint, v), TopPower)); } var middle = SgtEase.Evaluate(MiddleEase, SgtHelper.Pow(1.0f - v, MiddlePower)); color.a *= SgtHelper.HermiteInterpolate(noiseA, noiseB, noiseC, noiseD, noiseFrac); color.r *= middle * color.a; color.g *= middle * color.a; color.b *= middle * color.a; color.a *= 1.0f - middle; generatedTexture.SetPixel(x, y, color); } [ContextMenu("Update Apply")] public void UpdateApply() { if (Aurora != null) { Aurora.MainTex = generatedTexture; Aurora.UpdateMainTex(); } } protected virtual void OnEnable() { if (startCalled == true) { CheckUpdateCalls(); } } protected virtual void Start() { if (startCalled == false) { startCalled = true; if (Aurora == null) { Aurora = GetComponent<SgtAurora>(); } CheckUpdateCalls(); } } protected virtual void OnDestroy() { SgtHelper.Destroy(generatedTexture); } private void CheckUpdateCalls() { if (generatedTexture == null) { UpdateTextures(); } UpdateApply(); } }
// Copyright 2014 Google Inc. 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. using UnityEngine; using System.Collections; /// <summary> /// Simple state machine for handling states, state transitions and input /// </summary> public class SceneManager : MonoBehaviour { static SceneManager instance; public static SceneManager Instance{ get{return instance;} } [SerializeField] public DemoSceneState splashScene; [SerializeField] public DemoSceneState menuScene; [SerializeField] public DemoSceneState targetScene; [SerializeField] public DemoSceneState minecartScene; [SerializeField] public DemoSceneState trackingScene; [SerializeField] public DemoSceneState relativityScene; [SerializeField] public DemoSceneState visionScene; [SerializeField] public DemoSceneState redwoodScene; [SerializeField] PlayerMover player; //[SerializeField] CardboardHead cardboardHead; private DemoSceneState currentState; private DemoSceneState nextState; private bool pendingTransition = false; float transitionTime = 0.75f; /// <summary> /// Are we transitioning to another state? /// </summary> public bool PendingTransition{ get{ return pendingTransition; } } /// <summary> /// What is the current 'forward' direction, based on the current state /// </summary> public float OrientationYaw{ get{ if(currentState != null){ return currentState.OrientationYaw; } return 0; } } int transitionIdx = 0; float transitionTimer = 0; /// <summary> /// Transition to another state. Re-entry IS permitted to allow for resetting state. Optional parameter IDX allows for some flags to be passed to the state from the UI (for example entering a specific section of a state) /// </summary> public void StateTransition(DemoSceneState targetState, int idx = 0){ StateTransition(targetState, Color.white, idx); } /// <summary> /// Transition to another state. Re-entry IS permitted to allow for resetting state. Takes a transition color to control the fade color. Optional parameter IDX allows for some flags to be passed to the state from the UI (for example entering a specific section of a state) /// </summary> public void StateTransition(DemoSceneState targetState,Color c, int idx = 0){ ///Make sure we aren't mid-transition - primarily because of graphical glitches if(!pendingTransition ){ ///First we begein exiting the current state. currentState.BeginExitState(this); ///Update the target indices transitionIdx = idx; nextState = targetState; ///we are transitioning, so yeah, flag that, too pendingTransition = true; ///start our fade to (color c) Blackout.Instance.SetColor(c); Blackout.Instance.TargetBlackoutValue = 1; ///start a timer to end the transition. This used to wait on blackout, but that actually caused a seriously scary bug when there was a feature request to fade to black at other times. You were able to start a transition, and get stuck - so instead we maintain our own separate timer. ///if the blackout speed changes later, this time will need to be adjusted. Ideally, it should read from a public blackout time, or better yet - blackout could accept a transition speed variable - but that still can be risky for multiple entry on the blackout side transitionTimer = transitionTime; } } void Awake(){ instance = this; currentState = splashScene; currentState.EnterState(this); Blackout.Instance.TargetBlackoutValue = 0; } ////activate blackout between scenes ///activate, deactivate, reset messages ///use onEnable, onDisable? //// need to know when we are ready to transition, maybe call a start cleanup, as fades begin void Update(){ if(pendingTransition){ transitionTimer -= Time.deltaTime; ///To smoothly transition audio, we fade the listener down while transitioning AudioListener.volume = Mathf.Clamp01(transitionTimer / transitionTime); /// We're ready to actually transition - the screen should be 100% opaque (white, black, or some other color) if(transitionTimer <= 0){ /// WARNING - this was the previous way of handling this - but waiting on UI is bad practice, and it stayed in the code too long. I leave this here as a reminder to whoever looks at this - please, don't wait on UI transitions that can be controlled from multiple sources //if(Blackout.Instance.BlackoutValue == 1){ pendingTransition = false; /// Exit the current state currentState.ExitState(this); currentState = nextState; /// since the screen is opaque, we can rotate the entire scene so that forward is the direction the user is currently facing /// certain scenes may have orientation offsets based on the transition index (in the hike, certain nodes have you spawn at different angles) float orientationOffset = currentState.GetOrientationOffset(transitionIdx); currentState.OrientateScene(orientationOffset + VRInput.Instance.Yaw);//+ VRInput.Instance.Yaw /// we're good to load up the next scene, at the correct angle currentState.EnterState(this, transitionIdx); /// if we have a spawn point, move the player there if(currentState.SpawnPoint != null){ player.SetTarget(currentState.SpawnPoint); } /// start fading the scene back in currentState.ClearBlackout(); } } else{ ///To smoothly transition audio, we fade the listener back up if(AudioListener.volume <1){ AudioListener.volume = Mathf.Clamp01(AudioListener.volume + 2*Time.deltaTime); } //#if UNITY_EDITOR //StateTransitionDebug(); //#endif } if(currentState != null){ currentState.DoUpdate(this); } if(Cardboard.SDK.BackButtonPressed){ Application.Quit (); } } ////Perform UI stuff last, since cardboard updates in late update - we need to script execution order the priority of this after everything else void LateUpdate(){ /// record the time we've been staring at an element, gazeIn, gazeOut, gazeDuration, onClick (begin / release? plz?) ///modals? Yes / No up, side to side ///hot 'regions'? up / down? screen sides? Hot corners? ///Current relative center, in yaw, or spherical coordinates? Lying down in bed? } /* void StateTransitionDebug(){ int transition = -1; if(Input.GetKeyDown(KeyCode.Alpha1)){ transition = 1; StateTransition(menuScene); } else if(Input.GetKeyDown(KeyCode.Alpha2)){ transition = 2; StateTransition(targetScene); } else if(Input.GetKeyDown(KeyCode.Alpha3)){ transition = 3; StateTransition(minecartScene); } else if(Input.GetKeyDown(KeyCode.Alpha4)){ transition = 4; StateTransition(trackingScene); } else if(Input.GetKeyDown(KeyCode.Alpha5)){ transition = 5; StateTransition(relativityScene); } else if(Input.GetKeyDown(KeyCode.Alpha7)){ transition = 7; StateTransition(visionScene); } //Debug.Log(transition); }*/ }
// 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. // The MatchCollection lists the successful matches that // result when searching a string for a regular expression. using System.Collections; using System.Collections.Generic; using System.Diagnostics; namespace System.Text.RegularExpressions { /* * This collection returns a sequence of successful match results, either * from GetMatchCollection() or GetExecuteCollection(). It stops when the * first failure is encountered (it does not return the failed match). */ /// <summary> /// Represents the set of names appearing as capturing group /// names in a regular expression. /// </summary> [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(RegexCollectionDebuggerProxy<Match>))] [Serializable] public class MatchCollection : IList<Match>, IReadOnlyList<Match>, IList { private readonly Regex _regex; private readonly List<Match> _matches; private bool _done; private readonly string _input; private readonly int _beginning; private readonly int _length; private int _startat; private int _prevlen; internal MatchCollection(Regex regex, string input, int beginning, int length, int startat) { if (startat < 0 || startat > input.Length) throw new ArgumentOutOfRangeException(nameof(startat), SR.BeginIndexNotNegative); _regex = regex; _input = input; _beginning = beginning; _length = length; _startat = startat; _prevlen = -1; _matches = new List<Match>(); _done = false; } public bool IsReadOnly => true; /// <summary> /// Returns the number of captures. /// </summary> public int Count { get { EnsureInitialized(); return _matches.Count; } } /// <summary> /// Returns the ith Match in the collection. /// </summary> public virtual Match this[int i] { get { if (i < 0) throw new ArgumentOutOfRangeException(nameof(i)); Match match = GetMatch(i); if (match == null) throw new ArgumentOutOfRangeException(nameof(i)); return match; } } /// <summary> /// Provides an enumerator in the same order as Item[i]. /// </summary> public IEnumerator GetEnumerator() => new Enumerator(this); IEnumerator<Match> IEnumerable<Match>.GetEnumerator() => new Enumerator(this); private Match GetMatch(int i) { Debug.Assert(i >= 0, "i cannot be negative."); if (_matches.Count > i) return _matches[i]; if (_done) return null; Match match; do { match = _regex.Run(false, _prevlen, _input, _beginning, _length, _startat); if (!match.Success) { _done = true; return null; } _matches.Add(match); _prevlen = match._length; _startat = match._textpos; } while (_matches.Count <= i); return match; } private void EnsureInitialized() { if (!_done) { GetMatch(int.MaxValue); } } public bool IsSynchronized => false; public object SyncRoot => this; public void CopyTo(Array array, int arrayIndex) { EnsureInitialized(); ((ICollection)_matches).CopyTo(array, arrayIndex); } public void CopyTo(Match[] array, int arrayIndex) { EnsureInitialized(); _matches.CopyTo(array, arrayIndex); } int IList<Match>.IndexOf(Match item) { EnsureInitialized(); return _matches.IndexOf(item); } void IList<Match>.Insert(int index, Match item) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } void IList<Match>.RemoveAt(int index) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } Match IList<Match>.this[int index] { get { return this[index]; } set { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } } void ICollection<Match>.Add(Match item) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } void ICollection<Match>.Clear() { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } bool ICollection<Match>.Contains(Match item) { EnsureInitialized(); return _matches.Contains(item); } bool ICollection<Match>.Remove(Match item) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } int IList.Add(object value) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } void IList.Clear() { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } bool IList.Contains(object value) => value is Match && ((ICollection<Match>)this).Contains((Match)value); int IList.IndexOf(object value) => value is Match ? ((IList<Match>)this).IndexOf((Match)value) : -1; void IList.Insert(int index, object value) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } bool IList.IsFixedSize => true; void IList.Remove(object value) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } void IList.RemoveAt(int index) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } object IList.this[int index] { get { return this[index]; } set { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } } [Serializable] private sealed class Enumerator : IEnumerator<Match> { private readonly MatchCollection _collection; private int _index; internal Enumerator(MatchCollection collection) { Debug.Assert(collection != null, "collection cannot be null."); _collection = collection; _index = -1; } public bool MoveNext() { if (_index == -2) return false; _index++; Match match = _collection.GetMatch(_index); if (match == null) { _index = -2; return false; } return true; } public Match Current { get { if (_index < 0) throw new InvalidOperationException(SR.EnumNotStarted); return _collection.GetMatch(_index); } } object IEnumerator.Current => Current; void IEnumerator.Reset() { _index = -1; } void IDisposable.Dispose() { } } } }
// <copyright file="CommandLineDialog.cs" company="Google Inc."> // Copyright (C) 2016 Google Inc. 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. // </copyright> namespace GooglePlayServices { using System.Collections.Generic; using System.Collections; using System.Diagnostics; using System.IO; using System; using UnityEditor; using UnityEngine; public class CommandLineDialog : TextAreaDialog { /// <summary> /// Forwards the output of the currently executing command to a CommandLineDialog window. /// </summary> public class ProgressReporter : CommandLine.LineReader { /// <summary> /// Used to scale the progress bar by the number of lines reported by the command /// line tool. /// </summary> public int maxProgressLines; // Queue of command line output lines to send to the main / UI thread. private System.Collections.Queue textQueue = null; // Number of lines reported by the command line tool. private volatile int linesReported; // Command line tool result, set when command line execution is complete. private volatile CommandLine.Result result = null; /// <summary> /// Event called on the main / UI thread when the outstanding command line tool /// completes. /// </summary> public event CommandLine.CompletionHandler Complete; /// <summary> /// Construct a new reporter. /// </summary> public ProgressReporter(CommandLine.IOHandler handler = null) { textQueue = System.Collections.Queue.Synchronized(new System.Collections.Queue()); maxProgressLines = 0; linesReported = 0; LineHandler += CommandLineIOHandler; Complete = null; } // Count the number of newlines and carriage returns in a string. private int CountLines(string str) { return str.Split(new char[] { '\n', '\r' }).Length - 1; } /// <summary> /// Called from RunCommandLine() tool to report the output of the currently /// executing commmand. /// </summary> /// <param name="process">Executing process.</param> /// <param name="stdin">Standard input stream.</param> /// <param name="data">Data read from the standard output or error streams.</param> private void CommandLineIOHandler(Process process, StreamWriter stdin, CommandLine.StreamData data) { if (process.HasExited || data.data == null) return; // Count lines in stdout. if (data.handle == 0) linesReported += CountLines(data.text); // Enqueue data for the text view. textQueue.Enqueue(System.Text.Encoding.UTF8.GetString(data.data)); } /// <summary> /// Called when the currently executing command completes. /// </summary> public void CommandLineToolCompletion(CommandLine.Result result) { this.result = result; } /// <summary> /// Called from CommandLineDialog in the context of the main / UI thread. /// </summary> public void Update(CommandLineDialog window) { if (textQueue.Count > 0) { List<string> textList = new List<string>(); while (textQueue.Count > 0) textList.Add((string)textQueue.Dequeue()); string bodyText = window.bodyText + String.Join("", textList.ToArray()); // Really weak handling of carriage returns. Truncates to the previous // line for each newline detected. while (true) { // Really weak handling carriage returns for progress style updates. int carriageReturn = bodyText.LastIndexOf("\r"); if (carriageReturn < 0 || bodyText.Substring(carriageReturn, 1) == "\n") { break; } string bodyTextHead = ""; int previousNewline = bodyText.LastIndexOf("\n", carriageReturn, carriageReturn); if (previousNewline >= 0) { bodyTextHead = bodyText.Substring(0, previousNewline + 1); } bodyText = bodyTextHead + bodyText.Substring(carriageReturn + 1); } window.bodyText = bodyText; if (window.autoScrollToBottom) { window.scrollPosition.y = Mathf.Infinity; } window.Repaint(); } if (maxProgressLines > 0) { window.progress = (float)linesReported / (float)maxProgressLines; } if (result != null) { window.progressTitle = ""; if (Complete != null) { Complete(result); Complete = null; } } } } public volatile float progress; public string progressTitle; public string progressSummary; public volatile bool autoScrollToBottom; /// <summary> /// Event delegate called from the Update() method of the window. /// </summary> public delegate void UpdateDelegate(CommandLineDialog window); public event UpdateDelegate UpdateEvent; private bool progressBarVisible; /// <summary> /// Create a dialog box which can display command line output. /// </summary> /// <returns>Reference to the new window.</returns> public static CommandLineDialog CreateCommandLineDialog(string title) { CommandLineDialog window = (CommandLineDialog)EditorWindow.GetWindow( typeof(CommandLineDialog), true, title); window.Initialize(); return window; } /// <summary> /// Initialize all members of the window. /// </summary> public override void Initialize() { base.Initialize(); progress = 0.0f; progressTitle = ""; progressSummary = ""; UpdateEvent = null; progressBarVisible = false; autoScrollToBottom = false; } /// <summary> /// Asynchronously execute a command line tool in this window, showing progress /// and finally calling the specified delegate on completion from the main / UI thread. /// </summary> /// <param name="toolPath">Tool to execute.</param> /// <param name="arguments">String to pass to the tools' command line.</param> /// <param name="completionDelegate">Called when the tool completes.</param> /// <param name="workingDirectory">Directory to execute the tool from.</param> /// <param name="ioHandler">Allows a caller to provide interactive input and also handle /// both output and error streams from a single delegate.</param> /// <param name="maxProgressLines">Specifies the number of lines output by the /// command line that results in a 100% value on a progress bar.</param> /// <returns>Reference to the new window.</returns> public void RunAsync( string toolPath, string arguments, CommandLine.CompletionHandler completionDelegate, string workingDirectory = null, Dictionary<string, string> envVars = null, CommandLine.IOHandler ioHandler = null, int maxProgressLines = 0) { CommandLineDialog.ProgressReporter reporter = new CommandLineDialog.ProgressReporter(); reporter.maxProgressLines = maxProgressLines; // Call the reporter from the UI thread from this window. UpdateEvent += reporter.Update; // Connect the user's delegate to the reporter's completion method. reporter.Complete += completionDelegate; // Connect the caller's IoHandler delegate to the reporter. reporter.DataHandler += ioHandler; // Disconnect the reporter when the command completes. CommandLine.CompletionHandler reporterUpdateDisable = (CommandLine.Result unusedResult) => { this.UpdateEvent -= reporter.Update; }; reporter.Complete += reporterUpdateDisable; CommandLine.RunAsync(toolPath, arguments, reporter.CommandLineToolCompletion, workingDirectory: workingDirectory, envVars: envVars, ioHandler: reporter.AggregateLine); } /// <summary> /// Call the update event from the UI thread, optionally display / hide the progress bar. /// </summary> protected virtual void Update() { if (UpdateEvent != null) UpdateEvent(this); if (progressTitle != "") { progressBarVisible = true; EditorUtility.DisplayProgressBar(progressTitle, progressSummary, progress); } else if (progressBarVisible) { progressBarVisible = false; EditorUtility.ClearProgressBar(); } } } }
using System; using System.Collections.Generic; using System.Linq; using BTDB.Collections; using BTDB.FieldHandler; using BTDB.KVDBLayer; using BTDB.StreamLayer; namespace BTDB.ODBLayer; struct FieldId : IEquatable<FieldId> { readonly bool _isFromPrimaryKey; readonly uint _index; public bool IsFromPrimaryKey => _isFromPrimaryKey; public uint Index => _index; public FieldId(bool isFromPrimaryKey, uint index) { _isFromPrimaryKey = isFromPrimaryKey; _index = index; } public bool Equals(FieldId other) { return _isFromPrimaryKey == other.IsFromPrimaryKey && _index == other.Index; } } class SecondaryKeyInfo { public IList<FieldId> Fields { get; set; } public string Name { get; set; } public static bool Equal(SecondaryKeyInfo a, SecondaryKeyInfo b) { if (a.Name != b.Name) return false; if (a.Fields.Count != b.Fields.Count) return false; for (int i = 0; i < a.Fields.Count; i++) { if (!a.Fields[i].Equals(b.Fields[i])) return false; } return true; } } public class RelationVersionInfo { public ReadOnlyMemory<TableFieldInfo> Fields; public ReadOnlyMemory<TableFieldInfo> PrimaryKeyFields; ReadOnlyMemory<TableFieldInfo> _secondaryKeyFields; IDictionary<string, uint> _secondaryKeysNames; IDictionary<uint, SecondaryKeyInfo> _secondaryKeys; public RelationVersionInfo(Dictionary<uint, TableFieldInfo> primaryKeyFields, //order -> info List<Tuple<int, IList<SecondaryKeyAttribute>>> secondaryKeys, //positive: sec key field idx, negative: pk order, attrs ReadOnlyMemory<TableFieldInfo> secondaryKeyFields, ReadOnlyMemory<TableFieldInfo> fields) { PrimaryKeyFields = primaryKeyFields.OrderBy(kv => kv.Key).Select(kv => kv.Value).ToArray(); _secondaryKeyFields = secondaryKeyFields; CreateSecondaryKeyInfo(secondaryKeys, primaryKeyFields); Fields = fields; } void CreateSecondaryKeyInfo(List<Tuple<int, IList<SecondaryKeyAttribute>>> attributes, Dictionary<uint, TableFieldInfo> primaryKeyFields) { _secondaryKeys = new Dictionary<uint, SecondaryKeyInfo>(); _secondaryKeysNames = new Dictionary<string, uint>(); var skIndexNames = attributes.SelectMany(t => t.Item2).Select(a => a.Name).Distinct(); foreach (var indexName in skIndexNames) { var indexFields = new List<Tuple<int, SecondaryKeyAttribute>>(); //fieldIndex, attribute foreach (var kv in attributes) { var attr = kv.Item2.FirstOrDefault(a => a.Name == indexName); if (attr == null) continue; indexFields.Add(Tuple.Create(kv.Item1, attr)); } var orderedAttrs = indexFields.OrderBy(a => a.Item2.Order).ToList(); var info = new SecondaryKeyInfo { Name = indexName, Fields = new List<FieldId>() }; var usedPKFields = new Dictionary<uint, object>(); foreach (var attr in orderedAttrs) { for (uint i = 1; i <= attr.Item2.IncludePrimaryKeyOrder; i++) { usedPKFields.Add(i, null); var pi = PrimaryKeyFields.Span.IndexOf(primaryKeyFields[i]); info.Fields.Add(new FieldId(true, (uint)pi)); } if (attr.Item1 < 0) { var pkOrder = (uint)-attr.Item1; usedPKFields.Add(pkOrder, null); var pi = PrimaryKeyFields.Span.IndexOf(primaryKeyFields[pkOrder]); info.Fields.Add(new FieldId(true, (uint)pi)); } else { info.Fields.Add(new FieldId(false, (uint)attr.Item1)); } } //fill all not present parts of primary key foreach (var pk in primaryKeyFields) { if (!usedPKFields.ContainsKey(pk.Key)) info.Fields.Add(new FieldId(true, (uint)PrimaryKeyFields.Span.IndexOf(primaryKeyFields[pk.Key]))); } var skIndex = SelectSecondaryKeyIndex(info); _secondaryKeysNames[indexName] = skIndex; _secondaryKeys[skIndex] = info; } } uint SelectSecondaryKeyIndex(SecondaryKeyInfo info) { var index = 0u; while (_secondaryKeys.ContainsKey(index)) index++; return index; //use fresh one } internal RelationVersionInfo(ReadOnlyMemory<TableFieldInfo> primaryKeyFields, Dictionary<uint, SecondaryKeyInfo> secondaryKeys, ReadOnlyMemory<TableFieldInfo> secondaryKeyFields, ReadOnlyMemory<TableFieldInfo> fields) { PrimaryKeyFields = primaryKeyFields; _secondaryKeys = secondaryKeys; _secondaryKeysNames = new Dictionary<string, uint>(secondaryKeys.Count); foreach (var secondaryKeyInfo in secondaryKeys) { _secondaryKeysNames.Add(secondaryKeyInfo.Value.Name, secondaryKeyInfo.Key); } _secondaryKeyFields = secondaryKeyFields; Fields = fields; } internal TableFieldInfo? this[string name] { get { foreach (var fieldInfo in Fields.Span) { if (fieldInfo.Name == name) return fieldInfo; } foreach (var fieldInfo in PrimaryKeyFields.Span) { if (fieldInfo.Name == name) return fieldInfo; } return null; } } internal ReadOnlyMemory<TableFieldInfo> GetAllFields() { var res = new TableFieldInfo[PrimaryKeyFields.Length + Fields.Length]; PrimaryKeyFields.CopyTo(res); Fields.CopyTo(res.AsMemory(PrimaryKeyFields.Length)); return res; } internal TableFieldInfo GetSecondaryKeyField(int index) { return _secondaryKeyFields.Span[index]; } internal bool HasSecondaryIndexes => _secondaryKeys.Count > 0; internal IDictionary<uint, SecondaryKeyInfo> SecondaryKeys => _secondaryKeys; public ReadOnlyMemory<TableFieldInfo> SecondaryKeyFields { get => _secondaryKeyFields; set => _secondaryKeyFields = value; } public IDictionary<string, uint> SecondaryKeysNames { get => _secondaryKeysNames; set => _secondaryKeysNames = value; } internal ReadOnlySpan<TableFieldInfo> GetSecondaryKeyFields(uint secondaryKeyIndex) { if (!_secondaryKeys.TryGetValue(secondaryKeyIndex, out var info)) throw new BTDBException($"Unknown secondary key {secondaryKeyIndex}."); return GetSecondaryKeyFields(info); } ReadOnlySpan<TableFieldInfo> GetSecondaryKeyFields(SecondaryKeyInfo info) { var fields = new StructList<TableFieldInfo>(); foreach (var field in info.Fields) { fields.Add(field.IsFromPrimaryKey ? PrimaryKeyFields.Span[(int)field.Index] : _secondaryKeyFields.Span[(int)field.Index]); } return fields; } internal uint GetSecondaryKeyIndex(string name) { if (!_secondaryKeysNames.TryGetValue(name, out var index)) throw new BTDBException($"Unknown secondary key {name}."); return index; } internal void Save(ref SpanWriter writer) { writer.WriteVUInt32((uint)PrimaryKeyFields.Length); foreach (var field in PrimaryKeyFields.Span) { field.Save(ref writer); } writer.WriteVUInt32((uint)_secondaryKeyFields.Length); foreach (var field in _secondaryKeyFields.Span) { field.Save(ref writer); } writer.WriteVUInt32((uint)_secondaryKeys.Count); foreach (var key in _secondaryKeys) { writer.WriteVUInt32(key.Key); var info = key.Value; writer.WriteVUInt32(0); //unused writer.WriteString(info.Name); writer.WriteVUInt32((uint)info.Fields.Count); foreach (var fi in info.Fields) { writer.WriteBool(fi.IsFromPrimaryKey); writer.WriteVUInt32(fi.Index); } } var fields = Fields.Span; writer.WriteVUInt32((uint)fields.Length); foreach (var tfi in fields) { tfi.Save(ref writer); } } public static RelationVersionInfo LoadUnresolved(ref SpanReader reader, string relationName) { var pkCount = reader.ReadVUInt32(); var primaryKeyFields = new StructList<TableFieldInfo>(); primaryKeyFields.Reserve(pkCount); for (var i = 0u; i < pkCount; i++) { primaryKeyFields.Add(UnresolvedTableFieldInfo.Load(ref reader, relationName, FieldHandlerOptions.Orderable)); } var skFieldCount = reader.ReadVUInt32(); var secondaryKeyFields = new TableFieldInfo[skFieldCount]; for (var i = 0; i < skFieldCount; i++) { secondaryKeyFields[i] = UnresolvedTableFieldInfo.Load(ref reader, relationName, FieldHandlerOptions.Orderable); } var skCount = reader.ReadVUInt32(); var secondaryKeys = new Dictionary<uint, SecondaryKeyInfo>((int)skCount); for (var i = 0; i < skCount; i++) { var skIndex = reader.ReadVUInt32(); var info = new SecondaryKeyInfo(); reader.SkipVUInt32(); //unused info.Name = reader.ReadString()!; var cnt = reader.ReadVUInt32(); info.Fields = new List<FieldId>((int)cnt); for (var j = 0; j < cnt; j++) { var fromPrimary = reader.ReadBool(); var index = reader.ReadVUInt32(); info.Fields.Add(new FieldId(fromPrimary, index)); } secondaryKeys.Add(skIndex, info); } var fieldCount = reader.ReadVUInt32(); var fieldInfos = new TableFieldInfo[fieldCount]; for (var i = 0; i < fieldCount; i++) { fieldInfos[i] = UnresolvedTableFieldInfo.Load(ref reader, relationName, FieldHandlerOptions.None); } return new RelationVersionInfo(primaryKeyFields, secondaryKeys, secondaryKeyFields, fieldInfos); } public void ResolveFieldHandlers(IFieldHandlerFactory fieldHandlerFactory) { var resolvedPrimaryKeyFields = new TableFieldInfo[PrimaryKeyFields.Length]; for (var i = 0; i < PrimaryKeyFields.Length; i++) resolvedPrimaryKeyFields[i] = ((UnresolvedTableFieldInfo)PrimaryKeyFields.Span[i]).Resolve(fieldHandlerFactory); PrimaryKeyFields = resolvedPrimaryKeyFields; var resolvedSecondaryKeyFields = new TableFieldInfo[_secondaryKeyFields.Length]; for (var i = 0; i < _secondaryKeyFields.Length; i++) resolvedSecondaryKeyFields[i] = ((UnresolvedTableFieldInfo)_secondaryKeyFields.Span[i]).Resolve(fieldHandlerFactory); _secondaryKeyFields = resolvedSecondaryKeyFields; var resolvedFields = new TableFieldInfo[Fields.Length]; for (var i = 0; i < Fields.Length; i++) resolvedFields[i] = ((UnresolvedTableFieldInfo)Fields.Span[i]).Resolve(fieldHandlerFactory); Fields = resolvedFields; } internal bool NeedsCtx() { foreach (var fieldInfo in Fields.Span) { if (fieldInfo.Handler!.NeedsCtx()) return true; } return false; } internal bool NeedsInit() { foreach (var fieldInfo in Fields.Span) { if (fieldInfo.Handler is IFieldHandlerWithInit) return true; } return false; } internal static bool Equal(RelationVersionInfo a, RelationVersionInfo b) { //PKs if (a.PrimaryKeyFields.Length != b.PrimaryKeyFields.Length) return false; for (int i = 0; i < a.PrimaryKeyFields.Length; i++) { if (!TableFieldInfo.Equal(a.PrimaryKeyFields.Span[i], b.PrimaryKeyFields.Span[i])) return false; } //SKs if (a._secondaryKeys.Count != b._secondaryKeys.Count) return false; foreach (var key in a._secondaryKeys) { if (!b._secondaryKeys.TryGetValue(key.Key, out var bInfo)) return false; if (!SecondaryKeyInfo.Equal(key.Value, bInfo)) return false; } //Fields if (a.Fields.Length != b.Fields.Length) return false; for (var i = 0; i < a.Fields.Length; i++) { if (!TableFieldInfo.Equal(a.Fields.Span[i], b.Fields.Span[i])) return false; } return true; } }
using System; using System.Collections.Generic; using System.Text; using DCalcCore.Algorithm; using DCalcCore.Assemblers; using DCalcCore.Utilities; using DCalcCore.Threading; using DCalcCore.LoadBalancers; using System.Threading; namespace DCalcCore.Runners { /// <summary> /// Local runner. Provides means of executing a script on local cores. This class is thread-safe. /// </summary> /// <typeparam name="A">Script assembler to use.</typeparam> /// <typeparam name="LB">Load balancer to be used across threads.</typeparam> public sealed class LocalMachineRunner<A, LB> : IRunner where A : IScriptAssembler, new() where LB : ILoadBalancer, new() { #region Private Fields private A m_Assembler = new A(); private Dictionary<IScript, ICompiledScript> m_ScriptsToCompiled = new Dictionary<IScript, ICompiledScript>(); private Dictionary<ICompiledScript, IScript> m_CompiledToScripts = new Dictionary<ICompiledScript, IScript>(); private ThreadedWorkQueue<LB> m_WorkQueue; private String m_SyncRoot = "LocalMachineRunner Sync"; #endregion #region Private Methods /// <summary> /// Compiles the script. /// </summary> /// <param name="Script">The script.</param> /// <returns></returns> private ICompiledScript CompileScript(IScript Script) { /* Check if we have this Script already */ if (m_ScriptsToCompiled.ContainsKey(Script)) return m_ScriptsToCompiled[Script]; /* Try to actually compile the Script using the given assembler */ ICompiledScript compiled = m_Assembler.Assemble(Script); if (compiled != null) { m_ScriptsToCompiled.Add(Script, compiled); m_CompiledToScripts.Add(compiled, Script); } return compiled; } /// <summary> /// Initiates the queue. /// </summary> /// <param name="threadCount">The thread count.</param> private void InitiateQueue(Int32 threadCount) { /* Create new work queue */ m_WorkQueue = new ThreadedWorkQueue<LB>(threadCount); m_WorkQueue.QueuedWorkCompleted -= m_workQueue_QueuedWorkCompleted; m_WorkQueue.QueuedWorkCompleted += m_workQueue_QueuedWorkCompleted; m_WorkQueue.Start(); } /// <summary> /// Handles the QueuedWorkCompleted event of the m_workQueue control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="DCalcCore.Utilities.QueueEventArgs"/> instance containing the event data.</param> private void m_workQueue_QueuedWorkCompleted(object sender, QueueEventArgs e) { if (QueuedWorkCompleted != null) QueuedWorkCompleted(this, new ScriptQueueEventArgs((IScript)sender, e.OutputSet, e.SetId)); } #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="LocalMachineRunner&lt;A&gt;"/> class. Using the number of processors /// as default. /// </summary> public LocalMachineRunner() { /* Take the number of processors default */ InitiateQueue(Environment.ProcessorCount); } /// <summary> /// Initializes a new instance of the <see cref="LocalMachineRunner&lt;A&gt;"/> class. /// </summary> /// <param name="threadsToSpawn">The threads to spawn.</param> public LocalMachineRunner(Int32 threadsToSpawn) { if (threadsToSpawn < 1) throw new ArgumentException("threadsToSpawn"); InitiateQueue(threadsToSpawn); } #endregion #region IRunner Members /// <summary> /// Loads the script. /// </summary> /// <param name="script">The script.</param> /// <returns></returns> public Boolean LoadScript(IScript script) { if (script == null) throw new ArgumentNullException("script"); lock (m_SyncRoot) { /* Try and compile */ ICompiledScript compiledScript = CompileScript(script); return (compiledScript != null); } } /// <summary> /// Removes the script. /// </summary> /// <param name="script">The script.</param> /// <returns></returns> public Boolean RemoveScript(IScript script) { if (script == null) throw new ArgumentNullException("script"); ScalarSet[] cancelledSets = null; lock (m_SyncRoot) { /* Check if we already have it loaded */ if (m_ScriptsToCompiled.ContainsKey(script)) { ICompiledScript compiledScript = m_ScriptsToCompiled[script]; /* Cancel executive in the queue */ cancelledSets = m_WorkQueue.CancelEvaluation(compiledScript); Thread.Sleep(10); m_ScriptsToCompiled.Remove(script); m_CompiledToScripts.Remove(compiledScript); compiledScript.Dispose(); } else return false; } if (cancelledSets != null && cancelledSets.Length > 0) { foreach (ScalarSet set in cancelledSets) { if (QueuedWorkCompleted != null) QueuedWorkCompleted(this, new ScriptQueueEventArgs(script, null, set.Id)); } } return true; } /// <summary> /// Queues the work. /// </summary> /// <param name="script">The script.</param> /// <param name="inputSet">The input set.</param> /// <returns></returns> public Boolean QueueWork(IScript script, ScalarSet inputSet) { if (script == null) throw new ArgumentNullException("script"); if (inputSet == null) throw new ArgumentNullException("inputSet"); lock (m_SyncRoot) { /* First of all see if we have this Script compiled */ if (m_ScriptsToCompiled.ContainsKey(script)) { m_WorkQueue.QueueEvaluation(script, m_ScriptsToCompiled[script], inputSet); return true; } else return false; } } /// <summary> /// Occurs when queued work completed (a set has been evaluated). /// </summary> public event ScriptQueueEventHandler QueuedWorkCompleted; #endregion #region IDisposable Members /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { lock (m_SyncRoot) { /* We must clear out all queued items */ List<IScript> allScripts = new List<IScript>(m_ScriptsToCompiled.Keys); foreach (IScript Script in allScripts) { /* Remove all Scripts */ RemoveScript(Script); } /* Stop working queue */ m_WorkQueue.Stop(); m_WorkQueue.Dispose(); } } #endregion } }
// 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.InteropServices; using System.Collections; using System.Diagnostics; namespace System.DirectoryServices.ActiveDirectory { public class DirectoryServerCollection : CollectionBase { internal readonly string siteDN = null; internal readonly string transportDN = null; internal readonly DirectoryContext context = null; internal bool initialized = false; internal readonly Hashtable changeList = null; private readonly ArrayList _copyList = new ArrayList(); private readonly DirectoryEntry _crossRefEntry = null; private readonly bool _isADAM = false; private readonly bool _isForNC = false; internal DirectoryServerCollection(DirectoryContext context, string siteDN, string transportName) { Hashtable tempTable = new Hashtable(); changeList = Hashtable.Synchronized(tempTable); this.context = context; this.siteDN = siteDN; this.transportDN = transportName; } internal DirectoryServerCollection(DirectoryContext context, DirectoryEntry crossRefEntry, bool isADAM, ReadOnlyDirectoryServerCollection servers) { this.context = context; _crossRefEntry = crossRefEntry; _isADAM = isADAM; _isForNC = true; foreach (DirectoryServer server in servers) { InnerList.Add(server); } } public DirectoryServer this[int index] { get => (DirectoryServer)InnerList[index]; set { DirectoryServer server = (DirectoryServer)value; if (server == null) throw new ArgumentNullException(nameof(value)); if (!Contains(server)) List[index] = server; else throw new ArgumentException(SR.Format(SR.AlreadyExistingInCollection, server), nameof(value)); } } public int Add(DirectoryServer server) { if (server == null) throw new ArgumentNullException(nameof(server)); // make sure that it is within the current site if (_isForNC) { if ((!_isADAM)) { if (!(server is DomainController)) throw new ArgumentException(SR.ServerShouldBeDC, nameof(server)); // verify that the version >= 5.2 // DC should be Win 2003 or higher if (((DomainController)server).NumericOSVersion < 5.2) { throw new ArgumentException(SR.ServerShouldBeW2K3, nameof(server)); } } if (!Contains(server)) { return List.Add(server); } else { throw new ArgumentException(SR.Format(SR.AlreadyExistingInCollection, server), nameof(server)); } } else { string siteName = (server is DomainController) ? ((DomainController)server).SiteObjectName : ((AdamInstance)server).SiteObjectName; Debug.Assert(siteName != null); if (Utils.Compare(siteDN, siteName) != 0) { throw new ArgumentException(SR.NotWithinSite); } if (!Contains(server)) return List.Add(server); else throw new ArgumentException(SR.Format(SR.AlreadyExistingInCollection, server), nameof(server)); } } public void AddRange(DirectoryServer[] servers) { if (servers == null) throw new ArgumentNullException(nameof(servers)); foreach (DirectoryServer s in servers) { if (s == null) { throw new ArgumentException(nameof(servers)); } } for (int i = 0; ((i) < (servers.Length)); i = ((i) + (1))) this.Add(servers[i]); } public bool Contains(DirectoryServer server) { if (server == null) throw new ArgumentNullException(nameof(server)); for (int i = 0; i < InnerList.Count; i++) { DirectoryServer tmp = (DirectoryServer)InnerList[i]; if (Utils.Compare(tmp.Name, server.Name) == 0) { return true; } } return false; } public void CopyTo(DirectoryServer[] array, int index) { List.CopyTo(array, index); } public int IndexOf(DirectoryServer server) { if (server == null) throw new ArgumentNullException(nameof(server)); for (int i = 0; i < InnerList.Count; i++) { DirectoryServer tmp = (DirectoryServer)InnerList[i]; if (Utils.Compare(tmp.Name, server.Name) == 0) { return i; } } return -1; } public void Insert(int index, DirectoryServer server) { if (server == null) throw new ArgumentNullException(nameof(server)); if (_isForNC) { if ((!_isADAM)) { if (!(server is DomainController)) throw new ArgumentException(SR.ServerShouldBeDC, nameof(server)); // verify that the version >= 5.2 // DC should be Win 2003 or higher if (((DomainController)server).NumericOSVersion < 5.2) { throw new ArgumentException(SR.ServerShouldBeW2K3, nameof(server)); } } if (!Contains(server)) { List.Insert(index, server); } else { throw new ArgumentException(SR.Format(SR.AlreadyExistingInCollection, server), nameof(server)); } } else { // make sure that it is within the current site string siteName = (server is DomainController) ? ((DomainController)server).SiteObjectName : ((AdamInstance)server).SiteObjectName; Debug.Assert(siteName != null); if (Utils.Compare(siteDN, siteName) != 0) { throw new ArgumentException(SR.NotWithinSite, nameof(server)); } if (!Contains(server)) List.Insert(index, server); else throw new ArgumentException(SR.Format(SR.AlreadyExistingInCollection, server)); } } public void Remove(DirectoryServer server) { if (server == null) throw new ArgumentNullException(nameof(server)); for (int i = 0; i < InnerList.Count; i++) { DirectoryServer tmp = (DirectoryServer)InnerList[i]; if (Utils.Compare(tmp.Name, server.Name) == 0) { List.Remove(tmp); return; } } // something that does not exist in the collection throw new ArgumentException(SR.Format(SR.NotFoundInCollection, server), nameof(server)); } protected override void OnClear() { if (initialized && !_isForNC) { _copyList.Clear(); foreach (object o in List) { _copyList.Add(o); } } } protected override void OnClearComplete() { // if the property exists, clear it out if (_isForNC) { if (_crossRefEntry != null) { try { if (_crossRefEntry.Properties.Contains(PropertyManager.MsDSNCReplicaLocations)) { _crossRefEntry.Properties[PropertyManager.MsDSNCReplicaLocations].Clear(); } } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } } else if (initialized) { for (int i = 0; i < _copyList.Count; i++) { OnRemoveComplete(i, _copyList[i]); } } } protected override void OnInsertComplete(int index, object value) { if (_isForNC) { if (_crossRefEntry != null) { try { DirectoryServer server = (DirectoryServer)value; string ntdsaName = (server is DomainController) ? ((DomainController)server).NtdsaObjectName : ((AdamInstance)server).NtdsaObjectName; _crossRefEntry.Properties[PropertyManager.MsDSNCReplicaLocations].Add(ntdsaName); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } } else if (initialized) { DirectoryServer server = (DirectoryServer)value; string name = server.Name; string serverName = (server is DomainController) ? ((DomainController)server).ServerObjectName : ((AdamInstance)server).ServerObjectName; try { if (changeList.Contains(name)) { ((DirectoryEntry)changeList[name]).Properties["bridgeheadTransportList"].Value = this.transportDN; } else { DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(context, serverName); de.Properties["bridgeheadTransportList"].Value = this.transportDN; changeList.Add(name, de); } } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } } protected override void OnRemoveComplete(int index, object value) { if (_isForNC) { try { if (_crossRefEntry != null) { string ntdsaName = (value is DomainController) ? ((DomainController)value).NtdsaObjectName : ((AdamInstance)value).NtdsaObjectName; _crossRefEntry.Properties[PropertyManager.MsDSNCReplicaLocations].Remove(ntdsaName); } } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } else { DirectoryServer server = (DirectoryServer)value; string name = server.Name; string serverName = (server is DomainController) ? ((DomainController)server).ServerObjectName : ((AdamInstance)server).ServerObjectName; try { if (changeList.Contains(name)) { ((DirectoryEntry)changeList[name]).Properties["bridgeheadTransportList"].Clear(); } else { DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(context, serverName); de.Properties["bridgeheadTransportList"].Clear(); changeList.Add(name, de); } } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } } protected override void OnSetComplete(int index, object oldValue, object newValue) { OnRemoveComplete(index, oldValue); OnInsertComplete(index, newValue); } protected override void OnValidate(object value) { if (value == null) throw new ArgumentNullException(nameof(value)); if (_isForNC) { if (_isADAM) { // for adam this should be an ADAMInstance if (!(value is AdamInstance)) throw new ArgumentException(SR.ServerShouldBeAI, nameof(value)); } else { // for AD this should be a DomainController if (!(value is DomainController)) throw new ArgumentException(SR.ServerShouldBeDC, nameof(value)); } } else { if (!(value is DirectoryServer)) throw new ArgumentException(nameof(value)); } } internal string[] GetMultiValuedProperty() { ArrayList values = new ArrayList(); for (int i = 0; i < InnerList.Count; i++) { DirectoryServer ds = (DirectoryServer)InnerList[i]; string ntdsaName = (ds is DomainController) ? ((DomainController)ds).NtdsaObjectName : ((AdamInstance)ds).NtdsaObjectName; values.Add(ntdsaName); } return (string[])values.ToArray(typeof(string)); } } }
// ---------------------------------------------------------------------------------- // // 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.Collections; using System.Collections.Generic; using System.Management.Automation; using Microsoft.Azure.Commands.ResourceManager.Common.Tags; using Microsoft.Azure.Management.Storage; using Microsoft.Azure.Management.Storage.Models; using StorageModels = Microsoft.Azure.Management.Storage.Models; using Microsoft.Azure.Commands.Management.Storage.Models; using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; using System; namespace Microsoft.Azure.Commands.Management.Storage { /// <summary> /// Lists all storage services underneath the subscription. /// </summary> [Cmdlet(VerbsCommon.Set, StorageAccountNounStr, SupportsShouldProcess = true, DefaultParameterSetName = StorageEncryptionParameterSet), OutputType(typeof(PSStorageAccount))] public class SetAzureStorageAccountCommand : StorageAccountBaseCmdlet { /// <summary> /// Storage Encryption parameter set name /// </summary> private const string StorageEncryptionParameterSet = "StorageEncryption"; /// <summary> /// Keyvault Encryption parameter set name /// </summary> private const string KeyvaultEncryptionParameterSet = "KeyvaultEncryption"; [Parameter( Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "Resource Group Name.")] [ResourceGroupCompleter] [ValidateNotNullOrEmpty] public string ResourceGroupName { get; set; } [Parameter( Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "Storage Account Name.")] [Alias(StorageAccountNameAlias, AccountNameAlias)] [ValidateNotNullOrEmpty] public string Name { get; set; } [Parameter(HelpMessage = "Force to Set the Account")] public SwitchParameter Force { get { return force; } set { force = value; } } private bool force = false; [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Storage Account Sku Name.")] [Alias(StorageAccountTypeAlias, AccountTypeAlias, Account_TypeAlias)] [ValidateSet(AccountTypeString.StandardLRS, AccountTypeString.StandardZRS, AccountTypeString.StandardGRS, AccountTypeString.StandardRAGRS, AccountTypeString.PremiumLRS, IgnoreCase = true)] public string SkuName { get; set; } [Parameter( Mandatory = false, HelpMessage = "Storage Account Access Tier.")] [ValidateSet(AccountAccessTier.Hot, AccountAccessTier.Cool, IgnoreCase = true)] public string AccessTier { get; set; } [Parameter( Mandatory = false, HelpMessage = "Storage Account Custom Domain.")] [ValidateNotNull] public string CustomDomainName { get; set; } [Parameter( Mandatory = false, HelpMessage = "To Use Sub Domain.")] [ValidateNotNullOrEmpty] public bool? UseSubDomain { get; set; } [Parameter( Mandatory = false, HelpMessage = "Storage Service that will enable encryption.")] [Obsolete("Encryption at Rest is enabled by default for this storage account.", false)] public EncryptionSupportServiceEnum? EnableEncryptionService { get; set; } [Parameter( Mandatory = false, HelpMessage = "Storage Service that will disable encryption.")] [Obsolete("Encryption at Rest is enabled by default for this storage account. This feature cannot be disabled.", false)] public EncryptionSupportServiceEnum? DisableEncryptionService { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Storage Account Tags.")] [AllowEmptyCollection] [ValidateNotNull] [Alias(TagsAlias)] public Hashtable Tag { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Storage Account EnableHttpsTrafficOnly.")] public bool EnableHttpsTrafficOnly { get { return enableHttpsTrafficOnly.Value; } set { enableHttpsTrafficOnly = value; } } private bool? enableHttpsTrafficOnly = null; [Parameter(HelpMessage = "Whether to set Storage Account Encryption KeySource to Microsoft.Storage or not.", Mandatory = false, ParameterSetName = StorageEncryptionParameterSet)] public SwitchParameter StorageEncryption { get { return storageEncryption; } set { storageEncryption = value; } } private bool storageEncryption = false; [Parameter(HelpMessage = "Whether to set Storage Account encryption keySource to Microsoft.Keyvault or not. " + "If you specify KeyName, KeyVersion and KeyvaultUri, Storage Account Encryption KeySource will also be set to Microsoft.Keyvault weather this parameter is set or not.", Mandatory = false, ParameterSetName = KeyvaultEncryptionParameterSet)] public SwitchParameter KeyvaultEncryption { get { return keyvaultEncryption; } set { keyvaultEncryption = value; } } private bool keyvaultEncryption = false; [Parameter(HelpMessage = "Storage Account encryption keySource KeyVault KeyName", Mandatory = true, ParameterSetName = KeyvaultEncryptionParameterSet)] [ValidateNotNullOrEmpty] public string KeyName { get; set; } [Parameter(HelpMessage = "Storage Account encryption keySource KeyVault KeyVersion", Mandatory = true, ParameterSetName = KeyvaultEncryptionParameterSet)] [ValidateNotNullOrEmpty] public string KeyVersion { get; set; } [Parameter(HelpMessage = "Storage Account encryption keySource KeyVault KeyVaultUri", Mandatory = true, ParameterSetName = KeyvaultEncryptionParameterSet)] [ValidateNotNullOrEmpty] public string KeyVaultUri { get; set; } [Parameter( Mandatory = false, HelpMessage = "Generate and assign a new Storage Account Identity for this storage account for use with key management services like Azure KeyVault.")] public SwitchParameter AssignIdentity { get; set; } [Parameter(HelpMessage = "Storage Account NetworkRule", Mandatory = false)] [ValidateNotNullOrEmpty] public PSNetworkRuleSet NetworkRuleSet { get; set; } [Parameter( Mandatory = false, HelpMessage = "Upgrade Storage Account Kind to StorageV2.")] public SwitchParameter UpgradeToStorageV2 { get; set; } [Parameter(Mandatory = false, HelpMessage = "Run cmdlet in the background")] public SwitchParameter AsJob { get; set; } public override void ExecuteCmdlet() { base.ExecuteCmdlet(); if (ShouldProcess(this.Name, "Set Storage Account")) { if (this.force || this.AccessTier == null || ShouldContinue("Changing the access tier may result in additional charges. See (http://go.microsoft.com/fwlink/?LinkId=786482) to learn more.", "")) { StorageAccountUpdateParameters updateParameters = new StorageAccountUpdateParameters(); if (this.SkuName != null) { updateParameters.Sku = new Sku(ParseSkuName(this.SkuName)); } if (this.Tag != null) { Dictionary<string, string> tagDictionary = TagsConversionHelper.CreateTagDictionary(Tag, validate: true); updateParameters.Tags = tagDictionary ?? new Dictionary<string, string>(); } if (this.CustomDomainName != null) { updateParameters.CustomDomain = new CustomDomain() { Name = CustomDomainName, UseSubDomain = UseSubDomain }; } else if (UseSubDomain != null) { throw new System.ArgumentException(string.Format("UseSubDomain must be set together with CustomDomainName.")); } if (this.AccessTier != null) { updateParameters.AccessTier = ParseAccessTier(AccessTier); } if (enableHttpsTrafficOnly != null) { updateParameters.EnableHttpsTrafficOnly = enableHttpsTrafficOnly; } if (AssignIdentity.IsPresent) { updateParameters.Identity = new Identity(); } if (StorageEncryption || (ParameterSetName == KeyvaultEncryptionParameterSet)) { if (ParameterSetName == KeyvaultEncryptionParameterSet) { keyvaultEncryption = true; } updateParameters.Encryption = ParseEncryption(StorageEncryption, keyvaultEncryption, KeyName, KeyVersion, KeyVaultUri); } if (NetworkRuleSet != null) { updateParameters.NetworkRuleSet = PSNetworkRuleSet.ParseStorageNetworkRule(NetworkRuleSet); } if (UpgradeToStorageV2.IsPresent) { updateParameters.Kind = Kind.StorageV2; } var updatedAccountResponse = this.StorageClient.StorageAccounts.Update( this.ResourceGroupName, this.Name, updateParameters); var storageAccount = this.StorageClient.StorageAccounts.GetProperties(this.ResourceGroupName, this.Name); WriteStorageAccount(storageAccount); } } } } }
/// Copyright (C) 2012-2014 Soomla 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 UnityEngine; using System; using System.Runtime.InteropServices; namespace Soomla.Store { /// <summary> /// This class holds the basic assets needed to operate the Store. /// You can use it to purchase products from the mobile store. /// This is the only class you need to initialize in order to use the SOOMLA SDK. /// </summary> public class SoomlaStore { static SoomlaStore _instance = null; static SoomlaStore instance { get { if(_instance == null) { #if UNITY_ANDROID && !UNITY_EDITOR _instance = new SoomlaStoreAndroid(); #elif UNITY_IOS && !UNITY_EDITOR _instance = new SoomlaStoreIOS(); #else _instance = new SoomlaStore(); #endif } return _instance; } } /// <summary> /// Initializes the SOOMLA SDK. /// </summary> /// <param name="storeAssets">Your game's economy.</param> /// <exception cref="ExitGUIException">Thrown if soomlaSecret is missing or has not been changed.</exception> public static bool Initialize(IStoreAssets storeAssets) { if (string.IsNullOrEmpty(CoreSettings.SoomlaSecret)) { SoomlaUtils.LogError(TAG, "MISSING SoomlaSecret !!! Stopping here !!"); throw new ExitGUIException(); } if (CoreSettings.SoomlaSecret==CoreSettings.ONLY_ONCE_DEFAULT) { SoomlaUtils.LogError(TAG, "You have to change SoomlaSecret !!! Stopping here !!"); throw new ExitGUIException(); } var storeEvents = GameObject.FindObjectOfType<StoreEvents> (); if (storeEvents == null) { SoomlaUtils.LogDebug(TAG, "StoreEvents Component not found in scene. We're continuing from here but you won't get many events."); } if (Initialized) { string err = "SoomlaStore is already initialized. You can't initialize it twice!"; StoreEvents.Instance.onUnexpectedErrorInStore(err, true); SoomlaUtils.LogError(TAG, err); return false; } SoomlaUtils.LogDebug(TAG, "SoomlaStore Initializing ..."); instance._loadBillingService(); StoreInfo.SetStoreAssets(storeAssets); #if UNITY_IOS // On iOS we only refresh market items instance._refreshMarketItemsDetails(); #elif UNITY_ANDROID // On Android we refresh market items and restore transactions instance._refreshInventory(); #endif Initialized = true; StoreEvents.Instance.onSoomlaStoreInitialized("", true); return true; } /// <summary> /// Starts a purchase process in the market. /// </summary> /// <param name="productId">product id of the item to buy. This id is the one you set up on itunesconnect or Google Play developer console.</param> /// <param name="payload">Some text you want to get back when the purchasing process is completed.</param> public static void BuyMarketItem(string productId, string payload) { instance._buyMarketItem(productId, payload); } /// <summary> /// This method will run RestoreTransactions followed by RefreshMarketItemsDetails /// </summary> public static void RefreshInventory() { instance._refreshInventory(); } /// <summary> /// Creates a list of all metadata stored in the Market (the items that have been purchased). /// The metadata includes the item's name, description, price, product id, etc... /// Posts a <c>MarketItemsRefreshed</c> event with the list just created. /// Upon failure, prints error message. /// </summary> public static void RefreshMarketItemsDetails() { instance._refreshMarketItemsDetails(); } /// <summary> /// Initiates the restore transactions process. /// </summary> public static void RestoreTransactions() { instance._restoreTransactions(); } /// <summary> /// Checks if transactions were already restored. /// </summary> /// <returns><c>true</c> if transactions were already restored, <c>false</c> otherwise.</returns> public static bool TransactionsAlreadyRestored() { return instance._transactionsAlreadyRestored(); } /// <summary> /// Starts in-app billing service in background. /// </summary> public static void StartIabServiceInBg() { instance._startIabServiceInBg(); } /// <summary> /// Stops in-app billing service in background. /// </summary> public static void StopIabServiceInBg() { instance._stopIabServiceInBg(); } /** protected functions **/ /** The implementation of these functions here will be the behaviour when working in the editor **/ protected virtual void _loadBillingService() { } protected virtual void _buyMarketItem(string productId, string payload) { #if UNITY_EDITOR PurchasableVirtualItem item = StoreInfo.GetPurchasableItemWithProductId(productId); if (item == null) { throw new VirtualItemNotFoundException("ProductId", productId); } // simulate onMarketPurchaseStarted event var eventJSON = new JSONObject(); eventJSON.AddField("itemId", item.ItemId); eventJSON.AddField("payload", payload); StoreEvents.Instance.onMarketPurchaseStarted(eventJSON.print()); // in the editor we just give the item... no real market. item.Give(1); // simulate onMarketPurchase event StoreEvents.Instance.RunLater(() => { eventJSON = new JSONObject(); eventJSON.AddField("itemId", item.ItemId); eventJSON.AddField("payload", payload); var extraJSON = new JSONObject(); #if UNITY_IOS extraJSON.AddField("receipt", "fake_receipt_abcd1234"); extraJSON.AddField("token", "fake_token_zyxw9876"); #elif UNITY_ANDROID extraJSON.AddField("orderId", "fake_orderId_abcd1234"); extraJSON.AddField("purchaseToken", "fake_purchaseToken_zyxw9876"); #endif eventJSON.AddField("extra", extraJSON); StoreEvents.Instance.onMarketPurchase(eventJSON.print()); }); #endif } protected virtual void _refreshInventory() { } protected virtual void _restoreTransactions() { } protected virtual void _refreshMarketItemsDetails() { } protected virtual bool _transactionsAlreadyRestored() { return true; } protected virtual void _startIabServiceInBg() { } protected virtual void _stopIabServiceInBg() { } /** Class Members **/ protected const string TAG = "SOOMLA SoomlaStore"; /// <summary> /// Gets a value indicating whether <see cref="Soomla.Store.SoomlaStore"/> is initialized. /// </summary> /// <value><c>true</c> if initialized; otherwise, <c>false</c>.</value> public static bool Initialized { get; private set; } } }
/* The MIT License (MIT) Copyright (c) 2014 Play-Em 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 UnityEngine; #if UNITY_EDITOR using UnityEditor; using System.IO; using System.Collections.Generic; namespace SpritesAndBones.Editor { [ExecuteInEditMode] public class BakePoseEditor : EditorWindow { private GameObject animatorObject; private Dictionary<Skeleton, Pose> Poses = new Dictionary<Skeleton, Pose>(); [MenuItem("Sprites And Bones/Bake Poses")] protected static void ShowBakePoseEditor() { var wnd = GetWindow<BakePoseEditor>(); wnd.titleContent.text = "Bake Poses"; wnd.Show(); // SceneView.onSceneGUIDelegate += wnd.OnSceneGUI; } // public void OnDestroy() { // SceneView.onSceneGUIDelegate -= OnSceneGUI; // } public void OnGUI() { GUILayout.Label("Bake Poses", EditorStyles.boldLabel); EditorGUI.BeginChangeCheck(); GUILayout.Label("GameObject with Skeletons to Bake Pose", EditorStyles.boldLabel); animatorObject = (GameObject)EditorGUILayout.ObjectField(animatorObject, typeof(GameObject), true); if (animatorObject != null) { EditorGUILayout.Separator(); GUILayout.Label("Bake the Poses into selected Keyframe", EditorStyles.boldLabel); if (GUILayout.Button("Bake Poses")) { BakePose(); } if (Poses.Count > 0) { EditorGUILayout.Separator(); EditorGUILayout.Separator(); if (GUILayout.Button("Clear Poses")) { Poses = new Dictionary<Skeleton, Pose>(); } EditorGUILayout.Separator(); GUILayout.Label("Disable IK before Applying Poses", EditorStyles.boldLabel); EditorGUILayout.Separator(); if (GUILayout.Button("Disable Skeletons IK")) { DisableSkeletonsIK(); } EditorGUILayout.Separator(); if (GUILayout.Button("Enable Skeletons IK")) { EnableSkeletonsIK(); } if (GUILayout.Button("Apply Poses")) { ApplyPoses(); } EditorGUILayout.Separator(); GUILayout.Label("Only Saves Active GameObjects in Poses", EditorStyles.boldLabel); if (GUILayout.Button("Save Poses")) { SavePoses(); } } } else { EditorGUILayout.HelpBox("Please select a GameObject with Skeletons to Bake Pose and have Animation window open and set to Record.", MessageType.Error); EditorApplication.ExecuteMenuItem("Window/Animation"); } } private void BakePose() { if (animatorObject != null) { Skeleton[] skeletons = animatorObject.transform.root.gameObject.GetComponentsInChildren<Skeleton>(true); Poses = new Dictionary<Skeleton, Pose>(); foreach (Skeleton s in skeletons) { if (s.gameObject.activeInHierarchy) { Pose bakedPose = s.CreatePose(false); Poses.Add(s, bakedPose); Debug.Log("Added Baked Pose for " + s.name); } UnityEditorInternal.InternalEditorUtility.RepaintAllViews(); } Debug.Log("Finished baking poses for " + animatorObject.gameObject.name); } } private void DisableSkeletonsIK() { foreach (Skeleton s in Poses.Keys) { #if UNITY_EDITOR Undo.RecordObject(s, "Disable IK"); #endif s.IK_Enabled = false; #if UNITY_EDITOR EditorUtility.SetDirty(s); #endif Debug.Log("Disabled IK for " + s.name); } } private void EnableSkeletonsIK() { foreach (Skeleton s in Poses.Keys) { #if UNITY_EDITOR Undo.RecordObject(s, "Disable IK"); #endif s.IK_Enabled = true; #if UNITY_EDITOR EditorUtility.SetDirty(s); #endif Debug.Log("Enabled IK for " + s.name); } } private void ApplyPoses() { foreach (Skeleton s in Poses.Keys) { bool isIK = s.IK_Enabled; s.IK_Enabled = false; #if UNITY_EDITOR Undo.RecordObject(s, "Apply Pose"); #endif s.RestorePose((Pose)Poses[s]); #if UNITY_EDITOR EditorUtility.SetDirty(s); #endif s.IK_Enabled = isIK; Debug.Log("Applied Baked Poses for " + s.name); } } private void SavePoses() { if (!Directory.Exists("Assets/Poses")) { AssetDatabase.CreateFolder("Assets", "Poses"); AssetDatabase.Refresh(); } foreach (Skeleton s in Poses.Keys) { #if UNITY_EDITOR ScriptableObjectUtility.CreateAsset((Pose)Poses[s], "Poses/" + s.name + " Pose"); #endif Debug.Log("Saved Baked Poses for " + s.name); } } } } #endif
using System; using System.Runtime.InteropServices; using System.Linq; namespace SteamNative { internal unsafe class SteamMusicRemote : IDisposable { // // Holds a platform specific implentation // internal Platform.Interface platform; internal Facepunch.Steamworks.BaseSteamworks steamworks; // // Constructor decides which implementation to use based on current platform // internal SteamMusicRemote( Facepunch.Steamworks.BaseSteamworks steamworks, IntPtr pointer ) { this.steamworks = steamworks; if ( Platform.IsWindows64 ) platform = new Platform.Win64( pointer ); else if ( Platform.IsWindows32 ) platform = new Platform.Win32( pointer ); else if ( Platform.IsLinux32 ) platform = new Platform.Linux32( pointer ); else if ( Platform.IsLinux64 ) platform = new Platform.Linux64( pointer ); else if ( Platform.IsOsx ) platform = new Platform.Mac( pointer ); } // // Class is invalid if we don't have a valid implementation // public bool IsValid{ get{ return platform != null && platform.IsValid; } } // // When shutting down clear all the internals to avoid accidental use // public virtual void Dispose() { if ( platform != null ) { platform.Dispose(); platform = null; } } // bool public bool BActivationSuccess( bool bValue /*bool*/ ) { return platform.ISteamMusicRemote_BActivationSuccess( bValue ); } // bool public bool BIsCurrentMusicRemote() { return platform.ISteamMusicRemote_BIsCurrentMusicRemote(); } // bool public bool CurrentEntryDidChange() { return platform.ISteamMusicRemote_CurrentEntryDidChange(); } // bool public bool CurrentEntryIsAvailable( bool bAvailable /*bool*/ ) { return platform.ISteamMusicRemote_CurrentEntryIsAvailable( bAvailable ); } // bool public bool CurrentEntryWillChange() { return platform.ISteamMusicRemote_CurrentEntryWillChange(); } // bool public bool DeregisterSteamMusicRemote() { return platform.ISteamMusicRemote_DeregisterSteamMusicRemote(); } // bool public bool EnableLooped( bool bValue /*bool*/ ) { return platform.ISteamMusicRemote_EnableLooped( bValue ); } // bool public bool EnablePlaylists( bool bValue /*bool*/ ) { return platform.ISteamMusicRemote_EnablePlaylists( bValue ); } // bool public bool EnablePlayNext( bool bValue /*bool*/ ) { return platform.ISteamMusicRemote_EnablePlayNext( bValue ); } // bool public bool EnablePlayPrevious( bool bValue /*bool*/ ) { return platform.ISteamMusicRemote_EnablePlayPrevious( bValue ); } // bool public bool EnableQueue( bool bValue /*bool*/ ) { return platform.ISteamMusicRemote_EnableQueue( bValue ); } // bool public bool EnableShuffled( bool bValue /*bool*/ ) { return platform.ISteamMusicRemote_EnableShuffled( bValue ); } // bool public bool PlaylistDidChange() { return platform.ISteamMusicRemote_PlaylistDidChange(); } // bool public bool PlaylistWillChange() { return platform.ISteamMusicRemote_PlaylistWillChange(); } // bool public bool QueueDidChange() { return platform.ISteamMusicRemote_QueueDidChange(); } // bool public bool QueueWillChange() { return platform.ISteamMusicRemote_QueueWillChange(); } // bool public bool RegisterSteamMusicRemote( string pchName /*const char **/ ) { return platform.ISteamMusicRemote_RegisterSteamMusicRemote( pchName ); } // bool public bool ResetPlaylistEntries() { return platform.ISteamMusicRemote_ResetPlaylistEntries(); } // bool public bool ResetQueueEntries() { return platform.ISteamMusicRemote_ResetQueueEntries(); } // bool public bool SetCurrentPlaylistEntry( int nID /*int*/ ) { return platform.ISteamMusicRemote_SetCurrentPlaylistEntry( nID ); } // bool public bool SetCurrentQueueEntry( int nID /*int*/ ) { return platform.ISteamMusicRemote_SetCurrentQueueEntry( nID ); } // bool public bool SetDisplayName( string pchDisplayName /*const char **/ ) { return platform.ISteamMusicRemote_SetDisplayName( pchDisplayName ); } // bool public bool SetPlaylistEntry( int nID /*int*/, int nPosition /*int*/, string pchEntryText /*const char **/ ) { return platform.ISteamMusicRemote_SetPlaylistEntry( nID, nPosition, pchEntryText ); } // bool public bool SetPNGIcon_64x64( IntPtr pvBuffer /*void **/, uint cbBufferLength /*uint32*/ ) { return platform.ISteamMusicRemote_SetPNGIcon_64x64( (IntPtr) pvBuffer, cbBufferLength ); } // bool public bool SetQueueEntry( int nID /*int*/, int nPosition /*int*/, string pchEntryText /*const char **/ ) { return platform.ISteamMusicRemote_SetQueueEntry( nID, nPosition, pchEntryText ); } // bool public bool UpdateCurrentEntryCoverArt( IntPtr pvBuffer /*void **/, uint cbBufferLength /*uint32*/ ) { return platform.ISteamMusicRemote_UpdateCurrentEntryCoverArt( (IntPtr) pvBuffer, cbBufferLength ); } // bool public bool UpdateCurrentEntryElapsedSeconds( int nValue /*int*/ ) { return platform.ISteamMusicRemote_UpdateCurrentEntryElapsedSeconds( nValue ); } // bool public bool UpdateCurrentEntryText( string pchText /*const char **/ ) { return platform.ISteamMusicRemote_UpdateCurrentEntryText( pchText ); } // bool public bool UpdateLooped( bool bValue /*bool*/ ) { return platform.ISteamMusicRemote_UpdateLooped( bValue ); } // bool public bool UpdatePlaybackStatus( AudioPlayback_Status nStatus /*AudioPlayback_Status*/ ) { return platform.ISteamMusicRemote_UpdatePlaybackStatus( nStatus ); } // bool public bool UpdateShuffled( bool bValue /*bool*/ ) { return platform.ISteamMusicRemote_UpdateShuffled( bValue ); } // bool public bool UpdateVolume( float flValue /*float*/ ) { return platform.ISteamMusicRemote_UpdateVolume( flValue ); } } }
/* * * 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 Lucene.Net.Analysis; using Lucene.Net.Analysis.TokenAttributes; using Lucene.Net.Codecs.Lucene41; using Lucene.Net.Documents; using Lucene.Net.QueryParsers.Classic; using Lucene.Net.Search; using Lucene.Net.Search.Spans; using Lucene.Net.Store; using Lucene.Net.Support; using Lucene.Net.Util; using NUnit.Framework; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using Console = Lucene.Net.Support.SystemConsole; namespace Lucene.Net.Index.Memory { public class MemoryIndexTest : BaseTokenStreamTestCase { private ISet<string> queries = new HashSet<string>(); public static readonly int ITERATIONS = 100 * RANDOM_MULTIPLIER; public override void SetUp() { base.SetUp(); queries.addAll(ReadQueries("testqueries.txt")); queries.addAll(ReadQueries("testqueries2.txt")); } /** * read a set of queries from a resource file */ private ISet<string> ReadQueries(string resource) { ISet<string> queries = new HashSet<string>(); Stream stream = GetType().getResourceAsStream(resource); TextReader reader = new StreamReader(stream, Encoding.UTF8); String line = null; while ((line = reader.ReadLine()) != null) { line = line.Trim(); if (line.Length > 0 && !line.StartsWith("#", StringComparison.Ordinal) && !line.StartsWith("//", StringComparison.Ordinal)) { queries.add(line); } } return queries; } /** * runs random tests, up to ITERATIONS times. */ [Test] public void TestRandomQueries() { MemoryIndex index = new MemoryIndex(Random().nextBoolean(), Random().nextInt(50) * 1024 * 1024); for (int i = 0; i < ITERATIONS; i++) { AssertAgainstRAMDirectory(index); } } /** * Build a randomish document for both RAMDirectory and MemoryIndex, * and run all the queries against it. */ public void AssertAgainstRAMDirectory(MemoryIndex memory) { memory.Reset(); StringBuilder fooField = new StringBuilder(); StringBuilder termField = new StringBuilder(); // add up to 250 terms to field "foo" int numFooTerms = Random().nextInt(250 * RANDOM_MULTIPLIER); for (int i = 0; i < numFooTerms; i++) { fooField.append(" "); fooField.append(RandomTerm()); } // add up to 250 terms to field "term" int numTermTerms = Random().nextInt(250 * RANDOM_MULTIPLIER); for (int i = 0; i < numTermTerms; i++) { termField.append(" "); termField.append(RandomTerm()); } Store.Directory ramdir = new RAMDirectory(); Analyzer analyzer = RandomAnalyzer(); IndexWriter writer = new IndexWriter(ramdir, new IndexWriterConfig(TEST_VERSION_CURRENT, analyzer).SetCodec(TestUtil.AlwaysPostingsFormat(new Lucene41PostingsFormat()))); Document doc = new Document(); Field field1 = NewTextField("foo", fooField.toString(), Field.Store.NO); Field field2 = NewTextField("term", termField.toString(), Field.Store.NO); doc.Add(field1); doc.Add(field2); writer.AddDocument(doc); writer.Dispose(); memory.AddField("foo", fooField.toString(), analyzer); memory.AddField("term", termField.toString(), analyzer); if (VERBOSE) { Console.WriteLine("Random MemoryIndex:\n" + memory.toString()); Console.WriteLine("Same index as RAMDirectory: " + RamUsageEstimator.HumanReadableUnits(RamUsageEstimator.SizeOf(ramdir))); Console.WriteLine(); } else { assertTrue(memory.GetMemorySize() > 0L); } AtomicReader reader = (AtomicReader)memory.CreateSearcher().IndexReader; DirectoryReader competitor = DirectoryReader.Open(ramdir); DuellReaders(competitor, reader); IOUtils.Dispose(reader, competitor); AssertAllQueries(memory, ramdir, analyzer); ramdir.Dispose(); } private void DuellReaders(CompositeReader other, AtomicReader memIndexReader) { AtomicReader competitor = SlowCompositeReaderWrapper.Wrap(other); Fields memFields = memIndexReader.Fields; foreach (string field in competitor.Fields) { Terms memTerms = memFields.GetTerms(field); Terms iwTerms = memIndexReader.GetTerms(field); if (iwTerms == null) { assertNull(memTerms); } else { NumericDocValues normValues = competitor.GetNormValues(field); NumericDocValues memNormValues = memIndexReader.GetNormValues(field); if (normValues != null) { // mem idx always computes norms on the fly assertNotNull(memNormValues); assertEquals(normValues.Get(0), memNormValues.Get(0)); } assertNotNull(memTerms); assertEquals(iwTerms.DocCount, memTerms.DocCount); assertEquals(iwTerms.SumDocFreq, memTerms.SumDocFreq); assertEquals(iwTerms.SumTotalTermFreq, memTerms.SumTotalTermFreq); TermsEnum iwTermsIter = iwTerms.GetIterator(null); TermsEnum memTermsIter = memTerms.GetIterator(null); if (iwTerms.HasPositions) { bool offsets = iwTerms.HasOffsets && memTerms.HasOffsets; while (iwTermsIter.Next() != null) { assertNotNull(memTermsIter.Next()); assertEquals(iwTermsIter.Term, memTermsIter.Term); DocsAndPositionsEnum iwDocsAndPos = iwTermsIter.DocsAndPositions(null, null); DocsAndPositionsEnum memDocsAndPos = memTermsIter.DocsAndPositions(null, null); while (iwDocsAndPos.NextDoc() != DocsAndPositionsEnum.NO_MORE_DOCS) { assertEquals(iwDocsAndPos.DocID, memDocsAndPos.NextDoc()); assertEquals(iwDocsAndPos.Freq, memDocsAndPos.Freq); for (int i = 0; i < iwDocsAndPos.Freq; i++) { assertEquals("term: " + iwTermsIter.Term.Utf8ToString(), iwDocsAndPos.NextPosition(), memDocsAndPos.NextPosition()); if (offsets) { assertEquals(iwDocsAndPos.StartOffset, memDocsAndPos.StartOffset); assertEquals(iwDocsAndPos.EndOffset, memDocsAndPos.EndOffset); } } } } } else { while (iwTermsIter.Next() != null) { assertEquals(iwTermsIter.Term, memTermsIter.Term); DocsEnum iwDocsAndPos = iwTermsIter.Docs(null, null); DocsEnum memDocsAndPos = memTermsIter.Docs(null, null); while (iwDocsAndPos.NextDoc() != DocsAndPositionsEnum.NO_MORE_DOCS) { assertEquals(iwDocsAndPos.DocID, memDocsAndPos.NextDoc()); assertEquals(iwDocsAndPos.Freq, memDocsAndPos.Freq); } } } } } } /** * Run all queries against both the RAMDirectory and MemoryIndex, ensuring they are the same. */ public void AssertAllQueries(MemoryIndex memory, Store.Directory ramdir, Analyzer analyzer) { IndexReader reader = DirectoryReader.Open(ramdir); IndexSearcher ram = NewSearcher(reader); IndexSearcher mem = memory.CreateSearcher(); QueryParser qp = new QueryParser(TEST_VERSION_CURRENT, "foo", analyzer) { // LUCENENET specific - to avoid random failures, set the culture // of the QueryParser to invariant Locale = CultureInfo.InvariantCulture }; foreach (string query in queries) { TopDocs ramDocs = ram.Search(qp.Parse(query), 1); TopDocs memDocs = mem.Search(qp.Parse(query), 1); assertEquals(query, ramDocs.TotalHits, memDocs.TotalHits); } reader.Dispose(); } internal class RandomAnalyzerHelper : Analyzer { private readonly MemoryIndexTest outerInstance; public RandomAnalyzerHelper(MemoryIndexTest outerInstance) { this.outerInstance = outerInstance; } protected override TokenStreamComponents CreateComponents(string fieldName, TextReader reader) { Tokenizer tokenizer = new MockTokenizer(reader); return new TokenStreamComponents(tokenizer, new CrazyTokenFilter(tokenizer)); } } /** * Return a random analyzer (Simple, Stop, Standard) to analyze the terms. */ private Analyzer RandomAnalyzer() { switch (Random().nextInt(4)) { case 0: return new MockAnalyzer(Random(), MockTokenizer.SIMPLE, true); case 1: return new MockAnalyzer(Random(), MockTokenizer.SIMPLE, true, MockTokenFilter.ENGLISH_STOPSET); case 2: return new RandomAnalyzerHelper(this); // return new Analyzer() { // protected TokenStreamComponents createComponents(string fieldName, TextReader reader) //{ // Tokenizer tokenizer = new MockTokenizer(reader); // return new TokenStreamComponents(tokenizer, new CrazyTokenFilter(tokenizer)); //} // }; default: return new MockAnalyzer(Random(), MockTokenizer.WHITESPACE, false); } } // a tokenfilter that makes all terms starting with 't' empty strings internal sealed class CrazyTokenFilter : TokenFilter { private readonly ICharTermAttribute termAtt; public CrazyTokenFilter(TokenStream input) : base(input) { termAtt = AddAttribute<ICharTermAttribute>(); } public override bool IncrementToken() { if (m_input.IncrementToken()) { if (termAtt.Length > 0 && termAtt.Buffer[0] == 't') { termAtt.SetLength(0); } return true; } else { return false; } } }; /** * Some terms to be indexed, in addition to random words. * These terms are commonly used in the queries. */ private static readonly string[] TEST_TERMS = {"term", "Term", "tErm", "TERM", "telm", "stop", "drop", "roll", "phrase", "a", "c", "bar", "blar", "gack", "weltbank", "worlbank", "hello", "on", "the", "apache", "Apache", "copyright", "Copyright"}; /** * half of the time, returns a random term from TEST_TERMS. * the other half of the time, returns a random unicode string. */ private string RandomTerm() { if (Random().nextBoolean()) { // return a random TEST_TERM return TEST_TERMS[Random().nextInt(TEST_TERMS.Length)]; } else { // return a random unicode term return TestUtil.RandomUnicodeString(Random()); } } [Test] public void TestDocsEnumStart() { Analyzer analyzer = new MockAnalyzer(Random()); MemoryIndex memory = new MemoryIndex(Random().nextBoolean(), Random().nextInt(50) * 1024 * 1024); memory.AddField("foo", "bar", analyzer); AtomicReader reader = (AtomicReader)memory.CreateSearcher().IndexReader; DocsEnum disi = TestUtil.Docs(Random(), reader, "foo", new BytesRef("bar"), null, null, DocsFlags.NONE); int docid = disi.DocID; assertEquals(-1, docid); assertTrue(disi.NextDoc() != DocIdSetIterator.NO_MORE_DOCS); // now reuse and check again TermsEnum te = reader.GetTerms("foo").GetIterator(null); assertTrue(te.SeekExact(new BytesRef("bar"))); disi = te.Docs(null, disi, DocsFlags.NONE); docid = disi.DocID; assertEquals(-1, docid); assertTrue(disi.NextDoc() != DocIdSetIterator.NO_MORE_DOCS); reader.Dispose(); } private ByteBlockPool.Allocator RandomByteBlockAllocator() { if (Random().nextBoolean()) { return new RecyclingByteBlockAllocator(); } else { return new ByteBlockPool.DirectAllocator(); } } [Test] public void RestDocsAndPositionsEnumStart() { Analyzer analyzer = new MockAnalyzer(Random()); int numIters = AtLeast(3); MemoryIndex memory = new MemoryIndex(true, Random().nextInt(50) * 1024 * 1024); for (int i = 0; i < numIters; i++) { // check reuse memory.AddField("foo", "bar", analyzer); AtomicReader reader = (AtomicReader)memory.CreateSearcher().IndexReader; assertEquals(1, reader.GetTerms("foo").SumTotalTermFreq); DocsAndPositionsEnum disi = reader.GetTermPositionsEnum(new Term("foo", "bar")); int docid = disi.DocID; assertEquals(-1, docid); assertTrue(disi.NextDoc() != DocIdSetIterator.NO_MORE_DOCS); assertEquals(0, disi.NextPosition()); assertEquals(0, disi.StartOffset); assertEquals(3, disi.EndOffset); // now reuse and check again TermsEnum te = reader.GetTerms("foo").GetIterator(null); assertTrue(te.SeekExact(new BytesRef("bar"))); disi = te.DocsAndPositions(null, disi); docid = disi.DocID; assertEquals(-1, docid); assertTrue(disi.NextDoc() != DocIdSetIterator.NO_MORE_DOCS); reader.Dispose(); memory.Reset(); } } // LUCENE-3831 [Test] public void TestNullPointerException() { RegexpQuery regex = new RegexpQuery(new Term("field", "worl.")); SpanQuery wrappedquery = new SpanMultiTermQueryWrapper<RegexpQuery>(regex); MemoryIndex mindex = new MemoryIndex(Random().nextBoolean(), Random().nextInt(50) * 1024 * 1024); mindex.AddField("field", new MockAnalyzer(Random()).GetTokenStream("field", "hello there")); // This throws an NPE assertEquals(0, mindex.Search(wrappedquery), 0.00001f); } // LUCENE-3831 [Test] public void TestPassesIfWrapped() { RegexpQuery regex = new RegexpQuery(new Term("field", "worl.")); SpanQuery wrappedquery = new SpanOrQuery(new SpanMultiTermQueryWrapper<RegexpQuery>(regex)); MemoryIndex mindex = new MemoryIndex(Random().nextBoolean(), Random().nextInt(50) * 1024 * 1024); mindex.AddField("field", new MockAnalyzer(Random()).GetTokenStream("field", "hello there")); // This passes though assertEquals(0, mindex.Search(wrappedquery), 0.00001f); } [Test] public void TestSameFieldAddedMultipleTimes() { MemoryIndex mindex = new MemoryIndex(Random().nextBoolean(), Random().nextInt(50) * 1024 * 1024); MockAnalyzer mockAnalyzer = new MockAnalyzer(Random()); mindex.AddField("field", "the quick brown fox", mockAnalyzer); mindex.AddField("field", "jumps over the", mockAnalyzer); AtomicReader reader = (AtomicReader)mindex.CreateSearcher().IndexReader; assertEquals(7, reader.GetTerms("field").SumTotalTermFreq); PhraseQuery query = new PhraseQuery(); query.Add(new Term("field", "fox")); query.Add(new Term("field", "jumps")); assertTrue(mindex.Search(query) > 0.1); mindex.Reset(); mockAnalyzer.PositionIncrementGap = (1 + Random().nextInt(10)); mindex.AddField("field", "the quick brown fox", mockAnalyzer); mindex.AddField("field", "jumps over the", mockAnalyzer); assertEquals(0, mindex.Search(query), 0.00001f); query.Slop = (10); assertTrue("posGap" + mockAnalyzer.GetPositionIncrementGap("field"), mindex.Search(query) > 0.0001); } [Test] public void TestNonExistingsField() { MemoryIndex mindex = new MemoryIndex(Random().nextBoolean(), Random().nextInt(50) * 1024 * 1024); MockAnalyzer mockAnalyzer = new MockAnalyzer(Random()); mindex.AddField("field", "the quick brown fox", mockAnalyzer); AtomicReader reader = (AtomicReader)mindex.CreateSearcher().IndexReader; assertNull(reader.GetNumericDocValues("not-in-index")); assertNull(reader.GetNormValues("not-in-index")); assertNull(reader.GetTermDocsEnum(new Term("not-in-index", "foo"))); assertNull(reader.GetTermPositionsEnum(new Term("not-in-index", "foo"))); assertNull(reader.GetTerms("not-in-index")); } [Test] public void TestDuellMemIndex() { LineFileDocs lineFileDocs = new LineFileDocs(Random()); int numDocs = AtLeast(10); MemoryIndex memory = new MemoryIndex(Random().nextBoolean(), Random().nextInt(50) * 1024 * 1024); for (int i = 0; i < numDocs; i++) { Store.Directory dir = NewDirectory(); MockAnalyzer mockAnalyzer = new MockAnalyzer(Random()); mockAnalyzer.MaxTokenLength = (TestUtil.NextInt(Random(), 1, IndexWriter.MAX_TERM_LENGTH)); IndexWriter writer = new IndexWriter(dir, NewIndexWriterConfig(Random(), TEST_VERSION_CURRENT, mockAnalyzer)); Document nextDoc = lineFileDocs.NextDoc(); Document doc = new Document(); foreach (IIndexableField field in nextDoc.Fields) { if (field.IndexableFieldType.IsIndexed) { doc.Add(field); if (Random().nextInt(3) == 0) { doc.Add(field); // randomly add the same field twice } } } writer.AddDocument(doc); writer.Dispose(); foreach (IIndexableField field in doc.Fields) { memory.AddField(field.Name, ((Field)field).GetStringValue(), mockAnalyzer); } DirectoryReader competitor = DirectoryReader.Open(dir); AtomicReader memIndexReader = (AtomicReader)memory.CreateSearcher().IndexReader; DuellReaders(competitor, memIndexReader); IOUtils.Dispose(competitor, memIndexReader); memory.Reset(); dir.Dispose(); } lineFileDocs.Dispose(); } // LUCENE-4880 [Test] public void TestEmptyString() { MemoryIndex memory = new MemoryIndex(); memory.AddField("foo", new CannedTokenStream(new Analysis.Token("", 0, 5))); IndexSearcher searcher = memory.CreateSearcher(); TopDocs docs = searcher.Search(new TermQuery(new Term("foo", "")), 10); assertEquals(1, docs.TotalHits); } [Test] public void TestDuelMemoryIndexCoreDirectoryWithArrayField() { string field_name = "text"; MockAnalyzer mockAnalyzer = new MockAnalyzer(Random()); if (Random().nextBoolean()) { mockAnalyzer.OffsetGap = (Random().nextInt(100)); } //index into a random directory FieldType type = new FieldType(TextField.TYPE_STORED); type.StoreTermVectorOffsets = (true); type.StoreTermVectorPayloads = (false); type.StoreTermVectorPositions = (true); type.StoreTermVectors = (true); type.Freeze(); Document doc = new Document(); doc.Add(new Field(field_name, "la la", type)); doc.Add(new Field(field_name, "foo bar foo bar foo", type)); Store.Directory dir = NewDirectory(); IndexWriter writer = new IndexWriter(dir, NewIndexWriterConfig(Random(), TEST_VERSION_CURRENT, mockAnalyzer)); writer.UpdateDocument(new Term("id", "1"), doc); writer.Commit(); writer.Dispose(); DirectoryReader reader = DirectoryReader.Open(dir); //Index document in Memory index MemoryIndex memIndex = new MemoryIndex(true); memIndex.AddField(field_name, "la la", mockAnalyzer); memIndex.AddField(field_name, "foo bar foo bar foo", mockAnalyzer); //compare term vectors Terms ramTv = reader.GetTermVector(0, field_name); IndexReader memIndexReader = memIndex.CreateSearcher().IndexReader; Terms memTv = memIndexReader.GetTermVector(0, field_name); CompareTermVectors(ramTv, memTv, field_name); memIndexReader.Dispose(); reader.Dispose(); dir.Dispose(); } protected void CompareTermVectors(Terms terms, Terms memTerms, string field_name) { TermsEnum termEnum = terms.GetIterator(null); TermsEnum memTermEnum = memTerms.GetIterator(null); while (termEnum.Next() != null) { assertNotNull(memTermEnum.Next()); assertEquals(termEnum.TotalTermFreq, memTermEnum.TotalTermFreq); DocsAndPositionsEnum docsPosEnum = termEnum.DocsAndPositions(null, null, 0); DocsAndPositionsEnum memDocsPosEnum = memTermEnum.DocsAndPositions(null, null, 0); String currentTerm = termEnum.Term.Utf8ToString(); assertEquals("Token mismatch for field: " + field_name, currentTerm, memTermEnum.Term.Utf8ToString()); docsPosEnum.NextDoc(); memDocsPosEnum.NextDoc(); int freq = docsPosEnum.Freq; assertEquals(freq, memDocsPosEnum.Freq); for (int i = 0; i < freq; i++) { string failDesc = " (field:" + field_name + " term:" + currentTerm + ")"; int memPos = memDocsPosEnum.NextPosition(); int pos = docsPosEnum.NextPosition(); assertEquals("Position test failed" + failDesc, memPos, pos); assertEquals("Start offset test failed" + failDesc, memDocsPosEnum.StartOffset, docsPosEnum.StartOffset); assertEquals("End offset test failed" + failDesc, memDocsPosEnum.EndOffset, docsPosEnum.EndOffset); assertEquals("Missing payload test failed" + failDesc, docsPosEnum.GetPayload(), null); } } assertNull("Still some tokens not processed", memTermEnum.Next()); } } }
// 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. // File System.Math.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System { static public partial class Math { public const double PI = 3.1415926535897931; #region Methods and constructors [Pure] public static int Abs(int value) { // F: -2147483648 == Int32.MinValue, but here I do not have a name for it Contract.Requires(value != -2147483648); Contract.Ensures(Contract.Result<int>() >= 0); Contract.Ensures((value - Contract.Result<int>()) <= 0); return default(int); } [Pure] public static long Abs(long value) { Contract.Requires(value != -9223372036854775808L); Contract.Ensures(Contract.Result<long>() >= 0); Contract.Ensures((value - Contract.Result<long>()) <= 0); return default(long); } [Pure] public static sbyte Abs(sbyte value) { Contract.Requires(value != -128); Contract.Ensures(Contract.Result<SByte>() >= 0); Contract.Ensures((value - Contract.Result<sbyte>()) <= 0); return default(sbyte); } [Pure] public static short Abs(short value) { Contract.Requires(value != -32768); Contract.Ensures(Contract.Result<short>() >= 0); Contract.Ensures((value - Contract.Result<short>()) <= 0); return default(short); } [Pure] public static Decimal Abs(Decimal value) { return default(Decimal); } [Pure] public static float Abs(float value) { Contract.Ensures((Contract.Result<float>() >= 0.0) || float.IsNaN(Contract.Result<float>()) || float.IsPositiveInfinity(Contract.Result<float>())); // 2015-03-26: tom-englert // Disabled, since this was too complex for the checker to understand. // e.g. new Rect(0, 0, Math.Abs(a), Math.Abs(b)) raised a warning that with and height are unproven to be positive values. // !NaN ==> >= 0 // Contract.Ensures(float.IsNaN(value) || Contract.Result<float>() >= 0.0); // NaN ==> NaN // Contract.Ensures(!float.IsNaN(value) || float.IsNaN(Contract.Result<float>())); // Infty ==> +Infty // Contract.Ensures(!float.IsInfinity(value) || float.IsPositiveInfinity(Contract.Result<float>())); return default(float); } [Pure] public static double Abs(double value) { Contract.Ensures((Contract.Result<double>() >= 0.0) || double.IsNaN(Contract.Result<double>()) || double.IsPositiveInfinity(Contract.Result<double>())); // 2015-03-26: tom-englert // Disabled, since this was too complex for the checker to understand. // e.g. new Rect(0, 0, Math.Abs(a), Math.Abs(b)) raised a warning that with and height are unproven to be positive values. // !NaN ==> >= 0 // Contract.Ensures(double.IsNaN(value) || Contract.Result<double>() >= 0.0); // NaN ==> NaN // Contract.Ensures(!double.IsNaN(value) || double.IsNaN(Contract.Result<double>())); // Infty ==> +Infty // Contract.Ensures(!double.IsInfinity(value) || double.IsPositiveInfinity(Contract.Result<double>())); return default(double); } [Pure] public static double Acos(double d) { // -1 <= d <= 1 ==> 0<= result <= Pi Contract.Ensures(!(-1 <= d && d <= 1) || Contract.Result<double>() >= 0.0); Contract.Ensures(!(-1 <= d && d <= 1) || Contract.Result<double>() <= Math.PI); // d < -1 || d > 1 ==> NaN Contract.Ensures(!(d < -1 || d > 1) || Double.IsNaN(Contract.Result<double>())); // d == NaN ==> NaN Contract.Ensures(!Double.IsNaN(d) || Double.IsNaN(Contract.Result<double>())); return default(double); } [Pure] public static double Asin(double d) { // -1 <= d <= 1 ==> -Pi/2<= result <= Pi/2 Contract.Ensures(!(-1 <= d && d <= 1) || Contract.Result<double>() >= -Math.PI/2); Contract.Ensures(!(-1 <= d && d <= 1) || Contract.Result<double>() <= Math.PI/2); // d < -1 || d > 1 ==> NaN Contract.Ensures(!(d < -1 || d > 1) || Double.IsNaN(Contract.Result<double>())); // d == NaN ==> NaN Contract.Ensures(!Double.IsNaN(d) || Double.IsNaN(Contract.Result<double>())); return default(double); } [Pure] public static double Atan(double d) { // d != Infty && d != NaN ==> -Pi/2 <= result <= Pi/2 Contract.Ensures(Double.IsNaN(d) || Double.IsInfinity(d) || Contract.Result<double>() >= -Math.PI/2); Contract.Ensures(Double.IsNaN(d) || Double.IsInfinity(d) || Contract.Result<double>() <= Math.PI / 2); // d == Infty ==> Pi/2 Contract.Ensures(!Double.IsNegativeInfinity(d) || Contract.Result<double>() == Math.PI / 2); // d == -Infty ==> -Pi/2 Contract.Ensures(!Double.IsNegativeInfinity(d) || Contract.Result<double>() == -Math.PI / 2); // d == NaN ==> NaN Contract.Ensures(!Double.IsNaN(d) || Double.IsNaN(Contract.Result<double>())); return default(double); } [Pure] public static double Atan2(double y, double x) { // F: TODO: Add contracts. From the MSDN documentation is unclear what should be the behavior when values are infinty return default(double); } #if !SILVERLIGHT [Pure] public static long BigMul(int a, int b) { Contract.Ensures(Contract.Result<long>() == ((long)(a) * (long)(b))); return default(long); } #endif [Pure] public static double Ceiling(double a) { // a == NaN || a is Infty ==> a Contract.Ensures(!(Double.IsInfinity(a) || Double.IsNaN(a)) || Contract.Result<double>().Equals(a)); // Otherwise, result >= a; Contract.Ensures((Double.IsInfinity(a) || Double.IsNaN(a)) || Contract.Result<double>() >= a); return default(double); } #if !SILVERLIGHT [Pure] public static Decimal Ceiling(Decimal d) { return default(Decimal); } #endif [Pure] public static double Cos(double d) { // -9223372036854775295 <= d <= 9223372036854775295 ==> -1 <= result <= 1 Contract.Ensures(!(-9223372036854775295 <= d || d <= 9223372036854775295) || Contract.Result<double>() >= -1.0); Contract.Ensures(!(-9223372036854775295 <= d || d <= 9223372036854775295) || Contract.Result<double>() <= 1.0); // d == NaN || d is Infty ==> NaN Contract.Ensures(!(Double.IsNaN(d) || Double.IsInfinity(d)) || Double.IsNaN(Contract.Result<double>())); return default(double); } [Pure] public static double Cosh(double value) { // value is Infty == > +Infty Contract.Ensures(!Double.IsInfinity(value) || Double.IsPositiveInfinity(Contract.Result<Double>())); // value == NaN ==> NaN Contract.Ensures(!Double.IsNaN(value) || Double.IsNaN(Contract.Result<double>())); return default(double); } #if !SILVERLIGHT [Pure] public static int DivRem(int a, int b, out int result) { Contract.Requires(b != 0); Contract.Ensures(Contract.Result<int>() == ((a / b))); Contract.Ensures(Contract.ValueAtReturn(out result) == (a % b)); return default(int); } [Pure] public static long DivRem(long a, long b, out long result) { Contract.Requires(b != 0); Contract.Ensures(Contract.Result<long>() == ((a / b))); Contract.Ensures(Contract.ValueAtReturn(out result) == (a % b)); return default(long); } #endif [Pure] public static double Exp(double d) { // d != NaN && d is not Infty ==> >= 0.0 Contract.Ensures(Double.IsNaN(d) || Double.IsInfinity(d) || Contract.Result<Double>() >= 0.0); // d == -Infty ==> 0 Contract.Ensures(!Double.IsNegativeInfinity(d) || Contract.Result<Double>() == 0.0); // d == +Inftty ==> +Infty Contract.Ensures(!Double.IsPositiveInfinity(d) || Double.IsPositiveInfinity(Contract.Result<Double>())); // d == NaN ==> NaN Contract.Ensures(!Double.IsNaN(d) || Double.IsNaN(Contract.Result<Double>())); return default(double); } #if !SILVERLIGHT [Pure] public static Decimal Floor(Decimal d) { return default(Decimal); } #endif [Pure] public static double Floor(double d) { // d == NaN || a is Infty ==> d Contract.Ensures(!(Double.IsInfinity(d) || Double.IsNaN(d)) || Contract.Result<double>().Equals(d)); // Otherwise, result <= d; Contract.Ensures(Double.IsInfinity(d) || Double.IsNaN(d) || Contract.Result<double>() <= d); return default(double); } [Pure] public static double IEEERemainder(double x, double y) { return default(double); } [Pure] public static double Log(double d) { // d == 0 ==> -Infty Contract.Ensures(d != 0.0 || Double.IsNegativeInfinity(Contract.Result<double>())); // 0 < d < 1 ==> < 0 Contract.Ensures(!(0.0 < d && d < 1.0) || Contract.Result<double>() < 0); // d == 1 ==> 1 Contract.Ensures(d != 1.0 || Contract.Result<double>() == 0.0); // d > 1 ==> > 1 Contract.Ensures(d < 1.0 || Contract.Result<double>() > 0.0); // d == NaN || d is -Infty ==> Nan Contract.Ensures(!Double.IsNaN(d) || !Double.IsNegativeInfinity(d) || Double.IsNaN(Contract.Result<Double>())); // d is +Infty ==> +Infty Contract.Ensures(!Double.IsPositiveInfinity(d) || Double.IsPositiveInfinity(Contract.Result<Double>())); return default(double); } [Pure] public static double Log10(double d) { // d == 0 ==> -Infty Contract.Ensures(d != 0.0 || Double.IsNegativeInfinity(Contract.Result<double>())); // 0 < d < 1 ==> < 0 Contract.Ensures(!(0.0 < d && d < 1.0) || Contract.Result<double>() < 0); // d == 1 ==> 1 Contract.Ensures(d != 1.0 || Contract.Result<double>() == 0.0); // d > 1 ==> > 1 Contract.Ensures(d < 1.0 || Contract.Result<double>() > 0.0); // d == NaN || d is -Infty ==> Nan Contract.Ensures(!Double.IsNaN(d) || !Double.IsNegativeInfinity(d) || Double.IsNaN(Contract.Result<Double>())); // d is +Infty ==> +Infty Contract.Ensures(!Double.IsPositiveInfinity(d) || Double.IsPositiveInfinity(Contract.Result<Double>())); return default(double); } [Pure] public static double Log(double a, double newBase) { return default(double); } [Pure] public static short Max(short val1, short val2) { Contract.Ensures(Contract.Result<short>() == (val1 > val2 ? val1 : val2)); return default(short); } [Pure] public static byte Max(byte val1, byte val2) { Contract.Ensures(Contract.Result<byte>() == (val1 > val2 ? val1 : val2)); return default(byte); } [Pure] public static sbyte Max(sbyte val1, sbyte val2) { Contract.Ensures(Contract.Result<sbyte>() == (val1 > val2 ? val1 : val2)); return default(sbyte); } [Pure] public static float Max(float val1, float val2) { return default(float); } [Pure] public static ulong Max(ulong val1, ulong val2) { Contract.Ensures(Contract.Result<ulong>() == (val1 > val2 ? val1 : val2)); return default(ulong); } [Pure] public static Decimal Max(Decimal val1, Decimal val2) { return default(Decimal); } [Pure] public static double Max(double val1, double val2) { return default(double); } [Pure] public static long Max(long val1, long val2) { Contract.Ensures(Contract.Result<long>() == (val1 > val2 ? val1 : val2)); return default(long); } [Pure] public static ushort Max(ushort val1, ushort val2) { Contract.Ensures(Contract.Result<ushort>() == (val1 > val2 ? val1 : val2)); return default(ushort); } [Pure] public static int Max(int val1, int val2) { Contract.Ensures(Contract.Result<int>() == (val1 > val2 ? val1 : val2)); return default(int); } [Pure] public static uint Max(uint val1, uint val2) { Contract.Ensures(Contract.Result<uint>() == (val1 > val2 ? val1 : val2)); return default(uint); } [Pure] public static ushort Min(ushort val1, ushort val2) { Contract.Ensures(Contract.Result<ushort>() == (val1 < val2 ? val1 : val2)); return default(ushort); } [Pure] public static int Min(int val1, int val2) { Contract.Ensures(Contract.Result<int>() == (val1 < val2 ? val1 : val2)); return default(int); } [Pure] public static byte Min(byte val1, byte val2) { Contract.Ensures(Contract.Result<byte>() == (val1 < val2 ? val1 : val2)); return default(byte); } [Pure] public static short Min(short val1, short val2) { Contract.Ensures(Contract.Result<short>() == (val1 < val2 ? val1 : val2)); return default(short); } [Pure] public static uint Min(uint val1, uint val2) { Contract.Ensures(Contract.Result<uint>() == (val1 < val2 ? val1 : val2)); return default(uint); } [Pure] public static float Min(float val1, float val2) { return default(float); } [Pure] public static double Min(double val1, double val2) { return default(double); } [Pure] public static long Min(long val1, long val2) { Contract.Ensures(Contract.Result<long>() == (val1 < val2 ? val1 : val2)); return default(long); } [Pure] public static ulong Min(ulong val1, ulong val2) { Contract.Ensures(Contract.Result<ulong>() == (val1 < val2 ? val1 : val2)); return default(ulong); } [Pure] public static Decimal Min(Decimal val1, Decimal val2) { return default(Decimal); } [Pure] public static sbyte Min(sbyte val1, sbyte val2) { Contract.Ensures(Contract.Result<sbyte>() == (val1 < val2 ? val1 : val2)); return default(sbyte); } [Pure] public static double Pow(double x, double y) { // x == NaN or y == NaN ==> NaN Contract.Ensures(!(Double.IsNaN(x) || Double.IsNaN(y)) || Double.IsNaN(Contract.Result<Double>())); // y == 0 ==> 1 Contract.Ensures(!(!Double.IsNaN(x) && y == 0) || Contract.Result<Double>() == 1.0); // x == -infty && y < 0 ==> 0 Contract.Ensures(!(Double.IsNegativeInfinity(x) && y < 0.0) || Contract.Result<Double>() == 0.0); // x == -infty && y > 0 ==> Infty Contract.Ensures(!(Double.IsNegativeInfinity(x) && y > 0.0) || Double.IsInfinity(Contract.Result<Double>())); // x == -1 && y is infty ==> NaN Contract.Ensures(!(x == -1 && Double.IsInfinity(y)) || Double.IsNaN(Contract.Result<Double>())); // -1 < x < 1 && y = -Infty ==> +Infty Contract.Ensures(!(-1 < x && x < 1 && Double.IsNegativeInfinity(y)) || Double.IsPositiveInfinity(Contract.Result<Double>())); // -1 < x < 1 && y = +Infty ==> 0 Contract.Ensures(!(-1 < x && x < 1 && Double.IsPositiveInfinity(y)) || Contract.Result<Double>() == 0.0); // x < -1 || x > 1 && y = - Infty ==> 0 Contract.Ensures(!((x < -1 || x > 1) && Double.IsNegativeInfinity(y)) || Contract.Result<Double>() == 0.0); // x < -1 || x > 1 && y = Infty ==> 0 Contract.Ensures(!((x < -1 || x > 1) && Double.IsPositiveInfinity(y)) || Double.IsPositiveInfinity(Contract.Result<Double>())); // x = 0 and y < 0 ==> +Infty Contract.Ensures(!(x == 0.0 && y < 0.0) || Double.IsPositiveInfinity(Contract.Result<double>())); // x = 0 and y > 0 ==> 0 Contract.Ensures(!(x == 0.0 && y > 0.0) || Contract.Result<double>() == 0.0); // x == 1 && y != NaN Contract.Ensures(!(x == 1 && !Double.IsNaN(y)) || Contract.Result<double>() == 1.0); // x == +infty && y < 0 Contract.Ensures(!(Double.IsPositiveInfinity(y) && y < 0) || Contract.Result<double>() == 0.0); // x == +infty && y < 0 Contract.Ensures(!(Double.IsPositiveInfinity(y) && y > 0) || Double.IsPositiveInfinity(Contract.Result<double>())); return default(double); } #if !SILVERLIGHT [Pure] public static double Round(double value, MidpointRounding mode) { Contract.Requires(Enum.IsDefined(typeof(MidpointRounding), mode)); return default(double); } #endif [Pure] public static double Round(double a) { return default(double); } [Pure] public static Decimal Round(Decimal d) { return default(Decimal); } [Pure] public static double Round(double value, int digits) { Contract.Requires(digits >= 0); Contract.Requires(digits <= 15); return default(double); } #if !SILVERLIGHT [Pure] public static double Round(double value, int digits, MidpointRounding mode) { Contract.Requires(digits >= 0); Contract.Requires(digits <= 15); Contract.Requires(Enum.IsDefined(typeof(MidpointRounding), mode)); return default(double); } [Pure] public static Decimal Round(Decimal d, int decimals, MidpointRounding mode) { Contract.Requires(decimals >= 0); Contract.Requires(decimals <= 28); Contract.Requires(Enum.IsDefined(typeof(MidpointRounding), mode)); return default(Decimal); } [Pure] public static Decimal Round(Decimal d, MidpointRounding mode) { Contract.Requires(Enum.IsDefined(typeof(MidpointRounding), mode)); return default(Decimal); } #endif [Pure] public static Decimal Round(Decimal d, int decimals) { Contract.Requires(decimals >= 0); Contract.Requires(decimals <= 28); return default(Decimal); } [Pure] public static int Sign(Decimal value) { Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() <= 1); return default(int); } [Pure] public static int Sign(sbyte value) { Contract.Ensures(Contract.Result<int>() == (value == 0 ? 0 : (value > 0 ? 1 : -1))); return default(int); } [Pure] public static int Sign(int value) { Contract.Ensures(Contract.Result<int>() == (value == 0 ? 0 : (value > 0 ? 1 : -1))); return default(int); } [Pure] public static int Sign(double value) { Contract.Requires(!Double.IsNaN(value)); Contract.Ensures(Contract.Result<int>() == (value < 0.0 ? -1 : (value > 0.0 ? 1 : 0))); return default(int); } [Pure] public static int Sign(short value) { Contract.Ensures(Contract.Result<int>() == (value == 0 ? 0 : (value > 0 ? 1 : -1))); return default(int); } [Pure] public static int Sign(long value) { Contract.Ensures(Contract.Result<int>() == (value == 0 ? 0 : (value > 0 ? 1 : -1))); return default(int); } [Pure] public static int Sign(float value) { Contract.Requires(!Single.IsNaN(value)); Contract.Ensures(Contract.Result<int>() == (value < 0.0 ? -1 : (value > 0.0 ? 1 : 0))); return default(int); } [Pure] public static double Sin(double a) { // -9223372036854775295 <= a <= 9223372036854775295 ==> -1 <= result <= 1 Contract.Ensures(!(-9223372036854775295 <= a || a <= 9223372036854775295) || Contract.Result<double>() >= -1.0); Contract.Ensures(!(-9223372036854775295 <= a || a <= 9223372036854775295) || Contract.Result<double>() <= 1.0); // d == NaN || d is Infty ==> NaN Contract.Ensures(!(Double.IsNaN(a) || Double.IsInfinity(a)) || Double.IsNaN(Contract.Result<double>())); return default(double); } [Pure] public static double Sinh(double value) { // d == NaN || d is Infty ==> NaN Contract.Ensures(!(Double.IsNaN(value) || Double.IsInfinity(value)) || Contract.Result<double>().Equals(value)); return default(double); } [Pure] public static double Sqrt(double d) { Contract.Ensures(!(d >= 0.0) || Contract.Result<double>() >= 0.0); Contract.Ensures(!(d < 0) || Double.IsNaN(Contract.Result<Double>())); Contract.Ensures(!Double.IsNaN(d) || Double.IsNaN(Contract.Result<Double>())); Contract.Ensures(!Double.IsPositiveInfinity(d) || Double.IsPositiveInfinity(Contract.Result<Double>())); return default(double); } [Pure] public static double Tan(double a) { // d == NaN || d == +Infty ==> d Contract.Ensures(!(Double.IsNaN(a) || Double.IsInfinity(a)) || Contract.Result<Double>().Equals(a) ); return default(double); } [Pure] public static double Tanh(double value) { Contract.Ensures(!Double.IsPositiveInfinity(value) || Contract.Result<Double>() == 1.0); Contract.Ensures(!Double.IsNegativeInfinity(value) || Contract.Result<Double>() == -1.0); Contract.Ensures(!Double.IsNaN(value) || Double.IsNaN(Contract.Result<Double>())); return default(double); } #if !SILVERLIGHT [Pure] public static double Truncate(double d) { Contract.Ensures(!(Double.IsNaN(d) || Double.IsInfinity(d)) || Contract.Result<Double>().Equals(d)); return default(double); } [Pure] public static Decimal Truncate(Decimal d) { return default(Decimal); } #endif #endregion } }
using System; using System.Collections.Generic; using System.Text; using FlatRedBall.Graphics.Model; using FlatRedBall.Math; using System.Collections.ObjectModel; using FlatRedBall.Content.Model.Helpers; using GraphicsDevice = Microsoft.Xna.Framework.Graphics.GraphicsDevice; using ModelMeshXna = Microsoft.Xna.Framework.Graphics.ModelMesh; using BasicEffect = Microsoft.Xna.Framework.Graphics.BasicEffect; using Matrix = Microsoft.Xna.Framework.Matrix; using Vector3 = Microsoft.Xna.Framework.Vector3; using PrimitiveType = Microsoft.Xna.Framework.Graphics.PrimitiveType; #if !SILVERLIGHT using FlatRedBall.Graphics.Lighting; using VertexPositionNormalTexture = Microsoft.Xna.Framework.Graphics.VertexPositionNormalTexture; using VertexPositionTexture = Microsoft.Xna.Framework.Graphics.VertexPositionTexture; using EffectPass = Microsoft.Xna.Framework.Graphics.EffectPass; using EffectTechnique = Microsoft.Xna.Framework.Graphics.EffectTechnique; using ModelMeshPartXna = Microsoft.Xna.Framework.Graphics.ModelMeshPart; using VertexBuffer = Microsoft.Xna.Framework.Graphics.VertexBuffer; using IndexBuffer = Microsoft.Xna.Framework.Graphics.IndexBuffer; using BufferUsage = Microsoft.Xna.Framework.Graphics.BufferUsage; #endif #if SILVERLIGHT #elif !WINDOWS_PHONE using Effect = Microsoft.Xna.Framework.Graphics.Effect; #else using Effect = FlatRedBall.Graphics.GenericEffect; #endif #if XNA4 using DepthStencilState = Microsoft.Xna.Framework.Graphics.DepthStencilState; using RasterizerState = Microsoft.Xna.Framework.Graphics.RasterizerState; using BlendState = Microsoft.Xna.Framework.Graphics.BlendState; #else using RenderState = Microsoft.Xna.Framework.Graphics.RenderState; using CompareFunction = Microsoft.Xna.Framework.Graphics.CompareFunction; using SamplerState = Microsoft.Xna.Framework.Graphics.SamplerState; using TextureAddressMode = Microsoft.Xna.Framework.Graphics.TextureAddressMode; using FillMode = Microsoft.Xna.Framework.Graphics.FillMode; using CullMode = Microsoft.Xna.Framework.Graphics.CullMode; using SaveStateMode = Microsoft.Xna.Framework.Graphics.SaveStateMode; #if !SILVERLIGHT using EffectParameter = Microsoft.Xna.Framework.Graphics.EffectParameter; #endif #endif namespace FlatRedBall.Graphics.Renderers { #region ModelLayer struct internal struct ModelLayer { #region Fields internal int CurrentItem; internal Camera Camera; internal Layer Layer; internal PositionedObjectList<PositionedModel> Models; internal bool DrawnThisFrame; #endregion internal ModelLayer(Camera camera, Layer layer, PositionedObjectList<PositionedModel> models) { CurrentItem = 0; Camera = camera; Layer = layer; Models = models; DrawnThisFrame = false; } } #endregion #region LayerDinition Struct internal struct LayerDefinition { public Camera Camera; public Layer Layer; internal LayerDefinition(Camera camera, Layer layer) { Camera = camera; Layer = layer; } } #endregion public class ModelRenderer #if !SILVERLIGHT : IRenderer #endif { #if !SILVERLIGHT #region Fields private SortMode mSortMode = SortMode.DistanceAlongForwardVector; private Dictionary<LayerDefinition, ModelLayer> mLayers = new Dictionary<LayerDefinition, ModelLayer>(); #if PROFILE static internal int ModelsDrawnThisFrame = 0; #endif #if XNA4 && WINDOWS_PHONE && USING_EMULATOR && DEBUG const bool AllowQuickRender = false; int mMaxNumberOfVertices = 60000; //VertexBuffer mReusableVertexBuffer; //VertexPositionNormalTexture[] mReusableVertexList; //ushort[] mReusableIndexList; //ushort[] mPerInstanceIndexBuffer = new ushort[6000]; //IndexBuffer mReusableIndexBuffer; #else const bool AllowQuickRender = false; #endif #if XNA4 DepthStencilState mDepthStencilState = DepthStencilState.Default; Dictionary<FlatRedBall.Content.Model.Helpers.ModelMeshPart, List<ModelMeshPartRender>> mSortedModelMeshes = new Dictionary<Content.Model.Helpers.ModelMeshPart, List<ModelMeshPartRender>>(); #endif #endregion #region Properties public bool DrawSorted { get { return false; } } public SortMode SortMode { get { return mSortMode; } set { mSortMode = value; } } internal static ReadOnlyCollection<LightBase> AvailableLights { get; set; } #endregion #region Constructor / Initialization public ModelRenderer() { #if XNA4 && WINDOWS_PHONE && USING_EMULATOR && DEBUG //mReusableVertexBuffer = new VertexBuffer(FlatRedBallServices.GraphicsDevice, // typeof(VertexPositionNormalTexture), mMaxNumberOfVertices, BufferUsage.WriteOnly); //mReusableIndexBuffer = new IndexBuffer(FlatRedBallServices.GraphicsDevice, // typeof(ushort), mMaxNumberOfVertices, BufferUsage.WriteOnly); //mReusableVertexList = new VertexPositionNormalTexture[mMaxNumberOfVertices]; //mReusableIndexList = new ushort[mMaxNumberOfVertices]; #endif } #endregion #endif #region Methods #if !SILVERLIGHT public void Prepare(Camera camera) { } public void SetDeviceSettings(Camera camera, RenderMode renderMode) { #region Set device settings for model drawing #if XNA4 Renderer.GraphicsDevice.RasterizerState = RasterizerState.CullClockwise; if (camera.ClearsDepthBuffer) { Renderer.GraphicsDevice.DepthStencilState = DepthStencilState.Default; } //Renderer.GraphicsDevice.SamplerStates[0] = Microsoft.Xna.Framework.Graphics.SamplerState.LinearWrap; Renderer.TextureAddressMode = Microsoft.Xna.Framework.Graphics.TextureAddressMode.Wrap; //throw new NotImplementedException(); // TODO: Gotta set up the device for rendering models. We'll do nothing for now #else RenderState renderState = FlatRedBallServices.GraphicsDevice.RenderState; //renderState.CullMode = CullMode.CullCounterClockwiseFace; renderState.DepthBufferFunction = CompareFunction.Less; renderState.DepthBufferEnable = true; renderState.DepthBufferWriteEnable = true; SamplerState samplerState = FlatRedBallServices.GraphicsDevice.SamplerStates[0]; samplerState.AddressU = TextureAddressMode.Wrap; samplerState.AddressV = TextureAddressMode.Wrap; #endif #endregion } #region Model Drawing Helpers static Matrix[] transforms = new Matrix[100]; private void DrawModel(Camera camera, PositionedModel model, RenderMode renderMode) { #if PROFILE ModelsDrawnThisFrame++; #endif //TimeManager.SumTimeSection("Draw Model Start"); bool flipped = model.FlipX ^ model.FlipY ^ model.FlipZ; #if XNA4 SetCullStateForModel(model, flipped); #else if (model.mDrawWireframe) FlatRedBallServices.GraphicsDevice.RenderState.FillMode = FillMode.WireFrame; switch (model.FaceCullMode) { case ModelFaceCullMode.CullClockwiseFace: if (!flipped) Renderer.GraphicsDevice.RenderState.CullMode = CullMode.CullClockwiseFace; else Renderer.GraphicsDevice.RenderState.CullMode = CullMode.CullCounterClockwiseFace; break; case ModelFaceCullMode.CullCounterClockwiseFace: if (!flipped) Renderer.GraphicsDevice.RenderState.CullMode = CullMode.CullCounterClockwiseFace; else Renderer.GraphicsDevice.RenderState.CullMode = CullMode.CullClockwiseFace; break; case ModelFaceCullMode.None: Renderer.GraphicsDevice.RenderState.CullMode = CullMode.None; break; } #region Reset device settings if they've changed - They may change in a shader FlatRedBallServices.GraphicsDevice.RenderState.DepthBufferEnable = true; FlatRedBallServices.GraphicsDevice.RenderState.DepthBufferWriteEnable = true; #endregion #endif //TimeManager.SumTimeSection("Set depth states"); #if XNA4 // I don't think we need to worry about vertex declarations #else #region Set Vertex Declaration if (model.XnaModel != null) { if (model.XnaModel.Meshes.Count != 0 && model.XnaModel.Meshes[0].MeshParts.Count != 0) { // The assumption is that each mesh part is using the same vertex declaration for the // whole model. Instead of setting the vertex declaration in the DrawMeshPart method we'll // set it up here to save on the number of method calls on the 360. FlatRedBallServices.GraphicsDevice.VertexDeclaration = model.XnaModel.Meshes[0].MeshParts[0].VertexDeclaration; } } #endregion #endif //TimeManager.SumTimeSection("Set vertex declaration"); #region Set Point Light // Find the closest light //int lightIndex = 0; //float distance; Vector3 meshCenter = (model == null) ? Vector3.Zero : model.Position; #endregion #region Draw Model #if WINDOWS_PHONE if (model.XnaModel != null) { model.XnaModel.CopyAbsoluteBoneTransformsTo(transforms); Matrix transformationMatrixFlippedAsNeeded = model.TransformationMatrix; foreach (ModelMeshXna mesh in model.XnaModel.Meshes) { for( int iCurEffect = 0; iCurEffect < mesh.Effects.Count; ++iCurEffect ) { GenericEffect effect = new GenericEffect( mesh.Effects[ iCurEffect ] ); ApplyColorOperation(model, effect); effect.EnableDefaultLighting(); // Set this to false and all is fixed magically! effect.VertexColorEnabled = false; SpriteManager.Camera.SetDeviceViewAndProjection(effect, false); // World can be used to set the mesh's transform effect.World = transforms[mesh.ParentBone.Index] * transformationMatrixFlippedAsNeeded; } mesh.Draw(); } } else if (model.CustomModel != null) { RenderCustomModel(model); } #else #region If using Custom Effect if (model.CustomEffect != null) { // Set technique here if using custom effect model.CustomEffect.SetParameterValues(); EffectTechnique technique = model.EffectCache.GetTechnique( model.CustomEffect.Effect, Renderer.EffectTechniqueNames[(int)renderMode]); if (technique == null && renderMode == RenderMode.Default) { technique = model.CustomEffect.Effect.Techniques[0]; } if (technique != null) { // Draw meshes only if custom effect has the required technique model.CustomEffect.Effect.CurrentTechnique = technique; DrawModelMeshes(camera, model, renderMode); } } #endregion else if (model.CustomModel != null) { RenderCustomModel(model); } else { // Just draw the meshes DrawModelMeshes(camera, model, renderMode); } #endif #endregion //TimeManager.SumTimeSection("DrawModelMeshes"); if (model.mDrawWireframe) { #if XNA4 throw new NotImplementedException(); #else FlatRedBallServices.GraphicsDevice.RenderState.FillMode = FillMode.Solid; #endif } } #if XNA4 private static void SetCullStateForModel(PositionedModel model, bool flipped) { switch (model.FaceCullMode) { case ModelFaceCullMode.CullClockwiseFace: if (!flipped) Renderer.GraphicsDevice.RasterizerState = RasterizerState.CullClockwise; else Renderer.GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise; break; case ModelFaceCullMode.CullCounterClockwiseFace: if (!flipped) Renderer.GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise; else Renderer.GraphicsDevice.RasterizerState = RasterizerState.CullClockwise; break; case ModelFaceCullMode.None: Renderer.GraphicsDevice.RasterizerState = RasterizerState.CullNone; break; } } #endif private static void RenderCustomModel(PositionedModel model) { //There are three things that need to happen here // The first one is common to all CustomModels // The second is code that is unique to unskinned CustomModels // The third is code that is unique to skinned CustomModels bool isSkinned = model.CustomModel.IsSkinnedMesh; bool isAnimated = model.AnimationController != null && model.AnimationController.Matrices != null; if (!isSkinned) //unskinned { if (isAnimated) { int matrixCount = model.AnimationController.Matrices.Length; for (int i = 0; i < matrixCount; i++) { transforms[i] = model.AnimationController.Matrices[i].Transform; } } } else //Skinned { if (isAnimated) { model.CustomModel.SetBones(model.AnimationController.Matrices); } else { model.CustomModel.ResetVertexBuffers(); } } FlatRedBall.Content.Model.Helpers.CustomModel customModel = model.CustomModel; int meshCount = customModel.Meshes.Count; FlatRedBall.Content.Model.Helpers.ModelMesh mesh; #if !WINDOWS_PHONE BasicEffect effect; #else GenericEffect effect; #endif if (customModel.SharesEffects) { #if WINDOWS_PHONE effect = customModel.Meshes[0].MeshParts[0].Effect; #else effect = (BasicEffect)customModel.Meshes[0].MeshParts[0].Effect; #endif PrepareEffectForRendering(model, effect); } Matrix transformationMatrixFlippedAsNeeded = model.TransformationMatrix; for (int meshIndex = 0; meshIndex < meshCount; meshIndex++) { mesh = customModel.Meshes[meshIndex]; if (!isSkinned && isAnimated && mesh.BoneIndex == -1) { int boneCount = model.AnimationController.Matrices.Length; for (int boneIndex = 0; boneIndex < boneCount; boneIndex++) { FlatRedBall.Graphics.Animation3D.Animation3DJoint boneInfo = model.AnimationController.Matrices[boneIndex]; if (mesh.Name == boneInfo.Name) { mesh.BoneIndex = boneIndex; } } } #if !WINDOWS_PHONE && XNA4 //foreach(ModelMeshPart meshPart in mesh.MeshParts) for(int partIndex = 0; partIndex < mesh.MeshParts.Count; partIndex++) { effect = mesh.MeshParts[partIndex].Effect as BasicEffect; #else for (int effectIndex = 0; effectIndex < mesh.Effects.Count; effectIndex++) { #if !WINDOWS_PHONE || !XNA4 effect = (BasicEffect)mesh.Effects[effectIndex]; #else effect = mesh.Effects[effectIndex]; #endif #endif if (!customModel.SharesEffects) { PrepareEffectForRendering(model, effect); } if (!isSkinned && isAnimated && mesh.BoneIndex != -1) { effect.World = transforms[mesh.BoneIndex]; effect.World *= transformationMatrixFlippedAsNeeded; } else effect.World = transformationMatrixFlippedAsNeeded; } mesh.Draw(model.RenderOverrides); } #if false //Copy bone matrices. bool hasBones = model.CustomModel.Bones != null; Matrix[] transforms = null; if (model.AnimationController != null && model.AnimationController.Matrices != null) { model.CustomModel.SetBones(model.AnimationController.Matrices); } else { model.CustomModel.ResetVertexBuffers(); } #if XNA4 if (hasBones) { transforms = new Matrix[model.CustomModel.Bones.Count]; //model.CustomModel.CopyAbsoluteBoneTransformsTo(transforms); for (int i = 0; i < model.CustomModel.Bones.Count; i++) { transforms[i] = model.AnimationController.Matrices[i].Transform; } } FlatRedBallServices.GraphicsDevice.DepthStencilState = DepthStencilState.Default; #endif FlatRedBall.Content.Model.Helpers.CustomModel customModel = model.CustomModel; int meshCount = customModel.Meshes.Count; FlatRedBall.Content.Model.Helpers.ModelMesh mesh; BasicEffect effect; for(int meshIndex = 0; meshIndex < meshCount; meshIndex++) { mesh = customModel.Meshes[meshIndex]; for(int effectIndex = 0; effectIndex < mesh.Effects.Count; effectIndex++) { effect = (BasicEffect)mesh.Effects[effectIndex]; if (AvailableLights != null && AvailableLights.Count > 0) { effect.EnableDefaultLighting(); //Start by turning off all the lights. effect.DirectionalLight0.Enabled = effect.DirectionalLight1.Enabled = effect.DirectionalLight2.Enabled = false; //This tracks which directional light in the shader we are working with. int effectLightIndex = 0; //Loop through all lights for (int i = 0; i < AvailableLights.Count; i++) { LightBase baseLight = AvailableLights[i]; if (baseLight.Enabled) { if (baseLight is AmbientLight) { SetAmbientLight(effect, baseLight); } else { #if XNA4 Microsoft.Xna.Framework.Graphics.DirectionalLight directionalLight; if (effectLightIndex == 0) directionalLight = effect.DirectionalLight0; else if (effectLightIndex == 1) directionalLight = effect.DirectionalLight1; else directionalLight = effect.DirectionalLight2; SetDirectionalLight(directionalLight, baseLight, model.Position); effectLightIndex++; #endif } } } } else { effect.EnableDefaultLighting(); effect.DirectionalLight0.Enabled = effect.DirectionalLight1.Enabled = effect.DirectionalLight2.Enabled = false; effect.AmbientLightColor = Vector3.Zero; } // Set this to false and all is fixed magically! effect.VertexColorEnabled = false; ApplyColorOperation(model, effect); effect.World = model.TransformationMatrix; if (hasBones && mesh.ParentBone != null) { effect.World *= transforms[mesh.ParentBone.Index]; } SpriteManager.Camera.SetDeviceViewAndProjection(effect, false); } mesh.Draw(model.RenderOverrides); } #endif } #if WINDOWS_PHONE private static void PrepareEffectForRendering(PositionedModel model, GenericEffect effect) #else private static void PrepareEffectForRendering(PositionedModel model, BasicEffect effect) #endif { ApplyLighting(model, effect); // Set this to false and all is fixed magically! effect.VertexColorEnabled = false; ApplyColorOperation(model, effect); SpriteManager.Camera.SetDeviceViewAndProjection(effect, false); } private void DrawModelMeshes(Camera camera, PositionedModel model, RenderMode renderMode) { switch (model.LodType) { case PositionedModel.LodTypes.Mesh: #region Mesh-Based LOD // Get the mesh index int l = model.LodMeshOrder.Count - 1; float dist = Vector3.Distance(camera.Position, model.Position); while (model.LodMeshOrder[l].LodDistance > dist && l > 0) { l--; } // Set parameters and draw the mesh ModelMeshXna lodMesh = model.XnaModel.Meshes[model.LodMeshOrder[l].MeshId]; // Draw the mesh DrawMesh(camera, model, model.LodMeshOrder[l].MeshId, renderMode); #endregion break; case PositionedModel.LodTypes.None: default: #region No LOD (Draw whole model) int meshCount = model.XnaModel.Meshes.Count; for (int i = 0; i < meshCount; i++) { DrawMesh(camera, model, i, renderMode); } #endregion break; } } private void DrawMesh(Camera camera, PositionedModel model, int meshIndex, RenderMode renderMode) { #if XNA4 throw new NotImplementedException(); #else //TimeManager.SumTimeSection("Start of DrawMesh"); ModelMeshXna mesh = model.XnaModel.Meshes[meshIndex]; if (model.CustomEffect != null) { #region Draw using custom effect model.CustomEffect.Effect.Begin(SaveStateMode.None); FlatRedBallServices.GraphicsDevice.Indices = mesh.IndexBuffer; for (int i = 0; i < model.CustomEffect.Effect.CurrentTechnique.Passes.Count; i++) { EffectPass pass = model.CustomEffect.Effect.CurrentTechnique.Passes[i]; pass.Begin(); for (int partIndex = 0; partIndex < mesh.MeshParts.Count; partIndex++) { ModelMeshPartXna part = mesh.MeshParts[partIndex]; // Set parameters //SetPartEffectParameters(model, model.CustomEffect.Effect, meshIndex, part); #region Set the world matrix for the World Effect Parameter // Get parameters EffectParameter worldParameter = model.mEffectCache[model.CustomEffect.Effect, EffectCache.EffectParameterNames[(int)EffectCache.EffectParameterNamesEnum.World]]; if (worldParameter != null) worldParameter.SetValue(model.mBoneWorldTransformations[meshIndex]); #endregion model.CustomEffect.Effect.CommitChanges(); // Just draw the part - the effect has been taken care of already DrawMeshPart(mesh, part); } pass.End(); } model.CustomEffect.Effect.End(); #endregion } else { #region Draw parts with their own effects Effect effect; FlatRedBallServices.GraphicsDevice.Indices = mesh.IndexBuffer; for (int i = 0; i < mesh.MeshParts.Count; i++) { ModelMeshPartXna part = mesh.MeshParts[i]; effect = part.Effect; //TimeManager.SumTimeSection("Start of meshpart loop"); // Check if the effect has the required technique EffectTechnique technique = null;// = model.EffectCache.GetTechnique( //effect, Renderer.EffectTechniqueNames[(int)renderMode]); //if (Renderer.LightingEnabled) //{ // switch (model.LightingMethod) // { // case PositionedModel.LightingType.None: // technique = model.EffectCache.GetTechnique(effect, "Default"); // break; // case PositionedModel.LightingType.Ambient: // technique = model.EffectCache.GetTechnique(effect, "AmbientOnly"); // break; // case PositionedModel.LightingType.Diffuse: // technique = model.EffectCache.GetTechnique(effect, "DiffuseOnly"); // break; // case PositionedModel.LightingType.Specular: // technique = model.EffectCache.GetTechnique(effect, "SpecularOnly"); // break; // case (PositionedModel.LightingType.Ambient | PositionedModel.LightingType.Diffuse): // technique = model.EffectCache.GetTechnique(effect, "AmbientAndDiffuse"); // break; // case (PositionedModel.LightingType.Ambient | PositionedModel.LightingType.Specular): // technique = model.EffectCache.GetTechnique(effect, "AmbientAndSpecular"); // break; // case (PositionedModel.LightingType.Diffuse | PositionedModel.LightingType.Specular): // technique = model.EffectCache.GetTechnique(effect, "DiffuseAndSpecular"); // break; // case PositionedModel.LightingType.All: // technique = model.EffectCache.GetTechnique(effect, "AmbientDiffuseSpecular"); // break; // } //} //else { technique = model.EffectCache.GetTechnique(effect, "Default"); } if (technique == null && renderMode == RenderMode.Default) { technique = model.EffectCache.GetTechnique(effect, "Default");// effect.Techniques[0]; } //TimeManager.SumTimeSection("Get technique"); if (technique != null) { // Set the technique and draw the part effect.CurrentTechnique = technique; if (!model.mHasClonedEffects) { #region Set the world matrix for the World Effect Parameter // Get parameters EffectParameter worldParameter = model.mEffectCache[effect, EffectCache.EffectParameterNames[(int)EffectCache.EffectParameterNamesEnum.World]]; if (worldParameter != null) worldParameter.SetValue(model.mBoneWorldTransformations[meshIndex]); #endregion } /// This code, is the old Drawing code. This is all done in the mesh.Draw() method and is not needed. /// However vic would like to keep this code here, incase something isn't right after release. /// then we can go back and return it to it's original state. #region OldCode //// Pulled this out of the foreach loop since it looks like it only //// has to be done once //FlatRedBallServices.GraphicsDevice.Vertices[0].SetSource( // mesh.VertexBuffer, part.StreamOffset, part.VertexStride); //TimeManager.SumTimeSection("Set effect Parameters"); // Draw the part //effect.Begin(SaveStateMode.None); //for (int passIndex = 0; passIndex < effect.CurrentTechnique.Passes.Count; passIndex++) //{ // EffectPass pass = effect.CurrentTechnique.Passes[passIndex]; // pass.Begin(); // // Contents of DrawMeshPart are below and just outside // // of the foreach for performance reasons. // // DrawMeshPart(mesh, part); // //if (part.NumVertices > 0) // //{ // // FlatRedBallServices.GraphicsDevice.DrawIndexedPrimitives( // // PrimitiveType.TriangleList, // // part.BaseVertex, // // 0, // // part.NumVertices, // // part.StartIndex, // // part.PrimitiveCount); // //} // pass.End(); //} //effect.End(); mesh.Draw(SaveStateMode.None); #endregion //TimeManager.SumTimeSection("DrawMeshPart"); } } #endregion } #endif } private void DrawMeshPart(ModelMeshXna mesh, ModelMeshPartXna part) { #if XNA4 throw new NotImplementedException(); #else // Draw part FlatRedBallServices.GraphicsDevice.Vertices[0].SetSource( mesh.VertexBuffer, part.StreamOffset, part.VertexStride); FlatRedBallServices.GraphicsDevice.DrawIndexedPrimitives( PrimitiveType.TriangleList, part.BaseVertex, 0, part.NumVertices, part.StartIndex, part.PrimitiveCount); #endif } #endregion public void Draw(Camera camera, Layer layer, RenderMode renderMode) { PositionedObjectList<PositionedModel> listToDraw = null; List< RenderOverrideBatch > batchesToDraw = null; if (layer != null) { listToDraw = layer.mModels; } else { listToDraw = ModelManager.mDrawnModels; if (ModelManager.mRenderOverrideBatches != null && ModelManager.mRenderOverrideBatches.Count > 0) { batchesToDraw = ModelManager.mRenderOverrideBatches; } } if (listToDraw.Count == 0 && (batchesToDraw == null || batchesToDraw.Count == 0)) { return; } //TimeManager.TimeSection("1"); #if XNA4 foreach (KeyValuePair<FlatRedBall.Content.Model.Helpers.ModelMeshPart, List<ModelMeshPartRender>> kvp in mSortedModelMeshes) { kvp.Value.Clear(); } #endif // Draw the positioned models for (int i = 0; i < listToDraw.Count; i++) { PositionedModel model = listToDraw[i]; DrawModelOrAddToSortedDictionary(camera, renderMode, model); } // Draw the render override batches if there are any if (batchesToDraw != null) { for (int iCurBatch = 0; iCurBatch < batchesToDraw.Count; iCurBatch++) { batchesToDraw[iCurBatch].Draw(camera); } } //TimeManager.TimeSection("2"); #region Render everything in the dictionary #if XNA4 //if (AllowQuickRender) //{ // lastEffect = null; // foreach (KeyValuePair<FlatRedBall.Content.Model.Helpers.ModelMeshPart, List<ModelMeshPartRender>> kvp in mSortedModelMeshes) // { // RenderMmprList(kvp.Value); // } //} #endif //TimeManager.TimeSection("3"); #endregion } #if XNA4 //GenericEffect lastEffect = null; #endif // private void RenderMmprList(List<ModelMeshPartRender> list) // { //#if XNA4 && WINDOWS_PHONE && USING_EMULATOR && DEBUG // if (list.Count != 0) // { // GenericEffect effectToUse = list[0].ModelMeshPart.Effect; // FlatRedBall.Content.Model.Helpers.ModelMeshPart modelMeshPart = // list[0].ModelMeshPart; // GraphicsDevice graphicsDevice = Renderer.GraphicsDevice; // // temporary to test things out: // Renderer.GraphicsDevice.RasterizerState = RasterizerState.CullNone; // // TODO: Apply lighting // if (!LightManager.EnableLighting) // { // effectToUse.LightingEnabled = false; // } // // This causes problems // // effectToUse.VertexColorEnabled = true; // /* // // TODO: ApplyColorOperation // effectToUse.EmissiveColor = Vector3.Zero; // effectToUse.DiffuseColor = Vector3.One; // */ // int indexIncrementPerModelMeshPart = modelMeshPart.PrimitiveCount * 3; // for (int i = 0; i < indexIncrementPerModelMeshPart; i++) // { // mPerInstanceIndexBuffer[i] = modelMeshPart.mIndexList[i + modelMeshPart.StartIndex]; // } // // Assumes 1 pass // if( effectToUse.GetCurrentTechnique(true).Passes.Count > 1 ) // { // throw new InvalidOperationException("The new efficient rendering system only supports effects with 1 render pass"); // } // BlendState previousState = FlatRedBallServices.GraphicsDevice.BlendState; // EffectPass effectPass; // if (lastEffect != effectToUse) // { // SpriteManager.Camera.SetDeviceViewAndProjection(effectToUse, false); // effectPass = effectToUse.GetCurrentTechnique( true ).Passes[0]; // effectPass.Apply(); // lastEffect = effectToUse; // } // int reusableIndex = 0; // VertexPositionNormalTexture tempVertex = new VertexPositionNormalTexture(); // Vector3 tempVector = new Vector3(); // Matrix matrix; // int mmprIndex = 0; // VertexPositionNormalTexture[] verticesToCopy = modelMeshPart.CpuVertices; // foreach (ModelMeshPartRender mmpr in list) // { // if (mmpr.PreCalculatedVerts != null) // { // mmpr.PreCalculatedVerts.CopyTo( // mReusableVertexList, reusableIndex); // reusableIndex += mmpr.PreCalculatedVerts.Length; // //for (int i = 0; i < verticesToCopy.Length; i++) // //{ // // mReusableVertexList[reusableIndex] = mmpr.PreCalculatedVerts[i]; // // reusableIndex++; // //} // } // else // { // matrix = mmpr.World; // for (int i = 0; i < verticesToCopy.Length; i++) // { // tempVertex = verticesToCopy[i]; // tempVector.X = tempVertex.Position.X; // tempVector.Y = tempVertex.Position.Y; // tempVector.Z = tempVertex.Position.Z; // MathFunctions.TransformVector(ref tempVector, ref matrix); // tempVertex.Position.X = tempVector.X; // tempVertex.Position.Y = tempVector.Y; // tempVertex.Position.Z = tempVector.Z; // mReusableVertexList[reusableIndex] = tempVertex; // reusableIndex++; // } // } // ushort extraAmountDestination = (ushort)(mmprIndex * indexIncrementPerModelMeshPart); // ushort extraAmountSource = (ushort)(mmprIndex * verticesToCopy.Length); // for (int i = indexIncrementPerModelMeshPart - 1; i > -1; i--) // //for (int i = 0; i < indexIncrementPerModelMeshPart; i++) // { // mReusableIndexList[i + extraAmountDestination] = (ushort)(mPerInstanceIndexBuffer[i] + extraAmountSource); // } // //graphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, modelMeshPart.numVertices, modelMeshPart.startIndex, modelMeshPart.primitiveCount); // mmprIndex++; // /* // if (mmpr.RenderOverrides != null) // { // for (int i = 0; i < mmpr.RenderOverrides.Count; i++) // { // mmpr.RenderOverrides[i].Apply(ref modelMeshPart.vertexBuffer); // graphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, modelMeshPart.numVertices, modelMeshPart.startIndex, modelMeshPart.primitiveCount); // } // } // */ // } // int numberOfVerts = reusableIndex; // int numberOfIndices = mmprIndex * indexIncrementPerModelMeshPart; // int numberOfPrimitives = numberOfIndices / 3; // mReusableVertexBuffer.SetData<VertexPositionNormalTexture>(mReusableVertexList, 0, numberOfVerts); // mReusableIndexBuffer.SetData<ushort>(mReusableIndexList, 0, numberOfIndices); // FlatRedBallServices.GraphicsDevice.SetVertexBuffer(mReusableVertexBuffer); // FlatRedBallServices.GraphicsDevice.Indices = mReusableIndexBuffer; // graphicsDevice.DrawIndexedPrimitives( // PrimitiveType.TriangleList, 0, 0, numberOfVerts, 0, numberOfPrimitives); // FlatRedBallServices.GraphicsDevice.SetVertexBuffer(null); // FlatRedBallServices.GraphicsDevice.Indices = null; // FlatRedBallServices.GraphicsDevice.BlendState = previousState; // } //#else // throw new NotImplementedException(); //#endif // } private void DrawModelOrAddToSortedDictionary(Camera camera, RenderMode renderMode, PositionedModel model) { if (model.Visible && (camera.CameraModelCullMode == CameraModelCullMode.None || camera.IsModelInView(model))) { if (model.AnimationController == null && model.CustomModel != null && AllowQuickRender) { #if XNA4 Matrix transformationMatrixFlippedAsNeeded = model.TransformationMatrix; foreach (FlatRedBall.Content.Model.Helpers.ModelMesh mesh in model.CustomModel.Meshes) { foreach (FlatRedBall.Content.Model.Helpers.ModelMeshPart meshPart in mesh.MeshParts) { // It's okay if we call this over and over, // it has a bool which it uses internally to // make sure there isn't unnecessary copying of // verts. meshPart.ResetVertexBuffer(); ModelMeshPartRender mmpr = new ModelMeshPartRender(); mmpr.ModelMeshPart = meshPart; if (model.RenderOverrides != null && model.RenderOverrides.ContainsKey(meshPart)) { mmpr.RenderOverrides = model.RenderOverrides[meshPart]; } mmpr.World = transformationMatrixFlippedAsNeeded; if (!model.IsAutomaticallyUpdated) { mmpr.PreCalculatedVerts = model.mPrecalculatedVertices[meshPart]; } if (mSortedModelMeshes.ContainsKey(meshPart)) { mSortedModelMeshes[meshPart].Add(mmpr); } else { List<ModelMeshPartRender> newList = new List<ModelMeshPartRender>(); newList.Add(mmpr); mSortedModelMeshes.Add(meshPart, newList); } } } #endif } else { DrawModel(camera, model, renderMode); } } } #endif internal void ClearRenderingDictionary() { #if XNA4 mSortedModelMeshes.Clear(); #endif } #if !SILVERLIGHT public float GetNextObjectDepth(Camera camera, Layer layer) { return 0f; } public bool HasObjectsLeftToDraw(Camera camera, Layer layer) { LayerDefinition def = new LayerDefinition(camera, layer); if (mLayers.ContainsKey(def)) return mLayers[def].DrawnThisFrame; else return true; } public void RemoveLayer(Camera camera, Layer layer) { LayerDefinition def = new LayerDefinition(camera, layer); if (mLayers.ContainsKey(def)) mLayers.Remove(def); } #region Lighting Helpers #if XNA4 protected static void SetDirectionalLight(Microsoft.Xna.Framework.Graphics.DirectionalLight directionalLight, LightBase light, Vector3 objectPosition) { directionalLight.DiffuseColor = light.DiffuseColor; directionalLight.SpecularColor = light.SpecularColor; directionalLight.Direction = light.GetDirectionTo(objectPosition); directionalLight.Enabled = true; } #endif protected static void SetAmbientLight(Microsoft.Xna.Framework.Graphics.BasicEffect effect, LightBase light) { effect.AmbientLightColor = light.DiffuseColor; } #if XNA4 protected static void SetAmbientLight(GenericEffect effect, LightBase light) { effect.AmbientLightColor = light.DiffuseColor; } #endif #endregion #if !WINDOWS_PHONE private static void ApplyColorOperation(PositionedModel model, BasicEffect effect) #else private static void ApplyColorOperation(PositionedModel model, GenericEffect effect) #endif { switch (model.ColorOperation) { case ColorOperation.None: effect.EmissiveColor = Vector3.Zero; effect.DiffuseColor = Vector3.One; effect.Alpha = model.Alpha; effect.TextureEnabled = true; break; case ColorOperation.Add: effect.EmissiveColor = new Vector3(model.Red, model.Green, model.Blue); effect.DiffuseColor = Vector3.Zero; effect.Alpha = model.Alpha; effect.TextureEnabled = true; break; case ColorOperation.Modulate: effect.EmissiveColor = Vector3.Zero; effect.DiffuseColor = new Vector3(model.Red, model.Green, model.Blue); effect.Alpha = model.Alpha; effect.TextureEnabled = true; break; case ColorOperation.Color: effect.EmissiveColor = Vector3.Zero; effect.DiffuseColor = new Vector3(model.Red, model.Green, model.Blue); effect.Alpha = model.Alpha; effect.TextureEnabled = false; break; default: throw new NotImplementedException("Models do not support the color operation " + model.ColorOperation); //break; } } private static void ApplyLighting(PositionedModel model, BasicEffect effect) { if (!LightManager.EnableLighting) { effect.LightingEnabled = false; } else if (AvailableLights != null && AvailableLights.Count > 0) { //effect.EnableDefaultLighting(); //Start by turning off all the lights. effect.LightingEnabled = true; effect.DirectionalLight0.Enabled = effect.DirectionalLight1.Enabled = effect.DirectionalLight2.Enabled = false; //This tracks which directional light in the shader we are working with. int effectLightIndex = 0; //Loop through all lights for (int i = 0; i < AvailableLights.Count; i++) { LightBase baseLight = AvailableLights[i]; if (baseLight.Enabled) { if (baseLight is AmbientLight) { SetAmbientLight(effect, baseLight); } else { #if XNA4 Microsoft.Xna.Framework.Graphics.DirectionalLight directionalLight; if (effectLightIndex == 0) directionalLight = effect.DirectionalLight0; else if (effectLightIndex == 1) directionalLight = effect.DirectionalLight1; else directionalLight = effect.DirectionalLight2; SetDirectionalLight(directionalLight, baseLight, model.Position); effectLightIndex++; #endif } } } } else { effect.EnableDefaultLighting(); effect.DirectionalLight0.Enabled = effect.DirectionalLight1.Enabled = effect.DirectionalLight2.Enabled = false; effect.AmbientLightColor = Vector3.Zero; } } #if XNA4 private static void ApplyLighting(PositionedModel model, GenericEffect effect) { if (!LightManager.EnableLighting) { effect.LightingEnabled = false; } else if (AvailableLights != null && AvailableLights.Count > 0) { //effect.EnableDefaultLighting(); //Start by turning off all the lights. effect.LightingEnabled = true; effect.DirectionalLight0.Enabled = effect.DirectionalLight1.Enabled = effect.DirectionalLight2.Enabled = false; //This tracks which directional light in the shader we are working with. int effectLightIndex = 0; //Loop through all lights for (int i = 0; i < AvailableLights.Count; i++) { LightBase baseLight = AvailableLights[i]; if (baseLight.Enabled) { if (baseLight is AmbientLight) { SetAmbientLight(effect, baseLight); } else { Microsoft.Xna.Framework.Graphics.DirectionalLight directionalLight; if (effectLightIndex == 0) directionalLight = effect.DirectionalLight0; else if (effectLightIndex == 1) directionalLight = effect.DirectionalLight1; else directionalLight = effect.DirectionalLight2; SetDirectionalLight(directionalLight, baseLight, model.Position); effectLightIndex++; } } } } else { effect.EnableDefaultLighting(); effect.DirectionalLight0.Enabled = effect.DirectionalLight1.Enabled = effect.DirectionalLight2.Enabled = false; effect.AmbientLightColor = Vector3.Zero; } } #endif #endif #endregion } }
/* * 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. */ // Distributed under the Thrift Software License // // See accompanying file LICENSE or visit the Thrift site at: // http://developers.facebook.com/thrift/ using System; using System.Collections.Generic; using System.Security.Cryptography.X509Certificates; using Thrift.Collections; using Thrift.Test; //generated code using Thrift.Transport; using Thrift.Protocol; using Thrift.Server; namespace Test { public class TestServer { public class TradeServerEventHandler : TServerEventHandler { public int callCount = 0; public void preServe() { callCount++; } public Object createContext(Thrift.Protocol.TProtocol input, Thrift.Protocol.TProtocol output) { callCount++; return null; } public void deleteContext(Object serverContext, Thrift.Protocol.TProtocol input, Thrift.Protocol.TProtocol output) { callCount++; } public void processContext(Object serverContext, Thrift.Transport.TTransport transport) { callCount++; } }; public class TestHandler : ThriftTest.Iface { public TServer server; public TestHandler() { } public void testVoid() { Console.WriteLine("testVoid()"); } public string testString(string thing) { Console.WriteLine("teststring(\"" + thing + "\")"); return thing; } public bool testBool(bool thing) { Console.WriteLine("testBool(" + thing + ")"); return thing; } public sbyte testByte(sbyte thing) { Console.WriteLine("testByte(" + thing + ")"); return thing; } public int testI32(int thing) { Console.WriteLine("testI32(" + thing + ")"); return thing; } public long testI64(long thing) { Console.WriteLine("testI64(" + thing + ")"); return thing; } public double testDouble(double thing) { Console.WriteLine("testDouble(" + thing + ")"); return thing; } public byte[] testBinary(byte[] thing) { string hex = BitConverter.ToString(thing).Replace("-", string.Empty); Console.WriteLine("testBinary(" + hex + ")"); return thing; } public Xtruct testStruct(Xtruct thing) { Console.WriteLine("testStruct({" + "\"" + thing.String_thing + "\", " + thing.Byte_thing + ", " + thing.I32_thing + ", " + thing.I64_thing + "})"); return thing; } public Xtruct2 testNest(Xtruct2 nest) { Xtruct thing = nest.Struct_thing; Console.WriteLine("testNest({" + nest.Byte_thing + ", {" + "\"" + thing.String_thing + "\", " + thing.Byte_thing + ", " + thing.I32_thing + ", " + thing.I64_thing + "}, " + nest.I32_thing + "})"); return nest; } public Dictionary<int, int> testMap(Dictionary<int, int> thing) { Console.WriteLine("testMap({"); bool first = true; foreach (int key in thing.Keys) { if (first) { first = false; } else { Console.WriteLine(", "); } Console.WriteLine(key + " => " + thing[key]); } Console.WriteLine("})"); return thing; } public Dictionary<string, string> testStringMap(Dictionary<string, string> thing) { Console.WriteLine("testStringMap({"); bool first = true; foreach (string key in thing.Keys) { if (first) { first = false; } else { Console.WriteLine(", "); } Console.WriteLine(key + " => " + thing[key]); } Console.WriteLine("})"); return thing; } public THashSet<int> testSet(THashSet<int> thing) { Console.WriteLine("testSet({"); bool first = true; foreach (int elem in thing) { if (first) { first = false; } else { Console.WriteLine(", "); } Console.WriteLine(elem); } Console.WriteLine("})"); return thing; } public List<int> testList(List<int> thing) { Console.WriteLine("testList({"); bool first = true; foreach (int elem in thing) { if (first) { first = false; } else { Console.WriteLine(", "); } Console.WriteLine(elem); } Console.WriteLine("})"); return thing; } public Numberz testEnum(Numberz thing) { Console.WriteLine("testEnum(" + thing + ")"); return thing; } public long testTypedef(long thing) { Console.WriteLine("testTypedef(" + thing + ")"); return thing; } public Dictionary<int, Dictionary<int, int>> testMapMap(int hello) { Console.WriteLine("testMapMap(" + hello + ")"); Dictionary<int, Dictionary<int, int>> mapmap = new Dictionary<int, Dictionary<int, int>>(); Dictionary<int, int> pos = new Dictionary<int, int>(); Dictionary<int, int> neg = new Dictionary<int, int>(); for (int i = 1; i < 5; i++) { pos[i] = i; neg[-i] = -i; } mapmap[4] = pos; mapmap[-4] = neg; return mapmap; } public Dictionary<long, Dictionary<Numberz, Insanity>> testInsanity(Insanity argument) { Console.WriteLine("testInsanity()"); Xtruct hello = new Xtruct(); hello.String_thing = "Hello2"; hello.Byte_thing = 2; hello.I32_thing = 2; hello.I64_thing = 2; Xtruct goodbye = new Xtruct(); goodbye.String_thing = "Goodbye4"; goodbye.Byte_thing = (sbyte)4; goodbye.I32_thing = 4; goodbye.I64_thing = (long)4; Insanity crazy = new Insanity(); crazy.UserMap = new Dictionary<Numberz, long>(); crazy.UserMap[Numberz.EIGHT] = (long)8; crazy.Xtructs = new List<Xtruct>(); crazy.Xtructs.Add(goodbye); Insanity looney = new Insanity(); crazy.UserMap[Numberz.FIVE] = (long)5; crazy.Xtructs.Add(hello); Dictionary<Numberz, Insanity> first_map = new Dictionary<Numberz, Insanity>(); Dictionary<Numberz, Insanity> second_map = new Dictionary<Numberz, Insanity>(); ; first_map[Numberz.TWO] = crazy; first_map[Numberz.THREE] = crazy; second_map[Numberz.SIX] = looney; Dictionary<long, Dictionary<Numberz, Insanity>> insane = new Dictionary<long, Dictionary<Numberz, Insanity>>(); insane[(long)1] = first_map; insane[(long)2] = second_map; return insane; } public Xtruct testMulti(sbyte arg0, int arg1, long arg2, Dictionary<short, string> arg3, Numberz arg4, long arg5) { Console.WriteLine("testMulti()"); Xtruct hello = new Xtruct(); ; hello.String_thing = "Hello2"; hello.Byte_thing = arg0; hello.I32_thing = arg1; hello.I64_thing = arg2; return hello; } /** * Print 'testException(%s)' with arg as '%s' * @param string arg - a string indication what type of exception to throw * if arg == "Xception" throw Xception with errorCode = 1001 and message = arg * elsen if arg == "TException" throw TException * else do not throw anything */ public void testException(string arg) { Console.WriteLine("testException(" + arg + ")"); if (arg == "Xception") { Xception x = new Xception(); x.ErrorCode = 1001; x.Message = arg; throw x; } if (arg == "TException") { throw new Thrift.TException(); } return; } public Xtruct testMultiException(string arg0, string arg1) { Console.WriteLine("testMultiException(" + arg0 + ", " + arg1 + ")"); if (arg0 == "Xception") { Xception x = new Xception(); x.ErrorCode = 1001; x.Message = "This is an Xception"; throw x; } else if (arg0 == "Xception2") { Xception2 x = new Xception2(); x.ErrorCode = 2002; x.Struct_thing = new Xtruct(); x.Struct_thing.String_thing = "This is an Xception2"; throw x; } Xtruct result = new Xtruct(); result.String_thing = arg1; return result; } public void testStop() { if (server != null) { server.Stop(); } } public void testOneway(int arg) { Console.WriteLine("testOneway(" + arg + "), sleeping..."); System.Threading.Thread.Sleep(arg * 1000); Console.WriteLine("testOneway finished"); } } // class TestHandler public static bool Execute(string[] args) { try { bool useBufferedSockets = false, useFramed = false, useEncryption = false, compact = false, json = false; int port = 9090; string pipe = null; string certPath = "../../../../../keys/server.pem"; for (int i = 0; i < args.Length; i++) { if (args[i] == "-pipe") // -pipe name { pipe = args[++i]; } else if (args[i].Contains("--port=")) { port = int.Parse(args[i].Substring(args[i].IndexOf("=")+1)); } else if (args[i] == "-b" || args[i] == "--buffered" || args[i] == "--transport=buffered") { useBufferedSockets = true; } else if (args[i] == "-f" || args[i] == "--framed" || args[i] == "--transport=framed") { useFramed = true; } else if (args[i] == "--compact" || args[i] == "--protocol=compact") { compact = true; } else if (args[i] == "--json" || args[i] == "--protocol=json") { json = true; } else if (args[i] == "--ssl") { useEncryption = true; } else if (args[i].StartsWith("--cert=")) { certPath = args[i].Substring("--cert=".Length); } } // Processor TestHandler testHandler = new TestHandler(); ThriftTest.Processor testProcessor = new ThriftTest.Processor(testHandler); // Transport TServerTransport trans; if( pipe != null) { trans = new TNamedPipeServerTransport(pipe); } else { if (useEncryption) { trans = new TTLSServerSocket(port, 0, useBufferedSockets, new X509Certificate2(certPath)); } else { trans = new TServerSocket(port, 0, useBufferedSockets); } } TProtocolFactory proto; if ( compact ) proto = new TCompactProtocol.Factory(); else if ( json ) proto = new TJSONProtocol.Factory(); else proto = new TBinaryProtocol.Factory(); // Simple Server TServer serverEngine; if ( useFramed ) serverEngine = new TSimpleServer(testProcessor, trans, new TFramedTransport.Factory(), proto); else serverEngine = new TSimpleServer(testProcessor, trans, new TTransportFactory(), proto); // ThreadPool Server // serverEngine = new TThreadPoolServer(testProcessor, tServerSocket); // Threaded Server // serverEngine = new TThreadedServer(testProcessor, tServerSocket); //Server event handler TradeServerEventHandler serverEvents = new TradeServerEventHandler(); serverEngine.setEventHandler(serverEvents); testHandler.server = serverEngine; // Run it string where = ( pipe != null ? "on pipe "+pipe : "on port " + port); Console.WriteLine("Starting the server " + where + (useBufferedSockets ? " with buffered socket" : "") + (useFramed ? " with framed transport" : "") + (useEncryption ? " with encryption" : "") + (compact ? " with compact protocol" : "") + (json ? " with json protocol" : "") + "..."); serverEngine.Serve(); } catch (Exception x) { Console.Error.Write(x); return false; } Console.WriteLine("done."); return true; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using DowUtils; namespace Factotum { public partial class InspectionEdit : Form, IEntityEditForm { private EInspection curInspection; private bool savedInternally; // Allow the calling form to access the entity public IEntity Entity { get { return curInspection; } } //--------------------------------------------------------- // Initialization //--------------------------------------------------------- // If you are creating a new record, the ID should be null // Normally in this case, you will want to provide component and outage parentIDs public InspectionEdit(Guid? ID) : this(ID, null){} public InspectionEdit(Guid? ID, Guid? inspectedComponentID) { InitializeComponent(); curInspection = new EInspection(); curInspection.Load(ID); if (inspectedComponentID != null) curInspection.InspectionIscID = inspectedComponentID; InitializeControls(ID == null); savedInternally = false; } // Initialize the form control values private void InitializeControls(bool newRecord) { SetControlValues(); this.Text = newRecord ? "New Inspection" : "Edit Inspection"; } private void InspectedComponentEdit_Load(object sender, EventArgs e) { // Apply the current filters and set the selector row. // Passing a null selects the first row if there are any rows. UpdateSelector(null); // Now that we have some rows and columns, we can do some customization. CustomizeGrid(); // Need to do this because the customization clears the row selection. SelectGridRow(null); ManageButtons(); EDset.Changed += new EventHandler<EntityChangedEventArgs>(EDset_Changed); EGrid.Changed += new EventHandler<EntityChangedEventArgs>(EGrid_Changed); EGraphic.Changed += new EventHandler<EntityChangedEventArgs>(EGraphic_Changed); } private void InspectionEdit_FormClosed(object sender, FormClosedEventArgs e) { EDset.Changed -= new EventHandler<EntityChangedEventArgs>(EDset_Changed); EGrid.Changed -= new EventHandler<EntityChangedEventArgs>(EGrid_Changed); EGraphic.Changed -= new EventHandler<EntityChangedEventArgs>(EGraphic_Changed); } //--------------------------------------------------------- // Event Handlers //--------------------------------------------------------- void EDset_Changed(object sender, EntityChangedEventArgs e) { UpdateSelector(e.ID); ManageButtons(); } void EGraphic_Changed(object sender, EntityChangedEventArgs e) { ManageButtons(); } void EGrid_Changed(object sender, EntityChangedEventArgs e) { ManageButtons(); } // If the user cancels out, just close. private void btnCancel_Click(object sender, EventArgs e) { Close(); DialogResult = savedInternally ? DialogResult.OK : DialogResult.Cancel; } // If the user clicks OK, first validate and set the error text // for any controls with invalid values. // If it validates, try to save. private void btnOK_Click(object sender, EventArgs e) { SaveAndClose(); } // Handle the user's decision to edit the current tool private void EditCurrentSelection() { // Make sure there's a row selected if (dgvDatasets.SelectedRows.Count != 1) return; if (!performSilentSave()) return; Guid? currentEditItem = (Guid?)(dgvDatasets.SelectedRows[0].Cells["ID"].Value); // First check to see if an instance of the form set to the selected ID already exists if (!Globals.CanActivateForm(this, "DsetEdit", currentEditItem)) { // Open the edit form with the currently selected ID. DsetEdit frm = new DsetEdit(currentEditItem); frm.MdiParent = this.MdiParent; frm.Show(); } } // This handles the datagridview double-click as well as button click void btnEditDset_Click(object sender, System.EventArgs e) { EditCurrentSelection(); } private void dgvDatasets_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) EditCurrentSelection(); } private bool performSilentSave() { // we need to do a 'silent save' if (AnyControlErrors()) { MessageBox.Show("Make sure all errors are cleared first", "Factotum"); return false; } // Set the entity values to match the form values UpdateRecord(); // Try to validate if (!curInspection.Valid()) { setAllErrors(); MessageBox.Show("Make sure all errors are cleared first", "Factotum"); return false; } // The Save function returns a the Guid? of the record created or updated. Guid? tmpID = curInspection.Save(); if (tmpID == null) return false; savedInternally = true; return true; } // Handle the user's decision to add a new tool private void btnAddDset_Click(object sender, EventArgs e) { if (!performSilentSave()) return; // show form etc DsetEdit frm = new DsetEdit(null, curInspection.ID); frm.MdiParent = this.MdiParent; frm.Show(); } // Handle the user's decision to delete the selected tool private void btnDeleteDset_Click(object sender, EventArgs e) { if (dgvDatasets.SelectedRows.Count != 1) { MessageBox.Show("Please select a Dataset to delete first.", "Factotum"); return; } Guid? currentEditItem = (Guid?)(dgvDatasets.SelectedRows[0].Cells["ID"].Value); if (Globals.IsFormOpen(this, "DsetEdit", currentEditItem)) { MessageBox.Show("Can't delete because that item is currently being edited.", "Factotum"); return; } EDset Dset = new EDset(currentEditItem); Dset.Delete(true); if (Dset.DsetErrMsg != null) { MessageBox.Show(Dset.DsetErrMsg, "Factotum"); Dset.DsetErrMsg = null; } } private void btnMoveUp_Click(object sender, EventArgs e) { if (dgvDatasets.SelectedRows.Count != 1) { MessageBox.Show("Please select a dataset to move up first.", "Factotum"); return; } if (dgvDatasets.SelectedRows[0].Index == 0) { MessageBox.Show("Can't move that dataset up. It already has highest priority.", "Factotum"); return; } int selIdx = dgvDatasets.SelectedRows[0].Index; EDset source = new EDset((Guid?)dgvDatasets.Rows[selIdx].Cells["ID"].Value); EDset dest = new EDset((Guid?)dgvDatasets.Rows[selIdx - 1].Cells["ID"].Value); RenumberDsets(source, dest); } private void btnMoveDown_Click(object sender, EventArgs e) { if (dgvDatasets.SelectedRows.Count != 1) { MessageBox.Show("Please select a dataset to move down first.", "Factotum"); return; } int selIdx = dgvDatasets.SelectedRows[0].Index; if (selIdx >= dgvDatasets.Rows.Count - 1) { MessageBox.Show("Can't move that dataset down. It already has lowest priority.", "Factotum"); return; } EDset source = new EDset((Guid?)dgvDatasets.Rows[selIdx].Cells["ID"].Value); EDset dest = new EDset((Guid?)dgvDatasets.Rows[selIdx + 1].Cells["ID"].Value); RenumberDsets(source, dest); } // Each time the text changes, check to make sure its length is ok // If not, set the error. private void txtName_TextChanged(object sender, EventArgs e) { // Calling this method sets the ErrMsg property of the Object. curInspection.InspectionNameLengthOk(txtName.Text); errorProvider1.SetError(txtName, curInspection.InspectionNameErrMsg); } // We don't have a handler for inspector hours text changed. // It's a float, I don't know what the character limit is... I guess I could find out... private void txtNotes_TextChanged(object sender, EventArgs e) { curInspection.InspectionNotesLengthOk(txtNotes.Text); errorProvider1.SetError(txtNotes, curInspection.InspectionNotesErrMsg); } // The validating event gets called when the user leaves the control. // We handle it to perform all validation for the value. private void txtName_Validating(object sender, CancelEventArgs e) { // Calling this function will set the ErrMsg property of the object. curInspection.InspectionNameValid(txtName.Text); errorProvider1.SetError(txtName, curInspection.InspectionNameErrMsg); } private void txtNotes_Validating(object sender, CancelEventArgs e) { curInspection.InspectionNotesValid(txtNotes.Text); errorProvider1.SetError(txtNotes, curInspection.InspectionNotesErrMsg); } private void txtInspectorHours_Validating(object sender, CancelEventArgs e) { curInspection.InspectionPersonHoursValid(txtInspectorHours.Text); errorProvider1.SetError(txtInspectorHours, curInspection.InspectionPersonHoursErrMsg); } //--------------------------------------------------------- // Helper functions //--------------------------------------------------------- private void UpdateSelector(Guid? id) { // Save the sort specs if there are any, so we can re-apply them SortOrder sortOrder = dgvDatasets.SortOrder; int sortCol = -1; if (sortOrder != SortOrder.None) sortCol = dgvDatasets.SortedColumn.Index; // Update the grid view selector DataView dv = EDset.GetDefaultDataView(curInspection.ID); dgvDatasets.DataSource = dv; // Re-apply the sort specs if (sortOrder == SortOrder.Ascending) dgvDatasets.Sort(dgvDatasets.Columns[sortCol], ListSortDirection.Ascending); else if (sortOrder == SortOrder.Descending) dgvDatasets.Sort(dgvDatasets.Columns[sortCol], ListSortDirection.Descending); // Select the current row SelectGridRow(id); } private void CustomizeGrid() { // Apply a default sort dgvDatasets.Sort(dgvDatasets.Columns["DsetGridPriority"], ListSortDirection.Ascending); // Fix up the column headings dgvDatasets.Columns["DsetName"].HeaderText = "Dataset"; dgvDatasets.Columns["DsetHasTextFile"].HeaderText = "Has Textfile"; dgvDatasets.Columns["DsetAdditionalMeasurements"].HeaderText = "Add. Meas."; // Hide some columns dgvDatasets.Columns["ID"].Visible = false; dgvDatasets.Columns["DsetGridPriority"].Visible = false; dgvDatasets.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells); } // Select the row with the specified ID if it is currently displayed and scroll to it. // If the ID is not in the list, private void SelectGridRow(Guid? id) { bool found = false; int rows = dgvDatasets.Rows.Count; if (rows == 0) return; int r = 0; DataGridViewCell firstCell = dgvDatasets.FirstDisplayedCell; if (id != null) { // Find the row with the specified key id and select it. for (r = 0; r < rows; r++) { if ((Guid?)dgvDatasets.Rows[r].Cells["ID"].Value == id) { dgvDatasets.CurrentCell = dgvDatasets[firstCell.ColumnIndex, r]; dgvDatasets.Rows[r].Selected = true; found = true; break; } } } if (found) { if (!dgvDatasets.Rows[r].Displayed) { // Scroll to the selected row if the ID was in the list. dgvDatasets.FirstDisplayedScrollingRowIndex = r; } } else { // Select the first item dgvDatasets.CurrentCell = firstCell; dgvDatasets.Rows[0].Selected = true; } } private void ManageButtons() { bool hasGrid = curInspection.InspectionHasGrid; bool hasGraphic = curInspection.InspectionHasGraphic; btnAddEditGrid.Enabled = dgvDatasets.Rows.Count > 0; btnAddEditGrid.Text = hasGrid ? "Edit Grid" : "Add Grid"; btnAddEditGraphic.Text = hasGraphic ? "Edit Graphic" : "Add Graphic"; btnDeleteGrid.Enabled = hasGrid; btnDeleteGraphic.Enabled = hasGraphic; } // No prompting is performed. The user should understand the meanings of OK and Cancel. private void SaveAndClose() { if (AnyControlErrors()) return; // Set the entity values to match the form values UpdateRecord(); // Try to validate if (!curInspection.Valid()) { setAllErrors(); return; } // The Save function returns a the Guid? of the record created or updated. Guid? tmpID = curInspection.Save(); if (tmpID != null) { Close(); DialogResult = DialogResult.OK; } } // Set the form controls to the inspected component object values. private void SetControlValues() { if (curInspection.InspectionIscID != null) { EInspectedComponent inspectedComponent = new EInspectedComponent(curInspection.InspectionIscID); lblSiteName.Text = "Inspection for Report: '" + inspectedComponent.InspComponentName + "'"; } else lblSiteName.Text = "Inspection for Unknown Report"; DowUtils.Util.CenterControlHorizInForm(lblSiteName, this); txtName.Text = curInspection.InspectionName; txtInspectorHours.Text = GetFormattedFloat(curInspection.InspectionPersonHours); txtNotes.Text = curInspection.InspectionNotes; } private string GetFormattedFloat(float? number) { return number == null ? null : string.Format("{0:0.00}", number); } // Set the error provider text for all controls that use it. private void setAllErrors() { errorProvider1.SetError(txtInspectorHours, curInspection.InspectionPersonHoursErrMsg); errorProvider1.SetError(txtName, curInspection.InspectionNameErrMsg); errorProvider1.SetError(txtNotes, curInspection.InspectionNotesErrMsg); } // Check all controls to see if any have errors. private bool AnyControlErrors() { return (errorProvider1.GetError(txtInspectorHours).Length > 0 || errorProvider1.GetError(txtName).Length > 0 || errorProvider1.GetError(txtNotes).Length > 0); } // Update the object values from the form control values. private void UpdateRecord() { curInspection.InspectionName = txtName.Text; curInspection.InspectionNotes = txtNotes.Text; curInspection.InspectionPersonHours = Util.GetNullableFloatForString(txtInspectorHours.Text); } private void RenumberDsets(EDset source, EDset dest) { short tmpGridPriority = (short)source.DsetGridPriority; source.DsetGridPriority = dest.DsetGridPriority; dest.DsetGridPriority = tmpGridPriority; source.Save(); dest.Save(); } private void btnAddEditGrid_Click(object sender, EventArgs e) { if (!performSilentSave()) return; Guid? gridID = curInspection.GridID; GridEdit frm; if (gridID == null) { frm = new GridEdit(null, curInspection.ID); } else { frm = new GridEdit(gridID); } frm.ShowDialog(); } private void btnDeleteGrid_Click(object sender, EventArgs e) { Guid? gridID = curInspection.GridID; if (gridID != null) { EGrid grid = new EGrid(gridID); grid.Delete(false); } } private void btnAddEditGraphic_Click(object sender, EventArgs e) { if (!performSilentSave()) return; Guid? graphicID = curInspection.GraphicID; GraphicEdit frm; if (graphicID == null) { frm = new GraphicEdit(null, curInspection.ID); } else { frm = new GraphicEdit(graphicID); } frm.ShowDialog(); } private void btnDeleteGraphic_Click(object sender, EventArgs e) { Guid? graphicID = curInspection.GraphicID; if (graphicID != null) { EGraphic graphic = new EGraphic(graphicID); graphic.Delete(false); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Localization; using Microsoft.Extensions.Localization; using OrchardCore.Data.Documents; using OrchardCore.DisplayManagement.Notify; using OrchardCore.Environment.Extensions; using OrchardCore.Roles.ViewModels; using OrchardCore.Security; using OrchardCore.Security.Permissions; using OrchardCore.Security.Services; namespace OrchardCore.Roles.Controllers { public class AdminController : Controller { private readonly IDocumentStore _documentStore; private readonly IAuthorizationService _authorizationService; private readonly IStringLocalizer S; private readonly RoleManager<IRole> _roleManager; private readonly IEnumerable<IPermissionProvider> _permissionProviders; private readonly ITypeFeatureProvider _typeFeatureProvider; private readonly IRoleService _roleService; private readonly INotifier _notifier; private readonly IHtmlLocalizer H; public AdminController( IAuthorizationService authorizationService, ITypeFeatureProvider typeFeatureProvider, IDocumentStore documentStore, IStringLocalizer<AdminController> stringLocalizer, IHtmlLocalizer<AdminController> htmlLocalizer, RoleManager<IRole> roleManager, IRoleService roleService, INotifier notifier, IEnumerable<IPermissionProvider> permissionProviders ) { H = htmlLocalizer; _notifier = notifier; _roleService = roleService; _typeFeatureProvider = typeFeatureProvider; _permissionProviders = permissionProviders; _roleManager = roleManager; S = stringLocalizer; _authorizationService = authorizationService; _documentStore = documentStore; } public async Task<ActionResult> Index() { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageRoles)) { return Forbid(); } var roles = await _roleService.GetRolesAsync(); var model = new RolesViewModel { RoleEntries = roles.Select(BuildRoleEntry).ToList() }; return View(model); } public async Task<IActionResult> Create() { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageRoles)) { return Forbid(); } var model = new CreateRoleViewModel(); return View(model); } [HttpPost] public async Task<IActionResult> Create(CreateRoleViewModel model) { if (ModelState.IsValid) { model.RoleName = model.RoleName.Trim(); if (model.RoleName.Contains('/')) { ModelState.AddModelError(string.Empty, S["Invalid role name."]); } if (await _roleManager.FindByNameAsync(_roleManager.NormalizeKey(model.RoleName)) != null) { ModelState.AddModelError(string.Empty, S["The role is already used."]); } } if (ModelState.IsValid) { var role = new Role { RoleName = model.RoleName, RoleDescription = model.RoleDescription }; var result = await _roleManager.CreateAsync(role); if (result.Succeeded) { await _notifier.SuccessAsync(H["Role created successfully."]); return RedirectToAction(nameof(Index)); } await _documentStore.CancelAsync(); foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } // If we got this far, something failed, redisplay form return View(model); } [HttpPost] public async Task<IActionResult> Delete(string id) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageRoles)) { return Forbid(); } var currentRole = await _roleManager.FindByIdAsync(id); if (currentRole == null) { return NotFound(); } var result = await _roleManager.DeleteAsync(currentRole); if (result.Succeeded) { await _notifier.SuccessAsync(H["Role deleted successfully."]); } else { await _documentStore.CancelAsync(); await _notifier.ErrorAsync(H["Could not delete this role."]); foreach (var error in result.Errors) { await _notifier.ErrorAsync(H[error.Description]); } } return RedirectToAction(nameof(Index)); } public async Task<IActionResult> Edit(string id) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageRoles)) { return Forbid(); } var role = (Role)await _roleManager.FindByNameAsync(_roleManager.NormalizeKey(id)); if (role == null) { return NotFound(); } var installedPermissions = await GetInstalledPermissionsAsync(); var allPermissions = installedPermissions.SelectMany(x => x.Value); var model = new EditRoleViewModel { Role = role, Name = role.RoleName, RoleDescription = role.RoleDescription, EffectivePermissions = await GetEffectivePermissions(role, allPermissions), RoleCategoryPermissions = installedPermissions }; return View(model); } [HttpPost, ActionName(nameof(Edit))] public async Task<IActionResult> EditPost(string id, string roleDescription) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageRoles)) { return Forbid(); } var role = (Role)await _roleManager.FindByNameAsync(_roleManager.NormalizeKey(id)); if (role == null) { return NotFound(); } role.RoleDescription = roleDescription; // Save var rolePermissions = new List<RoleClaim>(); foreach (string key in Request.Form.Keys) { if (key.StartsWith("Checkbox.", StringComparison.Ordinal) && Request.Form[key] == "true") { string permissionName = key.Substring("Checkbox.".Length); rolePermissions.Add(new RoleClaim { ClaimType = Permission.ClaimType, ClaimValue = permissionName }); } } role.RoleClaims.RemoveAll(c => c.ClaimType == Permission.ClaimType); role.RoleClaims.AddRange(rolePermissions); await _roleManager.UpdateAsync(role); await _notifier.SuccessAsync(H["Role updated successfully."]); return RedirectToAction(nameof(Index)); } private RoleEntry BuildRoleEntry(IRole role) { return new RoleEntry { Name = role.RoleName, Description = role.RoleDescription, Selected = false }; } private async Task<IDictionary<string, IEnumerable<Permission>>> GetInstalledPermissionsAsync() { var installedPermissions = new Dictionary<string, IEnumerable<Permission>>(); foreach (var permissionProvider in _permissionProviders) { var feature = _typeFeatureProvider.GetFeatureForDependency(permissionProvider.GetType()); var featureName = feature.Id; var permissions = await permissionProvider.GetPermissionsAsync(); foreach (var permission in permissions) { var category = permission.Category; string title = String.IsNullOrWhiteSpace(category) ? S["{0} Feature", featureName] : category; if (installedPermissions.ContainsKey(title)) { installedPermissions[title] = installedPermissions[title].Concat(new[] { permission }); } else { installedPermissions.Add(title, new[] { permission }); } } } return installedPermissions; } private async Task<IEnumerable<string>> GetEffectivePermissions(Role role, IEnumerable<Permission> allPermissions) { // Create a fake user to check the actual permissions. If the role is anonymous // IsAuthenticated needs to be false. var fakeIdentity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Role, role.RoleName) }, role.RoleName != "Anonymous" ? "FakeAuthenticationType" : null); // Add role claims fakeIdentity.AddClaims(role.RoleClaims.Select(c => c.ToClaim())); var fakePrincipal = new ClaimsPrincipal(fakeIdentity); var result = new List<string>(); foreach (var permission in allPermissions) { if (await _authorizationService.AuthorizeAsync(fakePrincipal, permission)) { result.Add(permission.Name); } } return result; } } }
// Copyright (c) 2017 Mark A. Olbert some rights reserved // // This software is licensed under the terms of the MIT License // (https://opensource.org/licenses/MIT) using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Windows.Controls; using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Messaging; using Microsoft.Tools.WindowsInstallerXml.Bootstrapper; using Olbert.JumpForJoy.WPF; using Olbert.Wix.Panels; namespace Olbert.Wix.ViewModels { /// <summary> /// Defines the base class, dervied from MvvmLight's ViewModelBase, for the view model /// used by SimpleUI. /// </summary> public abstract class WixViewModel : ViewModelBase, IWixViewModel { private InstallState _state; private string _windowTitle; private bool _bundleInstalled; private int _cachePct; private int _exePct; /// <summary> /// Creates an instance of the view model, linked to a particular IWixApp object. /// /// Sets LaunchAction to wixApp.LaunchAction, WindowTitle to "Application Installer", /// InstallState to InstallState.NotPresent and loads the properties and parameters exposed /// thru the Wix BoostrapperApplication's generated xml file. /// /// A NullReferenceException is thrown if the wixApp is undefined. /// </summary> /// <param name="wixApp">the IWixApp with which this view model needs to be integrated</param> protected WixViewModel( IWixApp wixApp ) { BootstrapperApp = wixApp ?? throw new NullReferenceException( nameof(wixApp) ); LaunchAction = BootstrapperApp.LaunchAction; WindowTitle = "Application Installer"; BundleProperties = WixBundleProperties.Load() ?? throw new NullReferenceException( nameof(BundleProperties) ); InstallState = InstallState.NotPresent; Messenger.Default.Register<PanelButtonClick>(this, PanelButtonClickHandler); } /// <summary> /// The IWixApp object with which this view model is integrated /// </summary> protected IWixApp BootstrapperApp { get; } /// <summary> /// Information about the current panel being displayed by the SimpleUI /// </summary> public CurrentPanelInfo Current { get; } = new CurrentPanelInfo(); /// <summary> /// Creates a panel, makes it the current one being displayed, and updates /// the Current property. /// /// An ArgumentOutOfRangeException is thrown if no panel with an ID equal to /// the id parameter can be found. The search is done in a case-insensitive fashion. /// </summary> /// <param name="id">the unique ID of the panel to be created</param> /// <param name="stage">the stage of installation; if not specified, the value of the /// id parameter is used</param> protected void CreatePanel(string id, string stage = null) { if (stage == null) stage = id; if (!WixPanels.Instance.Contains(id.ToLower())) { var mesg = $"No panel defined with ID '{id}'"; throw new ArgumentOutOfRangeException(nameof(CreatePanel), mesg); } var panelInfo = WixPanels.Instance[id]; Current.ID = panelInfo.ID; Current.Stage = stage; Current.PanelViewModel = (PanelViewModel)Activator.CreateInstance(panelInfo.ViewModelType); Current.Buttons = (UserControl)Activator.CreateInstance(panelInfo.ButtonsType); Current.ButtonsViewModel = Current.PanelViewModel.GetButtonsViewModel(); Current.Buttons.DataContext = Current.ButtonsViewModel; Current.Panel = (UserControl)Activator.CreateInstance(panelInfo.UserControlType); Current.Panel.DataContext = Current.PanelViewModel; } /// <summary> /// Defines how to move to the next panel. This method must be overriden in a derived class. /// </summary> protected abstract void MoveNext(); /// <summary> /// Defines how to move to the previous panel. This method must be overriden in a derived class. /// </summary> protected abstract void MovePrevious(); /// <summary> /// The LaunchActions supported by this UI. Must be overriden in a derived class. /// </summary> public abstract IEnumerable<LaunchAction> SupportedActions { get; } /// <summary> /// The parameters and properties of this installation exposed thru the Wix BootstrapperApplication's /// generated xml file. /// </summary> public WixBundleProperties BundleProperties { get; private set; } /// <summary> /// Flag indicating whether or not the bundle is already installed /// </summary> public bool BundleInstalled { get => _bundleInstalled; set => Set(ref _bundleInstalled, value); } /// <summary> /// The LaunchAction being performed /// </summary> public LaunchAction LaunchAction { get; set; } /// <summary> /// A flag indicating whether or not the bundle is installed on the system /// </summary> public InstallState InstallState { get => _state; set => Set(ref _state, value); } /// <summary> /// The current state of the Wix BootstrapperApplication's engine /// </summary> public EngineState EngineState { get; set; } = EngineState.NotStarted; /// <summary> /// The current phase of the Wix BootstrapperApplication's progress /// </summary> public EnginePhase EnginePhase { get; set; } = EnginePhase.NotStarted; /// <summary> /// The text displayed in the SimpleUI's window title bar /// </summary> public string WindowTitle { get => _windowTitle; set => Set( ref _windowTitle, value ); } /// <summary> /// Updates EngineState to EngineState.DetectionComplete. Sets InstallState to either InstallState.Present or /// InstallState.NotPresent depending upon whether or not there are packages that need to be installed from /// the bundle. /// </summary> public virtual void OnDetectionComplete() { EngineState = EngineState.DetectionComplete; InstallState = BundleProperties.GetNumPackagesToInstall() == 0 ? InstallState.Present : InstallState.NotPresent; } /// <summary> /// If the WixProgress panel is being displayed, adds the specified message to its list of messages. /// </summary> /// <param name="mesg">a message to display</param> public virtual void ReportProgress( string mesg ) { ProgressPanelViewModel vm = Current.PanelViewModel as ProgressPanelViewModel; if( vm != null ) WixApp.Dispatcher.BeginInvoke( (Action<string>) vm.Messages.Add, mesg ); } /// <summary> /// If the WixProgress panel is being displayed, updates the percent of completion /// numbers. /// /// This method adjusts for the fact that during installations the Wix engine reports /// separate caching and execution phase percentages, each of which rise to 100. /// </summary> /// <param name="phasePct">the percent of the current phase's completion</param> public virtual void ReportProgress( int phasePct ) { switch( EnginePhase ) { case EnginePhase.Caching: _cachePct = phasePct; break; case EnginePhase.Executing: _exePct = phasePct; break; } ProgressPanelViewModel vm = Current.PanelViewModel as ProgressPanelViewModel; if ( vm != null ) { vm.PhasePercent = phasePct; var totalPct = _cachePct + _exePct; if( LaunchAction == LaunchAction.Install ) totalPct /= 2; vm.OverallPercent = totalPct; } } /// <summary> /// Called when installation is complete. This base implementation does nothing. /// </summary> public virtual void OnInstallationComplete() { } /// <summary> /// Utility method for retrieving a ManifestResourceStream as text. Used primarily to retrieve /// things like license text from an installation assembly. /// </summary> /// <param name="fileName">the name of the embedded text file to retrieve</param> /// <param name="ns">the namespace containing the specified file; defaults to the Namespace /// of the class' Type</param> /// <returns>the text from an embedded resource, or null if the resource could not be found</returns> protected string GetEmbeddedTextFile(string fileName, string ns = null) { ns = ns ?? this.GetType().Namespace; using (Stream stream = Assembly.GetCallingAssembly().GetManifestResourceStream($"{ns}.{fileName}")) { if (stream == null) return null; using (StreamReader reader = new StreamReader(stream)) { return reader.ReadToEnd(); } } } /// <summary> /// Utility method to check whether or not a particular process is running on the system. Used primarily to /// indicate when user intervention to shut down an app is required. /// /// The check is done by comparing process names in a case-insensitive fashion. /// </summary> /// <param name="processName">the name of a process</param> /// <returns>true if the process is running, false otherwise</returns> protected bool IsProcessRunning( string processName ) { if( String.IsNullOrEmpty( processName ) ) return false; return Process.GetProcesses() .Any( p => p.ProcessName.Equals( processName, StringComparison.OrdinalIgnoreCase ) ); } private void PanelButtonClickHandler(PanelButtonClick obj) { if (obj == null) return; switch (obj.ButtonID) { case StandardButtonsViewModel.CancelButtonID: var msgBox = new J4JMessageBox().Title( "Please Confirm" ) .Message( "Are you sure you want to cancel the installation?" ) .DefaultButton( 1 ) .ButtonText( "Yes", "No" ); if (msgBox.ShowMessageBox() == 0) WixApp.Dispatcher.InvokeShutdown(); break; case StandardButtonsViewModel.NextButtonID: MoveNext(); break; case StandardButtonsViewModel.PreviousButtonID: MovePrevious(); break; } } } }
// // PlayerEngine.cs // // Author: // Gabriel Burt <gburt@novell.com> // Sean McNamara <smcnam@gmail.com // // Copyright (C) 2010 Novell, Inc. // Copyright (C) 2010 Sean McNamara // // 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; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using Mono.Unix; using Gst; using Gst.BasePlugins; using Gst.Base; using Hyena; using Hyena.Data; using Banshee.Base; using Banshee.Streaming; using Banshee.MediaEngine; using Banshee.ServiceStack; using Banshee.Configuration; using Banshee.Preferences; namespace Banshee.GStreamerSharp { public class PlayerEngine : Banshee.MediaEngine.PlayerEngine { Pipeline pipeline; PlayBin2 playbin; private MyBinType audiobin; private BinList<Element> filterbin; private Element audiosink; private Element queue; private readonly List<Bin> filterList = new List<Bin> (); private readonly GhostPad audiobinsink = new GhostPad ("sink", PadDirection.Sink); public PlayerEngine () { Console.WriteLine ("Gst# PlayerEngine ctor - completely experimental, still a WIP"); Gst.Application.Init (); //Making early-bound elements pipeline = new Pipeline (); playbin = new PlayBin2 (); audiobin = new MyBinType ("audiobin"); filterbin = new BinList<Element> ("filterbin"); //Making late-bound elements (not currently bound by gst-sharp) audiosink = ElementFactory.Make ("gconfaudiosink", "thesink"); if (audiosink == null) audiosink = ElementFactory.Make ("autoaudiosink", "thesink"); queue = ElementFactory.Make ("queue", "audioqueue"); //Adding, linking, and padding filterbin.Add (queue); audiobin.Add (filterbin.GetBin (), audiosink); filterbin.GetSourceGhostPad ().Link (audiosink.GetStaticPad ("sink")); audiobinsink.SetTarget (filterbin.GetSinkGhostPad ()); audiobin.AddPadHack (audiobinsink); playbin.AudioSink = audiobin; pipeline.Add (playbin); pipeline.Bus.AddWatch (OnBusMessage); Banshee.ServiceStack.Application.RunTimeout (200, delegate { OnEventChanged (PlayerEvent.Iterate); return true; }); OnStateChanged (PlayerState.Ready); } private bool OnBusMessage (Bus bus, Message msg) { switch (msg.Type) { case MessageType.Eos: Close (false); OnEventChanged (PlayerEvent.EndOfStream); OnEventChanged (PlayerEvent.RequestNextTrack); break; case MessageType.StateChanged: State old_state, new_state, pending_state; msg.ParseStateChanged (out old_state, out new_state, out pending_state); HandleStateChange (old_state, new_state, pending_state); break; case MessageType.Buffering: int buffer_percent; msg.ParseBuffering (out buffer_percent); HandleBuffering (buffer_percent); break; case MessageType.Tag: Pad pad; TagList tag_list; msg.ParseTag (out pad, out tag_list); HandleTag (pad, tag_list); break; case MessageType.Error: Enum error_type; string err_msg, debug; msg.ParseError (out error_type, out err_msg, out debug); // TODO: What to do with the error? break; } return true; } private void HandleBuffering (int buffer_percent) { OnEventChanged (new PlayerEventBufferingArgs (buffer_percent / 100.0)); } private void HandleStateChange (State old_state, State new_state, State pending_state) { if (CurrentState != PlayerState.Loaded && old_state == State.Ready && new_state == State.Paused && pending_state == State.Playing) { OnStateChanged (PlayerState.Loaded); } else if (old_state == State.Paused && new_state == State.Playing && pending_state == State.VoidPending) { if (CurrentState == PlayerState.Loaded) { OnEventChanged (PlayerEvent.StartOfStream); } OnStateChanged (PlayerState.Playing); } else if (CurrentState == PlayerState.Playing && old_state == State.Playing && new_state == State.Paused) { OnStateChanged (PlayerState.Paused); } } private void HandleTag (Pad pad, TagList tag_list) { foreach (string tag in tag_list.Tags) { if (String.IsNullOrEmpty (tag)) { continue; } if (tag_list.GetTagSize (tag) < 1) { continue; } List tags = tag_list.GetTag (tag); foreach (object o in tags) { OnTagFound (new StreamTag { Name = tag, Value = o }); } } } protected override void OpenUri (SafeUri uri) { Console.WriteLine ("Gst# PlayerEngine OpenUri: {0}", uri); if (pipeline.CurrentState == State.Playing) { pipeline.SetState (Gst.State.Null); } playbin.Uri = uri.AbsoluteUri; } public override void Play () { Console.WriteLine ("Gst# PlayerEngine play"); pipeline.SetState (Gst.State.Playing); OnStateChanged (PlayerState.Playing); } public override void Pause () { Console.WriteLine ("Gst# PlayerEngine pause"); pipeline.SetState (Gst.State.Paused); OnStateChanged (PlayerState.Paused); } public override ushort Volume { get { return (ushort)Math.Round (playbin.Volume * 100.0); } set { playbin.Volume = (value / 100.0); } } public override bool CanSeek { get { return true; } } private static Format query_format = Format.Time; public override uint Position { get { long pos; playbin.QueryPosition (ref query_format, out pos); return (uint)((ulong)pos / Gst.Clock.MSecond); } set { playbin.Seek (Format.Time, SeekFlags.Accurate, (long)(value * Gst.Clock.MSecond)); } } public override uint Length { get { long duration; playbin.QueryDuration (ref query_format, out duration); return (uint)((ulong)duration / Gst.Clock.MSecond); } } private static string[] source_capabilities = { "file", "http", "cdda" }; public override IEnumerable SourceCapabilities { get { return source_capabilities; } } private static string[] decoder_capabilities = { "ogg", "wma", "asf", "flac", "mp3", "mp4", "m4a", "" }; public override IEnumerable ExplicitDecoderCapabilities { get { return decoder_capabilities; } } public override string Id { get { return "gstreamer-sharp"; } } public override string Name { get { return Catalog.GetString ("GStreamer# 0.10"); } } public override bool SupportsEqualizer { get { return false; } } public override VideoDisplayContextType VideoDisplayContextType { get { return VideoDisplayContextType.Unsupported; } } public override object AddFilterElement (string elementClass, string name) { if (elementClass != null && elementClass.Length > 0 && name != null && name.Length > 0) { Bin parsed = (Bin)Gst.Parse.BinFromDescription ("audioconvert ! " + elementClass + " name=" + name + " ! audioconvert", true); parsed.Name = name + "bin"; filterbin.Add (parsed); filterList.Add (parsed); IEnumerator ie = parsed.ElementsSorted.GetEnumerator (); ie.MoveNext (); ie.MoveNext (); return ie.Current; } else { return null; } } public override bool RemoveFilterElement (object elem) { if (name is Element) { Bin found = null; Element e = (Element)name; foreach (Bin b in filterList) { IEnumerator enu = b.ElementsRecurse.GetEnumerator (); foreach (object o in enu) { if (o is Element && ((Element)o) == e) { found = b; break; } } if (found != null) { break; } } if (found == null) { return false; } else { filterbin.Remove (found); filterList.Remove (found); return true; } } else { return false; } } } }
using System.Collections.Generic; using System.Text.RegularExpressions; namespace System { /// <summary> /// The Guid data type which is mapped to the string type in Javascript. /// </summary> [Bridge.Immutable] public struct Guid : IEquatable<Guid>, IComparable<Guid>, IFormattable { private const string error1 = "Byte array for GUID must be exactly {0} bytes long"; private static readonly RegExp Valid = new RegExp("^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", "i"); private static readonly RegExp Split = new RegExp("^(.{8})(.{4})(.{4})(.{4})(.{12})$"); private static readonly RegExp NonFormat = new RegExp("^[{(]?([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})[)}]?$", "i"); private static readonly RegExp Replace = new RegExp("-", "g"); private static readonly Random Rnd = new Random(); /// <summary> /// A read-only instance of the Guid structure whose value is all zeros. /// </summary> public static readonly Guid Empty = new Guid(); private int _a; private short _b; private short _c; private byte _d; private byte _e; private byte _f; private byte _g; private byte _h; private byte _i; private byte _j; private byte _k; /// <summary> /// Initializes a new instance of the Guid structure by using the value represented by the specified string. /// </summary> /// <param name="uuid">A string that contains a GUID</param> public Guid(string uuid) { this = new Guid(); ParseInternal(uuid, null, true); } /// <summary> /// Initializes a new instance of the Guid structure by using the specified array of bytes. /// </summary> /// <param name="b">A 16-element byte array containing values with which to initialize the GUID.</param> public Guid(byte[] b) { if (b == null) { throw new ArgumentNullException("b"); } if (b.Length != 16) { throw new ArgumentException(string.Format(error1, 16)); } _a = ((int)b[3] << 24) | ((int)b[2] << 16) | ((int)b[1] << 8) | b[0]; _b = (short)(((int)b[5] << 8) | b[4]); _c = (short)(((int)b[7] << 8) | b[6]); _d = b[8]; _e = b[9]; _f = b[10]; _g = b[11]; _h = b[12]; _i = b[13]; _j = b[14]; _k = b[15]; } /// <summary> /// Initializes a new instance of the Guid structure by using the specified unsigned integers and bytes. /// </summary> /// <param name="a">The first 4 bytes of the GUID.</param> /// <param name="b">The next 2 bytes of the GUID.</param> /// <param name="c">The next 2 bytes of the GUID.</param> /// <param name="d">The next byte of the GUID.</param> /// <param name="e">The next byte of the GUID.</param> /// <param name="f">The next byte of the GUID.</param> /// <param name="g">The next byte of the GUID.</param> /// <param name="h">The next byte of the GUID.</param> /// <param name="i">The next byte of the GUID.</param> /// <param name="j">The next byte of the GUID.</param> /// <param name="k">The next byte of the GUID.</param> [CLSCompliant(false)] public Guid(uint a, ushort b, ushort c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k) { _a = (int)a; _b = (short)b; _c = (short)c; _d = d; _e = e; _f = f; _g = g; _h = h; _i = i; _j = j; _k = k; } /// <summary> /// Initializes a new instance of the Guid structure by using the specified integers and byte array. /// </summary> /// <param name="a">The first 4 bytes of the GUID.</param> /// <param name="b">The next 2 bytes of the GUID.</param> /// <param name="c">The next 2 bytes of the GUID.</param> /// <param name="d">The remaining 8 bytes of the GUID.</param> public Guid(int a, short b, short c, byte[] d) { if (d == null) { throw new ArgumentNullException("d"); } if (d.Length != 8) { throw new ArgumentException(string.Format(error1, 8)); } _a = a; _b = b; _c = c; _d = d[0]; _e = d[1]; _f = d[2]; _g = d[3]; _h = d[4]; _i = d[5]; _j = d[6]; _k = d[7]; } /// <summary> /// Initializes a new instance of the Guid structure by using the specified integers and bytes. /// </summary> /// <param name="a">The first 4 bytes of the GUID.</param> /// <param name="b">The next 2 bytes of the GUID.</param> /// <param name="c">The next 2 bytes of the GUID.</param> /// <param name="d">The next byte of the GUID.</param> /// <param name="e">The next byte of the GUID.</param> /// <param name="f">The next byte of the GUID.</param> /// <param name="g">The next byte of the GUID.</param> /// <param name="h">The next byte of the GUID.</param> /// <param name="i">The next byte of the GUID.</param> /// <param name="j">The next byte of the GUID.</param> /// <param name="k">The next byte of the GUID.</param> public Guid(int a, short b, short c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k) { _a = a; _b = b; _c = c; _d = d; _e = e; _f = f; _g = g; _h = h; _i = i; _j = j; _k = k; } /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns>The hash code for this instance.</returns> public override int GetHashCode() { return this._a ^ (((int)this._b << 16) | (int)(ushort)this._c) ^ (((int)this._f << 24) | this._k); } /// <summary> /// Returns a value indicating whether this instance and a specified Guid object represent the same value. /// </summary> /// <param name="o">An object to compare to this instance.</param> /// <returns>true if o is equal to this instance; otherwise, false.</returns> public override bool Equals(Object o) { if (!(o is Guid)) { return false; } return this.Equals((Guid)o); } /// <summary> /// Returns a value indicating whether this instance and a specified Guid object represent the same value. /// </summary> /// <param name="o">An object to compare to this instance.</param> /// <returns>true if o is equal to this instance; otherwise, false.</returns> public bool Equals(Guid o) { if ((this._a != o._a) || (this._b != o._b) || (this._c != o._c) || (this._d != o._d) || (this._e != o._e) || (this._f != o._f) || (this._g != o._g) || (this._h != o._h) || (this._i != o._i) || (this._j != o._j) || (this._k != o._k)) { return false; } return true; } /// <summary> /// Compares this instance to a specified Guid object and returns an indication of their relative values. /// </summary> /// <param name="value">An object to compare to this instance.</param> /// <returns>A signed number indicating the relative values of this instance and value.</returns> public int CompareTo(Guid value) { return this.ToString().CompareTo(value.ToString()); } /// <summary> /// Returns a string representation of the value of this instance in registry format. /// </summary> /// <returns>The value of this Guid, formatted by using the "D" format specifier.</returns> public override string ToString() { return Format(null); } /// <summary> /// Returns a string representation of the value of this Guid instance, according to the provided format specifier. /// </summary> /// <param name="format">A single format specifier that indicates how to format the value of this Guid. The format parameter can be "N", "D", "B", "P". If format is null or an empty string (""), "D" is used.</param> /// <returns>The value of this Guid, represented as a series of lowercase hexadecimal digits in the specified format.</returns> public string ToString(string format) { return Format(format); } /// <summary> /// Returns a string representation of the value of this instance of the Guid class, according to the provided format specifier and culture-specific format information. /// </summary> /// <param name="format">A single format specifier that indicates how to format the value of this Guid. The format parameter can be "N", "D", "B", "P". If format is null or an empty string (""), "D" is used.</param> /// <param name="formatProvider">(Reserved) An object that supplies culture-specific formatting information.</param> /// <returns>The value of this Guid, represented as a series of lowercase hexadecimal digits in the specified format.</returns> public string ToString(string format, IFormatProvider formatProvider) { return Format(format); } /// <summary> /// Returns a 16-element byte array that contains the value of this instance. /// </summary> /// <returns>A 16-element byte array.</returns> public byte[] ToByteArray() { byte[] g = new byte[16]; g[0] = (byte)(_a); g[1] = (byte)(_a >> 8); g[2] = (byte)(_a >> 16); g[3] = (byte)(_a >> 24); g[4] = (byte)(_b); g[5] = (byte)(_b >> 8); g[6] = (byte)(_c); g[7] = (byte)(_c >> 8); g[8] = _d; g[9] = _e; g[10] = _f; g[11] = _g; g[12] = _h; g[13] = _i; g[14] = _j; g[15] = _k; return g; } /// <summary> /// Converts the string representation of a GUID to the equivalent Guid structure. /// </summary> /// <param name="input">The string to convert.</param> /// <returns>A structure that contains the value that was parsed.</returns> public static Guid Parse(string input) { return ParseExact(input, null); } /// <summary> /// Converts the string representation of a GUID to the equivalent Guid structure, provided that the string is in the specified format. /// </summary> /// <param name="input">The GUID to convert.</param> /// <param name="format">One of the following specifiers that indicates the exact format to use when interpreting input: "N", "D", "B", "P".</param> /// <returns></returns> public static Guid ParseExact(string input, string format) { var r = new Guid(); r.ParseInternal(input, format, true); return r; } /// <summary> /// Converts the string representation of a GUID to the equivalent Guid structure. /// </summary> /// <param name="input">The GUID to convert.</param> /// <param name="result">The structure that will contain the parsed value. If the method returns true, result contains a valid Guid. If the method returns false, result equals Guid.Empty.</param> /// <returns></returns> public static bool TryParse(string input, out Guid result) { return TryParseExact(input, null, out result); } /// <summary> /// Converts the string representation of a GUID to the equivalent Guid structure, provided that the string is in the specified format. /// </summary> /// <param name="input">The GUID to convert.</param> /// <param name="format">One of the following specifiers that indicates the exact format to use when interpreting input: "N", "D", "B", "P".</param> /// <param name="result">The structure that will contain the parsed value. If the method returns true, result contains a valid Guid. If the method returns false, result equals Guid.Empty.</param> /// <returns></returns> public static bool TryParseExact(string input, string format, out Guid result) { result = new Guid(); return result.ParseInternal(input, format, false); } /// <summary> /// Initializes a new instance of the Guid structure. /// </summary> /// <returns>A new GUID object.</returns> public static Guid NewGuid() { var a = new byte[16]; Rnd.NextBytes(a); a[7] = (byte)(a[7] & 0x0f | 0x40); a[8] = (byte)(a[8] & 0xbf | 0x80); return new Guid(a); } /// <summary> /// Indicates whether the values of two specified Guid objects are equal. /// </summary> /// <param name="a">The first object to compare.</param> /// <param name="b">The second object to compare.</param> /// <returns>true if a and b are equal; otherwise, false.</returns> public static bool operator ==(Guid a, Guid b) { if (Object.ReferenceEquals(a, null)) { return Object.ReferenceEquals(b, null); } return a.Equals(b); } /// <summary> /// Indicates whether the values of two specified Guid objects are not equal. /// </summary> /// <param name="a">The first object to compare.</param> /// <param name="b">The second object to compare.</param> /// <returns>true if a and b are not equal; otherwise, false.</returns> public static bool operator !=(Guid a, Guid b) { return !(a == b); } private bool ParseInternal(string input, string format, bool check) { string r = null; if (string.IsNullOrEmpty(input)) { if (check) { throw new System.ArgumentNullException("input"); } return false; } if (string.IsNullOrEmpty(format)) { var m = NonFormat.Exec(input); if (m != null) { List<string> list = new List<string>(); for (int i = 1; i <= m.Length; i++) { if (m[i] != null) { list.Add(m[i]); } } r = list.ToArray().Join("-").ToLower(); } } else { format = format.ToUpper(); var p = false; if (format == "N") { var m = Split.Exec(input); if (m != null) { List<string> list = new List<string>(); for (int i = 1; i <= m.Length; i++) { if (m[i] != null) { list.Add(m[i]); } } p = true; input = list.ToArray().Join("-"); } } else if (format == "B" || format == "P") { var b = format == "B" ? new[] { '{', '}' } : new[] { '(', ')' }; if ((input[0] == b[0]) && (input[input.Length - 1] == b[1])) { p = true; input = input.Substring(1, input.Length - 2); } } else { p = true; } if (p && Guid.Valid.Test(input)) { r = input.ToLower(); } } if (r != null) { FromString(r); return true; } if (check) { throw new System.FormatException("input is not in a recognized format"); } return false; } private string Format(string format) { var s = ToHex((uint)_a, 8) + ToHex((ushort)_b, 4) + ToHex((ushort)_c, 4); s = s + (new[] { _d, _e, _f, _g, _h, _i, _j, _k }).Map(ToHex).Join(""); var m = Bridge.Script.Write<string[]>("/^(.{8})(.{4})(.{4})(.{4})(.{12})$/.exec(s)"); string[] list = new string[0]; for (int i = 1; i < m.Length; i++) { if (m[i] != null) { list.Push(m[i]); } } s = list.Join("-"); switch (format) { case "n": case "N": return s.ToDynamic().replace(Guid.Replace, ""); case "b": case "B": return '{' + s + '}'; case "p": case "P": return '(' + s + ')'; default: return s; } } private static string ToHex(uint x, int precision) { var result = Bridge.Script.Call<string>("x.toString", 16); precision -= result.Length; for (var i = 0; i < precision; i++) { result = "0" + result; } return result; } private static string ToHex(byte x) { var result = Bridge.Script.Call<string>("x.toString", 16); if (result.Length == 1) { result = "0" + result; } return result; } private void FromString(string s) { if (string.IsNullOrEmpty(s)) { return; } s = s.ToDynamic().replace(Guid.Replace, ""); var r = new byte[8]; _a = (int)uint.Parse(s.Substring(0, 8), 16); _b = (short)ushort.Parse(s.Substring(8, 4), 16); _c = (short)ushort.Parse(s.Substring(12, 4), 16); for (var i = 8; i < 16; i++) { r[i - 8] = byte.Parse(s.Substring(i * 2, 2), 16); } _d = r[0]; _e = r[1]; _f = r[2]; _g = r[3]; _h = r[4]; _i = r[5]; _j = r[6]; _k = r[7]; } private string toJSON() { return this.ToString(); } } }
// This file contains general utilities to aid in development. // Classes here generally shouldn't be exposed publicly since // they're not particular to any library functionality. // Because the classes here are internal, it's likely this file // might be included in multiple assemblies. namespace Standard { using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection; using System.Windows; using System.Windows.Media; using System.Windows.Media.Imaging; internal static partial class Utility { [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static byte[] GetBytesFromBitmapSource(BitmapSource bmp) { int width = bmp.PixelWidth; int height = bmp.PixelHeight; int stride = width * ((bmp.Format.BitsPerPixel + 7) / 8); var pixels = new byte[height * stride]; bmp.CopyPixels(pixels, stride, 0); return pixels; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static BitmapSource GenerateBitmapSource(ImageSource img) { return GenerateBitmapSource(img, img.Width, img.Height); } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static BitmapSource GenerateBitmapSource(ImageSource img, double renderWidth, double renderHeight) { var dv = new DrawingVisual(); using (DrawingContext dc = dv.RenderOpen()) { dc.DrawImage(img, new Rect(0, 0, renderWidth, renderHeight)); } var bmp = new RenderTargetBitmap((int)renderWidth, (int)renderHeight, 96, 96, PixelFormats.Pbgra32); bmp.Render(dv); return bmp; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static BitmapSource GenerateBitmapSource(UIElement element, double renderWidth, double renderHeight, bool performLayout) { if (performLayout) { element.Measure(new Size(renderWidth, renderHeight)); element.Arrange(new Rect(new Size(renderWidth, renderHeight))); } var bmp = new RenderTargetBitmap((int)renderWidth, (int)renderHeight, 96, 96, PixelFormats.Pbgra32); var dv = new DrawingVisual(); using (DrawingContext dc = dv.RenderOpen()) { dc.DrawRectangle(new VisualBrush(element), null, new Rect(0, 0, renderWidth, renderHeight)); } bmp.Render(dv); return bmp; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static void SaveToPng(BitmapSource source, string fileName) { var encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(source)); using (FileStream stream = File.Create(fileName)) { encoder.Save(stream); } } // This can be cached. It's not going to change under reasonable circumstances. private static int s_bitDepth; // = 0; [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private static int _GetBitDepth() { if (s_bitDepth == 0) { using (SafeDC dc = SafeDC.GetDesktop()) { s_bitDepth = NativeMethods.GetDeviceCaps(dc, DeviceCap.BITSPIXEL) * NativeMethods.GetDeviceCaps(dc, DeviceCap.PLANES); } } return s_bitDepth; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static BitmapFrame GetBestMatch(IList<BitmapFrame> frames, int width, int height) { return _GetBestMatch(frames, _GetBitDepth(), width, height); } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private static int _MatchImage(BitmapFrame frame, int bitDepth, int width, int height, int bpp) { int score = 2 * _WeightedAbs(bpp, bitDepth, false) + _WeightedAbs(frame.PixelWidth, width, true) + _WeightedAbs(frame.PixelHeight, height, true); return score; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private static int _WeightedAbs(int valueHave, int valueWant, bool fPunish) { int diff = (valueHave - valueWant); if (diff < 0) { diff = (fPunish ? -2 : -1) * diff; } return diff; } /// From a list of BitmapFrames find the one that best matches the requested dimensions. /// The methods used here are copied from Win32 sources. We want to be consistent with /// system behaviors. [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private static BitmapFrame _GetBestMatch(IList<BitmapFrame> frames, int bitDepth, int width, int height) { int bestScore = int.MaxValue; int bestBpp = 0; int bestIndex = 0; bool isBitmapIconDecoder = frames[0].Decoder is IconBitmapDecoder; for (int i = 0; i < frames.Count && bestScore != 0; ++i) { int currentIconBitDepth = isBitmapIconDecoder ? frames[i].Thumbnail.Format.BitsPerPixel : frames[i].Format.BitsPerPixel; if (currentIconBitDepth == 0) { currentIconBitDepth = 8; } int score = _MatchImage(frames[i], bitDepth, width, height, currentIconBitDepth); if (score < bestScore) { bestIndex = i; bestBpp = currentIconBitDepth; bestScore = score; } else if (score == bestScore) { // Tie breaker: choose the higher color depth. If that fails, choose first one. if (bestBpp < currentIconBitDepth) { bestIndex = i; bestBpp = currentIconBitDepth; } } } return frames[bestIndex]; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static int RGB(Color c) { return c.B | (c.G << 8) | (c.R << 16); } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static int AlphaRGB(Color c) { return c.B | (c.G << 8) | (c.R << 16) | (c.A << 24); } /// <summary>Convert a native integer that represent a color with an alpha channel into a Color struct.</summary> /// <param name="color">The integer that represents the color. Its bits are of the format 0xAARRGGBB.</param> /// <returns>A Color representation of the parameter.</returns> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static Color ColorFromArgbDword(uint color) { return Color.FromArgb( (byte)((color & 0xFF000000) >> 24), (byte)((color & 0x00FF0000) >> 16), (byte)((color & 0x0000FF00) >> 8), (byte)((color & 0x000000FF) >> 0)); } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static bool AreImageSourcesEqual(ImageSource left, ImageSource right) { if (null == left) { return right == null; } if (null == right) { return false; } BitmapSource leftBmp = GenerateBitmapSource(left); BitmapSource rightBmp = GenerateBitmapSource(right); byte[] leftPixels = GetBytesFromBitmapSource(leftBmp); byte[] rightPixels = GetBytesFromBitmapSource(rightBmp); if (leftPixels.Length != rightPixels.Length) { return false; } return MemCmp(leftPixels, rightPixels, leftPixels.Length); } // Caller is responsible for destroying the HICON // Caller is responsible to ensure that GDI+ has been initialized. [SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")] [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static IntPtr GenerateHICON(ImageSource image, Size dimensions) { if (image == null) { return IntPtr.Zero; } // If we're getting this from a ".ico" resource, then it comes through as a BitmapFrame. // We can use leverage this as a shortcut to get the right 16x16 representation // because DrawImage doesn't do that for us. var bf = image as BitmapFrame; if (bf != null) { bf = GetBestMatch(bf.Decoder.Frames, (int)dimensions.Width, (int)dimensions.Height); } else { // Constrain the dimensions based on the aspect ratio. var drawingDimensions = new Rect(0, 0, dimensions.Width, dimensions.Height); // There's no reason to assume that the requested image dimensions are square. double renderRatio = dimensions.Width / dimensions.Height; double aspectRatio = image.Width / image.Height; // If it's smaller than the requested size, then place it in the middle and pad the image. if (image.Width <= dimensions.Width && image.Height <= dimensions.Height) { drawingDimensions = new Rect((dimensions.Width - image.Width) / 2, (dimensions.Height - image.Height) / 2, image.Width, image.Height); } else if (renderRatio > aspectRatio) { double scaledRenderWidth = (image.Width / image.Height) * dimensions.Width; drawingDimensions = new Rect((dimensions.Width - scaledRenderWidth) / 2, 0, scaledRenderWidth, dimensions.Height); } else if (renderRatio < aspectRatio) { double scaledRenderHeight = (image.Height / image.Width) * dimensions.Height; drawingDimensions = new Rect(0, (dimensions.Height - scaledRenderHeight) / 2, dimensions.Width, scaledRenderHeight); } var dv = new DrawingVisual(); DrawingContext dc = dv.RenderOpen(); dc.DrawImage(image, drawingDimensions); dc.Close(); var bmp = new RenderTargetBitmap((int)dimensions.Width, (int)dimensions.Height, 96, 96, PixelFormats.Pbgra32); bmp.Render(dv); bf = BitmapFrame.Create(bmp); } // Using GDI+ to convert to an HICON. // I'd rather not duplicate their code. using (MemoryStream memstm = new MemoryStream()) { BitmapEncoder enc = new PngBitmapEncoder(); enc.Frames.Add(bf); enc.Save(memstm); using (var istm = new ManagedIStream(memstm)) { // We are not bubbling out GDI+ errors when creating the native image fails. IntPtr bitmap = IntPtr.Zero; try { Status gpStatus = NativeMethods.GdipCreateBitmapFromStream(istm, out bitmap); if (Status.Ok != gpStatus) { return IntPtr.Zero; } IntPtr hicon; gpStatus = NativeMethods.GdipCreateHICONFromBitmap(bitmap, out hicon); if (Status.Ok != gpStatus) { return IntPtr.Zero; } // Caller is responsible for freeing this. return hicon; } finally { Utility.SafeDisposeImage(ref bitmap); } } } } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static void AddDependencyPropertyChangeListener(object component, DependencyProperty property, EventHandler listener) { if (component == null) { return; } Assert.IsNotNull(property); Assert.IsNotNull(listener); DependencyPropertyDescriptor dpd = DependencyPropertyDescriptor.FromProperty(property, component.GetType()); dpd.AddValueChanged(component, listener); } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static void RemoveDependencyPropertyChangeListener(object component, DependencyProperty property, EventHandler listener) { if (component == null) { return; } Assert.IsNotNull(property); Assert.IsNotNull(listener); DependencyPropertyDescriptor dpd = DependencyPropertyDescriptor.FromProperty(property, component.GetType()); dpd.RemoveValueChanged(component, listener); } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static bool IsNonNegative(this Thickness thickness) { if (!thickness.Top.IsFiniteAndNonNegative()) { return false; } if (!thickness.Left.IsFiniteAndNonNegative()) { return false; } if (!thickness.Bottom.IsFiniteAndNonNegative()) { return false; } if (!thickness.Right.IsFiniteAndNonNegative()) { return false; } return true; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static bool IsValid(this CornerRadius cornerRadius) { if (!cornerRadius.TopLeft.IsFiniteAndNonNegative()) { return false; } if (!cornerRadius.TopRight.IsFiniteAndNonNegative()) { return false; } if (!cornerRadius.BottomLeft.IsFiniteAndNonNegative()) { return false; } if (!cornerRadius.BottomRight.IsFiniteAndNonNegative()) { return false; } return true; } } }
/* ==================================================================== */ 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 Oranikle.ReportDesigner { /// <summary> /// Grouping specification: used for DataRegions (List, Chart, Table, Matrix), DataSets, group instances /// </summary> internal class GroupingCtl : Oranikle.ReportDesigner.Base.BaseControl, IProperty { private DesignXmlDraw _Draw; private XmlNode _GroupingParent; private DataTable _DataTable; // private DGCBColumn dgtbGE; private DataGridTextBoxColumn dgtbGE; private Oranikle.Studio.Controls.StyledButton bDelete; private System.Windows.Forms.DataGridTableStyle dgTableStyle; private Oranikle.Studio.Controls.StyledButton bUp; private Oranikle.Studio.Controls.StyledButton bDown; private System.Windows.Forms.DataGrid dgGroup; private System.Windows.Forms.Label label1; private Oranikle.Studio.Controls.CustomTextControl tbName; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private Oranikle.Studio.Controls.StyledComboBox cbLabelExpr; private Oranikle.Studio.Controls.StyledComboBox cbParentExpr; private Oranikle.Studio.Controls.StyledCheckBox chkPBS; private Oranikle.Studio.Controls.StyledCheckBox chkPBE; private Oranikle.Studio.Controls.StyledCheckBox chkRepeatHeader; private Oranikle.Studio.Controls.StyledCheckBox chkGrpHeader; private Oranikle.Studio.Controls.StyledCheckBox chkRepeatFooter; private Oranikle.Studio.Controls.StyledCheckBox chkGrpFooter; private System.Windows.Forms.Label lParent; private Oranikle.Studio.Controls.StyledButton bValueExpr; private Oranikle.Studio.Controls.StyledButton bLabelExpr; private Oranikle.Studio.Controls.StyledButton bParentExpr; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; internal GroupingCtl(DesignXmlDraw dxDraw, XmlNode groupingParent) { _Draw = dxDraw; _GroupingParent = groupingParent; // 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 // dgtbGE = new DGCBColumn(ComboBoxStyle.DropDown); dgtbGE = new DataGridTextBoxColumn(); this.dgTableStyle.GridColumnStyles.AddRange(new DataGridColumnStyle[] { this.dgtbGE}); // // dgtbGE // dgtbGE.HeaderText = "Expression"; dgtbGE.MappingName = "Expression"; dgtbGE.Width = 175; // Get the parent's dataset name // string dataSetName = _Draw.GetDataSetNameValue(_GroupingParent); // // string[] fields = _Draw.GetFields(dataSetName, true); // if (fields != null) // dgtbGE.CB.Items.AddRange(fields); // Initialize the DataTable _DataTable = new DataTable(); _DataTable.Columns.Add(new DataColumn("Expression", typeof(string))); string[] rowValues = new string[1]; XmlNode grouping = _Draw.GetNamedChildNode(_GroupingParent, "Grouping"); // Handle the group expressions XmlNode groupingExs = _Draw.GetNamedChildNode(grouping, "GroupExpressions"); if (groupingExs != null) foreach (XmlNode gNode in groupingExs.ChildNodes) { if (gNode.NodeType != XmlNodeType.Element || gNode.Name != "GroupExpression") continue; rowValues[0] = gNode.InnerText; _DataTable.Rows.Add(rowValues); } this.dgGroup.DataSource = _DataTable; DataGridTableStyle ts = dgGroup.TableStyles[0]; // ts.PreferredRowHeight = dgtbGE.CB.Height; ts.GridColumnStyles[0].Width = 330; // if (grouping == null) { this.tbName.Text = ""; this.cbParentExpr.Text = ""; this.cbLabelExpr.Text = ""; } else { this.chkPBE.Checked = _Draw.GetElementValue(grouping, "PageBreakAtEnd", "false").ToLower() == "true"; this.chkPBS.Checked = _Draw.GetElementValue(grouping, "PageBreakAtStart", "false").ToLower() == "true"; this.tbName.Text = _Draw.GetElementAttribute(grouping, "Name", ""); this.cbParentExpr.Text = _Draw.GetElementValue(grouping, "Parent", ""); this.cbLabelExpr.Text = _Draw.GetElementValue(grouping, "Label", ""); } if (_GroupingParent.Name == "TableGroup") { XmlNode repeat; repeat = DesignXmlDraw.FindNextInHierarchy(_GroupingParent, "Header", "RepeatOnNewPage"); if (repeat != null) this.chkRepeatHeader.Checked = repeat.InnerText.ToLower() == "true"; repeat = DesignXmlDraw.FindNextInHierarchy(_GroupingParent, "Footer", "RepeatOnNewPage"); if (repeat != null) this.chkRepeatFooter.Checked = repeat.InnerText.ToLower() == "true"; this.chkGrpHeader.Checked = _Draw.GetNamedChildNode(_GroupingParent, "Header") != null; this.chkGrpFooter.Checked = _Draw.GetNamedChildNode(_GroupingParent, "Footer") != null; } else { this.chkRepeatFooter.Visible = false; this.chkRepeatHeader.Visible = false; this.chkGrpFooter.Visible = false; this.chkGrpHeader.Visible = false; } if (_GroupingParent.Name == "DynamicColumns" || _GroupingParent.Name == "DynamicRows") { this.chkPBE.Visible = this.chkPBS.Visible = false; } else if (_GroupingParent.Name == "DynamicSeries" || _GroupingParent.Name == "DynamicCategories") { this.chkPBE.Visible = this.chkPBS.Visible = false; this.cbParentExpr.Visible = this.lParent.Visible = false; this.cbLabelExpr.Text = _Draw.GetElementValue(_GroupingParent, "Label", ""); } // load label and parent controls with fields string dsn = _Draw.GetDataSetNameValue(_GroupingParent); if (dsn != null) // found it { string[] f = _Draw.GetFields(dsn, true); if (f != null) { this.cbParentExpr.Items.AddRange(f); this.cbLabelExpr.Items.AddRange(f); } } } /// <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.dgGroup = new System.Windows.Forms.DataGrid(); this.dgTableStyle = new System.Windows.Forms.DataGridTableStyle(); this.bDelete = new Oranikle.Studio.Controls.StyledButton(); this.bUp = new Oranikle.Studio.Controls.StyledButton(); this.bDown = new Oranikle.Studio.Controls.StyledButton(); this.label1 = new System.Windows.Forms.Label(); this.tbName = new Oranikle.Studio.Controls.CustomTextControl(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.cbLabelExpr = new Oranikle.Studio.Controls.StyledComboBox(); this.cbParentExpr = new Oranikle.Studio.Controls.StyledComboBox(); this.lParent = new System.Windows.Forms.Label(); this.chkPBS = new Oranikle.Studio.Controls.StyledCheckBox(); this.chkPBE = new Oranikle.Studio.Controls.StyledCheckBox(); this.chkRepeatHeader = new Oranikle.Studio.Controls.StyledCheckBox(); this.chkGrpHeader = new Oranikle.Studio.Controls.StyledCheckBox(); this.chkRepeatFooter = new Oranikle.Studio.Controls.StyledCheckBox(); this.chkGrpFooter = new Oranikle.Studio.Controls.StyledCheckBox(); this.bValueExpr = new Oranikle.Studio.Controls.StyledButton(); this.bLabelExpr = new Oranikle.Studio.Controls.StyledButton(); this.bParentExpr = new Oranikle.Studio.Controls.StyledButton(); ((System.ComponentModel.ISupportInitialize)(this.dgGroup)).BeginInit(); this.SuspendLayout(); // // dgGroup // this.dgGroup.BackgroundColor = System.Drawing.Color.White; this.dgGroup.CaptionVisible = false; this.dgGroup.DataMember = ""; this.dgGroup.HeaderForeColor = System.Drawing.SystemColors.ControlText; this.dgGroup.Location = new System.Drawing.Point(8, 48); this.dgGroup.Name = "dgGroup"; this.dgGroup.Size = new System.Drawing.Size(376, 88); this.dgGroup.TabIndex = 1; this.dgGroup.TableStyles.AddRange(new System.Windows.Forms.DataGridTableStyle[] { this.dgTableStyle}); // // dgTableStyle // this.dgTableStyle.AllowSorting = false; this.dgTableStyle.DataGrid = this.dgGroup; this.dgTableStyle.HeaderForeColor = System.Drawing.SystemColors.ControlText; // // bDelete // this.bDelete.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245))))); this.bDelete.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225))))); this.bDelete.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.bDelete.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200))))); this.bDelete.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.bDelete.Font = new System.Drawing.Font("Arial", 9F); this.bDelete.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90))))); this.bDelete.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bDelete.Location = new System.Drawing.Point(392, 69); this.bDelete.Name = "bDelete"; this.bDelete.OverriddenSize = null; this.bDelete.Size = new System.Drawing.Size(48, 21); this.bDelete.TabIndex = 2; this.bDelete.Text = "Delete"; this.bDelete.UseVisualStyleBackColor = true; this.bDelete.Click += new System.EventHandler(this.bDelete_Click); // // bUp // this.bUp.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245))))); this.bUp.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225))))); this.bUp.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.bUp.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200))))); this.bUp.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.bUp.Font = new System.Drawing.Font("Arial", 9F); this.bUp.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90))))); this.bUp.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bUp.Location = new System.Drawing.Point(392, 94); this.bUp.Name = "bUp"; this.bUp.OverriddenSize = null; this.bUp.Size = new System.Drawing.Size(48, 21); this.bUp.TabIndex = 3; this.bUp.Text = "Up"; this.bUp.UseVisualStyleBackColor = true; this.bUp.Click += new System.EventHandler(this.bUp_Click); // // bDown // this.bDown.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245))))); this.bDown.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225))))); this.bDown.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.bDown.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200))))); this.bDown.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.bDown.Font = new System.Drawing.Font("Arial", 9F); this.bDown.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90))))); this.bDown.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bDown.Location = new System.Drawing.Point(392, 119); this.bDown.Name = "bDown"; this.bDown.OverriddenSize = null; this.bDown.Size = new System.Drawing.Size(48, 21); this.bDown.TabIndex = 4; this.bDown.Text = "Down"; this.bDown.UseVisualStyleBackColor = true; this.bDown.Click += new System.EventHandler(this.bDown_Click); // // label1 // this.label1.Location = new System.Drawing.Point(8, 8); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(48, 23); this.label1.TabIndex = 5; this.label1.Text = "Name"; // // tbName // this.tbName.AddX = 0; this.tbName.AddY = 0; this.tbName.AllowSpace = false; this.tbName.BorderColor = System.Drawing.Color.LightGray; this.tbName.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.tbName.ChangeVisibility = false; this.tbName.ChildControl = null; this.tbName.ConvertEnterToTab = true; this.tbName.ConvertEnterToTabForDialogs = false; this.tbName.Decimals = 0; this.tbName.DisplayList = new object[0]; this.tbName.HitText = Oranikle.Studio.Controls.HitText.String; this.tbName.Location = new System.Drawing.Point(56, 8); this.tbName.Name = "tbName"; this.tbName.OnDropDownCloseFocus = true; this.tbName.SelectType = 0; this.tbName.Size = new System.Drawing.Size(328, 20); this.tbName.TabIndex = 0; this.tbName.Text = "textBox1"; this.tbName.UseValueForChildsVisibilty = false; this.tbName.Value = true; this.tbName.Validating += new System.ComponentModel.CancelEventHandler(this.tbName_Validating); // // label2 // this.label2.Location = new System.Drawing.Point(8, 146); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(40, 23); this.label2.TabIndex = 7; this.label2.Text = "Label"; // // label3 // this.label3.Location = new System.Drawing.Point(8, 32); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(56, 16); this.label3.TabIndex = 9; this.label3.Text = "Group By"; // // cbLabelExpr // this.cbLabelExpr.AutoAdjustItemHeight = false; this.cbLabelExpr.BorderColor = System.Drawing.Color.LightGray; this.cbLabelExpr.ConvertEnterToTabForDialogs = false; this.cbLabelExpr.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable; this.cbLabelExpr.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.cbLabelExpr.Location = new System.Drawing.Point(48, 147); this.cbLabelExpr.Name = "cbLabelExpr"; this.cbLabelExpr.SeparatorColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90))))); this.cbLabelExpr.SeparatorMargin = 1; this.cbLabelExpr.SeparatorStyle = System.Drawing.Drawing2D.DashStyle.Solid; this.cbLabelExpr.SeparatorWidth = 1; this.cbLabelExpr.Size = new System.Drawing.Size(336, 21); this.cbLabelExpr.TabIndex = 5; this.cbLabelExpr.Text = "comboBox1"; // // cbParentExpr // this.cbParentExpr.AutoAdjustItemHeight = false; this.cbParentExpr.BorderColor = System.Drawing.Color.LightGray; this.cbParentExpr.ConvertEnterToTabForDialogs = false; this.cbParentExpr.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable; this.cbParentExpr.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.cbParentExpr.Location = new System.Drawing.Point(48, 180); this.cbParentExpr.Name = "cbParentExpr"; this.cbParentExpr.SeparatorColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90))))); this.cbParentExpr.SeparatorMargin = 1; this.cbParentExpr.SeparatorStyle = System.Drawing.Drawing2D.DashStyle.Solid; this.cbParentExpr.SeparatorWidth = 1; this.cbParentExpr.Size = new System.Drawing.Size(336, 21); this.cbParentExpr.TabIndex = 6; this.cbParentExpr.Text = "comboBox1"; // // lParent // this.lParent.Location = new System.Drawing.Point(8, 179); this.lParent.Name = "lParent"; this.lParent.Size = new System.Drawing.Size(40, 23); this.lParent.TabIndex = 11; this.lParent.Text = "Parent"; // // chkPBS // this.chkPBS.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.chkPBS.ForeColor = System.Drawing.Color.Black; this.chkPBS.Location = new System.Drawing.Point(8, 208); this.chkPBS.Name = "chkPBS"; this.chkPBS.Size = new System.Drawing.Size(136, 24); this.chkPBS.TabIndex = 7; this.chkPBS.Text = "Page Break at Start"; // // chkPBE // this.chkPBE.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.chkPBE.ForeColor = System.Drawing.Color.Black; this.chkPBE.Location = new System.Drawing.Point(232, 208); this.chkPBE.Name = "chkPBE"; this.chkPBE.Size = new System.Drawing.Size(136, 24); this.chkPBE.TabIndex = 8; this.chkPBE.Text = "Page Break at End"; // // chkRepeatHeader // this.chkRepeatHeader.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.chkRepeatHeader.ForeColor = System.Drawing.Color.Black; this.chkRepeatHeader.Location = new System.Drawing.Point(232, 232); this.chkRepeatHeader.Name = "chkRepeatHeader"; this.chkRepeatHeader.Size = new System.Drawing.Size(136, 24); this.chkRepeatHeader.TabIndex = 13; this.chkRepeatHeader.Text = "Repeat group header"; // // chkGrpHeader // this.chkGrpHeader.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.chkGrpHeader.ForeColor = System.Drawing.Color.Black; this.chkGrpHeader.Location = new System.Drawing.Point(8, 232); this.chkGrpHeader.Name = "chkGrpHeader"; this.chkGrpHeader.Size = new System.Drawing.Size(136, 24); this.chkGrpHeader.TabIndex = 12; this.chkGrpHeader.Text = "Include group header"; // // chkRepeatFooter // this.chkRepeatFooter.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.chkRepeatFooter.ForeColor = System.Drawing.Color.Black; this.chkRepeatFooter.Location = new System.Drawing.Point(232, 256); this.chkRepeatFooter.Name = "chkRepeatFooter"; this.chkRepeatFooter.Size = new System.Drawing.Size(136, 24); this.chkRepeatFooter.TabIndex = 15; this.chkRepeatFooter.Text = "Repeat group footer"; // // chkGrpFooter // this.chkGrpFooter.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.chkGrpFooter.ForeColor = System.Drawing.Color.Black; this.chkGrpFooter.Location = new System.Drawing.Point(8, 256); this.chkGrpFooter.Name = "chkGrpFooter"; this.chkGrpFooter.Size = new System.Drawing.Size(136, 24); this.chkGrpFooter.TabIndex = 14; this.chkGrpFooter.Text = "Include group footer"; // // bValueExpr // this.bValueExpr.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245))))); this.bValueExpr.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225))))); this.bValueExpr.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.bValueExpr.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200))))); this.bValueExpr.FlatStyle = System.Windows.Forms.FlatStyle.Flat; 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.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90))))); this.bValueExpr.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bValueExpr.Location = new System.Drawing.Point(392, 45); this.bValueExpr.Name = "bValueExpr"; this.bValueExpr.OverriddenSize = null; this.bValueExpr.Size = new System.Drawing.Size(22, 21); this.bValueExpr.TabIndex = 16; this.bValueExpr.Tag = "value"; this.bValueExpr.Text = "fx"; this.bValueExpr.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bValueExpr.UseVisualStyleBackColor = true; this.bValueExpr.Click += new System.EventHandler(this.bValueExpr_Click); // // bLabelExpr // this.bLabelExpr.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245))))); this.bLabelExpr.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225))))); this.bLabelExpr.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.bLabelExpr.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200))))); this.bLabelExpr.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.bLabelExpr.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.bLabelExpr.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90))))); this.bLabelExpr.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bLabelExpr.Location = new System.Drawing.Point(392, 147); this.bLabelExpr.Name = "bLabelExpr"; this.bLabelExpr.OverriddenSize = null; this.bLabelExpr.Size = new System.Drawing.Size(22, 21); this.bLabelExpr.TabIndex = 17; this.bLabelExpr.Tag = "label"; this.bLabelExpr.Text = "fx"; this.bLabelExpr.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bLabelExpr.UseVisualStyleBackColor = true; this.bLabelExpr.Click += new System.EventHandler(this.bExpr_Click); // // bParentExpr // this.bParentExpr.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245))))); this.bParentExpr.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225))))); this.bParentExpr.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.bParentExpr.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200))))); this.bParentExpr.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.bParentExpr.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.bParentExpr.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90))))); this.bParentExpr.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bParentExpr.Location = new System.Drawing.Point(392, 180); this.bParentExpr.Name = "bParentExpr"; this.bParentExpr.OverriddenSize = null; this.bParentExpr.Size = new System.Drawing.Size(22, 21); this.bParentExpr.TabIndex = 18; this.bParentExpr.Tag = "parent"; this.bParentExpr.Text = "fx"; this.bParentExpr.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bParentExpr.UseVisualStyleBackColor = true; this.bParentExpr.Click += new System.EventHandler(this.bExpr_Click); // // GroupingCtl // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.Controls.Add(this.bParentExpr); this.Controls.Add(this.bLabelExpr); this.Controls.Add(this.bValueExpr); this.Controls.Add(this.chkRepeatFooter); this.Controls.Add(this.chkGrpFooter); this.Controls.Add(this.chkRepeatHeader); this.Controls.Add(this.chkGrpHeader); this.Controls.Add(this.chkPBE); this.Controls.Add(this.chkPBS); this.Controls.Add(this.cbParentExpr); this.Controls.Add(this.lParent); this.Controls.Add(this.cbLabelExpr); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.tbName); this.Controls.Add(this.label1); this.Controls.Add(this.bDown); this.Controls.Add(this.bUp); this.Controls.Add(this.bDelete); this.Controls.Add(this.dgGroup); this.Name = "GroupingCtl"; this.Size = new System.Drawing.Size(488, 304); ((System.ComponentModel.ISupportInitialize)(this.dgGroup)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion public bool IsValid() { // Check to see if we have an expression bool bRows=HasRows(); // If no rows and no data if (!bRows && this.tbName.Text.Trim().Length == 0) { if (_GroupingParent.Name == "Details" || _GroupingParent.Name == "List") return true; MessageBox.Show("Group must be defined.", "Grouping"); return false; } // Grouping must have name XmlNode grouping = _Draw.GetNamedChildNode(_GroupingParent, "Grouping"); string nerr = _Draw.GroupingNameCheck(grouping, this.tbName.Text); if (nerr != null) { MessageBox.Show(nerr, "Group Name in Error"); return false; } if (!bRows) { MessageBox.Show("No expressions have been defined for the group.", "Group"); return false; } if (_GroupingParent.Name != "DynamicSeries") return true; // DynamicSeries grouping must have a label for the legend if (this.cbLabelExpr.Text.Length > 0) return true; MessageBox.Show("Chart series must have label defined for the legend.", "Chart"); return false; } private bool HasRows() { bool bRows=false; foreach (DataRow dr in _DataTable.Rows) { if (dr[0] == DBNull.Value) continue; string ge = (string) dr[0]; if (ge.Length <= 0) continue; bRows = true; break; } return bRows; } public void Apply() { if (!HasRows()) // No expressions in grouping; get rid of grouping { _Draw.RemoveElement(_GroupingParent, "Grouping"); // can't have a grouping return; } // Get the group XmlNode grouping = _Draw.GetCreateNamedChildNode(_GroupingParent, "Grouping"); _Draw.SetGroupName(grouping, tbName.Text.Trim()); // Handle the label if (_GroupingParent.Name == "DynamicSeries" || _GroupingParent.Name == "DynamicCategories") { if (this.cbLabelExpr.Text.Length > 0) _Draw.SetElement(_GroupingParent, "Label", cbLabelExpr.Text); else _Draw.RemoveElement(_GroupingParent, "Label"); } else { if (this.cbLabelExpr.Text.Length > 0) _Draw.SetElement(grouping, "Label", cbLabelExpr.Text); else _Draw.RemoveElement(grouping, "Label"); _Draw.SetElement(grouping, "PageBreakAtStart", this.chkPBS.Checked? "true": "false"); _Draw.SetElement(grouping, "PageBreakAtEnd", this.chkPBE.Checked? "true": "false"); if (cbParentExpr.Text.Length > 0) _Draw.SetElement(grouping, "Parent", cbParentExpr.Text); else _Draw.RemoveElement(grouping, "Parent"); } // Loop thru and add all the group expressions XmlNode grpExprs = _Draw.GetCreateNamedChildNode(grouping, "GroupExpressions"); grpExprs.RemoveAll(); string firstexpr=null; foreach (DataRow dr in _DataTable.Rows) { if (dr[0] == DBNull.Value) continue; string ge = (string) dr[0]; if (ge.Length <= 0) continue; _Draw.CreateElement(grpExprs, "GroupExpression", ge); if (firstexpr == null) firstexpr = ge; } if (!grpExprs.HasChildNodes) { // With no group expressions there are no groups grouping.RemoveChild(grpExprs); grouping.ParentNode.RemoveChild(grouping); grouping = null; } if (_GroupingParent.Name == "TableGroup" && grouping != null) { if (this.chkGrpHeader.Checked) { XmlNode header = _Draw.GetCreateNamedChildNode(_GroupingParent, "Header"); _Draw.SetElement(header, "RepeatOnNewPage", chkRepeatHeader.Checked? "true": "false"); XmlNode tblRows = _Draw.GetCreateNamedChildNode(header, "TableRows"); if (!tblRows.HasChildNodes) { // We need to create a row _Draw.InsertTableRow(tblRows); } } else { _Draw.RemoveElement(_GroupingParent, "Header"); } if (this.chkGrpFooter.Checked) { XmlNode footer = _Draw.GetCreateNamedChildNode(_GroupingParent, "Footer"); _Draw.SetElement(footer, "RepeatOnNewPage", chkRepeatFooter.Checked? "true": "false"); XmlNode tblRows = _Draw.GetCreateNamedChildNode(footer, "TableRows"); if (!tblRows.HasChildNodes) { // We need to create a row _Draw.InsertTableRow(tblRows); } } else { _Draw.RemoveElement(_GroupingParent, "Footer"); } } else if (_GroupingParent.Name == "DynamicColumns" || _GroupingParent.Name == "DynamicRows") { XmlNode ritems = _Draw.GetNamedChildNode(_GroupingParent, "ReportItems"); if (ritems == null) ritems = _Draw.GetCreateNamedChildNode(_GroupingParent, "ReportItems"); XmlNode item = ritems.FirstChild; if (item == null) { item = _Draw.GetCreateNamedChildNode(ritems, "Textbox"); XmlNode vnode = _Draw.GetCreateNamedChildNode(item, "Value"); vnode.InnerText = firstexpr == null? "": firstexpr; } } } private void bDelete_Click(object sender, System.EventArgs e) { int cr = dgGroup.CurrentRowIndex; if (cr < 0) // already at the top return; else if (cr == 0) { DataRow dr = _DataTable.Rows[0]; dr[0] = null; } this._DataTable.Rows.RemoveAt(cr); } private void bUp_Click(object sender, System.EventArgs e) { int cr = dgGroup.CurrentRowIndex; if (cr <= 0) // already at the top return; SwapRow(_DataTable.Rows[cr-1], _DataTable.Rows[cr]); dgGroup.CurrentRowIndex = cr-1; } private void bDown_Click(object sender, System.EventArgs e) { int cr = dgGroup.CurrentRowIndex; if (cr < 0) // invalid index return; if (cr + 1 >= _DataTable.Rows.Count) return; // already at end SwapRow(_DataTable.Rows[cr+1], _DataTable.Rows[cr]); dgGroup.CurrentRowIndex = cr+1; } private void SwapRow(DataRow tdr, DataRow fdr) { // column 1 object save = tdr[0]; tdr[0] = fdr[0]; fdr[0] = save; // column 2 save = tdr[1]; tdr[1] = fdr[1]; fdr[1] = save; // column 3 save = tdr[2]; tdr[2] = fdr[2]; fdr[2] = save; return; } private void tbName_Validating(object sender, System.ComponentModel.CancelEventArgs e) { bool bRows=HasRows(); // If no rows and no data in name it's ok if (!bRows && this.tbName.Text.Trim().Length == 0) return; if (!ReportNames.IsNameValid(tbName.Text)) { e.Cancel = true; MessageBox.Show(string.Format("{0} is an invalid name.", tbName.Text), "Name"); } } private void bValueExpr_Click(object sender, System.EventArgs e) { int cr = dgGroup.CurrentRowIndex; if (cr < 0) { // No rows yet; create one string[] rowValues = new string[1]; rowValues[0] = null; _DataTable.Rows.Add(rowValues); cr = 0; } DataGridCell dgc = dgGroup.CurrentCell; int cc = dgc.ColumnNumber; DataRow dr = _DataTable.Rows[cr]; string cv = dr[cc] as string; DialogExprEditor ee = new DialogExprEditor(_Draw, cv, _GroupingParent, false); try { DialogResult dlgr = ee.ShowDialog(); if (dlgr == DialogResult.OK) dr[cc] = ee.Expression; } finally { ee.Dispose(); } } private void bExpr_Click(object sender, System.EventArgs e) { Button b = sender as Button; if (b == null) return; Control c = null; switch (b.Tag as string) { case "label": c = this.cbLabelExpr; break; case "parent": c = this.cbParentExpr; break; } if (c == null) return; DialogExprEditor ee = new DialogExprEditor(_Draw, c.Text, _GroupingParent, false); try { DialogResult dr = ee.ShowDialog(); if (dr == DialogResult.OK) c.Text = ee.Expression; } finally { ee.Dispose(); } return; } } }
// 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.CodeAnalysis; using System.Globalization; using System.Runtime.ConstrainedExecution; using System.Security.Principal; namespace System.Threading { #if PROJECTN [Internal.Runtime.CompilerServices.RelocatedType("System.Threading.Thread")] #endif public sealed partial class Thread : CriticalFinalizerObject { private static AsyncLocal<IPrincipal?>? s_asyncLocalPrincipal; [ThreadStatic] private static Thread? t_currentThread; public Thread(ThreadStart start) : this() { if (start == null) { throw new ArgumentNullException(nameof(start)); } Create(start); } public Thread(ThreadStart start, int maxStackSize) : this() { if (start == null) { throw new ArgumentNullException(nameof(start)); } if (maxStackSize < 0) { throw new ArgumentOutOfRangeException(nameof(maxStackSize), SR.ArgumentOutOfRange_NeedNonNegNum); } Create(start, maxStackSize); } public Thread(ParameterizedThreadStart start) : this() { if (start == null) { throw new ArgumentNullException(nameof(start)); } Create(start); } public Thread(ParameterizedThreadStart start, int maxStackSize) : this() { if (start == null) { throw new ArgumentNullException(nameof(start)); } if (maxStackSize < 0) { throw new ArgumentOutOfRangeException(nameof(maxStackSize), SR.ArgumentOutOfRange_NeedNonNegNum); } Create(start, maxStackSize); } private void RequireCurrentThread() { if (this != CurrentThread) { throw new InvalidOperationException(SR.Thread_Operation_RequiresCurrentThread); } } private void SetCultureOnUnstartedThread(CultureInfo value, bool uiCulture) { if (value == null) { throw new ArgumentNullException(nameof(value)); } if ((ThreadState & ThreadState.Unstarted) == 0) { throw new InvalidOperationException(SR.Thread_Operation_RequiresCurrentThread); } SetCultureOnUnstartedThreadNoCheck(value, uiCulture); } partial void ThreadNameChanged(string? value); public CultureInfo CurrentCulture { get { RequireCurrentThread(); return CultureInfo.CurrentCulture; } set { if (this != CurrentThread) { SetCultureOnUnstartedThread(value, uiCulture: false); return; } CultureInfo.CurrentCulture = value; } } public CultureInfo CurrentUICulture { get { RequireCurrentThread(); return CultureInfo.CurrentUICulture; } set { if (this != CurrentThread) { SetCultureOnUnstartedThread(value, uiCulture: true); return; } CultureInfo.CurrentUICulture = value; } } public static IPrincipal? CurrentPrincipal { get { IPrincipal? principal = s_asyncLocalPrincipal?.Value; if (principal is null) { CurrentPrincipal = (principal = AppDomain.CurrentDomain.GetThreadPrincipal()); } return principal; } set { if (s_asyncLocalPrincipal is null) { if (value is null) { return; } Interlocked.CompareExchange(ref s_asyncLocalPrincipal, new AsyncLocal<IPrincipal?>(), null); } s_asyncLocalPrincipal.Value = value; } } public static Thread CurrentThread => t_currentThread ?? InitializeCurrentThread(); public ExecutionContext? ExecutionContext => ExecutionContext.Capture(); public string? Name { get => _name; set { lock (this) { if (_name != null) { throw new InvalidOperationException(SR.InvalidOperation_WriteOnce); } _name = value; ThreadNameChanged(value); } } } public void Abort() { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ThreadAbort); } public void Abort(object? stateInfo) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ThreadAbort); } public static void ResetAbort() { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ThreadAbort); } [ObsoleteAttribute("Thread.Suspend has been deprecated. Please use other classes in System.Threading, such as Monitor, Mutex, Event, and Semaphore, to synchronize Threads or protect resources. https://go.microsoft.com/fwlink/?linkid=14202", false)] public void Suspend() { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ThreadSuspend); } [ObsoleteAttribute("Thread.Resume has been deprecated. Please use other classes in System.Threading, such as Monitor, Mutex, Event, and Semaphore, to synchronize Threads or protect resources. https://go.microsoft.com/fwlink/?linkid=14202", false)] public void Resume() { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ThreadSuspend); } // Currently, no special handling is done for critical regions, and no special handling is necessary to ensure thread // affinity. If that changes, the relevant functions would instead need to delegate to RuntimeThread. public static void BeginCriticalRegion() { } public static void EndCriticalRegion() { } public static void BeginThreadAffinity() { } public static void EndThreadAffinity() { } public static LocalDataStoreSlot AllocateDataSlot() => LocalDataStore.AllocateSlot(); public static LocalDataStoreSlot AllocateNamedDataSlot(string name) => LocalDataStore.AllocateNamedSlot(name); public static LocalDataStoreSlot GetNamedDataSlot(string name) => LocalDataStore.GetNamedSlot(name); public static void FreeNamedDataSlot(string name) => LocalDataStore.FreeNamedSlot(name); public static object? GetData(LocalDataStoreSlot slot) => LocalDataStore.GetData(slot); public static void SetData(LocalDataStoreSlot slot, object? data) => LocalDataStore.SetData(slot, data); [Obsolete("The ApartmentState property has been deprecated. Use GetApartmentState, SetApartmentState or TrySetApartmentState instead.", false)] public ApartmentState ApartmentState { get { return GetApartmentState(); } set { TrySetApartmentState(value); } } public void SetApartmentState(ApartmentState state) { if (!TrySetApartmentState(state)) { throw GetApartmentStateChangeFailedException(); } } public bool TrySetApartmentState(ApartmentState state) { switch (state) { case ApartmentState.STA: case ApartmentState.MTA: case ApartmentState.Unknown: break; default: throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_Enum, nameof(state)); } return TrySetApartmentStateUnchecked(state); } [Obsolete("Thread.GetCompressedStack is no longer supported. Please use the System.Threading.CompressedStack class")] public CompressedStack GetCompressedStack() { throw new InvalidOperationException(SR.Thread_GetSetCompressedStack_NotSupported); } [Obsolete("Thread.SetCompressedStack is no longer supported. Please use the System.Threading.CompressedStack class")] public void SetCompressedStack(CompressedStack stack) { throw new InvalidOperationException(SR.Thread_GetSetCompressedStack_NotSupported); } public static AppDomain GetDomain() => AppDomain.CurrentDomain; public static int GetDomainID() => 1; public override int GetHashCode() => ManagedThreadId; public void Join() => Join(-1); public bool Join(TimeSpan timeout) => Join(WaitHandle.ToTimeoutMilliseconds(timeout)); public static void MemoryBarrier() => Interlocked.MemoryBarrier(); public static void Sleep(TimeSpan timeout) => Sleep(WaitHandle.ToTimeoutMilliseconds(timeout)); public static byte VolatileRead(ref byte address) => Volatile.Read(ref address); public static double VolatileRead(ref double address) => Volatile.Read(ref address); public static short VolatileRead(ref short address) => Volatile.Read(ref address); public static int VolatileRead(ref int address) => Volatile.Read(ref address); public static long VolatileRead(ref long address) => Volatile.Read(ref address); public static IntPtr VolatileRead(ref IntPtr address) => Volatile.Read(ref address); [return: NotNullIfNotNull("address")] public static object? VolatileRead(ref object? address) => Volatile.Read(ref address); [CLSCompliant(false)] public static sbyte VolatileRead(ref sbyte address) => Volatile.Read(ref address); public static float VolatileRead(ref float address) => Volatile.Read(ref address); [CLSCompliant(false)] public static ushort VolatileRead(ref ushort address) => Volatile.Read(ref address); [CLSCompliant(false)] public static uint VolatileRead(ref uint address) => Volatile.Read(ref address); [CLSCompliant(false)] public static ulong VolatileRead(ref ulong address) => Volatile.Read(ref address); [CLSCompliant(false)] public static UIntPtr VolatileRead(ref UIntPtr address) => Volatile.Read(ref address); public static void VolatileWrite(ref byte address, byte value) => Volatile.Write(ref address, value); public static void VolatileWrite(ref double address, double value) => Volatile.Write(ref address, value); public static void VolatileWrite(ref short address, short value) => Volatile.Write(ref address, value); public static void VolatileWrite(ref int address, int value) => Volatile.Write(ref address, value); public static void VolatileWrite(ref long address, long value) => Volatile.Write(ref address, value); public static void VolatileWrite(ref IntPtr address, IntPtr value) => Volatile.Write(ref address, value); public static void VolatileWrite([NotNullIfNotNull("value")] ref object? address, object? value) => Volatile.Write(ref address, value); [CLSCompliant(false)] public static void VolatileWrite(ref sbyte address, sbyte value) => Volatile.Write(ref address, value); public static void VolatileWrite(ref float address, float value) => Volatile.Write(ref address, value); [CLSCompliant(false)] public static void VolatileWrite(ref ushort address, ushort value) => Volatile.Write(ref address, value); [CLSCompliant(false)] public static void VolatileWrite(ref uint address, uint value) => Volatile.Write(ref address, value); [CLSCompliant(false)] public static void VolatileWrite(ref ulong address, ulong value) => Volatile.Write(ref address, value); [CLSCompliant(false)] public static void VolatileWrite(ref UIntPtr address, UIntPtr value) => Volatile.Write(ref address, value); /// <summary> /// Manages functionality required to support members of <see cref="Thread"/> dealing with thread-local data /// </summary> private static class LocalDataStore { private static Dictionary<string, LocalDataStoreSlot>? s_nameToSlotMap; public static LocalDataStoreSlot AllocateSlot() { return new LocalDataStoreSlot(new ThreadLocal<object?>()); } private static Dictionary<string, LocalDataStoreSlot> EnsureNameToSlotMap() { Dictionary<string, LocalDataStoreSlot>? nameToSlotMap = s_nameToSlotMap; if (nameToSlotMap != null) { return nameToSlotMap; } nameToSlotMap = new Dictionary<string, LocalDataStoreSlot>(); return Interlocked.CompareExchange(ref s_nameToSlotMap, nameToSlotMap, null) ?? nameToSlotMap; } public static LocalDataStoreSlot AllocateNamedSlot(string name) { LocalDataStoreSlot slot = AllocateSlot(); Dictionary<string, LocalDataStoreSlot> nameToSlotMap = EnsureNameToSlotMap(); lock (nameToSlotMap) { nameToSlotMap.Add(name, slot); } return slot; } public static LocalDataStoreSlot GetNamedSlot(string name) { Dictionary<string, LocalDataStoreSlot> nameToSlotMap = EnsureNameToSlotMap(); lock (nameToSlotMap) { LocalDataStoreSlot? slot; if (!nameToSlotMap.TryGetValue(name, out slot)) { slot = AllocateSlot(); nameToSlotMap[name] = slot; } return slot; } } public static void FreeNamedSlot(string name) { Dictionary<string, LocalDataStoreSlot> nameToSlotMap = EnsureNameToSlotMap(); lock (nameToSlotMap) { nameToSlotMap.Remove(name); } } private static ThreadLocal<object?> GetThreadLocal(LocalDataStoreSlot slot) { if (slot == null) { throw new ArgumentNullException(nameof(slot)); } Debug.Assert(slot.Data != null); return slot.Data; } public static object? GetData(LocalDataStoreSlot slot) { return GetThreadLocal(slot).Value; } public static void SetData(LocalDataStoreSlot slot, object? value) { GetThreadLocal(slot).Value = value; } } } }
using System; using System.IO; using System.Net; #if !(MONOTOUCH || SILVERLIGHT) using System.Web; #endif using ServiceStack.Common; using ServiceStack.Common.Web; using ServiceStack.Logging; using ServiceStack.Service; using ServiceStack.ServiceHost; using ServiceStack.Text; namespace ServiceStack.ServiceClient.Web { /** * Need to provide async request options * http://msdn.microsoft.com/en-us/library/86wf6409(VS.71).aspx */ public abstract class ServiceClientBase #if !SILVERLIGHT : IServiceClient, IRestClient #else : IServiceClient #endif { private static readonly ILog log = LogManager.GetLogger(typeof(ServiceClientBase)); /// <summary> /// The request filter is called before any request. /// This request filter is executed globally. /// </summary> private static Action<HttpWebRequest> httpWebRequestFilter; public static Action<HttpWebRequest> HttpWebRequestFilter { get { return httpWebRequestFilter; } set { httpWebRequestFilter = value; AsyncServiceClient.HttpWebRequestFilter = value; } } /// <summary> /// The response action is called once the server response is available. /// It will allow you to access raw response information. /// This response action is executed globally. /// Note that you should NOT consume the response stream as this is handled by ServiceStack /// </summary> private static Action<HttpWebResponse> httpWebResponseFilter; public static Action<HttpWebResponse> HttpWebResponseFilter { get { return httpWebResponseFilter; } set { httpWebResponseFilter = value; AsyncServiceClient.HttpWebResponseFilter = value; } } public const string DefaultHttpMethod = "POST"; readonly AsyncServiceClient asyncClient; protected ServiceClientBase() { this.HttpMethod = DefaultHttpMethod; this.CookieContainer = new CookieContainer(); asyncClient = new AsyncServiceClient { ContentType = ContentType, StreamSerializer = SerializeToStream, StreamDeserializer = StreamDeserializer, CookieContainer = this.CookieContainer, UserName = this.UserName, Password = this.Password, LocalHttpWebRequestFilter = this.LocalHttpWebRequestFilter, LocalHttpWebResponseFilter = this.LocalHttpWebResponseFilter }; this.StoreCookies = true; //leave #if SILVERLIGHT asyncClient.HandleCallbackOnUIThread = this.HandleCallbackOnUIThread = true; asyncClient.UseBrowserHttpHandling = this.UseBrowserHttpHandling = false; asyncClient.ShareCookiesWithBrowser = this.ShareCookiesWithBrowser = true; #endif } protected ServiceClientBase(string syncReplyBaseUri, string asyncOneWayBaseUri) : this() { this.SyncReplyBaseUri = syncReplyBaseUri; this.AsyncOneWayBaseUri = asyncOneWayBaseUri; } /// <summary> /// Sets all baseUri properties, using the Format property for the SyncReplyBaseUri and AsyncOneWayBaseUri /// </summary> /// <param name="baseUri">Base URI of the service</param> public void SetBaseUri(string baseUri) { this.BaseUri = baseUri; this.asyncClient.BaseUri = baseUri; this.SyncReplyBaseUri = baseUri.WithTrailingSlash() + Format + "/syncreply/"; this.AsyncOneWayBaseUri = baseUri.WithTrailingSlash() + Format + "/asynconeway/"; } /// <summary> /// Sets all baseUri properties allowing for a temporary override of the Format property /// </summary> /// <param name="baseUri">Base URI of the service</param> /// <param name="format">Override of the Format property for the service</param> //Marked obsolete on 4/11/2012 [Obsolete("Please call the SetBaseUri(string baseUri) method, which uses the specific implementation's Format property.")] public void SetBaseUri(string baseUri, string format) { this.BaseUri = baseUri; this.asyncClient.BaseUri = baseUri; this.SyncReplyBaseUri = baseUri.WithTrailingSlash() + format + "/syncreply/"; this.AsyncOneWayBaseUri = baseUri.WithTrailingSlash() + format + "/asynconeway/"; } private bool _disableAutoCompression; /// <summary> /// Whether to Accept Gzip,Deflate Content-Encoding and to auto decompress responses /// </summary> public bool DisableAutoCompression { get { return _disableAutoCompression; } set { _disableAutoCompression = value; asyncClient.DisableAutoCompression = value; } } private string _username; /// <summary> /// The user name for basic authentication /// </summary> public string UserName { get { return _username; } set { _username = value; asyncClient.UserName = value; } } private string _password; /// <summary> /// The password for basic authentication /// </summary> public string Password { get { return _password; } set { _password = value; asyncClient.Password = value; } } /// <summary> /// Sets the username and the password for basic authentication. /// </summary> public void SetCredentials(string userName, string password) { this.UserName = userName; this.Password = password; } public string BaseUri { get; set; } public abstract string Format { get; } public string SyncReplyBaseUri { get; set; } public string AsyncOneWayBaseUri { get; set; } private TimeSpan? timeout; public TimeSpan? Timeout { get { return this.timeout; } set { this.timeout = value; this.asyncClient.Timeout = value; } } public abstract string ContentType { get; } public string HttpMethod { get; set; } #if !SILVERLIGHT public IWebProxy Proxy { get; set; } #endif #if SILVERLIGHT private bool handleCallbackOnUiThread; public bool HandleCallbackOnUIThread { get { return this.handleCallbackOnUiThread; } set { asyncClient.HandleCallbackOnUIThread = this.handleCallbackOnUiThread = value; } } private bool useBrowserHttpHandling; public bool UseBrowserHttpHandling { get { return this.useBrowserHttpHandling; } set { asyncClient.UseBrowserHttpHandling = this.useBrowserHttpHandling = value; } } private bool shareCookiesWithBrowser; public bool ShareCookiesWithBrowser { get { return this.shareCookiesWithBrowser; } set { asyncClient.ShareCookiesWithBrowser = this.shareCookiesWithBrowser = value; } } #endif private ICredentials credentials; /// <summary> /// Gets or sets authentication information for the request. /// Warning: It's recommened to use <see cref="UserName"/> and <see cref="Password"/> for basic auth. /// This property is only used for IIS level authentication. /// </summary> public ICredentials Credentials { set { this.credentials = value; this.asyncClient.Credentials = value; } } /// <summary> /// Determines if the basic auth header should be sent with every request. /// By default, the basic auth header is only sent when "401 Unauthorized" is returned. /// </summary> public bool AlwaysSendBasicAuthHeader { get; set; } /// <summary> /// Specifies if cookies should be stored /// </summary> private bool storeCookies; public bool StoreCookies { get { return storeCookies; } set { asyncClient.StoreCookies = storeCookies = value; } } public CookieContainer CookieContainer { get; set; } /// <summary> /// Called before request resend, when the initial request required authentication /// </summary> private Action<WebRequest> onAuthenticationRequired { get; set; } public Action<WebRequest> OnAuthenticationRequired { get { return onAuthenticationRequired; } set { onAuthenticationRequired = value; asyncClient.OnAuthenticationRequired = value; } } /// <summary> /// The request filter is called before any request. /// This request filter only works with the instance where it was set (not global). /// </summary> private Action<HttpWebRequest> localHttpWebRequestFilter { get; set; } public Action<HttpWebRequest> LocalHttpWebRequestFilter { get { return localHttpWebRequestFilter; } set { localHttpWebRequestFilter = value; asyncClient.LocalHttpWebRequestFilter = value; } } /// <summary> /// The response action is called once the server response is available. /// It will allow you to access raw response information. /// Note that you should NOT consume the response stream as this is handled by ServiceStack /// </summary> private Action<HttpWebResponse> localHttpWebResponseFilter { get; set; } public Action<HttpWebResponse> LocalHttpWebResponseFilter { get { return localHttpWebResponseFilter; } set { localHttpWebResponseFilter = value; asyncClient.LocalHttpWebResponseFilter = value; } } public abstract void SerializeToStream(IRequestContext requestContext, object request, Stream stream); public abstract T DeserializeFromStream<T>(Stream stream); public abstract StreamDeserializerDelegate StreamDeserializer { get; } #if !SILVERLIGHT public virtual TResponse Send<TResponse>(object request) { var requestUri = this.SyncReplyBaseUri.WithTrailingSlash() + request.GetType().Name; var client = SendRequest(requestUri, request); try { var webResponse = client.GetResponse(); return HandleResponse<TResponse>(webResponse); } catch (Exception ex) { TResponse response; if (!HandleResponseException(ex, requestUri, () => SendRequest(Web.HttpMethod.Post, requestUri, request), c => c.GetResponse(), out response)) { throw; } return response; } } private bool HandleResponseException<TResponse>(Exception ex, string requestUri, Func<WebRequest> createWebRequest, Func<WebRequest, WebResponse> getResponse, out TResponse response) { try { if (WebRequestUtils.ShouldAuthenticate(ex, this.UserName, this.Password)) { var client = createWebRequest(); client.AddBasicAuth(this.UserName, this.Password); if (OnAuthenticationRequired != null) { OnAuthenticationRequired(client); } var webResponse = getResponse(client); response = HandleResponse<TResponse>(webResponse); return true; } } catch (Exception subEx) { // Since we are effectively re-executing the call, // the new exception should be shown to the caller rather // than the old one. // The new exception is either this one or the one thrown // by the following method. HandleResponseException<TResponse>(subEx, requestUri); throw; } // If this doesn't throw, the calling method // should rethrow the original exception upon // return value of false. HandleResponseException<TResponse>(ex, requestUri); response = default(TResponse); return false; } private void HandleResponseException<TResponse>(Exception ex, string requestUri) { var webEx = ex as WebException; if (webEx != null && webEx.Status == WebExceptionStatus.ProtocolError) { var errorResponse = ((HttpWebResponse)webEx.Response); log.Error(webEx); log.DebugFormat("Status Code : {0}", errorResponse.StatusCode); log.DebugFormat("Status Description : {0}", errorResponse.StatusDescription); var serviceEx = new WebServiceException(errorResponse.StatusDescription) { StatusCode = (int)errorResponse.StatusCode, StatusDescription = errorResponse.StatusDescription, }; try { if (errorResponse.ContentType.MatchesContentType(ContentType)) { using (var stream = errorResponse.GetResponseStream()) { serviceEx.ResponseDto = DeserializeFromStream<TResponse>(stream); } } else { serviceEx.ResponseBody = errorResponse.GetResponseStream().ReadFully().FromUtf8Bytes(); } } catch (Exception innerEx) { // Oh, well, we tried throw new WebServiceException(errorResponse.StatusDescription, innerEx) { StatusCode = (int)errorResponse.StatusCode, StatusDescription = errorResponse.StatusDescription, }; } //Escape deserialize exception handling and throw here throw serviceEx; } var authEx = ex as AuthenticationException; if (authEx != null) { throw WebRequestUtils.CreateCustomException(requestUri, authEx); } } private WebRequest SendRequest(string requestUri, object request) { return SendRequest(HttpMethod ?? DefaultHttpMethod, requestUri, request); } private WebRequest SendRequest(string httpMethod, string requestUri, object request) { return PrepareWebRequest(httpMethod, requestUri, request, client => { using (var requestStream = client.GetRequestStream()) { SerializeToStream(null, request, requestStream); } }); } private WebRequest PrepareWebRequest(string httpMethod, string requestUri, object request, Action<HttpWebRequest> sendRequestAction) { if (httpMethod == null) throw new ArgumentNullException("httpMethod"); if (httpMethod == Web.HttpMethod.Get && request != null) { var queryString = QueryStringSerializer.SerializeToString(request); if (!string.IsNullOrEmpty(queryString)) { requestUri += "?" + queryString; } } var client = (HttpWebRequest)WebRequest.Create(requestUri); try { client.Accept = ContentType; client.Method = httpMethod; if (Proxy != null) client.Proxy = Proxy; if (this.Timeout.HasValue) client.Timeout = (int)this.Timeout.Value.TotalMilliseconds; if (this.credentials != null) client.Credentials = this.credentials; if (this.AlwaysSendBasicAuthHeader) client.AddBasicAuth(this.UserName, this.Password); if (!DisableAutoCompression) { client.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate"); client.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; } if (StoreCookies) { client.CookieContainer = CookieContainer; } ApplyWebRequestFilters(client); if (httpMethod != Web.HttpMethod.Get && httpMethod != Web.HttpMethod.Delete) { client.ContentType = ContentType; if (sendRequestAction != null) sendRequestAction(client); } } catch (AuthenticationException ex) { throw WebRequestUtils.CreateCustomException(requestUri, ex) ?? ex; } return client; } private void ApplyWebResponseFilters(WebResponse webResponse) { if (!(webResponse is HttpWebResponse)) return; if (HttpWebResponseFilter != null) HttpWebResponseFilter((HttpWebResponse)webResponse); if (LocalHttpWebResponseFilter != null) LocalHttpWebResponseFilter((HttpWebResponse)webResponse); } private void ApplyWebRequestFilters(HttpWebRequest client) { if (LocalHttpWebRequestFilter != null) LocalHttpWebRequestFilter(client); if (HttpWebRequestFilter != null) HttpWebRequestFilter(client); } #else private void SendRequest(string requestUri, object request, Action<WebRequest> callback) { var isHttpGet = HttpMethod != null && HttpMethod.ToUpper() == "GET"; if (isHttpGet) { var queryString = QueryStringSerializer.SerializeToString(request); if (!string.IsNullOrEmpty(queryString)) { requestUri += "?" + queryString; } } SendRequest(HttpMethod ?? DefaultHttpMethod, requestUri, request, callback); } private void SendRequest(string httpMethod, string requestUri, object request, Action<WebRequest> callback) { if (httpMethod == null) throw new ArgumentNullException("httpMethod"); var client = (HttpWebRequest)WebRequest.Create(requestUri); try { client.Accept = ContentType; client.Method = httpMethod; if (this.credentials != null) client.Credentials = this.credentials; if (this.AlwaysSendBasicAuthHeader) client.AddBasicAuth(this.UserName, this.Password); if (StoreCookies) { client.CookieContainer = CookieContainer; } if (this.LocalHttpWebRequestFilter != null) LocalHttpWebRequestFilter(client); if (HttpWebRequestFilter != null) HttpWebRequestFilter(client); if (httpMethod != Web.HttpMethod.Get && httpMethod != Web.HttpMethod.Delete) { client.ContentType = ContentType; client.BeginGetRequestStream(delegate(IAsyncResult target) { var webReq = (HttpWebRequest)target.AsyncState; var requestStream = webReq.EndGetRequestStream(target); SerializeToStream(null, request, requestStream); callback(client); }, null); } } catch (AuthenticationException ex) { throw WebRequestUtils.CreateCustomException(requestUri, ex) ?? ex; } } #endif private string GetUrl(string relativeOrAbsoluteUrl) { return relativeOrAbsoluteUrl.StartsWith("http:") || relativeOrAbsoluteUrl.StartsWith("https:") ? relativeOrAbsoluteUrl : this.BaseUri.CombineWith(relativeOrAbsoluteUrl); } #if !SILVERLIGHT private byte[] DownloadBytes(string requestUri, object request) { var webRequest = SendRequest(requestUri, request); using (var response = webRequest.GetResponse()) { ApplyWebResponseFilters(response); using (var stream = response.GetResponseStream()) return stream.ReadFully(); } } #else private void DownloadBytes(string requestUri, object request, Action<byte[]> callback = null) { SendRequest(requestUri, request, webRequest => webRequest.BeginGetResponse(delegate(IAsyncResult result) { var webReq = (HttpWebRequest)result.AsyncState; var response = (HttpWebResponse)webReq.EndGetResponse(result); using (var stream = response.GetResponseStream()) { var bytes = stream.ReadFully(); if (callback != null) { callback(bytes); } } }, null)); } #endif public virtual void SendOneWay(object request) { var requestUri = this.AsyncOneWayBaseUri.WithTrailingSlash() + request.GetType().Name; DownloadBytes(requestUri, request); } public virtual void SendOneWay(string relativeOrAbsoluteUrl, object request) { var requestUri = GetUrl(relativeOrAbsoluteUrl); DownloadBytes(requestUri, request); } public virtual void SendAsync<TResponse>(object request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError) { var requestUri = this.SyncReplyBaseUri.WithTrailingSlash() + request.GetType().Name; asyncClient.SendAsync(Web.HttpMethod.Post, requestUri, request, onSuccess, onError); } public virtual void GetAsync<TResponse>(string relativeOrAbsoluteUrl, Action<TResponse> onSuccess, Action<TResponse, Exception> onError) { asyncClient.SendAsync(Web.HttpMethod.Get, GetUrl(relativeOrAbsoluteUrl), null, onSuccess, onError); } public virtual void DeleteAsync<TResponse>(string relativeOrAbsoluteUrl, Action<TResponse> onSuccess, Action<TResponse, Exception> onError) { asyncClient.SendAsync(Web.HttpMethod.Delete, GetUrl(relativeOrAbsoluteUrl), null, onSuccess, onError); } public virtual void PostAsync<TResponse>(string relativeOrAbsoluteUrl, object request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError) { asyncClient.SendAsync(Web.HttpMethod.Post, GetUrl(relativeOrAbsoluteUrl), request, onSuccess, onError); } public virtual void PutAsync<TResponse>(string relativeOrAbsoluteUrl, object request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError) { asyncClient.SendAsync(Web.HttpMethod.Put, GetUrl(relativeOrAbsoluteUrl), request, onSuccess, onError); } public virtual void CancelAsync() { asyncClient.CancelAsync(); } #if !SILVERLIGHT public virtual TResponse Send<TResponse>(string httpMethod, string relativeOrAbsoluteUrl, object request) { var requestUri = GetUrl(relativeOrAbsoluteUrl); var client = SendRequest(httpMethod, requestUri, request); try { var webResponse = client.GetResponse(); return HandleResponse<TResponse>(webResponse); } catch (Exception ex) { TResponse response; if (!HandleResponseException(ex, requestUri, () => SendRequest(httpMethod, requestUri, request), c => c.GetResponse(), out response)) { throw; } return response; } } public virtual TResponse Get<TResponse>(string relativeOrAbsoluteUrl) { return Send<TResponse>(Web.HttpMethod.Get, relativeOrAbsoluteUrl, null); } public virtual TResponse Delete<TResponse>(string relativeOrAbsoluteUrl) { return Send<TResponse>(Web.HttpMethod.Delete, relativeOrAbsoluteUrl, null); } public virtual TResponse Post<TResponse>(string relativeOrAbsoluteUrl, object request) { return Send<TResponse>(Web.HttpMethod.Post, relativeOrAbsoluteUrl, request); } public virtual TResponse Put<TResponse>(string relativeOrAbsoluteUrl, object request) { return Send<TResponse>(Web.HttpMethod.Put, relativeOrAbsoluteUrl, request); } public virtual TResponse Patch<TResponse>(string relativeOrAbsoluteUrl, object request) { return Send<TResponse>(Web.HttpMethod.Patch, relativeOrAbsoluteUrl, request); } public virtual TResponse PostFileWithRequest<TResponse>(string relativeOrAbsoluteUrl, FileInfo fileToUpload, object request) { return PostFileWithRequest<TResponse>(relativeOrAbsoluteUrl, fileToUpload.OpenRead(), fileToUpload.Name, request); } public virtual TResponse PostFileWithRequest<TResponse>(string relativeOrAbsoluteUrl, Stream fileToUpload, string fileName, object request) { var requestUri = GetUrl(relativeOrAbsoluteUrl); var currentStreamPosition = fileToUpload.Position; Func<WebRequest> createWebRequest = () => { var webRequest = PrepareWebRequest(Web.HttpMethod.Post, requestUri, null, null); var queryString = QueryStringSerializer.SerializeToString(request); #if !MONOTOUCH var nameValueCollection = HttpUtility.ParseQueryString(queryString); #endif var boundary = DateTime.Now.Ticks.ToString(); webRequest.ContentType = "multipart/form-data; boundary=" + boundary; boundary = "--" + boundary; var newLine = Environment.NewLine; using (var outputStream = webRequest.GetRequestStream()) { #if !MONOTOUCH foreach (var key in nameValueCollection.AllKeys) { outputStream.Write(boundary + newLine); outputStream.Write("Content-Disposition: form-data;name=\"{0}\"{1}{2}".FormatWith(key, newLine, newLine)); outputStream.Write(nameValueCollection[key] + newLine); } #endif outputStream.Write(boundary + newLine); outputStream.Write("Content-Disposition: form-data;name=\"{0}\";filename=\"{1}\"{2}{3}".FormatWith("upload", fileName, newLine, newLine)); var buffer = new byte[4096]; int byteCount; while ((byteCount = fileToUpload.Read(buffer, 0, 4096)) > 0) { outputStream.Write(buffer, 0, byteCount); } outputStream.Write(newLine); outputStream.Write(boundary + "--"); } return webRequest; }; try { var webRequest = createWebRequest(); var webResponse = webRequest.GetResponse(); return HandleResponse<TResponse>(webResponse); } catch (Exception ex) { TResponse response; // restore original position before retry fileToUpload.Seek(currentStreamPosition, SeekOrigin.Begin); if (!HandleResponseException(ex, requestUri, createWebRequest, c => c.GetResponse(), out response)) { throw; } return response; } } public virtual TResponse PostFile<TResponse>(string relativeOrAbsoluteUrl, FileInfo fileToUpload, string mimeType) { return PostFile<TResponse>(relativeOrAbsoluteUrl, fileToUpload.OpenRead(), fileToUpload.Name, mimeType); } public virtual TResponse PostFile<TResponse>(string relativeOrAbsoluteUrl, Stream fileToUpload, string fileName, string mimeType) { var currentStreamPosition = fileToUpload.Position; var requestUri = GetUrl(relativeOrAbsoluteUrl); Func<WebRequest> createWebRequest = () => PrepareWebRequest(Web.HttpMethod.Post, requestUri, null, null); try { var webRequest = createWebRequest(); webRequest.UploadFile(fileToUpload, fileName, mimeType); var webResponse = webRequest.GetResponse(); return HandleResponse<TResponse>(webResponse); } catch (Exception ex) { TResponse response; // restore original position before retry fileToUpload.Seek(currentStreamPosition, SeekOrigin.Begin); if (!HandleResponseException(ex, requestUri, createWebRequest, c => { c.UploadFile(fileToUpload, fileName, mimeType); return c.GetResponse(); }, out response)) { throw; } return response; } } private TResponse HandleResponse<TResponse>(WebResponse webResponse) { ApplyWebResponseFilters(webResponse); using (var responseStream = webResponse.GetResponseStream()) { var response = DeserializeFromStream<TResponse>(responseStream); return response; } } #endif public void Dispose() { } } }
using System; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace RedditSharp.Things { public class RedditUser : Thing { private const string OverviewUrl = "/user/{0}.json"; private const string CommentsUrl = "/user/{0}/comments.json"; private const string LinksUrl = "/user/{0}/submitted.json"; private const string SubscribedSubredditsUrl = "/subreddits/mine.json"; private const string LikedUrl = "/user/{0}/liked.json"; private const string DislikedUrl = "/user/{0}/disliked.json"; private const int MAX_LIMIT = 100; public RedditUser Init(Reddit reddit, JToken json, IWebAgent webAgent) { CommonInit(reddit, json, webAgent); JsonConvert.PopulateObject(json["name"] == null ? json["data"].ToString() : json.ToString(), this, reddit.JsonSerializerSettings); return this; } public async Task<RedditUser> InitAsync(Reddit reddit, JToken json, IWebAgent webAgent) { CommonInit(reddit, json, webAgent); await Task.Factory.StartNew(() => JsonConvert.PopulateObject(json["name"] == null ? json["data"].ToString() : json.ToString(), this, reddit.JsonSerializerSettings)); return this; } private void CommonInit(Reddit reddit, JToken json, IWebAgent webAgent) { base.Init(json); Reddit = reddit; WebAgent = webAgent; } [JsonIgnore] protected Reddit Reddit { get; set; } [JsonIgnore] protected IWebAgent WebAgent { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("is_gold")] public bool HasGold { get; set; } [JsonProperty("is_mod")] public bool IsModerator { get; set; } [JsonProperty("link_karma")] public int LinkKarma { get; set; } [JsonProperty("comment_karma")] public int CommentKarma { get; set; } [JsonProperty("created")] [JsonConverter(typeof(UnixTimestampConverter))] public DateTime Created { get; set; } public Listing<VotableThing> Overview { get { return new Listing<VotableThing>(Reddit, string.Format(OverviewUrl, Name), WebAgent); } } public Listing<Post> LikedPosts { get { return new Listing<Post>(Reddit, string.Format(LikedUrl, Name), WebAgent); } } public Listing<Post> DislikedPosts { get { return new Listing<Post>(Reddit, string.Format(DislikedUrl, Name), WebAgent); } } public Listing<Comment> Comments { get { return new Listing<Comment>(Reddit, string.Format(CommentsUrl, Name), WebAgent); } } public Listing<Post> Posts { get { return new Listing<Post>(Reddit, string.Format(LinksUrl, Name), WebAgent); } } public Listing<Subreddit> SubscribedSubreddits { get { return new Listing<Subreddit>(Reddit, SubscribedSubredditsUrl, WebAgent); } } /// <summary> /// Get a listing of comments from the user sorted by <paramref name="sorting"/>, from time <paramref name="fromTime"/> /// and limited to <paramref name="limit"/>. /// </summary> /// <param name="sorting">How to sort the comments (hot, new, top, controversial).</param> /// <param name="limit">How many comments to fetch per request. Max is 100.</param> /// <param name="fromTime">What time frame of comments to show (hour, day, week, month, year, all).</param> /// <returns>The listing of comments requested.</returns> public Listing<Comment> GetComments(Sort sorting = Sort.New, int limit = 25, FromTime fromTime = FromTime.All) { if ((limit < 1) || (limit > MAX_LIMIT)) throw new ArgumentOutOfRangeException("limit", "Valid range: [1," + MAX_LIMIT + "]"); string commentsUrl = string.Format(CommentsUrl, Name); commentsUrl += string.Format("?sort={0}&limit={1}&t={2}", Enum.GetName(typeof(Sort), sorting), limit, Enum.GetName(typeof(FromTime), fromTime)); return new Listing<Comment>(Reddit, commentsUrl, WebAgent); } /// <summary> /// Get a listing of posts from the user sorted by <paramref name="sorting"/>, from time <paramref name="fromTime"/> /// and limited to <paramref name="limit"/>. /// </summary> /// <param name="sorting">How to sort the posts (hot, new, top, controversial).</param> /// <param name="limit">How many posts to fetch per request. Max is 100.</param> /// <param name="fromTime">What time frame of posts to show (hour, day, week, month, year, all).</param> /// <returns>The listing of posts requested.</returns> public Listing<Post> GetPosts(Sort sorting = Sort.New, int limit = 25, FromTime fromTime = FromTime.All) { if ((limit < 1) || (limit > 100)) throw new ArgumentOutOfRangeException("limit", "Valid range: [1,100]"); string linksUrl = string.Format(LinksUrl, Name); linksUrl += string.Format("?sort={0}&limit={1}&t={2}", Enum.GetName(typeof(Sort), sorting), limit, Enum.GetName(typeof(FromTime), fromTime)); return new Listing<Post>(Reddit, linksUrl, WebAgent); } public override string ToString() { return Name; } #region Obsolete Getter Methods [Obsolete("Use Overview property instead")] public Listing<VotableThing> GetOverview() { return Overview; } [Obsolete("Use Comments property instead")] public Listing<Comment> GetComments() { return Comments; } [Obsolete("Use Posts property instead")] public Listing<Post> GetPosts() { return Posts; } [Obsolete("Use SubscribedSubreddits property instead")] public Listing<Subreddit> GetSubscribedSubreddits() { return SubscribedSubreddits; } #endregion Obsolete Getter Methods } public enum Sort { New, Hot, Top, Controversial } public enum FromTime { All, Year, Month, Week, Day, Hour } }
// 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.Globalization; using System.IO; using System.Reflection; namespace System.CodeDom.Compiler { public abstract class CodeGenerator : ICodeGenerator { private const int ParameterMultilineThreshold = 15; private ExposedTabStringIndentedTextWriter _output; private CodeGeneratorOptions _options; private CodeTypeDeclaration _currentClass; private CodeTypeMember _currentMember; private bool _inNestedBinary = false; protected CodeTypeDeclaration CurrentClass => _currentClass; protected string CurrentTypeName => _currentClass != null ? _currentClass.Name : "<% unknown %>"; protected CodeTypeMember CurrentMember => _currentMember; protected string CurrentMemberName => _currentMember != null ? _currentMember.Name : "<% unknown %>"; protected bool IsCurrentInterface => _currentClass != null && !(_currentClass is CodeTypeDelegate) ? _currentClass.IsInterface : false; protected bool IsCurrentClass => _currentClass != null && !(_currentClass is CodeTypeDelegate) ? _currentClass.IsClass : false; protected bool IsCurrentStruct => _currentClass != null && !(_currentClass is CodeTypeDelegate) ? _currentClass.IsStruct : false; protected bool IsCurrentEnum => _currentClass != null && !(_currentClass is CodeTypeDelegate) ? _currentClass.IsEnum : false; protected bool IsCurrentDelegate => _currentClass != null && _currentClass is CodeTypeDelegate; protected int Indent { get => _output.Indent; set => _output.Indent = value; } protected abstract string NullToken { get; } protected TextWriter Output => _output; protected CodeGeneratorOptions Options => _options; private void GenerateType(CodeTypeDeclaration e) { _currentClass = e; if (e.StartDirectives.Count > 0) { GenerateDirectives(e.StartDirectives); } GenerateCommentStatements(e.Comments); if (e.LinePragma != null) { GenerateLinePragmaStart(e.LinePragma); } GenerateTypeStart(e); if (Options.VerbatimOrder) { foreach (CodeTypeMember member in e.Members) { GenerateTypeMember(member, e); } } else { GenerateFields(e); GenerateSnippetMembers(e); GenerateTypeConstructors(e); GenerateConstructors(e); GenerateProperties(e); GenerateEvents(e); GenerateMethods(e); GenerateNestedTypes(e); } // Nested types clobber the current class, so reset it. _currentClass = e; GenerateTypeEnd(e); if (e.LinePragma != null) { GenerateLinePragmaEnd(e.LinePragma); } if (e.EndDirectives.Count > 0) { GenerateDirectives(e.EndDirectives); } } protected virtual void GenerateDirectives(CodeDirectiveCollection directives) { } private void GenerateTypeMember(CodeTypeMember member, CodeTypeDeclaration declaredType) { if (_options.BlankLinesBetweenMembers) { Output.WriteLine(); } if (member is CodeTypeDeclaration) { ((ICodeGenerator)this).GenerateCodeFromType((CodeTypeDeclaration)member, _output.InnerWriter, _options); // Nested types clobber the current class, so reset it. _currentClass = declaredType; // For nested types, comments and line pragmas are handled separately, so return here return; } if (member.StartDirectives.Count > 0) { GenerateDirectives(member.StartDirectives); } GenerateCommentStatements(member.Comments); if (member.LinePragma != null) { GenerateLinePragmaStart(member.LinePragma); } if (member is CodeMemberField) { GenerateField((CodeMemberField)member); } else if (member is CodeMemberProperty) { GenerateProperty((CodeMemberProperty)member, declaredType); } else if (member is CodeMemberMethod) { if (member is CodeConstructor) { GenerateConstructor((CodeConstructor)member, declaredType); } else if (member is CodeTypeConstructor) { GenerateTypeConstructor((CodeTypeConstructor)member); } else if (member is CodeEntryPointMethod) { GenerateEntryPointMethod((CodeEntryPointMethod)member, declaredType); } else { GenerateMethod((CodeMemberMethod)member, declaredType); } } else if (member is CodeMemberEvent) { GenerateEvent((CodeMemberEvent)member, declaredType); } else if (member is CodeSnippetTypeMember) { // Don't indent snippets, in order to preserve the column // information from the original code. This improves the debugging // experience. int savedIndent = Indent; Indent = 0; GenerateSnippetMember((CodeSnippetTypeMember)member); // Restore the indent Indent = savedIndent; // Generate an extra new line at the end of the snippet. // If the snippet is comment and this type only contains comments. // The generated code will not compile. Output.WriteLine(); } if (member.LinePragma != null) { GenerateLinePragmaEnd(member.LinePragma); } if (member.EndDirectives.Count > 0) { GenerateDirectives(member.EndDirectives); } } private void GenerateTypeConstructors(CodeTypeDeclaration e) { foreach (CodeTypeMember current in e.Members) { if (current is CodeTypeConstructor) { _currentMember = current; if (_options.BlankLinesBetweenMembers) { Output.WriteLine(); } if (_currentMember.StartDirectives.Count > 0) { GenerateDirectives(_currentMember.StartDirectives); } GenerateCommentStatements(_currentMember.Comments); CodeTypeConstructor imp = (CodeTypeConstructor)current; if (imp.LinePragma != null) GenerateLinePragmaStart(imp.LinePragma); GenerateTypeConstructor(imp); if (imp.LinePragma != null) GenerateLinePragmaEnd(imp.LinePragma); if (_currentMember.EndDirectives.Count > 0) { GenerateDirectives(_currentMember.EndDirectives); } } } } protected void GenerateNamespaces(CodeCompileUnit e) { foreach (CodeNamespace n in e.Namespaces) { ((ICodeGenerator)this).GenerateCodeFromNamespace(n, _output.InnerWriter, _options); } } protected void GenerateTypes(CodeNamespace e) { foreach (CodeTypeDeclaration c in e.Types) { if (_options.BlankLinesBetweenMembers) { Output.WriteLine(); } ((ICodeGenerator)this).GenerateCodeFromType(c, _output.InnerWriter, _options); } } bool ICodeGenerator.Supports(GeneratorSupport support) => Supports(support); void ICodeGenerator.GenerateCodeFromType(CodeTypeDeclaration e, TextWriter w, CodeGeneratorOptions o) { bool setLocal = false; if (_output != null && w != _output.InnerWriter) { throw new InvalidOperationException(SR.CodeGenOutputWriter); } if (_output == null) { setLocal = true; _options = o ?? new CodeGeneratorOptions(); _output = new ExposedTabStringIndentedTextWriter(w, _options.IndentString); } try { GenerateType(e); } finally { if (setLocal) { _output = null; _options = null; } } } void ICodeGenerator.GenerateCodeFromExpression(CodeExpression e, TextWriter w, CodeGeneratorOptions o) { bool setLocal = false; if (_output != null && w != _output.InnerWriter) { throw new InvalidOperationException(SR.CodeGenOutputWriter); } if (_output == null) { setLocal = true; _options = o ?? new CodeGeneratorOptions(); _output = new ExposedTabStringIndentedTextWriter(w, _options.IndentString); } try { GenerateExpression(e); } finally { if (setLocal) { _output = null; _options = null; } } } void ICodeGenerator.GenerateCodeFromCompileUnit(CodeCompileUnit e, TextWriter w, CodeGeneratorOptions o) { bool setLocal = false; if (_output != null && w != _output.InnerWriter) { throw new InvalidOperationException(SR.CodeGenOutputWriter); } if (_output == null) { setLocal = true; _options = o ?? new CodeGeneratorOptions(); _output = new ExposedTabStringIndentedTextWriter(w, _options.IndentString); } try { if (e is CodeSnippetCompileUnit) { GenerateSnippetCompileUnit((CodeSnippetCompileUnit)e); } else { GenerateCompileUnit(e); } } finally { if (setLocal) { _output = null; _options = null; } } } void ICodeGenerator.GenerateCodeFromNamespace(CodeNamespace e, TextWriter w, CodeGeneratorOptions o) { bool setLocal = false; if (_output != null && w != _output.InnerWriter) { throw new InvalidOperationException(SR.CodeGenOutputWriter); } if (_output == null) { setLocal = true; _options = o ?? new CodeGeneratorOptions(); _output = new ExposedTabStringIndentedTextWriter(w, _options.IndentString); } try { GenerateNamespace(e); } finally { if (setLocal) { _output = null; _options = null; } } } void ICodeGenerator.GenerateCodeFromStatement(CodeStatement e, TextWriter w, CodeGeneratorOptions o) { bool setLocal = false; if (_output != null && w != _output.InnerWriter) { throw new InvalidOperationException(SR.CodeGenOutputWriter); } if (_output == null) { setLocal = true; _options = o ?? new CodeGeneratorOptions(); _output = new ExposedTabStringIndentedTextWriter(w, _options.IndentString); } try { GenerateStatement(e); } finally { if (setLocal) { _output = null; _options = null; } } } public virtual void GenerateCodeFromMember(CodeTypeMember member, TextWriter writer, CodeGeneratorOptions options) { if (_output != null) { throw new InvalidOperationException(SR.CodeGenReentrance); } _options = options ?? new CodeGeneratorOptions(); _output = new ExposedTabStringIndentedTextWriter(writer, _options.IndentString); try { CodeTypeDeclaration dummyClass = new CodeTypeDeclaration(); _currentClass = dummyClass; GenerateTypeMember(member, dummyClass); } finally { _currentClass = null; _output = null; _options = null; } } bool ICodeGenerator.IsValidIdentifier(string value) => IsValidIdentifier(value); void ICodeGenerator.ValidateIdentifier(string value) => ValidateIdentifier(value); string ICodeGenerator.CreateEscapedIdentifier(string value) => CreateEscapedIdentifier(value); string ICodeGenerator.CreateValidIdentifier(string value) => CreateValidIdentifier(value); string ICodeGenerator.GetTypeOutput(CodeTypeReference type) => GetTypeOutput(type); private void GenerateConstructors(CodeTypeDeclaration e) { foreach (CodeTypeMember current in e.Members) { if (current is CodeConstructor) { _currentMember = current; if (_options.BlankLinesBetweenMembers) { Output.WriteLine(); } if (_currentMember.StartDirectives.Count > 0) { GenerateDirectives(_currentMember.StartDirectives); } GenerateCommentStatements(_currentMember.Comments); CodeConstructor imp = (CodeConstructor)current; if (imp.LinePragma != null) { GenerateLinePragmaStart(imp.LinePragma); } GenerateConstructor(imp, e); if (imp.LinePragma != null) { GenerateLinePragmaEnd(imp.LinePragma); } if (_currentMember.EndDirectives.Count > 0) { GenerateDirectives(_currentMember.EndDirectives); } } } } private void GenerateEvents(CodeTypeDeclaration e) { foreach (CodeTypeMember current in e.Members) { if (current is CodeMemberEvent) { _currentMember = current; if (_options.BlankLinesBetweenMembers) { Output.WriteLine(); } if (_currentMember.StartDirectives.Count > 0) { GenerateDirectives(_currentMember.StartDirectives); } GenerateCommentStatements(_currentMember.Comments); CodeMemberEvent imp = (CodeMemberEvent)current; if (imp.LinePragma != null) { GenerateLinePragmaStart(imp.LinePragma); } GenerateEvent(imp, e); if (imp.LinePragma != null) { GenerateLinePragmaEnd(imp.LinePragma); } if (_currentMember.EndDirectives.Count > 0) { GenerateDirectives(_currentMember.EndDirectives); } } } } protected void GenerateExpression(CodeExpression e) { if (e is CodeArrayCreateExpression) { GenerateArrayCreateExpression((CodeArrayCreateExpression)e); } else if (e is CodeBaseReferenceExpression) { GenerateBaseReferenceExpression((CodeBaseReferenceExpression)e); } else if (e is CodeBinaryOperatorExpression) { GenerateBinaryOperatorExpression((CodeBinaryOperatorExpression)e); } else if (e is CodeCastExpression) { GenerateCastExpression((CodeCastExpression)e); } else if (e is CodeDelegateCreateExpression) { GenerateDelegateCreateExpression((CodeDelegateCreateExpression)e); } else if (e is CodeFieldReferenceExpression) { GenerateFieldReferenceExpression((CodeFieldReferenceExpression)e); } else if (e is CodeArgumentReferenceExpression) { GenerateArgumentReferenceExpression((CodeArgumentReferenceExpression)e); } else if (e is CodeVariableReferenceExpression) { GenerateVariableReferenceExpression((CodeVariableReferenceExpression)e); } else if (e is CodeIndexerExpression) { GenerateIndexerExpression((CodeIndexerExpression)e); } else if (e is CodeArrayIndexerExpression) { GenerateArrayIndexerExpression((CodeArrayIndexerExpression)e); } else if (e is CodeSnippetExpression) { GenerateSnippetExpression((CodeSnippetExpression)e); } else if (e is CodeMethodInvokeExpression) { GenerateMethodInvokeExpression((CodeMethodInvokeExpression)e); } else if (e is CodeMethodReferenceExpression) { GenerateMethodReferenceExpression((CodeMethodReferenceExpression)e); } else if (e is CodeEventReferenceExpression) { GenerateEventReferenceExpression((CodeEventReferenceExpression)e); } else if (e is CodeDelegateInvokeExpression) { GenerateDelegateInvokeExpression((CodeDelegateInvokeExpression)e); } else if (e is CodeObjectCreateExpression) { GenerateObjectCreateExpression((CodeObjectCreateExpression)e); } else if (e is CodeParameterDeclarationExpression) { GenerateParameterDeclarationExpression((CodeParameterDeclarationExpression)e); } else if (e is CodeDirectionExpression) { GenerateDirectionExpression((CodeDirectionExpression)e); } else if (e is CodePrimitiveExpression) { GeneratePrimitiveExpression((CodePrimitiveExpression)e); } else if (e is CodePropertyReferenceExpression) { GeneratePropertyReferenceExpression((CodePropertyReferenceExpression)e); } else if (e is CodePropertySetValueReferenceExpression) { GeneratePropertySetValueReferenceExpression((CodePropertySetValueReferenceExpression)e); } else if (e is CodeThisReferenceExpression) { GenerateThisReferenceExpression((CodeThisReferenceExpression)e); } else if (e is CodeTypeReferenceExpression) { GenerateTypeReferenceExpression((CodeTypeReferenceExpression)e); } else if (e is CodeTypeOfExpression) { GenerateTypeOfExpression((CodeTypeOfExpression)e); } else if (e is CodeDefaultValueExpression) { GenerateDefaultValueExpression((CodeDefaultValueExpression)e); } else { if (e == null) { throw new ArgumentNullException(nameof(e)); } else { throw new ArgumentException(SR.Format(SR.InvalidElementType, e.GetType().FullName), nameof(e)); } } } private void GenerateFields(CodeTypeDeclaration e) { foreach (CodeTypeMember current in e.Members) { if (current is CodeMemberField) { _currentMember = current; if (_options.BlankLinesBetweenMembers) { Output.WriteLine(); } if (_currentMember.StartDirectives.Count > 0) { GenerateDirectives(_currentMember.StartDirectives); } GenerateCommentStatements(_currentMember.Comments); CodeMemberField imp = (CodeMemberField)current; if (imp.LinePragma != null) { GenerateLinePragmaStart(imp.LinePragma); } GenerateField(imp); if (imp.LinePragma != null) { GenerateLinePragmaEnd(imp.LinePragma); } if (_currentMember.EndDirectives.Count > 0) { GenerateDirectives(_currentMember.EndDirectives); } } } } private void GenerateSnippetMembers(CodeTypeDeclaration e) { bool hasSnippet = false; foreach (CodeTypeMember current in e.Members) { if (current is CodeSnippetTypeMember) { hasSnippet = true; _currentMember = current; if (_options.BlankLinesBetweenMembers) { Output.WriteLine(); } if (_currentMember.StartDirectives.Count > 0) { GenerateDirectives(_currentMember.StartDirectives); } GenerateCommentStatements(_currentMember.Comments); CodeSnippetTypeMember imp = (CodeSnippetTypeMember)current; if (imp.LinePragma != null) { GenerateLinePragmaStart(imp.LinePragma); } // Don't indent snippets, in order to preserve the column // information from the original code. This improves the debugging // experience. int savedIndent = Indent; Indent = 0; GenerateSnippetMember(imp); // Restore the indent Indent = savedIndent; if (imp.LinePragma != null) { GenerateLinePragmaEnd(imp.LinePragma); } if (_currentMember.EndDirectives.Count > 0) { GenerateDirectives(_currentMember.EndDirectives); } } } // Generate an extra new line at the end of the snippet. // If the snippet is comment and this type only contains comments. // The generated code will not compile. if (hasSnippet) { Output.WriteLine(); } } protected virtual void GenerateSnippetCompileUnit(CodeSnippetCompileUnit e) { GenerateDirectives(e.StartDirectives); if (e.LinePragma != null) { GenerateLinePragmaStart(e.LinePragma); } Output.WriteLine(e.Value); if (e.LinePragma != null) { GenerateLinePragmaEnd(e.LinePragma); } if (e.EndDirectives.Count > 0) { GenerateDirectives(e.EndDirectives); } } private void GenerateMethods(CodeTypeDeclaration e) { foreach (CodeTypeMember current in e.Members) { if (current is CodeMemberMethod && !(current is CodeTypeConstructor) && !(current is CodeConstructor)) { _currentMember = current; if (_options.BlankLinesBetweenMembers) { Output.WriteLine(); } if (_currentMember.StartDirectives.Count > 0) { GenerateDirectives(_currentMember.StartDirectives); } GenerateCommentStatements(_currentMember.Comments); CodeMemberMethod imp = (CodeMemberMethod)current; if (imp.LinePragma != null) { GenerateLinePragmaStart(imp.LinePragma); } if (current is CodeEntryPointMethod) { GenerateEntryPointMethod((CodeEntryPointMethod)current, e); } else { GenerateMethod(imp, e); } if (imp.LinePragma != null) { GenerateLinePragmaEnd(imp.LinePragma); } if (_currentMember.EndDirectives.Count > 0) { GenerateDirectives(_currentMember.EndDirectives); } } } } private void GenerateNestedTypes(CodeTypeDeclaration e) { foreach (CodeTypeMember current in e.Members) { if (current is CodeTypeDeclaration) { if (_options.BlankLinesBetweenMembers) { Output.WriteLine(); } CodeTypeDeclaration currentClass = (CodeTypeDeclaration)current; ((ICodeGenerator)this).GenerateCodeFromType(currentClass, _output.InnerWriter, _options); } } } protected virtual void GenerateCompileUnit(CodeCompileUnit e) { GenerateCompileUnitStart(e); GenerateNamespaces(e); GenerateCompileUnitEnd(e); } protected virtual void GenerateNamespace(CodeNamespace e) { GenerateCommentStatements(e.Comments); GenerateNamespaceStart(e); GenerateNamespaceImports(e); Output.WriteLine(); GenerateTypes(e); GenerateNamespaceEnd(e); } protected void GenerateNamespaceImports(CodeNamespace e) { foreach (CodeNamespaceImport imp in e.Imports) { if (imp.LinePragma != null) GenerateLinePragmaStart(imp.LinePragma); GenerateNamespaceImport(imp); if (imp.LinePragma != null) GenerateLinePragmaEnd(imp.LinePragma); } } private void GenerateProperties(CodeTypeDeclaration e) { foreach (CodeTypeMember current in e.Members) { if (current is CodeMemberProperty) { _currentMember = current; if (_options.BlankLinesBetweenMembers) { Output.WriteLine(); } if (_currentMember.StartDirectives.Count > 0) { GenerateDirectives(_currentMember.StartDirectives); } GenerateCommentStatements(_currentMember.Comments); CodeMemberProperty imp = (CodeMemberProperty)current; if (imp.LinePragma != null) { GenerateLinePragmaStart(imp.LinePragma); } GenerateProperty(imp, e); if (imp.LinePragma != null) { GenerateLinePragmaEnd(imp.LinePragma); } if (_currentMember.EndDirectives.Count > 0) { GenerateDirectives(_currentMember.EndDirectives); } } } } protected void GenerateStatement(CodeStatement e) { if (e.StartDirectives.Count > 0) { GenerateDirectives(e.StartDirectives); } if (e.LinePragma != null) { GenerateLinePragmaStart(e.LinePragma); } if (e is CodeCommentStatement) { GenerateCommentStatement((CodeCommentStatement)e); } else if (e is CodeMethodReturnStatement) { GenerateMethodReturnStatement((CodeMethodReturnStatement)e); } else if (e is CodeConditionStatement) { GenerateConditionStatement((CodeConditionStatement)e); } else if (e is CodeTryCatchFinallyStatement) { GenerateTryCatchFinallyStatement((CodeTryCatchFinallyStatement)e); } else if (e is CodeAssignStatement) { GenerateAssignStatement((CodeAssignStatement)e); } else if (e is CodeExpressionStatement) { GenerateExpressionStatement((CodeExpressionStatement)e); } else if (e is CodeIterationStatement) { GenerateIterationStatement((CodeIterationStatement)e); } else if (e is CodeThrowExceptionStatement) { GenerateThrowExceptionStatement((CodeThrowExceptionStatement)e); } else if (e is CodeSnippetStatement) { // Don't indent snippet statements, in order to preserve the column // information from the original code. This improves the debugging // experience. int savedIndent = Indent; Indent = 0; GenerateSnippetStatement((CodeSnippetStatement)e); // Restore the indent Indent = savedIndent; } else if (e is CodeVariableDeclarationStatement) { GenerateVariableDeclarationStatement((CodeVariableDeclarationStatement)e); } else if (e is CodeAttachEventStatement) { GenerateAttachEventStatement((CodeAttachEventStatement)e); } else if (e is CodeRemoveEventStatement) { GenerateRemoveEventStatement((CodeRemoveEventStatement)e); } else if (e is CodeGotoStatement) { GenerateGotoStatement((CodeGotoStatement)e); } else if (e is CodeLabeledStatement) { GenerateLabeledStatement((CodeLabeledStatement)e); } else { throw new ArgumentException(SR.Format(SR.InvalidElementType, e.GetType().FullName), nameof(e)); } if (e.LinePragma != null) { GenerateLinePragmaEnd(e.LinePragma); } if (e.EndDirectives.Count > 0) { GenerateDirectives(e.EndDirectives); } } protected void GenerateStatements(CodeStatementCollection stmts) { foreach (CodeStatement stmt in stmts) { ((ICodeGenerator)this).GenerateCodeFromStatement(stmt, _output.InnerWriter, _options); } } protected virtual void OutputAttributeDeclarations(CodeAttributeDeclarationCollection attributes) { if (attributes.Count == 0) return; GenerateAttributeDeclarationsStart(attributes); bool first = true; foreach (CodeAttributeDeclaration current in attributes) { if (first) { first = false; } else { ContinueOnNewLine(", "); } Output.Write(current.Name); Output.Write('('); bool firstArg = true; foreach (CodeAttributeArgument arg in current.Arguments) { if (firstArg) { firstArg = false; } else { Output.Write(", "); } OutputAttributeArgument(arg); } Output.Write(')'); } GenerateAttributeDeclarationsEnd(attributes); } protected virtual void OutputAttributeArgument(CodeAttributeArgument arg) { if (!string.IsNullOrEmpty(arg.Name)) { OutputIdentifier(arg.Name); Output.Write('='); } ((ICodeGenerator)this).GenerateCodeFromExpression(arg.Value, _output.InnerWriter, _options); } protected virtual void OutputDirection(FieldDirection dir) { switch (dir) { case FieldDirection.In: break; case FieldDirection.Out: Output.Write("out "); break; case FieldDirection.Ref: Output.Write("ref "); break; } } protected virtual void OutputFieldScopeModifier(MemberAttributes attributes) { switch (attributes & MemberAttributes.VTableMask) { case MemberAttributes.New: Output.Write("new "); break; } switch (attributes & MemberAttributes.ScopeMask) { case MemberAttributes.Final: break; case MemberAttributes.Static: Output.Write("static "); break; case MemberAttributes.Const: Output.Write("const "); break; default: break; } } protected virtual void OutputMemberAccessModifier(MemberAttributes attributes) { switch (attributes & MemberAttributes.AccessMask) { case MemberAttributes.Assembly: Output.Write("internal "); break; case MemberAttributes.FamilyAndAssembly: Output.Write("internal "); /*FamANDAssem*/ break; case MemberAttributes.Family: Output.Write("protected "); break; case MemberAttributes.FamilyOrAssembly: Output.Write("protected internal "); break; case MemberAttributes.Private: Output.Write("private "); break; case MemberAttributes.Public: Output.Write("public "); break; } } protected virtual void OutputMemberScopeModifier(MemberAttributes attributes) { switch (attributes & MemberAttributes.VTableMask) { case MemberAttributes.New: Output.Write("new "); break; } switch (attributes & MemberAttributes.ScopeMask) { case MemberAttributes.Abstract: Output.Write("abstract "); break; case MemberAttributes.Final: Output.Write(""); break; case MemberAttributes.Static: Output.Write("static "); break; case MemberAttributes.Override: Output.Write("override "); break; default: switch (attributes & MemberAttributes.AccessMask) { case MemberAttributes.Family: case MemberAttributes.Public: Output.Write("virtual "); break; default: // nothing; break; } break; } } protected abstract void OutputType(CodeTypeReference typeRef); protected virtual void OutputTypeAttributes(TypeAttributes attributes, bool isStruct, bool isEnum) { switch (attributes & TypeAttributes.VisibilityMask) { case TypeAttributes.Public: case TypeAttributes.NestedPublic: Output.Write("public "); break; case TypeAttributes.NestedPrivate: Output.Write("private "); break; } if (isStruct) { Output.Write("struct "); } else if (isEnum) { Output.Write("enum "); } else { switch (attributes & TypeAttributes.ClassSemanticsMask) { case TypeAttributes.Class: if ((attributes & TypeAttributes.Sealed) == TypeAttributes.Sealed) { Output.Write("sealed "); } if ((attributes & TypeAttributes.Abstract) == TypeAttributes.Abstract) { Output.Write("abstract "); } Output.Write("class "); break; case TypeAttributes.Interface: Output.Write("interface "); break; } } } protected virtual void OutputTypeNamePair(CodeTypeReference typeRef, string name) { OutputType(typeRef); Output.Write(' '); OutputIdentifier(name); } protected virtual void OutputIdentifier(string ident) => Output.Write(ident); protected virtual void OutputExpressionList(CodeExpressionCollection expressions) { OutputExpressionList(expressions, newlineBetweenItems: false); } protected virtual void OutputExpressionList(CodeExpressionCollection expressions, bool newlineBetweenItems) { bool first = true; Indent++; foreach (CodeExpression current in expressions) { if (first) { first = false; } else { if (newlineBetweenItems) ContinueOnNewLine(","); else Output.Write(", "); } ((ICodeGenerator)this).GenerateCodeFromExpression(current, _output.InnerWriter, _options); } Indent--; } protected virtual void OutputOperator(CodeBinaryOperatorType op) { switch (op) { case CodeBinaryOperatorType.Add: Output.Write('+'); break; case CodeBinaryOperatorType.Subtract: Output.Write('-'); break; case CodeBinaryOperatorType.Multiply: Output.Write('*'); break; case CodeBinaryOperatorType.Divide: Output.Write('/'); break; case CodeBinaryOperatorType.Modulus: Output.Write('%'); break; case CodeBinaryOperatorType.Assign: Output.Write('='); break; case CodeBinaryOperatorType.IdentityInequality: Output.Write("!="); break; case CodeBinaryOperatorType.IdentityEquality: Output.Write("=="); break; case CodeBinaryOperatorType.ValueEquality: Output.Write("=="); break; case CodeBinaryOperatorType.BitwiseOr: Output.Write('|'); break; case CodeBinaryOperatorType.BitwiseAnd: Output.Write('&'); break; case CodeBinaryOperatorType.BooleanOr: Output.Write("||"); break; case CodeBinaryOperatorType.BooleanAnd: Output.Write("&&"); break; case CodeBinaryOperatorType.LessThan: Output.Write('<'); break; case CodeBinaryOperatorType.LessThanOrEqual: Output.Write("<="); break; case CodeBinaryOperatorType.GreaterThan: Output.Write('>'); break; case CodeBinaryOperatorType.GreaterThanOrEqual: Output.Write(">="); break; } } protected virtual void OutputParameters(CodeParameterDeclarationExpressionCollection parameters) { bool first = true; bool multiline = parameters.Count > ParameterMultilineThreshold; if (multiline) { Indent += 3; } foreach (CodeParameterDeclarationExpression current in parameters) { if (first) { first = false; } else { Output.Write(", "); } if (multiline) { ContinueOnNewLine(""); } GenerateExpression(current); } if (multiline) { Indent -= 3; } } protected abstract void GenerateArrayCreateExpression(CodeArrayCreateExpression e); protected abstract void GenerateBaseReferenceExpression(CodeBaseReferenceExpression e); protected virtual void GenerateBinaryOperatorExpression(CodeBinaryOperatorExpression e) { bool indentedExpression = false; Output.Write('('); GenerateExpression(e.Left); Output.Write(' '); if (e.Left is CodeBinaryOperatorExpression || e.Right is CodeBinaryOperatorExpression) { // In case the line gets too long with nested binary operators, we need to output them on // different lines. However we want to indent them to maintain readability, but this needs // to be done only once; if (!_inNestedBinary) { indentedExpression = true; _inNestedBinary = true; Indent += 3; } ContinueOnNewLine(""); } OutputOperator(e.Operator); Output.Write(' '); GenerateExpression(e.Right); Output.Write(')'); if (indentedExpression) { Indent -= 3; _inNestedBinary = false; } } protected virtual void ContinueOnNewLine(string st) => Output.WriteLine(st); protected abstract void GenerateCastExpression(CodeCastExpression e); protected abstract void GenerateDelegateCreateExpression(CodeDelegateCreateExpression e); protected abstract void GenerateFieldReferenceExpression(CodeFieldReferenceExpression e); protected abstract void GenerateArgumentReferenceExpression(CodeArgumentReferenceExpression e); protected abstract void GenerateVariableReferenceExpression(CodeVariableReferenceExpression e); protected abstract void GenerateIndexerExpression(CodeIndexerExpression e); protected abstract void GenerateArrayIndexerExpression(CodeArrayIndexerExpression e); protected abstract void GenerateSnippetExpression(CodeSnippetExpression e); protected abstract void GenerateMethodInvokeExpression(CodeMethodInvokeExpression e); protected abstract void GenerateMethodReferenceExpression(CodeMethodReferenceExpression e); protected abstract void GenerateEventReferenceExpression(CodeEventReferenceExpression e); protected abstract void GenerateDelegateInvokeExpression(CodeDelegateInvokeExpression e); protected abstract void GenerateObjectCreateExpression(CodeObjectCreateExpression e); protected virtual void GenerateParameterDeclarationExpression(CodeParameterDeclarationExpression e) { if (e.CustomAttributes.Count > 0) { OutputAttributeDeclarations(e.CustomAttributes); Output.Write(' '); } OutputDirection(e.Direction); OutputTypeNamePair(e.Type, e.Name); } protected virtual void GenerateDirectionExpression(CodeDirectionExpression e) { OutputDirection(e.Direction); GenerateExpression(e.Expression); } protected virtual void GeneratePrimitiveExpression(CodePrimitiveExpression e) { if (e.Value == null) { Output.Write(NullToken); } else if (e.Value is string) { Output.Write(QuoteSnippetString((string)e.Value)); } else if (e.Value is char) { Output.Write("'" + e.Value.ToString() + "'"); } else if (e.Value is byte) { Output.Write(((byte)e.Value).ToString(CultureInfo.InvariantCulture)); } else if (e.Value is short) { Output.Write(((short)e.Value).ToString(CultureInfo.InvariantCulture)); } else if (e.Value is int) { Output.Write(((int)e.Value).ToString(CultureInfo.InvariantCulture)); } else if (e.Value is long) { Output.Write(((long)e.Value).ToString(CultureInfo.InvariantCulture)); } else if (e.Value is float) { GenerateSingleFloatValue((float)e.Value); } else if (e.Value is double) { GenerateDoubleValue((double)e.Value); } else if (e.Value is decimal) { GenerateDecimalValue((decimal)e.Value); } else if (e.Value is bool) { if ((bool)e.Value) { Output.Write("true"); } else { Output.Write("false"); } } else { throw new ArgumentException(SR.Format(SR.InvalidPrimitiveType, e.Value.GetType())); } } protected virtual void GenerateSingleFloatValue(float s) => Output.Write(s.ToString("R", CultureInfo.InvariantCulture)); protected virtual void GenerateDoubleValue(double d) => Output.Write(d.ToString("R", CultureInfo.InvariantCulture)); protected virtual void GenerateDecimalValue(decimal d) => Output.Write(d.ToString(CultureInfo.InvariantCulture)); protected virtual void GenerateDefaultValueExpression(CodeDefaultValueExpression e) { } protected abstract void GeneratePropertyReferenceExpression(CodePropertyReferenceExpression e); protected abstract void GeneratePropertySetValueReferenceExpression(CodePropertySetValueReferenceExpression e); protected abstract void GenerateThisReferenceExpression(CodeThisReferenceExpression e); protected virtual void GenerateTypeReferenceExpression(CodeTypeReferenceExpression e) { OutputType(e.Type); } protected virtual void GenerateTypeOfExpression(CodeTypeOfExpression e) { Output.Write("typeof("); OutputType(e.Type); Output.Write(')'); } protected abstract void GenerateExpressionStatement(CodeExpressionStatement e); protected abstract void GenerateIterationStatement(CodeIterationStatement e); protected abstract void GenerateThrowExceptionStatement(CodeThrowExceptionStatement e); protected virtual void GenerateCommentStatement(CodeCommentStatement e) { if (e.Comment == null) { throw new ArgumentException(SR.Format(SR.Argument_NullComment, nameof(e)), nameof(e)); } GenerateComment(e.Comment); } protected virtual void GenerateCommentStatements(CodeCommentStatementCollection e) { foreach (CodeCommentStatement comment in e) { GenerateCommentStatement(comment); } } protected abstract void GenerateComment(CodeComment e); protected abstract void GenerateMethodReturnStatement(CodeMethodReturnStatement e); protected abstract void GenerateConditionStatement(CodeConditionStatement e); protected abstract void GenerateTryCatchFinallyStatement(CodeTryCatchFinallyStatement e); protected abstract void GenerateAssignStatement(CodeAssignStatement e); protected abstract void GenerateAttachEventStatement(CodeAttachEventStatement e); protected abstract void GenerateRemoveEventStatement(CodeRemoveEventStatement e); protected abstract void GenerateGotoStatement(CodeGotoStatement e); protected abstract void GenerateLabeledStatement(CodeLabeledStatement e); protected virtual void GenerateSnippetStatement(CodeSnippetStatement e) => Output.WriteLine(e.Value); protected abstract void GenerateVariableDeclarationStatement(CodeVariableDeclarationStatement e); protected abstract void GenerateLinePragmaStart(CodeLinePragma e); protected abstract void GenerateLinePragmaEnd(CodeLinePragma e); protected abstract void GenerateEvent(CodeMemberEvent e, CodeTypeDeclaration c); protected abstract void GenerateField(CodeMemberField e); protected abstract void GenerateSnippetMember(CodeSnippetTypeMember e); protected abstract void GenerateEntryPointMethod(CodeEntryPointMethod e, CodeTypeDeclaration c); protected abstract void GenerateMethod(CodeMemberMethod e, CodeTypeDeclaration c); protected abstract void GenerateProperty(CodeMemberProperty e, CodeTypeDeclaration c); protected abstract void GenerateConstructor(CodeConstructor e, CodeTypeDeclaration c); protected abstract void GenerateTypeConstructor(CodeTypeConstructor e); protected abstract void GenerateTypeStart(CodeTypeDeclaration e); protected abstract void GenerateTypeEnd(CodeTypeDeclaration e); protected virtual void GenerateCompileUnitStart(CodeCompileUnit e) { if (e.StartDirectives.Count > 0) { GenerateDirectives(e.StartDirectives); } } protected virtual void GenerateCompileUnitEnd(CodeCompileUnit e) { if (e.EndDirectives.Count > 0) { GenerateDirectives(e.EndDirectives); } } protected abstract void GenerateNamespaceStart(CodeNamespace e); protected abstract void GenerateNamespaceEnd(CodeNamespace e); protected abstract void GenerateNamespaceImport(CodeNamespaceImport e); protected abstract void GenerateAttributeDeclarationsStart(CodeAttributeDeclarationCollection attributes); protected abstract void GenerateAttributeDeclarationsEnd(CodeAttributeDeclarationCollection attributes); protected abstract bool Supports(GeneratorSupport support); protected abstract bool IsValidIdentifier(string value); protected virtual void ValidateIdentifier(string value) { if (!IsValidIdentifier(value)) { throw new ArgumentException(SR.Format(SR.InvalidIdentifier, value)); } } protected abstract string CreateEscapedIdentifier(string value); protected abstract string CreateValidIdentifier(string value); protected abstract string GetTypeOutput(CodeTypeReference value); protected abstract string QuoteSnippetString(string value); public static bool IsValidLanguageIndependentIdentifier(string value) => CSharpHelpers.IsValidTypeNameOrIdentifier(value, false); internal static bool IsValidLanguageIndependentTypeName(string value) => CSharpHelpers.IsValidTypeNameOrIdentifier(value, true); public static void ValidateIdentifiers(CodeObject e) { CodeValidator codeValidator = new CodeValidator(); // This has internal state and hence is not static codeValidator.ValidateIdentifiers(e); } } }
// *********************************************************************** // Copyright (c) 2011-2014 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.Xml; using NUnit.Common; using NUnit.Engine.Internal; using NUnit.Engine.Services; namespace NUnit.Engine.Runners { /// <summary> /// Summary description for ProcessRunner. /// </summary> public class ProcessRunner : AbstractTestRunner { private const int NORMAL_TIMEOUT = 30000; // 30 seconds private const int DEBUG_TIMEOUT = NORMAL_TIMEOUT * 10; // 5 minutes private static readonly Logger log = InternalTrace.GetLogger(typeof(ProcessRunner)); private ITestAgent _agent; private ITestEngineRunner _remoteRunner; private TestAgency _agency; public ProcessRunner(IServiceLocator services, TestPackage package) : base(services, package) { _agency = Services.GetService<TestAgency>(); } #region Properties public RuntimeFramework RuntimeFramework { get; private set; } #endregion #region AbstractTestRunner Overrides /// <summary> /// Explore a TestPackage and return information about /// the tests found. /// </summary> /// <param name="filter">A TestFilter used to select tests</param> /// <returns>A TestEngineResult.</returns> protected override TestEngineResult ExploreTests(TestFilter filter) { try { return _remoteRunner.Explore(filter); } catch (Exception e) { log.Error("Failed to run remote tests {0}", e.Message); return CreateFailedResult(e); } } /// <summary> /// Load a TestPackage for possible execution /// </summary> /// <returns>A TestEngineResult.</returns> protected override TestEngineResult LoadPackage() { log.Info("Loading " + TestPackage.Name); Unload(); try { if (_agent == null) { // Increase the timeout to give time to attach a debugger bool debug = TestPackage.GetSetting(PackageSettings.DebugAgent, false) || TestPackage.GetSetting(PackageSettings.PauseBeforeRun, false); _agent = _agency.GetAgent(TestPackage, debug ? DEBUG_TIMEOUT : NORMAL_TIMEOUT); if (_agent == null) throw new Exception("Unable to acquire remote process agent"); } if (_remoteRunner == null) _remoteRunner = _agent.CreateRunner(TestPackage); return _remoteRunner.Load(); } catch(Exception) { // TODO: Check if this is really needed // Clean up if the load failed Unload(); throw; } } /// <summary> /// Unload any loaded TestPackage and clear /// the reference to the remote runner. /// </summary> public override void UnloadPackage() { try { if (_remoteRunner != null) { log.Info("Unloading remote runner"); _remoteRunner.Unload(); _remoteRunner = null; } } catch (Exception e) { log.Warning("Failed to unload the remote runner. {0}", e.Message); _remoteRunner = null; } } /// <summary> /// Count the test cases that would be run under /// the specified filter. /// </summary> /// <param name="filter">A TestFilter</param> /// <returns>The count of test cases</returns> protected override int CountTests(TestFilter filter) { try { return _remoteRunner.CountTestCases(filter); } catch (Exception e) { log.Error("Failed to count remote tests {0}", e.Message); return 0; } } /// <summary> /// Run the tests in a loaded TestPackage /// </summary> /// <param name="listener">An ITestEventHandler to receive events</param> /// <param name="filter">A TestFilter used to select tests</param> /// <returns>A TestResult giving the result of the test execution</returns> protected override TestEngineResult RunTests(ITestEventListener listener, TestFilter filter) { try { return _remoteRunner.Run(listener, filter); } catch (Exception e) { log.Error("Failed to run remote tests {0}", e.Message); return CreateFailedResult(e); } } /// <summary> /// Start a run of the tests in the loaded TestPackage, returning immediately. /// The tests are run asynchronously and the listener interface is notified /// as it progresses. /// </summary> /// <param name="listener">An ITestEventHandler to receive events</param> /// <param name="filter">A TestFilter used to select tests</param> /// <returns>An AsyncTestRun that will provide the result of the test execution</returns> protected override AsyncTestEngineResult RunTestsAsync(ITestEventListener listener, TestFilter filter) { try { return _remoteRunner.RunAsync(listener, filter); } catch (Exception e) { log.Error("Failed to run remote tests {0}", e.Message); var result = new AsyncTestEngineResult(); result.SetResult(CreateFailedResult(e)); return result; } } /// <summary> /// Cancel the ongoing test run. If no test is running, the call is ignored. /// </summary> /// <param name="force">If true, cancel any ongoing test threads, otherwise wait for them to complete.</param> public override void StopRun(bool force) { try { _remoteRunner.StopRun(force); } catch (Exception e) { log.Error("Failed to stop the remote run. {0}", e.Message); } } protected override void Dispose(bool disposing) { base.Dispose(disposing); try { if (disposing && _agent != null) { log.Info("Stopping remote agent"); _agent.Stop(); _agent = null; } } catch (Exception e) { log.Error("Failed to stop the remote agent. {0}", e.Message); _agent = null; } } TestEngineResult CreateFailedResult(Exception e) { var suite = XmlHelper.CreateTopLevelElement("test-suite"); XmlHelper.AddAttribute(suite, "type", "Assembly"); XmlHelper.AddAttribute(suite, "id", TestPackage.ID); XmlHelper.AddAttribute(suite, "name", TestPackage.Name); XmlHelper.AddAttribute(suite, "fullname", TestPackage.FullName); XmlHelper.AddAttribute(suite, "runstate", "NotRunnable"); XmlHelper.AddAttribute(suite, "testcasecount", "1"); XmlHelper.AddAttribute(suite, "result", "Failed"); XmlHelper.AddAttribute(suite, "label", "Error"); XmlHelper.AddAttribute(suite, "start-time", DateTime.UtcNow.ToString("u")); XmlHelper.AddAttribute(suite, "end-time", DateTime.UtcNow.ToString("u")); XmlHelper.AddAttribute(suite, "duration", "0.001"); XmlHelper.AddAttribute(suite, "total", "1"); XmlHelper.AddAttribute(suite, "passed", "0"); XmlHelper.AddAttribute(suite, "failed", "1"); XmlHelper.AddAttribute(suite, "inconclusive", "0"); XmlHelper.AddAttribute(suite, "skipped", "0"); XmlHelper.AddAttribute(suite, "asserts", "0"); var failure = suite.AddElement("failure"); var message = failure.AddElementWithCDataSection("message", e.Message); var stack = failure.AddElementWithCDataSection("stack-trace", e.StackTrace); return new TestEngineResult(suite); } #endregion } }
using System; using System.Collections.Specialized; using System.Configuration; using System.Configuration.Provider; using System.Data; using System.Data.SQLite; using System.Diagnostics; using System.Web.Security; namespace WilliamsonFamily.Library.Web.Membership.SQLiteProviders { public sealed class SQLiteRoleProvider : RoleProvider { #region Variables private string rolesTable = "Roles"; private string usersInRolesTable = "UsersInRoles"; private string eventSource = "SQLiteRoleProvider"; private string eventLog = "Application"; private string exceptionMessage = "An exception occurred. Please check the Event Log."; private ConnectionStringSettings _connectionStringSettings; private string connectionString; #endregion #region Properties /// <summary> /// If false, exceptions are thrown to the caller. If true, /// exceptions are written to the event log. /// </summary> public bool WriteExceptionsToEventLog { get; set; } #endregion #region RoleProvider Properties public override string ApplicationName { get; set; } #endregion #region RoleProvider Methods #region Initialize public override void Initialize(string name, NameValueCollection config) { if (config == null) throw new ArgumentNullException("config"); if (name == null || name.Length == 0) name = "SQLiteRoleProvider"; if (String.IsNullOrEmpty(config["description"])) { config.Remove("description"); config.Add("description", "SQLite Role provider"); } // Initialize the abstract base class. base.Initialize(name, config); if (config["applicationName"] == null || config["applicationName"].Trim() == "") { ApplicationName = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath; } else { ApplicationName = config["applicationName"]; } if (config["writeExceptionsToEventLog"] != null) { if (config["writeExceptionsToEventLog"].ToUpper() == "TRUE") { WriteExceptionsToEventLog = true; } } // Initialize SQLiteConnection. _connectionStringSettings = ConfigurationManager. ConnectionStrings[config["connectionStringName"]]; if (_connectionStringSettings == null || _connectionStringSettings.ConnectionString.Trim() == "") { throw new ProviderException("Connection string cannot be blank."); } connectionString = _connectionStringSettings.ConnectionString; } #endregion #region AddUsersToRoles public override void AddUsersToRoles(string[] usernames, string[] rolenames) { foreach (string rolename in rolenames) { if (!RoleExists(rolename)) { throw new ProviderException("Role name not found."); } } foreach (string username in usernames) { if (username.IndexOf(',') > 0) { throw new ArgumentException("User names cannot contain commas."); } foreach (string rolename in rolenames) { if (IsUserInRole(username, rolename)) { throw new ProviderException("User is already in role."); } } } SQLiteConnection conn = new SQLiteConnection(connectionString); SQLiteCommand cmd = new SQLiteCommand("INSERT INTO `" + usersInRolesTable + "`" + " (Username, Rolename, ApplicationName) " + " Values($Username, $Rolename, $ApplicationName)", conn); SQLiteParameter userParm = cmd.Parameters.Add("$Username", DbType.String, 255); SQLiteParameter roleParm = cmd.Parameters.Add("$Rolename", DbType.String, 255); cmd.Parameters.Add("$ApplicationName", DbType.String, 255).Value = ApplicationName; SQLiteTransaction tran = null; try { conn.Open(); tran = conn.BeginTransaction(); cmd.Transaction = tran; foreach (string username in usernames) { foreach (string rolename in rolenames) { userParm.Value = username; roleParm.Value = rolename; cmd.ExecuteNonQuery(); } } tran.Commit(); } catch (SQLiteException e) { try { tran.Rollback(); } catch { } if (WriteExceptionsToEventLog) { WriteToEventLog(e, "AddUsersToRoles"); } else { throw e; } } finally { conn.Close(); } } #endregion #region CreateRole public override void CreateRole(string rolename) { if (rolename.IndexOf(',') > 0) { throw new ArgumentException("Role names cannot contain commas."); } if (RoleExists(rolename)) { throw new ProviderException("Role name already exists."); } SQLiteConnection conn = new SQLiteConnection(connectionString); SQLiteCommand cmd = new SQLiteCommand("INSERT INTO `" + rolesTable + "`" + " (Rolename, ApplicationName) " + " Values($Rolename, $ApplicationName)", conn); cmd.Parameters.Add("$Rolename", DbType.String, 255).Value = rolename; cmd.Parameters.Add("$ApplicationName", DbType.String, 255).Value = ApplicationName; try { conn.Open(); cmd.ExecuteNonQuery(); } catch (SQLiteException e) { if (WriteExceptionsToEventLog) { WriteToEventLog(e, "CreateRole"); } else { throw e; } } finally { conn.Close(); } } #endregion #region DeleteRole public override bool DeleteRole(string rolename, bool throwOnPopulatedRole) { if (!RoleExists(rolename)) { throw new ProviderException("Role does not exist."); } if (throwOnPopulatedRole && GetUsersInRole(rolename).Length > 0) { throw new ProviderException("Cannot delete a populated role."); } SQLiteConnection conn = new SQLiteConnection(connectionString); SQLiteCommand cmd = new SQLiteCommand("DELETE FROM `" + rolesTable + "`" + " WHERE Rolename = $Rolename AND ApplicationName = $ApplicationName", conn); cmd.Parameters.Add("$Rolename", DbType.String, 255).Value = rolename; cmd.Parameters.Add("$ApplicationName", DbType.String, 255).Value = ApplicationName; SQLiteCommand cmd2 = new SQLiteCommand("DELETE FROM `" + usersInRolesTable + "`" + " WHERE Rolename = $Rolename AND ApplicationName = $ApplicationName", conn); cmd2.Parameters.Add("$Rolename", DbType.String, 255).Value = rolename; cmd2.Parameters.Add("$ApplicationName", DbType.String, 255).Value = ApplicationName; SQLiteTransaction tran = null; try { conn.Open(); tran = conn.BeginTransaction(); cmd.Transaction = tran; cmd2.Transaction = tran; cmd2.ExecuteNonQuery(); cmd.ExecuteNonQuery(); tran.Commit(); } catch (SQLiteException e) { try { tran.Rollback(); } catch { } if (WriteExceptionsToEventLog) { WriteToEventLog(e, "DeleteRole"); return false; } else { throw e; } } finally { conn.Close(); } return true; } #endregion #region GetAllRoles public override string[] GetAllRoles() { string tmpRoleNames = ""; SQLiteConnection conn = new SQLiteConnection(connectionString); SQLiteCommand cmd = new SQLiteCommand("SELECT Rolename FROM `" + rolesTable + "`" + " WHERE ApplicationName = $ApplicationName", conn); cmd.Parameters.Add("$ApplicationName", DbType.String, 255).Value = ApplicationName; SQLiteDataReader reader = null; try { conn.Open(); reader = cmd.ExecuteReader(); while (reader.Read()) { tmpRoleNames += reader.GetString(0) + ","; } } catch (SQLiteException e) { if (WriteExceptionsToEventLog) { WriteToEventLog(e, "GetAllRoles"); } else { throw e; } } finally { if (reader != null) { reader.Close(); } conn.Close(); } if (tmpRoleNames.Length > 0) { // Remove trailing comma. tmpRoleNames = tmpRoleNames.Substring(0, tmpRoleNames.Length - 1); return tmpRoleNames.Split(','); } return new string[0]; } #endregion #region GetRolesForUser public override string[] GetRolesForUser(string username) { string tmpRoleNames = ""; SQLiteConnection conn = new SQLiteConnection(connectionString); SQLiteCommand cmd = new SQLiteCommand("SELECT Rolename FROM `" + usersInRolesTable + "`" + " WHERE Username = $Username AND ApplicationName = $ApplicationName", conn); cmd.Parameters.Add("$Username", DbType.String, 255).Value = username; cmd.Parameters.Add("$ApplicationName", DbType.String, 255).Value = ApplicationName; SQLiteDataReader reader = null; try { conn.Open(); reader = cmd.ExecuteReader(); while (reader.Read()) { tmpRoleNames += reader.GetString(0) + ","; } } catch (SQLiteException e) { if (WriteExceptionsToEventLog) { WriteToEventLog(e, "GetRolesForUser"); } else { throw e; } } finally { if (reader != null) { reader.Close(); } conn.Close(); } if (tmpRoleNames.Length > 0) { // Remove trailing comma. tmpRoleNames = tmpRoleNames.Substring(0, tmpRoleNames.Length - 1); return tmpRoleNames.Split(','); } return new string[0]; } #endregion #region GetUsersInRole public override string[] GetUsersInRole(string rolename) { string tmpUserNames = ""; SQLiteConnection conn = new SQLiteConnection(connectionString); SQLiteCommand cmd = new SQLiteCommand("SELECT Username FROM `" + usersInRolesTable + "`" + " WHERE Rolename = $Rolename AND ApplicationName = $ApplicationName", conn); cmd.Parameters.Add("$Rolename", DbType.String, 255).Value = rolename; cmd.Parameters.Add("$ApplicationName", DbType.String, 255).Value = ApplicationName; SQLiteDataReader reader = null; try { conn.Open(); reader = cmd.ExecuteReader(); while (reader.Read()) { tmpUserNames += reader.GetString(0) + ","; } } catch (SQLiteException e) { if (WriteExceptionsToEventLog) { WriteToEventLog(e, "GetUsersInRole"); } else { throw e; } } finally { if (reader != null) { reader.Close(); } conn.Close(); } if (tmpUserNames.Length > 0) { // Remove trailing comma. tmpUserNames = tmpUserNames.Substring(0, tmpUserNames.Length - 1); return tmpUserNames.Split(','); } return new string[0]; } #endregion #region IsUserInRole public override bool IsUserInRole(string username, string rolename) { bool userIsInRole = false; SQLiteConnection conn = new SQLiteConnection(connectionString); SQLiteCommand cmd = new SQLiteCommand("SELECT COUNT(*) FROM `" + usersInRolesTable + "`" + " WHERE Username = $Username AND Rolename = $Rolename AND ApplicationName = $ApplicationName", conn); cmd.Parameters.Add("$Username", DbType.String, 255).Value = username; cmd.Parameters.Add("$Rolename", DbType.String, 255).Value = rolename; cmd.Parameters.Add("$ApplicationName", DbType.String, 255).Value = ApplicationName; try { conn.Open(); long numRecs = (long)cmd.ExecuteScalar(); if (numRecs > 0) { userIsInRole = true; } } catch (SQLiteException e) { if (WriteExceptionsToEventLog) { WriteToEventLog(e, "IsUserInRole"); } else { throw e; } } finally { conn.Close(); } return userIsInRole; } #endregion #region RemoveUsersFromRoles public override void RemoveUsersFromRoles(string[] usernames, string[] rolenames) { foreach (string rolename in rolenames) { if (!RoleExists(rolename)) { throw new ProviderException("Role name not found."); } } foreach (string username in usernames) { foreach (string rolename in rolenames) { if (!IsUserInRole(username, rolename)) { throw new ProviderException("User is not in role."); } } } SQLiteConnection conn = new SQLiteConnection(connectionString); SQLiteCommand cmd = new SQLiteCommand("DELETE FROM `" + usersInRolesTable + "`" + " WHERE Username = $Username AND Rolename = $Rolename AND ApplicationName = $ApplicationName", conn); SQLiteParameter userParm = cmd.Parameters.Add("$Username", DbType.String, 255); SQLiteParameter roleParm = cmd.Parameters.Add("$Rolename", DbType.String, 255); cmd.Parameters.Add("$ApplicationName", DbType.String, 255).Value = ApplicationName; SQLiteTransaction tran = null; try { conn.Open(); tran = conn.BeginTransaction(); cmd.Transaction = tran; foreach (string username in usernames) { foreach (string rolename in rolenames) { userParm.Value = username; roleParm.Value = rolename; cmd.ExecuteNonQuery(); } } tran.Commit(); } catch (SQLiteException e) { try { tran.Rollback(); } catch { } if (WriteExceptionsToEventLog) { WriteToEventLog(e, "RemoveUsersFromRoles"); } else { throw e; } } finally { conn.Close(); } } #endregion #region RoleExists public override bool RoleExists(string rolename) { bool exists = false; SQLiteConnection conn = new SQLiteConnection(connectionString); SQLiteCommand cmd = new SQLiteCommand("SELECT COUNT(*) FROM `" + rolesTable + "`" + " WHERE Rolename = $Rolename AND ApplicationName = $ApplicationName", conn); cmd.Parameters.Add("$Rolename", DbType.String, 255).Value = rolename; cmd.Parameters.Add("$ApplicationName", DbType.String, 255).Value = ApplicationName; try { conn.Open(); long numRecs = (long)cmd.ExecuteScalar(); if (numRecs > 0) { exists = true; } } catch (SQLiteException e) { if (WriteExceptionsToEventLog) { WriteToEventLog(e, "RoleExists"); } else { throw e; } } finally { conn.Close(); } return exists; } #endregion #region FindUsersInRole public override string[] FindUsersInRole(string rolename, string usernameToMatch) { SQLiteConnection conn = new SQLiteConnection(connectionString); SQLiteCommand cmd = new SQLiteCommand("SELECT Username FROM `" + usersInRolesTable + "` " + "WHERE Username LIKE $UsernameSearch AND Rolename = $Rolename AND ApplicationName = $ApplicationName", conn); cmd.Parameters.Add("$UsernameSearch", DbType.String, 255).Value = usernameToMatch; cmd.Parameters.Add("$RoleName", DbType.String, 255).Value = rolename; cmd.Parameters.Add("$ApplicationName", DbType.String, 255).Value = ApplicationName; string tmpUserNames = ""; SQLiteDataReader reader = null; try { conn.Open(); reader = cmd.ExecuteReader(); while (reader.Read()) { tmpUserNames += reader.GetString(0) + ","; } } catch (SQLiteException e) { if (WriteExceptionsToEventLog) { WriteToEventLog(e, "FindUsersInRole"); } else { throw e; } } finally { if (reader != null) { reader.Close(); } conn.Close(); } if (tmpUserNames.Length > 0) { // Remove trailing comma. tmpUserNames = tmpUserNames.Substring(0, tmpUserNames.Length - 1); return tmpUserNames.Split(','); } return new string[0]; } #endregion #endregion #region WriteToEventLog /// <summary> /// A helper function that writes exception detail to the event log. Exceptions /// are written to the event log as a security measure to avoid private database /// details from being returned to the browser. If a method does not return a status /// or boolean indicating the action succeeded or failed, a generic exception is also /// thrown by the caller. /// </summary> /// <param name="e"></param> /// <param name="action"></param> private void WriteToEventLog(SQLiteException e, string action) { EventLog log = new EventLog(); log.Source = eventSource; log.Log = eventLog; string message = exceptionMessage + "\n\n"; message += "Action: " + action + "\n\n"; message += "Exception: " + e.ToString(); log.WriteEntry(message); } #endregion } }
// Project.cs - project management code // Copyright (C) 2001 Jason Diamond // // 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 using System; using System.Collections; using System.Diagnostics; using System.IO; using System.Reflection; using System.Xml; using System.Text; namespace NDoc.Core { /// <summary>Represents an NDoc project.</summary> public class Project { /// <summary>Initializes a new instance of the <see cref="Project"/> class.</summary> public Project() { _IsDirty = false; _referencePaths = new ReferencePathCollection(); _namespaces = new Namespaces(); _namespaces.ContentsChanged += new EventHandler(ContentsChanged); _AssemblySlashDocs = new AssemblySlashDocCollection(); _AssemblySlashDocs.Cleared += new EventHandler(_AssemblySlashDocs_Cleared); _AssemblySlashDocs.ItemAdded += new AssemblySlashDocEventHandler(_AssemblySlashDocs_ItemAdded); _AssemblySlashDocs.ItemRemoved += new AssemblySlashDocEventHandler(_AssemblySlashDocs_ItemRemoved); } private string _projectFile; /// <summary> /// Gets or sets the project file. /// </summary> /// <value></value> public string ProjectFile { get { return _projectFile; } set { //set the base path for project Path Items if ((value != null) && (value.Length > 0)) PathItemBase.BasePath=Path.GetDirectoryName(value); else PathItemBase.BasePath=null; _projectFile = value; } } #region 'Dirty' flag handling private bool _IsDirty; /// <summary>Raised when the project <see cref="IsDirty"/> state changes from <see langword="false"/> to <see langword="true"/>.</summary> public event ProjectModifiedEventHandler Modified; private void ContentsChanged(object sender, EventArgs e) { IsDirty = true; } /// <summary>Gets or sets a value indicating whether the contents of this project have been modified.</summary> /// <remarks>If a project is marked as 'dirty' then the GUI will ask to user if they wish to save the project before loading another, or exiting.</remarks> public bool IsDirty { get { return _IsDirty; } set { if (!_suspendDirtyCheck) { if (!_IsDirty && value) { _IsDirty = true; if (Modified != null) Modified(this, EventArgs.Empty); } else { _IsDirty = value; } } } } private bool _suspendDirtyCheck=false; /// <summary> /// Gets or sets a value indicating whether <see cref="IsDirty"/> is updated when a project property is modifed. /// </summary> /// <value> /// <see langword="true"/>, if changes to project properties should <b>not</b> update the value of <see cref="IsDirty"/>; otherwise, <see langword="false"/>. /// </value> /// <remarks>The default value of this property is <see langword="false"/>, however it is set to <see langword="true"/> during <see cref="Read"/> so a newly loaded project is not flagged as 'dirty'</remarks> public bool SuspendDirtyCheck { get { return _suspendDirtyCheck; } set { _suspendDirtyCheck = value; } } #endregion #region AssemblySlashDocs private AssemblySlashDocCollection _AssemblySlashDocs; /// <summary> /// Gets the collection of assemblies and documentation comment XML files in the project. /// </summary> /// <value>An <see cref="AssemblySlashDocCollection"/>.</value> public AssemblySlashDocCollection AssemblySlashDocs { get { return _AssemblySlashDocs; } } #endregion #region ReferencePaths /// <summary> /// A collection of directories that will be probed when attempting to load assemblies. /// </summary> internal ReferencePathCollection _referencePaths; /// <summary>Gets a collection of directories that will be probed when attempting to load assemblies.</summary> public ReferencePathCollection ReferencePaths { get { return _referencePaths; } } #endregion #region Fixed/Relative Paths /// <summary> /// Gets the base directory used for relative references. /// </summary> /// <value> /// The directory of the project file, or the current working directory /// if the project was not loaded from a project file. /// </value> public string BaseDirectory { get { if (_projectFile == null) { ProjectFile = Path.Combine(Directory.GetCurrentDirectory(),"Untitled.ndoc"); } return Path.GetDirectoryName(ProjectFile); } } /// <summary> /// Combines the specified path with the <see cref="BaseDirectory"/> of /// the <see cref="Project" /> to form a full path to file or directory. /// </summary> /// <param name="path">The relative or absolute path.</param> /// <returns> /// A rooted path. /// </returns> public string GetFullPath(string path) { return PathUtilities.GetFullPath( BaseDirectory, path ); } /// <summary> /// Gets the relative path of the passed path with respect to the <see cref="BaseDirectory"/> of /// the <see cref="Project" />. /// </summary> /// <param name="path">The relative or absolute path.</param> /// <returns> /// A relative path. /// </returns> public string GetRelativePath(string path) { return PathUtilities.GetRelativePath( BaseDirectory, path ); } #endregion #region Namespaces private Namespaces _namespaces; /// <summary> /// Gets the project namespace summaries collection. /// </summary> /// <value></value> public Namespaces Namespaces { get { return _namespaces; } } #endregion #region Read from Disk /// <summary>Reads an NDoc project file from disk.</summary> public void Read(string filename) { Clear(); ProjectFile = Path.GetFullPath(filename); XmlTextReader reader = null; // keep track of whether or not any assemblies fail to load CouldNotLoadAllAssembliesException assemblyLoadException = null; // keep track of whether or not any errors in documenter property values DocumenterPropertyFormatException documenterPropertyFormatExceptions = null; try { StreamReader streamReader = new StreamReader(filename); reader = new XmlTextReader(streamReader); reader.MoveToContent(); reader.ReadStartElement("project"); while (!reader.EOF) { if (reader.NodeType == XmlNodeType.Element) { switch (reader.Name) { case "assemblies" : // continue even if we don't load all assemblies try { _AssemblySlashDocs.ReadXml(reader); } catch (CouldNotLoadAllAssembliesException e) { assemblyLoadException = e; } break; case "referencePaths" : _referencePaths.ReadXml(reader); break; case "namespaces" : //GetNamespacesFromAssemblies(); Namespaces.Read(reader); break; case "documenters" : // continue even if we have errors in documenter properties try { ReadDocumenters(reader); } catch (DocumenterPropertyFormatException e) { documenterPropertyFormatExceptions = e; } break; default : reader.Read(); break; } } else { reader.Read(); } } } catch (Exception ex) { //Clear the project to ensure everything is back to default state Clear(); throw new DocumenterException("Error reading in project file " + filename + ".\n" + ex.Message, ex); } finally { if (reader != null) { reader.Close(); // Closes the underlying stream. } } if (assemblyLoadException != null) { throw assemblyLoadException; } if (documenterPropertyFormatExceptions != null) { throw documenterPropertyFormatExceptions; } // IsDirty = false; } private void ReadDocumenters(XmlReader reader) { string FailureMessages = ""; while (!reader.EOF && !(reader.NodeType == XmlNodeType.EndElement && reader.Name == "documenters")) { if (reader.NodeType == XmlNodeType.Element && reader.Name == "documenter") { string name = reader["name"]; IDocumenterInfo info = InstalledDocumenters.GetDocumenter(name); if (info != null) { IDocumenterConfig config = info.CreateConfig( this ); reader.Read(); // Advance to next node. try { config.Read(reader); } catch (DocumenterPropertyFormatException e) { FailureMessages += name + " Documenter\n" + e.Message + "\n"; } if ( _configs.ContainsKey( info.Name ) == false ) _configs.Add( info.Name, config ); else _configs[info.Name] = config; } } reader.Read(); } if (FailureMessages.Length > 0) throw new DocumenterPropertyFormatException(FailureMessages); } private Hashtable _configs = new Hashtable(); /// <summary> /// Event rasied when the <see cref="ActiveConfig"/> changes /// </summary> public event EventHandler ActiveConfigChanged; /// <summary> /// Raises the <see cref="ActiveConfigChanged"/> event /// </summary> protected virtual void OnActiveConfigChanged() { if ( ActiveConfigChanged != null ) ActiveConfigChanged( this, EventArgs.Empty ); } /// <summary> /// The active documenter type /// </summary> public IDocumenterInfo ActiveDocumenter { get { if ( _currentConfig != null ) return _currentConfig.DocumenterInfo; return null; } set { _currentConfig = null; if ( value != null ) { // add a new config for this type if not already present if ( _configs.ContainsKey( value.Name ) == false ) _configs.Add( value.Name, value.CreateConfig( this ) ); // set the active config _currentConfig = _configs[value.Name] as IDocumenterConfig; } OnActiveConfigChanged(); } } private IDocumenterConfig _currentConfig; /// <summary> /// The curently active <see cref="IDocumenterConfig"/> /// </summary> public IDocumenterConfig ActiveConfig { get { return _currentConfig; } } #endregion #region Write to Disk /// <summary>Writes an NDoc project to a disk file.</summary> /// <remarks>A project is written to file in a 2 stage process; /// <list type="number"> /// <item>The project data is serialised to an in-memory store.</item> /// <item>If no errors occured during serialization, the data is written to disk.</item> /// </list> /// <p>This technique ensures that any fatal error during serialization will not cause a /// a corrupt or incomplete project file to be written to disk.</p> /// </remarks> public void Write(string filename) { //save the previous project file location. //If an error occurs during serialization, we we need to restore this... string oldProjectFile = ProjectFile; //Let the project know where it is being stored. This is used when deriving //pathnames relative to the project file ProjectFile = Path.GetFullPath(filename); //We will assume an reasonable initial capacity of 8k, //So the store does not normally need to grow. MemoryStream tempDataStore = new MemoryStream(8192); XmlTextWriter writer = null; try { //open an xml text writer to the memory stream writer = new XmlTextWriter(tempDataStore,new UTF8Encoding( false )); writer.Formatting = Formatting.Indented; writer.Indentation = 4; writer.WriteStartElement("project"); writer.WriteAttributeString("SchemaVersion", "1.3"); //do not change the order of those lines! _AssemblySlashDocs.WriteXml(writer); _referencePaths.WriteXml(writer); Namespaces.Write(writer); WriteDocumenters(writer); writer.WriteEndElement(); //Flush the writer - note that we cannot close it yet, //as that would also close the temporary data store writer.Flush(); //OK, we have managed to create the project file in memory. //Now we can try to write it to disk using(Stream stream = File.Create(filename)) tempDataStore.WriteTo(stream); } catch (Exception ex) { //ouch, something went horribly wrong! //restore the original filename ProjectFile = oldProjectFile ; throw new DocumenterException("Error saving project file.\n" + ex.Message, ex); } finally { if (writer != null) writer.Close(); // Closes the underlying stream. } IsDirty = false; } private void WriteDocumenters(XmlWriter writer) { if ( _configs.Count > 0 ) { writer.WriteStartElement( "documenters" ); foreach ( IDocumenterConfig documenter in _configs.Values ) documenter.Write(writer); writer.WriteEndElement(); } } #endregion /// <summary>Clears the project.</summary> public void Clear() { _AssemblySlashDocs.Clear(); if (_namespaces != null) _namespaces = new Namespaces(); if (_referencePaths != null) _referencePaths = new ReferencePathCollection(); // cache the current active info object IDocumenterInfo currentInfo = null; if ( this._currentConfig != null ) currentInfo = _currentConfig.DocumenterInfo; // create a new configs collection populated with new configs for each type Hashtable newConfigs = new Hashtable(); foreach ( IDocumenterConfig config in _configs.Values ) newConfigs.Add( config.DocumenterInfo.Name, config.DocumenterInfo.CreateConfig( this ) ); _configs = newConfigs; // reset the active config if ( currentInfo != null ) _currentConfig = _configs[currentInfo.Name] as IDocumenterConfig; IsDirty = false; ProjectFile = ""; } private void _AssemblySlashDocs_Cleared(object sender, EventArgs e) { IsDirty = true; } private void _AssemblySlashDocs_ItemAdded(object sender, AssemblySlashDocEventArgs args) { IsDirty = true; } private void _AssemblySlashDocs_ItemRemoved(object sender, AssemblySlashDocEventArgs args) { IsDirty = true; } } /// <summary>Handles Project <see cref="Project.Modified"/> events.</summary> public delegate void ProjectModifiedEventHandler(object sender, EventArgs e); /// <summary> /// This exception is thrown when one or more assemblies can not be loaded. /// </summary> [Serializable] public class CouldNotLoadAllAssembliesException : ApplicationException { /// <summary/> public CouldNotLoadAllAssembliesException() { } /// <summary/> public CouldNotLoadAllAssembliesException(string message) : base(message) { } /// <summary/> public CouldNotLoadAllAssembliesException(string message, Exception inner) : base(message, inner) { } /// <summary/> protected CouldNotLoadAllAssembliesException( System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } } /// <summary> /// This exception is thrown when there were invalid values in the documenter properties. /// </summary> [Serializable] public class DocumenterPropertyFormatException : ApplicationException { /// <summary/> public DocumenterPropertyFormatException() { } /// <summary/> public DocumenterPropertyFormatException(string message) : base(message) { } /// <summary/> public DocumenterPropertyFormatException(string message, Exception inner) : base(message, inner) { } /// <summary/> protected DocumenterPropertyFormatException( System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } } }
/* * 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.Net; using System.Xml; using System.Reflection; using System.Text; using System.Threading; using OpenSim.Framework; using OpenSim.Framework.Capabilities; using OpenSim.Framework.Client; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Scenes.Serialization; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using OpenMetaverse; using log4net; using Nini.Config; using Mono.Addins; using PermissionMask = OpenSim.Framework.PermissionMask; namespace OpenSim.Region.CoreModules.Framework.InventoryAccess { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "BasicInventoryAccessModule")] public class BasicInventoryAccessModule : INonSharedRegionModule, IInventoryAccessModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected bool m_Enabled = false; protected Scene m_Scene; protected IUserManagement m_UserManagement; protected IUserManagement UserManagementModule { get { if (m_UserManagement == null) m_UserManagement = m_Scene.RequestModuleInterface<IUserManagement>(); return m_UserManagement; } } public bool CoalesceMultipleObjectsToInventory { get; set; } #region INonSharedRegionModule public Type ReplaceableInterface { get { return null; } } public virtual string Name { get { return "BasicInventoryAccessModule"; } } public virtual void Initialise(IConfigSource source) { IConfig moduleConfig = source.Configs["Modules"]; if (moduleConfig != null) { string name = moduleConfig.GetString("InventoryAccessModule", ""); if (name == Name) { m_Enabled = true; InitialiseCommon(source); m_log.InfoFormat("[INVENTORY ACCESS MODULE]: {0} enabled.", Name); } } } /// <summary> /// Common module config for both this and descendant classes. /// </summary> /// <param name="source"></param> protected virtual void InitialiseCommon(IConfigSource source) { IConfig inventoryConfig = source.Configs["Inventory"]; if (inventoryConfig != null) CoalesceMultipleObjectsToInventory = inventoryConfig.GetBoolean("CoalesceMultipleObjectsToInventory", true); else CoalesceMultipleObjectsToInventory = true; } public virtual void PostInitialise() { } public virtual void AddRegion(Scene scene) { if (!m_Enabled) return; m_Scene = scene; scene.RegisterModuleInterface<IInventoryAccessModule>(this); scene.EventManager.OnNewClient += OnNewClient; } protected virtual void OnNewClient(IClientAPI client) { client.OnCreateNewInventoryItem += CreateNewInventoryItem; } public virtual void Close() { if (!m_Enabled) return; } public virtual void RemoveRegion(Scene scene) { if (!m_Enabled) return; m_Scene = null; } public virtual void RegionLoaded(Scene scene) { if (!m_Enabled) return; } #endregion #region Inventory Access /// <summary> /// Create a new inventory item. Called when the client creates a new item directly within their /// inventory (e.g. by selecting a context inventory menu option). /// </summary> /// <param name="remoteClient"></param> /// <param name="transactionID"></param> /// <param name="folderID"></param> /// <param name="callbackID"></param> /// <param name="description"></param> /// <param name="name"></param> /// <param name="invType"></param> /// <param name="type"></param> /// <param name="wearableType"></param> /// <param name="nextOwnerMask"></param> public void CreateNewInventoryItem(IClientAPI remoteClient, UUID transactionID, UUID folderID, uint callbackID, string description, string name, sbyte invType, sbyte assetType, byte wearableType, uint nextOwnerMask, int creationDate) { m_log.DebugFormat("[INVENTORY ACCESS MODULE]: Received request to create inventory item {0} in folder {1}, transactionID {2}", name, folderID, transactionID); if (!m_Scene.Permissions.CanCreateUserInventory(invType, remoteClient.AgentId)) return; InventoryFolderBase f = new InventoryFolderBase(folderID, remoteClient.AgentId); InventoryFolderBase folder = m_Scene.InventoryService.GetFolder(f); if (folder == null || folder.Owner != remoteClient.AgentId) return; if (transactionID != UUID.Zero) { IAgentAssetTransactions agentTransactions = m_Scene.AgentTransactionsModule; if (agentTransactions != null) { if (agentTransactions.HandleItemCreationFromTransaction( remoteClient, transactionID, folderID, callbackID, description, name, invType, assetType, wearableType, nextOwnerMask)) return; } } ScenePresence presence; if (m_Scene.TryGetScenePresence(remoteClient.AgentId, out presence)) { byte[] data = null; if (invType == (sbyte)InventoryType.Landmark && presence != null) { string suffix = string.Empty, prefix = string.Empty; string strdata = GenerateLandmark(presence, out prefix, out suffix); data = Encoding.ASCII.GetBytes(strdata); name = prefix + name; description += suffix; } AssetBase asset = m_Scene.CreateAsset(name, description, assetType, data, remoteClient.AgentId); m_Scene.AssetService.Store(asset); m_Scene.CreateNewInventoryItem( remoteClient, remoteClient.AgentId.ToString(), string.Empty, folderID, name, description, 0, callbackID, asset.FullID, asset.Type, invType, nextOwnerMask, creationDate); } else { m_log.ErrorFormat( "[INVENTORY ACCESS MODULE]: ScenePresence for agent uuid {0} unexpectedly not found in CreateNewInventoryItem", remoteClient.AgentId); } } protected virtual string GenerateLandmark(ScenePresence presence, out string prefix, out string suffix) { prefix = string.Empty; suffix = string.Empty; Vector3 pos = presence.AbsolutePosition; return String.Format("Landmark version 2\nregion_id {0}\nlocal_pos {1} {2} {3}\nregion_handle {4}\n", presence.Scene.RegionInfo.RegionID, pos.X, pos.Y, pos.Z, presence.RegionHandle); } /// <summary> /// Capability originating call to update the asset of an item in an agent's inventory /// </summary> /// <param name="remoteClient"></param> /// <param name="itemID"></param> /// <param name="data"></param> /// <returns></returns> public virtual UUID CapsUpdateInventoryItemAsset(IClientAPI remoteClient, UUID itemID, byte[] data) { InventoryItemBase item = new InventoryItemBase(itemID, remoteClient.AgentId); item = m_Scene.InventoryService.GetItem(item); if (item.Owner != remoteClient.AgentId) return UUID.Zero; if (item != null) { if ((InventoryType)item.InvType == InventoryType.Notecard) { if (!m_Scene.Permissions.CanEditNotecard(itemID, UUID.Zero, remoteClient.AgentId)) { remoteClient.SendAgentAlertMessage("Insufficient permissions to edit notecard", false); return UUID.Zero; } remoteClient.SendAlertMessage("Notecard saved"); } else if ((InventoryType)item.InvType == InventoryType.LSL) { if (!m_Scene.Permissions.CanEditScript(itemID, UUID.Zero, remoteClient.AgentId)) { remoteClient.SendAgentAlertMessage("Insufficient permissions to edit script", false); return UUID.Zero; } remoteClient.SendAlertMessage("Script saved"); } else if ((CustomInventoryType)item.InvType == CustomInventoryType.AnimationSet) { AnimationSet animSet = new AnimationSet(data); if (!animSet.Validate(x => { int perms = m_Scene.InventoryService.GetAssetPermissions(remoteClient.AgentId, x); int required = (int)(PermissionMask.Transfer | PermissionMask.Copy); if ((perms & required) != required) return false; return true; })) { data = animSet.ToBytes(); } } AssetBase asset = CreateAsset(item.Name, item.Description, (sbyte)item.AssetType, data, remoteClient.AgentId.ToString()); item.AssetID = asset.FullID; m_Scene.AssetService.Store(asset); m_Scene.InventoryService.UpdateItem(item); // remoteClient.SendInventoryItemCreateUpdate(item); return (asset.FullID); } else { m_log.ErrorFormat( "[INVENTORY ACCESS MODULE]: Could not find item {0} for caps inventory update", itemID); } return UUID.Zero; } public virtual bool UpdateInventoryItemAsset(UUID ownerID, InventoryItemBase item, AssetBase asset) { if (item != null && item.Owner == ownerID && asset != null) { // m_log.DebugFormat( // "[INVENTORY ACCESS MODULE]: Updating item {0} {1} with new asset {2}", // item.Name, item.ID, asset.ID); item.AssetID = asset.FullID; item.Description = asset.Description; item.Name = asset.Name; item.AssetType = asset.Type; item.InvType = (int)InventoryType.Object; m_Scene.AssetService.Store(asset); m_Scene.InventoryService.UpdateItem(item); return true; } else { m_log.ErrorFormat("[INVENTORY ACCESS MODULE]: Given invalid item for inventory update: {0}", (item == null || asset == null? "null item or asset" : "wrong owner")); return false; } } public virtual List<InventoryItemBase> CopyToInventory( DeRezAction action, UUID folderID, List<SceneObjectGroup> objectGroups, IClientAPI remoteClient, bool asAttachment) { List<InventoryItemBase> copiedItems = new List<InventoryItemBase>(); Dictionary<UUID, List<SceneObjectGroup>> bundlesToCopy = new Dictionary<UUID, List<SceneObjectGroup>>(); if (CoalesceMultipleObjectsToInventory) { // The following code groups the SOG's by owner. No objects // belonging to different people can be coalesced, for obvious // reasons. foreach (SceneObjectGroup g in objectGroups) { if (!bundlesToCopy.ContainsKey(g.OwnerID)) bundlesToCopy[g.OwnerID] = new List<SceneObjectGroup>(); bundlesToCopy[g.OwnerID].Add(g); } } else { // If we don't want to coalesce then put every object in its own bundle. foreach (SceneObjectGroup g in objectGroups) { List<SceneObjectGroup> bundle = new List<SceneObjectGroup>(); bundle.Add(g); bundlesToCopy[g.UUID] = bundle; } } // m_log.DebugFormat( // "[INVENTORY ACCESS MODULE]: Copying {0} object bundles to folder {1} action {2} for {3}", // bundlesToCopy.Count, folderID, action, remoteClient.Name); // Each iteration is really a separate asset being created, // with distinct destinations as well. foreach (List<SceneObjectGroup> bundle in bundlesToCopy.Values) copiedItems.Add(CopyBundleToInventory(action, folderID, bundle, remoteClient, asAttachment)); return copiedItems; } /// <summary> /// Copy a bundle of objects to inventory. If there is only one object, then this will create an object /// item. If there are multiple objects then these will be saved as a single coalesced item. /// </summary> /// <param name="action"></param> /// <param name="folderID"></param> /// <param name="objlist"></param> /// <param name="remoteClient"></param> /// <param name="asAttachment">Should be true if the bundle is being copied as an attachment. This prevents /// attempted serialization of any script state which would abort any operating scripts.</param> /// <returns>The inventory item created by the copy</returns> protected InventoryItemBase CopyBundleToInventory( DeRezAction action, UUID folderID, List<SceneObjectGroup> objlist, IClientAPI remoteClient, bool asAttachment) { CoalescedSceneObjects coa = new CoalescedSceneObjects(UUID.Zero); Dictionary<UUID, Vector3> originalPositions = new Dictionary<UUID, Vector3>(); Dictionary<UUID, Quaternion> originalRotations = new Dictionary<UUID, Quaternion>(); // this possible is not needed if keyframes are saved Dictionary<UUID, KeyframeMotion> originalKeyframes = new Dictionary<UUID, KeyframeMotion>(); foreach (SceneObjectGroup objectGroup in objlist) { if (objectGroup.RootPart.KeyframeMotion != null) { objectGroup.RootPart.KeyframeMotion.Suspend(); } objectGroup.RootPart.SetForce(Vector3.Zero); objectGroup.RootPart.SetAngularImpulse(Vector3.Zero, false); originalKeyframes[objectGroup.UUID] = objectGroup.RootPart.KeyframeMotion; objectGroup.RootPart.KeyframeMotion = null; Vector3 inventoryStoredPosition = objectGroup.AbsolutePosition; originalPositions[objectGroup.UUID] = inventoryStoredPosition; Quaternion inventoryStoredRotation = objectGroup.GroupRotation; originalRotations[objectGroup.UUID] = inventoryStoredRotation; // Restore attachment data after trip through the sim if (objectGroup.RootPart.AttachPoint > 0) { inventoryStoredPosition = objectGroup.RootPart.AttachedPos; inventoryStoredRotation = objectGroup.RootPart.AttachRotation; } // Trees could be attached and it's been done, but it makes // no sense. State must be preserved because it's the tree type if (objectGroup.RootPart.Shape.PCode != (byte) PCode.Tree && objectGroup.RootPart.Shape.PCode != (byte) PCode.NewTree) { objectGroup.RootPart.Shape.State = objectGroup.RootPart.AttachPoint; if (objectGroup.RootPart.AttachPoint > 0) objectGroup.RootPart.Shape.LastAttachPoint = objectGroup.RootPart.AttachPoint; } objectGroup.AbsolutePosition = inventoryStoredPosition; objectGroup.RootPart.RotationOffset = inventoryStoredRotation; // Make sure all bits but the ones we want are clear // on take. // This will be applied to the current perms, so // it will do what we want. objectGroup.RootPart.NextOwnerMask &= ((uint)PermissionMask.Copy | (uint)PermissionMask.Transfer | (uint)PermissionMask.Modify | (uint)PermissionMask.Export); objectGroup.RootPart.NextOwnerMask |= (uint)PermissionMask.Move; coa.Add(objectGroup); } string itemXml; // If we're being called from a script, then trying to serialize that same script's state will not complete // in any reasonable time period. Therefore, we'll avoid it. The worst that can happen is that if // the client/server crashes rather than logging out normally, the attachment's scripts will resume // without state on relog. Arguably, this is what we want anyway. if (objlist.Count > 1) itemXml = CoalescedSceneObjectsSerializer.ToXml(coa, !asAttachment); else itemXml = SceneObjectSerializer.ToOriginalXmlFormat(objlist[0], !asAttachment); // Restore the position of each group now that it has been stored to inventory. foreach (SceneObjectGroup objectGroup in objlist) { objectGroup.AbsolutePosition = originalPositions[objectGroup.UUID]; objectGroup.RootPart.RotationOffset = originalRotations[objectGroup.UUID]; objectGroup.RootPart.KeyframeMotion = originalKeyframes[objectGroup.UUID]; if (objectGroup.RootPart.KeyframeMotion != null) objectGroup.RootPart.KeyframeMotion.Resume(); } InventoryItemBase item = CreateItemForObject(action, remoteClient, objlist[0], folderID); // m_log.DebugFormat( // "[INVENTORY ACCESS MODULE]: Created item is {0}", // item != null ? item.ID.ToString() : "NULL"); if (item == null) return null; item.CreatorId = objlist[0].RootPart.CreatorID.ToString(); item.CreatorData = objlist[0].RootPart.CreatorData; if (objlist.Count > 1) { item.Flags = (uint)InventoryItemFlags.ObjectHasMultipleItems; // If the objects have different creators then don't specify a creator at all foreach (SceneObjectGroup objectGroup in objlist) { if ((objectGroup.RootPart.CreatorID.ToString() != item.CreatorId) || (objectGroup.RootPart.CreatorData.ToString() != item.CreatorData)) { item.CreatorId = UUID.Zero.ToString(); item.CreatorData = string.Empty; break; } } } else { item.SaleType = objlist[0].RootPart.ObjectSaleType; item.SalePrice = objlist[0].RootPart.SalePrice; } AssetBase asset = CreateAsset( objlist[0].GetPartName(objlist[0].RootPart.LocalId), objlist[0].GetPartDescription(objlist[0].RootPart.LocalId), (sbyte)AssetType.Object, Utils.StringToBytes(itemXml), objlist[0].OwnerID.ToString()); m_Scene.AssetService.Store(asset); item.AssetID = asset.FullID; if (DeRezAction.SaveToExistingUserInventoryItem == action) { m_Scene.InventoryService.UpdateItem(item); } else { item.CreationDate = Util.UnixTimeSinceEpoch(); item.Description = asset.Description; item.Name = asset.Name; item.AssetType = asset.Type; //preserve perms on return if(DeRezAction.Return == action) AddPermissions(item, objlist[0], objlist, null); else AddPermissions(item, objlist[0], objlist, remoteClient); m_Scene.AddInventoryItem(item); if (remoteClient != null && item.Owner == remoteClient.AgentId) { remoteClient.SendInventoryItemCreateUpdate(item, 0); } else { ScenePresence notifyUser = m_Scene.GetScenePresence(item.Owner); if (notifyUser != null) { notifyUser.ControllingClient.SendInventoryItemCreateUpdate(item, 0); } } } // This is a hook to do some per-asset post-processing for subclasses that need that if (remoteClient != null) ExportAsset(remoteClient.AgentId, asset.FullID); return item; } protected virtual void ExportAsset(UUID agentID, UUID assetID) { // nothing to do here } /// <summary> /// Add relevant permissions for an object to the item. /// </summary> /// <param name="item"></param> /// <param name="so"></param> /// <param name="objsForEffectivePermissions"></param> /// <param name="remoteClient"></param> /// <returns></returns> protected InventoryItemBase AddPermissions( InventoryItemBase item, SceneObjectGroup so, List<SceneObjectGroup> objsForEffectivePermissions, IClientAPI remoteClient) { uint effectivePerms = (uint)(PermissionMask.Copy | PermissionMask.Transfer | PermissionMask.Modify | PermissionMask.Move | PermissionMask.Export) | 7; uint allObjectsNextOwnerPerms = 0x7fffffff; // For the porposes of inventory, an object is modify if the prims // are modify. This allows renaming an object that contains no // mod items. foreach (SceneObjectGroup grp in objsForEffectivePermissions) { uint groupPerms = grp.GetEffectivePermissions(true); if ((grp.RootPart.BaseMask & (uint)PermissionMask.Modify) != 0) groupPerms |= (uint)PermissionMask.Modify; effectivePerms &= groupPerms; } effectivePerms |= (uint)PermissionMask.Move; //PermissionsUtil.LogPermissions(item.Name, "Before AddPermissions", item.BasePermissions, item.CurrentPermissions, item.NextPermissions); if (remoteClient != null && (remoteClient.AgentId != so.RootPart.OwnerID) && m_Scene.Permissions.PropagatePermissions()) { // Changing ownership, so apply the "Next Owner" permissions to all of the // inventory item's permissions. uint perms = effectivePerms; PermissionsUtil.ApplyFoldedPermissions(effectivePerms, ref perms); item.BasePermissions = perms & so.RootPart.NextOwnerMask; item.CurrentPermissions = item.BasePermissions; item.NextPermissions = perms & so.RootPart.NextOwnerMask; item.EveryOnePermissions = so.RootPart.EveryoneMask & so.RootPart.NextOwnerMask; item.GroupPermissions = so.RootPart.GroupMask & so.RootPart.NextOwnerMask; // apply next owner perms on rez item.CurrentPermissions |= SceneObjectGroup.SLAM; } else { // Not changing ownership. // In this case we apply the permissions in the object's items ONLY to the inventory // item's "Next Owner" permissions, but NOT to its "Current", "Base", etc. permissions. // E.g., if the object contains a No-Transfer item then the item's "Next Owner" // permissions are also No-Transfer. PermissionsUtil.ApplyFoldedPermissions(effectivePerms, ref allObjectsNextOwnerPerms); item.BasePermissions = effectivePerms; item.CurrentPermissions = effectivePerms; item.NextPermissions = so.RootPart.NextOwnerMask & effectivePerms; item.EveryOnePermissions = so.RootPart.EveryoneMask & effectivePerms; item.GroupPermissions = so.RootPart.GroupMask & effectivePerms; item.CurrentPermissions &= ((uint)PermissionMask.Copy | (uint)PermissionMask.Transfer | (uint)PermissionMask.Modify | (uint)PermissionMask.Move | (uint)PermissionMask.Export | 7); // Preserve folded permissions } //PermissionsUtil.LogPermissions(item.Name, "After AddPermissions", item.BasePermissions, item.CurrentPermissions, item.NextPermissions); return item; } /// <summary> /// Create an item using details for the given scene object. /// </summary> /// <param name="action"></param> /// <param name="remoteClient"></param> /// <param name="so"></param> /// <param name="folderID"></param> /// <returns></returns> protected InventoryItemBase CreateItemForObject( DeRezAction action, IClientAPI remoteClient, SceneObjectGroup so, UUID folderID) { // m_log.DebugFormat( // "[BASIC INVENTORY ACCESS MODULE]: Creating item for object {0} {1} for folder {2}, action {3}", // so.Name, so.UUID, folderID, action); // // Get the user info of the item destination // UUID userID = UUID.Zero; if (action == DeRezAction.Take || action == DeRezAction.TakeCopy || action == DeRezAction.SaveToExistingUserInventoryItem) { // Take or take copy require a taker // Saving changes requires a local user // if (remoteClient == null) return null; userID = remoteClient.AgentId; // m_log.DebugFormat( // "[INVENTORY ACCESS MODULE]: Target of {0} in CreateItemForObject() is {1} {2}", // action, remoteClient.Name, userID); } else if (so.RootPart.OwnerID == so.RootPart.GroupID) { // Group owned objects go to the last owner before the object was transferred. userID = so.RootPart.LastOwnerID; } else { // Other returns / deletes go to the object owner // userID = so.RootPart.OwnerID; // m_log.DebugFormat( // "[INVENTORY ACCESS MODULE]: Target of {0} in CreateItemForObject() is object owner {1}", // action, userID); } if (userID == UUID.Zero) // Can't proceed { return null; } // If we're returning someone's item, it goes back to the // owner's Lost And Found folder. // Delete is treated like return in this case // Deleting your own items makes them go to trash // InventoryFolderBase folder = null; InventoryItemBase item = null; if (DeRezAction.SaveToExistingUserInventoryItem == action) { item = new InventoryItemBase(so.RootPart.FromUserInventoryItemID, userID); item = m_Scene.InventoryService.GetItem(item); //item = userInfo.RootFolder.FindItem( // objectGroup.RootPart.FromUserInventoryItemID); if (null == item) { m_log.DebugFormat( "[INVENTORY ACCESS MODULE]: Object {0} {1} scheduled for save to inventory has already been deleted.", so.Name, so.UUID); return null; } } else { // Folder magic // if (action == DeRezAction.Delete) { // Deleting someone else's item // if (remoteClient == null || so.OwnerID != remoteClient.AgentId) { folder = m_Scene.InventoryService.GetFolderForType(userID, FolderType.LostAndFound); } else { folder = m_Scene.InventoryService.GetFolderForType(userID, FolderType.Trash); } } else if (action == DeRezAction.Return) { // Dump to lost + found unconditionally // folder = m_Scene.InventoryService.GetFolderForType(userID, FolderType.LostAndFound); } if (folderID == UUID.Zero && folder == null) { if (action == DeRezAction.Delete) { // Deletes go to trash by default // folder = m_Scene.InventoryService.GetFolderForType(userID, FolderType.Trash); } else { if (remoteClient == null || so.RootPart.OwnerID != remoteClient.AgentId) { // Taking copy of another person's item. Take to // Objects folder. folder = m_Scene.InventoryService.GetFolderForType(userID, FolderType.Object); so.FromFolderID = UUID.Zero; } else { // Catch all. Use lost & found // folder = m_Scene.InventoryService.GetFolderForType(userID, FolderType.LostAndFound); } } } // Override and put into where it came from, if it came // from anywhere in inventory and the owner is taking it back. // if (action == DeRezAction.Take || action == DeRezAction.TakeCopy) { if (so.FromFolderID != UUID.Zero && so.RootPart.OwnerID == remoteClient.AgentId) { InventoryFolderBase f = new InventoryFolderBase(so.FromFolderID, userID); if (f != null) folder = m_Scene.InventoryService.GetFolder(f); if(folder.Type == 14 || folder.Type == 16) { // folder.Type = 6; folder = m_Scene.InventoryService.GetFolderForType(userID, FolderType.Object); } } } if (folder == null) // None of the above { folder = new InventoryFolderBase(folderID); if (folder == null) // Nowhere to put it { return null; } } item = new InventoryItemBase(); item.ID = UUID.Random(); item.InvType = (int)InventoryType.Object; item.Folder = folder.ID; item.Owner = userID; } return item; } public virtual SceneObjectGroup RezObject( IClientAPI remoteClient, UUID itemID, Vector3 RayEnd, Vector3 RayStart, UUID RayTargetID, byte BypassRayCast, bool RayEndIsIntersection, bool RezSelected, bool RemoveItem, UUID fromTaskID, bool attachment) { // m_log.DebugFormat("[INVENTORY ACCESS MODULE]: RezObject for {0}, item {1}", remoteClient.Name, itemID); InventoryItemBase item = new InventoryItemBase(itemID, remoteClient.AgentId); item = m_Scene.InventoryService.GetItem(item); if (item == null) { return null; } item.Owner = remoteClient.AgentId; return RezObject( remoteClient, item, item.AssetID, RayEnd, RayStart, RayTargetID, BypassRayCast, RayEndIsIntersection, RezSelected, RemoveItem, fromTaskID, attachment); } public virtual SceneObjectGroup RezObject( IClientAPI remoteClient, InventoryItemBase item, UUID assetID, Vector3 RayEnd, Vector3 RayStart, UUID RayTargetID, byte BypassRayCast, bool RayEndIsIntersection, bool RezSelected, bool RemoveItem, UUID fromTaskID, bool attachment) { AssetBase rezAsset = m_Scene.AssetService.Get(assetID.ToString()); if (rezAsset == null) { if (item != null) { m_log.WarnFormat( "[InventoryAccessModule]: Could not find asset {0} for item {1} {2} for {3} in RezObject()", assetID, item.Name, item.ID, remoteClient.Name); remoteClient.SendAgentAlertMessage(string.Format("Unable to rez: could not find asset {0} for item {1}.", assetID, item.Name), false); } else { m_log.WarnFormat( "[INVENTORY ACCESS MODULE]: Could not find asset {0} for {1} in RezObject()", assetID, remoteClient.Name); remoteClient.SendAgentAlertMessage(string.Format("Unable to rez: could not find asset {0}.", assetID), false); } return null; } SceneObjectGroup group = null; List<SceneObjectGroup> objlist; List<Vector3> veclist; Vector3 bbox; float offsetHeight; byte bRayEndIsIntersection = (byte)(RayEndIsIntersection ? 1 : 0); Vector3 pos; bool single = m_Scene.GetObjectsToRez( rezAsset.Data, attachment, out objlist, out veclist, out bbox, out offsetHeight); if (single) { pos = m_Scene.GetNewRezLocation( RayStart, RayEnd, RayTargetID, Quaternion.Identity, BypassRayCast, bRayEndIsIntersection, true, bbox, false); pos.Z += offsetHeight; } else { pos = m_Scene.GetNewRezLocation(RayStart, RayEnd, RayTargetID, Quaternion.Identity, BypassRayCast, bRayEndIsIntersection, true, bbox, false); pos -= bbox / 2; } int primcount = 0; foreach (SceneObjectGroup g in objlist) primcount += g.PrimCount; if (!m_Scene.Permissions.CanRezObject( primcount, remoteClient.AgentId, pos) && !attachment) { // The client operates in no fail mode. It will // have already removed the item from the folder // if it's no copy. // Put it back if it's not an attachment // if (item != null) { if (((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0) && (!attachment)) remoteClient.SendBulkUpdateInventory(item); } return null; } if (item != null && !DoPreRezWhenFromItem(remoteClient, item, objlist, pos, veclist, attachment)) return null; for (int i = 0; i < objlist.Count; i++) { group = objlist[i]; SceneObjectPart rootPart = group.RootPart; // m_log.DebugFormat( // "[INVENTORY ACCESS MODULE]: Preparing to rez {0} {1} {2} ownermask={3:X} nextownermask={4:X} groupmask={5:X} everyonemask={6:X} for {7}", // group.Name, group.LocalId, group.UUID, // group.RootPart.OwnerMask, group.RootPart.NextOwnerMask, group.RootPart.GroupMask, group.RootPart.EveryoneMask, // remoteClient.Name); // Vector3 storedPosition = group.AbsolutePosition; if (group.UUID == UUID.Zero) { m_log.Debug("[INVENTORY ACCESS MODULE]: Object has UUID.Zero! Position 3"); } // if this was previously an attachment and is now being rezzed, // save the old attachment info. if (group.IsAttachment == false && group.RootPart.Shape.State != 0) { group.RootPart.AttachedPos = group.AbsolutePosition; group.RootPart.Shape.LastAttachPoint = (byte)group.AttachmentPoint; } if (item == null) { // Change ownership. Normally this is done in DoPreRezWhenFromItem(), but in this case we must do it here. foreach (SceneObjectPart part in group.Parts) { // Make the rezzer the owner, as this is not necessarily set correctly in the serialized asset. part.LastOwnerID = part.OwnerID; part.OwnerID = remoteClient.AgentId; } } group.ResetIDs(); if (!attachment) { // If it's rezzed in world, select it. Much easier to // find small items. // foreach (SceneObjectPart part in group.Parts) { part.CreateSelected = true; } if (rootPart.Shape.PCode == (byte)PCode.Prim) group.ClearPartAttachmentData(); } else { group.IsAttachment = true; } // If we're rezzing an attachment then don't ask // AddNewSceneObject() to update the client since // we'll be doing that later on. Scheduling more than // one full update during the attachment // process causes some clients to fail to display the // attachment properly. m_Scene.AddNewSceneObject(group, true, false); if (!attachment) group.AbsolutePosition = pos + veclist[i]; group.SetGroup(remoteClient.ActiveGroupId, remoteClient); if (!attachment) { // Fire on_rez group.CreateScriptInstances(0, true, m_Scene.DefaultScriptEngine, 1); rootPart.ParentGroup.ResumeScripts(); group.ScheduleGroupForFullUpdate(); } // m_log.DebugFormat( // "[INVENTORY ACCESS MODULE]: Rezzed {0} {1} {2} ownermask={3:X} nextownermask={4:X} groupmask={5:X} everyonemask={6:X} for {7}", // group.Name, group.LocalId, group.UUID, // group.RootPart.OwnerMask, group.RootPart.NextOwnerMask, group.RootPart.GroupMask, group.RootPart.EveryoneMask, // remoteClient.Name); } // group.SetGroup(remoteClient.ActiveGroupId, remoteClient); if (item != null) DoPostRezWhenFromItem(item, attachment); return group; } /// <summary> /// Do pre-rez processing when the object comes from an item. /// </summary> /// <param name="remoteClient"></param> /// <param name="item"></param> /// <param name="objlist"></param> /// <param name="pos"></param> /// <param name="veclist"> /// List of vector position adjustments for a coalesced objects. For ordinary objects /// this list will contain just Vector3.Zero. The order of adjustments must match the order of objlist /// </param> /// <param name="isAttachment"></param> /// <returns>true if we can processed with rezzing, false if we need to abort</returns> private bool DoPreRezWhenFromItem( IClientAPI remoteClient, InventoryItemBase item, List<SceneObjectGroup> objlist, Vector3 pos, List<Vector3> veclist, bool isAttachment) { UUID fromUserInventoryItemId = UUID.Zero; // If we have permission to copy then link the rezzed object back to the user inventory // item that it came from. This allows us to enable 'save object to inventory' if (!m_Scene.Permissions.BypassPermissions()) { if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == (uint)PermissionMask.Copy && (item.Flags & (uint)InventoryItemFlags.ObjectHasMultipleItems) == 0) { fromUserInventoryItemId = item.ID; } } else { if ((item.Flags & (uint)InventoryItemFlags.ObjectHasMultipleItems) == 0) { // Brave new fullperm world fromUserInventoryItemId = item.ID; } } for (int i = 0; i < objlist.Count; i++) { SceneObjectGroup g = objlist[i]; if (!m_Scene.Permissions.CanRezObject( g.PrimCount, remoteClient.AgentId, pos + veclist[i]) && !isAttachment) { // The client operates in no fail mode. It will // have already removed the item from the folder // if it's no copy. // Put it back if it's not an attachment // if (((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0) && (!isAttachment)) remoteClient.SendBulkUpdateInventory(item); ILandObject land = m_Scene.LandChannel.GetLandObject(pos.X, pos.Y); remoteClient.SendAlertMessage(string.Format( "Can't rez object '{0}' at <{1:F3}, {2:F3}, {3:F3}> on parcel '{4}' in region {5}.", item.Name, pos.X, pos.Y, pos.Z, land != null ? land.LandData.Name : "Unknown", m_Scene.Name)); return false; } } for (int i = 0; i < objlist.Count; i++) { SceneObjectGroup so = objlist[i]; SceneObjectPart rootPart = so.RootPart; // Since renaming the item in the inventory does not // affect the name stored in the serialization, transfer // the correct name from the inventory to the // object itself before we rez. // // Only do these for the first object if we are rezzing a coalescence. // nahh dont mess with coalescence objects, // the name in inventory can be change for inventory purpuses only if (objlist.Count == 1) { rootPart.Name = item.Name; rootPart.Description = item.Description; } if ((item.Flags & (uint)InventoryItemFlags.ObjectSlamSale) != 0) { rootPart.ObjectSaleType = item.SaleType; rootPart.SalePrice = item.SalePrice; } so.FromFolderID = item.Folder; // m_log.DebugFormat( // "[INVENTORY ACCESS MODULE]: rootPart.OwnedID {0}, item.Owner {1}, item.CurrentPermissions {2:X}", // rootPart.OwnerID, item.Owner, item.CurrentPermissions); if ((rootPart.OwnerID != item.Owner) || (item.CurrentPermissions & 16) != 0 || (item.Flags & (uint)InventoryItemFlags.ObjectSlamPerm) != 0) { //Need to kill the for sale here rootPart.ObjectSaleType = 0; rootPart.SalePrice = 10; if (m_Scene.Permissions.PropagatePermissions()) { foreach (SceneObjectPart part in so.Parts) { part.GroupMask = 0; // DO NOT propagate here part.LastOwnerID = part.OwnerID; part.OwnerID = item.Owner; part.Inventory.ChangeInventoryOwner(item.Owner); } so.ApplyNextOwnerPermissions(); // In case the user has changed flags on a received item // we have to apply those changes after the slam. Else we // get a net loss of permissions foreach (SceneObjectPart part in so.Parts) { if ((item.Flags & (uint)InventoryItemFlags.ObjectHasMultipleItems) == 0) { if ((item.Flags & (uint)InventoryItemFlags.ObjectOverwriteEveryone) != 0) part.EveryoneMask = item.EveryOnePermissions & part.BaseMask; if ((item.Flags & (uint)InventoryItemFlags.ObjectOverwriteNextOwner) != 0) part.NextOwnerMask = item.NextPermissions & part.BaseMask; } } } } else { foreach (SceneObjectPart part in so.Parts) { part.FromUserInventoryItemID = fromUserInventoryItemId; if ((item.Flags & (uint)InventoryItemFlags.ObjectOverwriteEveryone) != 0) part.EveryoneMask = item.EveryOnePermissions; if ((item.Flags & (uint)InventoryItemFlags.ObjectOverwriteNextOwner) != 0) part.NextOwnerMask = item.NextPermissions; if ((item.Flags & (uint)InventoryItemFlags.ObjectOverwriteGroup) != 0) part.GroupMask = item.GroupPermissions; } } rootPart.TrimPermissions(); if (isAttachment) so.FromItemID = item.ID; } return true; } /// <summary> /// Do post-rez processing when the object comes from an item. /// </summary> /// <param name="item"></param> /// <param name="isAttachment"></param> private void DoPostRezWhenFromItem(InventoryItemBase item, bool isAttachment) { if (!m_Scene.Permissions.BypassPermissions()) { if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0) { // If this is done on attachments, no // copy ones will be lost, so avoid it // if (!isAttachment) { List<UUID> uuids = new List<UUID>(); uuids.Add(item.ID); m_Scene.InventoryService.DeleteItems(item.Owner, uuids); } } } } protected void AddUserData(SceneObjectGroup sog) { UserManagementModule.AddUser(sog.RootPart.CreatorID, sog.RootPart.CreatorData); foreach (SceneObjectPart sop in sog.Parts) UserManagementModule.AddUser(sop.CreatorID, sop.CreatorData); } public virtual void TransferInventoryAssets(InventoryItemBase item, UUID sender, UUID receiver) { } public virtual bool CanGetAgentInventoryItem(IClientAPI remoteClient, UUID itemID, UUID requestID) { InventoryItemBase assetRequestItem = GetItem(remoteClient.AgentId, itemID); if (assetRequestItem == null) { ILibraryService lib = m_Scene.RequestModuleInterface<ILibraryService>(); if (lib != null) assetRequestItem = lib.LibraryRootFolder.FindItem(itemID); if (assetRequestItem == null) return false; } // At this point, we need to apply perms // only to notecards and scripts. All // other asset types are always available // if (assetRequestItem.AssetType == (int)AssetType.LSLText) { if (!m_Scene.Permissions.CanViewScript(itemID, UUID.Zero, remoteClient.AgentId)) { remoteClient.SendAgentAlertMessage("Insufficient permissions to view script", false); return false; } } else if (assetRequestItem.AssetType == (int)AssetType.Notecard) { if (!m_Scene.Permissions.CanViewNotecard(itemID, UUID.Zero, remoteClient.AgentId)) { remoteClient.SendAgentAlertMessage("Insufficient permissions to view notecard", false); return false; } } if (assetRequestItem.AssetID != requestID) { m_log.WarnFormat( "[INVENTORY ACCESS MODULE]: {0} requested asset {1} from item {2} but this does not match item's asset {3}", Name, requestID, itemID, assetRequestItem.AssetID); return false; } return true; } public virtual bool IsForeignUser(UUID userID, out string assetServerURL) { assetServerURL = string.Empty; return false; } #endregion #region Misc /// <summary> /// Create a new asset data structure. /// </summary> /// <param name="name"></param> /// <param name="description"></param> /// <param name="invType"></param> /// <param name="assetType"></param> /// <param name="data"></param> /// <returns></returns> private AssetBase CreateAsset(string name, string description, sbyte assetType, byte[] data, string creatorID) { AssetBase asset = new AssetBase(UUID.Random(), name, assetType, creatorID); asset.Description = description; asset.Data = (data == null) ? new byte[1] : data; return asset; } protected virtual InventoryItemBase GetItem(UUID agentID, UUID itemID) { IInventoryService invService = m_Scene.RequestModuleInterface<IInventoryService>(); InventoryItemBase item = new InventoryItemBase(itemID, agentID); item = invService.GetItem(item); if (item != null && item.CreatorData != null && item.CreatorData != string.Empty) UserManagementModule.AddUser(item.CreatorIdAsUuid, item.CreatorData); return item; } #endregion } }
// // This code was created by Jeff Molofee '99 // // If you've found this code useful, please let me know. // // Visit me at www.demonews.com/hosted/nehe // //===================================================================== // Converted to C# and MonoMac by Kenneth J. Pouncey // http://www.cocoa-mono.org // // Copyright (c) 2011 Kenneth J. Pouncey // // // 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.Drawing; using MonoMac.Foundation; using MonoMac.AppKit; using MonoMac.CoreVideo; using MonoMac.OpenGL; namespace NeHeLesson13 { public partial class MyOpenGLView : MonoMac.AppKit.NSView { NSOpenGLContext openGLContext; NSOpenGLPixelFormat pixelFormat; MainWindowController controller; CVDisplayLink displayLink; NSObject notificationProxy; [Export("initWithFrame:")] public MyOpenGLView (RectangleF frame) : this(frame, null) { } public MyOpenGLView (RectangleF frame,NSOpenGLContext context) : base(frame) { var attribs = new object [] { NSOpenGLPixelFormatAttribute.Accelerated, NSOpenGLPixelFormatAttribute.NoRecovery, NSOpenGLPixelFormatAttribute.DoubleBuffer, NSOpenGLPixelFormatAttribute.ColorSize, 24, NSOpenGLPixelFormatAttribute.DepthSize, 16 }; pixelFormat = new NSOpenGLPixelFormat (attribs); if (pixelFormat == null) Console.WriteLine ("No OpenGL pixel format"); // NSOpenGLView does not handle context sharing, so we draw to a custom NSView instead openGLContext = new NSOpenGLContext (pixelFormat, context); openGLContext.MakeCurrentContext (); // Synchronize buffer swaps with vertical refresh rate openGLContext.SwapInterval = true; // Initialize our newly created view. InitGL (); SetupDisplayLink (); // Look for changes in view size // Note, -reshape will not be called automatically on size changes because NSView does not export it to override notificationProxy = NSNotificationCenter.DefaultCenter.AddObserver (NSView.NSViewGlobalFrameDidChangeNotification, HandleReshape); } public override void DrawRect (RectangleF dirtyRect) { // Ignore if the display link is still running if (!displayLink.IsRunning && controller != null) DrawView (); } public override bool AcceptsFirstResponder () { // We want this view to be able to receive key events return true; } public override void LockFocus () { base.LockFocus (); if (openGLContext.View != this) openGLContext.View = this; } public override void KeyDown (NSEvent theEvent) { controller.KeyDown (theEvent); } public override void MouseDown (NSEvent theEvent) { controller.MouseDown (theEvent); } // All Setup For OpenGL Goes Here public bool InitGL () { // Enables Smooth Shading GL.ShadeModel (ShadingModel.Smooth); // Set background color to black GL.ClearColor (Color.Black); // Setup Depth Testing // Depth Buffer setup GL.ClearDepth (1.0); // Enables Depth testing GL.Enable (EnableCap.DepthTest); // The type of depth testing to do GL.DepthFunc (DepthFunction.Lequal); // Really Nice Perspective Calculations GL.Hint (HintTarget.PerspectiveCorrectionHint, HintMode.Nicest); return true; } private void DrawView () { // This method will be called on both the main thread (through -drawRect:) and a secondary thread (through the display link rendering loop) // Also, when resizing the view, -reshape is called on the main thread, but we may be drawing on a secondary thread // Add a mutex around to avoid the threads accessing the context simultaneously openGLContext.CGLContext.Lock (); // Make sure we draw to the right context openGLContext.MakeCurrentContext (); // Delegate to the scene object for rendering controller.Scene.DrawGLScene (); openGLContext.FlushBuffer (); openGLContext.CGLContext.Unlock (); } private void SetupDisplayLink () { // Create a display link capable of being used with all active displays displayLink = new CVDisplayLink (); // Set the renderer output callback function displayLink.SetOutputCallback (MyDisplayLinkOutputCallback); // Set the display link for the current renderer CGLContext cglContext = openGLContext.CGLContext; CGLPixelFormat cglPixelFormat = PixelFormat.CGLPixelFormat; displayLink.SetCurrentDisplay (cglContext, cglPixelFormat); } public CVReturn MyDisplayLinkOutputCallback (CVDisplayLink displayLink, ref CVTimeStamp inNow, ref CVTimeStamp inOutputTime, CVOptionFlags flagsIn, ref CVOptionFlags flagsOut) { CVReturn result = GetFrameForTime (inOutputTime); return result; } private CVReturn GetFrameForTime (CVTimeStamp outputTime) { // There is no autorelease pool when this method is called because it will be called from a background thread // It's important to create one or you will leak objects using (NSAutoreleasePool pool = new NSAutoreleasePool ()) { // Update the animation DrawView (); } return CVReturn.Success; } public NSOpenGLContext OpenGLContext { get { return openGLContext; } } public NSOpenGLPixelFormat PixelFormat { get { return pixelFormat; } } public MainWindowController MainController { set { controller = value; } } public void UpdateView () { // This method will be called on the main thread when resizing, but we may be drawing on a secondary thread through the display link // Add a mutex around to avoid the threads accessing the context simultaneously openGLContext.CGLContext.Lock (); // Delegate to the scene object to update for a change in the view size controller.Scene.ResizeGLScene (Bounds); openGLContext.Update (); openGLContext.CGLContext.Unlock (); } private void HandleReshape (NSNotification note) { UpdateView (); } public void StartAnimation () { if (displayLink != null && !displayLink.IsRunning) displayLink.Start (); } public void StopAnimation () { if (displayLink != null && displayLink.IsRunning) displayLink.Stop (); } // Clean up the notifications public void DeAllocate () { displayLink.Stop (); displayLink.SetOutputCallback (null); NSNotificationCenter.DefaultCenter.RemoveObserver (notificationProxy); } [Export("toggleFullScreen:")] public void toggleFullScreen (NSObject sender) { controller.toggleFullScreen (sender); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace ClousotCacheTests { using System.Collections.Generic; using System.IO; using System.Linq; using Tests; using Xunit; using Xunit.Abstractions; /// <summary> /// Cache tests for the static checker. /// </summary> /// <remarks> /// For XUnit there is no way to guarantee the test order of [MemberData] driven tests - however for these tests the order is important. /// Workaround: use [Fact] instead of [Theory]+[MemberData] and execute all cases within one test. /// </remarks> public class ClousotCacheTests { private readonly ITestOutputHelper _testOutputHelper; public ClousotCacheTests(ITestOutputHelper testOutputHelper) { _testOutputHelper = testOutputHelper; } #region Test data private static IEnumerable<Options> TestRunDataSource { get { // These 4 TestRun must be run together in that order ! yield return new Options( sourceFile: @"Microsoft.Research\RegressionTest\ClousotCacheTests\Sources\Test.cs", compilerOptions: @"/optimize /d:FIRST", libPaths: new string[0], references: new string[0], clousotOptions: @"-nonnull -bounds -show progress -cache -emitErrorOnCacheLookup -clearCache -cacheServer="""" -cacheName:Test", useContractReferenceAssemblies: true, useExe: false, compilerCode: "CS" ); yield return new Options( sourceFile: @"Microsoft.Research\RegressionTest\ClousotCacheTests\Sources\Test2.cs", compilerOptions: @"/optimize /d:FIRST", libPaths: new string[0], references: new string[0], clousotOptions: @"-nonnull -bounds -show progress -cache -emitErrorOnCacheLookup -cacheServer="""" -cacheName:Test", useContractReferenceAssemblies: true, useExe: false, compilerCode: "CS" ); yield return new Options( sourceFile: @"Microsoft.Research\RegressionTest\ClousotCacheTests\Sources\Test.cs", compilerOptions: @"/optimize", libPaths: new string[0], references: new string[0], clousotOptions: @"-nonnull -bounds -show progress -cache -emitErrorOnCacheLookup -cacheServer="""" -cacheName:Test", useContractReferenceAssemblies: true, useExe: false, compilerCode: "CS" ); yield return new Options( sourceFile: @"Microsoft.Research\RegressionTest\ClousotCacheTests\Sources\Test2.cs", compilerOptions: @"/optimize", libPaths: new string[0], references: new string[0], clousotOptions: @"-nonnull -bounds -show progress -cache -emitErrorOnCacheLookup -cacheServer="""" -cacheName:Test", useContractReferenceAssemblies: true, useExe: false, compilerCode: "CS" ); // The remaining TestRun's are paired. Each pair must be run in that order yield return new Options( sourceFile: @"Microsoft.Research\RegressionTest\ClousotCacheTests\Sources\TestQuantifiers.cs", compilerOptions: @"/optimize /d:FIRST", libPaths: new string[0], references: new string[0], clousotOptions: @"-nonnull -bounds -arrays -show progress -cache -emitErrorOnCacheLookup -clearCache -cacheServer="""" -cacheName:Test", useContractReferenceAssemblies: true, useExe: false, compilerCode: "CS" ); yield return new Options( sourceFile: @"Microsoft.Research\RegressionTest\ClousotCacheTests\Sources\TestQuantifiers.cs", compilerOptions: @"/optimize", libPaths: new string[0], references: new string[0], clousotOptions: @"-nonnull -bounds -arrays -show progress -cache -emitErrorOnCacheLookup -cacheServer="""" -cacheName:Test", useContractReferenceAssemblies: true, useExe: false, compilerCode: "CS" ); yield return new Options( sourceFile: @"Microsoft.Research\RegressionTest\ClousotCacheTests\Sources\DB.cs", compilerOptions: @"/optimize /d:FIRST /debug-", libPaths: new string[0], references: new string[0], clousotOptions: @"-nonnull -bounds -show progress -cache -emitErrorOnCacheLookup -clearCache -cacheServer="""" -cacheName:Test", useContractReferenceAssemblies: true, useExe: false, compilerCode: "CS" ); yield return new Options( sourceFile: @"Microsoft.Research\RegressionTest\ClousotCacheTests\Sources\DB.cs", compilerOptions: @"/optimize /debug-", libPaths: new string[0], references: new string[0], clousotOptions: @"-nonnull -bounds -show progress -cache -emitErrorOnCacheLookup -cacheServer="""" -cacheName:Test", useContractReferenceAssemblies: true, useExe: false, compilerCode: "CS" ); yield return new Options( sourceFile: @"Microsoft.Research\RegressionTest\ClousotCacheTests\Sources\Serialization.cs", compilerOptions: @"/optimize /d:FIRST /debug-", libPaths: new string[0], references: new string[0], clousotOptions: @"-nonnull -bounds -show progress -cache -emitErrorOnCacheLookup -clearCache -cacheServer="""" -cacheName:Test", useContractReferenceAssemblies: true, useExe: false, compilerCode: "CS" ); yield return new Options( sourceFile: @"Microsoft.Research\RegressionTest\ClousotCacheTests\Sources\Serialization.cs", compilerOptions: @"/optimize /debug-", libPaths: new string[0], references: new string[0], clousotOptions: @"-nonnull -bounds -show progress -cache -emitErrorOnCacheLookup -cacheServer="""" -cacheName:Test", useContractReferenceAssemblies: true, useExe: false, compilerCode: "CS" ); yield return new Options( sourceFile: @"Microsoft.Research\RegressionTest\ClousotCacheTests\Sources\SerializationInferred.cs", compilerOptions: @"/optimize /d:FIRST /debug-", libPaths: new string[0], references: new string[0], clousotOptions: @"-includesuggestionsinregression -suggest requires -suggest methodensures -infer methodensures -infer requires -nonnull -bounds -show progress -cache -emitErrorOnCacheLookup -clearCache -cacheServer="""" -cacheName:Test", useContractReferenceAssemblies: true, useExe: false, compilerCode: "CS" ); yield return new Options( sourceFile: @"Microsoft.Research\RegressionTest\ClousotCacheTests\Sources\SerializationInferred.cs", compilerOptions: @"/optimize /debug-", libPaths: new string[0], references: new string[0], clousotOptions: @"-includesuggestionsinregression -suggest requires -suggest methodensures -infer methodensures -infer requires -nonnull -bounds -show progress -cache -emitErrorOnCacheLookup -cacheServer="""" -cacheName:Test", useContractReferenceAssemblies: true, useExe: false, compilerCode: "CS" ); yield return new Options( sourceFile: @"Microsoft.Research\RegressionTest\ClousotCacheTests\Sources\SemanticBaseliningTests.cs", compilerOptions: @"/optimize /d:FIRST", libPaths: new string[0], references: new string[0], clousotOptions: @"-show progress,validations -emitErrorOnCacheLookup -clearCache -cache -cacheServer="""" -cacheName:Test -infer methodensures -suggest methodensures -suggest assumes -suggest requires -nonnull -bounds -repairs -premode combined -saveSemanticBaseline:semanticTest", useContractReferenceAssemblies: true, useExe: false, compilerCode: "CS" ); yield return new Options( sourceFile: @"Microsoft.Research\RegressionTest\ClousotCacheTests\Sources\SemanticBaseliningTests.cs", compilerOptions: @"/optimize", libPaths: new string[0], references: new string[0], clousotOptions: @"-show progress,validations -emitErrorOnCacheLookup -cache -cacheServer="""" -cacheName:Test -infer methodensures -suggest methodensures -suggest assumes -suggest requires -nonnull -bounds -repairs -premode combined -useSemanticBaseline:semanticTest -skipIdenticalMethods=false", useContractReferenceAssemblies: true, useExe: false, compilerCode: "CS" ); /* yield return new Options( sourceFile: @"Microsoft.Research\RegressionTest\ClousotCacheTests\Sources\TestPurity.cs", compilerOptions: @"/optimize /d:FIRST", libPaths: new string[0], references: new string[0], clousotOptions: @"-nonnull:noobl -bounds:noobl -arrays:arraypurity -infer arraypurity -suggest arraypurity -show progress -cache -emitErrorOnCacheLookup -cacheName:Test" useContractReferenceAssemblies: true, useExe: false, compilerCode: "CS" SkipCCI2="true" ); yield return new Options( sourceFile: @"Microsoft.Research\RegressionTest\ClousotCacheTests\Sources\TestPurity.cs", compilerOptions: @"/optimize", libPaths: new string[0], references: new string[0], clousotOptions: @"-nonnull:noobl -bounds:noobl -arrays:arraypurity -infer arraypurity -suggest arraypurity -show progress -cache -emitErrorOnCacheLookup -cacheName:Test" useContractReferenceAssemblies: true, useExe: false, compilerCode: "CS" SkipCCI2="true" ); */ } } private static readonly Options[] TestRunData = TestRunDataSource.ToArray(); #endregion [Fact] [Trait("Category", "StaticChecker"), Trait("Category", "Clousot1"), Trait("Category", "Cache")] public void V35Cache() { Execute(@"v3.5", @"v3.5"); } [Fact] [Trait("Category", "StaticChecker"), Trait("Category", "Clousot1"), Trait("Category", "Cache")] public void V40Cache() { Execute(@".NETFramework\v4.0", @".NETFramework\v4.0"); } [Fact] [Trait("Category", "StaticChecker"), Trait("Category", "Clousot1"), Trait("Category", "Cache")] public void V40AgainstV35ContractsCache() { Execute( @".NETFramework\v4.0", @"v3.5"); } private void Execute(string buildFramework, string contractFramework) { foreach (var testIndex in Enumerable.Range(0, TestRunData.Length)) { var options = TestRunData[testIndex]; var testName = Path.GetFileNameWithoutExtension(options.SourceFile) + "_" + testIndex; Execute(testIndex, testName, buildFramework, contractFramework); } } private void Execute(int testIndex, string testName, string buildFramework, string contractFramework) { var options = TestRunData[testIndex]; options.BuildFramework = buildFramework; options.ContractFramework = contractFramework; TestDriver.BuildAndAnalyze(_testOutputHelper, options, testName, testIndex); } } }
#region License, Terms and Conditions // // Jayrock - JSON and JSON-RPC for Microsoft .NET Framework and Mono // Written by Atif Aziz (atif.aziz@skybow.com) // Copyright (c) 2005 Atif Aziz. All rights reserved. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License as published by the Free // Software Foundation; either version 2.1 of the License, or (at your option) // any later version. // // This library 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 Lesser General Public License for more // details. // // You should have received a copy of the GNU Lesser General Public License // along with this library; if not, write to the Free Software Foundation, Inc., // 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #endregion namespace EZOper.NetSiteUtilities.Jayrock { #region Imports using System; using System.IO; #endregion /// <summary> /// Represents a writer that provides a fast, non-cached, forward-only means of /// emitting JSON data formatted as JSON text (RFC 4627). /// </summary> public class JsonTextWriter : JsonWriterBase { private readonly TextWriter _writer; // // Pretty printing as per: // http://developer.mozilla.org/es4/proposals/json_encoding_and_decoding.html // // <quote> // ...linefeeds are inserted after each { and , and before } , and multiples // of 4 spaces are inserted to indicate the level of nesting, and one space // will be inserted after :. Otherwise, no whitespace is inserted between // the tokens. // </quote> // private bool _prettyPrint; private bool _newLine; private int _indent; private char[] _indentBuffer; public JsonTextWriter() : this(null) {} public JsonTextWriter(TextWriter writer) { _writer = writer != null ? writer : new StringWriter(); } public bool PrettyPrint { get { return _prettyPrint; } set { _prettyPrint = value; } } protected TextWriter InnerWriter { get { return _writer; } } public override void Flush() { _writer.Flush(); } public override string ToString() { StringWriter stringWriter = _writer as StringWriter; return stringWriter != null ? stringWriter.ToString() : base.ToString(); } protected override void WriteStartObjectImpl() { OnWritingValue(); WriteDelimiter('{'); PrettySpace(); } protected override void WriteEndObjectImpl() { if (Index > 0) { PrettyLine(); _indent--; } WriteDelimiter('}'); } protected override void WriteMemberImpl(string name) { if (Index > 0) { WriteDelimiter(','); PrettyLine(); } else { PrettyLine(); _indent++; } WriteStringImpl(name); PrettySpace(); WriteDelimiter(':'); PrettySpace(); } protected override void WriteStringImpl(string value) { WriteScalar(JsonString.Enquote(value)); } protected override void WriteNumberImpl(string value) { WriteScalar(value); } protected override void WriteBooleanImpl(bool value) { WriteScalar(value ? JsonBoolean.TrueText : JsonBoolean.FalseText); } protected override void WriteNullImpl() { WriteScalar(JsonNull.Text); } protected override void WriteStartArrayImpl() { OnWritingValue(); WriteDelimiter('['); PrettySpace(); } protected override void WriteEndArrayImpl() { if (IsNonEmptyArray()) PrettySpace(); WriteDelimiter(']'); } private void WriteScalar(string text) { OnWritingValue(); PrettyIndent(); _writer.Write(text); } private bool IsNonEmptyArray() { return Bracket == JsonWriterBracket.Array && Index > 0; } // // Methods below are mostly related to pretty-printing of JSON text. // private void OnWritingValue() { if (IsNonEmptyArray()) { WriteDelimiter(','); PrettySpace(); } } private void WriteDelimiter(char ch) { PrettyIndent(); _writer.Write(ch); } private void PrettySpace() { if (!_prettyPrint) return; WriteDelimiter(' '); } private void PrettyLine() { if (!_prettyPrint) return; _writer.WriteLine(); _newLine = true; } private void PrettyIndent() { if (!_prettyPrint) return; if (_newLine) { if (_indent > 0) { int spaces = _indent * 4; if (_indentBuffer == null || _indentBuffer.Length < spaces) _indentBuffer = new string(' ', spaces * 4).ToCharArray(); _writer.Write(_indentBuffer, 0, spaces); } _newLine = false; } } } }
/* * MindTouch Dream - a distributed REST framework * Copyright (C) 2006-2014 MindTouch, Inc. * www.mindtouch.com oss@mindtouch.com * * For community documentation and downloads visit 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; namespace MindTouch.Collections { /// <summary> /// Provides a queue that allows items to pushed and popped by a single thread while /// other threads may attempt steal from it. The implementation is based on the work done by /// Danny Hendler, Yossi Lev, Mark Moir, and Nir Shavit: "A dynamic-sized nonblocking work stealing deque", /// Distributed Computing, Volume 18, Issue 3 (February 2006), pp189-207, ISSN:0178-2770 /// </summary> /// <typeparam name="T">Collection item type.</typeparam> public sealed class WorkStealingDeque<T> where T: class { //--- Constants --- private const int DEFAULT_CAPACITY = 32; //--- Types --- internal class BottomData { //--- Fields --- internal readonly DequeNode Node; internal readonly int Index; //--- Constructors --- internal BottomData(DequeNode node, int index) { this.Node = node; this.Index = index; } } internal class TopData { //--- Fields --- internal readonly int Tag; internal readonly DequeNode Node; internal readonly int Index; //--- Constructors --- internal TopData(int tag, DequeNode node, int index) { this.Tag = tag; this.Node = node; this.Index = index; } } internal class DequeNode { //--- Fields --- internal readonly T[] Data; internal DequeNode Next; internal DequeNode Prev; //--- Constructors --- internal DequeNode(int capacity, DequeNode next) { Data = new T[capacity]; if(next != null) { this.Next = next; next.Prev = this; } } } //--- Class Methods --- private static bool IsEmpty(BottomData bottom, TopData top, int capacity) { if(ReferenceEquals(bottom.Node, top.Node) && ((bottom.Index == top.Index) || (bottom.Index == (top.Index + 1)))) { return true; } else if(ReferenceEquals(bottom.Node, top.Node.Next) && (bottom.Index == 0) && (top.Index == (capacity - 1))) { return true; } return false; } //--- Fields --- private readonly int _capacity; private BottomData _bottom; private TopData _top; //--- Constructors --- /// <summary> /// Create a new instance. /// </summary> public WorkStealingDeque() : this(DEFAULT_CAPACITY) { } /// <summary> /// Create a new instance. /// </summary> /// <param name="capacity">Maximum number of items in the queue.</param> public WorkStealingDeque(int capacity) { _capacity = capacity; DequeNode nodeB = new DequeNode(_capacity, null); DequeNode nodeA = new DequeNode(_capacity, nodeB); _bottom = new BottomData(nodeA, _capacity - 1); _top = new TopData(0, nodeA, _capacity - 1); } //--- Properties --- /// <summary> /// Total number of items in queue. /// </summary> public int Count { get { BottomData curBottom = _bottom; TopData curTop = _top; int count; // check if top and bottom share the same node if(ReferenceEquals(curBottom.Node, curTop.Node)) { count = Math.Max(0, curTop.Index - curBottom.Index); } else if(ReferenceEquals(curBottom.Node, curTop.Node.Next) && (curBottom.Index == 0) && (curTop.Index == (_capacity - 1))) { count = 0; } else { count = _capacity - (curBottom.Index + 1); for(var node = curBottom.Node.Next; (node != curTop.Node) && (node != null); node = node.Next) { count += _capacity; } count += curTop.Index + 1; } return count; } } //--- Methods --- /// <summary> /// Push an item onto the tail of the queue. /// </summary> /// <remarks> /// NOTE: Push() and TryPop() <strong>MUST</strong> be called from the same thread. /// </remarks> /// <param name="data">Item to push onto the tail of the queue.</param> public void Push(T data) { // read bottom data BottomData curBottom = _bottom; // write data in current bottom cell curBottom.Node.Data[curBottom.Index] = data; BottomData newBottom; if(curBottom.Index != 0) { newBottom = new BottomData(curBottom.Node, curBottom.Index - 1); } else { // allocate and link a new node DequeNode newNode = new DequeNode(_capacity, curBottom.Node); newBottom = new BottomData(newNode, _capacity - 1); } // update bottom _bottom = newBottom; } /// <summary> /// Pop an item from the tail of the queue. /// </summary> /// <remarks> /// NOTE: Push() and TryPop() <strong>MUST</strong> be called from the same thread. /// </remarks> /// <param name="item">Tail item of the queue when operation is successful.</param> /// <returns><see langword="True"/> if operation was successful.</returns> public bool TryPop(out T item) { item = default(T); // read bottom data BottomData curBottom = _bottom; BottomData newBottom; if(curBottom.Index != (_capacity - 1)) { newBottom = new BottomData(curBottom.Node, curBottom.Index + 1); } else { newBottom = new BottomData(curBottom.Node.Next, 0); } // update bottom _bottom = newBottom; // read top TopData curTop = _top; // read data to be popped T retVal = newBottom.Node.Data[newBottom.Index]; // case 1: if _top has crossed _bottom if(ReferenceEquals(curBottom.Node, curTop.Node) && (curBottom.Index == curTop.Index)) { // return bottom to its old position _bottom = curBottom; return false; } // case 2: when popping the last entry in the deque (i.e. deque is empty after the update of bottom) if(ReferenceEquals(newBottom.Node, curTop.Node) && (newBottom.Index == curTop.Index)) { // try to update _top's tag so no concurrent Steal operation will also pop the same entry TopData newTopVal = new TopData(curTop.Tag + 1, curTop.Node, curTop.Index); if(SysUtil.CAS(ref _top, curTop, newTopVal)) { // clear out the entry we read, so the GC can reclaim it newBottom.Node.Data[newBottom.Index] = default(T); // free old node if needed if(!ReferenceEquals(curBottom.Node, newBottom.Node)) { newBottom.Node.Prev = null; } item = retVal; return true; } else { // if CAS failed (i.e. a concurrent Steal operation alrady popped that last entry) // return bottom to its old position _bottom = curBottom; return false; } } // case 3: regular case (i.e. there was a least one entry in the deque _after_ bottom's update) // free old node if needed if(!ReferenceEquals(curBottom.Node, newBottom.Node)) { newBottom.Node.Prev = null; } item = retVal; return true; } /// <summary> /// Pop an item from the head of the queue. /// </summary> /// <remarks> /// NOTE: TrySteal() can be invoked from any thread. /// </remarks> /// <param name="item">Head item of the queue when operation is successful.</param> /// <returns><see langword="True"/> if operation was successful.</returns> public bool TrySteal(out T item) { // read top TopData curTop = _top; // read bottom BottomData curBottom = _bottom; if(IsEmpty(curBottom, curTop, _capacity)) { item = default(T); if(ReferenceEquals(curTop, _top)) { return false; } else { // NOTE (steveb): this is contentious access case; we currently return 'false' but may want to differentiate in the future return false; } } // if deque isn't empty, calcuate next top pointer TopData newTop; if(curTop.Index != 0) { // stay at current node newTop = new TopData(curTop.Tag, curTop.Node, curTop.Index - 1); } else { // move to next node and update tag newTop = new TopData(curTop.Tag + 1, curTop.Node.Prev, _capacity - 1); } // read value T retVal = curTop.Node.Data[curTop.Index]; // try updating _top using CAS if(SysUtil.CAS(ref _top, curTop, newTop)) { // clear out the entry we read, so the GC can reclaim it SysUtil.CAS(ref curTop.Node.Data[curTop.Index], retVal, default(T)); // free old node curTop.Node.Next = null; item = retVal; return true; } else { item = default(T); // NOTE (steveb): this is contentious access case; we currently return 'false' but may want to differentiate in the future return false; } } } }
/* * CID0008.cs - el culture handler. * * Copyright (c) 2003 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 */ // Generated from "el.txt". namespace I18N.West { using System; using System.Globalization; using I18N.Common; public class CID0008 : RootCulture { public CID0008() : base(0x0008) {} public CID0008(int culture) : base(culture) {} public override String Name { get { return "el"; } } public override String ThreeLetterISOLanguageName { get { return "ell"; } } public override String ThreeLetterWindowsLanguageName { get { return "ELL"; } } public override String TwoLetterISOLanguageName { get { return "el"; } } public override DateTimeFormatInfo DateTimeFormat { get { DateTimeFormatInfo dfi = base.DateTimeFormat; dfi.AMDesignator = "\u03C0\u03BC"; dfi.PMDesignator = "\u03BC\u03BC"; dfi.AbbreviatedDayNames = new String[] {"\u039A\u03C5\u03C1", "\u0394\u03B5\u03C5", "\u03A4\u03C1\u03B9", "\u03A4\u03B5\u03C4", "\u03A0\u03B5\u03BC", "\u03A0\u03B1\u03C1", "\u03A3\u03B1\u03B2"}; dfi.DayNames = new String[] {"\u039A\u03C5\u03C1\u03B9\u03B1\u03BA\u03AE", "\u0394\u03B5\u03C5\u03C4\u03AD\u03C1\u03B1", "\u03A4\u03C1\u03AF\u03C4\u03B7", "\u03A4\u03B5\u03C4\u03AC\u03C1\u03C4\u03B7", "\u03A0\u03AD\u03BC\u03C0\u03C4\u03B7", "\u03A0\u03B1\u03C1\u03B1\u03C3\u03BA\u03B5\u03C5\u03AE", "\u03A3\u03AC\u03B2\u03B2\u03B1\u03C4\u03BF"}; dfi.AbbreviatedMonthNames = new String[] {"\u0399\u03B1\u03BD", "\u03A6\u03B5\u03B2", "\u039C\u03B1\u03C1", "\u0391\u03C0\u03C1", "\u039C\u03B1\u03CA", "\u0399\u03BF\u03C5\u03BD", "\u0399\u03BF\u03C5\u03BB", "\u0391\u03C5\u03B3", "\u03A3\u03B5\u03C0", "\u039F\u03BA\u03C4", "\u039D\u03BF\u03B5", "\u0394\u03B5\u03BA", ""}; dfi.MonthNames = new String[] {"\u0399\u03B1\u03BD\u03BF\u03C5\u03AC\u03C1\u03B9\u03BF\u03C2", "\u03A6\u03B5\u03B2\u03C1\u03BF\u03C5\u03AC\u03C1\u03B9\u03BF\u03C2", "\u039C\u03AC\u03C1\u03C4\u03B9\u03BF\u03C2", "\u0391\u03C0\u03C1\u03AF\u03BB\u03B9\u03BF\u03C2", "\u039C\u03AC\u03CA\u03BF\u03C2", "\u0399\u03BF\u03CD\u03BD\u03B9\u03BF\u03C2", "\u0399\u03BF\u03CD\u03BB\u03B9\u03BF\u03C2", "\u0391\u03CD\u03B3\u03BF\u03C5\u03C3\u03C4\u03BF\u03C2", "\u03A3\u03B5\u03C0\u03C4\u03AD\u03BC\u03B2\u03C1\u03B9\u03BF\u03C2", "\u039F\u03BA\u03C4\u03CE\u03B2\u03C1\u03B9\u03BF\u03C2", "\u039D\u03BF\u03AD\u03BC\u03B2\u03C1\u03B9\u03BF\u03C2", "\u0394\u03B5\u03BA\u03AD\u03BC\u03B2\u03C1\u03B9\u03BF\u03C2", ""}; dfi.DateSeparator = "/"; dfi.TimeSeparator = ":"; dfi.LongDatePattern = "d MMMM yyyy"; dfi.LongTimePattern = "h:mm:ss tt z"; dfi.ShortDatePattern = "d/M/yyyy"; dfi.ShortTimePattern = "h:mm tt"; dfi.FullDateTimePattern = "dddd, d MMMM yyyy h:mm:ss tt z"; dfi.I18NSetDateTimePatterns(new String[] { "d:d/M/yyyy", "D:dddd, d MMMM yyyy", "f:dddd, d MMMM yyyy h:mm:ss tt z", "f:dddd, d MMMM yyyy h:mm:ss tt z", "f:dddd, d MMMM yyyy h:mm:ss tt", "f:dddd, d MMMM yyyy h:mm tt", "F:dddd, d MMMM yyyy HH:mm:ss", "g:d/M/yyyy h:mm:ss tt z", "g:d/M/yyyy h:mm:ss tt z", "g:d/M/yyyy h:mm:ss tt", "g:d/M/yyyy h:mm tt", "G:d/M/yyyy HH:mm:ss", "m:MMMM dd", "M:MMMM dd", "r:ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", "R:ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", "s:yyyy'-'MM'-'dd'T'HH':'mm':'ss", "t:h:mm:ss tt z", "t:h:mm:ss tt z", "t:h:mm:ss tt", "t:h:mm tt", "T:HH:mm:ss", "u:yyyy'-'MM'-'dd HH':'mm':'ss'Z'", "U:dddd, dd MMMM yyyy HH:mm:ss", "y:yyyy MMMM", "Y:yyyy MMMM", }); return dfi; } set { base.DateTimeFormat = value; // not used } } public override NumberFormatInfo NumberFormat { get { NumberFormatInfo nfi = base.NumberFormat; nfi.CurrencyDecimalSeparator = ","; nfi.CurrencyGroupSeparator = "."; nfi.NumberGroupSeparator = "."; nfi.PercentGroupSeparator = "."; nfi.NegativeSign = "-"; nfi.NumberDecimalSeparator = ","; nfi.PercentDecimalSeparator = ","; nfi.PercentSymbol = "%"; nfi.PerMilleSymbol = "\u2030"; return nfi; } set { base.NumberFormat = value; // not used } } public override String ResolveLanguage(String name) { switch(name) { case "ar": return "\u0391\u03c1\u03b1\u03b2\u03b9\u03ba\u03ac"; case "bg": return "\u0392\u03bf\u03c5\u03bb\u03b3\u03b1\u03c1\u03b9\u03ba\u03ac"; case "ca": return "\u039a\u03b1\u03c4\u03b1\u03bb\u03b1\u03bd\u03b9\u03ba\u03ac"; case "cs": return "\u03a4\u03c3\u03ad\u03c7\u03b9\u03ba\u03b1"; case "da": return "\u0394\u03b1\u03bd\u03ad\u03b6\u03b9\u03ba\u03b1"; case "de": return "\u0393\u03b5\u03c1\u03bc\u03b1\u03bd\u03b9\u03ba\u03ac"; case "el": return "\u03b5\u03bb\u03bb\u03b7\u03bd\u03b9\u03ba\u03ac"; case "en": return "\u0391\u03b3\u03b3\u03bb\u03b9\u03ba\u03ac"; case "es": return "\u0399\u03c3\u03c0\u03b1\u03bd\u03b9\u03ba\u03ac"; case "fi": return "\u03a6\u03b9\u03bd\u03bb\u03b1\u03bd\u03b4\u03b9\u03ba\u03ac"; case "fr": return "\u0393\u03b1\u03bb\u03bb\u03b9\u03ba\u03ac"; case "he": return "\u0395\u03b2\u03c1\u03b1\u03ca\u03ba\u03ac"; case "hr": return "\u039a\u03c1\u03bf\u03b1\u03c4\u03b9\u03ba\u03ac"; case "hu": return "\u039f\u03c5\u03b3\u03b3\u03c1\u03b9\u03ba\u03ac"; case "it": return "\u0399\u03c4\u03b1\u03bb\u03b9\u03ba\u03ac"; case "mk": return "\u03a3\u03bb\u03b1\u03b2\u03bf\u03bc\u03b1\u03ba\u03b5\u03b4\u03bf\u03bd\u03b9\u03ba\u03ac"; case "nl": return "\u039f\u03bb\u03bb\u03b1\u03bd\u03b4\u03b9\u03ba\u03ac"; case "no": return "\u039d\u03bf\u03c1\u03b2\u03b7\u03b3\u03b9\u03ba\u03ac"; case "pl": return "\u03a0\u03bf\u03bb\u03c9\u03bd\u03b9\u03ba\u03ac"; case "pt": return "\u03a0\u03bf\u03c1\u03c4\u03bf\u03b3\u03b1\u03bb\u03b9\u03ba\u03ac"; case "ro": return "\u03a1\u03bf\u03c5\u03bc\u03b1\u03bd\u03b9\u03ba\u03ac"; case "ru": return "\u03a1\u03c9\u03c3\u03b9\u03ba\u03ac"; case "sk": return "\u03a3\u03bb\u03bf\u03b2\u03b1\u03ba\u03b9\u03ba\u03ac"; case "sl": return "\u03a3\u03bb\u03bf\u03b2\u03b5\u03bd\u03b9\u03ba\u03ac"; case "sq": return "\u0391\u03bb\u03b2\u03b1\u03bd\u03b9\u03ba\u03ac"; case "sr": return "\u03a3\u03b5\u03c1\u03b2\u03b9\u03ba\u03ac"; case "sv": return "\u03a3\u03bf\u03c5\u03b7\u03b4\u03b9\u03ba\u03ac"; } return base.ResolveLanguage(name); } public override String ResolveCountry(String name) { switch(name) { case "AL": return "\u0391\u03bb\u03b2\u03b1\u03bd\u03af\u03b1"; case "AS": return "\u0391\u03c3\u03af\u03b1 (\u0391\u03b3\u03b3\u03bb\u03b9\u03ba\u03ac)"; case "AT": return "\u0391\u03c5\u03c3\u03c4\u03c1\u03af\u03b1"; case "AU": return "\u0391\u03c5\u03c3\u03c4\u03c1\u03b1\u03bb\u03af\u03b1 (\u0391\u03b3\u03b3\u03bb\u03b9\u03ba\u03ac)"; case "BA": return "\u0392\u03bf\u03c3\u03bd\u03af\u03b1"; case "BE": return "\u0392\u03ad\u03bb\u03b3\u03b9\u03bf"; case "BG": return "\u0392\u03bf\u03c5\u03bb\u03b3\u03b1\u03c1\u03af\u03b1"; case "BR": return "\u0392\u03c1\u03b1\u03b6\u03b9\u03bb\u03af\u03b1"; case "CA": return "\u039a\u03b1\u03bd\u03b1\u03b4\u03ac\u03c2"; case "CH": return "\u0395\u03bb\u03b2\u03b5\u03c4\u03af\u03b1"; case "CN": return "\u039a\u03af\u03bd\u03b1 (\u039b.\u0394.\u039a.)"; case "CZ": return "\u03a4\u03c3\u03b5\u03c7\u03af\u03b1"; case "DE": return "\u0393\u03b5\u03c1\u03bc\u03b1\u03bd\u03af\u03b1"; case "DK": return "\u0394\u03b1\u03bd\u03af\u03b1"; case "EE": return "\u0395\u03c3\u03b8\u03bf\u03bd\u03af\u03b1"; case "ES": return "\u0399\u03c3\u03c0\u03b1\u03bd\u03af\u03b1"; case "FI": return "\u03a6\u03b9\u03bd\u03bb\u03b1\u03bd\u03b4\u03af\u03b1"; case "FR": return "\u0393\u03b1\u03bb\u03bb\u03af\u03b1"; case "GB": return "\u0397\u03bd\u03c9\u03bc\u03ad\u03bd\u03bf \u0392\u03b1\u03c3\u03af\u03bb\u03b5\u03b9\u03bf"; case "GR": return "\u0395\u03bb\u03bb\u03ac\u03b4\u03b1"; case "HR": return "\u039a\u03c1\u03bf\u03b1\u03c4\u03af\u03b1"; case "HU": return "\u039f\u03c5\u03b3\u03b3\u03b1\u03c1\u03af\u03b1"; case "IE": return "\u0399\u03c1\u03bb\u03b1\u03bd\u03b4\u03af\u03b1"; case "IL": return "\u0399\u03c3\u03c1\u03b1\u03ae\u03bb"; case "IS": return "\u0399\u03c3\u03bb\u03b1\u03bd\u03b4\u03af\u03b1"; case "IT": return "\u0399\u03c4\u03b1\u03bb\u03af\u03b1"; case "JP": return "\u0399\u03b1\u03c0\u03c9\u03bd\u03af\u03b1"; case "KR": return "\u039a\u03bf\u03c1\u03ad\u03b1"; case "LA": return "\u039b\u03b1\u03c4\u03b9\u03bd\u03b9\u03ba\u03ae \u0391\u03bc\u03b5\u03c1\u03b9\u03ba\u03ae"; case "LT": return "\u039b\u03b9\u03b8\u03bf\u03c5\u03b1\u03bd\u03af\u03b1"; case "LV": return "\u039b\u03b5\u03c4\u03bf\u03bd\u03af\u03b1"; case "MK": return "\u03a0\u0393\u0394 \u039c\u03b1\u03ba\u03b5\u03b4\u03bf\u03bd\u03af\u03b1\u03c2"; case "NL": return "\u039f\u03bb\u03bb\u03b1\u03bd\u03b4\u03af\u03b1"; case "NO": return "\u039d\u03bf\u03c1\u03b2\u03b7\u03b3\u03af\u03b1"; case "NZ": return "\u039d\u03ad\u03b1 \u0396\u03b7\u03bb\u03b1\u03bd\u03b4\u03af\u03b1"; case "PL": return "\u03a0\u03bf\u03bb\u03c9\u03bd\u03af\u03b1"; case "PT": return "\u03a0\u03bf\u03c1\u03c4\u03bf\u03b3\u03b1\u03bb\u03af\u03b1"; case "RO": return "\u03a1\u03bf\u03c5\u03bc\u03b1\u03bd\u03af\u03b1"; case "RU": return "\u03a1\u03c9\u03c3\u03af\u03b1"; case "SE": return "\u03a3\u03bf\u03c5\u03b7\u03b4\u03af\u03b1"; case "SI": return "\u03a3\u03bb\u03bf\u03b2\u03b5\u03bd\u03af\u03b1"; case "SK": return "\u03a3\u03bb\u03bf\u03b2\u03b1\u03ba\u03af\u03b1"; case "SP": return "\u03a3\u03b5\u03c1\u03b2\u03af\u03b1"; case "TH": return "\u03a4\u03b1\u03ca\u03bb\u03ac\u03bd\u03b4\u03b7"; case "TR": return "\u03a4\u03bf\u03c5\u03c1\u03ba\u03af\u03b1"; case "TW": return "\u03a4\u03b1\u03ca\u03b2\u03ac\u03bd (\u0394.\u039a.)"; case "US": return "\u0397\u03bd\u03c9\u03bc\u03ad\u03bd\u03b5\u03c2 \u03a0\u03bf\u03bb\u03b9\u03c4\u03b5\u03af\u03b5\u03c2 \u0391\u03bc\u03b5\u03c1\u03b9\u03ba\u03ae\u03c2"; case "ZA": return "\u039d\u03cc\u03c4\u03b9\u03bf\u03c2 \u0391\u03c6\u03c1\u03b9\u03ba\u03ae"; } return base.ResolveCountry(name); } private class PrivateTextInfo : _I18NTextInfo { public PrivateTextInfo(int culture) : base(culture) {} public override int ANSICodePage { get { return 1253; } } public override int EBCDICCodePage { get { return 20273; } } public override int MacCodePage { get { return 10006; } } public override int OEMCodePage { get { return 737; } } public override String ListSeparator { get { return ";"; } } }; // class PrivateTextInfo public override TextInfo TextInfo { get { return new PrivateTextInfo(LCID); } } }; // class CID0008 public class CNel : CID0008 { public CNel() : base() {} }; // class CNel }; // namespace I18N.West
using System.Collections; using UnityEngine; namespace Xft { public class EffectLayer : MonoBehaviour { public EffectNode[] ActiveENodes; public bool AlongVelocity; public int AngleAroundAxis; public bool AttractionAffectorEnable; public AnimationCurve AttractionCurve; public Vector3 AttractionPosition; public float AttractMag = 0.1f; public EffectNode[] AvailableENodes; public int AvailableNodeCount; public Vector3 BoxSize; public float ChanceToEmit = 100f; public Vector3 CircleDir; public Transform ClientTransform; public Color Color1 = Color.white; public Color Color2; public Color Color3; public Color Color4; public bool ColorAffectorEnable; public int ColorAffectType; public float ColorGradualTimeLength = 1f; public ColorGradualType ColorGradualType; public int Cols = 1; public float DeltaRot; public float DeltaScaleX; public float DeltaScaleY; public float DiffDistance = 0.1f; public int EanIndex; public string EanPath = "none"; public float EmitDelay; public float EmitDuration = 10f; public int EmitLoop = 1; public Vector3 EmitPoint; public int EmitRate = 20; protected Emitter emitter; public int EmitType; public bool IsEmitByDistance; public bool IsNodeLifeLoop = true; public bool IsRandomDir; public bool JetAffectorEnable; public float JetMax; public float JetMin; public Vector3 LastClientPos; public Vector3 LinearForce; public bool LinearForceAffectorEnable; public float LinearMagnitude = 1f; public float LineLengthLeft = -1f; public float LineLengthRight = 1f; public int LoopCircles = -1; protected Camera MainCamera; public Material Material; public int MaxENodes = 1; public float MaxFps = 60f; public int MaxRibbonElements = 6; public float NodeLifeMax = 1f; public float NodeLifeMin = 1f; public Vector2 OriLowerLeftUV = Vector2.zero; public int OriPoint; public int OriRotationMax; public int OriRotationMin; public float OriScaleXMax = 1f; public float OriScaleXMin = 1f; public float OriScaleYMax = 1f; public float OriScaleYMin = 1f; public float OriSpeed; public Vector2 OriUVDimensions = Vector2.one; public Vector3 OriVelocityAxis; public float Radius; public bool RandomOriRot; public bool RandomOriScale; public int RenderType; public float RibbonLen = 1f; public float RibbonWidth = 0.5f; public bool RotAffectorEnable; public AnimationCurve RotateCurve; public RSTYPE RotateType; public int Rows = 1; public bool ScaleAffectorEnable; public RSTYPE ScaleType; public AnimationCurve ScaleXCurve; public AnimationCurve ScaleYCurve; public float SpriteHeight = 1f; public int SpriteType; public int SpriteUVStretch; public float SpriteWidth = 1f; public float StartTime; public int StretchType; public bool SyncClient; public float TailDistance; public bool UseAttractCurve; public bool UseVortexCurve; public bool UVAffectorEnable; public float UVTime = 30f; public int UVType; public VertexPool Vertexpool; public bool VortexAffectorEnable; public AnimationCurve VortexCurve; public Vector3 VortexDirection; public float VortexMag = 0.1f; public void AddActiveNode(EffectNode node) { if (this.AvailableNodeCount == 0) { Debug.LogError("out index!"); } if (this.AvailableENodes[node.Index] != null) { this.ActiveENodes[node.Index] = node; this.AvailableENodes[node.Index] = null; this.AvailableNodeCount--; } } protected void AddNodes(int num) { int num2 = 0; for (int i = 0; i < this.MaxENodes; i++) { if (num2 == num) { break; } EffectNode node = this.AvailableENodes[i]; if (node != null) { this.AddActiveNode(node); num2++; this.emitter.SetEmitPosition(node); float life = 0f; if (this.IsNodeLifeLoop) { life = -1f; } else { life = Random.Range(this.NodeLifeMin, this.NodeLifeMax); } Vector3 emitRotation = this.emitter.GetEmitRotation(node); node.Init(emitRotation.normalized, this.OriSpeed, life, Random.Range(this.OriRotationMin, this.OriRotationMax), Random.Range(this.OriScaleXMin, this.OriScaleXMax), Random.Range(this.OriScaleYMin, this.OriScaleYMax), this.Color1, this.OriLowerLeftUV, this.OriUVDimensions); } } } public void FixedUpdateCustom() { int nodes = this.emitter.GetNodes(); this.AddNodes(nodes); for (int i = 0; i < this.MaxENodes; i++) { EffectNode node = this.ActiveENodes[i]; if (node != null) { node.Update(); } } } public RibbonTrail GetRibbonTrail() { if (!((this.ActiveENodes == null) | (this.ActiveENodes.Length != 1)) && this.MaxENodes == 1 && this.RenderType == 1) { return this.ActiveENodes[0].Ribbon; } return null; } public VertexPool GetVertexPool() { return this.Vertexpool; } protected void Init() { this.AvailableENodes = new EffectNode[this.MaxENodes]; this.ActiveENodes = new EffectNode[this.MaxENodes]; for (int i = 0; i < this.MaxENodes; i++) { EffectNode node = new EffectNode(i, this.ClientTransform, this.SyncClient, this); ArrayList afts = this.InitAffectors(node); node.SetAffectorList(afts); if (this.RenderType == 0) { node.SetType(this.SpriteWidth, this.SpriteHeight, (Style) this.SpriteType, (ORIPOINT) this.OriPoint, this.SpriteUVStretch, this.MaxFps); } else { node.SetType(this.RibbonWidth, this.MaxRibbonElements, this.RibbonLen, this.ClientTransform.position, this.StretchType, this.MaxFps); } this.AvailableENodes[i] = node; } this.AvailableNodeCount = this.MaxENodes; this.emitter = new Emitter(this); } protected ArrayList InitAffectors(EffectNode node) { ArrayList list = new ArrayList(); if (this.UVAffectorEnable) { UVAnimation frame = new UVAnimation(); Texture mainTex = this.Vertexpool.GetMaterial().GetTexture("_MainTex"); if (this.UVType == 2) { frame.BuildFromFile(this.EanPath, this.EanIndex, this.UVTime, mainTex); this.OriLowerLeftUV = frame.frames[0]; this.OriUVDimensions = frame.UVDimensions[0]; } else if (this.UVType == 1) { float num = mainTex.width / this.Cols; float num2 = mainTex.height / this.Rows; Vector2 cellSize = new Vector2(num / mainTex.width, num2 / mainTex.height); Vector2 start = new Vector2(0f, 1f); frame.BuildUVAnim(start, cellSize, this.Cols, this.Rows, this.Cols * this.Rows); this.OriLowerLeftUV = start; this.OriUVDimensions = cellSize; this.OriUVDimensions.y = -this.OriUVDimensions.y; } if (frame.frames.Length == 1) { this.OriLowerLeftUV = frame.frames[0]; this.OriUVDimensions = frame.UVDimensions[0]; } else { frame.loopCycles = this.LoopCircles; Affector affector = new UVAffector(frame, this.UVTime, node); list.Add(affector); } } if (this.RotAffectorEnable && this.RotateType != RSTYPE.NONE) { Affector affector2; if (this.RotateType == RSTYPE.CURVE) { affector2 = new RotateAffector(this.RotateCurve, node); } else { affector2 = new RotateAffector(this.DeltaRot, node); } list.Add(affector2); } if (this.ScaleAffectorEnable && this.ScaleType != RSTYPE.NONE) { Affector affector3; if (this.ScaleType == RSTYPE.CURVE) { affector3 = new ScaleAffector(this.ScaleXCurve, this.ScaleYCurve, node); } else { affector3 = new ScaleAffector(this.DeltaScaleX, this.DeltaScaleY, node); } list.Add(affector3); } if (this.ColorAffectorEnable && this.ColorAffectType != 0) { ColorAffector affector4; if (this.ColorAffectType == 2) { Color[] colorArr = new Color[] { this.Color1, this.Color2, this.Color3, this.Color4 }; affector4 = new ColorAffector(colorArr, this.ColorGradualTimeLength, this.ColorGradualType, node); } else { Color[] colorArray2 = new Color[] { this.Color1, this.Color2 }; affector4 = new ColorAffector(colorArray2, this.ColorGradualTimeLength, this.ColorGradualType, node); } list.Add(affector4); } if (this.LinearForceAffectorEnable) { Affector affector5 = new LinearForceAffector(this.LinearForce.normalized * this.LinearMagnitude, node); list.Add(affector5); } if (this.JetAffectorEnable) { Affector affector6 = new JetAffector(this.JetMin, this.JetMax, node); list.Add(affector6); } if (this.VortexAffectorEnable) { Affector affector7; if (this.UseVortexCurve) { affector7 = new VortexAffector(this.VortexCurve, this.VortexDirection, node); } else { affector7 = new VortexAffector(this.VortexMag, this.VortexDirection, node); } list.Add(affector7); } if (this.AttractionAffectorEnable) { Affector affector8; if (this.UseVortexCurve) { affector8 = new AttractionForceAffector(this.AttractionCurve, this.AttractionPosition, node); } else { affector8 = new AttractionForceAffector(this.AttractMag, this.AttractionPosition, node); } list.Add(affector8); } return list; } private void OnDrawGizmosSelected() { } public void RemoveActiveNode(EffectNode node) { if (this.AvailableNodeCount == this.MaxENodes) { Debug.LogError("out index!"); } if (this.ActiveENodes[node.Index] != null) { this.ActiveENodes[node.Index] = null; this.AvailableENodes[node.Index] = node; this.AvailableNodeCount++; } } public void Reset() { for (int i = 0; i < this.MaxENodes; i++) { if (this.ActiveENodes == null) { return; } EffectNode node = this.ActiveENodes[i]; if (node != null) { node.Reset(); this.RemoveActiveNode(node); } } this.emitter.Reset(); } public void StartCustom() { if (this.MainCamera == null) { this.MainCamera = Camera.main; } this.Init(); this.LastClientPos = this.ClientTransform.position; } } }
//------------------------------------------------------------------------------ // Microsoft Avalon // Copyright (c) Microsoft Corporation. All Rights Reserved. // // File: CachedBitmap.cs // //------------------------------------------------------------------------------ using System; using System.IO; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Reflection; using MS.Internal; using MS.Win32.PresentationCore; using System.Security; using System.Security.Permissions; using System.Diagnostics; using System.Windows.Media; using System.Globalization; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Media.Animation; using System.Windows.Media.Composition; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; namespace System.Windows.Media.Imaging { #region CachedBitmap /// <summary> /// CachedBitmap provides caching functionality for a BitmapSource. /// </summary> public sealed class CachedBitmap : System.Windows.Media.Imaging.BitmapSource { /// <summary> /// Construct a CachedBitmap /// </summary> /// <param name="source">BitmapSource to apply to the crop to</param> /// <param name="createOptions">CreateOptions for the new Bitmap</param> /// <param name="cacheOption">CacheOption for the new Bitmap</param> public CachedBitmap(BitmapSource source, BitmapCreateOptions createOptions, BitmapCacheOption cacheOption) : base(true) // Use base class virtuals { if (source == null) { throw new ArgumentNullException("source"); } BeginInit(); _source = source; RegisterDownloadEventSource(_source); _createOptions = createOptions; _cacheOption = cacheOption; _syncObject = source.SyncObject; EndInit(); } /// <summary> /// </summary> /// <SecurityNote> /// Critical - access critical code, accepts pointer arguments /// </SecurityNote> [SecurityCritical] unsafe internal CachedBitmap( int pixelWidth, int pixelHeight, double dpiX, double dpiY, PixelFormat pixelFormat, BitmapPalette palette, IntPtr buffer, int bufferSize, int stride ) : base(true) // Use base class virtuals { InitFromMemoryPtr(pixelWidth, pixelHeight, dpiX, dpiY, pixelFormat, palette, buffer, bufferSize, stride); } /// <summary> /// Creates a managed BitmapSource wrapper around a pre-existing /// unmanaged bitmap. /// </summary> /// <SecurityNote> /// Critical - access critical code, accepts pointer /// </SecurityNote> [SecurityCritical] internal CachedBitmap(BitmapSourceSafeMILHandle bitmap) : base(true) { if (bitmap == null) { throw new ArgumentNullException("bitmap"); } // We're not calling CachedBitmap.Begin/EndInit because that would // invoke FinalizeCreation which calls CreateCachedBitmap that does // unnecessary work and only deals with BitmapFrames _bitmapInit.BeginInit(); _source = null; _createOptions = BitmapCreateOptions.None; _cacheOption = BitmapCacheOption.OnLoad; // // This constructor is used by D3DImage, which does not calculate memory pressure for // the bitmap parameter before calling the constructor. // bitmap.CalculateSize(); // This will QI to IWICBitmapSource for us. QI also AddRefs, of course. WicSourceHandle = bitmap; _syncObject = WicSourceHandle; IsSourceCached = true; CreationCompleted = true; _bitmapInit.EndInit(); } /// <summary> /// Create an Empty CachedBitap /// </summary> private CachedBitmap() : base(true) // Use base class virtuals { } /// <summary> /// </summary> /// <SecurityNote> /// Critical - calls unmanaged objects /// TreatAsSafe - all inputs verified, including buffer sizes /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] unsafe internal CachedBitmap( int pixelWidth, int pixelHeight, double dpiX, double dpiY, PixelFormat pixelFormat, BitmapPalette palette, System.Array pixels, int stride ) : base(true) // Use base class virtuals { if (pixels == null) throw new System.ArgumentNullException ("pixels"); if (pixels.Rank != 1) throw new ArgumentException (SR.Get (SRID.Collection_BadRank), "pixels"); int elementSize = -1; if (pixels is byte[]) elementSize = 1; else if (pixels is short[] || pixels is ushort[]) elementSize = 2; else if (pixels is int[] || pixels is uint[] || pixels is float[]) elementSize = 4; else if (pixels is double[]) elementSize = 8; if (elementSize == -1) throw new ArgumentException(SR.Get(SRID.Image_InvalidArrayForPixel)); int destBufferSize = elementSize * pixels.Length; if (pixels is byte[]) { fixed(void * pixelArray = (byte[])pixels) InitFromMemoryPtr(pixelWidth, pixelHeight, dpiX, dpiY, pixelFormat, palette, (IntPtr)pixelArray, destBufferSize, stride); } else if (pixels is short[]) { fixed(void * pixelArray = (short[])pixels) InitFromMemoryPtr(pixelWidth, pixelHeight, dpiX, dpiY, pixelFormat, palette, (IntPtr)pixelArray, destBufferSize, stride); } else if (pixels is ushort[]) { fixed(void * pixelArray = (ushort[])pixels) InitFromMemoryPtr(pixelWidth, pixelHeight, dpiX, dpiY, pixelFormat, palette, (IntPtr)pixelArray, destBufferSize, stride); } else if (pixels is int[]) { fixed(void * pixelArray = (int[])pixels) InitFromMemoryPtr(pixelWidth, pixelHeight, dpiX, dpiY, pixelFormat, palette, (IntPtr)pixelArray, destBufferSize, stride); } else if (pixels is uint[]) { fixed(void * pixelArray = (uint[])pixels) InitFromMemoryPtr(pixelWidth, pixelHeight, dpiX, dpiY, pixelFormat, palette, (IntPtr)pixelArray, destBufferSize, stride); } else if (pixels is float[]) { fixed(void * pixelArray = (float[])pixels) InitFromMemoryPtr(pixelWidth, pixelHeight, dpiX, dpiY, pixelFormat, palette, (IntPtr)pixelArray, destBufferSize, stride); } else if (pixels is double[]) { fixed(void * pixelArray = (double[])pixels) InitFromMemoryPtr(pixelWidth, pixelHeight, dpiX, dpiY, pixelFormat, palette, (IntPtr)pixelArray, destBufferSize, stride); } } /// <summary> /// Common implementation for CloneCore(), CloneCurrentValueCore(), /// GetAsFrozenCore(), and GetCurrentValueAsFrozenCore(). /// </summary> /// <SecurityNote> /// Critical - calls critical InitFromWICSource /// </SecurityNote> [SecurityCritical] private void CopyCommon(CachedBitmap sourceBitmap) { // Avoid Animatable requesting resource updates for invalidations that occur during construction Animatable_IsResourceInvalidationNecessary = false; if (sourceBitmap._source != null) { BeginInit(); _syncObject = sourceBitmap._syncObject; _source = sourceBitmap._source; RegisterDownloadEventSource(_source); _createOptions = sourceBitmap._createOptions; _cacheOption = sourceBitmap._cacheOption; // if (_cacheOption == BitmapCacheOption.OnDemand) _cacheOption = BitmapCacheOption.OnLoad; EndInit(); } else { InitFromWICSource(sourceBitmap.WicSourceHandle); } // The next invalidation will cause Animatable to register an UpdateResource callback Animatable_IsResourceInvalidationNecessary = true; } // ISupportInitialize /// <summary> /// Prepare the bitmap to accept initialize paramters. /// </summary> private void BeginInit() { _bitmapInit.BeginInit(); } /// <summary> /// Prepare the bitmap to accept initialize paramters. /// </summary> /// <SecurityNote> /// Critical - access critical resources /// TreatAsSafe - All inputs verified /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] private void EndInit() { _bitmapInit.EndInit(); // if we don't need to delay, let 'er rip if (!DelayCreation) FinalizeCreation(); } /// /// Create the unmanaged resources /// /// <SecurityNote> /// Critical - access critical resource /// </SecurityNote> [SecurityCritical] internal override void FinalizeCreation() { lock (_syncObject) { WicSourceHandle = CreateCachedBitmap(_source as BitmapFrame, _source.WicSourceHandle, _createOptions, _cacheOption, _source.Palette); } IsSourceCached = (_cacheOption != BitmapCacheOption.None); CreationCompleted = true; UpdateCachedSettings(); } #region Public Methods /// <summary> /// Shadows inherited Copy() with a strongly typed /// version for convenience. /// </summary> public new CachedBitmap Clone() { return (CachedBitmap)base.Clone(); } /// <summary> /// Shadows inherited CloneCurrentValue() with a /// strongly typed version for convenience. /// </summary> public new CachedBitmap CloneCurrentValue() { return (CachedBitmap)base.CloneCurrentValue(); } #endregion Public Methods //------------------------------------------------------ // // Protected Methods // //------------------------------------------------------ #region Protected Methods /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>. /// </summary> /// <returns>The new Freezable.</returns> /// <SecurityNote> /// Critical - accesses critical code. /// TreatAsSafe - method only produces clone of original image. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] protected override Freezable CreateInstanceCore() { return new CachedBitmap(); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CloneCore(Freezable)">Freezable.CloneCore</see>. /// </summary> /// <SecurityNote> /// Critical - accesses critical code. /// TreatAsSafe - method only produces clone of original image. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] protected override void CloneCore(Freezable sourceFreezable) { CachedBitmap sourceBitmap = (CachedBitmap) sourceFreezable; base.CloneCore(sourceFreezable); CopyCommon(sourceBitmap); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CloneCurrentValueCore(Freezable)">Freezable.CloneCurrentValueCore</see>. /// </summary> /// <SecurityNote> /// Critical - accesses critical code. /// TreatAsSafe - method only produces clone of original image. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] protected override void CloneCurrentValueCore(Freezable sourceFreezable) { CachedBitmap sourceBitmap = (CachedBitmap) sourceFreezable; base.CloneCurrentValueCore(sourceFreezable); CopyCommon(sourceBitmap); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.GetAsFrozenCore(Freezable)">Freezable.GetAsFrozenCore</see>. /// </summary> /// <SecurityNote> /// Critical - accesses critical code. /// TreatAsSafe - method only produces GetAsFrozen of original image. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] protected override void GetAsFrozenCore(Freezable sourceFreezable) { CachedBitmap sourceBitmap = (CachedBitmap)sourceFreezable; base.GetAsFrozenCore(sourceFreezable); CopyCommon(sourceBitmap); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.GetCurrentValueAsFrozenCore(Freezable)">Freezable.GetCurrentValueAsFrozenCore</see>. /// </summary> /// <SecurityNote> /// Critical - accesses critical code. /// TreatAsSafe - method only produces GetCurrentValueAsFrozen of original image. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] protected override void GetCurrentValueAsFrozenCore(Freezable sourceFreezable) { CachedBitmap sourceBitmap = (CachedBitmap)sourceFreezable; base.GetCurrentValueAsFrozenCore(sourceFreezable); CopyCommon(sourceBitmap); } #endregion ProtectedMethods /// /// Create from WICBitmapSource /// /// <SecurityNote> /// Critical - calls unmanaged objects /// </SecurityNote> [SecurityCritical] private void InitFromWICSource( SafeMILHandle wicSource ) { _bitmapInit.BeginInit(); BitmapSourceSafeMILHandle bitmapSource = null; lock (_syncObject) { using (FactoryMaker factoryMaker = new FactoryMaker()) { HRESULT.Check(UnsafeNativeMethods.WICImagingFactory.CreateBitmapFromSource( factoryMaker.ImagingFactoryPtr, wicSource, WICBitmapCreateCacheOptions.WICBitmapCacheOnLoad, out bitmapSource)); } bitmapSource.CalculateSize(); } WicSourceHandle = bitmapSource; _isSourceCached = true; _bitmapInit.EndInit(); UpdateCachedSettings(); } /// /// Create from memory /// /// <SecurityNote> /// Critical - calls unmanaged objects, accepts pointer parameters /// </SecurityNote> [SecurityCritical] private void InitFromMemoryPtr( int pixelWidth, int pixelHeight, double dpiX, double dpiY, PixelFormat pixelFormat, BitmapPalette palette, IntPtr buffer, int bufferSize, int stride ) { if (pixelFormat.Palettized == true && palette == null) throw new InvalidOperationException(SR.Get(SRID.Image_IndexedPixelFormatRequiresPalette)); if (pixelFormat.Format == PixelFormatEnum.Default && pixelFormat.Guid == WICPixelFormatGUIDs.WICPixelFormatDontCare) { throw new System.ArgumentException( SR.Get(SRID.Effect_PixelFormat, pixelFormat), "pixelFormat" ); } _bitmapInit.BeginInit(); try { BitmapSourceSafeMILHandle wicBitmap; // Create the unmanaged resources Guid guidFmt = pixelFormat.Guid; using (FactoryMaker factoryMaker = new FactoryMaker()) { HRESULT.Check(UnsafeNativeMethods.WICImagingFactory.CreateBitmapFromMemory( factoryMaker.ImagingFactoryPtr, (uint)pixelWidth, (uint)pixelHeight, ref guidFmt, (uint)stride, (uint)bufferSize, buffer, out wicBitmap)); wicBitmap.CalculateSize(); } HRESULT.Check(UnsafeNativeMethods.WICBitmap.SetResolution( wicBitmap, dpiX, dpiY)); if (pixelFormat.Palettized) { HRESULT.Check(UnsafeNativeMethods.WICBitmap.SetPalette( wicBitmap, palette.InternalPalette)); } WicSourceHandle = wicBitmap; _isSourceCached = true; } catch { _bitmapInit.Reset(); throw; } _createOptions = BitmapCreateOptions.PreservePixelFormat; _cacheOption = BitmapCacheOption.OnLoad; _syncObject = WicSourceHandle; _bitmapInit.EndInit(); UpdateCachedSettings(); } BitmapSource _source; BitmapCreateOptions _createOptions = BitmapCreateOptions.None; BitmapCacheOption _cacheOption = BitmapCacheOption.Default; } #endregion // CachedBitmap }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Web; using System.Web.Mvc; using System.Web.Mvc.Html; using System.Web.Routing; using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Core.Dynamics; using Umbraco.Core.IO; using Umbraco.Core.Profiling; using Umbraco.Web.Mvc; using umbraco; using umbraco.cms.businesslogic.member; namespace Umbraco.Web { /// <summary> /// HtmlHelper extensions for use in templates /// </summary> public static class HtmlHelperRenderExtensions { /// <summary> /// Renders the markup for the profiler /// </summary> /// <param name="helper"></param> /// <returns></returns> public static IHtmlString RenderProfiler(this HtmlHelper helper) { return new HtmlString(ProfilerResolver.Current.Profiler.Render()); } /// <summary> /// Renders a partial view that is found in the specified area /// </summary> /// <param name="helper"></param> /// <param name="partial"></param> /// <param name="area"></param> /// <param name="model"></param> /// <param name="viewData"></param> /// <returns></returns> public static MvcHtmlString AreaPartial(this HtmlHelper helper, string partial, string area, object model = null, ViewDataDictionary viewData = null) { var originalArea = helper.ViewContext.RouteData.DataTokens["area"]; helper.ViewContext.RouteData.DataTokens["area"] = area; var result = helper.Partial(partial, model, viewData); helper.ViewContext.RouteData.DataTokens["area"] = originalArea; return result; } /// <summary> /// Will render the preview badge when in preview mode which is not required ever unless the MVC page you are /// using does not inherit from UmbracoTemplatePage /// </summary> /// <param name="helper"></param> /// <returns></returns> /// <remarks> /// See: http://issues.umbraco.org/issue/U4-1614 /// </remarks> public static MvcHtmlString PreviewBadge(this HtmlHelper helper) { if (UmbracoContext.Current.InPreviewMode) { var htmlBadge = String.Format(UmbracoConfig.For.UmbracoSettings().Content.PreviewBadge, IOHelper.ResolveUrl(SystemDirectories.Umbraco), IOHelper.ResolveUrl(SystemDirectories.UmbracoClient), UmbracoContext.Current.HttpContext.Server.UrlEncode(UmbracoContext.Current.HttpContext.Request.Path)); return new MvcHtmlString(htmlBadge); } return new MvcHtmlString(""); } public static IHtmlString CachedPartial( this HtmlHelper htmlHelper, string partialViewName, object model, int cachedSeconds, bool cacheByPage = false, bool cacheByMember = false, ViewDataDictionary viewData = null, Func<object, ViewDataDictionary, string> contextualKeyBuilder = null) { var cacheKey = new StringBuilder(partialViewName); if (cacheByPage) { if (UmbracoContext.Current == null) { throw new InvalidOperationException("Cannot cache by page if the UmbracoContext has not been initialized, this parameter can only be used in the context of an Umbraco request"); } cacheKey.AppendFormat("{0}-", UmbracoContext.Current.PageId); } if (cacheByMember) { var currentMember = Member.GetCurrentMember(); cacheKey.AppendFormat("m{0}-", currentMember == null ? 0 : currentMember.Id); } if (contextualKeyBuilder != null) { var contextualKey = contextualKeyBuilder(model, viewData); cacheKey.AppendFormat("c{0}-", contextualKey); } return ApplicationContext.Current.ApplicationCache.CachedPartialView(htmlHelper, partialViewName, model, cachedSeconds, cacheKey.ToString(), viewData); } public static MvcHtmlString EditorFor<T>(this HtmlHelper htmlHelper, string templateName = "", string htmlFieldName = "", object additionalViewData = null) where T : new() { var model = new T(); var typedHelper = new HtmlHelper<T>( htmlHelper.ViewContext.CopyWithModel(model), htmlHelper.ViewDataContainer.CopyWithModel(model)); return typedHelper.EditorFor(x => model, templateName, htmlFieldName, additionalViewData); } /// <summary> /// A validation summary that lets you pass in a prefix so that the summary only displays for elements /// containing the prefix. This allows you to have more than on validation summary on a page. /// </summary> /// <param name="htmlHelper"></param> /// <param name="prefix"></param> /// <param name="excludePropertyErrors"></param> /// <param name="message"></param> /// <param name="htmlAttributes"></param> /// <returns></returns> public static MvcHtmlString ValidationSummary(this HtmlHelper htmlHelper, string prefix = "", bool excludePropertyErrors = false, string message = "", IDictionary<string, object> htmlAttributes = null) { if (prefix.IsNullOrWhiteSpace()) { return htmlHelper.ValidationSummary(excludePropertyErrors, message, htmlAttributes); } //if there's a prefix applied, we need to create a new html helper with a filtered ModelState collection so that it only looks for //specific model state with the prefix. var filteredHtmlHelper = new HtmlHelper(htmlHelper.ViewContext, htmlHelper.ViewDataContainer.FilterContainer(prefix)); return filteredHtmlHelper.ValidationSummary(excludePropertyErrors, message, htmlAttributes); } /// <summary> /// Returns the result of a child action of a strongly typed SurfaceController /// </summary> /// <typeparam name="T"></typeparam> /// <param name="htmlHelper"></param> /// <param name="actionName"></param> /// <returns></returns> public static IHtmlString Action<T>(this HtmlHelper htmlHelper, string actionName) where T : SurfaceController { return htmlHelper.Action(actionName, typeof(T)); } /// <summary> /// Returns the result of a child action of a SurfaceController /// </summary> /// <typeparam name="T"></typeparam> /// <param name="htmlHelper"></param> /// <param name="actionName"></param> /// <param name="surfaceType"></param> /// <returns></returns> public static IHtmlString Action(this HtmlHelper htmlHelper, string actionName, Type surfaceType) { Mandate.ParameterNotNull(surfaceType, "surfaceType"); Mandate.ParameterNotNullOrEmpty(actionName, "actionName"); var routeVals = new RouteValueDictionary(new {area = ""}); var surfaceController = SurfaceControllerResolver.Current.RegisteredSurfaceControllers .SingleOrDefault(x => x == surfaceType); if (surfaceController == null) throw new InvalidOperationException("Could not find the surface controller of type " + surfaceType.FullName); var metaData = PluginController.GetMetadata(surfaceController); if (!metaData.AreaName.IsNullOrWhiteSpace()) { //set the area to the plugin area if (routeVals.ContainsKey("area")) { routeVals["area"] = metaData.AreaName; } else { routeVals.Add("area", metaData.AreaName); } } return htmlHelper.Action(actionName, metaData.ControllerName, routeVals); } #region BeginUmbracoForm /// <summary> /// Used for rendering out the Form for BeginUmbracoForm /// </summary> internal class UmbracoForm : MvcForm { /// <summary> /// Creates an UmbracoForm /// </summary> /// <param name="viewContext"></param> /// <param name="controllerName"></param> /// <param name="controllerAction"></param> /// <param name="area"></param> /// <param name="method"></param> /// <param name="additionalRouteVals"></param> public UmbracoForm( ViewContext viewContext, string controllerName, string controllerAction, string area, FormMethod method, object additionalRouteVals = null) : base(viewContext) { _viewContext = viewContext; _method = method; _encryptedString = UmbracoHelper.CreateEncryptedRouteString(controllerName, controllerAction, area, additionalRouteVals); } private readonly ViewContext _viewContext; private readonly FormMethod _method; private bool _disposed; private readonly string _encryptedString; protected override void Dispose(bool disposing) { if (this._disposed) return; this._disposed = true; //write out the hidden surface form routes _viewContext.Writer.Write("<input name='ufprt' type='hidden' value='" + _encryptedString + "' />"); base.Dispose(disposing); } } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline against a locally declared controller /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="controllerName"></param> /// <param name="method"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName, FormMethod method) { return html.BeginUmbracoForm(action, controllerName, null, new Dictionary<string, object>(), method); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline against a locally declared controller /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="controllerName"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName) { return html.BeginUmbracoForm(action, controllerName, null, new Dictionary<string, object>()); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline against a locally declared controller /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="controllerName"></param> /// <param name="additionalRouteVals"></param> /// <param name="method"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName, object additionalRouteVals, FormMethod method) { return html.BeginUmbracoForm(action, controllerName, additionalRouteVals, new Dictionary<string, object>(), method); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline against a locally declared controller /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="controllerName"></param> /// <param name="additionalRouteVals"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName, object additionalRouteVals) { return html.BeginUmbracoForm(action, controllerName, additionalRouteVals, new Dictionary<string, object>()); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline against a locally declared controller /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="controllerName"></param> /// <param name="additionalRouteVals"></param> /// <param name="htmlAttributes"></param> /// <param name="method"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName, object additionalRouteVals, object htmlAttributes, FormMethod method) { return html.BeginUmbracoForm(action, controllerName, additionalRouteVals, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes), method); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline against a locally declared controller /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="controllerName"></param> /// <param name="additionalRouteVals"></param> /// <param name="htmlAttributes"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName, object additionalRouteVals, object htmlAttributes) { return html.BeginUmbracoForm(action, controllerName, additionalRouteVals, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline against a locally declared controller /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="controllerName"></param> /// <param name="additionalRouteVals"></param> /// <param name="htmlAttributes"></param> /// <param name="method"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName, object additionalRouteVals, IDictionary<string, object> htmlAttributes, FormMethod method) { Mandate.ParameterNotNullOrEmpty(action, "action"); Mandate.ParameterNotNullOrEmpty(controllerName, "controllerName"); return html.BeginUmbracoForm(action, controllerName, "", additionalRouteVals, htmlAttributes, method); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline against a locally declared controller /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="controllerName"></param> /// <param name="additionalRouteVals"></param> /// <param name="htmlAttributes"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName, object additionalRouteVals, IDictionary<string, object> htmlAttributes) { Mandate.ParameterNotNullOrEmpty(action, "action"); Mandate.ParameterNotNullOrEmpty(controllerName, "controllerName"); return html.BeginUmbracoForm(action, controllerName, "", additionalRouteVals, htmlAttributes); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="surfaceType">The surface controller to route to</param> /// <param name="method"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, Type surfaceType, FormMethod method) { return html.BeginUmbracoForm(action, surfaceType, null, new Dictionary<string, object>(), method); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="surfaceType">The surface controller to route to</param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, Type surfaceType) { return html.BeginUmbracoForm(action, surfaceType, null, new Dictionary<string, object>()); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <typeparam name="T"></typeparam> /// <param name="html"></param> /// <param name="action"></param> /// <param name="method"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm<T>(this HtmlHelper html, string action, FormMethod method) where T : SurfaceController { return html.BeginUmbracoForm(action, typeof(T), method); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <typeparam name="T"></typeparam> /// <param name="html"></param> /// <param name="action"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm<T>(this HtmlHelper html, string action) where T : SurfaceController { return html.BeginUmbracoForm(action, typeof(T)); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="surfaceType">The surface controller to route to</param> /// <param name="additionalRouteVals"></param> /// <param name="method"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, Type surfaceType, object additionalRouteVals, FormMethod method) { return html.BeginUmbracoForm(action, surfaceType, additionalRouteVals, new Dictionary<string, object>(), method); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="surfaceType">The surface controller to route to</param> /// <param name="additionalRouteVals"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, Type surfaceType, object additionalRouteVals) { return html.BeginUmbracoForm(action, surfaceType, additionalRouteVals, new Dictionary<string, object>()); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <typeparam name="T"></typeparam> /// <param name="html"></param> /// <param name="action"></param> /// <param name="additionalRouteVals"></param> /// <param name="method"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm<T>(this HtmlHelper html, string action, object additionalRouteVals, FormMethod method) where T : SurfaceController { return html.BeginUmbracoForm(action, typeof(T), additionalRouteVals, method); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <typeparam name="T"></typeparam> /// <param name="html"></param> /// <param name="action"></param> /// <param name="additionalRouteVals"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm<T>(this HtmlHelper html, string action, object additionalRouteVals) where T : SurfaceController { return html.BeginUmbracoForm(action, typeof(T), additionalRouteVals); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="surfaceType">The surface controller to route to</param> /// <param name="additionalRouteVals"></param> /// <param name="htmlAttributes"></param> /// <param name="method"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, Type surfaceType, object additionalRouteVals, object htmlAttributes, FormMethod method) { return html.BeginUmbracoForm(action, surfaceType, additionalRouteVals, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes), method); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="surfaceType">The surface controller to route to</param> /// <param name="additionalRouteVals"></param> /// <param name="htmlAttributes"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, Type surfaceType, object additionalRouteVals, object htmlAttributes) { return html.BeginUmbracoForm(action, surfaceType, additionalRouteVals, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <typeparam name="T"></typeparam> /// <param name="html"></param> /// <param name="action"></param> /// <param name="additionalRouteVals"></param> /// <param name="htmlAttributes"></param> /// <param name="method"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm<T>(this HtmlHelper html, string action, object additionalRouteVals, object htmlAttributes, FormMethod method) where T : SurfaceController { return html.BeginUmbracoForm(action, typeof(T), additionalRouteVals, htmlAttributes, method); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <typeparam name="T"></typeparam> /// <param name="html"></param> /// <param name="action"></param> /// <param name="additionalRouteVals"></param> /// <param name="htmlAttributes"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm<T>(this HtmlHelper html, string action, object additionalRouteVals, object htmlAttributes) where T : SurfaceController { return html.BeginUmbracoForm(action, typeof(T), additionalRouteVals, htmlAttributes); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="surfaceType">The surface controller to route to</param> /// <param name="additionalRouteVals"></param> /// <param name="htmlAttributes"></param> /// <param name="method"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, Type surfaceType, object additionalRouteVals, IDictionary<string, object> htmlAttributes, FormMethod method) { Mandate.ParameterNotNullOrEmpty(action, "action"); Mandate.ParameterNotNull(surfaceType, "surfaceType"); var area = ""; var surfaceController = SurfaceControllerResolver.Current.RegisteredSurfaceControllers .SingleOrDefault(x => x == surfaceType); if (surfaceController == null) throw new InvalidOperationException("Could not find the surface controller of type " + surfaceType.FullName); var metaData = PluginController.GetMetadata(surfaceController); if (metaData.AreaName.IsNullOrWhiteSpace() == false) { //set the area to the plugin area area = metaData.AreaName; } return html.BeginUmbracoForm(action, metaData.ControllerName, area, additionalRouteVals, htmlAttributes, method); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="surfaceType">The surface controller to route to</param> /// <param name="additionalRouteVals"></param> /// <param name="htmlAttributes"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, Type surfaceType, object additionalRouteVals, IDictionary<string, object> htmlAttributes) { return html.BeginUmbracoForm(action, surfaceType, additionalRouteVals, htmlAttributes, FormMethod.Post); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <typeparam name="T"></typeparam> /// <param name="html"></param> /// <param name="action"></param> /// <param name="additionalRouteVals"></param> /// <param name="htmlAttributes"></param> /// <param name="method"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm<T>(this HtmlHelper html, string action, object additionalRouteVals, IDictionary<string, object> htmlAttributes, FormMethod method) where T : SurfaceController { return html.BeginUmbracoForm(action, typeof(T), additionalRouteVals, htmlAttributes, method); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <typeparam name="T"></typeparam> /// <param name="html"></param> /// <param name="action"></param> /// <param name="additionalRouteVals"></param> /// <param name="htmlAttributes"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm<T>(this HtmlHelper html, string action, object additionalRouteVals, IDictionary<string, object> htmlAttributes) where T : SurfaceController { return html.BeginUmbracoForm(action, typeof(T), additionalRouteVals, htmlAttributes); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="controllerName"></param> /// <param name="area"></param> /// <param name="method"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName, string area, FormMethod method) { return html.BeginUmbracoForm(action, controllerName, area, null, new Dictionary<string, object>(), method); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="controllerName"></param> /// <param name="area"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName, string area) { return html.BeginUmbracoForm(action, controllerName, area, null, new Dictionary<string, object>()); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="controllerName"></param> /// <param name="area"></param> /// <param name="additionalRouteVals"></param> /// <param name="htmlAttributes"></param> /// <param name="method"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName, string area, object additionalRouteVals, IDictionary<string, object> htmlAttributes, FormMethod method) { Mandate.ParameterNotNullOrEmpty(action, "action"); Mandate.ParameterNotNullOrEmpty(controllerName, "controllerName"); var formAction = UmbracoContext.Current.OriginalRequestUrl.PathAndQuery; return html.RenderForm(formAction, method, htmlAttributes, controllerName, action, area, additionalRouteVals); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="controllerName"></param> /// <param name="area"></param> /// <param name="additionalRouteVals"></param> /// <param name="htmlAttributes"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName, string area, object additionalRouteVals, IDictionary<string, object> htmlAttributes) { return html.BeginUmbracoForm(action, controllerName, area, additionalRouteVals, htmlAttributes, FormMethod.Post); } /// <summary> /// This renders out the form for us /// </summary> /// <param name="htmlHelper"></param> /// <param name="formAction"></param> /// <param name="method"></param> /// <param name="htmlAttributes"></param> /// <param name="surfaceController"></param> /// <param name="surfaceAction"></param> /// <param name="area"></param> /// <param name="additionalRouteVals"></param> /// <returns></returns> /// <remarks> /// This code is pretty much the same as the underlying MVC code that writes out the form /// </remarks> private static MvcForm RenderForm(this HtmlHelper htmlHelper, string formAction, FormMethod method, IDictionary<string, object> htmlAttributes, string surfaceController, string surfaceAction, string area, object additionalRouteVals = null) { //ensure that the multipart/form-data is added to the html attributes if (htmlAttributes.ContainsKey("enctype") == false) { htmlAttributes.Add("enctype", "multipart/form-data"); } var tagBuilder = new TagBuilder("form"); tagBuilder.MergeAttributes(htmlAttributes); // action is implicitly generated, so htmlAttributes take precedence. tagBuilder.MergeAttribute("action", formAction); // method is an explicit parameter, so it takes precedence over the htmlAttributes. tagBuilder.MergeAttribute("method", HtmlHelper.GetFormMethodString(method), true); var traditionalJavascriptEnabled = htmlHelper.ViewContext.ClientValidationEnabled && htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled == false; if (traditionalJavascriptEnabled) { // forms must have an ID for client validation tagBuilder.GenerateId("form" + Guid.NewGuid().ToString("N")); } htmlHelper.ViewContext.Writer.Write(tagBuilder.ToString(TagRenderMode.StartTag)); //new UmbracoForm: var theForm = new UmbracoForm(htmlHelper.ViewContext, surfaceController, surfaceAction, area, method, additionalRouteVals); if (traditionalJavascriptEnabled) { htmlHelper.ViewContext.FormContext.FormId = tagBuilder.Attributes["id"]; } return theForm; } #endregion #region Wrap public static HtmlTagWrapper Wrap(this HtmlHelper html, string tag, string innerText, params IHtmlTagWrapper[] children) { var item = html.Wrap(tag, innerText, (object)null); foreach (var child in children) { item.AddChild(child); } return item; } public static HtmlTagWrapper Wrap(this HtmlHelper html, string tag, object inner, object anonymousAttributes, params IHtmlTagWrapper[] children) { string innerText = null; if (inner != null && inner.GetType() != typeof(DynamicNull)) { innerText = string.Format("{0}", inner); } var item = html.Wrap(tag, innerText, anonymousAttributes); foreach (var child in children) { item.AddChild(child); } return item; } public static HtmlTagWrapper Wrap(this HtmlHelper html, string tag, object inner) { string innerText = null; if (inner != null && inner.GetType() != typeof(DynamicNull)) { innerText = string.Format("{0}", inner); } return html.Wrap(tag, innerText, (object)null); } public static HtmlTagWrapper Wrap(this HtmlHelper html, string tag, string innerText, object anonymousAttributes, params IHtmlTagWrapper[] children) { var wrap = new HtmlTagWrapper(tag); if (anonymousAttributes != null) { wrap.ReflectAttributesFromAnonymousType(anonymousAttributes); } if (!string.IsNullOrWhiteSpace(innerText)) { wrap.AddChild(new HtmlTagWrapperTextNode(innerText)); } foreach (var child in children) { wrap.AddChild(child); } return wrap; } public static HtmlTagWrapper Wrap(this HtmlHelper html, bool visible, string tag, string innerText, object anonymousAttributes, params IHtmlTagWrapper[] children) { var item = html.Wrap(tag, innerText, anonymousAttributes, children); item.Visible = visible; foreach (var child in children) { item.AddChild(child); } return item; } #endregion } }
// 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.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Net.Security; using System.ServiceModel.Security; namespace System.ServiceModel.Description { [DebuggerDisplay("Name={_name}, Namespace={_ns}, ContractType={_contractType}")] public class ContractDescription { private XmlName _name; private string _ns; private SessionMode _sessionMode; private ProtectionLevel _protectionLevel; public ContractDescription(string name) : this(name, null) { } public ContractDescription(string name, string ns) { // the property setter validates given value Name = name; if (!string.IsNullOrEmpty(ns)) { NamingHelper.CheckUriParameter(ns, "ns"); } Operations = new OperationDescriptionCollection(); _ns = ns ?? NamingHelper.DefaultNamespace; // ns can be "" } internal string CodeName { get { return _name.DecodedName; } } [DefaultValue(null)] public string ConfigurationName { get; set; } public Type ContractType { get; set; } public Type CallbackContractType { get; set; } public string Name { get { return _name.EncodedName; } set { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(value)); } if (value.Length == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentOutOfRangeException(nameof(value), SR.SFxContractDescriptionNameCannotBeEmpty)); } _name = new XmlName(value, true /*isEncoded*/); } } public string Namespace { get { return _ns; } set { if (!string.IsNullOrEmpty(value)) { NamingHelper.CheckUriProperty(value, "Namespace"); } _ns = value; } } public OperationDescriptionCollection Operations { get; } public ProtectionLevel ProtectionLevel { get { return _protectionLevel; } set { if (!ProtectionLevelHelper.IsDefined(value)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(value))); } _protectionLevel = value; HasProtectionLevel = true; } } public bool ShouldSerializeProtectionLevel() { return HasProtectionLevel; } public bool HasProtectionLevel { get; private set; } [DefaultValue(SessionMode.Allowed)] public SessionMode SessionMode { get { return _sessionMode; } set { if (!SessionModeHelper.IsDefined(value)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(value))); } _sessionMode = value; } } public KeyedCollection<Type, IContractBehavior> ContractBehaviors { get { return Behaviors; } } [EditorBrowsable(EditorBrowsableState.Never)] public KeyedByTypeCollection<IContractBehavior> Behaviors { get; } = new KeyedByTypeCollection<IContractBehavior>(); public static ContractDescription GetContract(Type contractType) { if (contractType == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(contractType)); } TypeLoader typeLoader = new TypeLoader(); return typeLoader.LoadContractDescription(contractType); } public static ContractDescription GetContract(Type contractType, Type serviceType) { if (contractType == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(contractType)); } if (serviceType == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(serviceType)); } TypeLoader typeLoader = new TypeLoader(); ContractDescription description = typeLoader.LoadContractDescription(contractType, serviceType); return description; } public static ContractDescription GetContract(Type contractType, object serviceImplementation) { if (contractType == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(contractType)); } if (serviceImplementation == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(serviceImplementation)); } TypeLoader typeLoader = new TypeLoader(); Type serviceType = serviceImplementation.GetType(); ContractDescription description = typeLoader.LoadContractDescription(contractType, serviceType, serviceImplementation); return description; } public Collection<ContractDescription> GetInheritedContracts() { Collection<ContractDescription> result = new Collection<ContractDescription>(); for (int i = 0; i < Operations.Count; i++) { OperationDescription od = Operations[i]; if (od.DeclaringContract != this) { ContractDescription inheritedContract = od.DeclaringContract; if (!result.Contains(inheritedContract)) { result.Add(inheritedContract); } } } return result; } internal void EnsureInvariants() { if (string.IsNullOrEmpty(Name)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.AChannelServiceEndpointSContractSNameIsNull0)); } if (Namespace == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.AChannelServiceEndpointSContractSNamespace0)); } if (Operations.Count == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.Format(SR.SFxContractHasZeroOperations, Name))); } bool thereIsAtLeastOneInitiatingOperation = false; for (int i = 0; i < Operations.Count; i++) { OperationDescription operationDescription = Operations[i]; operationDescription.EnsureInvariants(); if (operationDescription.IsInitiating) { thereIsAtLeastOneInitiatingOperation = true; } if ((!operationDescription.IsInitiating || operationDescription.IsTerminating) && (SessionMode != SessionMode.Required)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.Format(SR.ContractIsNotSelfConsistentItHasOneOrMore2, Name))); } } if (!thereIsAtLeastOneInitiatingOperation) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.Format(SR.SFxContractHasZeroInitiatingOperations, Name))); } } internal bool IsDuplex() { for (int i = 0; i < Operations.Count; ++i) { if (Operations[i].IsServerInitiated()) { return true; } } return false; } } }
// 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.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using Xunit; namespace System.Linq.Tests { public class QueryableTests { [Fact] public void AsQueryable() { Assert.NotNull(((IEnumerable)(new int[] { })).AsQueryable()); } [Fact] public void AsQueryableT() { Assert.NotNull((new int[] { }).AsQueryable()); } [Fact] public void NullAsQueryableT() { Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<int>)null).AsQueryable()); } [Fact] public void NullAsQueryable() { Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable)null).AsQueryable()); } private class NonGenericEnumerableSoWeDontNeedADependencyOnTheAssemblyWithNonGeneric : IEnumerable { public IEnumerator GetEnumerator() { yield break; } } [Fact] public void NonGenericToQueryable() { Assert.Throws<ArgumentException>(() => new NonGenericEnumerableSoWeDontNeedADependencyOnTheAssemblyWithNonGeneric().AsQueryable()); } [Fact] public void ReturnsSelfIfPossible() { IEnumerable<int> query = Enumerable.Repeat(1, 2).AsQueryable(); Assert.Same(query, query.AsQueryable()); } [Fact] public void ReturnsSelfIfPossibleNonGeneric() { IEnumerable query = Enumerable.Repeat(1, 2).AsQueryable(); Assert.Same(query, query.AsQueryable()); } [Fact] public static void QueryableOfQueryable() { IQueryable<int> queryable1 = new [] { 1, 2, 3 }.AsQueryable(); IQueryable<int>[] queryableArray1 = { queryable1, queryable1 }; IQueryable<IQueryable<int>> queryable2 = queryableArray1.AsQueryable(); ParameterExpression expression1 = Expression.Parameter(typeof(IQueryable<int>), "i"); ParameterExpression[] expressionArray1 = { expression1 }; IQueryable<IQueryable<int>> queryable3 = queryable2.Select(Expression.Lambda<Func<IQueryable<int>, IQueryable<int>>>(expression1, expressionArray1)); int i = queryable3.Count(); Assert.Equal(2, i); } [Fact] public static void MatchSequencePattern() { // If a change to Queryable has required a change to the exception list in this test // make the same change at src/System.Linq/tests/ConsistencyTests.cs MethodInfo enumerableNotInQueryable = GetMissingExtensionMethod( typeof(Enumerable), typeof(Queryable), new [] { "ToLookup", "ToDictionary", "ToArray", "AsEnumerable", "ToList", "Fold", "LeftJoin", "Append", "Prepend", "ToHashSet" } ); Assert.True(enumerableNotInQueryable == null, string.Format("Enumerable method {0} not defined by Queryable", enumerableNotInQueryable)); MethodInfo queryableNotInEnumerable = GetMissingExtensionMethod( typeof(Queryable), typeof(Enumerable), new [] { "AsQueryable" } ); Assert.True(queryableNotInEnumerable == null, string.Format("Queryable method {0} not defined by Enumerable", queryableNotInEnumerable)); } private static MethodInfo GetMissingExtensionMethod(Type a, Type b, IEnumerable<string> excludedMethods) { var dex = new HashSet<string>(excludedMethods); var aMethods = a.GetMethods(BindingFlags.Static | BindingFlags.Public) .Where(m => m.CustomAttributes.Any(c => c.AttributeType == typeof(ExtensionAttribute))) .ToLookup(m => m.Name); MethodComparer mc = new MethodComparer(); var bMethods = b.GetMethods(BindingFlags.Static | BindingFlags.Public) .Where(m => m.CustomAttributes.Any(c => c.AttributeType == typeof(ExtensionAttribute))) .ToLookup(m => m, mc); foreach (var group in aMethods.Where(g => !dex.Contains(g.Key))) { foreach (MethodInfo m in group) { if (!bMethods.Contains(m)) return m; } } return null; } private class MethodComparer : IEqualityComparer<MethodInfo> { public int GetHashCode(MethodInfo m) => m.Name.GetHashCode(); public bool Equals(MethodInfo a, MethodInfo b) { if (a.Name != b.Name) return false; ParameterInfo[] pas = a.GetParameters(); ParameterInfo[] pbs = b.GetParameters(); if (pas.Length != pbs.Length) return false; Type[] aArgs = a.GetGenericArguments(); Type[] bArgs = b.GetGenericArguments(); for (int i = 0, n = pas.Length; i < n; i++) { ParameterInfo pa = pas[i]; ParameterInfo pb = pbs[i]; Type ta = Strip(pa.ParameterType); Type tb = Strip(pb.ParameterType); if (ta.IsGenericType && tb.IsGenericType) { if (ta.GetGenericTypeDefinition() != tb.GetGenericTypeDefinition()) { return false; } } else if (ta.IsGenericParameter && tb.IsGenericParameter) { return Array.IndexOf(aArgs, ta) == Array.IndexOf(bArgs, tb); } else if (ta != tb) { return false; } } return true; } private Type Strip(Type t) { if (t.IsGenericType) { Type g = t; if (!g.IsGenericTypeDefinition) { g = t.GetGenericTypeDefinition(); } if (g == typeof(IQueryable<>) || g == typeof(IEnumerable<>)) { return typeof(IEnumerable); } if (g == typeof(Expression<>)) { return t.GetGenericArguments()[0]; } if (g == typeof(IOrderedEnumerable<>) || g == typeof(IOrderedQueryable<>)) { return typeof(IOrderedQueryable); } } else { if (t == typeof(IQueryable)) { return typeof(IEnumerable); } } return t; } } } }
using UnityEngine; using Cinemachine.Utility; using UnityEngine.Serialization; using System; namespace Cinemachine { /// <summary> /// A Cinemachine Camera geared towards a 3rd person camera experience. /// The camera orbits around its subject with three separate camera rigs defining /// rings around the target. Each rig has its own radius, height offset, composer, /// and lens settings. /// Depending on the camera's position along the spline connecting these three rigs, /// these settings are interpolated to give the final camera position and state. /// </summary> [DocumentationSorting(11, DocumentationSortingAttribute.Level.UserRef)] [ExecuteInEditMode, DisallowMultipleComponent] [AddComponentMenu("Cinemachine/CinemachineFreeLook")] public class CinemachineFreeLook : CinemachineVirtualCameraBase { /// <summary>Object for the camera children to look at (the aim target)</summary> [Tooltip("Object for the camera children to look at (the aim target).")] [NoSaveDuringPlay] public Transform m_LookAt = null; /// <summary>Object for the camera children wants to move with (the body target)</summary> [Tooltip("Object for the camera children wants to move with (the body target).")] [NoSaveDuringPlay] public Transform m_Follow = null; /// <summary>If enabled, this lens setting will apply to all three child rigs, otherwise the child rig lens settings will be used</summary> [Tooltip("If enabled, this lens setting will apply to all three child rigs, otherwise the child rig lens settings will be used")] [FormerlySerializedAs("m_UseCommonLensSetting")] public bool m_CommonLens = true; /// <summary>Specifies the lens properties of this Virtual Camera. /// This generally mirrors the Unity Camera's lens settings, and will be used to drive /// the Unity camera when the vcam is active</summary> [FormerlySerializedAs("m_LensAttributes")] [Tooltip("Specifies the lens properties of this Virtual Camera. This generally mirrors the Unity Camera's lens settings, and will be used to drive the Unity camera when the vcam is active")] [LensSettingsProperty] public LensSettings m_Lens = LensSettings.Default; /// <summary>The Vertical axis. Value is 0..1. Chooses how to blend the child rigs</summary> [Header("Axis Control")] [Tooltip("The Vertical axis. Value is 0..1. Chooses how to blend the child rigs")] public AxisState m_YAxis = new AxisState(2f, 0.2f, 0.1f, 0.5f, "Mouse Y", false); /// <summary>The Horizontal axis. Value is 0..359. This is passed on to the rigs' OrbitalTransposer component</summary> [Tooltip("The Horizontal axis. Value is 0..359. This is passed on to the rigs' OrbitalTransposer component")] public AxisState m_XAxis = new AxisState(300f, 0.1f, 0.1f, 0f, "Mouse X", true); /// <summary>The definition of Forward. Camera will follow behind</summary> [Tooltip("The definition of Forward. Camera will follow behind.")] public CinemachineOrbitalTransposer.Heading m_Heading = new CinemachineOrbitalTransposer.Heading( CinemachineOrbitalTransposer.Heading.HeadingDefinition.TargetForward, 4, 0); /// <summary>Controls how automatic recentering of the X axis is accomplished</summary> [Tooltip("Controls how automatic recentering of the X axis is accomplished")] public CinemachineOrbitalTransposer.Recentering m_RecenterToTargetHeading = new CinemachineOrbitalTransposer.Recentering(false, 1, 2); /// <summary>The coordinate space to use when interpreting the offset from the target</summary> [Header("Orbits")] [Tooltip("The coordinate space to use when interpreting the offset from the target. This is also used to set the camera's Up vector, which will be maintained when aiming the camera.")] public CinemachineOrbitalTransposer.BindingMode m_BindingMode = CinemachineOrbitalTransposer.BindingMode.SimpleFollowWithWorldUp; /// <summary></summary> [Tooltip("Controls how taut is the line that connects the rigs' orbits, which determines final placement on the Y axis")] [Range(0f, 1f)] [FormerlySerializedAs("m_SplineTension")] public float m_SplineCurvature = 0.2f; /// <summary>Defines the height and radius of the Rig orbit</summary> [Serializable] public struct Orbit { /// <summary>Height relative to target</summary> public float m_Height; /// <summary>Radius of orbit</summary> public float m_Radius; /// <summary>Constructor with specific values</summary> public Orbit(float h, float r) { m_Height = h; m_Radius = r; } } /// <summary>The radius and height of the three orbiting rigs</summary> [Tooltip("The radius and height of the three orbiting rigs.")] public Orbit[] m_Orbits = new Orbit[3] { // These are the default orbits new Orbit(4.5f, 1.75f), new Orbit(2.5f, 3f), new Orbit(0.4f, 1.3f) }; // Legacy support [SerializeField] [HideInInspector] [FormerlySerializedAs("m_HeadingBias")] private float m_LegacyHeadingBias = float.MaxValue; bool mUseLegacyRigDefinitions = false; /// <summary>Enforce bounds for fields, when changed in inspector.</summary> protected override void OnValidate() { base.OnValidate(); // Upgrade after a legacy deserialize if (m_LegacyHeadingBias != float.MaxValue) { m_Heading.m_HeadingBias = m_LegacyHeadingBias; m_LegacyHeadingBias = float.MaxValue; m_RecenterToTargetHeading.LegacyUpgrade( ref m_Heading.m_HeadingDefinition, ref m_Heading.m_VelocityFilterStrength); mUseLegacyRigDefinitions = true; } m_YAxis.Validate(); m_XAxis.Validate(); m_RecenterToTargetHeading.Validate(); m_Lens.Validate(); InvalidateRigCache(); } /// <summary>Get a child rig</summary> /// <param name="i">Rig index. Can be 0, 1, or 2</param> /// <returns>The rig, or null if index is bad.</returns> public CinemachineVirtualCamera GetRig(int i) { UpdateRigCache(); return (i < 0 || i > 2) ? null : m_Rigs[i]; } /// <summary>Names of the 3 child rigs</summary> public static string[] RigNames { get { return new string[] { "TopRig", "MiddleRig", "BottomRig" }; } } bool mIsDestroyed = false; /// <summary>Updates the child rig cache</summary> protected override void OnEnable() { mIsDestroyed = false; base.OnEnable(); InvalidateRigCache(); } /// <summary>Makes sure that the child rigs get destroyed in an undo-firndly manner. /// Invalidates the rig cache.</summary> protected override void OnDestroy() { // Make the rigs visible instead of destroying - this is to keep Undo happy if (m_Rigs != null) foreach (var rig in m_Rigs) if (rig != null && rig.gameObject != null) rig.gameObject.hideFlags &= ~(HideFlags.HideInHierarchy | HideFlags.HideInInspector); mIsDestroyed = true; base.OnDestroy(); } /// <summary>Invalidates the rig cache</summary> void OnTransformChildrenChanged() { InvalidateRigCache(); } void Reset() { DestroyRigs(); } /// <summary>The cacmera state, which will be a blend of the child rig states</summary> override public CameraState State { get { return m_State; } } /// <summary>Get the current LookAt target. Returns parent's LookAt if parent /// is non-null and no specific LookAt defined for this camera</summary> override public Transform LookAt { get { return ResolveLookAt(m_LookAt); } set { m_LookAt = value; } } /// <summary>Get the current Follow target. Returns parent's Follow if parent /// is non-null and no specific Follow defined for this camera</summary> override public Transform Follow { get { return ResolveFollow(m_Follow); } set { m_Follow = value; } } /// <summary>Returns the rig with the greatest weight</summary> public override ICinemachineCamera LiveChildOrSelf { get { // Do not update the rig cache here or there will be infinite loop at creation time if (m_Rigs == null || m_Rigs.Length != 3) return this; if (m_YAxis.Value < 0.33f) return m_Rigs[2]; if (m_YAxis.Value > 0.66f) return m_Rigs[0]; return m_Rigs[1]; } } /// <summary>Check whether the vcam a live child of this camera. /// Returns true if the child is currently contributing actively to the camera state.</summary> /// <param name="vcam">The Virtual Camera to check</param> /// <returns>True if the vcam is currently actively influencing the state of this vcam</returns> public override bool IsLiveChild(ICinemachineCamera vcam) { // Do not update the rig cache here or there will be infinite loop at creation time if (m_Rigs == null || m_Rigs.Length != 3) return false; if (m_YAxis.Value < 0.33f) return vcam == (ICinemachineCamera)m_Rigs[2]; if (m_YAxis.Value > 0.66f) return vcam == (ICinemachineCamera)m_Rigs[0]; return vcam == (ICinemachineCamera)m_Rigs[1]; } /// <summary>Remove a Pipeline stage hook callback. /// Make sure it is removed from all the children.</summary> /// <param name="d">The delegate to remove.</param> public override void RemovePostPipelineStageHook(OnPostPipelineStageDelegate d) { base.RemovePostPipelineStageHook(d); UpdateRigCache(); if (m_Rigs != null) foreach (var vcam in m_Rigs) if (vcam != null) vcam.RemovePostPipelineStageHook(d); } /// <summary>Called by CinemachineCore at designated update time /// so the vcam can position itself and track its targets. All 3 child rigs are updated, /// and a blend calculated, depending on the value of the Y axis.</summary> /// <param name="worldUp">Default world Up, set by the CinemachineBrain</param> /// <param name="deltaTime">Delta time for time-based effects (ignore if less than 0)</param> override public void UpdateCameraState(Vector3 worldUp, float deltaTime) { //UnityEngine.Profiling.Profiler.BeginSample("CinemachineFreeLook.UpdateCameraState"); if (!PreviousStateIsValid) deltaTime = -1; UpdateRigCache(); // Reset the base camera state, in case the game object got moved in the editor if (deltaTime < 0) m_State = PullStateFromVirtualCamera(worldUp); // Not in gameplay // Update the current state by invoking the component pipeline m_State = CalculateNewState(worldUp, deltaTime); // Push the raw position back to the game object's transform, so it // moves along with the camera. Leave the orientation alone, because it // screws up camera dragging when there is a LookAt behaviour. if (Follow != null) { Vector3 delta = State.RawPosition - transform.position; transform.position = State.RawPosition; m_Rigs[0].transform.position -= delta; m_Rigs[1].transform.position -= delta; m_Rigs[2].transform.position -= delta; } PreviousStateIsValid = true; // Set up for next frame bool activeCam = (deltaTime >= 0) || CinemachineCore.Instance.IsLive(this); if (activeCam) m_YAxis.Update(deltaTime); PushSettingsToRigs(); //UnityEngine.Profiling.Profiler.EndSample(); } /// <summary>If we are transitioning from another FreeLook, grab the axis values from it.</summary> /// <param name="fromCam">The camera being deactivated. May be null.</param> /// <param name="worldUp">Default world Up, set by the CinemachineBrain</param> /// <param name="deltaTime">Delta time for time-based effects (ignore if less than or equal to 0)</param> public override void OnTransitionFromCamera( ICinemachineCamera fromCam, Vector3 worldUp, float deltaTime) { base.OnTransitionFromCamera(fromCam, worldUp, deltaTime); if ((fromCam != null) && (fromCam is CinemachineFreeLook)) { CinemachineFreeLook freeLookFrom = fromCam as CinemachineFreeLook; if (freeLookFrom.Follow == Follow) { m_XAxis.Value = freeLookFrom.m_XAxis.Value; m_YAxis.Value = freeLookFrom.m_YAxis.Value; UpdateCameraState(worldUp, deltaTime); } } } CameraState m_State = CameraState.Default; // Current state this frame /// Serialized in order to support copy/paste [SerializeField][HideInInspector][NoSaveDuringPlay] private CinemachineVirtualCamera[] m_Rigs = new CinemachineVirtualCamera[3]; void InvalidateRigCache() { mOrbitals = null; } CinemachineOrbitalTransposer[] mOrbitals = null; CinemachineBlend mBlendA; CinemachineBlend mBlendB; /// <summary> /// Override component pipeline creation. /// This needs to be done by the editor to support Undo. /// The override must do exactly the same thing as the CreatePipeline method in this class. /// </summary> public static CreateRigDelegate CreateRigOverride; /// <summary> /// Override component pipeline creation. /// This needs to be done by the editor to support Undo. /// The override must do exactly the same thing as the CreatePipeline method in this class. /// </summary> public delegate CinemachineVirtualCamera CreateRigDelegate( CinemachineFreeLook vcam, string name, CinemachineVirtualCamera copyFrom); /// <summary> /// Override component pipeline destruction. /// This needs to be done by the editor to support Undo. /// </summary> public static DestroyRigDelegate DestroyRigOverride; /// <summary> /// Override component pipeline destruction. /// This needs to be done by the editor to support Undo. /// </summary> public delegate void DestroyRigDelegate(GameObject rig); private void DestroyRigs() { CinemachineVirtualCamera[] oldRigs = new CinemachineVirtualCamera[RigNames.Length]; for (int i = 0; i < RigNames.Length; ++i) { foreach (Transform child in transform) if (child.gameObject.name == RigNames[i]) oldRigs[i] = child.GetComponent<CinemachineVirtualCamera>(); } for (int i = 0; i < oldRigs.Length; ++i) { if (oldRigs[i] != null) { if (DestroyRigOverride != null) DestroyRigOverride(oldRigs[i].gameObject); else Destroy(oldRigs[i].gameObject); } } m_Rigs = null; mOrbitals = null; } private CinemachineVirtualCamera[] CreateRigs(CinemachineVirtualCamera[] copyFrom) { // Invalidate the cache mOrbitals = null; float[] softCenterDefaultsV = new float[] { 0.5f, 0.55f, 0.6f }; CinemachineVirtualCamera[] newRigs = new CinemachineVirtualCamera[3]; for (int i = 0; i < RigNames.Length; ++i) { CinemachineVirtualCamera src = null; if (copyFrom != null && copyFrom.Length > i) src = copyFrom[i]; if (CreateRigOverride != null) newRigs[i] = CreateRigOverride(this, RigNames[i], src); else { // Create a new rig with default components GameObject go = new GameObject(RigNames[i]); go.transform.parent = transform; newRigs[i] = go.AddComponent<CinemachineVirtualCamera>(); if (src != null) ReflectionHelpers.CopyFields(src, newRigs[i]); else { go = newRigs[i].GetComponentOwner().gameObject; go.AddComponent<CinemachineOrbitalTransposer>(); go.AddComponent<CinemachineComposer>(); } } // Set up the defaults newRigs[i].InvalidateComponentPipeline(); CinemachineOrbitalTransposer orbital = newRigs[i].GetCinemachineComponent<CinemachineOrbitalTransposer>(); if (orbital == null) orbital = newRigs[i].AddCinemachineComponent<CinemachineOrbitalTransposer>(); // should not happen if (src == null) { // Only set defaults if not copying orbital.m_YawDamping = 0; CinemachineComposer composer = newRigs[i].GetCinemachineComponent<CinemachineComposer>(); if (composer != null) { composer.m_HorizontalDamping = composer.m_VerticalDamping = 0; composer.m_ScreenX = 0.5f; composer.m_ScreenY = softCenterDefaultsV[i]; composer.m_DeadZoneWidth = composer.m_DeadZoneHeight = 0.1f; composer.m_SoftZoneWidth = composer.m_SoftZoneHeight = 0.8f; composer.m_BiasX = composer.m_BiasY = 0; } } } return newRigs; } private void UpdateRigCache() { //UnityEngine.Profiling.Profiler.BeginSample("CinemachineFreeLook.UpdateRigCache"); if (mIsDestroyed) { //UnityEngine.Profiling.Profiler.EndSample(); return; } // Special condition: Did we just get copy/pasted? if (m_Rigs != null && m_Rigs.Length == 3 && m_Rigs[0] != null && m_Rigs[0].transform.parent != transform) { DestroyRigs(); m_Rigs = CreateRigs(m_Rigs); } // Early out if we're up to date if (mOrbitals != null && mOrbitals.Length == 3) { //UnityEngine.Profiling.Profiler.EndSample(); return; } // Locate existing rigs, and recreate them if any are missing if (LocateExistingRigs(RigNames, false) != 3) { DestroyRigs(); m_Rigs = CreateRigs(null); LocateExistingRigs(RigNames, true); } foreach (var rig in m_Rigs) { // Configure the UI rig.m_ExcludedPropertiesInInspector = m_CommonLens ? new string[] { "m_Script", "Header", "Extensions", "m_Priority", "m_Follow", "m_Lens" } : new string[] { "m_Script", "Header", "Extensions", "m_Priority", "m_Follow" }; rig.m_LockStageInInspector = new CinemachineCore.Stage[] { CinemachineCore.Stage.Body }; } // Create the blend objects mBlendA = new CinemachineBlend(m_Rigs[1], m_Rigs[0], AnimationCurve.Linear(0, 0, 1, 1), 1, 0); mBlendB = new CinemachineBlend(m_Rigs[2], m_Rigs[1], AnimationCurve.Linear(0, 0, 1, 1), 1, 0); // Horizontal rotation clamped to [0,360] (with wraparound) m_XAxis.SetThresholds(0f, 360f, true); // Vertical rotation cleamped to [0,1] as it is a t-value for the // catmull-rom spline going through the 3 points on the rig m_YAxis.SetThresholds(0f, 1f, false); //UnityEngine.Profiling.Profiler.EndSample(); } private int LocateExistingRigs(string[] rigNames, bool forceOrbital) { mOrbitals = new CinemachineOrbitalTransposer[rigNames.Length]; m_Rigs = new CinemachineVirtualCamera[rigNames.Length]; int rigsFound = 0; foreach (Transform child in transform) { CinemachineVirtualCamera vcam = child.GetComponent<CinemachineVirtualCamera>(); if (vcam != null) { GameObject go = child.gameObject; for (int i = 0; i < rigNames.Length; ++i) { if (mOrbitals[i] == null && go.name == rigNames[i]) { // Must have an orbital transposer or it's no good mOrbitals[i] = vcam.GetCinemachineComponent<CinemachineOrbitalTransposer>(); if (mOrbitals[i] == null && forceOrbital) mOrbitals[i] = vcam.AddCinemachineComponent<CinemachineOrbitalTransposer>(); if (mOrbitals[i] != null) { mOrbitals[i].m_HeadingIsSlave = true; if (i == 0) mOrbitals[i].HeadingUpdater = (CinemachineOrbitalTransposer orbital, float deltaTime, Vector3 up) => { return orbital.UpdateHeading(deltaTime, up, ref m_XAxis); }; m_Rigs[i] = vcam; ++rigsFound; } } } } } return rigsFound; } void PushSettingsToRigs() { //UnityEngine.Profiling.Profiler.BeginSample("CinemachineFreeLook.PushSettingsToRigs"); UpdateRigCache(); for (int i = 0; i < m_Rigs.Length; ++i) { //UnityEngine.Profiling.Profiler.BeginSample("CinemachineFreeLook.PushSettingsToRigs.m_Rigs[i] == null"); if (m_Rigs[i] == null) { //UnityEngine.Profiling.Profiler.EndSample(); continue; } //UnityEngine.Profiling.Profiler.EndSample(); //UnityEngine.Profiling.Profiler.BeginSample("CinemachineFreeLook.PushSettingsToRigs.m_CommonLens"); if (m_CommonLens) m_Rigs[i].m_Lens = m_Lens; //UnityEngine.Profiling.Profiler.EndSample(); // If we just deserialized from a legacy version, // pull the orbits and targets from the rigs //UnityEngine.Profiling.Profiler.BeginSample("CinemachineFreeLook.PushSettingsToRigs.mUseLegacyRigDefinitions"); if (mUseLegacyRigDefinitions) { mUseLegacyRigDefinitions = false; m_Orbits[i].m_Height = mOrbitals[i].m_FollowOffset.y; m_Orbits[i].m_Radius = -mOrbitals[i].m_FollowOffset.z; if (m_Rigs[i].Follow != null) Follow = m_Rigs[i].Follow; } m_Rigs[i].Follow = null; //UnityEngine.Profiling.Profiler.EndSample(); // Hide the rigs from prying eyes //UnityEngine.Profiling.Profiler.BeginSample("CinemachineFreeLook.PushSettingsToRigs.Hide the rigs"); if (CinemachineCore.sShowHiddenObjects) m_Rigs[i].gameObject.hideFlags &= ~(HideFlags.HideInHierarchy | HideFlags.HideInInspector); else m_Rigs[i].gameObject.hideFlags |= (HideFlags.HideInHierarchy | HideFlags.HideInInspector); //UnityEngine.Profiling.Profiler.EndSample(); //UnityEngine.Profiling.Profiler.BeginSample("CinemachineFreeLook.PushSettingsToRigs.Push"); mOrbitals[i].m_FollowOffset = GetLocalPositionForCameraFromInput(m_YAxis.Value); mOrbitals[i].m_BindingMode = m_BindingMode; mOrbitals[i].m_Heading = m_Heading; mOrbitals[i].m_XAxis = m_XAxis; mOrbitals[i].m_RecenterToTargetHeading = m_RecenterToTargetHeading; if (i > 0) mOrbitals[i].m_RecenterToTargetHeading.m_enabled = false; // Hack to get SimpleFollow with heterogeneous dampings to work if (m_BindingMode == CinemachineTransposer.BindingMode.SimpleFollowWithWorldUp) m_Rigs[i].SetStateRawPosition(State.RawPosition); //UnityEngine.Profiling.Profiler.EndSample(); } //UnityEngine.Profiling.Profiler.EndSample(); } private CameraState CalculateNewState(Vector3 worldUp, float deltaTime) { //UnityEngine.Profiling.Profiler.BeginSample("CinemachineFreeLook.CalculateNewState"); CameraState state = PullStateFromVirtualCamera(worldUp); // Blend from the appropriate rigs float t = m_YAxis.Value; if (t > 0.5f) { if (mBlendA != null) { mBlendA.TimeInBlend = (t - 0.5f) * 2f; mBlendA.UpdateCameraState(worldUp, deltaTime); state = mBlendA.State; } } else { if (mBlendB != null) { mBlendB.TimeInBlend = t * 2f; mBlendB.UpdateCameraState(worldUp, deltaTime); state = mBlendB.State; } } //UnityEngine.Profiling.Profiler.EndSample(); return state; } private CameraState PullStateFromVirtualCamera(Vector3 worldUp) { CameraState state = CameraState.Default; state.RawPosition = transform.position; state.RawOrientation = transform.rotation; state.ReferenceUp = worldUp; CinemachineBrain brain = CinemachineCore.Instance.FindPotentialTargetBrain(this); m_Lens.Aspect = brain != null ? brain.OutputCamera.aspect : 1; m_Lens.Orthographic = brain != null ? brain.OutputCamera.orthographic : false; state.Lens = m_Lens; return state; } /// <summary> /// Returns the local position of the camera along the spline used to connect the /// three camera rigs. Does not take into account the current heading of the /// camera (or its target) /// </summary> /// <param name="t">The t-value for the camera on its spline. Internally clamped to /// the value [0,1]</param> /// <returns>The local offset (back + up) of the camera WRT its target based on the /// supplied t-value</returns> public Vector3 GetLocalPositionForCameraFromInput(float t) { //UnityEngine.Profiling.Profiler.BeginSample("CinemachineFreeLook.GetLocalPositionForCameraFromInput"); if (mOrbitals == null) { //UnityEngine.Profiling.Profiler.EndSample(); return Vector3.zero; } UpdateCachedSpline(); int n = 1; if (t > 0.5f) { t -= 0.5f; n = 2; } //UnityEngine.Profiling.Profiler.EndSample(); return SplineHelpers.Bezier3( t * 2f, m_CachedKnots[n], m_CachedCtrl1[n], m_CachedCtrl2[n], m_CachedKnots[n+1]); } Orbit[] m_CachedOrbits; float m_CachedTension; Vector4[] m_CachedKnots; Vector4[] m_CachedCtrl1; Vector4[] m_CachedCtrl2; void UpdateCachedSpline() { //UnityEngine.Profiling.Profiler.BeginSample("CinemachineFreeLook.UpdateCachedSpline"); bool cacheIsValid = (m_CachedOrbits != null && m_CachedTension == m_SplineCurvature); for (int i = 0; i < 3 && cacheIsValid; ++i) cacheIsValid = (m_CachedOrbits[i].m_Height == m_Orbits[i].m_Height && m_CachedOrbits[i].m_Radius == m_Orbits[i].m_Radius); if (!cacheIsValid) { float t = m_SplineCurvature; m_CachedKnots = new Vector4[5]; m_CachedCtrl1 = new Vector4[5]; m_CachedCtrl2 = new Vector4[5]; m_CachedKnots[1] = new Vector4(0, m_Orbits[2].m_Height, -m_Orbits[2].m_Radius, 0); m_CachedKnots[2] = new Vector4(0, m_Orbits[1].m_Height, -m_Orbits[1].m_Radius, 0); m_CachedKnots[3] = new Vector4(0, m_Orbits[0].m_Height, -m_Orbits[0].m_Radius, 0); m_CachedKnots[0] = Vector4.Lerp(m_CachedKnots[1], Vector4.zero, t); m_CachedKnots[4] = Vector4.Lerp(m_CachedKnots[3], Vector4.zero, t); SplineHelpers.ComputeSmoothControlPoints( ref m_CachedKnots, ref m_CachedCtrl1, ref m_CachedCtrl2); m_CachedOrbits = new Orbit[3]; for (int i = 0; i < 3; ++i) m_CachedOrbits[i] = m_Orbits[i]; m_CachedTension = m_SplineCurvature; } //UnityEngine.Profiling.Profiler.EndSample(); } } }
/* * REST API Documentation for the MOTI Hired Equipment Tracking System (HETS) Application * * The Hired Equipment Program is for owners/operators who have a dump truck, bulldozer, backhoe or other piece of equipment they want to hire out to the transportation ministry for day labour and emergency projects. The Hired Equipment Program distributes available work to local equipment owners. The program is based on seniority and is designed to deliver work to registered users fairly and efficiently through the development of local area call-out lists. * * OpenAPI spec version: v1 * * */ using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; using HETSAPI.Models; namespace HETSAPI.Models { /// <summary> /// The Ministry of Transportion and Infrastructure DISTRICT /// </summary> [MetaDataExtension (Description = "The Ministry of Transportion and Infrastructure DISTRICT")] public partial class District : AuditableEntity, IEquatable<District> { /// <summary> /// Default constructor, required by entity framework /// </summary> public District() { this.Id = 0; } /// <summary> /// Initializes a new instance of the <see cref="District" /> class. /// </summary> /// <param name="Id">A system-generated unique identifier for a District (required).</param> /// <param name="MinistryDistrictID">A system generated unique identifier. NOT GENERATED IN THIS SYSTEM. (required).</param> /// <param name="Name">The Name of a Ministry District. (required).</param> /// <param name="Region">The region in which the District is found. (required).</param> /// <param name="StartDate">The DATE the business information came into effect. - NOT CURRENTLY ENFORCED IN THIS SYSTEM (required).</param> /// <param name="DistrictNumber">A number that uniquely defines a Ministry District..</param> /// <param name="EndDate">The DATE the business information ceased to be in effect. - NOT CURRENTLY ENFORCED IN THIS SYSTEM.</param> public District(int Id, int MinistryDistrictID, string Name, Region Region, DateTime StartDate, int? DistrictNumber = null, DateTime? EndDate = null) { this.Id = Id; this.MinistryDistrictID = MinistryDistrictID; this.Name = Name; this.Region = Region; this.StartDate = StartDate; this.DistrictNumber = DistrictNumber; this.EndDate = EndDate; } /// <summary> /// A system-generated unique identifier for a District /// </summary> /// <value>A system-generated unique identifier for a District</value> [MetaDataExtension (Description = "A system-generated unique identifier for a District")] public int Id { get; set; } /// <summary> /// A system generated unique identifier. NOT GENERATED IN THIS SYSTEM. /// </summary> /// <value>A system generated unique identifier. NOT GENERATED IN THIS SYSTEM.</value> [MetaDataExtension (Description = "A system generated unique identifier. NOT GENERATED IN THIS SYSTEM.")] public int MinistryDistrictID { get; set; } /// <summary> /// The Name of a Ministry District. /// </summary> /// <value>The Name of a Ministry District.</value> [MetaDataExtension (Description = "The Name of a Ministry District.")] [MaxLength(150)] public string Name { get; set; } /// <summary> /// The region in which the District is found. /// </summary> /// <value>The region in which the District is found.</value> [MetaDataExtension (Description = "The region in which the District is found.")] public Region Region { get; set; } /// <summary> /// Foreign key for Region /// </summary> [ForeignKey("Region")] [JsonIgnore] [MetaDataExtension (Description = "The region in which the District is found.")] public int? RegionId { get; set; } /// <summary> /// The DATE the business information came into effect. - NOT CURRENTLY ENFORCED IN THIS SYSTEM /// </summary> /// <value>The DATE the business information came into effect. - NOT CURRENTLY ENFORCED IN THIS SYSTEM</value> [MetaDataExtension (Description = "The DATE the business information came into effect. - NOT CURRENTLY ENFORCED IN THIS SYSTEM")] public DateTime StartDate { get; set; } /// <summary> /// A number that uniquely defines a Ministry District. /// </summary> /// <value>A number that uniquely defines a Ministry District.</value> [MetaDataExtension (Description = "A number that uniquely defines a Ministry District.")] public int? DistrictNumber { get; set; } /// <summary> /// The DATE the business information ceased to be in effect. - NOT CURRENTLY ENFORCED IN THIS SYSTEM /// </summary> /// <value>The DATE the business information ceased to be in effect. - NOT CURRENTLY ENFORCED IN THIS SYSTEM</value> [MetaDataExtension (Description = "The DATE the business information ceased to be in effect. - NOT CURRENTLY ENFORCED IN THIS SYSTEM")] public DateTime? EndDate { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class District {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" MinistryDistrictID: ").Append(MinistryDistrictID).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" Region: ").Append(Region).Append("\n"); sb.Append(" StartDate: ").Append(StartDate).Append("\n"); sb.Append(" DistrictNumber: ").Append(DistrictNumber).Append("\n"); sb.Append(" EndDate: ").Append(EndDate).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> 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((District)obj); } /// <summary> /// Returns true if District instances are equal /// </summary> /// <param name="other">Instance of District to be compared</param> /// <returns>Boolean</returns> public bool Equals(District other) { if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } return ( this.Id == other.Id || this.Id.Equals(other.Id) ) && ( this.MinistryDistrictID == other.MinistryDistrictID || this.MinistryDistrictID.Equals(other.MinistryDistrictID) ) && ( this.Name == other.Name || this.Name != null && this.Name.Equals(other.Name) ) && ( this.Region == other.Region || this.Region != null && this.Region.Equals(other.Region) ) && ( this.StartDate == other.StartDate || this.StartDate != null && this.StartDate.Equals(other.StartDate) ) && ( this.DistrictNumber == other.DistrictNumber || this.DistrictNumber != null && this.DistrictNumber.Equals(other.DistrictNumber) ) && ( this.EndDate == other.EndDate || this.EndDate != null && this.EndDate.Equals(other.EndDate) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks hash = hash * 59 + this.Id.GetHashCode(); hash = hash * 59 + this.MinistryDistrictID.GetHashCode(); if (this.Name != null) { hash = hash * 59 + this.Name.GetHashCode(); } if (this.Region != null) { hash = hash * 59 + this.Region.GetHashCode(); } if (this.StartDate != null) { hash = hash * 59 + this.StartDate.GetHashCode(); } if (this.DistrictNumber != null) { hash = hash * 59 + this.DistrictNumber.GetHashCode(); } if (this.EndDate != null) { hash = hash * 59 + this.EndDate.GetHashCode(); } return hash; } } #region Operators /// <summary> /// Equals /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator ==(District left, District right) { return Equals(left, right); } /// <summary> /// Not Equals /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator !=(District left, District right) { return !Equals(left, right); } #endregion Operators } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // #define LLVM //--// namespace Microsoft.Zelig.Runtime { using System; using TS = Microsoft.Zelig.Runtime.TypeSystem; [TS.WellKnownType( "Microsoft_Zelig_Runtime_ObjectHeader" )] [TS.NoVTable] public class ObjectHeader { const uint GarbageCollectorMask = 0x000000FF; const int GarbageCollectorShift = 0; const uint ExtensionKindMask = 0x00000300; const int ExtensionKindShift = 8; const uint ExtensionPayloadMask = 0xFFFFFC00; const int ExtensionPayloadShift = 10; [Flags] public enum GarbageCollectorFlags : uint { Unmarked = 0x00000000, Marked = 0x00000001, MutableMask = 0x00000001, FreeBlock = 0 << 1, // Free block. GapPlug = 1 << 1, // Used to mark free space that cannot be reclaimed due to fragmentation. ReadOnlyObject = 2 << 1, // This object is stored in read-only memory. UnreclaimableObject = 3 << 1, // This object is stored outside the garbage-collected heap. NormalObject = 4 << 1, // Normal object. SpecialHandlerObject = 5 << 1, // This object has a GC extension handler. } public enum ExtensionKinds : uint { Empty = 0x00000000, HashCode = 0x00000001, SyncBlock = 0x00000002, Reserved = 0x00000003, } // // State // [TS.WellKnownField( "ObjectHeader_MultiUseWord" )] public volatile int MultiUseWord; [TS.WellKnownField( "ObjectHeader_VirtualTable" )] public TS.VTable VirtualTable; // // Don't allow object creation, this is not a real class, it's more of a struct. // private ObjectHeader() { } // // Helper Methods // [Inline] public object Pack() { int size = System.Runtime.InteropServices.Marshal.SizeOf( typeof(ObjectHeader ) ); return ObjectImpl.CastAsObject( AddressMath.Increment( this.ToPointer(), (uint)size ) ); } [Inline] public static ObjectHeader Unpack( object obj ) { int size = System.Runtime.InteropServices.Marshal.SizeOf( typeof(ObjectHeader ) ); return CastAsObjectHeader( AddressMath.Decrement( ((ObjectImpl)obj).CastAsUIntPtr(), (uint)size ) ); } [TS.GenerateUnsafeCast] public extern UIntPtr ToPointer(); [TS.GenerateUnsafeCast] public extern static ObjectHeader CastAsObjectHeader( UIntPtr ptr ); [Inline] public unsafe UIntPtr GetNextObjectPointer() { ObjectImpl obj = (ObjectImpl)this.Pack(); TS.VTable vTable = this.VirtualTable; ArrayImpl array = ArrayImpl.CastAsArray( obj ); uint size = vTable.BaseSize + vTable.ElementSize * (uint)array.Length; size = AddressMath.AlignToWordBoundary( size ); return new UIntPtr( (uint)obj.Unpack() + size ); } [TS.WellKnownMethod("DebugGC_ObjectHeader_InsertPlug")] public unsafe void InsertPlug( uint size ) { UIntPtr address = this.ToPointer(); uint* dst = (uint*)address.ToPointer(); while(size >= sizeof(uint)) { *dst++ = (uint)GarbageCollectorFlags.GapPlug; size -= sizeof(uint); } } //--// public void UpdateExtension( ExtensionKinds kind , int payload ) { BugCheck.Assert( this.IsImmutable == false, BugCheck.StopCode.SyncBlockCorruption ); while(true) { var oldValue = this.MultiUseWord; uint newValue = ((uint)kind << ExtensionKindShift) | ((uint)payload << ExtensionPayloadShift) | ((uint)oldValue & GarbageCollectorMask); // CS0420: a reference to a volatile field will not be treated as volatile #pragma warning disable 420 var oldValue2 = System.Threading.Interlocked.CompareExchange( ref this.MultiUseWord, (int)newValue, oldValue ); #pragma warning restore 420 if(oldValue2 == oldValue) { break; } } } // // Access Methods // public unsafe GarbageCollectorFlags GarbageCollectorState { [Inline] get { #pragma warning disable 420 // a reference to a volatile field will not be treated as volatile fixed(int* ptr = &this.MultiUseWord) #pragma warning restore 420 { byte* flags = (byte*)ptr; return (GarbageCollectorFlags)(uint)*flags; } } [Inline] set { #pragma warning disable 420 // a reference to a volatile field will not be treated as volatile fixed(int* ptr = &this.MultiUseWord) #pragma warning restore 420 { byte* flags = (byte*)ptr; *flags = (byte)(uint)value; } } } public GarbageCollectorFlags GarbageCollectorStateWithoutMutableBits { [Inline] get { return (this.GarbageCollectorState & ~GarbageCollectorFlags.MutableMask); } } public ExtensionKinds ExtensionKind { [Inline] get { return (ExtensionKinds)((this.MultiUseWord & ExtensionKindMask) >> ExtensionKindShift); } } public bool IsImmutable { [Inline] get { return this.GarbageCollectorStateWithoutMutableBits == GarbageCollectorFlags.ReadOnlyObject; } } public int Payload { [Inline] get { return (int)(((uint)this.MultiUseWord & ExtensionPayloadMask) >> ExtensionPayloadShift); } } //--// // // Extension Methods // [ExtendClass(typeof(TS.VTable), NoConstructors=true, ProcessAfter=typeof(TypeImpl))] class VTableImpl { [Inline] public static TS.VTable Get( object a ) { ObjectImpl.NullCheck( a ); ObjectHeader oh = ObjectHeader.Unpack( a ); return oh.VirtualTable; } [Inline] public static TS.VTable GetFromTypeHandle( RuntimeTypeHandleImpl hnd ) { return hnd.m_value; } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using LibGit2Sharp.Core; using LibGit2Sharp.Tests.TestHelpers; using Xunit; using Xunit.Extensions; namespace LibGit2Sharp.Tests { public class CommitFixture : BaseFixture { private const string sha = "8496071c1b46c854b31185ea97743be6a8774479"; private readonly List<string> expectedShas = new List<string> { "a4a7d", "c4780", "9fd73", "4a202", "5b5b0", "84960" }; [Fact] public void CanCountCommits() { string path = SandboxBareTestRepo(); using (var repo = new Repository(path)) { Assert.Equal(7, repo.Commits.Count()); } } [Fact] public void CanCorrectlyCountCommitsWhenSwitchingToAnotherBranch() { string path = SandboxStandardTestRepo(); using (var repo = new Repository(path)) { // Hard reset and then remove untracked files repo.Reset(ResetMode.Hard); repo.RemoveUntrackedFiles(); repo.Checkout("test"); Assert.Equal(2, repo.Commits.Count()); Assert.Equal("e90810b8df3e80c413d903f631643c716887138d", repo.Commits.First().Id.Sha); repo.Checkout("master"); Assert.Equal(9, repo.Commits.Count()); Assert.Equal("32eab9cb1f450b5fe7ab663462b77d7f4b703344", repo.Commits.First().Id.Sha); } } [Fact] public void CanEnumerateCommits() { int count = 0; string path = SandboxBareTestRepo(); using (var repo = new Repository(path)) { foreach (Commit commit in repo.Commits) { Assert.NotNull(commit); count++; } } Assert.Equal(7, count); } [Fact] public void CanEnumerateCommitsInDetachedHeadState() { string path = SandboxBareTestRepo(); using (var repo = new Repository(path)) { ObjectId parentOfHead = repo.Head.Tip.Parents.First().Id; repo.Refs.Add("HEAD", parentOfHead.Sha, true); Assert.Equal(true, repo.Info.IsHeadDetached); Assert.Equal(6, repo.Commits.Count()); } } [Fact] public void DefaultOrderingWhenEnumeratingCommitsIsTimeBased() { string path = SandboxBareTestRepo(); using (var repo = new Repository(path)) { Assert.Equal(CommitSortStrategies.Time, repo.Commits.SortedBy); } } [Fact] public void CanEnumerateCommitsFromSha() { int count = 0; string path = SandboxBareTestRepo(); using (var repo = new Repository(path)) { foreach (Commit commit in repo.Commits.QueryBy(new CommitFilter { Since = "a4a7dce85cf63874e984719f4fdd239f5145052f" })) { Assert.NotNull(commit); count++; } } Assert.Equal(6, count); } [Fact] public void QueryingTheCommitHistoryWithUnknownShaOrInvalidEntryPointThrows() { string path = SandboxBareTestRepo(); using (var repo = new Repository(path)) { Assert.Throws<NotFoundException>(() => repo.Commits.QueryBy(new CommitFilter { Since = Constants.UnknownSha }).Count()); Assert.Throws<NotFoundException>(() => repo.Commits.QueryBy(new CommitFilter { Since = "refs/heads/deadbeef" }).Count()); Assert.Throws<ArgumentNullException>(() => repo.Commits.QueryBy(new CommitFilter { Since = null }).Count()); } } [Fact] public void QueryingTheCommitHistoryFromACorruptedReferenceThrows() { string path = SandboxBareTestRepo(); using (var repo = new Repository(path)) { CreateCorruptedDeadBeefHead(repo.Info.Path); Assert.Throws<NotFoundException>(() => repo.Commits.QueryBy(new CommitFilter { Since = repo.Branches["deadbeef"] }).Count()); Assert.Throws<NotFoundException>(() => repo.Commits.QueryBy(new CommitFilter { Since = repo.Refs["refs/heads/deadbeef"] }).Count()); } } [Fact] public void QueryingTheCommitHistoryWithBadParamsThrows() { string path = SandboxBareTestRepo(); using (var repo = new Repository(path)) { Assert.Throws<ArgumentException>(() => repo.Commits.QueryBy(new CommitFilter { Since = string.Empty })); Assert.Throws<ArgumentNullException>(() => repo.Commits.QueryBy(new CommitFilter { Since = null })); Assert.Throws<ArgumentNullException>(() => repo.Commits.QueryBy(default(CommitFilter))); } } [Fact] public void CanEnumerateCommitsWithReverseTimeSorting() { var reversedShas = new List<string>(expectedShas); reversedShas.Reverse(); int count = 0; string path = SandboxBareTestRepo(); using (var repo = new Repository(path)) { foreach (Commit commit in repo.Commits.QueryBy(new CommitFilter { Since = "a4a7dce85cf63874e984719f4fdd239f5145052f", SortBy = CommitSortStrategies.Time | CommitSortStrategies.Reverse })) { Assert.NotNull(commit); Assert.True(commit.Sha.StartsWith(reversedShas[count])); count++; } } Assert.Equal(6, count); } [Fact] public void CanEnumerateCommitsWithReverseTopoSorting() { string path = SandboxBareTestRepo(); using (var repo = new Repository(path)) { List<Commit> commits = repo.Commits.QueryBy(new CommitFilter { Since = "a4a7dce85cf63874e984719f4fdd239f5145052f", SortBy = CommitSortStrategies.Time | CommitSortStrategies.Reverse }).ToList(); foreach (Commit commit in commits) { Assert.NotNull(commit); foreach (Commit p in commit.Parents) { Commit parent = commits.Single(x => x.Id == p.Id); Assert.True(commits.IndexOf(commit) > commits.IndexOf(parent)); } } } } [Fact] public void CanSimplifyByFirstParent() { AssertEnumerationOfCommits( repo => new CommitFilter { Since = repo.Head, FirstParentOnly = true }, new[] { "4c062a6", "be3563a", "9fd738e", "4a202b3", "5b5b025", "8496071", }); } [Fact] public void CanGetParentsCount() { string path = SandboxBareTestRepo(); using (var repo = new Repository(path)) { Assert.Equal(1, repo.Commits.First().Parents.Count()); } } [Fact] public void CanEnumerateCommitsWithTimeSorting() { int count = 0; string path = SandboxBareTestRepo(); using (var repo = new Repository(path)) { foreach (Commit commit in repo.Commits.QueryBy(new CommitFilter { Since = "a4a7dce85cf63874e984719f4fdd239f5145052f", SortBy = CommitSortStrategies.Time })) { Assert.NotNull(commit); Assert.True(commit.Sha.StartsWith(expectedShas[count])); count++; } } Assert.Equal(6, count); } [Fact] public void CanEnumerateCommitsWithTopoSorting() { string path = SandboxBareTestRepo(); using (var repo = new Repository(path)) { List<Commit> commits = repo.Commits.QueryBy(new CommitFilter { Since = "a4a7dce85cf63874e984719f4fdd239f5145052f", SortBy = CommitSortStrategies.Topological }).ToList(); foreach (Commit commit in commits) { Assert.NotNull(commit); foreach (Commit p in commit.Parents) { Commit parent = commits.Single(x => x.Id == p.Id); Assert.True(commits.IndexOf(commit) < commits.IndexOf(parent)); } } } } [Fact] public void CanEnumerateFromHead() { AssertEnumerationOfCommits( repo => new CommitFilter { Since = repo.Head }, new[] { "4c062a6", "be3563a", "c47800c", "9fd738e", "4a202b3", "5b5b025", "8496071", }); } [Fact] public void CanEnumerateFromDetachedHead() { string path = SandboxStandardTestRepo(); using (var repoClone = new Repository(path)) { // Hard reset and then remove untracked files repoClone.Reset(ResetMode.Hard); repoClone.RemoveUntrackedFiles(); string headSha = repoClone.Head.Tip.Sha; repoClone.Checkout(headSha); AssertEnumerationOfCommitsInRepo(repoClone, repo => new CommitFilter { Since = repo.Head }, new[] { "32eab9c", "592d3c8", "4c062a6", "be3563a", "c47800c", "9fd738e", "4a202b3", "5b5b025", "8496071", }); } } [Fact] public void CanEnumerateUsingTwoHeadsAsBoundaries() { AssertEnumerationOfCommits( repo => new CommitFilter { Since = "HEAD", Until = "refs/heads/br2" }, new[] { "4c062a6", "be3563a" } ); } [Fact] public void CanEnumerateUsingImplicitHeadAsSinceBoundary() { AssertEnumerationOfCommits( repo => new CommitFilter { Until = "refs/heads/br2" }, new[] { "4c062a6", "be3563a" } ); } [Fact] public void CanEnumerateUsingTwoAbbreviatedShasAsBoundaries() { AssertEnumerationOfCommits( repo => new CommitFilter { Since = "a4a7dce", Until = "4a202b3" }, new[] { "a4a7dce", "c47800c", "9fd738e" } ); } [Fact] public void CanEnumerateCommitsFromTwoHeads() { AssertEnumerationOfCommits( repo => new CommitFilter { Since = new[] { "refs/heads/br2", "refs/heads/master" } }, new[] { "4c062a6", "a4a7dce", "be3563a", "c47800c", "9fd738e", "4a202b3", "5b5b025", "8496071", }); } [Fact] public void CanEnumerateCommitsFromMixedStartingPoints() { AssertEnumerationOfCommits( repo => new CommitFilter { Since = new object[] { repo.Branches["br2"], "refs/heads/master", new ObjectId("e90810b8df3e80c413d903f631643c716887138d") } }, new[] { "4c062a6", "e90810b", "6dcf9bf", "a4a7dce", "be3563a", "c47800c", "9fd738e", "4a202b3", "5b5b025", "8496071", }); } [Fact] public void CanEnumerateCommitsUsingGlob() { AssertEnumerationOfCommits( repo => new CommitFilter { Since = repo.Refs.FromGlob("refs/heads/*") }, new[] { "4c062a6", "e90810b", "6dcf9bf", "a4a7dce", "be3563a", "c47800c", "9fd738e", "4a202b3", "41bc8c6", "5001298", "5b5b025", "8496071" }); } [Fact] public void CanHideCommitsUsingGlob() { AssertEnumerationOfCommits( repo => new CommitFilter { Since = "refs/heads/packed-test", Until = repo.Refs.FromGlob("*/packed") }, new[] { "4a202b3", "5b5b025", "8496071" }); } [Fact] public void CanEnumerateCommitsFromAnAnnotatedTag() { CanEnumerateCommitsFromATag(t => t); } [Fact] public void CanEnumerateCommitsFromATagAnnotation() { CanEnumerateCommitsFromATag(t => t.Annotation); } private void CanEnumerateCommitsFromATag(Func<Tag, object> transformer) { AssertEnumerationOfCommits( repo => new CommitFilter { Since = transformer(repo.Tags["test"]) }, new[] { "e90810b", "6dcf9bf", } ); } [Fact] public void CanEnumerateAllCommits() { AssertEnumerationOfCommits( repo => new CommitFilter { Since = repo.Refs.OrderBy(r => r.CanonicalName, StringComparer.Ordinal), }, new[] { "44d5d18", "bb65291", "532740a", "503a16f", "3dfd6fd", "4409de1", "902c60b", "4c062a6", "e90810b", "6dcf9bf", "a4a7dce", "be3563a", "c47800c", "9fd738e", "4a202b3", "41bc8c6", "5001298", "5b5b025", "8496071", }); } [Fact] public void CanEnumerateCommitsFromATagWhichPointsToABlob() { AssertEnumerationOfCommits( repo => new CommitFilter { Since = repo.Tags["point_to_blob"] }, new string[] { }); } [Fact] public void CanEnumerateCommitsFromATagWhichPointsToATree() { string path = SandboxBareTestRepo(); using (var repo = new Repository(path)) { string headTreeSha = repo.Head.Tip.Tree.Sha; Tag tag = repo.ApplyTag("point_to_tree", headTreeSha); AssertEnumerationOfCommitsInRepo(repo, r => new CommitFilter { Since = tag }, new string[] { }); } } private void AssertEnumerationOfCommits(Func<IRepository, CommitFilter> filterBuilder, IEnumerable<string> abbrevIds) { string path = SandboxBareTestRepo(); using (var repo = new Repository(path)) { AssertEnumerationOfCommitsInRepo(repo, filterBuilder, abbrevIds); } } private static void AssertEnumerationOfCommitsInRepo(IRepository repo, Func<IRepository, CommitFilter> filterBuilder, IEnumerable<string> abbrevIds) { ICommitLog commits = repo.Commits.QueryBy(filterBuilder(repo)); IEnumerable<string> commitShas = commits.Select(c => c.Id.ToString(7)).ToArray(); Assert.Equal(abbrevIds, commitShas); } [Fact] public void CanLookupCommitGeneric() { string path = SandboxBareTestRepo(); using (var repo = new Repository(path)) { var commit = repo.Lookup<Commit>(sha); Assert.Equal("testing\n", commit.Message); Assert.Equal("testing", commit.MessageShort); Assert.Equal(sha, commit.Sha); } } [Fact] public void CanReadCommitData() { string path = SandboxBareTestRepo(); using (var repo = new Repository(path)) { GitObject obj = repo.Lookup(sha); Assert.NotNull(obj); Assert.Equal(typeof(Commit), obj.GetType()); var commit = (Commit)obj; Assert.Equal("testing\n", commit.Message); Assert.Equal("testing", commit.MessageShort); Assert.Equal("UTF-8", commit.Encoding); Assert.Equal(sha, commit.Sha); Assert.NotNull(commit.Author); Assert.Equal("Scott Chacon", commit.Author.Name); Assert.Equal("schacon@gmail.com", commit.Author.Email); Assert.Equal(1273360386, commit.Author.When.ToSecondsSinceEpoch()); Assert.NotNull(commit.Committer); Assert.Equal("Scott Chacon", commit.Committer.Name); Assert.Equal("schacon@gmail.com", commit.Committer.Email); Assert.Equal(1273360386, commit.Committer.When.ToSecondsSinceEpoch()); Assert.Equal("181037049a54a1eb5fab404658a3a250b44335d7", commit.Tree.Sha); Assert.Equal(0, commit.Parents.Count()); } } [Fact] public void CanReadCommitWithMultipleParents() { string path = SandboxBareTestRepo(); using (var repo = new Repository(path)) { var commit = repo.Lookup<Commit>("a4a7dce85cf63874e984719f4fdd239f5145052f"); Assert.Equal(2, commit.Parents.Count()); } } [Fact] public void CanDirectlyAccessABlobOfTheCommit() { string path = SandboxBareTestRepo(); using (var repo = new Repository(path)) { var commit = repo.Lookup<Commit>("4c062a6"); var blob = commit["1/branch_file.txt"].Target as Blob; Assert.NotNull(blob); Assert.Equal("hi\n", blob.GetContentText()); } } [Fact] public void CanDirectlyAccessATreeOfTheCommit() { string path = SandboxBareTestRepo(); using (var repo = new Repository(path)) { var commit = repo.Lookup<Commit>("4c062a6"); var tree1 = commit["1"].Target as Tree; Assert.NotNull(tree1); } } [Fact] public void DirectlyAccessingAnUnknownTreeEntryOfTheCommitReturnsNull() { string path = SandboxBareTestRepo(); using (var repo = new Repository(path)) { var commit = repo.Lookup<Commit>("4c062a6"); Assert.Null(commit["I-am-not-here"]); } } [Theory] [InlineData(null, "x@example.com")] [InlineData("", "x@example.com")] [InlineData("X", null)] [InlineData("X", "")] public void CommitWithInvalidSignatureConfigThrows(string name, string email) { string repoPath = InitNewRepository(); string configPath = CreateConfigurationWithDummyUser(name, email); var options = new RepositoryOptions { GlobalConfigurationLocation = configPath }; using (var repo = new Repository(repoPath, options)) { Assert.Equal(name, repo.Config.GetValueOrDefault<string>("user.name")); Assert.Equal(email, repo.Config.GetValueOrDefault<string>("user.email")); Assert.Throws<LibGit2SharpException>( () => repo.Commit("Initial egotistic commit", new CommitOptions { AllowEmptyCommit = true })); } } [Fact] public void CanCommitWithSignatureFromConfig() { string repoPath = InitNewRepository(); string configPath = CreateConfigurationWithDummyUser(Constants.Signature); var options = new RepositoryOptions { GlobalConfigurationLocation = configPath }; using (var repo = new Repository(repoPath, options)) { string dir = repo.Info.Path; Assert.True(Path.IsPathRooted(dir)); Assert.True(Directory.Exists(dir)); const string relativeFilepath = "new.txt"; string filePath = Touch(repo.Info.WorkingDirectory, relativeFilepath, "null"); repo.Stage(relativeFilepath); File.AppendAllText(filePath, "token\n"); repo.Stage(relativeFilepath); Assert.Null(repo.Head[relativeFilepath]); Commit commit = repo.Commit("Initial egotistic commit"); AssertBlobContent(repo.Head[relativeFilepath], "nulltoken\n"); AssertBlobContent(commit[relativeFilepath], "nulltoken\n"); AssertCommitSignaturesAre(commit, Constants.Signature); } } [Fact] public void CommitParentsAreMergeHeads() { string path = SandboxStandardTestRepo(); using (var repo = new Repository(path)) { repo.Reset(ResetMode.Hard, "c47800"); CreateAndStageANewFile(repo); Touch(repo.Info.Path, "MERGE_HEAD", "9fd738e8f7967c078dceed8190330fc8648ee56a\n"); Assert.Equal(CurrentOperation.Merge, repo.Info.CurrentOperation); Commit newMergedCommit = repo.Commit("Merge commit", Constants.Signature, Constants.Signature); Assert.Equal(CurrentOperation.None, repo.Info.CurrentOperation); Assert.Equal(2, newMergedCommit.Parents.Count()); Assert.Equal(newMergedCommit.Parents.First().Sha, "c47800c7266a2be04c571c04d5a6614691ea99bd"); Assert.Equal(newMergedCommit.Parents.Skip(1).First().Sha, "9fd738e8f7967c078dceed8190330fc8648ee56a"); // Assert reflog entry is created var reflogEntry = repo.Refs.Log(repo.Refs.Head).First(); Assert.Equal(repo.Head.Tip.Id, reflogEntry.To); Assert.NotNull(reflogEntry.Committer.Email); Assert.NotNull(reflogEntry.Committer.Name); Assert.Equal(string.Format("commit (merge): {0}", newMergedCommit.MessageShort), reflogEntry.Message); } } [Fact] public void CommitCleansUpMergeMetadata() { string repoPath = InitNewRepository(); using (var repo = new Repository(repoPath)) { string dir = repo.Info.Path; Assert.True(Path.IsPathRooted(dir)); Assert.True(Directory.Exists(dir)); const string relativeFilepath = "new.txt"; Touch(repo.Info.WorkingDirectory, relativeFilepath, "this is a new file"); repo.Stage(relativeFilepath); string mergeHeadPath = Touch(repo.Info.Path, "MERGE_HEAD", "abcdefabcdefabcdefabcdefabcdefabcdefabcd"); string mergeMsgPath = Touch(repo.Info.Path, "MERGE_MSG", "This is a dummy merge.\n"); string mergeModePath = Touch(repo.Info.Path, "MERGE_MODE", "no-ff"); string origHeadPath = Touch(repo.Info.Path, "ORIG_HEAD", "beefbeefbeefbeefbeefbeefbeefbeefbeefbeef"); Assert.True(File.Exists(mergeHeadPath)); Assert.True(File.Exists(mergeMsgPath)); Assert.True(File.Exists(mergeModePath)); Assert.True(File.Exists(origHeadPath)); var author = Constants.Signature; repo.Commit("Initial egotistic commit", author, author); Assert.False(File.Exists(mergeHeadPath)); Assert.False(File.Exists(mergeMsgPath)); Assert.False(File.Exists(mergeModePath)); Assert.True(File.Exists(origHeadPath)); } } [Fact] public void CanCommitALittleBit() { string repoPath = InitNewRepository(); var identity = Constants.Identity; using (var repo = new Repository(repoPath, new RepositoryOptions { Identity = identity })) { string dir = repo.Info.Path; Assert.True(Path.IsPathRooted(dir)); Assert.True(Directory.Exists(dir)); const string relativeFilepath = "new.txt"; string filePath = Touch(repo.Info.WorkingDirectory, relativeFilepath, "null"); repo.Stage(relativeFilepath); File.AppendAllText(filePath, "token\n"); repo.Stage(relativeFilepath); Assert.Null(repo.Head[relativeFilepath]); var author = Constants.Signature; const string shortMessage = "Initial egotistic commit"; const string commitMessage = shortMessage + "\n\nOnly the coolest commits from us"; Commit commit = repo.Commit(commitMessage, author, author); AssertBlobContent(repo.Head[relativeFilepath], "nulltoken\n"); AssertBlobContent(commit[relativeFilepath], "nulltoken\n"); Assert.Equal(0, commit.Parents.Count()); Assert.False(repo.Info.IsHeadUnborn); // Assert a reflog entry is created on HEAD Assert.Equal(1, repo.Refs.Log("HEAD").Count()); var reflogEntry = repo.Refs.Log("HEAD").First(); Assert.Equal(identity.Name, reflogEntry.Committer.Name); Assert.Equal(identity.Email, reflogEntry.Committer.Email); var now = DateTimeOffset.Now; Assert.InRange(reflogEntry.Committer.When, now - TimeSpan.FromSeconds(1), now); Assert.Equal(commit.Id, reflogEntry.To); Assert.Equal(ObjectId.Zero, reflogEntry.From); Assert.Equal(string.Format("commit (initial): {0}", shortMessage), reflogEntry.Message); // Assert a reflog entry is created on HEAD target var targetCanonicalName = repo.Refs.Head.TargetIdentifier; Assert.Equal(1, repo.Refs.Log(targetCanonicalName).Count()); Assert.Equal(commit.Id, repo.Refs.Log(targetCanonicalName).First().To); File.WriteAllText(filePath, "nulltoken commits!\n"); repo.Stage(relativeFilepath); var author2 = new Signature(author.Name, author.Email, author.When.AddSeconds(5)); Commit commit2 = repo.Commit("Are you trying to fork me?", author2, author2); AssertBlobContent(repo.Head[relativeFilepath], "nulltoken commits!\n"); AssertBlobContent(commit2[relativeFilepath], "nulltoken commits!\n"); Assert.Equal(1, commit2.Parents.Count()); Assert.Equal(commit.Id, commit2.Parents.First().Id); // Assert the reflog is shifted Assert.Equal(2, repo.Refs.Log("HEAD").Count()); Assert.Equal(reflogEntry.To, repo.Refs.Log("HEAD").First().From); Branch firstCommitBranch = repo.CreateBranch("davidfowl-rules", commit); repo.Checkout(firstCommitBranch); File.WriteAllText(filePath, "davidfowl commits!\n"); var author3 = new Signature("David Fowler", "david.fowler@microsoft.com", author.When.AddSeconds(2)); repo.Stage(relativeFilepath); Commit commit3 = repo.Commit("I'm going to branch you backwards in time!", author3, author3); AssertBlobContent(repo.Head[relativeFilepath], "davidfowl commits!\n"); AssertBlobContent(commit3[relativeFilepath], "davidfowl commits!\n"); Assert.Equal(1, commit3.Parents.Count()); Assert.Equal(commit.Id, commit3.Parents.First().Id); AssertBlobContent(firstCommitBranch[relativeFilepath], "nulltoken\n"); } } private static void AssertBlobContent(TreeEntry entry, string expectedContent) { Assert.Equal(TreeEntryTargetType.Blob, entry.TargetType); Assert.Equal(expectedContent, ((Blob)(entry.Target)).GetContentText()); } private static void AddCommitToRepo(string path) { using (var repo = new Repository(path)) { const string relativeFilepath = "test.txt"; Touch(repo.Info.WorkingDirectory, relativeFilepath, "test\n"); repo.Stage(relativeFilepath); var author = new Signature("nulltoken", "emeric.fermas@gmail.com", DateTimeOffset.Parse("Wed, Dec 14 2011 08:29:03 +0100")); repo.Commit("Initial commit", author, author); } } [Fact] public void CanGeneratePredictableObjectShas() { string repoPath = InitNewRepository(); AddCommitToRepo(repoPath); using (var repo = new Repository(repoPath)) { Commit commit = repo.Commits.Single(); Assert.Equal("1fe3126578fc4eca68c193e4a3a0a14a0704624d", commit.Sha); Tree tree = commit.Tree; Assert.Equal("2b297e643c551e76cfa1f93810c50811382f9117", tree.Sha); GitObject blob = tree.Single().Target; Assert.IsAssignableFrom<Blob>(blob); Assert.Equal("9daeafb9864cf43055ae93beb0afd6c7d144bfa4", blob.Sha); } } [Fact] public void CanAmendARootCommit() { string repoPath = InitNewRepository(); AddCommitToRepo(repoPath); using (var repo = new Repository(repoPath)) { Assert.Equal(1, repo.Head.Commits.Count()); Commit originalCommit = repo.Head.Tip; Assert.Equal(0, originalCommit.Parents.Count()); CreateAndStageANewFile(repo); Commit amendedCommit = repo.Commit("I'm rewriting the history!", Constants.Signature, Constants.Signature, new CommitOptions { AmendPreviousCommit = true }); Assert.Equal(1, repo.Head.Commits.Count()); AssertCommitHasBeenAmended(repo, amendedCommit, originalCommit); } } [Fact] public void CanAmendACommitWithMoreThanOneParent() { string path = SandboxStandardTestRepo(); using (var repo = new Repository(path, new RepositoryOptions { Identity = Constants.Identity })) { var mergedCommit = repo.Lookup<Commit>("be3563a"); Assert.NotNull(mergedCommit); Assert.Equal(2, mergedCommit.Parents.Count()); repo.Reset(ResetMode.Soft, mergedCommit.Sha); CreateAndStageANewFile(repo); const string commitMessage = "I'm rewriting the history!"; Commit amendedCommit = repo.Commit(commitMessage, Constants.Signature, Constants.Signature, new CommitOptions { AmendPreviousCommit = true }); AssertCommitHasBeenAmended(repo, amendedCommit, mergedCommit); AssertRefLogEntry(repo, "HEAD", string.Format("commit (amend): {0}", commitMessage), mergedCommit.Id, amendedCommit.Id, Constants.Identity, DateTimeOffset.Now); } } private static void CreateAndStageANewFile(IRepository repo) { string relativeFilepath = string.Format("new-file-{0}.txt", Path.GetRandomFileName()); Touch(repo.Info.WorkingDirectory, relativeFilepath, "brand new content\n"); repo.Stage(relativeFilepath); } private static void AssertCommitHasBeenAmended(IRepository repo, Commit amendedCommit, Commit originalCommit) { Commit headCommit = repo.Head.Tip; Assert.Equal(amendedCommit, headCommit); Assert.NotEqual(originalCommit.Sha, amendedCommit.Sha); Assert.Equal(originalCommit.Parents, amendedCommit.Parents); } [Fact] public void CanNotAmendAnEmptyRepository() { string repoPath = InitNewRepository(); using (var repo = new Repository(repoPath)) { Assert.Throws<UnbornBranchException>(() => repo.Commit("I can not amend anything !:(", Constants.Signature, Constants.Signature, new CommitOptions { AmendPreviousCommit = true })); } } [Fact] public void CanRetrieveChildrenOfASpecificCommit() { string path = SandboxStandardTestRepo(); using (var repo = new Repository(path)) { const string parentSha = "5b5b025afb0b4c913b4c338a42934a3863bf3644"; var filter = new CommitFilter { /* Revwalk from all the refs (git log --all) ... */ Since = repo.Refs, /* ... and stop when the parent is reached */ Until = parentSha }; var commits = repo.Commits.QueryBy(filter); var children = from c in commits from p in c.Parents let pId = p.Id where pId.Sha == parentSha select c; var expectedChildren = new[] { "c47800c7266a2be04c571c04d5a6614691ea99bd", "4a202b346bb0fb0db7eff3cffeb3c70babbd2045" }; Assert.Equal(expectedChildren, children.Select(c => c.Id.Sha)); } } [Fact] public void CanCorrectlyDistinguishAuthorFromCommitter() { string path = SandboxStandardTestRepo(); using (var repo = new Repository(path)) { var author = new Signature("Wilbert van Dolleweerd", "getit@xs4all.nl", Epoch.ToDateTimeOffset(1244187936, 120)); var committer = new Signature("Henk Westhuis", "Henk_Westhuis@hotmail.com", Epoch.ToDateTimeOffset(1244286496, 120)); Commit c = repo.Commit("I can haz an author and a committer!", author, committer); Assert.Equal(author, c.Author); Assert.Equal(committer, c.Committer); } } [Fact] public void CanCommitOnOrphanedBranch() { string newBranchName = "refs/heads/newBranch"; string repoPath = InitNewRepository(); using (var repo = new Repository(repoPath)) { // Set Head to point to branch other than master repo.Refs.UpdateTarget("HEAD", newBranchName); Assert.Equal(newBranchName, repo.Head.CanonicalName); const string relativeFilepath = "test.txt"; Touch(repo.Info.WorkingDirectory, relativeFilepath, "test\n"); repo.Stage(relativeFilepath); repo.Commit("Initial commit", Constants.Signature, Constants.Signature); Assert.Equal(1, repo.Head.Commits.Count()); } } [Fact] public void CanNotCommitAnEmptyCommit() { string path = SandboxStandardTestRepo(); using (var repo = new Repository(path)) { repo.Reset(ResetMode.Hard); repo.RemoveUntrackedFiles(); Assert.Throws<EmptyCommitException>(() => repo.Commit("Empty commit!", Constants.Signature, Constants.Signature)); } } [Fact] public void CanCommitAnEmptyCommitWhenForced() { string path = SandboxStandardTestRepo(); using (var repo = new Repository(path)) { repo.Reset(ResetMode.Hard); repo.RemoveUntrackedFiles(); repo.Commit("Empty commit!", Constants.Signature, Constants.Signature, new CommitOptions { AllowEmptyCommit = true }); } } [Fact] public void CanNotAmendAnEmptyCommit() { string path = SandboxStandardTestRepo(); using (var repo = new Repository(path)) { repo.Reset(ResetMode.Hard); repo.RemoveUntrackedFiles(); repo.Commit("Empty commit!", Constants.Signature, Constants.Signature, new CommitOptions { AllowEmptyCommit = true }); Assert.Throws<EmptyCommitException>(() => repo.Commit("Empty commit!", Constants.Signature, Constants.Signature, new CommitOptions { AmendPreviousCommit = true })); } } [Fact] public void CanAmendAnEmptyCommitWhenForced() { string path = SandboxStandardTestRepo(); using (var repo = new Repository(path)) { repo.Reset(ResetMode.Hard); repo.RemoveUntrackedFiles(); Commit emptyCommit = repo.Commit("Empty commit!", Constants.Signature, Constants.Signature, new CommitOptions { AllowEmptyCommit = true }); Commit amendedCommit = repo.Commit("I'm rewriting the history!", Constants.Signature, Constants.Signature, new CommitOptions { AmendPreviousCommit = true, AllowEmptyCommit = true }); AssertCommitHasBeenAmended(repo, amendedCommit, emptyCommit); } } [Fact] public void CanCommitAnEmptyCommitWhenMerging() { string path = SandboxStandardTestRepo(); using (var repo = new Repository(path)) { repo.Reset(ResetMode.Hard); repo.RemoveUntrackedFiles(); Touch(repo.Info.Path, "MERGE_HEAD", "f705abffe7015f2beacf2abe7a36583ebee3487e\n"); Assert.Equal(CurrentOperation.Merge, repo.Info.CurrentOperation); Commit newMergedCommit = repo.Commit("Merge commit", Constants.Signature, Constants.Signature); Assert.Equal(2, newMergedCommit.Parents.Count()); Assert.Equal(newMergedCommit.Parents.First().Sha, "32eab9cb1f450b5fe7ab663462b77d7f4b703344"); Assert.Equal(newMergedCommit.Parents.Skip(1).First().Sha, "f705abffe7015f2beacf2abe7a36583ebee3487e"); } } [Fact] public void CanAmendAnEmptyMergeCommit() { string path = SandboxStandardTestRepo(); using (var repo = new Repository(path)) { repo.Reset(ResetMode.Hard); repo.RemoveUntrackedFiles(); Touch(repo.Info.Path, "MERGE_HEAD", "f705abffe7015f2beacf2abe7a36583ebee3487e\n"); Commit newMergedCommit = repo.Commit("Merge commit", Constants.Signature, Constants.Signature); Commit amendedCommit = repo.Commit("I'm rewriting the history!", Constants.Signature, Constants.Signature, new CommitOptions { AmendPreviousCommit = true }); AssertCommitHasBeenAmended(repo, amendedCommit, newMergedCommit); } } [Fact] public void CanNotAmendACommitInAWayThatWouldLeadTheNewCommitToBecomeEmpty() { string repoPath = InitNewRepository(); using (var repo = new Repository(repoPath)) { Touch(repo.Info.WorkingDirectory, "test.txt", "test\n"); repo.Stage("test.txt"); repo.Commit("Initial commit", Constants.Signature, Constants.Signature); Touch(repo.Info.WorkingDirectory, "new.txt", "content\n"); repo.Stage("new.txt"); repo.Commit("One commit", Constants.Signature, Constants.Signature); repo.Remove("new.txt"); Assert.Throws<EmptyCommitException>(() => repo.Commit("Oops", Constants.Signature, Constants.Signature, new CommitOptions { AmendPreviousCommit = true })); } } } }
// 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.Collections.Generic; using System.Linq; using Microsoft.PythonTools.Parsing; using Microsoft.VisualStudio.Debugger; namespace Microsoft.PythonTools.DkmDebugger.Proxies.Structs { using Microsoft.VisualStudio.Debugger.Evaluation; using PyDictEntry = Microsoft.PythonTools.DkmDebugger.Proxies.Structs.PyDictKeyEntry; internal abstract class PyDictObject : PyObject { protected PyDictObject(DkmProcess process, ulong address) : base(process, address) { } public abstract IEnumerable<KeyValuePair<PyObject, PointerProxy<PyObject>>> ReadElements(); public override void Repr(ReprBuilder builder) { var count = ReadElements().Count(); if (count > ReprBuilder.MaxJoinedItems) { builder.AppendFormat("<dict, len() = {0}>", count); return; } builder.Append("{"); builder.AppendJoined(", ", ReadElements(), entry => { builder.AppendRepr(entry.Key); builder.Append(": "); builder.AppendRepr(entry.Value.TryRead()); }); builder.Append("}"); } public override IEnumerable<PythonEvaluationResult> GetDebugChildren(ReprOptions reprOptions) { yield return new PythonEvaluationResult(new ValueStore<long>(ReadElements().Count()), "len()") { Category = DkmEvaluationResultCategory.Method }; var reprBuilder = new ReprBuilder(reprOptions); foreach (var entry in ReadElements()) { reprBuilder.Clear(); reprBuilder.AppendFormat("[{0}]", entry.Key); yield return new PythonEvaluationResult(entry.Value, reprBuilder.ToString()); } } } [StructProxy(StructName = "PyDictObject", MaxVersion = PythonLanguageVersion.V27)] [PyType(VariableName = "PyDict_Type", MaxVersion = PythonLanguageVersion.V27)] internal class PyDictObject27 : PyDictObject { private class DummyHolder : DkmDataItem { public readonly PointerProxy<PyObject> Dummy; public DummyHolder(DkmProcess process) { Dummy = process.GetPythonRuntimeInfo().DLLs.Python.GetStaticVariable<PointerProxy<PyObject>>("dummy", "dictobject.obj"); } } private class Fields { public StructField<SSizeTProxy> ma_mask; public StructField<PointerProxy<ArrayProxy<PyDictEntry>>> ma_table; } private readonly Fields _fields; private readonly PyObject _dummy; public PyDictObject27(DkmProcess process, ulong address) : base(process, address) { InitializeStruct(this, out _fields); CheckPyType<PyDictObject27>(); _dummy = Process.GetOrCreateDataItem(() => new DummyHolder(Process)).Dummy.TryRead(); } public PointerProxy<ArrayProxy<PyDictEntry>> ma_table { get { return GetFieldProxy(_fields.ma_table); } } public SSizeTProxy ma_mask { get { return GetFieldProxy(_fields.ma_mask); } } public override IEnumerable<KeyValuePair<PyObject, PointerProxy<PyObject>>> ReadElements() { if (ma_table.IsNull) { return Enumerable.Empty<KeyValuePair<PyObject, PointerProxy<PyObject>>>(); } var count = ma_mask.Read() + 1; var entries = ma_table.Read().Take((int)count); var items = from entry in entries let key = entry.me_key.TryRead() where key != null && key != _dummy let valuePtr = entry.me_value where !valuePtr.IsNull select new KeyValuePair<PyObject, PointerProxy<PyObject>>(key, valuePtr); return items; } } [StructProxy(StructName = "PyDictObject", MinVersion = PythonLanguageVersion.V33)] [PyType(VariableName = "PyDict_Type", MinVersion = PythonLanguageVersion.V33)] internal class PyDictObject33 : PyDictObject { private class Fields { public StructField<PointerProxy<PyDictKeysObject>> ma_keys; public StructField<PointerProxy<ArrayProxy<PointerProxy<PyObject>>>> ma_values; } private readonly Fields _fields; public PyDictObject33(DkmProcess process, ulong address) : base(process, address) { InitializeStruct(this, out _fields); CheckPyType<PyDictObject33>(); } public PointerProxy<PyDictKeysObject> ma_keys { get { return GetFieldProxy(_fields.ma_keys); } } public PointerProxy<ArrayProxy<PointerProxy<PyObject>>> ma_values { get { return GetFieldProxy(_fields.ma_values); } } public override IEnumerable<KeyValuePair<PyObject, PointerProxy<PyObject>>> ReadElements() { if (ma_keys.IsNull) { yield break; } var keys = this.ma_keys.Read(); var entries = keys.dk_entries.Take((int)keys.dk_size.Read()); var ma_values = this.ma_values; if (ma_values.IsNull) { foreach (PyDictKeyEntry entry in entries) { var key = entry.me_key.TryRead(); if (key != null) { yield return new KeyValuePair<PyObject, PointerProxy<PyObject>>(key, entry.me_value); } } } else { var valuePtr = ma_values.Read()[0]; foreach (PyDictKeyEntry entry in entries) { var key = entry.me_key.TryRead(); if (key != null) { yield return new KeyValuePair<PyObject, PointerProxy<PyObject>>(key, valuePtr); } valuePtr = valuePtr.GetAdjacentProxy(1); } } } } [StructProxy(MinVersion = PythonLanguageVersion.V33, StructName = "_dictkeysobject")] internal class PyDictKeysObject : StructProxy { private class Fields { public StructField<SSizeTProxy> dk_size; public StructField<ArrayProxy<PyDictKeyEntry>> dk_entries; } private readonly Fields _fields; public SSizeTProxy dk_size { get { return GetFieldProxy(_fields.dk_size); } } public ArrayProxy<PyDictKeyEntry> dk_entries { get { return GetFieldProxy(_fields.dk_entries); } } public PyDictKeysObject(DkmProcess process, ulong address) : base(process, address) { InitializeStruct(this, out _fields); } } [StructProxy(MaxVersion = PythonLanguageVersion.V27, StructName = "PyDictEntry")] [StructProxy(MinVersion = PythonLanguageVersion.V33)] internal class PyDictKeyEntry : StructProxy { private class Fields { public StructField<PointerProxy<PyObject>> me_key; public StructField<PointerProxy<PyObject>> me_value; } private readonly Fields _fields; public PyDictKeyEntry(DkmProcess process, ulong address) : base(process, address) { InitializeStruct(this, out _fields); } public PointerProxy<PyObject> me_key { get { return GetFieldProxy(_fields.me_key); } } public PointerProxy<PyObject> me_value { get { return GetFieldProxy(_fields.me_value); } } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Reflection; using log4net; namespace VoronoiMap { public class VoronoiGraph { private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public bool Debug { get; set; } public int Width { get; private set; } public int Height { get; private set; } public readonly List<Site> Sites = new List<Site>(); public readonly List<Site> Vertices = new List<Site>(); public readonly List<Segment> Segments = new List<Segment>(); public readonly List<Triangle> Triangles = new List<Triangle>(); public readonly List<Edge> Edges = new List<Edge>(); public float SweepLine { get; set; } public VoronoiGraph(int width = 800, int height = 600) { Width = width; Height = height; Debug = false; } public static VoronoiGraph ComputeVoronoiGraph(IEnumerable<PointF> points, int w = 800, int h = 600, bool debug=false) { var sites = new SiteList(points); if (debug) { sites.LogSites(); } var graph = new VoronoiGraph(w, h) { Debug = debug }; try { var edgeList = new EdgeList(sites); var eventQueue = new EventQueue(); sites.BottomSite = sites.ExtractMin(); graph.PlotSite(sites.BottomSite); var newSite = sites.ExtractMin(); var newIntStar = new Site(Single.MaxValue, Single.MaxValue); while (true) { if (!eventQueue.IsEmpty) { newIntStar = eventQueue.Min(); } if (newSite != null && (eventQueue.IsEmpty || newSite.CompareTo(newIntStar) < 0)) { // new site is smallest graph.PlotSite(newSite); var lbnd = edgeList.LeftBound(newSite); var rbnd = lbnd.Right; var bot = edgeList.RightRegion(lbnd); var e = Edge.CreateBisectingEdge(bot, newSite); graph.PlotBisector(e); var bisector = new HalfEdge(e, Side.Left); EdgeList.Insert(lbnd, bisector); var p = Site.CreateIntersectingSite(lbnd, bisector); if (p != null) { eventQueue.Delete(lbnd); if (debug) { Console.WriteLine("Inserting {0}", p); } eventQueue.Insert(lbnd, p, Site.Distance(p, newSite)); } lbnd = bisector; bisector = new HalfEdge(e, Side.Right); EdgeList.Insert(lbnd, bisector); p = Site.CreateIntersectingSite(bisector, rbnd); if (p != null) { if (debug) { Console.WriteLine("Inserting {0}", p); } eventQueue.Insert(bisector, p, Site.Distance(p, newSite)); } newSite = sites.ExtractMin(); } else if (!eventQueue.IsEmpty) { // intersection is smallest var lbnd = eventQueue.ExtractMin(); var llbnd = lbnd.Left; var rbnd = lbnd.Right; var rrbnd = rbnd.Right; var bot = edgeList.LeftRegion(lbnd); var top = edgeList.RightRegion(rbnd); graph.PlotTriple(bot, top, edgeList.RightRegion(lbnd)); var v = lbnd.Vertex; graph.PlotVertex(v); graph.EndPoint(lbnd.Edge, lbnd.Side, v); graph.EndPoint(rbnd.Edge, rbnd.Side, v); EdgeList.Delete(lbnd); eventQueue.Delete(rbnd); EdgeList.Delete(rbnd); var pm = Side.Left; if (bot.Y > top.Y) { var temp = bot; bot = top; top = temp; pm = Side.Right; } var e = Edge.CreateBisectingEdge(bot, top); graph.PlotBisector(e); var bisector = new HalfEdge(e, pm); EdgeList.Insert(llbnd, bisector); graph.EndPoint(e, Side.Other(pm), v); var p = Site.CreateIntersectingSite(llbnd, bisector); if (p != null) { eventQueue.Delete(llbnd); if (debug) { Console.WriteLine("Inserting {0}", p); } eventQueue.Insert(llbnd, p, Site.Distance(p, bot)); } p = Site.CreateIntersectingSite(bisector, rrbnd); if (p != null) { if (debug) { Console.WriteLine("Inserting {0}", p); } eventQueue.Insert(bisector, p, Site.Distance(p, bot)); } } else { break; } } for (var lbnd = edgeList.LeftEnd.Right; lbnd != edgeList.RightEnd; lbnd = lbnd.Right) { var e = lbnd.Edge; graph.PlotEndpoint(e); } } catch (Exception ex) { Console.WriteLine("########################################"); Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); } graph.SweepLine = graph.Height; graph.ResetNewItems(); foreach (var edge in graph.Edges) { edge.ClipVertices(new Rectangle(0,0, w, h)); } return graph; } public void PlotSite(Site site) { site.New = true; Sites.Add(site); if (Debug) { Console.WriteLine("site {0}", site); Log.InfoFormat("site {0}", site); } if (site.Y > SweepLine) { SweepLine = site.Y; } } public void PlotBisector(Edge e) { if (Debug) { Console.WriteLine("bisector {0} {1}", e.Region[Side.Left], e.Region[Side.Right]); Log.InfoFormat("bisector {0} {1}", e.Region[Side.Left], e.Region[Side.Right]); } Edges.Add(e); } public void PlotEndpoint(Edge e) { if (Debug) { Console.WriteLine("EP {0}", e); Log.InfoFormat("EP {0}", e); } ClipLine(e); } public void PlotVertex(Site s) { if (Debug) { Console.WriteLine("vertex {0},{1}", s.X, s.Y); Log.InfoFormat("vertex {0},{1}", s.X, s.Y); } s.New = true; Vertices.Add(s); } public void PlotTriple(Site s1, Site s2, Site s3) { if (Debug) { Console.WriteLine("triple {0} {1} {2}", s1, s2, s3); } var triangle = new Triangle(s1, s2, s3) { New = true }; Triangles.Add(triangle); } public void ResetNewItems() { foreach (var site in Sites) { site.New = false; } foreach (var vertex in Vertices) { vertex.New = false; } foreach (var segment in Segments) { segment.New = false; } foreach (var triangle in Triangles) { triangle.New = false; } } /// <summary> /// Somewhat redundant line clipping routine /// </summary> /// <param name="e"></param> private void ClipLine(Edge e) { var clipped = e.GetClippedEnds(new Rectangle(0, 0, Width, Height)); if (clipped != null) { var site1 = new Site(clipped.Item1); var site2 = new Site(clipped.Item2); var s = new Segment(site1, site2) { New = true }; Segments.Add(s); } } public void EndPoint(Edge edge, Side side, Site site) { edge.Endpoint[side] = site; var opSide = side == Side.Left ? Side.Right : Side.Left; if (edge.Endpoint[opSide] == null) { return; } PlotEndpoint(edge); } } }
using System; using System.Threading.Tasks; using FluentAssertions; namespace CSharpFunctionalExtensions.Tests.ResultTests.Extensions { public abstract class BindIfTestsBase : TestBase { protected bool actionExecuted; protected bool predicateExecuted; protected BindIfTestsBase() { actionExecuted = false; predicateExecuted = false; } protected Func<Result> GetAction(bool isSuccess) { if (!isSuccess) { return FailureAction; } return SuccessAction; } protected Func<Task<Result>> GetAsyncAction(bool isSuccess) { if (!isSuccess) { return () => Task.FromResult(FailureAction()); } return () => Task.FromResult(SuccessAction()); } protected Func<T, Result<T>> GetValueAction(bool isSuccess) { if (!isSuccess) { return FailureValueAction; } return SuccessValueAction; } protected Func<T, Task<Result<T>>> GetAsyncValueAction(bool isSuccess) { if (!isSuccess) { return t => Task.FromResult(FailureValueAction(t)); } return t => Task.FromResult(SuccessValueAction(t)); } protected Func<UnitResult<E>> GetErrorAction(bool isSuccess) { if (!isSuccess) { return FailureErrorAction; } return SuccessErrorAction; } protected Func<Task<UnitResult<E>>> GetAsyncErrorAction(bool isSuccess) { if (!isSuccess) { return () => Task.FromResult(FailureErrorAction()); } return () => Task.FromResult(SuccessErrorAction()); } protected Func<T, Result<T, E>> GetValueErrorAction(bool isSuccess) { if (!isSuccess) { return FailureValueErrorAction; } return SuccessValueErrorAction; } protected Func<T, Task<Result<T, E>>> GetAsyncValueErrorAction(bool isSuccess) { if (!isSuccess) { return t => Task.FromResult(FailureValueErrorAction(t)); } return t => Task.FromResult(SuccessValueErrorAction(t)); } protected Result SuccessAction() { actionExecuted.Should().BeFalse(); actionExecuted = true; return Result.Success(); } protected Result FailureAction() { actionExecuted.Should().BeFalse(); actionExecuted = true; return Result.Failure(ErrorMessage2); } protected Result<T> SuccessValueAction(T value) { actionExecuted.Should().BeFalse(); value.Should().Be(T.Value); actionExecuted = true; return Result.Success(T.Value2); } protected Result<T> FailureValueAction(T value) { actionExecuted.Should().BeFalse(); value.Should().Be(T.Value); actionExecuted = true; return Result.Failure<T>(ErrorMessage2); } protected UnitResult<E> SuccessErrorAction() { actionExecuted.Should().BeFalse(); actionExecuted = true; return UnitResult.Success<E>(); } protected UnitResult<E> FailureErrorAction() { actionExecuted.Should().BeFalse(); actionExecuted = true; return UnitResult.Failure(E.Value2); } protected Result<T, E> SuccessValueErrorAction(T value) { actionExecuted.Should().BeFalse(); value.Should().Be(T.Value); actionExecuted = true; return Result.Success<T, E>(T.Value2); } protected Result<T, E> FailureValueErrorAction(T value) { actionExecuted.Should().BeFalse(); value.Should().Be(T.Value); actionExecuted = true; return Result.Failure<T, E>(E.Value2); } protected Func<bool> GetPredicate(bool value) { return () => { predicateExecuted.Should().BeFalse(); predicateExecuted = true; return value; }; } protected Func<T, bool> GetValuePredicate(bool value) { return t => { predicateExecuted.Should().BeFalse(); t.Should().Be(T.Value); predicateExecuted = true; return value; }; } protected static Result GetExpectedResult(bool isSuccess, bool condition, bool isSuccessAction) { var success = CheckSuccess(isSuccess, condition, isSuccessAction); var resultChanged = isSuccess && condition; return Result.SuccessIf(success, !resultChanged ? ErrorMessage : ErrorMessage2); } protected static Result<T> GetExpectedValueResult(bool isSuccess, bool condition, bool isSuccessAction) { var success = CheckSuccess(isSuccess, condition, isSuccessAction); var resultChanged = isSuccess && condition; if (!resultChanged) { return Result.SuccessIf(success, T.Value, ErrorMessage); } return Result.SuccessIf(success, T.Value2, ErrorMessage2); } protected static UnitResult<E> GetExpectedErrorResult(bool isSuccess, bool condition, bool isSuccessAction) { var success = CheckSuccess(isSuccess, condition, isSuccessAction); var resultChanged = isSuccess && condition; if (!resultChanged) { return UnitResult.SuccessIf(success, E.Value); } return UnitResult.SuccessIf(success, E.Value2); } protected static Result<T, E> GetExpectedValueErrorResult(bool isSuccess, bool condition, bool isSuccessAction) { var success = CheckSuccess(isSuccess, condition, isSuccessAction); var resultChanged = isSuccess && condition; if (!resultChanged) { return Result.SuccessIf(success, T.Value, E.Value); } return Result.SuccessIf(success, T.Value2, E.Value2); } protected static bool CheckSuccess(bool isSuccess, bool condition, bool isSuccessAction) { if (!condition) { return isSuccess; } return isSuccess && isSuccessAction; } } }
// ***************************************************************************** // // (c) Crownwood Consulting Limited 2002 // All rights reserved. The software and associated documentation // supplied hereunder are the proprietary information of Crownwood Consulting // Limited, Haxey, North Lincolnshire, England and are supplied subject to // licence terms. // // IDE Version 1.7 www.dotnetmagic.com // ***************************************************************************** using System; using System.Drawing; namespace IDE.Menus { internal class DrawCommand { // Instance fields protected int _row; protected int _col; protected char _mnemonic; protected bool _enabled; protected bool _subMenu; protected bool _expansion; protected bool _separator; protected bool _vertSeparator; protected bool _chevron; protected bool _topBorder; protected bool _bottomBorder; protected bool _infrequent; protected Rectangle _drawRect; protected Rectangle _selectRect; protected MenuCommand _command; public DrawCommand(Rectangle drawRect) { _row = -1; _col = -1; _mnemonic = '0'; _enabled = true; _subMenu = false; _expansion = false; _separator = false; _vertSeparator = false; _topBorder = false; _bottomBorder = false; _infrequent = false; _chevron = true; _drawRect = drawRect; _selectRect = drawRect; _command = null; } public DrawCommand(Rectangle drawRect, bool expansion) { _row = -1; _col = -1; _mnemonic = '0'; _enabled = true; _subMenu = false; _expansion = expansion; _separator = !expansion; _vertSeparator = !expansion; _topBorder = false; _bottomBorder = false; _infrequent = false; _chevron = false; _drawRect = drawRect; _selectRect = drawRect; _command = null; } public DrawCommand(MenuCommand command, Rectangle drawRect) { InternalConstruct(command, drawRect, drawRect, -1, -1); } public DrawCommand(MenuCommand command, Rectangle drawRect, Rectangle selectRect) { InternalConstruct(command, drawRect, selectRect, -1, -1); } public DrawCommand(MenuCommand command, Rectangle drawRect, int row, int col) { InternalConstruct(command, drawRect, drawRect, row, col); } public void InternalConstruct(MenuCommand command, Rectangle drawRect, Rectangle selectRect, int row, int col) { _row = row; _col = col; _enabled = command.Enabled; _expansion = false; _vertSeparator = false; _drawRect = drawRect; _selectRect = selectRect; _command = command; _topBorder = false; _bottomBorder = false; _infrequent = command.Infrequent; _chevron = false; // Is this MenuCommand a separator? _separator = (_command.Text == "-"); // Does this MenuCommand contain a submenu? _subMenu = (_command.MenuCommands.Count > 0); // Find position of first mnemonic character int position = -1; if (command.Text != null) position = command.Text.IndexOf('&'); // Did we find a mnemonic indicator? if (position != -1) { // Must be a character after the indicator if (position < (command.Text.Length - 1)) { // Remember the character _mnemonic = char.ToUpper(command.Text[position + 1]); } } } public Rectangle DrawRect { get { return _drawRect; } set { _drawRect = value; } } public Rectangle SelectRect { get { return _selectRect; } set { _selectRect = value; } } public MenuCommand MenuCommand { get { return _command; } } public bool Separator { get { return _separator; } } public bool VerticalSeparator { get { return _vertSeparator; } } public bool Expansion { get { return _expansion; } } public bool SubMenu { get { return _subMenu; } } public char Mnemonic { get { return _mnemonic; } } public bool Enabled { get { return _enabled; } } public int Row { get { return _row; } } public int Col { get { return _col; } } public bool Chevron { get { return _chevron; } } public bool TopBorder { get { return _topBorder; } set { _topBorder = value; } } public bool BottomBorder { get { return _bottomBorder; } set { _bottomBorder = value; } } public bool Infrequent { get { return _infrequent; } set { _infrequent = value; } } } }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Collections; using System.Runtime.CompilerServices; using System.Threading; using System.Reflection; using Microsoft.SPOT; //--// namespace Microsoft.SPOT.Hardware { [Serializable()] public class WatchdogException : SystemException { protected WatchdogException() : base() { } } /// <summary> /// Indicates what type of sleep event occurred. /// Invalid - Invalid event /// ChangeRequested - A managed thread has requested the system to go into a sleep state /// WakeUp - The sytem woke up from the a sleep state /// </summary> public enum SleepEventType : byte { Invalid = 0, ChangeRequested = 1, WakeUp = 2, } /// <summary> /// Indicates what type of power event occurred. /// Invalid - Invalid event /// PreNotify - A notification that the indicated power event is about to happen /// PostNotify - A notification that the current power state just changed /// </summary> public enum PowerEventType : byte { Invalid = 0, PreNotify = 1, PostNotify = 2 } /// <summary> /// The SleepEvent object contains information about a sleep event. It is passed to PowerState.OnSleepChange event handlers. /// EventType - Indicates the type of this event (ChangeRequested or WakeUp) /// Level - The new sleep level for this event /// WakeUpEvents - The events (if any) that caused this event. This is only used on the WakeUp event. /// Time - The timestamp of when this event occurred /// </summary> public class SleepEvent : BaseEvent { public SleepEventType EventType; public SleepLevel Level; public HardwareEvent WakeUpEvents; public DateTime Time; } /// <summary> /// The PowerEvent object contains information about a power event. It is passed to PowerState.OnPowerLevelChange event handlers. /// EventType - Indicates the type of this event (PreNotify or PostNotify) /// Level - The new power level introduced by this event /// Time - The timestamp of when this event occurred /// </summary> public class PowerEvent : BaseEvent { public PowerEventType EventType; public PowerLevel Level; public DateTime Time; } internal class PowerStateEventProcessor : IEventProcessor { public BaseEvent ProcessEvent(uint data1, uint data2, DateTime time) { EventCategory ec = (EventCategory)(0xFF & (data1 >> 8)); BaseEvent be = null; if (ec == EventCategory.SleepLevel) { SleepEvent ev = new SleepEvent(); ev.EventType = (SleepEventType)(data1 & 0xFF); // data1 encodes the type in the lower 16 bits and... ev.Level = SleepLevel.Awake; ev.WakeUpEvents = (HardwareEvent)data2; ev.Time = time; be = ev; } else if (ec == EventCategory.PowerLevel) { PowerEvent ev = new PowerEvent(); ev.EventType = PowerEventType.PostNotify; ev.Level = (PowerLevel)data2; ev.Time = time; be = ev; } return be; } } internal class PowerStateEventListener : IEventListener { public void InitializeForEventSource() { } public bool OnEvent(BaseEvent ev) { if (ev is SleepEvent) { PowerState.PostEvent((SleepEvent)ev); } else if (ev is PowerEvent) { PowerState.PostEvent((PowerEvent)ev); } return true; } } //--// /// <summary> /// The event handler delegate for the PowerState.OnSleepChange event. /// </summary> /// <param name="e">The SleepEvent object that contains details about the sleep event</param> public delegate void SleepChangeEventHandler(SleepEvent e); /// <summary> /// The event handler delegate for the PowerState.OnPowerLevelChange event. /// </summary> /// <param name="e">The PowerEvent object that contains information about the power level change event</param> public delegate void PowerLevelChangeEventHandler(PowerEvent e); /// <summary> /// The event handler delegate for the PowerState.OnReboot event. /// </summary> /// <param name="fSoftReboot"></param> public delegate void RebootEventHandler(bool fSoftReboot); //--// /// <summary> /// The SleepLevel enumeration contains the default sleep levels for the .Net Micro Framework. The behavior for each of these /// states is determined by the hardware vendor. The general guideline is that each increased value indicates a deeper sleep. /// Therefore, SelectiveOff might simply dim the display backlight, where as Sleep may turn off the display, and DeepSleep may /// go into a hibernation state. /// </summary> public enum SleepLevel : byte { Awake = 0x00, SelectiveOff = 0x10, Sleep = 0x20, DeepSleep = 0x30, Off = 0x40, } /// <summary> /// The PowerLevel enumeration contains the default power state levels for a .Net Micro Framework device. The behavior for each /// of the levels is determined by the hardware vendor. The general guideline is that each increased value indicates a lower /// power consumption state. This enumeration may also be extended by hardware vendors to include additional PowerLevels. /// </summary> public enum PowerLevel : byte { High = 0x10, Medium = 0x20, Low = 0x30, } /// <summary> /// The HardwareEvent flags allow users to choose which events cause the system to awake from a sleep state. These event can be bitwise OR'ed /// together to produce a set of events. /// /// The SystemTimer event is a timer which is responsible for waking sleeping threads and eventing managed timers. If this event is not /// included in the WakeupEvents property or the wakeupEvents parameter in the Sleep method, then the system will will not wakeup for managed /// timers or thread sleeps. /// /// The GeneralPurpose event flag represents General Purpose Input/Output (GPIO) ports and any number of peripherals that use a GPIO pin as an /// eventing mechanism. These peripherals may include storage devices, touch panels, network devices, etc. /// /// The OEMReserved events can be defined by the Device Manufacturer. /// </summary> [Flags()] public enum HardwareEvent { SerialIn = 0x00000001, SerialOut = 0x00000002, USBIn = 0x00000004, USBOut = 0x00000008, SystemTimer = 0x00000010, Timer1 = 0x00000020, Timer2 = 0x00000040, Socket = 0x00004000, Spi = 0x00008000, Charger = 0x00010000, OEMReserved1 = 0x00020000, OEMReserved2 = 0x00040000, FileSystemIO = 0x00080000, GeneralPurpose = 0x08000000, // GPIO, Touch, Gesture, Storage, Network, etc I2C = 0x10000000, } /// <summary> /// The PowerState class encapsulates the power management functionality of the .Net Micro Framework. It enables the managed /// application to adjust power settings for the device. /// </summary> public static class PowerState { private static PowerLevel s_CurrentPowerLevel = PowerLevel.High; /// <summary> /// This event notifies listeners when a sleep event occurs. The listeners will be notified /// prior to a sleep event and when the system wakes from a sleep. /// </summary> public static event SleepChangeEventHandler OnSleepChange; /// <summary> /// This event notifies listeners when a power level event occurs. /// </summary> public static event PowerLevelChangeEventHandler OnPowerLevelChange; /// <summary> /// This event notifies listeners prior to a device reboot (soft or hard). The event handlers may have an execution /// constraint placed on them by the caller of the Reboot method. Therefore, it is recommended that the event handlers /// be short atomic operations. /// </summary> public static event RebootEventHandler OnRebootEvent; /// <summary> /// The Sleep method puts the device into a sleeps state that is only woken by the events described in the paramter wakeUpEvents. /// Please note that if the event SystemTimer is not used, the system will not be woken up by any managed timers. In addition, /// other threads will not be executed until this sleep call exits. This method raises the OnSleepChange event. /// /// The MaximumTimeToActive property contains the timeout value for this call. /// </summary> /// <param name="level">Determines what level of sleep the system should enter. The behavior of the level is determined /// by the hardware vendor.</param> /// <param name="wakeUpEvents">Determines the events that will cause the system to exit the given sleep level</param> public static void Sleep(SleepLevel level, HardwareEvent wakeUpEvents) { SleepChangeEventHandler h = OnSleepChange; if (h != null) { SleepEvent e = new SleepEvent(); e.EventType = SleepEventType.ChangeRequested; e.Level = level; e.WakeUpEvents = wakeUpEvents; e.Time = DateTime.UtcNow; h(e); } InternalSleep(level, wakeUpEvents); } /// <summary> /// The ChangePowerLevel method enables the caller to adjust the current power level of the device. /// The behavior of the power levels are determined by the hardware vendor. This method raises the /// OnPowerLevelChange event. /// </summary> /// <param name="level">Describes the power level for which the system should enter</param> public static void ChangePowerLevel(PowerLevel level) { if (s_CurrentPowerLevel == level) return; PowerLevelChangeEventHandler h = OnPowerLevelChange; if (h != null) { PowerEvent e = new PowerEvent(); e.EventType = PowerEventType.PreNotify; e.Level = level; e.Time = DateTime.UtcNow; h(e); } InternalChangePowerLevel(level); s_CurrentPowerLevel = level; } /// <summary> /// The RebootDevice method enables the caller to force a soft or hard reboot of the device. /// This method raises the OnRebootEvent. With this method, there are no execution constraints /// placed on the event handlers, so the reboot will only happen after each handler finishes. /// </summary> /// <param name="soft">Determines whether the reboot request is for a soft or hard reboot. Note, /// some devices may not support soft reboot. /// </param> public static void RebootDevice(bool soft) { RebootDevice(soft, -1); } /// <summary> /// The RebootDevice method enables the caller to force a soft or hard reboot of the device. /// This method raises the OnRebootEvent. /// </summary> /// <param name="soft">Determines whether the reboot request is for a soft or hard reboot. Note, /// some devices may not support soft reboot.</param> /// <param name="exeConstraintTimeout_ms">Execution constraint timeout (in milliseconds) for /// the event handlers. If the event handlers take longer than the given value, then /// the handlers will be aborted and the reboot will be executed. /// </param> public static void RebootDevice(bool soft, int exeConstraintTimeout_ms) { try { ExecutionConstraint.Install(exeConstraintTimeout_ms, 4); RebootEventHandler h = OnRebootEvent; if (h != null) { h(soft); } } catch { } finally { Reboot(soft); } } [MethodImplAttribute(MethodImplOptions.InternalCall)] extern internal static void Reboot(bool soft); /// <summary> /// The WaitForIdleCPU method waits for the system to enter an idle state (no active threads). The call /// will return either when the timeout has expired or when the current idle time is greater than or equal /// to the expectedWorkItemDuration parameter (in milliseconds). /// </summary> /// <param name="expectedWorkItemDuration">The amount of idle time required to run the task</param> /// <param name="timeout">The timeout in milliseconds for the system to wait for the appropriate idle time</param> /// <returns> /// Returns true if the current idle time is greater than or equal to the time indicated by exeConstraintTimeout_ms. /// Returns false otherwise. ///</returns> [MethodImplAttribute(MethodImplOptions.InternalCall)] extern static public bool WaitForIdleCPU(int expectedWorkItemDuration, int timeout); /// <summary> /// Gets the current power level of the system. The behavior of the power level is determined by the hardware vendor. /// </summary> /// <returns></returns> public static PowerLevel CurrentPowerLevel { get { return s_CurrentPowerLevel; } } /// <summary> /// Gets and Sets the maximum timeout value for all system sleep calls (including internal system sleep calls). Set /// this property to determine the maximum time the system should sleep before processing non-masked events. /// </summary> extern public static TimeSpan MaximumTimeToActive { [MethodImplAttribute(MethodImplOptions.InternalCall)] get; [MethodImplAttribute(MethodImplOptions.InternalCall)] set; } /// <summary> /// Gets or Sets the default wakeup events for all Thread.Sleep calls and internal system sleep calls. Please note that /// if SystemTimer is not specified for this property, then managed code timers and thread sleeps will not be handled until /// the system wakes up. /// </summary> extern public static HardwareEvent WakeupEvents { [MethodImplAttribute(MethodImplOptions.InternalCall)] get; [MethodImplAttribute(MethodImplOptions.InternalCall)] set; } /// <summary> /// Gets the TimeSpan for which the system has been up and running. /// </summary> extern public static TimeSpan Uptime { [MethodImplAttribute(MethodImplOptions.InternalCall)] get; } //--// static PowerState() { PowerStateEventProcessor psep = new PowerStateEventProcessor(); PowerStateEventListener psel = new PowerStateEventListener(); Microsoft.SPOT.EventSink.AddEventProcessor(EventCategory.SleepLevel, psep); Microsoft.SPOT.EventSink.AddEventListener(EventCategory.SleepLevel, psel); Microsoft.SPOT.EventSink.AddEventProcessor(EventCategory.PowerLevel, psep); Microsoft.SPOT.EventSink.AddEventListener(EventCategory.PowerLevel, psel); } static internal void PostEvent(BaseEvent ev) { Timer messagePseudoThread = new Timer(MessageHandler, ev, 1, Timeout.Infinite); } private static void MessageHandler(object args) { if (args is SleepEvent) { SleepChangeEventHandler h = OnSleepChange; if (h != null) { h((SleepEvent)args); } } else if (args is PowerEvent) { PowerEvent pe = (PowerEvent)args; PowerLevelChangeEventHandler h = OnPowerLevelChange; s_CurrentPowerLevel = pe.Level; if (h != null) { h(pe); } } } [MethodImplAttribute(MethodImplOptions.InternalCall)] extern private static void InternalSleep(SleepLevel level, HardwareEvent wakeUpEvents); [MethodImplAttribute(MethodImplOptions.InternalCall)] extern private static void InternalChangePowerLevel(PowerLevel level); } //--// //--// //--// /// <summary> /// The WatchdogBehavior enumeration lists the different ways in which the system can handle watchdog events. All /// behavior types will attempt to log a watchdog event that can be retrieved with LastOccurrence property on the /// Watchdog class. /// None - Continues execution (may leave the system in a stalled state) /// SoftReboot - Performs a software reboot of the CLR (if the device does not support soft reboot, a hard reboot will occur) /// HardReboot - Performs a hardware reboot of the device /// EnterBooter - Enters the bootloader and waits for commands. /// DebugBreak_Managed - Injects a Watchdog exception into the current managed thread. Note this will only work for native methods that /// take longer than the allotted watchdog timeout. If the system is truly hung then the exception will not be seen. /// DebugBreak_Native - Intended for native debugging (porting kit users). Stops execution at the native level. /// </summary> public enum WatchdogBehavior { None = 0x00000000, SoftReboot = 0x00000001, HardReboot = 0x00000002, EnterBooter = 0x00000003, DebugBreak_Managed = 0x00000004, DebugBreak_Native = 0x00000005, } /// <summary> /// The WatchdogEvent class is the object that is sent during Watchdog events. /// </summary> public class WatchdogEvent { /// <summary> /// The time stamp when the watchdog event occurred. /// </summary> public DateTime WatchdogEventTime; /// <summary> /// The watchdog timeout value when the watchdog event occured. /// </summary> public TimeSpan WatchdogTimeoutValue; /// <summary> /// The offending managed call that was being executed when the watchdog occurred. /// </summary> public MethodInfo OffendingMethod; internal WatchdogEvent(DateTime time, TimeSpan timeout, MethodInfo method) { this.WatchdogEventTime = time; this.WatchdogTimeoutValue = timeout; this.OffendingMethod = method; } } /// <summary> /// The static Watchdog class contains methods that enables managed code to determine the watchdog behavior. /// </summary> public static class Watchdog { /// <summary> /// Gets or sets the enabled state of the watchdog. The watchdog can be turned off if the inter-op method /// takes an indeterminate time. Note, the watchdog does not need to be turned off for managed code becuase /// the interpreter will make sure the watchdog is reset. /// </summary> extern public static bool Enabled { [MethodImplAttribute(MethodImplOptions.InternalCall)] get; [MethodImplAttribute(MethodImplOptions.InternalCall)] set; } /// <summary> /// Gets or sets the timeout value of for the watchdog. Please note that some hardware vendors may /// set bounds and granularity on the timeout value for the watchdog. Please check with the hardware /// vendor for specifications. /// </summary> extern public static TimeSpan Timeout { [MethodImplAttribute(MethodImplOptions.InternalCall)] get; [MethodImplAttribute(MethodImplOptions.InternalCall)] set; } /// <summary> /// Gets or sets the behavior of the watchdog event handler. See description for the WatchdogBehavior enumeration. /// </summary> extern public static WatchdogBehavior Behavior { [MethodImplAttribute(MethodImplOptions.InternalCall)] get; [MethodImplAttribute(MethodImplOptions.InternalCall)] set; } /// <summary> /// Gets the last occurrence of a watchdog event (if one exists). /// </summary> public static WatchdogEvent LastOccurrence { get { DateTime time; TimeSpan timeout; MethodInfo info; if (GetLastOcurrenceDetails(out time, out timeout, out info)) { return new WatchdogEvent(time, timeout, info); } return null; } } /// <summary> /// Gets or sets the ILog interface for watchdog logging. /// </summary> extern public static ILog Log { [MethodImplAttribute(MethodImplOptions.InternalCall)] get; [MethodImplAttribute(MethodImplOptions.InternalCall)] set; } [MethodImplAttribute(MethodImplOptions.InternalCall)] extern private static bool GetLastOcurrenceDetails(out DateTime time, out TimeSpan timeout, out MethodInfo info); } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.EntityFrameworkCore; using Moq; using Xunit; using AutoRenter.Domain.Data; using AutoRenter.Domain.Interfaces; using AutoRenter.Domain.Models; using AutoRenter.Domain.Services.Commands; namespace AutoRenter.Domain.Services.Tests { public class LocationServiceTests : IDisposable { AutoRenterContext context; public LocationServiceTests() { // xUnit.net creates a new instance of the test class for every test that is run. // The constructor and the Dispose method will always be called once for every test. context = TestableContextFactory.GenerateContext(); } public void Dispose() { context.Dispose(); } [Fact] public async void GetAll_ReturnsData() { // arrange ICommandFactory<Location> commandFactory = new CommandFactory<Location>(); var validationServiceMoq = new Mock<IValidationService>(); var vehicleServiceMoq = new Mock<IVehicleService>(); vehicleServiceMoq.Setup(x => x.GetByLocationId(It.IsAny<Guid>())) .ReturnsAsync(() => new Result<IEnumerable<Vehicle>>(ResultCode.NotFound)); var sut = new LocationService(context, commandFactory, vehicleServiceMoq.Object, validationServiceMoq.Object); // act var result = await sut.GetAll(); // assert Assert.NotEmpty(result.Data); } [Fact] public async void GetAll_WhenNotFoundReturnsNotFound() { // arrange var allLocation = await context.Set<Location>().ToListAsync(); ICommandFactory<Location> commandFactory = new CommandFactory<Location>(); var validationServiceMoq = new Mock<IValidationService>(); var vehicleServiceMoq = new Mock<IVehicleService>(); vehicleServiceMoq.Setup(x => x.GetByLocationId(It.IsAny<Guid>())) .ReturnsAsync(() => new Result<IEnumerable<Vehicle>>(ResultCode.NotFound)); var sut = new LocationService(context, commandFactory, vehicleServiceMoq.Object, validationServiceMoq.Object); context.Locations.RemoveRange(allLocation); await context.SaveChangesAsync(); // act var result = await sut.GetAll(); // assert Assert.Equal(ResultCode.NotFound, result.ResultCode); } [Fact] public async void Get_ReturnsData() { // arrange var targetId = context.Locations.FirstOrDefault().Id; ICommandFactory<Location> commandFactory = new CommandFactory<Location>(); var validationServiceMoq = new Mock<IValidationService>(); var vehicleServiceMoq = new Mock<IVehicleService>(); vehicleServiceMoq.Setup(x => x.GetByLocationId(It.IsAny<Guid>())) .ReturnsAsync(() => new Result<IEnumerable<Vehicle>>(ResultCode.NotFound)); var sut = new LocationService(context, commandFactory, vehicleServiceMoq.Object, validationServiceMoq.Object); // act var result = await sut.Get(targetId); // assert Assert.NotNull(result.Data); } [Fact] public async void Get_WhenNotFoundReturnsNotFound() { // arrange var targetId = context.Locations.FirstOrDefault().Id; var targetEntity = await context.FindAsync<Location>(targetId); ICommandFactory<Location> commandFactory = new CommandFactory<Location>(); var validationServiceMoq = new Mock<IValidationService>(); var vehicleServiceMoq = new Mock<IVehicleService>(); vehicleServiceMoq.Setup(x => x.GetByLocationId(It.IsAny<Guid>())) .ReturnsAsync(() => new Result<IEnumerable<Vehicle>>(ResultCode.NotFound)); var sut = new LocationService(context, commandFactory, vehicleServiceMoq.Object, validationServiceMoq.Object); var removeResult = context.Remove(targetEntity); await context.SaveChangesAsync(); // act var result = await sut.Get(targetId); // assert Assert.Equal(ResultCode.NotFound, result.ResultCode); } [Fact] public async void Insert_Succeeds() { // arrange var location = context.Locations.First(); ICommandFactory<Location> commandFactory = new CommandFactory<Location>(); var validationServiceMoq = new Mock<IValidationService>(); validationServiceMoq.Setup(x => x.IsValidInsert(It.IsAny<Location>())) .ReturnsAsync(() => true); var vehicleServiceMoq = new Mock<IVehicleService>(); var sut = new LocationService(context, commandFactory, vehicleServiceMoq.Object, validationServiceMoq.Object); context.Locations.Remove(location); await context.SaveChangesAsync(); // act var result = await sut.Insert(location); // assert Assert.Equal(ResultCode.Success, result.ResultCode); } [Fact] public async void Insert_WhenDuplicateReturnsConflict() { // arrange var location = context.Locations.First(); ICommandFactory<Location> commandFactory = new CommandFactory<Location>(); var vehicleServiceMoq = new Mock<IVehicleService>(); var validationServiceMoq = new Mock<IValidationService>(); validationServiceMoq.Setup(x => x.IsValidInsert(It.IsAny<Location>())) .ReturnsAsync(() => true); var sut = new LocationService(context, commandFactory, vehicleServiceMoq.Object, validationServiceMoq.Object); // act var result = await sut.Insert(location); // assert Assert.Equal(ResultCode.Conflict, result.ResultCode); } [Fact] public async void Insert_ReturnsId() { // arrange var location = context.Locations.First(); ICommandFactory<Location> commandFactory = new CommandFactory<Location>(); var vehicleServiceMoq = new Mock<IVehicleService>(); var validationServiceMoq = new Mock<IValidationService>(); validationServiceMoq.Setup(x => x.IsValidInsert(It.IsAny<Location>())) .ReturnsAsync(() => true); var sut = new LocationService(context, commandFactory, vehicleServiceMoq.Object, validationServiceMoq.Object); context.Locations.Remove(location); await context.SaveChangesAsync(); // act var result = await sut.Insert(location); // assert Assert.NotEqual(Guid.Empty, result.Data); } [Fact] public async void Insert_InvalidReturnsBadRequest() { // arrange var location = context.Locations.First(); ICommandFactory<Location> commandFactory = new CommandFactory<Location>(); var vehicleServiceMoq = new Mock<IVehicleService>(); var validationServiceMoq = new Mock<IValidationService>(); validationServiceMoq.Setup(x => x.IsValidInsert(It.IsAny<Location>())) .ReturnsAsync(() => false); var sut = new LocationService(context, commandFactory, vehicleServiceMoq.Object, validationServiceMoq.Object); context.Locations.Remove(location); await context.SaveChangesAsync(); // act var result = await sut.Insert(location); // assert Assert.Equal(ResultCode.BadRequest, result.ResultCode); } [Fact] public async void Update_Succeeds() { // arrange var location = context.Locations.First(); location.City = "New Orleans"; ICommandFactory<Location> commandFactory = new CommandFactory<Location>(); var vehicleServiceMoq = new Mock<IVehicleService>(); var validationServiceMoq = new Mock<IValidationService>(); validationServiceMoq.Setup(x => x.IsValidUpdate(It.IsAny<Location>())) .ReturnsAsync(() => true); var sut = new LocationService(context, commandFactory, vehicleServiceMoq.Object, validationServiceMoq.Object); // act var result = await sut.Update(location); // assert Assert.Equal(ResultCode.Success, result.ResultCode); } [Fact] public async void Update_ReturnsId() { // arrange var location = context.Locations.First(); location.City = "New Orleans"; ICommandFactory<Location> commandFactory = new CommandFactory<Location>(); var vehicleServiceMoq = new Mock<IVehicleService>(); var validationServiceMoq = new Mock<IValidationService>(); validationServiceMoq.Setup(x => x.IsValidUpdate(It.IsAny<Location>())) .ReturnsAsync(() => true); var sut = new LocationService(context, commandFactory, vehicleServiceMoq.Object, validationServiceMoq.Object); // act var result = await sut.Update(location); // assert Assert.NotEqual(Guid.Empty, result.Data); } [Fact] public async void Update_InvalidReturnsBadRequest() { // arrange var location = context.Locations.First(); location.City = "New Orleans"; ICommandFactory<Location> commandFactory = new CommandFactory<Location>(); var vehicleServiceMoq = new Mock<IVehicleService>(); var validationServiceMoq = new Mock<IValidationService>(); validationServiceMoq.Setup(x => x.IsValidUpdate(It.IsAny<Location>())) .ReturnsAsync(() => false); var sut = new LocationService(context, commandFactory, vehicleServiceMoq.Object, validationServiceMoq.Object); // act var result = await sut.Insert(location); // assert Assert.Equal(ResultCode.BadRequest, result.ResultCode); } [Fact] public async void Delete_Succeeds() { // arrange var location = context.Locations.First(); ICommandFactory<Location> commandFactory = new CommandFactory<Location>(); var vehicleServiceMoq = new Mock<IVehicleService>(); var validationServiceMoq = new Mock<IValidationService>(); validationServiceMoq.Setup(x => x.IsValidDelete(It.IsAny<Location>())) .ReturnsAsync(() => true); var sut = new LocationService(context, commandFactory, vehicleServiceMoq.Object, validationServiceMoq.Object); // act var result = await sut.Delete(location.Id); // assert Assert.Equal(ResultCode.Success, result); } [Fact] public async void Delete_NotFoundWhenNotFound() { // arrange var location = context.Locations.First(); ICommandFactory<Location> commandFactory = new CommandFactory<Location>(); var vehicleServiceMoq = new Mock<IVehicleService>(); var validationServiceMoq = new Mock<IValidationService>(); validationServiceMoq.Setup(x => x.IsValidDelete(It.IsAny<Location>())) .ReturnsAsync(() => true); var sut = new LocationService(context, commandFactory, vehicleServiceMoq.Object, validationServiceMoq.Object); context.Locations.Remove(location); await context.SaveChangesAsync(); // act var result = await sut.Delete(location.Id); // assert Assert.Equal(ResultCode.NotFound, result); } [Fact] public async void Delete_InvalidReturnsBadRequest() { // arrange var location = context.Locations.First(); ICommandFactory<Location> commandFactory = new CommandFactory<Location>(); var vehicleServiceMoq = new Mock<IVehicleService>(); var validationServiceMoq = new Mock<IValidationService>(); validationServiceMoq.Setup(x => x.IsValidDelete(It.IsAny<Location>())) .ReturnsAsync(() => false); var sut = new LocationService(context, commandFactory, vehicleServiceMoq.Object, validationServiceMoq.Object); // act var result = await sut.Delete(location.Id); // assert Assert.Equal(ResultCode.BadRequest, result); } [Fact] public async void AddVehicle_NewSucceeds() { // arrange var location = context.Locations.First(); var vehicle = context.Vehicles.FirstOrDefault(x => x.LocationId == location.Id); vehicle.LocationId = Guid.Empty; context.SaveChanges(); var vehicles = context.Vehicles.Where(x => x.LocationId == location.Id && x.Id != vehicle.Id); ICommandFactory<Location> commandFactory = new CommandFactory<Location>(); var validationServiceMoq = new Mock<IValidationService>(); var vehicleServiceMoq = new Mock<IVehicleService>(); vehicleServiceMoq.Setup(x => x.GetByLocationId(It.IsAny<Guid>())) .ReturnsAsync(() => new Result<IEnumerable<Vehicle>>(ResultCode.Success, vehicles)); vehicleServiceMoq.Setup(x => x.Get(It.IsAny<Guid>())) .ReturnsAsync(() => new Result<Vehicle>(ResultCode.Success, vehicle)); vehicleServiceMoq.Setup(x => x.Insert(It.IsAny<Vehicle>())) .ReturnsAsync(() => new Result<Guid>(ResultCode.Success, vehicle.Id)); var sut = new LocationService(context, commandFactory, vehicleServiceMoq.Object, validationServiceMoq.Object); location.Vehicles.Remove(vehicle); await context.SaveChangesAsync(); // act var result = await sut.AddVehicle(location.Id, vehicle); // assert Assert.Equal(ResultCode.Success, result.ResultCode); } [Fact] public async void AddVehicle_NotFoundWhenLocationNotFound() { // arrange var location = context.Locations.First(); var vehicle = location.Vehicles.First(); ICommandFactory<Location> commandFactory = new CommandFactory<Location>(); var validationServiceMoq = new Mock<IValidationService>(); var vehicleServiceMoq = new Mock<IVehicleService>(); vehicleServiceMoq.Setup(x => x.GetByLocationId(It.IsAny<Guid>())) .ReturnsAsync(() => new Result<IEnumerable<Vehicle>>(ResultCode.NotFound)); var sut = new LocationService(context, commandFactory, vehicleServiceMoq.Object, validationServiceMoq.Object); location.Vehicles.Remove(vehicle); await context.SaveChangesAsync(); // act var result = await sut.AddVehicle(Guid.NewGuid(), vehicle); // assert Assert.Equal(ResultCode.NotFound, result.ResultCode); } [Fact] public async void AddVehicle_ConflictWhenDuplicate() { // arrange var location = context.Locations.First(); var vehicle = location.Vehicles.First(); ICommandFactory<Location> commandFactory = new CommandFactory<Location>(); var validationServiceMoq = new Mock<IValidationService>(); var vehicleServiceMoq = new Mock<IVehicleService>(); vehicleServiceMoq.Setup(x => x.GetByLocationId(It.IsAny<Guid>())) .ReturnsAsync(() => new Result<IEnumerable<Vehicle>>(ResultCode.Success, new[] { vehicle })); var sut = new LocationService(context, commandFactory, vehicleServiceMoq.Object, validationServiceMoq.Object); // act var result = await sut.AddVehicle(location.Id, vehicle); // assert Assert.Equal(ResultCode.Conflict, result.ResultCode); } [Fact] public async void GetVehicles_Succeeds() { // arrange var location = context.Locations.First(); ICommandFactory<Location> commandFactory = new CommandFactory<Location>(); var validationServiceMoq = new Mock<IValidationService>(); var vehicleServiceMoq = new Mock<IVehicleService>(); vehicleServiceMoq.Setup(x => x.GetByLocationId(It.IsAny<Guid>())) .ReturnsAsync(() => new Result<IEnumerable<Vehicle>>(ResultCode.Success, location.Vehicles)); var sut = new LocationService(context, commandFactory, vehicleServiceMoq.Object, validationServiceMoq.Object); // act var result = await sut.GetVehicles(location.Id); // assert Assert.Equal(ResultCode.Success, result.ResultCode); } [Fact] public async void GetVehicles_ReturnsVehicles() { // arrange var location = context.Locations.First(); ICommandFactory<Location> commandFactory = new CommandFactory<Location>(); var validationServiceMoq = new Mock<IValidationService>(); var vehicleServiceMoq = new Mock<IVehicleService>(); vehicleServiceMoq.Setup(x => x.GetByLocationId(It.IsAny<Guid>())) .ReturnsAsync(() => new Result<IEnumerable<Vehicle>>(ResultCode.Success, location.Vehicles)); var sut = new LocationService(context, commandFactory, vehicleServiceMoq.Object, validationServiceMoq.Object); // act var result = await sut.GetVehicles(location.Id); // assert Assert.NotEmpty(result.Data); } [Fact] public async void GetVehicles_InvalidLocationReturnsNotFound() { // arrange var location = context.Locations.First(); ICommandFactory<Location> commandFactory = new CommandFactory<Location>(); var validationServiceMoq = new Mock<IValidationService>(); var vehicleServiceMoq = new Mock<IVehicleService>(); vehicleServiceMoq.Setup(x => x.GetByLocationId(It.IsAny<Guid>())) .ReturnsAsync(() => new Result<IEnumerable<Vehicle>>(ResultCode.NotFound)); var sut = new LocationService(context, commandFactory, vehicleServiceMoq.Object, validationServiceMoq.Object); // act var result = await sut.GetVehicles(Guid.NewGuid()); // assert Assert.Equal(ResultCode.NotFound, result.ResultCode); } } }
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; #if UNITY_EDITOR using UnityEditor; using System.IO; using System.Linq; using Uni2DTextureImporterSettingsPair = System.Collections.Generic.KeyValuePair<UnityEngine.Texture2D, UnityEditor.TextureImporterSettings>; #endif // Texture Atlas [AddComponentMenu("Uni2D/Sprite/Uni2DTextureAtlas")] public class Uni2DTextureAtlas : MonoBehaviour { // Atlas size public enum AtlasSize { _2 = 2, _4 = 4, _8 = 8, _16 = 16, _32 = 32, _64 = 64, _128 = 128, _256 = 256, _512 = 512, _1024 = 1024, _2048 = 2048, _4096 = 4096, } // Atlas entry [Serializable] private class AtlasEntry { [SerializeField] private Texture2D m_rAtlasTexture = null; [SerializeField] private Material m_rAtlasMaterial = null; [SerializeField] private string[ ] m_rAtlasedTextureGUIDs = null; [SerializeField] private PackedRect[ ] m_rUVs = null; public Material material { get { return m_rAtlasMaterial; } } public Texture2D atlasTexture { get { return m_rAtlasTexture; } } public string[ ] atlasedTextureGUIDs { get { return m_rAtlasedTextureGUIDs; } } public AtlasEntry( Texture2D a_rAtlasTexture, Material a_rAtlasMaterial, string[ ] a_rTextureGUIDs, PackedRect[ ] a_rUVs ) { m_rAtlasTexture = a_rAtlasTexture; m_rAtlasMaterial = a_rAtlasMaterial; m_rAtlasedTextureGUIDs = a_rTextureGUIDs; m_rUVs = a_rUVs; } public bool Contains( string a_rTextureGUID ) { if( m_rAtlasedTextureGUIDs != null ) { int iGUIDCount = m_rAtlasedTextureGUIDs.Length; for( int iGUIDIndex = 0; iGUIDIndex < iGUIDCount; ++iGUIDIndex ) { if( m_rAtlasedTextureGUIDs[ iGUIDIndex ] == a_rTextureGUID ) { return true; } } } return false; } public bool GetUVs( string a_rTextureGUID, out Rect a_rUVs, out bool a_bIsFlipped ) { if( m_rAtlasedTextureGUIDs != null && m_rUVs != null ) { int iGUIDCount = m_rAtlasedTextureGUIDs.Length; for( int iGUIDIndex = 0; iGUIDIndex < iGUIDCount; ++iGUIDIndex ) { if( m_rAtlasedTextureGUIDs[ iGUIDIndex ] == a_rTextureGUID ) { a_bIsFlipped = m_rUVs[ iGUIDIndex ].isFlipped; a_rUVs = m_rUVs[ iGUIDIndex ].rect; return true; } } } a_bIsFlipped = false; a_rUVs = new Rect( 0.0f, 0.0f, 1.0f, 1.0f ); return false; } } // Inspector settings // The inspector texture field public Texture2DContainer[ ] textures = new Texture2DContainer[ 0 ]; // Padding public int padding = 1; // Maximum atlas size public AtlasSize maximumAtlasSize = (AtlasSize) 2048; // Base material public Material materialOverride = null; // Generated Data [HideInInspector] [SerializeField] private AtlasEntry[ ] m_oAtlasEntries = null; private Dictionary<string, AtlasEntry> m_oTextureGUIDAtlasEntriesDict = null; // The generation id [HideInInspector] public string generationId = ""; // Parameters // The textures [SerializeField] [HideInInspector] private Texture2DContainer[ ] m_rTextureContainers = new Texture2DContainer[ 0 ]; // Disable unused var #pragma warning disable 414 // Padding [HideInInspector] [SerializeField] private int m_iPadding = 1; // Maximum atlas size [SerializeField] [HideInInspector] private AtlasSize m_eMaximumAtlasSize = (AtlasSize) 2048; #pragma warning restore 414 private Dictionary<string, AtlasEntry> TextureGUIDAtlasEntriesDict { get { if( m_oTextureGUIDAtlasEntriesDict == null ) { RebuildDict( ); } return m_oTextureGUIDAtlasEntriesDict; } } public bool Contains( IEnumerable<string> a_rTextureGUIDs ) { foreach( string rTextureGUID in a_rTextureGUIDs ) { if( !this.Contains( rTextureGUID ) ) { return false; } } return true; } // Contains the texture ? public bool Contains( string a_rTextureGUID ) { Dictionary<string,AtlasEntry> rDict = this.TextureGUIDAtlasEntriesDict; return a_rTextureGUID != null && rDict.ContainsKey( a_rTextureGUID ); } // Returns the atlas material for the given texture public Material GetMaterial( string a_rTextureGUID ) { AtlasEntry rAtlasEntry; Dictionary<string, AtlasEntry> rDict = this.TextureGUIDAtlasEntriesDict; if( a_rTextureGUID != null && rDict.TryGetValue( a_rTextureGUID, out rAtlasEntry ) ) { return rAtlasEntry.material; } else { return null; } } // Returns the atlas texture for the given texture public Texture2D GetAtlasTexture( string a_rTextureGUID ) { AtlasEntry rAtlasEntry; Dictionary<string, AtlasEntry> rDict = this.TextureGUIDAtlasEntriesDict; if( a_rTextureGUID != null && rDict.TryGetValue( a_rTextureGUID, out rAtlasEntry ) ) { return rAtlasEntry.atlasTexture; } else { return null; } } // Returns the texture UVs in the atlas public bool GetUVs( string a_rTextureGUID, out Rect a_rUVs, out bool a_bIsFlipped ) { AtlasEntry rAtlasEntry; Dictionary<string, AtlasEntry> rDict = this.TextureGUIDAtlasEntriesDict; if( a_rTextureGUID != null && rDict.TryGetValue( a_rTextureGUID, out rAtlasEntry ) ) { return rAtlasEntry.GetUVs( a_rTextureGUID, out a_rUVs, out a_bIsFlipped ); } else { a_bIsFlipped = false; a_rUVs = new Rect( 0.0f, 0.0f, 1.0f, 1.0f ); return false; } } #if UNITY_EDITOR public void AddTextures( IEnumerable<string> a_rTextureGUIDs ) { if( a_rTextureGUIDs != null ) { HashSet<Texture2DContainer> oTextureContainers = new HashSet<Texture2DContainer>( this.textures ); //List<Texture2DContainer> oTextureContainers = new List<Texture2DContainer>( this.textures ); foreach( string rTextureGUID in a_rTextureGUIDs ) { if( !string.IsNullOrEmpty( rTextureGUID ) ) { oTextureContainers.Add( new Texture2DContainer( rTextureGUID, false ) ); } } this.textures = oTextureContainers.ToArray( ); EditorUtility.SetDirty( this ); } } public bool GetUVs( Texture2D a_rTexture, out Rect a_rUVs, out bool a_bIsFlipped ) { return this.GetUVs( Uni2DEditorUtils.GetUnityAssetGUID( a_rTexture ), out a_rUVs, out a_bIsFlipped ); } public bool Contains( Texture2D a_rTexture ) { return this.Contains( Uni2DEditorUtils.GetUnityAssetGUID( a_rTexture ) ); } public Material GetMaterial( Texture2D a_rTexture ) { return this.GetMaterial( Uni2DEditorUtils.GetUnityAssetGUID( a_rTexture ) ); } public Texture2D GetAtlasTexture( Texture2D a_rTexture ) { return this.GetAtlasTexture( Uni2DEditorUtils.GetUnityAssetGUID( a_rTexture ) ); } // Unapplied Settings? public bool UnappliedSettings { get { if( m_eMaximumAtlasSize != maximumAtlasSize || m_iPadding != padding || m_rTextureContainers.Length != textures.Length ) { return true; } else { int iTextureIndex = 0; foreach( Texture2DContainer rTextureContainer in m_rTextureContainers ) { if( rTextureContainer != textures[ iTextureIndex ] ) { return true; } ++iTextureIndex; } } return false; } } // Removes duplicates and empty containers private Texture2DContainer[ ] SanitizeInputTextures( Texture2DContainer[ ] a_rTextureContainers ) { int iUniqueTextureContainerCount = 0; int iTextureContainerCount = a_rTextureContainers.Length; List<Texture2DContainer> oUniqueTextureContainersList = new List<Texture2DContainer>( iTextureContainerCount ); // Iterate all texture containers... for( int iTextureContainerIndex = 0; iTextureContainerIndex < iTextureContainerCount; ++iTextureContainerIndex ) { Texture2DContainer rTextureContainer = a_rTextureContainers[ iTextureContainerIndex ]; // if not null and pointing to an existing texture (== not empty)... if( rTextureContainer != null && !string.IsNullOrEmpty( rTextureContainer.GUID ) && rTextureContainer.Texture != null ) { bool bIsDuplicate = false; // Look for duplicates for( int iUniqueTextureContainerIndex = 0; !bIsDuplicate && iUniqueTextureContainerIndex < iUniqueTextureContainerCount; ++iUniqueTextureContainerIndex ) { bIsDuplicate = rTextureContainer.GUID == oUniqueTextureContainersList[ iUniqueTextureContainerIndex ].GUID; } // No duplicate => add to list if( !bIsDuplicate ) { oUniqueTextureContainersList.Add( rTextureContainer ); ++iUniqueTextureContainerCount; } } } // List -> array return oUniqueTextureContainersList.ToArray( ); } // Apply settings public bool ApplySettings( bool a_bUpdateSprites = true ) { bool bSuccess; Uni2DAssetPostprocessor.Enabled = false; { int iContainerCount = textures.Length; Texture2D[ ] oTexturesToPack = new Texture2D[ iContainerCount ]; for( int iContainerIndex = 0; iContainerIndex < iContainerCount; ++iContainerIndex ) { oTexturesToPack[ iContainerIndex ] = textures[ iContainerIndex ].Texture; } List<Uni2DTextureImporterSettingsPair> rTextureImporterSettings = Uni2DEditorSpriteBuilderUtils.TexturesProcessingBegin( oTexturesToPack ); oTexturesToPack = null; // Look if the atlas is set properly regarding to texture sizes int iOversizedTextures = this.LookForOversizedTextures( textures, padding, maximumAtlasSize ); if( iOversizedTextures == 0 ) { textures = this.SanitizeInputTextures( textures ); iContainerCount = textures.Length; string rAtlasGUID = Uni2DEditorUtils.GetUnityAssetGUID( this ); Uni2DEditorAssetTable rAssetTable = Uni2DEditorAssetTable.Instance; for( int iTextureIndex = 0, iTextureCount = m_rTextureContainers.Length; iTextureIndex < iTextureCount; ++iTextureIndex ) { rAssetTable.RemoveAtlasUsingTexture( rAtlasGUID, m_rTextureContainers[ iTextureIndex ].GUID ); } m_rTextureContainers = new Texture2DContainer[ iContainerCount ]; // Deep copy for( int iContainerIndex = 0; iContainerIndex < iContainerCount; ++iContainerIndex ) { Texture2DContainer oTextureContainer = new Texture2DContainer( textures[ iContainerIndex ] ); m_rTextureContainers[ iContainerIndex ] = oTextureContainer; rAssetTable.AddAtlasUsingTexture( rAtlasGUID, oTextureContainer.GUID ); } rAssetTable.Save( ); m_iPadding = padding; m_eMaximumAtlasSize = maximumAtlasSize; bSuccess = Generate( ); if( a_bUpdateSprites ) { Uni2DEditorSpriteBuilderUtils.UpdateSpriteInCurrentSceneAndResourcesAccordinglyToAtlasChange( this ); } } else // Some textures can't fit { bSuccess = false; Debug.LogWarning( "Uni2D could not regenerate atlas '" + ( this.gameObject.name ) + "' properly: " + iOversizedTextures + " texture" + ( iOversizedTextures > 1 ? "s are" : " is" ) + " too large to fit in the atlas.", this.gameObject ); } Uni2DEditorSpriteBuilderUtils.TexturesProcessingEnd( rTextureImporterSettings ); } Uni2DAssetPostprocessor.Enabled = true; EditorUtility.UnloadUnusedAssets( ); return bSuccess; } // Revert settings public void RevertSettings( ) { int iContainerCount = m_rTextureContainers != null ? m_rTextureContainers.Length : 0; textures = new Texture2DContainer[ iContainerCount ]; // Deep copy for( int iContainerIndex = 0; iContainerIndex < iContainerCount; ++iContainerIndex ) { textures[ iContainerIndex ] = new Texture2DContainer( m_rTextureContainers[ iContainerIndex ] ); } padding = m_iPadding; maximumAtlasSize = m_eMaximumAtlasSize; EditorUtility.SetDirty( this ); } // On texture change public void OnTextureChange( ) { this.ApplySettings( false ); } // Generate public bool Generate( ) { // Make sure the data directory exist string oGeneratedDataPathLocal = Uni2DEditorUtils.GetLocalAssetFolderPath(gameObject) + gameObject.name + "_GeneratedData" + "/"; string oGeneratedDataPathGlobal = Uni2DEditorUtils.LocalToGlobalAssetPath(oGeneratedDataPathLocal); if(!Directory.Exists(oGeneratedDataPathGlobal)) { Directory.CreateDirectory(oGeneratedDataPathGlobal); } // Generate data! bool bSuccess = GenerateAtlasData( oGeneratedDataPathLocal ); generationId = System.Guid.NewGuid( ).ToString( ); EditorUtility.SetDirty( this ); AssetDatabase.SaveAssets( ); return bSuccess; } // Generates enough atlases to contain all given textures private bool GenerateAtlasData( string a_oGeneratedDataPathLocal ) { // Build texture rects dict int iTexturesCount = m_rTextureContainers.Length; Dictionary<int,Rect> oRectsDict = new Dictionary<int,Rect>( iTexturesCount ); for( int iTextureIndex = 0; iTextureIndex < iTexturesCount; ++iTextureIndex ) { if( m_rTextureContainers[ iTextureIndex ] != null ) { Texture2D rTexture = m_rTextureContainers[ iTextureIndex ]; if( rTexture != null ) { oRectsDict.Add( iTextureIndex, new Rect( 0.0f, 0.0f, rTexture.width, rTexture.height ) ); } } } bool bSuccess = false; int iAtlasCounter = 0; int iRectCount = oRectsDict.Count; List<AtlasEntry> oAtlasEntriesList = new List<AtlasEntry>( ); try { while( iRectCount > 0 ) // if there's remaining rects to pack { // Progress bar EditorUtility.DisplayProgressBar( "Uni2D Texture Atlasing", "Processing... " + iRectCount + " tex. remaining, " + iAtlasCounter + " atlas(es) created so far.", 1.0f - iRectCount / (float) m_rTextureContainers.Length ); int iAtlasWidth; int iAtlasHeight; Dictionary<int,PackedRect> oTextureIndexPackedUVRectsDict; // Pack textures the most as possible this.PackUVRects( ref oRectsDict, out oTextureIndexPackedUVRectsDict, out iAtlasWidth, out iAtlasHeight ); // Copy the atlased textures pixels into an atlas texture Texture2D oAtlasTexture = this.GenerateAtlasTexture( oTextureIndexPackedUVRectsDict, iAtlasWidth, iAtlasHeight ); // The packer did not success to pack the textures: the atlas seems too small if( oTextureIndexPackedUVRectsDict == null || oTextureIndexPackedUVRectsDict.Count == 0 ) { Debug.LogWarning( "Uni2D atlas '" + this.gameObject.name + "' could not pack all the specified textures.\n" + "Please check the maximum allowed atlas size and the input textures.", this.gameObject ); break; } // Add atlas entry oAtlasEntriesList.Add( this.GenerateAtlasEntry( iAtlasCounter, oAtlasTexture, oTextureIndexPackedUVRectsDict, a_oGeneratedDataPathLocal ) ); // Clean oTextureIndexPackedUVRectsDict = null; // Increment atlas counter iRectCount = oRectsDict.Count; ++iAtlasCounter; } bSuccess = iRectCount <= 0; } finally { // Clean exceeding atlas assets (material/texture) EditorUtility.DisplayProgressBar( "Uni2D Texture Atlasing", "Cleaning exceeding atlas assets...", 1.0f ); int iAtlasEntryCount = m_oAtlasEntries != null ? m_oAtlasEntries.Length : 0; for( int iEntryIndex = iAtlasCounter; iEntryIndex < iAtlasEntryCount; ++iEntryIndex ) { Material rEntryMaterial = m_oAtlasEntries[ iEntryIndex ].material; Texture2D rEntryTexture = m_oAtlasEntries[ iEntryIndex ].atlasTexture; if( rEntryMaterial != null ) { AssetDatabase.DeleteAsset( AssetDatabase.GetAssetPath( rEntryMaterial ) ); } if( rEntryTexture != null ) { AssetDatabase.DeleteAsset( AssetDatabase.GetAssetPath( rEntryTexture ) ); } } // List -> array m_oAtlasEntries = oAtlasEntriesList.ToArray( ); // Rebuild dict with final GUID/atlas entries lists this.RebuildDict( ); // Clean oAtlasEntriesList = null; oRectsDict = null; EditorUtility.ClearProgressBar( ); } return bSuccess; } // Generate atlas materials private Material GenerateAtlasMaterial( int a_iEntryIndex, Material a_rCurrentAtlasMaterial, Texture2D a_rAtlasTexture, string a_oGeneratedDataPathLocal ) { bool bNewMaterial = false; Material rAtlasMaterial = a_rCurrentAtlasMaterial; // Create material if( a_rCurrentAtlasMaterial == null ) { // Clone base material rAtlasMaterial = this.materialOverride != null ? new Material( this.materialOverride ) : new Material( Shader.Find( Uni2DEditorSpriteBuilderUtils.mc_oSpriteDefaultShader ) ); bNewMaterial = true; } else { string oFolderPathLocal = Uni2DEditorUtils.GetLocalAssetFolderPath(a_rCurrentAtlasMaterial); if(oFolderPathLocal != a_oGeneratedDataPathLocal) { // Duplicate rAtlasMaterial = new Material(a_rCurrentAtlasMaterial); bNewMaterial = true; } } // If we have created a new material if(bNewMaterial) { rAtlasMaterial.name = gameObject.name + "_AtlasMaterial" + a_iEntryIndex; string oMaterialPathLocal = a_oGeneratedDataPathLocal + rAtlasMaterial.name + ".mat"; // Ensure the material can be created Material rMaterialAtWantedPath = AssetDatabase.LoadAssetAtPath(oMaterialPathLocal, typeof(Texture2D)) as Material; if(rMaterialAtWantedPath != null) { // Todo_Sev : ask user before deletion? AssetDatabase.DeleteAsset(oMaterialPathLocal); } // Create material AssetDatabase.CreateAsset(rAtlasMaterial, oMaterialPathLocal); } // Assign the atlas texture rAtlasMaterial.mainTexture = a_rAtlasTexture; return rAtlasMaterial; } private void PackUVRects( ref Dictionary<int, Rect> a_rRectsToPackDict, out Dictionary<int, PackedRect> a_rPackedUVRectsDict, out int a_iAtlasWidth, out int a_iAtlasHeight ) { bool bAllPacked; int iMaximumAtlasSize = (int) m_eMaximumAtlasSize; // Estimate atlas size for this loop Uni2DEditorTextureAtlasPacker.EstimateMinAtlasSize( a_rRectsToPackDict.Values, iMaximumAtlasSize, m_iPadding, out a_iAtlasWidth, out a_iAtlasHeight ); Dictionary<int, Rect> oRectsToPackCopyDict = null; Uni2DEditorTextureAtlasPacker oPacker = new Uni2DEditorTextureAtlasPacker( a_iAtlasWidth, a_iAtlasHeight, m_iPadding, true ); // Looking for best atlas size // Save infos about the best size we'll found Vector2 f2BestSize = new Vector2( a_iAtlasWidth, a_iAtlasHeight ); Dictionary<int, PackedRect> rBestResultsOutput = null; Dictionary<int, Rect> rBestResultsInput = null; float fBestOccupancy = float.NegativeInfinity; // Breadth-first search data Queue<Vector2> oNextSizesToTest = new Queue<Vector2>( ); oNextSizesToTest.Enqueue( f2BestSize ); while( oNextSizesToTest.Count != 0 ) { Vector2 f2AtlasSize = oNextSizesToTest.Dequeue( ); // Create a working copy of the input dictionary oRectsToPackCopyDict = new Dictionary<int, Rect>( a_rRectsToPackDict ); // Reinit bin packer oPacker.Init( (int) f2AtlasSize.x, (int) f2AtlasSize.y, m_iPadding, true ); // Pack the most as possible with BSSF heuristic bAllPacked = oPacker.Insert( oRectsToPackCopyDict, Uni2DEditorTextureAtlasPacker.FreeRectChoiceHeuristic.RectBestShortSideFit ); if( bAllPacked ) { float fOccupancy = oPacker.Occupancy( ); // if better occupancy than current best or same occupancy and smaller surface area... if( fOccupancy > fBestOccupancy || ( fOccupancy == fBestOccupancy && f2AtlasSize.sqrMagnitude < f2BestSize.sqrMagnitude ) ) { // New best f2BestSize = f2AtlasSize; fBestOccupancy = fOccupancy; rBestResultsOutput = oPacker.UsedRectangles; rBestResultsInput = oRectsToPackCopyDict; } } // Is tested atlas size is max? if( f2AtlasSize.x != iMaximumAtlasSize || f2AtlasSize.y != iMaximumAtlasSize ) { // Add 2 sizes to test: doubled width & doubled height Vector2 f2AtlasDoubleWidthSize = new Vector2( Mathf.Min( f2AtlasSize.x * 2, iMaximumAtlasSize ), f2AtlasSize.y ); Vector2 f2AtlasDoubleHeightSize = new Vector2( f2AtlasSize.x, Mathf.Min( f2AtlasSize.y * 2, iMaximumAtlasSize ) ); // Ensure we don't enqueue these sizes twice if( f2AtlasSize != f2AtlasDoubleWidthSize && oNextSizesToTest.Contains( f2AtlasDoubleWidthSize ) == false ) { oNextSizesToTest.Enqueue( f2AtlasDoubleWidthSize ); } // If sizes equal, it's a square => don't test doubled height or doubled width. // These cases are equal (double width square = flipped double height square) if( f2AtlasSize.x != f2AtlasSize.y && f2AtlasSize != f2AtlasDoubleHeightSize && oNextSizesToTest.Contains( f2AtlasDoubleHeightSize ) == false ) { oNextSizesToTest.Enqueue( f2AtlasDoubleHeightSize ); } } else if( rBestResultsOutput == null ) // Max square, no best results so far { // Set it as default best f2BestSize = f2AtlasSize; //fBestOccupancy = oPacker.Occupancy( ); // Won't be used rBestResultsOutput = oPacker.UsedRectangles; rBestResultsInput = oRectsToPackCopyDict; } oRectsToPackCopyDict = null; } a_rRectsToPackDict = rBestResultsInput; a_rPackedUVRectsDict = rBestResultsOutput; a_iAtlasWidth = (int) f2BestSize.x; a_iAtlasHeight = (int) f2BestSize.y; oPacker = null; } private AtlasEntry GenerateAtlasEntry( int a_iAtlasEntryIndex, Texture2D a_rAtlasTexture, Dictionary<int,PackedRect> a_rTextureIndexUVRectsDict, string a_oGeneratedDataPathLocal ) { Texture2D rCurrentAtlasTexture; Material rCurrentAtlasMaterial; float fWidth = (float) a_rAtlasTexture.width; float fHeight = (float) a_rAtlasTexture.height; if( m_oAtlasEntries != null && m_oAtlasEntries.Length > a_iAtlasEntryIndex && m_oAtlasEntries[ a_iAtlasEntryIndex ] != null ) { AtlasEntry rAtlasEntry = m_oAtlasEntries[ a_iAtlasEntryIndex ]; rCurrentAtlasTexture = rAtlasEntry.atlasTexture; rCurrentAtlasMaterial = rAtlasEntry.material; } else { rCurrentAtlasTexture = null; rCurrentAtlasMaterial = null; } // rSavedAtlasTexture = instance of the saved/exported/serialized atlas texture at a_oGeneratedDataPathLocal Texture2D rSavedAtlasTexture = this.ExportAndSaveAtlasTexture( a_iAtlasEntryIndex, rCurrentAtlasTexture, a_rAtlasTexture, a_oGeneratedDataPathLocal ); Material rSavedAtlasMaterial = this.GenerateAtlasMaterial( a_iAtlasEntryIndex, rCurrentAtlasMaterial, rSavedAtlasTexture, a_oGeneratedDataPathLocal ); int iTextureCount = a_rTextureIndexUVRectsDict.Count; string[ ] oTextureGUIDs = new string[ iTextureCount ]; PackedRect[ ] oPackedUVRects = new PackedRect[ iTextureCount ]; int iTextureIndex = 0; foreach( KeyValuePair<int,PackedRect> rTextureIndexPackedUVRectPair in a_rTextureIndexUVRectsDict ) { oTextureGUIDs[ iTextureIndex ] = m_rTextureContainers[ rTextureIndexPackedUVRectPair.Key ].GUID; PackedRect oNormalizedPackedRect = rTextureIndexPackedUVRectPair.Value; // Normalize UVs Rect rUVRect = oNormalizedPackedRect.rect; oNormalizedPackedRect.rect = new Rect( rUVRect.x / fWidth, rUVRect.y / fHeight, rUVRect.width / fWidth, rUVRect.height / fHeight ); oPackedUVRects[ iTextureIndex ] = oNormalizedPackedRect; ++iTextureIndex; } return new AtlasEntry( rSavedAtlasTexture, rSavedAtlasMaterial, oTextureGUIDs, oPackedUVRects ); } private Texture2D ExportAndSaveAtlasTexture( int a_iAtlasEntryIndex, Texture2D a_rCurrentAtlasTexture, Texture2D a_rNewAtlasTexture, string a_oGeneratedDataPathLocal ) { bool bNewTexture = false; // Look if there's already a texture at desired path if( a_rCurrentAtlasTexture == null ) { // No => create the texture bNewTexture = true; } else { string oFolderPathLocal = Uni2DEditorUtils.GetLocalAssetFolderPath( a_rCurrentAtlasTexture ); if( oFolderPathLocal != a_oGeneratedDataPathLocal ) { bNewTexture = true; } } // Set atlas name accordingly if( bNewTexture ) { a_rNewAtlasTexture.name = gameObject.name + "_AtlasTexture" + a_iAtlasEntryIndex; } else { a_rNewAtlasTexture.name = a_rCurrentAtlasTexture.name; } // Get the atlas texture path string oAtlasTexturePathLocal = a_oGeneratedDataPathLocal + a_rNewAtlasTexture.name + ".png"; string oAtlasTexturePathGlobal = Uni2DEditorUtils.LocalToGlobalAssetPath( oAtlasTexturePathLocal ); // Save the atlas FileStream oFileStream = new FileStream( oAtlasTexturePathGlobal, FileMode.Create ); BinaryWriter oBinaryWriter = new BinaryWriter( oFileStream ); oBinaryWriter.Write( a_rNewAtlasTexture.EncodeToPNG( ) ); // Close IO resources oBinaryWriter.Close( ); oFileStream.Close( ); // If we had just created a new texture set the default import settings if( bNewTexture ) { ImportNewAtlasTexture( oAtlasTexturePathLocal ); } else { // or reimport AssetDatabase.ImportAsset( oAtlasTexturePathLocal, ImportAssetOptions.ForceUpdate ); } // Destroy the runtime-created instance DestroyImmediate( a_rNewAtlasTexture ); // Save a ref to new atlas texture (by instancing its Unity serialized model) a_rNewAtlasTexture = AssetDatabase.LoadAssetAtPath( oAtlasTexturePathLocal, typeof( Texture2D ) ) as Texture2D; // Mark the atlas texture Uni2DEditorUtils.MarkAsTextureAtlas( a_rNewAtlasTexture ); return a_rNewAtlasTexture; } private Texture2D GenerateAtlasTexture( Dictionary<int,PackedRect> a_rTextureIndexPackedUVRectsDict, int a_iAtlasWidth, int a_iAtlasHeight ) { Texture2D oAtlasTexture = new Texture2D( a_iAtlasWidth, a_iAtlasHeight, TextureFormat.ARGB32, false ); // GetPixels32 returns a copy of the atlas pixels //Color32[ ] oAtlasColor32 = oAtlasTexture.GetPixels32( ); // Create ourself the pixel array so we don't need to fill it: array is zero initialized Color32[ ] oAtlasColor32 = new Color32[ a_iAtlasWidth * a_iAtlasHeight ]; /* //Fill with black zero alpha Color32 f4ClearColor = new Color32( 0, 0, 0, 0 ); for( int iColorIndex = 0, iColorCount = oAtlasColor32.Length; iColorIndex < iColorCount; ++iColorIndex ) { oAtlasColor32[ iColorIndex ] = f4ClearColor; } */ // Copy the atlased textures pixels into the atlas texture foreach( KeyValuePair<int,PackedRect> rIndexedPackedRect in a_rTextureIndexPackedUVRectsDict ) { // The texture to copy Texture2D rPackedTexture = m_rTextureContainers[ rIndexedPackedRect.Key ]; PackedRect rPackedRect = rIndexedPackedRect.Value; // The UV rect Rect rUVRect = rPackedRect.rect; //Debug.Log( rPackedTexture.name + ": " + rPackedRect.rect.x + " / " + rPackedRect.rect.y + " / " + rPackedTexture.width + "px ; " + rPackedTexture.height + "px / flipped: " + rPackedRect.isFlipped ); // Copy texture into the atlas SetPixelBlock32( rPackedTexture.GetPixels32( ), oAtlasColor32, (int) rUVRect.x, (int) rUVRect.y, (int) rUVRect.width, (int) rUVRect.height, a_iAtlasWidth, a_iAtlasHeight, rPackedRect.isFlipped ); } // Set the new atlas pixels oAtlasTexture.SetPixels32( oAtlasColor32 ); oAtlasTexture.Apply( ); oAtlasColor32 = null; return oAtlasTexture; } // Prepares Texture private void ImportNewAtlasTexture(string a_rTexturePathLocal) { Uni2DAssetPostprocessor.ForceImportAssetIfLocked( a_rTexturePathLocal, ImportAssetOptions.ForceSynchronousImport ); } // Prepares Texture public static void SetDefaultAtlasTextureImportSettings(TextureImporter a_rTextureImporter) { a_rTextureImporter.textureType = TextureImporterType.Advanced; a_rTextureImporter.maxTextureSize = 4096; a_rTextureImporter.textureFormat = TextureImporterFormat.AutomaticTruecolor; a_rTextureImporter.mipmapEnabled = false; a_rTextureImporter.isReadable = false; } // Returns the number of textures which won't fit into the atlas private int LookForOversizedTextures( Texture2DContainer[ ] a_rTextureContainers, int a_iPadding, AtlasSize a_eMaximumAtlasSize ) { float fMaximumAtlasSize = (float) a_eMaximumAtlasSize; float fPadding = (float) a_iPadding; int iOversized = 0; if( a_rTextureContainers != null ) { foreach( Texture2DContainer rTextureContainer in a_rTextureContainers ) { if( rTextureContainer != null ) { Texture2D rTextureToPack = rTextureContainer; if( rTextureToPack != null && ( rTextureToPack.width + fPadding > fMaximumAtlasSize || rTextureToPack.height + fPadding > fMaximumAtlasSize ) ) { ++iOversized; } } } } return iOversized; } // Copies a color32 block, which can be flipped, to a larger color32 block private void SetPixelBlock32( Color32[ ] a_rSource, Color32[ ] a_rDestination, int a_iDestinationX, int a_iDestinationY, int a_iSourceWidth, int a_iSourceHeight, int a_iDestinationWidth, int a_iDestinationHeight, bool a_bIsFlipped ) { if( a_bIsFlipped ) { for( int iY = 0; iY < a_iSourceHeight; ++iY ) { for( int iX = 0; iX < a_iSourceWidth; ++iX ) { a_rDestination[ ( iX + a_iDestinationX ) + ( iY + a_iDestinationY ) * a_iDestinationWidth ] = a_rSource[ iY + ( a_iSourceWidth - 1 - iX ) * a_iSourceHeight ]; } } } else { for( int iY = 0; iY < a_iSourceHeight; ++iY ) { for( int iX = 0; iX < a_iSourceWidth; ++iX ) { a_rDestination[ ( iX + a_iDestinationX ) + ( iY + a_iDestinationY ) * a_iDestinationWidth ] = a_rSource[ iX + iY * a_iSourceWidth ]; } } } } public string[ ] GetTextureGUIDs( ) { int iTextureCount = m_rTextureContainers.Length; string[ ] oTextureGUIDs = new string[ iTextureCount ]; for( int iTextureIndex = 0; iTextureIndex < iTextureCount; ++iTextureIndex ) { oTextureGUIDs[ iTextureIndex ] = m_rTextureContainers[ iTextureIndex ].GUID; } return oTextureGUIDs; } public Material[ ] GetAllMaterials( ) { int iAtlasEntryCount = m_oAtlasEntries != null ? m_oAtlasEntries.Length : 0; Material[ ] oMaterials = new Material[ iAtlasEntryCount ]; for( int iAtlasEntryIndex = 0; iAtlasEntryIndex < iAtlasEntryCount; ++iAtlasEntryIndex ) { oMaterials[ iAtlasEntryIndex ] = m_oAtlasEntries[ iAtlasEntryIndex ].material; } return oMaterials; } public Texture2D[ ] GetAllAtlasTextures( ) { int iAtlasEntryCount = m_oAtlasEntries != null ? m_oAtlasEntries.Length : 0; Texture2D[ ] oAtlasTextures = new Texture2D[ iAtlasEntryCount ]; for( int iAtlasEntryIndex = 0; iAtlasEntryIndex < iAtlasEntryCount; ++iAtlasEntryIndex ) { oAtlasTextures[ iAtlasEntryIndex ] = m_oAtlasEntries[ iAtlasEntryIndex ].atlasTexture; } return oAtlasTextures; } #endif // UNITY_EDITOR private void RebuildDict( ) { m_oTextureGUIDAtlasEntriesDict = new Dictionary<string, AtlasEntry>( ); if( m_rTextureContainers != null && m_oAtlasEntries != null ) { // Build texture <-> atlas entry dict. int iAtlasEntriesCount = m_oAtlasEntries.Length; for( int iAtlasEntryIndex = 0; iAtlasEntryIndex < iAtlasEntriesCount; ++iAtlasEntryIndex ) { AtlasEntry rAtlasEntry = m_oAtlasEntries[ iAtlasEntryIndex ]; string[ ] rContainedTextureGUIDs = rAtlasEntry.atlasedTextureGUIDs; int iContainedTextureGUIDsCount = rContainedTextureGUIDs.Length; for( int iContainedTextureGUIDIndex = 0; iContainedTextureGUIDIndex < iContainedTextureGUIDsCount; ++iContainedTextureGUIDIndex ) { m_oTextureGUIDAtlasEntriesDict.Add( rContainedTextureGUIDs[ iContainedTextureGUIDIndex ], rAtlasEntry ); } } } } }
namespace Trionic5Controls { partial class ctrlComptressorMapGraph { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (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() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ctrlComptressorMapGraph)); DevExpress.XtraCharts.XYDiagram xyDiagram1 = new DevExpress.XtraCharts.XYDiagram(); DevExpress.XtraCharts.Series series1 = new DevExpress.XtraCharts.Series(); DevExpress.XtraCharts.SplineSeriesView splineSeriesView1 = new DevExpress.XtraCharts.SplineSeriesView(); DevExpress.XtraCharts.PointSeriesLabel pointSeriesLabel1 = new DevExpress.XtraCharts.PointSeriesLabel(); DevExpress.XtraCharts.Series series2 = new DevExpress.XtraCharts.Series(); DevExpress.XtraCharts.SplineSeriesView splineSeriesView2 = new DevExpress.XtraCharts.SplineSeriesView(); DevExpress.XtraCharts.PointSeriesLabel pointSeriesLabel2 = new DevExpress.XtraCharts.PointSeriesLabel(); DevExpress.XtraCharts.SplineSeriesView splineSeriesView3 = new DevExpress.XtraCharts.SplineSeriesView(); DevExpress.XtraCharts.PointSeriesLabel pointSeriesLabel3 = new DevExpress.XtraCharts.PointSeriesLabel(); this.panel1 = new System.Windows.Forms.Panel(); this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.toolStripLabel1 = new System.Windows.Forms.ToolStripLabel(); this.toolStripComboBox1 = new System.Windows.Forms.ToolStripComboBox(); this.toolStripButton1 = new System.Windows.Forms.ToolStripButton(); this.toolStripButton2 = new System.Windows.Forms.ToolStripButton(); this.toolStripDropDownButton1 = new System.Windows.Forms.ToolStripDropDownButton(); this.t25ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.tD0415GToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.tD0418TToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.tD0419TToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.gT28RSToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.gT3071r86ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.gT30RToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.gT40RToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.hX40wToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripLabel2 = new System.Windows.Forms.ToolStripLabel(); this.toolStripTextBox1 = new System.Windows.Forms.ToolStripTextBox(); this.toolStripLabel3 = new System.Windows.Forms.ToolStripLabel(); this.toolStripTextBox2 = new System.Windows.Forms.ToolStripTextBox(); this.chartControl1 = new DevExpress.XtraCharts.ChartControl(); this.panel1.SuspendLayout(); this.toolStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.chartControl1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(xyDiagram1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(series1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(splineSeriesView1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(pointSeriesLabel1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(series2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(splineSeriesView2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(pointSeriesLabel2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(splineSeriesView3)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(pointSeriesLabel3)).BeginInit(); this.SuspendLayout(); // // panel1 // this.panel1.Controls.Add(this.chartControl1); this.panel1.Dock = System.Windows.Forms.DockStyle.Fill; this.panel1.Location = new System.Drawing.Point(0, 25); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(682, 435); this.panel1.TabIndex = 1; // // toolStrip1 // this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripLabel1, this.toolStripComboBox1, this.toolStripButton1, this.toolStripButton2, this.toolStripDropDownButton1, this.toolStripLabel2, this.toolStripTextBox1, this.toolStripLabel3, this.toolStripTextBox2}); this.toolStrip1.Location = new System.Drawing.Point(0, 0); this.toolStrip1.Name = "toolStrip1"; this.toolStrip1.Size = new System.Drawing.Size(682, 25); this.toolStrip1.TabIndex = 2; this.toolStrip1.Text = "toolStrip1"; // // toolStripLabel1 // this.toolStripLabel1.Name = "toolStripLabel1"; this.toolStripLabel1.Size = new System.Drawing.Size(90, 22); this.toolStripLabel1.Text = "Select your turbo"; // // toolStripComboBox1 // this.toolStripComboBox1.Items.AddRange(new object[] { "Garrett T25 trim 55", "Garrett T25 trim 60", "Mitsubishi TD04-15G", "Mitsubishi TD04-16T", "Mitsubishi TD04-18T", "Mitsubishi TD04-19T", "Mitsubishi TD06-20G", "Garrett GT2871R", "Garrett GT28RS", "Garrett GT3071R", "Garrett GT3076R", "Garrett GT40R", "Holset HX40w"}); this.toolStripComboBox1.Name = "toolStripComboBox1"; this.toolStripComboBox1.Size = new System.Drawing.Size(250, 25); this.toolStripComboBox1.SelectedIndexChanged += new System.EventHandler(this.toolStripComboBox1_SelectedIndexChanged); // // toolStripButton1 // this.toolStripButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton1.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton1.Image"))); this.toolStripButton1.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton1.Name = "toolStripButton1"; this.toolStripButton1.Size = new System.Drawing.Size(23, 22); this.toolStripButton1.Text = "Refresh"; this.toolStripButton1.Click += new System.EventHandler(this.toolStripButton1_Click); // // toolStripButton2 // this.toolStripButton2.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton2.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton2.Image"))); this.toolStripButton2.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton2.Name = "toolStripButton2"; this.toolStripButton2.Size = new System.Drawing.Size(23, 22); this.toolStripButton2.Text = "Save image"; this.toolStripButton2.Visible = false; this.toolStripButton2.Click += new System.EventHandler(this.toolStripButton2_Click); // // toolStripDropDownButton1 // this.toolStripDropDownButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripDropDownButton1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.t25ToolStripMenuItem, this.tD0415GToolStripMenuItem, this.tD0418TToolStripMenuItem, this.tD0419TToolStripMenuItem, this.gT28RSToolStripMenuItem, this.gT3071r86ToolStripMenuItem, this.gT30RToolStripMenuItem, this.gT40RToolStripMenuItem, this.hX40wToolStripMenuItem}); this.toolStripDropDownButton1.Image = ((System.Drawing.Image)(resources.GetObject("toolStripDropDownButton1.Image"))); this.toolStripDropDownButton1.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripDropDownButton1.Name = "toolStripDropDownButton1"; this.toolStripDropDownButton1.Size = new System.Drawing.Size(29, 22); this.toolStripDropDownButton1.Text = "Select compressor map"; this.toolStripDropDownButton1.Visible = false; // // t25ToolStripMenuItem // this.t25ToolStripMenuItem.Name = "t25ToolStripMenuItem"; this.t25ToolStripMenuItem.Size = new System.Drawing.Size(133, 22); this.t25ToolStripMenuItem.Text = "T25"; this.t25ToolStripMenuItem.Click += new System.EventHandler(this.t25ToolStripMenuItem_Click); // // tD0415GToolStripMenuItem // this.tD0415GToolStripMenuItem.Name = "tD0415GToolStripMenuItem"; this.tD0415GToolStripMenuItem.Size = new System.Drawing.Size(133, 22); this.tD0415GToolStripMenuItem.Text = "TD04-15G"; this.tD0415GToolStripMenuItem.Click += new System.EventHandler(this.tD0415GToolStripMenuItem_Click); // // tD0418TToolStripMenuItem // this.tD0418TToolStripMenuItem.Name = "tD0418TToolStripMenuItem"; this.tD0418TToolStripMenuItem.Size = new System.Drawing.Size(133, 22); this.tD0418TToolStripMenuItem.Text = "TD04-18T"; this.tD0418TToolStripMenuItem.Click += new System.EventHandler(this.tD0418TToolStripMenuItem_Click); // // tD0419TToolStripMenuItem // this.tD0419TToolStripMenuItem.Name = "tD0419TToolStripMenuItem"; this.tD0419TToolStripMenuItem.Size = new System.Drawing.Size(133, 22); this.tD0419TToolStripMenuItem.Text = "TD04-19T"; this.tD0419TToolStripMenuItem.Click += new System.EventHandler(this.tD0419TToolStripMenuItem_Click); // // gT28RSToolStripMenuItem // this.gT28RSToolStripMenuItem.Name = "gT28RSToolStripMenuItem"; this.gT28RSToolStripMenuItem.Size = new System.Drawing.Size(133, 22); this.gT28RSToolStripMenuItem.Text = "GT28RS"; this.gT28RSToolStripMenuItem.Click += new System.EventHandler(this.gT28RSToolStripMenuItem_Click); // // gT3071r86ToolStripMenuItem // this.gT3071r86ToolStripMenuItem.Name = "gT3071r86ToolStripMenuItem"; this.gT3071r86ToolStripMenuItem.Size = new System.Drawing.Size(133, 22); this.gT3071r86ToolStripMenuItem.Text = "GT3071R"; this.gT3071r86ToolStripMenuItem.Click += new System.EventHandler(this.gT3071r86ToolStripMenuItem_Click); // // gT30RToolStripMenuItem // this.gT30RToolStripMenuItem.Name = "gT30RToolStripMenuItem"; this.gT30RToolStripMenuItem.Size = new System.Drawing.Size(133, 22); this.gT30RToolStripMenuItem.Text = "GT30R"; this.gT30RToolStripMenuItem.Click += new System.EventHandler(this.gT30RToolStripMenuItem_Click); // // gT40RToolStripMenuItem // this.gT40RToolStripMenuItem.Name = "gT40RToolStripMenuItem"; this.gT40RToolStripMenuItem.Size = new System.Drawing.Size(133, 22); this.gT40RToolStripMenuItem.Text = "GT40R"; this.gT40RToolStripMenuItem.Click += new System.EventHandler(this.gT40RToolStripMenuItem_Click); // // hX40wToolStripMenuItem // this.hX40wToolStripMenuItem.Name = "hX40wToolStripMenuItem"; this.hX40wToolStripMenuItem.Size = new System.Drawing.Size(133, 22); this.hX40wToolStripMenuItem.Text = "HX40w"; this.hX40wToolStripMenuItem.Click += new System.EventHandler(this.hX40wToolStripMenuItem_Click); // // toolStripLabel2 // this.toolStripLabel2.Name = "toolStripLabel2"; this.toolStripLabel2.Size = new System.Drawing.Size(51, 22); this.toolStripLabel2.Text = "Temp (C)"; // // toolStripTextBox1 // this.toolStripTextBox1.Name = "toolStripTextBox1"; this.toolStripTextBox1.Size = new System.Drawing.Size(30, 25); this.toolStripTextBox1.Text = "20"; this.toolStripTextBox1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.toolStripTextBox1_KeyDown); // // toolStripLabel3 // this.toolStripLabel3.Name = "toolStripLabel3"; this.toolStripLabel3.Size = new System.Drawing.Size(19, 22); this.toolStripLabel3.Text = "VE"; // // toolStripTextBox2 // this.toolStripTextBox2.Name = "toolStripTextBox2"; this.toolStripTextBox2.Size = new System.Drawing.Size(30, 25); this.toolStripTextBox2.Text = "85"; this.toolStripTextBox2.KeyDown += new System.Windows.Forms.KeyEventHandler(this.toolStripTextBox1_KeyDown); // // chartControl1 // this.chartControl1.BackImage.Image = ((System.Drawing.Image)(resources.GetObject("chartControl1.BackImage.Image"))); this.chartControl1.BackImage.Stretch = true; this.chartControl1.BorderOptions.Visible = false; xyDiagram1.AxisX.Visible = false; xyDiagram1.AxisX.VisibleInPanesSerializable = "-1"; xyDiagram1.AxisX.Range.SideMarginsEnabled = false; xyDiagram1.AxisX.Range.ScrollingRange.SideMarginsEnabled = true; xyDiagram1.AxisY.Visible = false; xyDiagram1.AxisY.VisibleInPanesSerializable = "-1"; xyDiagram1.AxisY.GridLines.Visible = false; xyDiagram1.AxisY.Range.SideMarginsEnabled = false; xyDiagram1.AxisY.Range.ScrollingRange.SideMarginsEnabled = true; xyDiagram1.DefaultPane.BorderVisible = false; xyDiagram1.DefaultPane.BackColor = System.Drawing.Color.Transparent; xyDiagram1.DefaultPane.ScrollBarOptions.XAxisScrollBarVisible = false; xyDiagram1.DefaultPane.ScrollBarOptions.YAxisScrollBarVisible = false; xyDiagram1.PaneDistance = 0; xyDiagram1.EnableZooming = true; xyDiagram1.EnableScrolling = true; this.chartControl1.Diagram = xyDiagram1; this.chartControl1.Dock = System.Windows.Forms.DockStyle.Fill; this.chartControl1.Legend.Visible = false; this.chartControl1.Location = new System.Drawing.Point(0, 0); this.chartControl1.Name = "chartControl1"; series1.Name = "Series 1"; series1.View = splineSeriesView1; pointSeriesLabel1.LineVisible = true; series1.Label = pointSeriesLabel1; series2.Name = "Series 2"; series2.View = splineSeriesView2; pointSeriesLabel2.LineVisible = true; series2.Label = pointSeriesLabel2; this.chartControl1.SeriesSerializable = new DevExpress.XtraCharts.Series[] { series1, series2}; this.chartControl1.SeriesTemplate.View = splineSeriesView3; pointSeriesLabel3.LineVisible = true; this.chartControl1.SeriesTemplate.Label = pointSeriesLabel3; this.chartControl1.Size = new System.Drawing.Size(682, 435); this.chartControl1.TabIndex = 0; // // ctrlComptressorMapGraph // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.panel1); this.Controls.Add(this.toolStrip1); this.Name = "ctrlComptressorMapGraph"; this.Size = new System.Drawing.Size(682, 460); this.panel1.ResumeLayout(false); this.toolStrip1.ResumeLayout(false); this.toolStrip1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(xyDiagram1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(splineSeriesView1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(pointSeriesLabel1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(series1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(splineSeriesView2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(pointSeriesLabel2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(series2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(splineSeriesView3)).EndInit(); ((System.ComponentModel.ISupportInitialize)(pointSeriesLabel3)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.chartControl1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Panel panel1; private System.Windows.Forms.ToolStrip toolStrip1; private System.Windows.Forms.ToolStripDropDownButton toolStripDropDownButton1; private System.Windows.Forms.ToolStripMenuItem t25ToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem tD0415GToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem gT28RSToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem gT30RToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem tD0418TToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem tD0419TToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem gT3071r86ToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem gT40RToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem hX40wToolStripMenuItem; private System.Windows.Forms.ToolStripComboBox toolStripComboBox1; private System.Windows.Forms.ToolStripLabel toolStripLabel1; private System.Windows.Forms.ToolStripButton toolStripButton1; private System.Windows.Forms.ToolStripButton toolStripButton2; private System.Windows.Forms.ToolStripLabel toolStripLabel2; private System.Windows.Forms.ToolStripTextBox toolStripTextBox1; private System.Windows.Forms.ToolStripLabel toolStripLabel3; private System.Windows.Forms.ToolStripTextBox toolStripTextBox2; private DevExpress.XtraCharts.ChartControl chartControl1; } }
// // System.Web.Services.Protocols.SoapExtension.cs // // Author: // Tim Coleman (tim@timcoleman.com) // // Copyright (C) Tim Coleman, 2002 // // // 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.IO; using System.Collections; using System.Web.Services.Configuration; namespace System.Web.Services.Protocols { public abstract class SoapExtension { #region Fields Stream stream; #endregion #region Constructors protected SoapExtension () { } #endregion // Constructors #region Methods public virtual Stream ChainStream (Stream stream) { return stream; } public abstract object GetInitializer (Type serviceType); public abstract object GetInitializer (LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute); public abstract void Initialize (object initializer); public abstract void ProcessMessage (SoapMessage message); #if !TARGET_JVM static ArrayList[] globalExtensions; #else static ArrayList[] globalExtensions { get { return (ArrayList[])AppDomain.CurrentDomain.GetData("SoapExtension.globalExtensions"); } set { AppDomain.CurrentDomain.SetData("SoapExtension.globalExtensions", value); } } #endif internal static SoapExtension[] CreateExtensionChain (SoapExtensionRuntimeConfig[] extensionConfigs) { if (extensionConfigs == null) return null; SoapExtension[] res = new SoapExtension [extensionConfigs.Length]; CreateExtensionChain (extensionConfigs, res, 0); return res; } internal static SoapExtension[] CreateExtensionChain (SoapExtensionRuntimeConfig[] hiPrioExts, SoapExtensionRuntimeConfig[] medPrioExts, SoapExtensionRuntimeConfig[] lowPrioExts) { int len = 0; if (hiPrioExts != null) len += hiPrioExts.Length; if (medPrioExts != null) len += medPrioExts.Length; if (lowPrioExts != null) len += lowPrioExts.Length; if (len == 0) return null; SoapExtension[] res = new SoapExtension [len]; int pos = 0; if (hiPrioExts != null) pos = CreateExtensionChain (hiPrioExts, res, pos); if (medPrioExts != null) pos = CreateExtensionChain (medPrioExts, res, pos); if (lowPrioExts != null) pos = CreateExtensionChain (lowPrioExts, res, pos); return res; } static int CreateExtensionChain (SoapExtensionRuntimeConfig[] extensionConfigs, SoapExtension[] destArray, int pos) { for (int n=0; n<extensionConfigs.Length; n++) { SoapExtensionRuntimeConfig econf = extensionConfigs [n]; SoapExtension ext = (SoapExtension) Activator.CreateInstance (econf.Type); ext.Initialize (econf.InitializationInfo); destArray [pos++] = ext; } return pos; } static void InitializeGlobalExtensions () { globalExtensions = new ArrayList[2]; ArrayList exts = WSConfig.Instance.ExtensionTypes; if (exts == null) return; foreach (WSExtensionConfig econf in exts) { if (globalExtensions [(int)econf.Group] == null) globalExtensions [(int)econf.Group] = new ArrayList (); ArrayList destList = globalExtensions [(int) econf.Group]; bool added = false; for (int n=0; n<destList.Count && !added; n++) if (((WSExtensionConfig)destList [n]).Priority > econf.Priority) { destList.Insert (n, econf); added = true; } if (!added) destList.Add (econf); } } internal static SoapExtensionRuntimeConfig[][] GetTypeExtensions (Type serviceType) { if (globalExtensions == null) InitializeGlobalExtensions(); SoapExtensionRuntimeConfig[][] exts = new SoapExtensionRuntimeConfig[2][]; for (int group = 0; group < 2; group++) { ArrayList globList = globalExtensions[group]; if (globList == null) continue; exts [group] = new SoapExtensionRuntimeConfig [globList.Count]; for (int n=0; n<globList.Count; n++) { WSExtensionConfig econf = (WSExtensionConfig) globList [n]; SoapExtensionRuntimeConfig typeconf = new SoapExtensionRuntimeConfig (); typeconf.Type = econf.Type; SoapExtension ext = (SoapExtension) Activator.CreateInstance (econf.Type); typeconf.InitializationInfo = ext.GetInitializer (serviceType); exts [group][n] = typeconf; } } return exts; } internal static SoapExtensionRuntimeConfig[] GetMethodExtensions (LogicalMethodInfo method) { object[] ats = method.GetCustomAttributes (typeof (SoapExtensionAttribute)); SoapExtensionRuntimeConfig[] exts = new SoapExtensionRuntimeConfig [ats.Length]; int[] priorities = new int[ats.Length]; for (int n=0; n<ats.Length; n++) { SoapExtensionAttribute at = (SoapExtensionAttribute) ats[n]; SoapExtensionRuntimeConfig econf = new SoapExtensionRuntimeConfig (); econf.Type = at.ExtensionType; priorities [n] = at.Priority; SoapExtension ext = (SoapExtension) Activator.CreateInstance (econf.Type); econf.InitializationInfo = ext.GetInitializer (method, at); exts [n] = econf; } Array.Sort (priorities, exts); return exts; } internal static Stream ExecuteChainStream (SoapExtension[] extensions, Stream stream) { if (extensions == null) return stream; Stream newStream = stream; foreach (SoapExtension ext in extensions) newStream = ext.ChainStream (newStream); return newStream; } internal static void ExecuteProcessMessage(SoapExtension[] extensions, SoapMessage message, bool inverseOrder) { if (extensions == null) return; if (inverseOrder) { for (int n = extensions.Length-1; n >= 0; n--) extensions[n].ProcessMessage (message); } else { for (int n = 0; n < extensions.Length; n++) extensions[n].ProcessMessage (message); } } #endregion // Methods } internal class SoapExtensionRuntimeConfig { public Type Type; public int Priority; public object InitializationInfo; } }
// Copyright (c) 2006, Gustavo Franco // Email: gustavo_franco@hotmail.com // All rights reserved. // 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. // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY // KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR // PURPOSE. IT CAN BE DISTRIBUTED FREE OF CHARGE AS LONG AS THIS HEADER // REMAINS UNCHANGED. using System; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Drawing.IconLib.Exceptions; using System.Drawing.IconLib.EncodingFormats; namespace System.Drawing.IconLib { [Author("Franco, Gustavo")] public class MultiIcon : List<SingleIcon> { #region Variables Declaration private int mSelectedIndex = -1; #endregion #region Constructors public MultiIcon() { } public MultiIcon(IEnumerable<SingleIcon> collection) { AddRange(collection); } public MultiIcon(SingleIcon singleIcon) { Add(singleIcon); SelectedName = singleIcon.Name; } #endregion #region Properties public int SelectedIndex { get {return mSelectedIndex;} set { if (value >= Count) throw new ArgumentOutOfRangeException("SelectedIndex"); mSelectedIndex = value; } } public string SelectedName { get { if (mSelectedIndex < 0 || mSelectedIndex >= Count) return null; return this[mSelectedIndex].Name; } set { if (value == null) throw new ArgumentNullException("SelectedName"); for(int i=0; i<Count; i++) if (this[i].Name.ToLower() == value.ToLower()) { mSelectedIndex = i; return; } throw new InvalidDataException("SelectedName does not exist."); } } public string[] IconNames { get { List<string> names = new List<string>(); foreach(SingleIcon icon in this) names.Add(icon.Name); return names.ToArray(); } } #endregion #region Indexers public SingleIcon this[string name] { get { for(int i=0; i<Count; i++) if (this[i].Name.ToLower() == name.ToLower()) return this[i]; return null; } } #endregion #region Public Methods public SingleIcon Add(string iconName) { // Already exist? if (Contains(iconName)) throw new IconNameAlreadyExistException(); // Lets Create the icon group // Add group to the master list and also lets give a name SingleIcon singleIcon = new SingleIcon(iconName); this.Add(singleIcon); return singleIcon; } public void Remove(string iconName) { if (iconName == null) throw new ArgumentNullException("iconName"); // If not exist then do nothing int index = IndexOf(iconName); if (index == -1) return; RemoveAt(index); } public bool Contains(string iconName) { if (iconName == null) throw new ArgumentNullException("iconName"); // Exist? return IndexOf(iconName) != -1 ? true : false; } public int IndexOf(string iconName) { if (iconName == null) throw new ArgumentNullException("iconName"); // Exist? for(int i=0; i<Count; i++) if (this[i].Name.ToLower() == iconName.ToLower()) return i; return -1; } public void Load(string fileName) { FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); try { Load(fs); } finally { if (fs != null) fs.Close(); } } public void Load(Stream stream) { ILibraryFormat baseFormat; if ((baseFormat = new IconFormat()).IsRecognizedFormat(stream)) { if (mSelectedIndex == -1) { this.Clear(); this.Add(baseFormat.Load(stream)[0]); this[0].Name = "Untitled"; } else { string currentName = this[mSelectedIndex].Name; this[mSelectedIndex] = baseFormat.Load(stream)[0]; this[mSelectedIndex].Name = currentName; } } /*else if ((baseFormat = new NEFormat()).IsRecognizedFormat(stream)) { CopyFrom(baseFormat.Load(stream)); }*/ else if ((baseFormat = new PEFormat()).IsRecognizedFormat(stream)) { CopyFrom(baseFormat.Load(stream)); } else throw new InvalidFileException(); SelectedIndex = Count > 0 ? 0 : -1; } public void Save(string fileName, MultiIconFormat format) { FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite); try { Save(fs, format); } finally { if (fs != null) fs.Close(); } } public void Save(Stream stream, MultiIconFormat format) { switch (format) { case MultiIconFormat.ICO: if (mSelectedIndex == -1) throw new InvalidIconSelectionException(); new IconFormat().Save(this, stream); break; case MultiIconFormat.ICL: /*new NEFormat().Save(this, stream); break;*/ case MultiIconFormat.DLL: /*new PEFormat().Save(this, stream); break;*/ case MultiIconFormat.EXE: case MultiIconFormat.OCX: case MultiIconFormat.CPL: case MultiIconFormat.SRC: throw new NotSupportedException("File format not supported"); default: throw new NotSupportedException("Unknow file type destination, Icons can't be saved"); } } #endregion #region Private Methods private void CopyFrom(MultiIcon multiIcon) { mSelectedIndex = multiIcon.mSelectedIndex; Clear(); AddRange(multiIcon); } #endregion } }
using System; using System.Drawing; using System.IO; using NUnit.Framework; using SharpVectors.Dom.Svg; using SharpVectors.Renderer.Gdi; using SharpVectors.UnitTests.Renderer; namespace SharpVectors.UnitTests.Renderer { [TestFixture] public class GdiRendererTests { #region Fields private static string baseDir; private static SvgWindow window; private static GdiRenderer renderer; private static BitmapComparator comparator; #endregion #region Static Constructor static GdiRendererTests() { // init baseDir (relative to current directory) baseDir = @"Renderer.Gdi\"; } #endregion [SetUp] public void SetUp() { // create a BitmapComparator comparator = new BitmapComparator(); // create an SVGWindow and an associated GdiRenderer renderer = new GdiRenderer(); window = new SvgWindow(75,75, renderer); } #region Tests [Test] public void TestCircleFill() { Assert.IsTrue(CompareImages("circleFill.svg")); } [Test] public void TestCircleFillStroke() { Assert.IsTrue(CompareImages("circleFillStroke.svg")); } [Test] public void TestCircleStroke() { Assert.IsTrue(CompareImages("circleStroke.svg")); } [Test] public void TestEllipseFill() { Assert.IsTrue(CompareImages("ellipseFill.svg")); } [Test] public void TestEllipseFillStroke() { Assert.IsTrue(CompareImages("ellipseFillStroke.svg")); } [Test] public void TestEllipseStroke() { Assert.IsTrue(CompareImages("ellipseStroke.svg")); } [Test] public void TestLinearGradient() { Assert.IsTrue(CompareImages("lineargradient.svg")); } [Test] public void TestLinearGradient2() { Assert.IsTrue(CompareImages("lineargradient2.svg")); } [Test] public void TestImageSvg() { Assert.IsTrue(CompareImages("image-svg.svg")); } [Test] public void TestImagePng() { Assert.IsTrue(CompareImages("image-png.svg")); } [Test] public void TestLineStroke() { Assert.IsTrue(CompareImages("lineStroke.svg")); } [Test] public void TestMarkerLine() { Assert.IsTrue(CompareImages("marker-line.svg"), "Marker - Line"); } [Test] public void TestMarkerPath() { Assert.IsTrue(CompareImages("marker-path.svg"), "Marker - Path"); } [Test] public void TestMarkerPolygon() { Assert.IsTrue(CompareImages("marker-polygon.svg"), "Marker - Polygon"); } [Test] public void TestMarkerPolyline() { Assert.IsTrue(CompareImages("marker-polyline.svg"), "Marker - Polyline"); } [Test] public void TestPathFill() { Assert.IsTrue(CompareImages("pathFill.svg")); } [Test] public void TestPathFillStroke() { Assert.IsTrue(CompareImages("pathFillStroke.svg")); } [Test] public void TestPathStroke() { Assert.IsTrue(CompareImages("pathStroke.svg")); } [Test] public void TestPolygonFill() { Assert.IsTrue(CompareImages("polygonFill.svg")); } [Test] public void TestPolygonFillStroke() { Assert.IsTrue(CompareImages("polygonFillStroke.svg")); } [Test] public void TestPolygonStroke() { Assert.IsTrue(CompareImages("polygonStroke.svg")); } [Test] public void TestPolylineFill() { Assert.IsTrue(CompareImages("polylineFill.svg")); } [Test] public void TestPolylineFillStroke() { Assert.IsTrue(CompareImages("polylineFillStroke.svg")); } [Test] public void TestPolylineStroke() { Assert.IsTrue(CompareImages("polylineStroke.svg")); } [Test] public void TestRectangleFill() { Assert.IsTrue(CompareImages("rectangleFill.svg")); } [Test] public void TestRectangleFillStroke() { Assert.IsTrue(CompareImages("rectangleFillStroke.svg")); } [Test] public void TestRectangleStroke() { Assert.IsTrue(CompareImages("rectangleStroke.svg")); } [Test] public void TestRoundedRectangleFill() { Assert.IsTrue(CompareImages("roundedFill.svg")); } [Test] public void TestRectangleMatrix() { Assert.IsTrue(CompareImages("rectangleMatrix.svg")); } [Test] public void TestRectangleRotate() { Assert.IsTrue(CompareImages("rectangleRotate.svg")); } [Test] public void TestRectangleScale() { Assert.IsTrue(CompareImages("rectangleScale.svg")); } [Test] public void TestRectangleSkewX() { Assert.IsTrue(CompareImages("rectangleSkewX.svg")); } [Test] public void TestRectangleSkewY() { Assert.IsTrue(CompareImages("rectangleSkewY.svg")); } [Test] public void TestRectangleTranslate() { Assert.IsTrue(CompareImages("rectangleTranslate.svg")); } [Test] public void TestRoundedRectangleFillStroke() { Assert.IsTrue(CompareImages("roundedFillStroke.svg")); } [Test] public void TestRoundedRectangleStroke() { Assert.IsTrue(CompareImages("roundedStroke.svg")); } [Test] public void TestUse() { Assert.IsTrue(CompareImages("use.svg")); } #endregion #region data protocol tests [Test] public void DataProtocolTestInlineSvgImage() { Assert.IsTrue(CompareImages("data-image.svg")); } #endregion #region Support Methods private bool CompareImages(string svgFile) { svgFile = Path.Combine(baseDir, svgFile); CompareUtil util = new CompareUtil(); SvgDocument doc = new SvgDocument(window); doc.Load(svgFile); return util.CompareImages(renderer.Render(doc), svgFile + ".png"); } #endregion } }
/* 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 java.lang; using org.eclipse.core.resources; using org.eclipse.core.runtime; using org.eclipse.jface.text; using org.eclipse.jface.text.contentassist; using org.eclipse.jface.text.reconciler; using org.eclipse.jface.text.source; using org.eclipse.swt.widgets; using org.eclipse.ui; using org.eclipse.ui.editors.text; using org.eclipse.ui.texteditor; namespace cnatural.eclipse.editors { public class SourceEditorActionContributor : BasicTextEditorActionContributor { } // // The editor for Stab source files. // public class SourceEditor : AbstractDecoratedTextEditor { private TextInputListener textInputListener; private BackgroundCompiler backgroundCompiler; private PartListener partListener; public SourceEditor() { setSourceViewerConfiguration(new SourceViewerConfiguration(this)); } public override void createPartControl(Composite parent) { super.createPartControl(parent); textInputListener = new TextInputListener(this); backgroundCompiler = new BackgroundCompiler(this); var window = getSite().getWorkbenchWindow(); partListener = new PartListener(this); window.getPartService().addPartListener(partListener); } public override void dispose() { if (partListener != null) { var window = getSite().getWorkbenchWindow(); window.getPartService().removePartListener(partListener); partListener = null; } if (backgroundCompiler != null) { backgroundCompiler.dispose(); backgroundCompiler = null; } if (textInputListener != null) { textInputListener.dispose(); textInputListener = null; } super.dispose(); } public bool IsActive^; public Highlighter Highlighter^; IFile getFile() { var editorInput = getEditorInput() as IFileEditorInput; return (editorInput == null) ? null : editorInput.getFile(); } private class SourceViewerConfiguration : org.eclipse.jface.text.source.SourceViewerConfiguration { private SourceEditor editor; SourceViewerConfiguration(SourceEditor editor) { this.editor = editor; } // Enables the tooltips on the markers in the margin. public override IAnnotationHover getAnnotationHover(ISourceViewer sourceViewer) { return new AnnotationHover(editor); } public override IReconciler getReconciler(ISourceViewer sourceViewer) { return new MonoReconciler(new ReconcilingStrategy(editor), false); } public override IContentAssistant getContentAssistant(ISourceViewer sourceViewer) { ContentAssistant contentAssistant = new ContentAssistant(); contentAssistant.enableAutoActivation(true); //contentAssistant.enableAutoInsert(true); contentAssistant.enablePrefixCompletion(true); contentAssistant.setContentAssistProcessor(new ContentAssistProcessor(editor, sourceViewer), IDocument.DEFAULT_CONTENT_TYPE); return contentAssistant; } } private class AnnotationHover : DefaultAnnotationHover { private SourceEditor editor; AnnotationHover(SourceEditor editor) { this.editor = editor; } protected override bool isIncluded(Annotation annotation) { if (annotation == null) { return true; } var preferenceStore = editor.getPreferenceStore(); if (preferenceStore == null) { return true; } var preference = EditorsUI.getAnnotationPreferenceLookup().getAnnotationPreference(annotation); if (preference == null) { return true; } var key = preference.getVerticalRulerPreferenceKey(); if (key != null && !preferenceStore.getBoolean(key)) { return false; } return true; } } private class ReconcilingStrategy : IReconcilingStrategy, IReconcilingStrategyExtension { private SourceEditor editor; private IProgressMonitor monitor; ReconcilingStrategy(SourceEditor editor) { this.editor = editor; } public void setProgressMonitor(IProgressMonitor monitor) { this.monitor = monitor; } public void initialReconcile() { editor.backgroundCompiler.compile(monitor); } public void setDocument(IDocument document) { } public void reconcile(DirtyRegion dirtyRegion, IRegion subRegion) { // Incremental mode: never called throw new UnsupportedOperationException(); } public void reconcile(IRegion partition) { editor.backgroundCompiler.compile(monitor); } } private class TextInputListener : ITextInputListener { private SourceEditor editor; TextInputListener(SourceEditor editor) { this.editor = editor; var sourceViewer = editor.getSourceViewer(); sourceViewer.addTextInputListener(this); var documentProvider = editor.getDocumentProvider(); if (documentProvider != null) { var document = documentProvider.getDocument(editor.getEditorInput()); if (document != null) { editor.Highlighter = new Highlighter(sourceViewer, document, editor.getFile(), editor.getSharedColors()); } } } void dispose() { if (editor.Highlighter != null) { editor.Highlighter.dispose(); editor.Highlighter = null; } if (editor != null) { editor.getSourceViewer().removeTextInputListener(this); editor = null; } } public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) { if (editor.Highlighter != null) { editor.Highlighter.dispose(); editor.Highlighter = null; } } public void inputDocumentChanged(IDocument oldInput, IDocument newInput) { if (newInput != null) { editor.Highlighter = new Highlighter(editor.getSourceViewer(), newInput, editor.getFile(), editor.getSharedColors()); } } } private class PartListener : IPartListener { private SourceEditor editor; PartListener(SourceEditor editor) { this.editor = editor; } public void partActivated(IWorkbenchPart part) { if (part == editor) { editor.IsActive = true; editor.backgroundCompiler.compileAsync(); } } public void partDeactivated(IWorkbenchPart part) { if (part == editor) { editor.IsActive = false; } } public void partBroughtToTop(IWorkbenchPart part) { } public void partClosed(IWorkbenchPart part) { } public void partOpened(IWorkbenchPart part) { } } } }
#if !NOT_UNITY3D using System; using System.Collections.Generic; using System.Linq; using ModestTree; using ModestTree.Util; using UnityEngine; using UnityEngine.Serialization; using UnityEngine.SceneManagement; using Zenject.Internal; namespace Zenject { public class SceneContext : RunnableContext { public static Action<DiContainer> ExtraBindingsInstallMethod; public static Action<DiContainer> ExtraBindingsLateInstallMethod; public static IEnumerable<DiContainer> ParentContainers; [FormerlySerializedAs("ParentNewObjectsUnderRoot")] [Tooltip("When true, objects that are created at runtime will be parented to the SceneContext")] [SerializeField] bool _parentNewObjectsUnderRoot = false; [Tooltip("Optional contract names for this SceneContext, allowing contexts in subsequently loaded scenes to depend on it and be parented to it, and also for previously loaded decorators to be included")] [SerializeField] List<string> _contractNames = new List<string>(); [Tooltip("Note: This field is deprecated! It will be removed in future versions.")] [SerializeField] string _parentContractName; [Tooltip("Optional contract names of SceneContexts in previously loaded scenes that this context depends on and to which it should be parented")] [SerializeField] List<string> _parentContractNames = new List<string>(); DiContainer _container; readonly List<object> _dependencyRoots = new List<object>(); readonly List<SceneDecoratorContext> _decoratorContexts = new List<SceneDecoratorContext>(); bool _hasInstalled; bool _hasResolved; public override DiContainer Container { get { return _container; } } public bool IsValidating { get { #if UNITY_EDITOR return ProjectContext.Instance.Container.IsValidating; #else return false; #endif } } public IEnumerable<string> ContractNames { get { return _contractNames; } set { _contractNames.Clear(); _contractNames.AddRange(value); } } public IEnumerable<string> ParentContractNames { get { var result = new List<string>(); if (!string.IsNullOrEmpty(_parentContractName)) { result.Add(_parentContractName); } result.AddRange(_parentContractNames); return result; } set { _parentContractName = null; _parentContractNames = value.ToList(); } } public bool ParentNewObjectsUnderRoot { get { return _parentNewObjectsUnderRoot; } set { _parentNewObjectsUnderRoot = value; } } void CheckParentContractName() { if (!string.IsNullOrEmpty(_parentContractName)) { Debug.LogWarning( "Field 'Parent Contract Name' is now deprecated! Please migrate to using the collection 'Parent Contract Names' instead on scene context '{0}'".Fmt(this.name)); } } public void Awake() { CheckParentContractName(); Initialize(); } #if UNITY_EDITOR public void Validate() { Assert.That(IsValidating); CheckParentContractName(); Install(); Resolve(); _container.ValidateValidatables(); } #endif protected override void RunInternal() { // We always want to initialize ProjectContext as early as possible ProjectContext.Instance.EnsureIsInitialized(); Assert.That(!IsValidating); Install(); Resolve(); } public override IEnumerable<GameObject> GetRootGameObjects() { return ZenUtilInternal.GetRootGameObjects(gameObject.scene); } IEnumerable<DiContainer> GetParentContainers() { var parentContractNames = ParentContractNames; if (parentContractNames.IsEmpty()) { if (ParentContainers != null) { var tempParentContainer = ParentContainers; // Always reset after using it - it is only used to pass the reference // between scenes via ZenjectSceneLoader ParentContainers = null; return tempParentContainer; } return new DiContainer[] { ProjectContext.Instance.Container }; } Assert.IsNull(ParentContainers, "Scene cannot have both a parent scene context name set and also an explicit parent container given"); var parentContainers = UnityUtil.AllLoadedScenes .Except(gameObject.scene) .SelectMany(scene => scene.GetRootGameObjects()) .SelectMany(root => root.GetComponentsInChildren<SceneContext>()) .Where(sceneContext => sceneContext.ContractNames.Where(x => parentContractNames.Contains(x)).Any()) .Select(x => x.Container) .ToList(); if (!parentContainers.Any()) { throw Assert.CreateException( "SceneContext on object {0} of scene {1} requires at least one of contracts '{2}', but none of the loaded SceneContexts implements that contract.", gameObject.name, gameObject.scene.name, parentContractNames.Join(", ")); } return parentContainers; } List<SceneDecoratorContext> LookupDecoratorContexts() { if (_contractNames.IsEmpty()) { return new List<SceneDecoratorContext>(); } return UnityUtil.AllLoadedScenes .Except(gameObject.scene) .SelectMany(scene => scene.GetRootGameObjects()) .SelectMany(root => root.GetComponentsInChildren<SceneDecoratorContext>()) .Where(decoratorContext => _contractNames.Contains(decoratorContext.DecoratedContractName)) .ToList(); } public void Install() { #if !UNITY_EDITOR Assert.That(!IsValidating); #endif Assert.That(!_hasInstalled); _hasInstalled = true; Assert.IsNull(_container); var parents = GetParentContainers(); Assert.That(!parents.IsEmpty()); Assert.That(parents.All(x => x.IsValidating == parents.First().IsValidating)); _container = new DiContainer(parents, parents.First().IsValidating); Assert.That(_decoratorContexts.IsEmpty()); _decoratorContexts.AddRange(LookupDecoratorContexts()); Log.Debug("SceneContext: Running installers..."); if (_parentNewObjectsUnderRoot) { _container.DefaultParent = this.transform; } else { // This is necessary otherwise we inherit the project root DefaultParent _container.DefaultParent = null; } // Record all the injectable components in the scene BEFORE installing the installers // This is nice for cases where the user calls InstantiatePrefab<>, etc. in their installer // so that it doesn't inject on the game object twice // InitialComponentsInjecter will also guarantee that any component that is injected into // another component has itself been injected var injectableMonoBehaviours = new List<MonoBehaviour>(); GetInjectableMonoBehaviours(injectableMonoBehaviours); foreach (var instance in injectableMonoBehaviours) { _container.QueueForInject(instance); } foreach (var decoratorContext in _decoratorContexts) { decoratorContext.Initialize(_container); } _container.IsInstalling = true; try { InstallBindings(injectableMonoBehaviours); } finally { _container.IsInstalling = false; } } public void Resolve() { Log.Debug("SceneContext: Injecting components in the scene..."); Assert.That(_hasInstalled); Assert.That(!_hasResolved); _hasResolved = true; Log.Debug("SceneContext: Resolving all..."); Assert.That(_dependencyRoots.IsEmpty()); _dependencyRoots.AddRange(_container.ResolveDependencyRoots()); _container.FlushInjectQueue(); Log.Debug("SceneContext: Initialized successfully"); } void InstallBindings(List<MonoBehaviour> injectableMonoBehaviours) { _container.Bind(typeof(Context), typeof(SceneContext)).To<SceneContext>().FromInstance(this); foreach (var decoratorContext in _decoratorContexts) { decoratorContext.InstallDecoratorSceneBindings(); } InstallSceneBindings(injectableMonoBehaviours); _container.Bind(typeof(SceneKernel), typeof(MonoKernel)) .To<SceneKernel>().FromNewComponentOn(this.gameObject).AsSingle().NonLazy(); _container.Bind<ZenjectSceneLoader>().AsSingle(); if (ExtraBindingsInstallMethod != null) { ExtraBindingsInstallMethod(_container); // Reset extra bindings for next time we change scenes ExtraBindingsInstallMethod = null; } // Always install the installers last so they can be injected with // everything above foreach (var decoratorContext in _decoratorContexts) { decoratorContext.InstallDecoratorInstallers(); } InstallInstallers(); foreach (var decoratorContext in _decoratorContexts) { decoratorContext.InstallLateDecoratorInstallers(); } if (ExtraBindingsLateInstallMethod != null) { ExtraBindingsLateInstallMethod(_container); // Reset extra bindings for next time we change scenes ExtraBindingsLateInstallMethod = null; } } protected override void GetInjectableMonoBehaviours(List<MonoBehaviour> monoBehaviours) { ZenUtilInternal.GetInjectableMonoBehaviours(this.gameObject.scene, monoBehaviours); } // These methods can be used for cases where you need to create the SceneContext entirely in code // Note that if you use these methods that you have to call Run() yourself // This is useful because it allows you to create a SceneContext and configure it how you want // and add what installers you want before kicking off the Install/Resolve public static SceneContext Create() { return CreateComponent<SceneContext>( new GameObject("SceneContext")); } } } #endif
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; // <auto-generated /> namespace SAEON.Observations.Data { /// <summary> /// Controller class for DataSourceTransformation /// </summary> [System.ComponentModel.DataObject] public partial class DataSourceTransformationController { // Preload our schema.. DataSourceTransformation thisSchemaLoad = new DataSourceTransformation(); private string userName = String.Empty; protected string UserName { get { if (userName.Length == 0) { if (System.Web.HttpContext.Current != null) { userName=System.Web.HttpContext.Current.User.Identity.Name; } else { userName=System.Threading.Thread.CurrentPrincipal.Identity.Name; } } return userName; } } [DataObjectMethod(DataObjectMethodType.Select, true)] public DataSourceTransformationCollection FetchAll() { DataSourceTransformationCollection coll = new DataSourceTransformationCollection(); Query qry = new Query(DataSourceTransformation.Schema); coll.LoadAndCloseReader(qry.ExecuteReader()); return coll; } [DataObjectMethod(DataObjectMethodType.Select, false)] public DataSourceTransformationCollection FetchByID(object Id) { DataSourceTransformationCollection coll = new DataSourceTransformationCollection().Where("ID", Id).Load(); return coll; } [DataObjectMethod(DataObjectMethodType.Select, false)] public DataSourceTransformationCollection FetchByQuery(Query qry) { DataSourceTransformationCollection coll = new DataSourceTransformationCollection(); coll.LoadAndCloseReader(qry.ExecuteReader()); return coll; } [DataObjectMethod(DataObjectMethodType.Delete, true)] public bool Delete(object Id) { return (DataSourceTransformation.Delete(Id) == 1); } [DataObjectMethod(DataObjectMethodType.Delete, false)] public bool Destroy(object Id) { return (DataSourceTransformation.Destroy(Id) == 1); } /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> [DataObjectMethod(DataObjectMethodType.Insert, true)] public void Insert(Guid Id,Guid TransformationTypeID,Guid PhenomenonID,Guid? PhenomenonOfferingID,Guid? PhenomenonUOMID,DateTime? StartDate,DateTime? EndDate,Guid DataSourceID,string Definition,double? ParamA,double? ParamB,double? ParamC,double? ParamD,double? ParamE,double? ParamF,double? ParamG,double? ParamH,double? ParamI,double? ParamJ,double? ParamK,double? ParamL,double? ParamM,double? ParamN,double? ParamO,double? ParamP,double? ParamQ,double? ParamR,double? ParamSX,double? ParamT,double? ParamU,double? ParamV,double? ParamW,double? ParamX,double? ParamY,Guid? NewPhenomenonID,Guid? NewPhenomenonOfferingID,Guid? NewPhenomenonUOMID,int? Rank,Guid? SensorID,Guid? UserId,DateTime? AddedAt,DateTime? UpdatedAt,byte[] RowVersion) { DataSourceTransformation item = new DataSourceTransformation(); item.Id = Id; item.TransformationTypeID = TransformationTypeID; item.PhenomenonID = PhenomenonID; item.PhenomenonOfferingID = PhenomenonOfferingID; item.PhenomenonUOMID = PhenomenonUOMID; item.StartDate = StartDate; item.EndDate = EndDate; item.DataSourceID = DataSourceID; item.Definition = Definition; item.ParamA = ParamA; item.ParamB = ParamB; item.ParamC = ParamC; item.ParamD = ParamD; item.ParamE = ParamE; item.ParamF = ParamF; item.ParamG = ParamG; item.ParamH = ParamH; item.ParamI = ParamI; item.ParamJ = ParamJ; item.ParamK = ParamK; item.ParamL = ParamL; item.ParamM = ParamM; item.ParamN = ParamN; item.ParamO = ParamO; item.ParamP = ParamP; item.ParamQ = ParamQ; item.ParamR = ParamR; item.ParamSX = ParamSX; item.ParamT = ParamT; item.ParamU = ParamU; item.ParamV = ParamV; item.ParamW = ParamW; item.ParamX = ParamX; item.ParamY = ParamY; item.NewPhenomenonID = NewPhenomenonID; item.NewPhenomenonOfferingID = NewPhenomenonOfferingID; item.NewPhenomenonUOMID = NewPhenomenonUOMID; item.Rank = Rank; item.SensorID = SensorID; item.UserId = UserId; item.AddedAt = AddedAt; item.UpdatedAt = UpdatedAt; item.RowVersion = RowVersion; item.Save(UserName); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> [DataObjectMethod(DataObjectMethodType.Update, true)] public void Update(Guid Id,Guid TransformationTypeID,Guid PhenomenonID,Guid? PhenomenonOfferingID,Guid? PhenomenonUOMID,DateTime? StartDate,DateTime? EndDate,Guid DataSourceID,string Definition,double? ParamA,double? ParamB,double? ParamC,double? ParamD,double? ParamE,double? ParamF,double? ParamG,double? ParamH,double? ParamI,double? ParamJ,double? ParamK,double? ParamL,double? ParamM,double? ParamN,double? ParamO,double? ParamP,double? ParamQ,double? ParamR,double? ParamSX,double? ParamT,double? ParamU,double? ParamV,double? ParamW,double? ParamX,double? ParamY,Guid? NewPhenomenonID,Guid? NewPhenomenonOfferingID,Guid? NewPhenomenonUOMID,int? Rank,Guid? SensorID,Guid? UserId,DateTime? AddedAt,DateTime? UpdatedAt,byte[] RowVersion) { DataSourceTransformation item = new DataSourceTransformation(); item.MarkOld(); item.IsLoaded = true; item.Id = Id; item.TransformationTypeID = TransformationTypeID; item.PhenomenonID = PhenomenonID; item.PhenomenonOfferingID = PhenomenonOfferingID; item.PhenomenonUOMID = PhenomenonUOMID; item.StartDate = StartDate; item.EndDate = EndDate; item.DataSourceID = DataSourceID; item.Definition = Definition; item.ParamA = ParamA; item.ParamB = ParamB; item.ParamC = ParamC; item.ParamD = ParamD; item.ParamE = ParamE; item.ParamF = ParamF; item.ParamG = ParamG; item.ParamH = ParamH; item.ParamI = ParamI; item.ParamJ = ParamJ; item.ParamK = ParamK; item.ParamL = ParamL; item.ParamM = ParamM; item.ParamN = ParamN; item.ParamO = ParamO; item.ParamP = ParamP; item.ParamQ = ParamQ; item.ParamR = ParamR; item.ParamSX = ParamSX; item.ParamT = ParamT; item.ParamU = ParamU; item.ParamV = ParamV; item.ParamW = ParamW; item.ParamX = ParamX; item.ParamY = ParamY; item.NewPhenomenonID = NewPhenomenonID; item.NewPhenomenonOfferingID = NewPhenomenonOfferingID; item.NewPhenomenonUOMID = NewPhenomenonUOMID; item.Rank = Rank; item.SensorID = SensorID; item.UserId = UserId; item.AddedAt = AddedAt; item.UpdatedAt = UpdatedAt; item.RowVersion = RowVersion; item.Save(UserName); } } }
/* * TreeBase.cs - Base class for generic tree implementations. * * Copyright (C) 2003 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 Generics { using System; // The algorithm used here is based on the red-black tree implementation // in the C++ Standard Template Library. // // Normally, programmers should use "TreeSet" or "TreeDictionary" // instead of inheriting from this class. public abstract class TreeBase<KeyT, ValueT> { // Structure of a tree node. private sealed class TreeNode<KeyT, ValueT> { public TreeNode<KeyT, ValueT> parent; // Parent of this node. public TreeNode<KeyT, ValueT> left; // Left child. public TreeNode<KeyT, ValueT> right; // Right child. public KeyT key; // Key stored in the node. public ValueT value; // Value stored in the node. public bool red; // True if the node is "red". }; // class TreeNode<KeyT, ValueT> // Internal state. protected IComparer<KeyT> cmp; private TreeNode<KeyT, ValueT> root; private TreeNode<KeyT, ValueT> leftMost; protected int count; // Constructors. protected TreeBase() : this(null) {} protected TreeBase(IComparer<KeyT> cmp) { if(cmp == null) { this.cmp = new Comparer<KeyT>(); } else { this.cmp = cmp; } root = null; leftMost = null; count = 0; } // Rotate the tree left around a node. private void RotateLeft(TreeNode<KeyT, ValueT> x) { TreeNode<KeyT, ValueT> y = x.right; x.right = y.left; if(y.left != null) { y.left.parent = x; } y.parent = x.parent; if(x == root) { root = y; } else if(x == x.parent.left) { x.parent.left = y; } else { x.parent.right = y; } y.left = x; x.parent = y; } // Rotate the tree right around a node. private void RotateRight(TreeNode<KeyT, ValueT> x) { TreeNode<KeyT, ValueT> y = x.left; x.left = y.right; if(y.right != null) { y.right.parent = x; } y.parent = x.parent; if(x == root) { root = y; } else if(x == x.parent.right) { x.parent.right = y; } else { x.parent.left = y; } y.right = x; x.parent = y; } // Rebalance the tree around a particular inserted node. private void Rebalance(TreeNode<KeyT, ValueT> x) { TreeNode<KeyT, ValueT> y; // Set the inserted node's color initially to "red". x.red = true; // Split and rotate sub-trees as necessary to rebalance. while(x != root && x.parent.red) { if(x.parent == x.parent.parent.left) { y = x.parent.parent.right; if(y != null && y.red) { x.parent.red = false; y.red = false; x.parent.parent.red = true; x = x.parent.parent; } else { if(x == x.parent.right) { x = x.parent; RotateLeft(x); } x.parent.red = false; x.parent.parent.red = true; RotateRight(x.parent.parent); } } else { y = x.parent.parent.left; if(y != null && y.red) { x.parent.red = false; y.red = false; x.parent.parent.red = true; x = x.parent.parent; } else { if(x == x.parent.left) { x = x.parent; RotateRight(x); } x.parent.red = false; x.parent.parent.red = true; RotateLeft(x.parent.parent); } } } // Set the root color to black. root.red = false; } // Remove a specific node and rebalance the tree afterwards. private void RemoveNode(TreeNode<KeyT, ValueT> z) { TreeNode<KeyT, ValueT> y = z; TreeNode<KeyT, ValueT> x = null; TreeNode<KeyT, ValueT> x_parent = null; TreeNode<KeyT, ValueT> w; bool tempRed; // There will be one less item once we are finished. --count; // Determine the starting position for the rebalance. if(y.left == null) { x = y.right; } else if(y.right == null) { x = y.left; } else { y = y.right; while(y.left != null) { y = y.left; } x = y.right; } // Re-link the nodes to remove z from the tree. if(y != z) { z.left.parent = y; y.left = z.left; if(y != z.right) { x_parent = y.parent; if(x != null) { x.parent = y.parent; } y.parent.left = x; y.right = z.right; z.right.parent = y; } else { x_parent = y; } if(root == z) { root = y; } else if(z.parent.left == z) { z.parent.left = y; } else { z.parent.right = y; } y.parent = z.parent; tempRed = y.red; y.red = z.red; z.red = tempRed; y = z; } else { x_parent = y.parent; if(x != null) { x.parent = y.parent; } if(root == z) { root = x; } else if(z.parent.left == z) { z.parent.left = x; } else { z.parent.right = x; } if(leftMost == z) { if(z.right == null) { leftMost = z.parent; } else { leftMost = x; while(leftMost != null && leftMost.left != null) { leftMost = leftMost.left; } } } } // If the y node is "red", then the tree is still balanced. if(y.red) { return; } // Rotate nodes within the tree to bring it back into balance. while(x != root && (x == null || !(x.red))) { if(x == x_parent.left) { w = x_parent.right; if(w.red) { w.red = false; x_parent.red = true; RotateLeft(x_parent); w = x_parent.right; } if((w.left == null || !(w.left.red)) && (w.right == null || !(w.right.red))) { w.red = true; x = x_parent; x_parent = x_parent.parent; } else { if(w.right == null || !(w.right.red)) { if(w.left != null) { w.left.red = false; } w.red = true; RotateRight(w); w = x_parent.right; } w.red = x_parent.red; x_parent.red = false; if(w.right != null) { w.right.red = false; } RotateLeft(x_parent); break; } } else { w = x_parent.left; if(w.red) { w.red = false; x_parent.red = true; RotateRight(x_parent); w = x_parent.left; } if((w.right == null || !(w.right.red)) && (w.left == null || !(w.left.red))) { w.red = true; x = x_parent; x_parent = x_parent.parent; } else { if(w.left == null || !(w.left.red)) { if(w.right != null) { w.right.red = false; } w.red = true; RotateLeft(w); w = x_parent.left; } w.red = x_parent.red; x_parent.red = false; if(w.left != null) { w.left.red = false; } RotateRight(x_parent); break; } } if(x != null) { x.red = false; } } } // Add an item to this tree. protected void AddItem(KeyT key, ValueT value, bool throwIfExists) { TreeNode<KeyT, ValueT> y; TreeNode<KeyT, ValueT> x; TreeNode<KeyT, ValueT> z; int cmpValue; // Find the insert position. y = null; x = root; while(x != null) { y = x; if((cmpValue = cmp.Compare(key, x.key)) < 0) { x = x.left; } else if(cmpValue > 0) { x = x.right; } else if(throwIfExists) { throw new ArgumentException(S._("Arg_ExistingEntry")); } else { x.value = value; return; } } // Create a new node to insert. z = new TreeNode<KeyT, ValueT>(); z.key = key; z.value = value; // Determine how to insert the node. if(y == null) { // The tree is empty, so add the initial node. root = z; leftMost = z; } else if(x != null || cmp.Compare(key, y.key) < 0) { // Insert on the left. y.left = z; if(y == leftMost) { leftMost = z; } } else { // Insert on the right. y.right = z; } z.parent = y; // Rebalance the tree around the inserted node. Rebalance(z); // We have one more element in the tree. ++count; } // Clear the contents of this tree. protected void ClearAllItems() { root = null; leftMost = null; count = 0; } // Determine if this tree contains a specific key. protected bool ContainsItem(KeyT key) { TreeNode<KeyT, ValueT> current = root; int cmpValue; while(current != null) { if((cmpValue = cmp.Compare(key, current.key)) < 0) { current = current.left; } else if(cmpValue > 0) { current = current.right; } else { return true; } } return false; } // Look up the value associated with a specific key. protected T LookupItem(KeyT key) { TreeNode<KeyT, ValueT> current = root; int cmpValue; while(current != null) { if((cmpValue = cmp.Compare(key, current.key)) < 0) { current = current.left; } else if(cmpValue > 0) { current = current.right; } else { return current.value; } } throw new ArgumentException(S._("Arg_NotInDictionary")); } // Remove the node for a specific key. protected void RemoveItem(KeyT key) { TreeNode<KeyT, ValueT> current = root; int cmpValue; while(current != null) { if((cmpValue = cmp.Compare(key, current.key)) < 0) { current = current.left; } else if(cmpValue > 0) { current = current.right; } else { RemoveNode(current); return; } } } // Get an iterator for this tree. protected TreeBaseIterator<KeyT, ValueT> GetInOrderIterator() { return new TreeBaseIterator<KeyT, ValueT>(this); } // Iterator class that implements in-order traversal of a tree. protected sealed class TreeBaseIterator<KeyT, ValueT> { // Internal state. private Tree<KeyT, ValueT> tree; private TreeNode<KeyT, ValueT> current; private bool reset; private bool removed; // Constructor. public TreeBaseIterator(Tree<KeyT, ValueT> tree) { this.tree = tree; this.current = null; this.reset = true; this.removed = false; } // Move to the next item in the iteration order. public bool MoveNext() { if(removed) { // The last node was removed, so we are already // positioned on the next node to be visited. removed = false; } else if(reset) { // Start with the left-most node in the tree. current = tree.leftMost; reset = false; } else if(current == null) { // We already reached the end of the tree. return false; } else if(current.right != null) { // Move to the left-most node in the right sub-tree. current = current.right; while(current.left != null) { current = current.left; } } else { // Move up ancestors until we are no longer // the right-most child of our parent. TreeNode<T> parent = current.parent; while(parent != null && parent.right == current) { current = parent; parent = current.parent; } current = parent; } return (current != null); } // Reset the iterator to the start. public void Reset() { current = null; reset = true; removed = false; } // Remove the current item in the iteration order. public void Remove() { // Bail out if we are not currently positioned on a node. if(current == null || removed) { throw new InvalidOperationException (S._("Invalid_BadIteratorPosition")); } // Save the current node. TreeNode<T> node = current; // Move on to the next node in the traversal order. MoveNext(); // Remove the node from the tree. tree.RemoveNode(node); // Record that we have removed "node". removed = true; } // Get the key from the current item. public KeyT Key { get { if(current != null && !removed) { return current.key; } throw new InvalidOperationException (S._("Invalid_BadIteratorPosition")); } } // Get the value from the current item. public ValueT Value { get { if(current != null && !removed) { return current.value; } throw new InvalidOperationException (S._("Invalid_BadIteratorPosition")); } set { if(current != null && !removed) { current.value = value; } else { throw new InvalidOperationException (S._("Invalid_BadIteratorPosition")); } } } }; // class TreeBaseIterator<KeyT, ValueT> }; // class TreeBase<KeyT, ValueT> }; // namespace Generics
#if !CITO using System; using System.IO; using System.Text; #endif // // Read/Write string and byte arrays // //namespace SilentOrbit.ProtocolBuffers //{ public class ProtocolParser { public static string ReadString(CitoStream stream) { byte[] bytes = ReadBytes(stream); return ProtoPlatform.BytesToString(bytes, 0); } /// <summary> /// Reads a length delimited byte array /// </summary> public static byte[] ReadBytes(CitoStream stream) { //VarInt length int length = ReadUInt32(stream); //Bytes byte[] buffer = new byte[length]; int read = 0; while (read < length) { int r = stream.Read(buffer, read, length - read); if (r == 0) #if !CITO throw new InvalidDataException("Expected " + (length - read) + " got " + read); #else return null; #endif read += r; } return buffer; } /// <summary> /// Skip the next varint length prefixed bytes. /// Alternative to ReadBytes when the data is not of interest. /// </summary> public static void SkipBytes(CitoStream stream) { int length = ReadUInt32(stream); if (stream.CanSeek()) stream.Seek(length, CitoSeekOrigin.Current); else ReadBytes(stream); } public static void WriteString(CitoStream stream, string val) { WriteBytes(stream, ProtoPlatform.StringToBytes(val)); } /// <summary> /// Writes length delimited byte array /// </summary> public static void WriteBytes(CitoStream stream, byte[] val) { WriteUInt32_(stream, ProtoPlatform.ArrayLength(val)); stream.Write(val, 0, ProtoPlatform.ArrayLength(val)); } //} //} // // This file contain references on how to write and read // fixed integers and float/double. // //using System; //using System.IO; //namespace SilentOrbit.ProtocolBuffers //{ //public static partial class ProtocolParser //{ //#region Fixed Int, Only for reference //#endregion //} //} // // Reader/Writer for field key // //using System; //using System.IO; //namespace SilentOrbit.ProtocolBuffers //{ //public static partial class ProtocolParser //{ public static Key ReadKey(CitoStream stream) { int n = ReadUInt32(stream); return Key.Create(n >> 3, (n & 0x07)); } public static Key ReadKey_(byte firstByte, CitoStream stream) { if (firstByte < 128) return Key.Create((firstByte >> 3), (firstByte & 0x07)); int fieldID = (ReadUInt32(stream) << 4) | ((firstByte >> 3) & 0x0F); return Key.Create(fieldID, (firstByte & 0x07)); } public static void WriteKey(CitoStream stream, Key key) { int n = (key.GetField() << 3) | (key.GetWireType()); WriteUInt32_(stream, n); } /// <summary> /// Seek past the value for the previously read key. /// </summary> public static void SkipKey(CitoStream stream, Key key) { switch (key.GetWireType()) { case Wire.Fixed32: stream.Seek(4, CitoSeekOrigin.Current); return; case Wire.Fixed64: stream.Seek(8, CitoSeekOrigin.Current); return; case Wire.LengthDelimited: stream.Seek(ProtocolParser.ReadUInt32(stream), CitoSeekOrigin.Current); return; case Wire.Varint: ProtocolParser.ReadSkipVarInt(stream); return; default: #if !CITO throw new NotImplementedException("Unknown wire type: " + key.GetWireType()); #else return; #endif } } /// <summary> /// Read the value for an unknown key as bytes. /// Used to preserve unknown keys during deserialization. /// Requires the message option preserveunknown=true. /// </summary> public static byte[] ReadValueBytes(CitoStream stream, Key key) { byte[] b; int offset = 0; switch (key.GetWireType()) { case Wire.Fixed32: b = new byte[4]; while (offset < 4) offset += stream.Read(b, offset, 4 - offset); return b; case Wire.Fixed64: b = new byte[8]; while (offset < 8) offset += stream.Read(b, offset, 8 - offset); return b; case Wire.LengthDelimited: //Read and include length in value buffer int length = ProtocolParser.ReadUInt32(stream); CitoMemoryStream ms = new CitoMemoryStream(); { //TODO: pass b directly to MemoryStream constructor or skip usage of it completely ProtocolParser.WriteUInt32(ms, length); b = new byte[length + ms.Length()]; byte[] arr = ms.ToArray(); for (int i = 0; i < ProtoPlatform.ArrayLength(arr); i++) { b[i] = arr[i]; } offset = ms.Length(); } //Read data into buffer while (offset < ProtoPlatform.ArrayLength(b)) offset += stream.Read(b, offset, ProtoPlatform.ArrayLength(b) - offset); return b; case Wire.Varint: return ProtocolParser.ReadVarIntBytes(stream); default: #if !CITO throw new NotImplementedException("Unknown wire type: " + key.GetWireType()); #else return null; #endif } } static void WriteUInt32(CitoMemoryStream ms, int length) { #if !CITO throw new NotImplementedException(); #endif } //} //} //using System; //using System.IO; //namespace SilentOrbit.ProtocolBuffers //{ //public static partial class ProtocolParser //{ /// <summary> /// Reads past a varint for an unknown field. /// </summary> public static void ReadSkipVarInt(CitoStream stream) { while (true) { int b = stream.ReadByte(); if (b < 0) #if !CITO throw new IOException("Stream ended too early"); #else return; #endif if ((b & 0x80) == 0) return; //end of varint } } public static byte[] ReadVarIntBytes(CitoStream stream) { byte[] buffer = new byte[10]; int offset = 0; while (true) { int b = stream.ReadByte(); if (b < 0) #if !CITO throw new IOException("Stream ended too early"); #else return null; #endif #if !CITO buffer[offset] = (byte)b; #else buffer[offset] = b.LowByte; #endif offset += 1; if ((b & 0x80) == 0) break; //end of varint if (offset >= ProtoPlatform.ArrayLength(buffer)) #if !CITO throw new InvalidDataException("VarInt too long, more than 10 bytes"); #else return null; #endif } byte[] ret = new byte[offset]; for (int i = 0; i < offset; i++) { ret[i] = buffer[i]; } return ret; } //#region VarInt: int32, uint32, sint32 //[Obsolete("Use (int)ReadUInt64(stream); //yes 64")] /// <summary> /// Since the int32 format is inefficient for negative numbers we have avoided to implement it. /// The same functionality can be achieved using: (int)ReadUInt64(stream); /// </summary> public static int ReadInt32(CitoStream stream) { return ReadUInt64(stream); } //[Obsolete("Use WriteUInt64(stream, (ulong)val); //yes 64, negative numbers are encoded that way")] /// <summary> /// Since the int32 format is inefficient for negative numbers we have avoided to imlplement. /// The same functionality can be achieved using: WriteUInt64(stream, (uint)val); /// Note that 64 must always be used for int32 to generate the ten byte wire format. /// </summary> public static void WriteInt32(CitoStream stream, int val) { //signed varint is always encoded as 64 but values! WriteUInt64(stream, val); } /// <summary> /// Zig-zag signed VarInt format /// </summary> public static int ReadZInt32(CitoStream stream) { int val = ReadUInt32(stream); return (val >> 1) ^ ((val << 31) >> 31); } /// <summary> /// Zig-zag signed VarInt format /// </summary> public static void WriteZInt32(CitoStream stream, int val) { WriteUInt32_(stream, ((val << 1) ^ (val >> 31))); } /// <summary> /// Unsigned VarInt format /// Do not use to read int32, use ReadUint64 for that. /// </summary> public static int ReadUInt32(CitoStream stream) { int b; int val = 0; for (int n = 0; n < 5; n++) { b = stream.ReadByte(); if (b < 0) #if !CITO throw new IOException("Stream ended too early"); #else return 0; #endif //Check that it fits in 32 bits if ((n == 4) && (b & 0xF0) != 0) #if !CITO throw new InvalidDataException("Got larger VarInt than 32bit unsigned"); #else return 0; #endif //End of check if ((b & 0x80) == 0) return val | b << (7 * n); val |= (b & 0x7F) << (7 * n); } #if !CITO throw new InvalidDataException("Got larger VarInt than 32bit unsigned"); #else return 0; #endif } /// <summary> /// Unsigned VarInt format /// </summary> public static void WriteUInt32_(CitoStream stream, int val) { byte[] buffer = new byte[5]; int count = 0; while (true) { #if !CITO buffer[count] = (byte)(val & 0x7F); #else buffer[count] = (val & 0x7F).LowByte; #endif val = val >> 7; if (val == 0) break; buffer[count] |= 0x80; count += 1; } stream.Write(buffer, 0, count + 1); } //#endregion //#region VarInt: int64, UInt64, SInt64 //[Obsolete("Use (long)ReadUInt64(stream); instead")] /// <summary> /// Since the int64 format is inefficient for negative numbers we have avoided to implement it. /// The same functionality can be achieved using: (long)ReadUInt64(stream); /// </summary> public static int ReadInt64(CitoStream stream) { return ReadUInt64(stream); } //[Obsolete("Use WriteUInt64 (stream, (ulong)val); instead")] /// <summary> /// Since the int64 format is inefficient for negative numbers we have avoided to implement. /// The same functionality can be achieved using: WriteUInt64 (stream, (ulong)val); /// </summary> public static void WriteInt64(CitoStream stream, int val) { WriteUInt64(stream, val); } /// <summary> /// Zig-zag signed VarInt format /// </summary> public static int ReadZInt64(CitoStream stream) { int val = ReadUInt64(stream); return (val >> 1) ^ ((val << 63) >> 63); } /// <summary> /// Zig-zag signed VarInt format /// </summary> public static void WriteZInt64(CitoStream stream, int val) { WriteUInt64(stream, ((val << 1) ^ (val >> 63))); } /// <summary> /// Unsigned VarInt format /// </summary> public static int ReadUInt64(CitoStream stream) { int b; int val = 0; for (int n = 0; n < 10; n++) { b = stream.ReadByte(); if (b < 0) #if !CITO throw new IOException("Stream ended too early"); #else return 0; #endif //Check that it fits in 64 bits if ((n == 9) && (b & 0xFE) != 0) #if !CITO throw new InvalidDataException("Got larger VarInt than 64 bit unsigned"); #else return 0; #endif //End of check if ((b & 0x80) == 0) //return val | (ulong)b << (7 * n); return val | b << (7 * n); //val |= (ulong)(b & 0x7F) << (7 * n); val |= (b & 0x7F) << (7 * n); } #if !CITO throw new InvalidDataException("Got larger VarInt than 64 bit unsigned"); #else return 0; #endif } /// <summary> /// Unsigned VarInt format /// </summary> public static void WriteUInt64(CitoStream stream, int val) { byte[] buffer = new byte[10]; int count = 0; while (true) { #if !CITO buffer[count] = (byte)(val & 0x7F); #else buffer[count] = (val & 0x7F).LowByte; #endif val = ProtoPlatform.logical_right_shift(val, 7); if (val == 0) break; buffer[count] |= 0x80; count += 1; } stream.Write(buffer, 0, count + 1); } //#endregion //#region Varint: bool public static bool ReadBool(CitoStream stream) { int b = stream.ReadByte(); if (b < 0) #if !CITO throw new IOException("Stream ended too early"); #else return false; #endif if (b == 1) return true; if (b == 0) return false; #if !CITO throw new InvalidDataException("Invalid boolean value"); #else return false; #endif } public static void WriteBool(CitoStream stream, bool val) { byte ret = 0; if (val) { ret = 1; } stream.WriteByte(ret); } //#endregion } //} ///// <summary> ///// Wrapper for streams that does not support the Position property ///// </summary> //public class StreamRead : Stream //{ // Stream stream; // /// <summary> // /// Bytes left to read // /// </summary> // public int BytesRead { get; private set; } // /// <summary> // /// Define how many bytes are allowed to read // /// </summary> // /// <param name='baseStream'> // /// Base stream. // /// </param> // /// <param name='maxLength'> // /// Max length allowed to read from the stream. // /// </param> // public StreamRead(Stream baseStream) // { // this.stream = baseStream; // } // public override void Flush() // { // throw new NotImplementedException(); // } // public override int Read(byte[] buffer, int offset, int count) // { // int read = stream.Read(buffer, offset, count); // BytesRead += read; // return read; // } // public override int ReadByte() // { // int b = stream.ReadByte(); // BytesRead += 1; // return b; // } // public override long Seek(long offset, SeekOrigin origin) // { // throw new NotImplementedException(); // } // public override void SetLength(long value) // { // throw new NotImplementedException(); // } // public override void Write(byte[] buffer, int offset, int count) // { // throw new NotImplementedException(); // } // public override bool CanRead // { // get // { // return true; // } // } // public override bool CanSeek // { // get // { // return false; // } // } // public override bool CanWrite // { // get // { // return false; // } // } // public override long Length // { // get // { // return stream.Length; // } // } // public override long Position // { // get // { // return this.BytesRead; // } // set // { // throw new NotImplementedException(); // } // } //} public class Wire { public const int Varint = 0; //int32, int64, UInt32, UInt64, SInt32, SInt64, bool, enum public const int Fixed64 = 1; //fixed64, sfixed64, double public const int LengthDelimited = 2; //string, bytes, embedded messages, packed repeated fields //Start = 3, // groups (deprecated) //End = 4, // groups (deprecated) public const int Fixed32 = 5; //32-bit fixed32, SFixed32, float } public class Key { int Field; public int GetField() { return Field; } public void SetField(int value) { Field = value; } int WireType; public int GetWireType() { return WireType; } public void SetWireType(int value) { WireType = value; } public static Key Create(int field, int wireType) { Key k = new Key(); k.Field = field; k.WireType = wireType; return k; } //public override string ToString() //{ // return string.Format("[Key: {0}, {1}]", Field, WireType); //} } /// <summary> /// Storage of unknown fields /// </summary> public class KeyValue { Key Key_; byte[] Value; public static KeyValue Create(Key key, byte[] value) { KeyValue k = new KeyValue(); k.Key_ = key; k.Value = value; return k; } //public override string ToString() //{ // return string.Format("[KeyValue: {0}, {1}, {2} bytes]", Key.Field, Key.WireType, Value.Length); //} } public abstract class CitoStream { public abstract int Read(byte[] buffer, int read, int p); public abstract bool CanSeek(); public abstract void Seek(int length, CitoSeekOrigin seekOrigin); public abstract void Write(byte[] val, int p, int p_3); public abstract void Seek_(int p, CitoSeekOrigin seekOrigin); public abstract int ReadByte(); public abstract void WriteByte(byte p); public abstract int Position(); } public class CitoMemoryStream : CitoStream { byte[] buffer_; int count_; int bufferlength; int position_; public CitoMemoryStream() { buffer_ = new byte[1]; count_ = 0; bufferlength = 1; position_ = 0; } public int Length() { return count_; } public byte[] ToArray() { return buffer_; } public static CitoMemoryStream Create(byte[] buffer, int length) { CitoMemoryStream m = new CitoMemoryStream(); m.buffer_ = buffer; m.count_ = length; m.bufferlength = length; m.position_ = 0; return m; } public byte[] GetBuffer() { return buffer_; } public override int Read(byte[] buffer, int offset, int count) { for (int i = 0; i < count; i++) { if (position_ + i >= this.count_) { position_ += i; return i; } buffer[offset + i] = this.buffer_[position_ + i]; } position_ += count; return count; } public override bool CanSeek() { return false; } public override void Seek(int length, CitoSeekOrigin seekOrigin) { switch (seekOrigin) { case CitoSeekOrigin.Current: position_ += length; break; } } public override void Write(byte[] buffer, int offset, int count) { for (int i = 0; i < count; i++) { WriteByte(buffer[offset + i]); } } public override void Seek_(int p, CitoSeekOrigin seekOrigin) { } public override int ReadByte() { if (position_ >= count_) { return -1; } return buffer_[position_++]; } public override void WriteByte(byte p) { if (position_ >= bufferlength) { byte[] buffer2 = new byte[bufferlength * 2]; for (int i = 0; i < bufferlength; i++) { buffer2[i] = buffer_[i]; } buffer_ = buffer2; bufferlength = bufferlength * 2; } buffer_[position_] = p; if (position_ == count_) { count_++; } position_++; } public override int Position() { return position_; } } public class ProtoPlatform { public static byte[] StringToBytes(string s) { byte[] b; #if CITO #if CS native { b = Encoding.UTF8.GetBytes(s); } #elif JS native { // http://stackoverflow.com/a/18729931 var str = s; var utf8 = []; for (var i=0; i < str.length; i++) { var charcode = str.charCodeAt(i); if (charcode < 0x80) utf8.push(charcode); else if (charcode < 0x800) { utf8.push(0xc0 | (charcode >> 6), 0x80 | (charcode & 0x3f)); } else if (charcode < 0xd800 || charcode >= 0xe000) { utf8.push(0xe0 | (charcode >> 12), 0x80 | ((charcode>>6) & 0x3f), 0x80 | (charcode & 0x3f)); } // surrogate pair else { i++; // UTF-16 encodes 0x10000-0x10FFFF by // subtracting 0x10000 and splitting the // 20 bits of 0x0-0xFFFFF into two halves charcode = 0x10000 + (((charcode & 0x3ff)<<10) | (str.charCodeAt(i) & 0x3ff)) utf8.push(0xf0 | (charcode >>18), 0x80 | ((charcode>>12) & 0x3f), 0x80 | ((charcode>>6) & 0x3f), 0x80 | (charcode & 0x3f)); } } b = utf8; } #elif JAVA native { try { b = s.getBytes("UTF-8"); } catch (Exception e) { b = null; } } #else b = null; #endif #else b = Encoding.UTF8.GetBytes(s); #endif return b; } public static string BytesToString(byte[] bytes, int length) { string s; #if CITO #if CS native { s = Encoding.UTF8.GetString(bytes); } #elif JS native { var arr = new Uint8Array(bytes.length); for(var i = 0; i < bytes.length;i++) { arr[i] = bytes[i]; } var encodedString = String.fromCharCode.apply(null, arr); var decodedString = decodeURIComponent(escape(encodedString)); s = decodedString; } #elif JAVA native { try { s = new String(bytes, "UTF-8"); } catch (Exception e) { s = null; } } #else s = null; #endif #else s = Encoding.UTF8.GetString(bytes); #endif return s; } public static int ArrayLength(byte[] a) { int len; #if CITO #if CS native { len = a.Length; } #elif JAVA native { len = a.length; } #elif JS native { len = a.length; } #else len = 0; #endif #else len = a.Length; #endif return len; } public static byte IntToByte(int a) { #if CITO return a.LowByte; #else return (byte)a; #endif } //http://stackoverflow.com/a/8248336 public static int logical_right_shift(int x, int n) { int mask = ~(-1 << n) << (32 - n); return ~mask & ((x >> n) | mask); } } public enum CitoSeekOrigin { Current }
using System; using System.Buffers; using System.Collections.Generic; using System.IO; using SharpCompress.Readers; namespace SharpCompress { internal static class Utility { public static ReadOnlyCollection<T> ToReadOnly<T>(this ICollection<T> items) { return new ReadOnlyCollection<T>(items); } /// <summary> /// Performs an unsigned bitwise right shift with the specified number /// </summary> /// <param name="number">Number to operate on</param> /// <param name="bits">Amount of bits to shift</param> /// <returns>The resulting number from the shift operation</returns> public static int URShift(int number, int bits) { if (number >= 0) { return number >> bits; } return (number >> bits) + (2 << ~bits); } /// <summary> /// Performs an unsigned bitwise right shift with the specified number /// </summary> /// <param name="number">Number to operate on</param> /// <param name="bits">Amount of bits to shift</param> /// <returns>The resulting number from the shift operation</returns> public static long URShift(long number, int bits) { if (number >= 0) { return number >> bits; } return (number >> bits) + (2L << ~bits); } public static void SetSize(this List<byte> list, int count) { if (count > list.Count) { // Ensure the list only needs to grow once list.Capacity = count; for (int i = list.Count; i < count; i++) { list.Add(0x0); } } else { list.RemoveRange(count, list.Count - count); } } public static void ForEach<T>(this IEnumerable<T> items, Action<T> action) { foreach (T item in items) { action(item); } } public static void Copy(Array sourceArray, long sourceIndex, Array destinationArray, long destinationIndex, long length) { if (sourceIndex > Int32.MaxValue || sourceIndex < Int32.MinValue) { throw new ArgumentOutOfRangeException(); } if (destinationIndex > Int32.MaxValue || destinationIndex < Int32.MinValue) { throw new ArgumentOutOfRangeException(); } if (length > Int32.MaxValue || length < Int32.MinValue) { throw new ArgumentOutOfRangeException(); } Array.Copy(sourceArray, (int)sourceIndex, destinationArray, (int)destinationIndex, (int)length); } public static IEnumerable<T> AsEnumerable<T>(this T item) { yield return item; } public static void CheckNotNull(this object obj, string name) { if (obj is null) { throw new ArgumentNullException(name); } } public static void CheckNotNullOrEmpty(this string obj, string name) { obj.CheckNotNull(name); if (obj.Length == 0) { throw new ArgumentException("String is empty.", name); } } public static void Skip(this Stream source, long advanceAmount) { if (source.CanSeek) { source.Position += advanceAmount; return; } byte[] buffer = GetTransferByteArray(); try { int read = 0; int readCount = 0; do { readCount = buffer.Length; if (readCount > advanceAmount) { readCount = (int)advanceAmount; } read = source.Read(buffer, 0, readCount); if (read <= 0) { break; } advanceAmount -= read; if (advanceAmount == 0) { break; } } while (true); } finally { ArrayPool<byte>.Shared.Return(buffer); } } public static void Skip(this Stream source) { byte[] buffer = GetTransferByteArray(); try { do { } while (source.Read(buffer, 0, buffer.Length) == buffer.Length); } finally { ArrayPool<byte>.Shared.Return(buffer); } } public static DateTime DosDateToDateTime(UInt16 iDate, UInt16 iTime) { int year = iDate / 512 + 1980; int month = iDate % 512 / 32; int day = iDate % 512 % 32; int hour = iTime / 2048; int minute = iTime % 2048 / 32; int second = iTime % 2048 % 32 * 2; if (iDate == UInt16.MaxValue || month == 0 || day == 0) { year = 1980; month = 1; day = 1; } if (iTime == UInt16.MaxValue) { hour = minute = second = 0; } DateTime dt; try { dt = new DateTime(year, month, day, hour, minute, second, DateTimeKind.Local); } catch { dt = new DateTime(); } return dt; } public static uint DateTimeToDosTime(this DateTime? dateTime) { if (dateTime is null) { return 0; } var localDateTime = dateTime.Value.ToLocalTime(); return (uint)( (localDateTime.Second / 2) | (localDateTime.Minute << 5) | (localDateTime.Hour << 11) | (localDateTime.Day << 16) | (localDateTime.Month << 21) | ((localDateTime.Year - 1980) << 25)); } public static DateTime DosDateToDateTime(UInt32 iTime) { return DosDateToDateTime((UInt16)(iTime / 65536), (UInt16)(iTime % 65536)); } /// <summary> /// Convert Unix time value to a DateTime object. /// </summary> /// <param name="unixtime">The Unix time stamp you want to convert to DateTime.</param> /// <returns>Returns a DateTime object that represents value of the Unix time.</returns> public static DateTime UnixTimeToDateTime(long unixtime) { DateTime sTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); return sTime.AddSeconds(unixtime); } public static long TransferTo(this Stream source, Stream destination) { byte[] array = GetTransferByteArray(); try { long total = 0; while (ReadTransferBlock(source, array, out int count)) { total += count; destination.Write(array, 0, count); } return total; } finally { ArrayPool<byte>.Shared.Return(array); } } public static long TransferTo(this Stream source, Stream destination, Common.Entry entry, IReaderExtractionListener readerExtractionListener) { byte[] array = GetTransferByteArray(); try { var iterations = 0; long total = 0; while (ReadTransferBlock(source, array, out int count)) { total += count; destination.Write(array, 0, count); iterations++; readerExtractionListener.FireEntryExtractionProgress(entry, total, iterations); } return total; } finally { ArrayPool<byte>.Shared.Return(array); } } private static bool ReadTransferBlock(Stream source, byte[] array, out int count) { return (count = source.Read(array, 0, array.Length)) != 0; } private static byte[] GetTransferByteArray() { return ArrayPool<byte>.Shared.Rent(81920); } public static bool ReadFully(this Stream stream, byte[] buffer) { int total = 0; int read; while ((read = stream.Read(buffer, total, buffer.Length - total)) > 0) { total += read; if (total >= buffer.Length) { return true; } } return (total >= buffer.Length); } public static bool ReadFully(this Stream stream, Span<byte> buffer) { int total = 0; int read; while ((read = stream.Read(buffer.Slice(total, buffer.Length - total))) > 0) { total += read; if (total >= buffer.Length) { return true; } } return (total >= buffer.Length); } public static string TrimNulls(this string source) { return source.Replace('\0', ' ').Trim(); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Linq; using System.Threading; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.Sprites; using osu.Framework.Testing; using osu.Framework.Tests.Visual; namespace osu.Framework.Tests.Containers { [System.ComponentModel.Description("ensure valid container state in various scenarios")] [HeadlessTest] public class TestSceneContainerState : FrameworkTestScene { /// <summary> /// Tests if a drawable can be added to a container, removed, and then re-added to the same container. /// </summary> [Test] public void TestPreLoadReAdding() { var container = new Container(); var sprite = new Sprite(); // Add Assert.DoesNotThrow(() => container.Add(sprite)); Assert.IsTrue(container.Contains(sprite)); // Remove Assert.DoesNotThrow(() => container.Remove(sprite)); Assert.IsFalse(container.Contains(sprite)); // Re-add Assert.DoesNotThrow(() => container.Add(sprite)); Assert.IsTrue(container.Contains(sprite)); } /// <summary> /// Tests whether adding a child to multiple containers by abusing <see cref="Container{T}.Children"/> /// results in a <see cref="InvalidOperationException"/>. /// </summary> [Test] public void TestPreLoadMultipleAdds() { // Non-async Assert.Throws<InvalidOperationException>(() => { var unused = new Container { // Container is an IReadOnlyList<T>, so Children can accept a Container. // This further means that CompositeDrawable.AddInternal will try to add all of // the children of the Container that was set to Children, which should throw an exception Children = new Container { Child = new Container() } }; }); } /// <summary> /// The same as <see cref="TestPreLoadMultipleAdds"/> however instead runs after the container is loaded. /// </summary> [Test] public void TestLoadedMultipleAdds() { AddAssert("Test loaded multiple adds", () => { var loadedContainer = new Container(); Add(loadedContainer); try { loadedContainer.Add(new Container { // Container is an IReadOnlyList<T>, so Children can accept a Container. // This further means that CompositeDrawable.AddInternal will try to add all of // the children of the Container that was set to Children, which should throw an exception Children = new Container { Child = new Container() } }); return false; } catch (InvalidOperationException) { return true; } }); } /// <summary> /// Tests whether the result of a <see cref="Container{T}.Contains(T)"/> operation is valid between multiple containers. /// This tests whether the comparator + equality operation in <see cref="CompositeDrawable.IndexOfInternal(Drawable)"/> is valid. /// </summary> [Test] public void TestContainerContains() { var drawableA = new Sprite(); var drawableB = new Sprite(); var containerA = new Container { Child = drawableA }; var containerB = new Container { Child = drawableB }; var newContainer = new Container<Container> { Children = new[] { containerA, containerB } }; // Because drawableA and drawableB have been added to separate containers, // they will both have Depth = 0 and ChildID = 1, which leads to edge cases if a // sorting comparer that doesn't compare references is used for Contains(). // If this is not handled properly, it may have devastating effects in, e.g. Remove(). Assert.IsTrue(newContainer.First(c => c.Contains(drawableA)) == containerA); Assert.IsTrue(newContainer.First(c => c.Contains(drawableB)) == containerB); Assert.DoesNotThrow(() => newContainer.First(c => c.Contains(drawableA)).Remove(drawableA)); Assert.DoesNotThrow(() => newContainer.First(c => c.Contains(drawableB)).Remove(drawableB)); } [Test] public void TestChildrenRemovedOnClearInternal() { var drawableA = new Sprite(); var drawableB = new Sprite(); var drawableC = new Sprite(); var containerA = new Container { Child = drawableC }; var targetContainer = new Container { Children = new Drawable[] { drawableA, drawableB, containerA } }; Assert.That(targetContainer, Has.Count.Not.Zero); targetContainer.ClearInternal(); // Immediate children removed Assert.That(targetContainer, Has.Count.Zero); // Nested container's children not removed Assert.That(containerA, Has.Count.EqualTo(1)); } [TestCase(false)] [TestCase(true)] public void TestUnbindOnClearInternal(bool shouldDispose) { bool unbound = false; var drawableA = new Sprite().With(d => { d.OnUnbindAllBindables += () => unbound = true; }); var container = new Container { Children = new[] { drawableA } }; container.ClearInternal(shouldDispose); Assert.That(container, Has.Count.Zero); Assert.That(unbound, Is.EqualTo(shouldDispose)); GC.KeepAlive(drawableA); } [TestCase(false)] [TestCase(true)] public void TestDisposeOnClearInternal(bool shouldDispose) { bool disposed = false; var drawableA = new Sprite().With(d => { d.OnDispose += () => disposed = true; }); var container = new Container { Children = new[] { drawableA } }; Assert.That(container, Has.Count.Not.Zero); container.ClearInternal(shouldDispose); Assert.That(container, Has.Count.Zero); // Disposal happens asynchronously int iterations = 20; while (iterations-- > 0) { if (disposed) break; Thread.Sleep(100); } Assert.That(disposed, Is.EqualTo(shouldDispose)); GC.KeepAlive(drawableA); } [Test] public void TestAsyncLoadClearWhileAsyncDisposing() { Container safeContainer = null; DelayedLoadDrawable drawable = null; // We are testing a disposal deadlock scenario. When the test runner exits, it will attempt to dispose the game hierarchy, // and will fall into the deadlocked state itself. For this reason an intermediate "safe" container is used, which is // removed from the hierarchy immediately after use and is thus not disposed when the test runner exits. // This does NOT free up the LoadComponentAsync thread pool for use by other tests - that thread is in a deadlocked state forever. AddStep("add safe container", () => Add(safeContainer = new Container())); // Get the drawable into an async loading state AddStep("begin async load", () => { safeContainer.LoadComponentAsync(drawable = new DelayedLoadDrawable(), _ => { }); Remove(safeContainer); }); AddUntilStep("wait until loading", () => drawable.LoadState == LoadState.Loading); // Make the async disposal queue attempt to dispose the drawable AddStep("enqueue async disposal", () => AsyncDisposalQueue.Enqueue(drawable)); AddWaitStep("wait for disposal task to run", 10); // Clear the contents of the drawable, causing a second async disposal AddStep("allow load", () => drawable.AllowLoad.Set()); AddUntilStep("drawable was cleared successfully", () => drawable.HasCleared); } [Test] public void TestExpireChildAfterLoad() { Container container = null; Drawable child = null; AddStep("add container and child", () => { Add(container = new Container { Child = child = new Box() }); }); AddStep("expire child", () => child.Expire()); AddUntilStep("container has no children", () => container.Count == 0); } [Test] public void TestExpireChildBeforeLoad() { Container container = null; AddStep("add container", () => Add(container = new Container())); AddStep("add expired child", () => { var child = new Box(); child.Expire(); container.Add(child); }); AddUntilStep("container has no children", () => container.Count == 0); } private class DelayedLoadDrawable : CompositeDrawable { public readonly ManualResetEventSlim AllowLoad = new ManualResetEventSlim(); public bool HasCleared { get; private set; } public DelayedLoadDrawable() { InternalChild = new Box(); } [BackgroundDependencyLoader] private void load() { if (!AllowLoad.Wait(TimeSpan.FromSeconds(10))) throw new TimeoutException(); ClearInternal(); HasCleared = true; } } [Test] public void TestAliveChangesDuringExpiry() { TestContainer container = null; int count = 0; void checkCount() => count = container.AliveInternalChildren.Count; AddStep("create container", () => Child = container = new TestContainer()); AddStep("perform test", () => { container.Add(new Box()); container.Add(new Box()); container.ScheduleAfterChildren(checkCount); }); AddAssert("correct count", () => count == 2); AddStep("perform test", () => { container.First().Expire(); container.Add(new Box()); container.ScheduleAfterChildren(checkCount); }); AddAssert("correct count", () => count == 2); } [Test] public void TestAliveChildrenContainsOnlyAliveChildren() { Container container = null; Drawable aliveChild = null; Drawable nonAliveChild = null; AddStep("create container", () => { Child = container = new Container { Children = new[] { aliveChild = new Box(), nonAliveChild = new Box { LifetimeStart = double.MaxValue } } }; }); AddAssert("1 alive child", () => container.AliveChildren.Count == 1); AddAssert("alive child contained", () => container.AliveChildren.Contains(aliveChild)); AddAssert("non-alive child not contained", () => !container.AliveChildren.Contains(nonAliveChild)); } private class TestContainer : Container { public new void ScheduleAfterChildren(Action action) => SchedulerAfterChildren.AddDelayed(action, TransformDelay); } } }
// 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.13.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; public static partial class SubnetsOperationsExtensions { /// <summary> /// The delete subnet operation deletes the specified subnet. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='subnetName'> /// The name of the subnet. /// </param> public static void Delete(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName) { Task.Factory.StartNew(s => ((ISubnetsOperations)s).DeleteAsync(resourceGroupName, virtualNetworkName, subnetName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The delete subnet operation deletes the specified subnet. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='subnetName'> /// The name of the subnet. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync( this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, subnetName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// The delete subnet operation deletes the specified subnet. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='subnetName'> /// The name of the subnet. /// </param> public static void BeginDelete(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName) { Task.Factory.StartNew(s => ((ISubnetsOperations)s).BeginDeleteAsync(resourceGroupName, virtualNetworkName, subnetName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The delete subnet operation deletes the specified subnet. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='subnetName'> /// The name of the subnet. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginDeleteAsync( this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, subnetName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// The Get subnet operation retreives information about the specified subnet. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='subnetName'> /// The name of the subnet. /// </param> /// <param name='expand'> /// expand references resources. /// </param> public static Subnet Get(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName, string expand = default(string)) { return Task.Factory.StartNew(s => ((ISubnetsOperations)s).GetAsync(resourceGroupName, virtualNetworkName, subnetName, expand), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get subnet operation retreives information about the specified subnet. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='subnetName'> /// The name of the subnet. /// </param> /// <param name='expand'> /// expand references resources. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Subnet> GetAsync( this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<Subnet> result = await operations.GetWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, subnetName, expand, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// The Put Subnet operation creates/updates a subnet in thespecified virtual /// network /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='subnetName'> /// The name of the subnet. /// </param> /// <param name='subnetParameters'> /// Parameters supplied to the create/update Subnet operation /// </param> public static Subnet CreateOrUpdate(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName, Subnet subnetParameters) { return Task.Factory.StartNew(s => ((ISubnetsOperations)s).CreateOrUpdateAsync(resourceGroupName, virtualNetworkName, subnetName, subnetParameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Put Subnet operation creates/updates a subnet in thespecified virtual /// network /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='subnetName'> /// The name of the subnet. /// </param> /// <param name='subnetParameters'> /// Parameters supplied to the create/update Subnet operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Subnet> CreateOrUpdateAsync( this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName, Subnet subnetParameters, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<Subnet> result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, subnetName, subnetParameters, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// The Put Subnet operation creates/updates a subnet in thespecified virtual /// network /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='subnetName'> /// The name of the subnet. /// </param> /// <param name='subnetParameters'> /// Parameters supplied to the create/update Subnet operation /// </param> public static Subnet BeginCreateOrUpdate(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName, Subnet subnetParameters) { return Task.Factory.StartNew(s => ((ISubnetsOperations)s).BeginCreateOrUpdateAsync(resourceGroupName, virtualNetworkName, subnetName, subnetParameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Put Subnet operation creates/updates a subnet in thespecified virtual /// network /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='subnetName'> /// The name of the subnet. /// </param> /// <param name='subnetParameters'> /// Parameters supplied to the create/update Subnet operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Subnet> BeginCreateOrUpdateAsync( this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName, Subnet subnetParameters, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<Subnet> result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, subnetName, subnetParameters, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// The List subnets opertion retrieves all the subnets in a virtual network. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> public static IPage<Subnet> List(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName) { return Task.Factory.StartNew(s => ((ISubnetsOperations)s).ListAsync(resourceGroupName, virtualNetworkName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The List subnets opertion retrieves all the subnets in a virtual network. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Subnet>> ListAsync( this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<IPage<Subnet>> result = await operations.ListWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// The List subnets opertion retrieves all the subnets in a virtual network. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<Subnet> ListNext(this ISubnetsOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((ISubnetsOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The List subnets opertion retrieves all the subnets in a virtual network. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Subnet>> ListNextAsync( this ISubnetsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<IPage<Subnet>> result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false); return result.Body; } } }
/* ==================================================================== 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 NPOI.HSSF.UserModel { using System; using System.Collections; using NPOI.HSSF.Model; using NPOI.HSSF.Record; using NPOI.HSSF.Util; using NPOI.SS.UserModel; /// <summary> /// High level representation of the style of a cell in a sheet of a workbook. /// @author Andrew C. Oliver (acoliver at apache dot org) /// @author Jason Height (jheight at chariot dot net dot au) /// </summary> internal class HSSFCellStyle : ICellStyle { private ExtendedFormatRecord format = null; private short index = 0; private NPOI.HSSF.Model.InternalWorkbook workbook = null; /// <summary> /// Initializes a new instance of the <see cref="HSSFCellStyle"/> class. /// </summary> /// <param name="index">The index.</param> /// <param name="rec">The record.</param> /// <param name="workbook">The workbook.</param> public HSSFCellStyle(short index, ExtendedFormatRecord rec, HSSFWorkbook workbook) :this(index, rec, workbook.Workbook) { } /// <summary> /// Initializes a new instance of the <see cref="HSSFCellStyle"/> class. /// </summary> /// <param name="index">The index.</param> /// <param name="rec">The record.</param> /// <param name="workbook">The workbook.</param> public HSSFCellStyle(short index, ExtendedFormatRecord rec, NPOI.HSSF.Model.InternalWorkbook workbook) { this.workbook = workbook; this.index = index; format = rec; } /// <summary> /// Get the index within the HSSFWorkbook (sequence within the collection of ExtnededFormat objects) /// </summary> /// <value>Unique index number of the Underlying record this style represents (probably you don't care /// Unless you're comparing which one is which)</value> public short Index { get { return index; } } /// <summary> /// Gets the parent style. /// </summary> /// <value>the parent style for this cell style. /// In most cases this will be null, but in a few /// cases there'll be a fully defined parent.</value> public HSSFCellStyle ParentStyle { get { short parentIndex = format.ParentIndex; // parentIndex equal 0xFFF indicates no inheritance from a cell style XF (See 2.4.353 XF) if ( parentIndex == 0|| parentIndex == 0xFFF) { return null; } return new HSSFCellStyle( parentIndex, workbook.GetExFormatAt(parentIndex), workbook ); } } /// <summary> /// Get the index of the format /// </summary> /// <value>The data format.</value> public short DataFormat { get { return format.FormatIndex; } set { format.FormatIndex = (value); } } /// <summary> /// Get the contents of the format string, by looking up /// the DataFormat against the bound workbook /// </summary> /// <returns></returns> public String GetDataFormatString() { HSSFDataFormat format = new HSSFDataFormat(workbook); return format.GetFormat(DataFormat); } /// <summary> /// Get the contents of the format string, by looking up /// the DataFormat against the supplied workbook /// </summary> /// <param name="workbook">The workbook.</param> /// <returns></returns> public String GetDataFormatString(NPOI.HSSF.Model.InternalWorkbook workbook) { HSSFDataFormat format = new HSSFDataFormat(workbook); return format.GetFormat(DataFormat); } /// <summary> /// Set the font for this style /// </summary> /// <param name="font">a font object Created or retreived from the HSSFWorkbook object</param> public void SetFont(NPOI.SS.UserModel.IFont font) { format.IsIndentNotParentFont=(true); short fontindex = font.Index; format.FontIndex=(fontindex); } /// <summary> /// Gets the index of the font for this style. /// </summary> /// <value>The index of the font.</value> public short FontIndex { get { return format.FontIndex; } } /// <summary> /// Gets the font for this style /// </summary> /// <param name="parentWorkbook">The parent workbook that this style belongs to.</param> /// <returns></returns> public IFont GetFont(IWorkbook parentWorkbook) { return ((HSSFWorkbook)parentWorkbook).GetFontAt(FontIndex); } /// <summary> /// Get whether the cell's using this style are to be hidden /// </summary> /// <value>whether the cell using this style should be hidden</value> public bool IsHidden { get { return format.IsHidden; } set { format.IsIndentNotParentCellOptions=(true); format.IsHidden=(value); } } /// <summary> /// Get whether the cell's using this style are to be locked /// </summary> /// <value>whether the cell using this style should be locked</value> public bool IsLocked { get { return format.IsLocked; } set { format.IsIndentNotParentCellOptions=(true); format.IsLocked=(value); } } /// <summary> /// Get the type of horizontal alignment for the cell /// </summary> /// <value> the type of alignment</value> public HorizontalAlignment Alignment { get { return (HorizontalAlignment)format.Alignment; } set { format.IsIndentNotParentAlignment=(true); format.Alignment=(short)value; } } /// <summary> /// Gets or sets a value indicating whether the text should be wrapped /// </summary> /// <value><c>true</c> if [wrap text]; otherwise, <c>false</c>.</value> public bool WrapText { get { return format.WrapText; } set { format.IsIndentNotParentAlignment = (true); format.WrapText = (value); } } /// <summary> /// Gets or sets the vertical alignment for the cell. /// </summary> /// <value>the type of alignment</value> public VerticalAlignment VerticalAlignment { get { return (VerticalAlignment)format.VerticalAlignment; } set { format.VerticalAlignment=(short)value; } } /// <summary> /// Gets or sets the degree of rotation for the text in the cell /// </summary> /// <value>The rotation degrees (between -90 and 90 degrees).</value> public short Rotation { get { short rotation = format.Rotation; if (rotation == 0xff) { return rotation; } if (rotation > 90) //This is actually the 4th quadrant rotation = (short)(90 - rotation); return rotation; } set { short rotation = value; if (rotation == 0xff) { }else if ((value < 0) && (value >= -90)) { //Take care of the funny 4th quadrant Issue //The 4th quadrant (-1 to -90) is stored as (91 to 180) rotation = (short)(90 - value); } else if ((value < -90) || (value > 90)) { //Do not allow an incorrect rotation to be Set throw new ArgumentException("The rotation must be between -90 and 90 degrees, or 0xff"); } format.Rotation=(rotation); } } /// <summary> /// Verifies that this style belongs to the supplied Workbook. /// Will throw an exception if it belongs to a different one. /// This is normally called when trying to assign a style to a /// cell, to ensure the cell and the style are from the same /// workbook (if they're not, it won't work) /// </summary> /// <param name="wb">The workbook.</param> public void VerifyBelongsToWorkbook(HSSFWorkbook wb) { if (wb.Workbook != workbook) { throw new ArgumentException("This Style does not belong to the supplied Workbook. Are you trying to assign a style from one workbook to the cell of a differnt workbook?"); } } /// <summary> /// Gets or sets the number of spaces to indent the text in the cell /// </summary> /// <value>number of spaces</value> public short Indention { get{return format.Indent;} set { format.Indent = (value); } } /// <summary> /// Gets or sets the type of border to use for the left border of the cell /// </summary> /// <value>The border type.</value> public BorderStyle BorderLeft { get { return (BorderStyle)format.BorderLeft; } set { format.IsIndentNotParentBorder=(true); format.BorderLeft=(short)value; } } /// <summary> /// Gets or sets the type of border to use for the right border of the cell /// </summary> /// <value>The border type.</value> public BorderStyle BorderRight { get { return (BorderStyle)format.BorderRight; } set { format.IsIndentNotParentBorder = (true); format.BorderRight = (short)value; } } /// <summary> /// Gets or sets the type of border to use for the top border of the cell /// </summary> /// <value>The border type.</value> public BorderStyle BorderTop { get { return (BorderStyle)format.BorderTop; } set { format.IsIndentNotParentBorder = (true); format.BorderTop = (short)value; } } /// <summary> /// Gets or sets the type of border to use for the bottom border of the cell /// </summary> /// <value>The border type.</value> public BorderStyle BorderBottom { get { return (BorderStyle)format.BorderBottom; } set { format.IsIndentNotParentBorder = true; format.BorderBottom = (short)value; } } /// <summary> /// Gets or sets the color to use for the left border /// </summary> /// <value>The index of the color definition</value> /// @see org.apache.poi.hssf.usermodel.HSSFPalette#GetColor(short) public short LeftBorderColor { get { return format.LeftBorderPaletteIdx; } set { format.LeftBorderPaletteIdx = (value); } } /// <summary> /// Gets or sets the color to use for the left border. /// </summary> /// <value>The index of the color definition</value> /// @see org.apache.poi.hssf.usermodel.HSSFPalette#GetColor(short) public short RightBorderColor { get { return format.RightBorderPaletteIdx; } set { format.RightBorderPaletteIdx = (value); } } /// <summary> /// Gets or sets the color to use for the top border /// </summary> /// <value>The index of the color definition.</value> /// @see org.apache.poi.hssf.usermodel.HSSFPalette#GetColor(short) public short TopBorderColor { get { return format.TopBorderPaletteIdx; } set { format.TopBorderPaletteIdx = (value); } } /// <summary> /// Gets or sets the color to use for the left border /// </summary> /// <value>The index of the color definition.</value> /// @see org.apache.poi.hssf.usermodel.HSSFPalette#GetColor(short) public short BottomBorderColor { get { return format.BottomBorderPaletteIdx; } set { format.BottomBorderPaletteIdx = (value); } } /// <summary> /// Gets or sets whether the cell is shrink-to-fit /// </summary> public bool ShrinkToFit { get { return format.ShrinkToFit; } set { format.ShrinkToFit = value; } } /// <summary> /// Gets or sets the fill pattern. - Set to 1 to Fill with foreground color /// </summary> /// <value>The fill pattern.</value> public FillPatternType FillPattern { get { return (FillPatternType)format.AdtlFillPattern; } set { format.AdtlFillPattern=(short)value; } } /// <summary> /// Checks if the background and foreground Fills are Set correctly when one /// or the other is Set to the default color. /// Works like the logic table below: /// BACKGROUND FOREGROUND /// NONE AUTOMATIC /// 0x41 0x40 /// NONE RED/ANYTHING /// 0x40 0xSOMETHING /// </summary> private void CheckDefaultBackgroundFills() { if (format.FillForeground == HSSFColor.AUTOMATIC.index) { //JMH: Why +1, hell why not. I guess it made some sense to someone at the time. Doesnt //to me now.... But experience has shown that when the fore is Set to AUTOMATIC then the //background needs to be incremented...... if (format.FillBackground != (HSSFColor.AUTOMATIC.index + 1)) FillBackgroundColor=((short)(HSSFColor.AUTOMATIC.index + 1)); } else if (format.FillBackground == HSSFColor.AUTOMATIC.index + 1) //Now if the forground Changes to a non-AUTOMATIC color the background Resets itself!!! if (format.FillForeground != HSSFColor.AUTOMATIC.index) FillBackgroundColor=(HSSFColor.AUTOMATIC.index); } /** * Clones all the style information from another * HSSFCellStyle, onto this one. This * HSSFCellStyle will then have all the same * properties as the source, but the two may * be edited independently. * Any stylings on this HSSFCellStyle will be lost! * * The source HSSFCellStyle could be from another * HSSFWorkbook if you like. This allows you to * copy styles from one HSSFWorkbook to another. */ public void CloneStyleFrom(ICellStyle source) { if (source is HSSFCellStyle) { this.CloneStyleFrom((HSSFCellStyle)source); } else { throw new ArgumentException("Can only clone from one HSSFCellStyle to another, not between HSSFCellStyle and XSSFCellStyle"); } } /// <summary> /// Clones all the style information from another /// HSSFCellStyle, onto this one. This /// HSSFCellStyle will then have all the same /// properties as the source, but the two may /// be edited independently. /// Any stylings on this HSSFCellStyle will be lost! /// The source HSSFCellStyle could be from another /// HSSFWorkbook if you like. This allows you to /// copy styles from one HSSFWorkbook to another. /// </summary> /// <param name="source">The source.</param> public void CloneStyleFrom(HSSFCellStyle source) { // First we need to clone the extended format // record format.CloneStyleFrom(source.format); // Handle matching things if we cross workbooks if (workbook != source.workbook) { // Then we need to clone the format string, // and update the format record for this short fmt = (short)workbook.CreateFormat( source.GetDataFormatString() ); this.DataFormat=(fmt); // Finally we need to clone the font, // and update the format record for this FontRecord fr = workbook.CreateNewFont(); fr.CloneStyleFrom( source.workbook.GetFontRecordAt( source.FontIndex ) ); HSSFFont font = new HSSFFont( (short)workbook.GetFontIndex(fr), fr ); this.SetFont(font); } } /// <summary> /// Gets or sets the color of the fill background. /// </summary> /// <value>The color of the fill background.</value> /// Set the background Fill color. /// <example> /// cs.SetFillPattern(HSSFCellStyle.FINE_DOTS ); /// cs.SetFillBackgroundColor(new HSSFColor.RED().Index); /// optionally a Foreground and background Fill can be applied: /// Note: Ensure Foreground color is Set prior to background /// cs.SetFillPattern(HSSFCellStyle.FINE_DOTS ); /// cs.SetFillForegroundColor(new HSSFColor.BLUE().Index); /// cs.SetFillBackgroundColor(new HSSFColor.RED().Index); /// or, for the special case of SOLID_Fill: /// cs.SetFillPattern(HSSFCellStyle.SOLID_FOREGROUND ); /// cs.SetFillForegroundColor(new HSSFColor.RED().Index); /// It is necessary to Set the Fill style in order /// for the color to be shown in the cell. /// </example> public short FillBackgroundColor { get { short result = format.FillBackground; //JMH: Do this ridiculous conversion, and let HSSFCellStyle //internally migrate back and forth if (result == (HSSFColor.AUTOMATIC.index + 1)) return HSSFColor.AUTOMATIC.index; else return result; } set { format.FillBackground=value; CheckDefaultBackgroundFills(); } } /// <summary> /// Gets or sets the foreground Fill color /// </summary> /// <value>Fill color.</value> /// @see org.apache.poi.hssf.usermodel.HSSFPalette#GetColor(short) public short FillForegroundColor { get{return format.FillForeground;} set { format.FillForeground = value; CheckDefaultBackgroundFills(); } } /** * Gets the name of the user defined style. * Returns null for built in styles, and * styles where no name has been defined */ public String UserStyleName { get { StyleRecord sr = workbook.GetStyleRecord(index); if (sr == null) { return null; } if (sr.IsBuiltin) { return null; } return sr.Name; } set { StyleRecord sr = workbook.GetStyleRecord(index); if (sr == null) { sr = workbook.CreateStyleRecord(index); } // All Style records start as "builtin", but generally // only 20 and below really need to be if (sr.IsBuiltin && index <= 20) { throw new ArgumentException("Unable to set user specified style names for built in styles!"); } sr.Name = value; } } /// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <returns> /// A hash code for the current <see cref="T:System.Object"/>. /// </returns> public override int GetHashCode() { int prime = 31; int result = 1; result = prime * result + ((format == null) ? 0 : format.GetHashCode()); result = prime * result + index; return result; } /// <summary> /// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>. /// </summary> /// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.</param> /// <returns> /// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false. /// </returns> /// <exception cref="T:System.NullReferenceException"> /// The <paramref name="obj"/> parameter is null. /// </exception> public override bool Equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj is HSSFCellStyle) { HSSFCellStyle other = (HSSFCellStyle)obj; if (format == null) { if (other.format != null) return false; } else if (!format.Equals(other.format)) return false; if (index != other.index) return false; return true; } return false; } } }
/* nwitsml Copyright 2010 Setiri LLC Derived from the jwitsml project, Copyright 2010 Statoil ASA 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. */ namespace witsmllib.units{ //import java.util.ArrayList; //import java.util.List; //import java.io.InputStream; //import java.io.IOException; ////import org.jdom.Element; ////import org.jdom.Namespace; ////import org.jdom.input.SAXBuilder; ////import org.jdom.JDOMException; ////import nwitsml.Value; /** * Singleton class for handling WITSML quantities, units and * unit conversions. * * @author <a href="mailto:info@nwitsml.org">NWitsml</a> */ using System; using System.Reflection; using System.Collections.Generic; using System.IO; using System.Text; using System.Xml.Linq; public sealed class WitsmlUnitManager { /** The sole instance of this class. */ private static WitsmlUnitManager instance = new WitsmlUnitManager(); /** All known quantities. */ private List<WitsmlQuantity> quantities = new List<WitsmlQuantity>(); /** * Create a unit manager instance. Private to prevent * client instantiation. */ private WitsmlUnitManager() { load(); } /** * Return sole instance of this class. * * @return Sole instance of this class. Never null. */ public static WitsmlUnitManager getInstance() { return instance; } /** * Load all quantity and unit information from the local "units.txt" file. */ private void load() { String fileName = "witsmlUnitDict.xml"; //String packageName = Assembly.GetExecutingAssembly().GetName().Name;// getClass().getPackage().getName(); //String packageLocation = packageName.Replace ('.', '/'); //String filePath = "/" + packageLocation + "/" + fileName; // Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(fileName ); Assembly ass = this.GetType().Assembly; Stream stream = ass.GetManifestResourceStream(ass.GetName().Name + ".nwitsml.units." + fileName); List<WitsmlQuantity> hasBaseUnit = new List<WitsmlQuantity>(); //InputStream stream = WitsmlUnitManager.class.getResourceAsStream(filePath); //SAXBuilder builder = new SAXBuilder(); try { XDocument document = XDocument.Load(stream); // builder.build(stream); XElement rootElement = document.Root; XNamespace @namespace = rootElement.Name.Namespace; //.getNamespace(); XElement unitDefinitionsElement = rootElement.Element(@namespace + "UnitsDefinition"/*,@namespace*/); var children = unitDefinitionsElement.Elements(@namespace+"UnitOfMeasure"/*, @namespace*/); foreach (Object child in children) { XElement unitOfMeasureElement = (XElement) child; List<WitsmlQuantity> quantitiesForUnit = new List<WitsmlQuantity>(); // // Extract the BaseUnit element with its Description memeber // XElement baseUnitElement = unitOfMeasureElement.Element(@namespace + "BaseUnit"/*, @namespace*/); bool isBaseUnit = baseUnitElement != null; String quantityDescription = baseUnitElement != null && baseUnitElement.Element(@namespace + "Description") != null ? //bugfix 9-25-10 baseUnitElement.Element(@namespace + "Description").Value.Trim() : null; // // Identify all the quantities this unit appears in // var quantityTypeElements = unitOfMeasureElement.Elements(@namespace + "QuantityType"/*,@namespace*/); foreach (Object child2 in quantityTypeElements) { XElement quantityTypeElement = (XElement) child2; String quantityName = quantityTypeElement.Value.Trim(); //.getTextTrim(); WitsmlQuantity quantity = findOrCreateQuantity(quantityName, quantityDescription); quantitiesForUnit.Add(quantity); // DEBUG if (isBaseUnit && hasBaseUnit.Contains(quantity)) Console.WriteLine( //System.out.println( "ALREADY BASE: " + quantity.getName()); if (isBaseUnit) hasBaseUnit.Add(quantity); } String unitName = unitOfMeasureElement.Element(@namespace + "Name"/*, @namespace*/).Value.Trim(); String unitSymbol = unitOfMeasureElement.Element(@namespace + "CatalogSymbol"/*,@namespace*/).Value.Trim(); XElement conversionElement = unitOfMeasureElement.Element("ConversionToBaseUnit"/*,@namespace*/); double a = 1.0; double b = 0.0; double c = 0.0; double d = 1.0; if (conversionElement != null) { String factorText = conversionElement.Element(@namespace + "Factor"/*,@namespace*/).Value.Trim(); XElement fractionElement = conversionElement.Element(@namespace + "Fraction"/*,@namespace*/); XElement formulaElement = conversionElement.Element(@namespace+"Formula"/*,@namespace*/); if (factorText != null) { try { a = Double.Parse(factorText); } catch (FormatException exception) { //Debug.Assert(false : "Invalid numeric value: " + factorText; } } else if (fractionElement != null) { String numeratorText = fractionElement.Element(@namespace+"Numerator"/*,@namespace*/).Value.Trim(); String denominatorText = fractionElement.Element(@namespace + "Denominator"/*,@namespace*/).Value.Trim(); try { double numerator = Double.Parse(numeratorText); double denominator = Double.Parse(denominatorText); a = numerator / denominator; } catch (FormatException exception) { //Debug.Assert(false : "Invalid numeric value: " + numeratorText + "/" + denominatorText; } } else if (formulaElement != null) { String aText = formulaElement.Element(@namespace+"A"/*, @namespace*/).Value.Trim(); String bText = formulaElement.Element(@namespace+"B"/*, @namespace*/).Value.Trim(); String cText = formulaElement.Element(@namespace+"C"/*, @namespace*/).Value.Trim(); String dText = formulaElement.Element(@namespace+"D"/*, @namespace*/).Value.Trim(); try { a = Double.Parse(aText); b = Double.Parse(bText); c = Double.Parse(cText); d = Double.Parse(dText); } catch (FormatException exception) { //Debug.Assert(false : "Invalid numeric value: " + aText + "," + bText + "," + cText + "," + dText; } } } WitsmlUnit unit = new WitsmlUnit(unitName, unitSymbol, a, b, c, d); foreach (WitsmlQuantity quantity in quantitiesForUnit) { quantity.addUnit(unit, isBaseUnit); } } } catch (IOException exception) { //Debug.Assert(false : "Parse error: " + filePath; } catch (Exception /*JDOMException*/ exception) { //Debug.Assert(false : "Parse error: " + filePath; } foreach (WitsmlQuantity q in quantities) { if (!hasBaseUnit.Contains(q)) Console.WriteLine( //System.out.println( "NO BASE UNIT: " + q.getName()); } } /** * Return names of all known quantities. * * @return List of all known quantities. Never null. */ public List<String> getQuantities() { List<String> quantityNames = new List<String>(); foreach (WitsmlQuantity quantity in quantities) quantityNames.Add(quantity.getName()); return quantityNames; } /** * Return all units of the specified quantity. * * @param quantityName Quantity to get units for. Non-null. * @return All units for the specified quantity. Never null. * @throws ArgumentException If quantityName is null or unknown. */ public List<WitsmlUnit> getUnits(String quantityName) { if (quantityName == null) throw new ArgumentException("quantityName cannot be null"); WitsmlQuantity quantity = findQuantity(quantityName); if (quantity == null) throw new ArgumentException("Unknown quantity: " + quantityName); return quantity.getUnits(); } /** * Return the quantity instance of the specified name. * * @param quantityName Name of quantity to find. Non-null. * @return Requested quantity, or null if not found. */ private WitsmlQuantity findQuantity(String quantityName) { //Debug.Assert(quantityName != null : "quantityName cannot be null"; foreach (WitsmlQuantity quantity in quantities) { if (quantity.getName().Equals(quantityName)) return quantity; } return null; } /** * Find quantity of the specified name, or create it if it is not found. * * @param quantityName Name of quantity to find or create. Non-null. * @return Requested quantity. Never null. */ private WitsmlQuantity findOrCreateQuantity(String quantityName, String description) { //Debug.Assert(quantityName != null : "quantityName cannot be null"; WitsmlQuantity quantity = findQuantity(quantityName); if (quantity == null) { quantity = new WitsmlQuantity(quantityName, description); quantities.Add(quantity); } return quantity; } /** * Find unit instance based on the specified unit symbol. * * @param unitSymbol Symbol of unit to find. Non-null. * @return Requested unit, or null if not found. * @throws ArgumentException If unitSymbol is null. */ public WitsmlUnit findUnit(String unitSymbol) { if (unitSymbol == null) throw new ArgumentException("unitSymbol cannot be null"); foreach (WitsmlQuantity quantity in quantities) { foreach (WitsmlUnit unit in quantity.getUnits()) { if (unit.getSymbol().Equals(unitSymbol)) return unit; } } // Not found return null; } /** * Find the base unit of the specified unit. * * @param unit Unit to find base unit for. Non-null. * @return Requested base unit. Never null. * @throws ArgumentException If unit is null. */ public WitsmlUnit findBaseUnit(WitsmlUnit unit) { if (unit == null) throw new ArgumentException("unit cannot be null"); foreach (WitsmlQuantity quantity in quantities) { foreach (WitsmlUnit u in quantity.getUnits()) { if (u.Equals(unit)) return quantity.getBaseUnit(); } } // Not found //Debug.Assert(false : "Impossible, as all units originates from the manager"; return null; } /** * Convert a specified value between two units. * * @param fromUnit Unit to convert from. Non-null. * @param toUnit Unit to convert to. Non-null. * @param value Value to convert. * @return Converted value. * @throws ArgumentException If fromUnit or toUnit is null. */ public double convert(WitsmlUnit fromUnit, WitsmlUnit toUnit, double value) { if (fromUnit == null) throw new ArgumentException("fromUnit cannot be null"); if (toUnit == null) throw new ArgumentException("toUnit cannot be null"); double baseValue = fromUnit.toBase(value); return toUnit.fromBase(baseValue); } /** * Convert the specified value instance to base unit * if possible. * * @param value Value to convert. Non-null. * @return Converted value. If the value cannot be converted * for some reason, a copy of the argument is returned. * Never null. * @throws ArgumentException If value is null. */ public Value toBaseUnit(Value value) { if (value == null) throw new ArgumentException("value cannot be null"); Double v = value.getValue().Value ; String unitSymbol = value.getUnit(); if (unitSymbol != null) { WitsmlUnit unit = findUnit(unitSymbol); if (unit != null) { WitsmlUnit baseUnit = findBaseUnit(unit); v = convert(unit, baseUnit, v); unitSymbol = baseUnit.getSymbol(); } } return new Value(v, unitSymbol); } /** {@inheritDoc} */ public override String ToString() { StringBuilder s = new StringBuilder(); foreach (WitsmlQuantity quantity in quantities) { s.Append(quantity.ToString()); s.Append("\n"); } return s.ToString(); } } }
#region copyright // Copyright (c) 2012, TIGWI // All rights reserved. // Distributed under BSD 2-Clause license #endregion namespace Tigwi.UI.Models.Storage { using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; using Tigwi.Storage.Library; public class StorageAccountModel : StorageEntityModel, IAccountModel { #region Constants and Fields private readonly ListCollectionAdapter allFollowedLists; private readonly ListCollectionAdapter allOwnedLists; private readonly ListCollectionAdapter memberOfLists; private readonly ListCollectionAdapter publicFollowedLists; private readonly ListCollectionAdapter publicOwnedLists; private readonly StorageEntityCollection<StorageUserModel, IUserModel> users; private StorageUserModel admin; private string avatar; private string description; private string name; private StorageListModel personalList; #endregion #region Constructors and Destructors public StorageAccountModel(IStorage storage, StorageContext storageContext, Guid accountId) : base(storage, storageContext, accountId) { this.users = new StorageEntityCollection<StorageUserModel, IUserModel>(this.StorageContext) { FetchIdCollection = () => storage.Account.GetUsers(accountId), GetId = user => user.Id, GetModel = storageContext.InternalUsers.InternalFind, ReverseAdd = user => user.InternalAccounts.CacheAdd(this), ReverseRemove = user => user.InternalAccounts.CacheRemove(this), SaveAdd = user => storage.Account.Add(this.Id, user.Id), SaveRemove = user => storage.Account.Remove(this.Id, user.Id), }; this.memberOfLists = new ListCollectionAdapter(this.StorageContext) { FetchIdCollection = () => storage.List.GetFollowingLists(accountId), GetId = list => list.Id, GetModel = storageContext.InternalLists.InternalFind, ReverseAdd = list => list.InternalMembers.CacheAdd(this), ReverseRemove = list => list.InternalMembers.CacheRemove(this), SaveAdd = list => storage.List.Add(list.Id, this.Id), SaveRemove = list => storage.List.Remove(list.Id, this.Id), }; this.allFollowedLists = new ListCollectionAdapter(storageContext) { FetchIdCollection = () => storage.List.GetAccountFollowedLists(accountId, true), GetId = list => list.Id, GetModel = storageContext.InternalLists.InternalFind, ReverseAdd = list => { // TODO: shouldn't call storage list.InternalFollowers.CacheAdd(this); if (!list.IsPrivate) { this.InternalPublicFollowedLists.CacheAdd(list); } }, ReverseRemove = list => { // TODO: shouldn't call storage list.InternalFollowers.CacheRemove(this); if (!list.IsPrivate) { this.InternalPublicFollowedLists.CacheRemove(list); } }, SaveAdd = list => storage.List.Follow(list.Id, this.Id), SaveRemove = list => storage.List.Unfollow(list.Id, this.Id), }; this.publicFollowedLists = new ListCollectionAdapter(storageContext) { FetchIdCollection = () => storage.List.GetAccountFollowedLists(accountId, true), GetId = list => list.Id, GetModel = storageContext.InternalLists.InternalFind, ReverseAdd = list => Contract.Assert(false), ReverseRemove = list => Contract.Assert(false), SaveAdd = list => Contract.Assert(false), SaveRemove = list => Contract.Assert(false), }; this.allOwnedLists = new ListCollectionAdapter(storageContext) { FetchIdCollection = () => storage.List.GetAccountOwnedLists(accountId, true), GetId = list => list.Id, GetModel = storageContext.InternalLists.InternalFind, ReverseAdd = list => Contract.Assert(false), ReverseRemove = list => Contract.Assert(false), SaveAdd = list => Contract.Assert(false), SaveRemove = list => Contract.Assert(false), }; this.publicOwnedLists = new ListCollectionAdapter(storageContext) { FetchIdCollection = () => storage.List.GetAccountOwnedLists(accountId, false), GetId = list => list.Id, GetModel = storageContext.InternalLists.InternalFind, ReverseAdd = list => Contract.Assert(false), ReverseRemove = list => Contract.Assert(false), SaveAdd = list => Contract.Assert(false), SaveRemove = list => Contract.Assert(false), }; } #endregion #region Public Properties public IUserModel Admin { get { // Admin's initialization involves storage calls, so let's be lazy return this.admin ?? (this.admin = this.StorageContext.InternalUsers.InternalFind(this.Storage.Account.GetAdminId(this.Id))); } set { this.admin = value as StorageUserModel ?? this.StorageContext.InternalUsers.InternalFind(value.Id); this.AdminUpdated = true; } } public IListModelCollection AllFollowedLists { get { return this.allFollowedLists; } } public IListModelEnumerable AllOwnedLists { get { return this.allOwnedLists; } } public string Avatar { get { if (!this.Prefetched) { this.Populate(); } return this.avatar; } set { this.avatar = value; } } public string Description { get { this.Populate(); return this.description; } set { this.description = value; this.DescriptionUpdated = true; } } public IListModelCollection MemberOfLists { get { return this.memberOfLists; } } public string Name { get { if (!this.Prefetched) { this.Populate(); } return this.name; } } public IListModel PersonalList { get { return this.InternalPersonalList; } } public IListModelEnumerable PublicFollowedLists { get { return this.publicFollowedLists; } } public IListModelEnumerable PublicOwnedLists { get { return this.publicOwnedLists; } } public ICollection<IUserModel> Users { get { return this.users; } } #endregion #region Properties internal ListCollectionAdapter InternalAllFollowedLists { get { return this.allFollowedLists; } } internal ListCollectionAdapter InternalAllOwnedLists { get { return this.allOwnedLists; } } internal ListCollectionAdapter InternalMemberOfLists { get { return this.memberOfLists; } } internal StorageListModel InternalPersonalList { get { return this.personalList ?? (this.personalList = this.StorageContext.InternalLists.InternalFind(this.Storage.List.GetPersonalList(this.Id))); } } internal ListCollectionAdapter InternalPublicFollowedLists { get { return this.publicFollowedLists; } } internal ListCollectionAdapter InternalPublicOwnedLists { get { return this.publicOwnedLists; } } internal StorageEntityCollection<StorageUserModel, IUserModel> InternalUsers { get { return this.users; } } protected override bool InfosUpdated { get { return this.DescriptionUpdated; } set { this.DescriptionUpdated = value; } } protected bool Prefetched { get; set; } private bool AdminUpdated { get; set; } private bool DescriptionUpdated { get; set; } #endregion #region Public Methods and Operators public StorageAccountModel PopulateWith(string name, string avatar) { this.Prefetched = true; this.name = name; this.avatar = avatar; return this; } #endregion #region Methods internal override void Repopulate() { // TODO: repopulate adapters ? // Fetch infos var accountInfo = this.Storage.Account.GetInfo(this.Id); this.name = accountInfo.Name; if (!this.DescriptionUpdated) { this.description = accountInfo.Description; } this.Populated = true; } internal override bool Save() { var success = true; if (this.Deleted) { this.Storage.Account.Delete(this.Id); } else { if (this.InfosUpdated) { try { this.Storage.Account.SetInfo(this.Id, this.Description); } catch (StorageLibException) { success = false; } } if (this.AdminUpdated) { try { this.Storage.Account.SetAdminId(this.Id, this.Admin.Id); } catch (StorageLibException) { success = false; } } success &= this.users.Save(); success &= this.allFollowedLists.Save(); success &= this.memberOfLists.Save(); if (this.personalList != null) { success &= this.personalList.Save(); } } return success; } #endregion internal class ListCollectionAdapter : StorageEntityCollection<StorageListModel, IListModel>, IListModelCollection { public ListCollectionAdapter(StorageContext storageContext) : base(storageContext) { } #region Implementation of IListModelCollection public IEnumerable<Guid> Ids { get { return this.InternalCollection.Keys; } } public IEnumerable<IPostModel> PostsAfter(DateTime date, int maximum = 100) { var msgCollection = this.Storage.Msg.GetListsMsgFrom( new HashSet<Guid>(this.Ids), date, maximum); return new List<IPostModel>(msgCollection.Select(msg => new StoragePostModel(this.StorageContext, msg))) .AsReadOnly(); } public IEnumerable<IPostModel> PostsBefore(DateTime date, int maximum = 100) { var msgCollection = this.Storage.Msg.GetListsMsgTo( new HashSet<Guid>(this.Ids), date, maximum); return new List<IPostModel>(msgCollection.Select(msg => new StoragePostModel(this.StorageContext, msg))) .AsReadOnly(); } #endregion } } }
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.ComponentModel; using System.Collections; using System.Collections.Generic; namespace WeifenLuo.WinFormsUI.Docking { internal class VS2005DockPaneStrip : DockPaneStripBase { private class TabVS2005 : Tab { public TabVS2005(IDockContent content) : base(content) { } private int m_tabX; public int TabX { get { return m_tabX; } set { m_tabX = value; } } private int m_tabWidth; public int TabWidth { get { return m_tabWidth; } set { m_tabWidth = value; } } private int m_maxWidth; public int MaxWidth { get { return m_maxWidth; } set { m_maxWidth = value; } } private bool m_flag; protected internal bool Flag { get { return m_flag; } set { m_flag = value; } } } protected internal override DockPaneStripBase.Tab CreateTab(IDockContent content) { return new TabVS2005(content); } private sealed class InertButton : InertButtonBase { private Bitmap m_image0, m_image1; public InertButton(Bitmap image0, Bitmap image1) : base() { m_image0 = image0; m_image1 = image1; } private int m_imageCategory = 0; public int ImageCategory { get { return m_imageCategory; } set { if (m_imageCategory == value) return; m_imageCategory = value; Invalidate(); } } public override Bitmap Image { get { return ImageCategory == 0 ? m_image0 : m_image1; } } } #region Constants private const int _ToolWindowStripGapTop = 0; private const int _ToolWindowStripGapBottom = 1; private const int _ToolWindowStripGapLeft = 0; private const int _ToolWindowStripGapRight = 0; private const int _ToolWindowImageHeight = 16; private const int _ToolWindowImageWidth = 16; private const int _ToolWindowImageGapTop = 3; private const int _ToolWindowImageGapBottom = 1; private const int _ToolWindowImageGapLeft = 2; private const int _ToolWindowImageGapRight = 0; private const int _ToolWindowTextGapRight = 3; private const int _ToolWindowTabSeperatorGapTop = 3; private const int _ToolWindowTabSeperatorGapBottom = 3; private const int _DocumentStripGapTop = 0; private const int _DocumentStripGapBottom = 1; private const int _DocumentTabMaxWidth = 200; private const int _DocumentButtonGapTop = 4; private const int _DocumentButtonGapBottom = 4; private const int _DocumentButtonGapBetween = 0; private const int _DocumentButtonGapRight = 3; private const int _DocumentTabGapTop = 3; private const int _DocumentTabGapLeft = 3; private const int _DocumentTabGapRight = 3; private const int _DocumentIconGapBottom = 2; private const int _DocumentIconGapLeft = 8; private const int _DocumentIconGapRight = 0; private const int _DocumentIconHeight = 16; private const int _DocumentIconWidth = 16; private const int _DocumentTextGapRight = 3; #endregion #region Members private ContextMenuStrip m_selectMenu; private static Bitmap m_imageButtonClose; private InertButton m_buttonClose; private static Bitmap m_imageButtonWindowList; private static Bitmap m_imageButtonWindowListOverflow; private InertButton m_buttonWindowList; private IContainer m_components; private ToolTip m_toolTip; private Font m_font; private Font m_boldFont; private int m_startDisplayingTab = 0; private int m_endDisplayingTab = 0; private int m_firstDisplayingTab = 0; private bool m_documentTabsOverflow = false; private static string m_toolTipSelect; private static string m_toolTipClose; private bool m_closeButtonVisible = false; #endregion #region Properties private Rectangle TabStripRectangle { get { if (Appearance == DockPane.AppearanceStyle.Document) return TabStripRectangle_Document; else return TabStripRectangle_ToolWindow; } } private Rectangle TabStripRectangle_ToolWindow { get { Rectangle rect = ClientRectangle; return new Rectangle(rect.X, rect.Top + ToolWindowStripGapTop, rect.Width, rect.Height - ToolWindowStripGapTop - ToolWindowStripGapBottom); } } private Rectangle TabStripRectangle_Document { get { Rectangle rect = ClientRectangle; return new Rectangle(rect.X, rect.Top + DocumentStripGapTop, rect.Width, rect.Height - DocumentStripGapTop - ToolWindowStripGapBottom); } } private Rectangle TabsRectangle { get { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return TabStripRectangle; Rectangle rectWindow = TabStripRectangle; int x = rectWindow.X; int y = rectWindow.Y; int width = rectWindow.Width; int height = rectWindow.Height; x += DocumentTabGapLeft; width -= DocumentTabGapLeft + DocumentTabGapRight + DocumentButtonGapRight + ButtonClose.Width + ButtonWindowList.Width + 2 * DocumentButtonGapBetween; return new Rectangle(x, y, width, height); } } private ContextMenuStrip SelectMenu { get { return m_selectMenu; } } private static Bitmap ImageButtonClose { get { if (m_imageButtonClose == null) m_imageButtonClose = Resources.DockPane_Close; return m_imageButtonClose; } } private InertButton ButtonClose { get { if (m_buttonClose == null) { m_buttonClose = new InertButton(ImageButtonClose, ImageButtonClose); m_toolTip.SetToolTip(m_buttonClose, ToolTipClose); m_buttonClose.Click += new EventHandler(Close_Click); Controls.Add(m_buttonClose); } return m_buttonClose; } } private static Bitmap ImageButtonWindowList { get { if (m_imageButtonWindowList == null) m_imageButtonWindowList = Resources.DockPane_Option; return m_imageButtonWindowList; } } private static Bitmap ImageButtonWindowListOverflow { get { if (m_imageButtonWindowListOverflow == null) m_imageButtonWindowListOverflow = Resources.DockPane_OptionOverflow; return m_imageButtonWindowListOverflow; } } private InertButton ButtonWindowList { get { if (m_buttonWindowList == null) { m_buttonWindowList = new InertButton(ImageButtonWindowList, ImageButtonWindowListOverflow); m_toolTip.SetToolTip(m_buttonWindowList, ToolTipSelect); m_buttonWindowList.Click += new EventHandler(WindowList_Click); Controls.Add(m_buttonWindowList); } return m_buttonWindowList; } } private static GraphicsPath GraphicsPath { get { return VS2005AutoHideStrip.GraphicsPath; } } private IContainer Components { get { return m_components; } } public Font TextFont { get { return DockPane.DockPanel.Skin.DockPaneStripSkin.TextFont; } } private Font BoldFont { get { if (IsDisposed) return null; if (m_boldFont == null) { m_font = TextFont; m_boldFont = new Font(TextFont, FontStyle.Bold); } else if (m_font != TextFont) { m_boldFont.Dispose(); m_font = TextFont; m_boldFont = new Font(TextFont, FontStyle.Bold); } return m_boldFont; } } private int StartDisplayingTab { get { return m_startDisplayingTab; } set { m_startDisplayingTab = value; Invalidate(); } } private int EndDisplayingTab { get { return m_endDisplayingTab; } set { m_endDisplayingTab = value; } } private int FirstDisplayingTab { get { return m_firstDisplayingTab; } set { m_firstDisplayingTab = value; } } private bool DocumentTabsOverflow { set { if (m_documentTabsOverflow == value) return; m_documentTabsOverflow = value; if (value) ButtonWindowList.ImageCategory = 1; else ButtonWindowList.ImageCategory = 0; } } #region Customizable Properties private static int ToolWindowStripGapTop { get { return _ToolWindowStripGapTop; } } private static int ToolWindowStripGapBottom { get { return _ToolWindowStripGapBottom; } } private static int ToolWindowStripGapLeft { get { return _ToolWindowStripGapLeft; } } private static int ToolWindowStripGapRight { get { return _ToolWindowStripGapRight; } } private static int ToolWindowImageHeight { get { return _ToolWindowImageHeight; } } private static int ToolWindowImageWidth { get { return _ToolWindowImageWidth; } } private static int ToolWindowImageGapTop { get { return _ToolWindowImageGapTop; } } private static int ToolWindowImageGapBottom { get { return _ToolWindowImageGapBottom; } } private static int ToolWindowImageGapLeft { get { return _ToolWindowImageGapLeft; } } private static int ToolWindowImageGapRight { get { return _ToolWindowImageGapRight; } } private static int ToolWindowTextGapRight { get { return _ToolWindowTextGapRight; } } private static int ToolWindowTabSeperatorGapTop { get { return _ToolWindowTabSeperatorGapTop; } } private static int ToolWindowTabSeperatorGapBottom { get { return _ToolWindowTabSeperatorGapBottom; } } private static string ToolTipClose { get { if (m_toolTipClose == null) m_toolTipClose = Strings.DockPaneStrip_ToolTipClose; return m_toolTipClose; } } private static string ToolTipSelect { get { if (m_toolTipSelect == null) m_toolTipSelect = Strings.DockPaneStrip_ToolTipWindowList; return m_toolTipSelect; } } private TextFormatFlags ToolWindowTextFormat { get { TextFormatFlags textFormat = TextFormatFlags.EndEllipsis | TextFormatFlags.HorizontalCenter | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter; if (RightToLeft == RightToLeft.Yes) return textFormat | TextFormatFlags.RightToLeft | TextFormatFlags.Right; else return textFormat; } } private static int DocumentStripGapTop { get { return _DocumentStripGapTop; } } private static int DocumentStripGapBottom { get { return _DocumentStripGapBottom; } } private TextFormatFlags DocumentTextFormat { get { TextFormatFlags textFormat = TextFormatFlags.EndEllipsis | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter | TextFormatFlags.HorizontalCenter; if (RightToLeft == RightToLeft.Yes) return textFormat | TextFormatFlags.RightToLeft; else return textFormat; } } private static int DocumentTabMaxWidth { get { return _DocumentTabMaxWidth; } } private static int DocumentButtonGapTop { get { return _DocumentButtonGapTop; } } private static int DocumentButtonGapBottom { get { return _DocumentButtonGapBottom; } } private static int DocumentButtonGapBetween { get { return _DocumentButtonGapBetween; } } private static int DocumentButtonGapRight { get { return _DocumentButtonGapRight; } } private static int DocumentTabGapTop { get { return _DocumentTabGapTop; } } private static int DocumentTabGapLeft { get { return _DocumentTabGapLeft; } } private static int DocumentTabGapRight { get { return _DocumentTabGapRight; } } private static int DocumentIconGapBottom { get { return _DocumentIconGapBottom; } } private static int DocumentIconGapLeft { get { return _DocumentIconGapLeft; } } private static int DocumentIconGapRight { get { return _DocumentIconGapRight; } } private static int DocumentIconWidth { get { return _DocumentIconWidth; } } private static int DocumentIconHeight { get { return _DocumentIconHeight; } } private static int DocumentTextGapRight { get { return _DocumentTextGapRight; } } private static Pen PenToolWindowTabBorder { get { return SystemPens.GrayText; } } private static Pen PenDocumentTabActiveBorder { get { return SystemPens.ControlDarkDark; } } private static Pen PenDocumentTabInactiveBorder { get { return SystemPens.GrayText; } } #endregion #endregion public VS2005DockPaneStrip(DockPane pane) : base(pane) { SetStyle(ControlStyles.ResizeRedraw | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true); SuspendLayout(); m_components = new Container(); m_toolTip = new ToolTip(Components); m_selectMenu = new ContextMenuStrip(Components); ResumeLayout(); } protected override void Dispose(bool disposing) { if (disposing) { Components.Dispose(); if (m_boldFont != null) { m_boldFont.Dispose(); m_boldFont = null; } } base.Dispose(disposing); } protected internal override int MeasureHeight() { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return MeasureHeight_ToolWindow(); else return MeasureHeight_Document(); } private int MeasureHeight_ToolWindow() { if (DockPane.IsAutoHide || Tabs.Count <= 1) return 0; int height = Math.Max(TextFont.Height, ToolWindowImageHeight + ToolWindowImageGapTop + ToolWindowImageGapBottom) + ToolWindowStripGapTop + ToolWindowStripGapBottom; return height; } private int MeasureHeight_Document() { int height = Math.Max(TextFont.Height + DocumentTabGapTop, ButtonClose.Height + DocumentButtonGapTop + DocumentButtonGapBottom) + DocumentStripGapBottom + DocumentStripGapTop; return height; } protected override void OnPaint(PaintEventArgs e) { Rectangle rect = TabsRectangle; if (Appearance == DockPane.AppearanceStyle.Document) { rect.X -= DocumentTabGapLeft; // Add these values back in so that the DockStrip color is drawn // beneath the close button and window list button. rect.Width += DocumentTabGapLeft + DocumentTabGapRight + DocumentButtonGapRight + ButtonClose.Width + ButtonWindowList.Width; // It is possible depending on the DockPanel DocumentStyle to have // a Document without a DockStrip. if (rect.Width > 0 && rect.Height > 0) { Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.StartColor; Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.EndColor; LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.LinearGradientMode; using (LinearGradientBrush brush = new LinearGradientBrush(rect, startColor, endColor, gradientMode)) { e.Graphics.FillRectangle(brush, rect); } } } else { Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient.StartColor; Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient.EndColor; LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient.LinearGradientMode; using (LinearGradientBrush brush = new LinearGradientBrush(rect, startColor, endColor, gradientMode)) { e.Graphics.FillRectangle(brush, rect); } } base.OnPaint(e); CalculateTabs(); if (Appearance == DockPane.AppearanceStyle.Document && DockPane.ActiveContent != null) { if (EnsureDocumentTabVisible(DockPane.ActiveContent, false)) CalculateTabs(); } DrawTabStrip(e.Graphics); } protected override void OnRefreshChanges() { SetInertButtons(); Invalidate(); } protected internal override GraphicsPath GetOutline(int index) { if (Appearance == DockPane.AppearanceStyle.Document) return GetOutline_Document(index); else return GetOutline_ToolWindow(index); } private GraphicsPath GetOutline_Document(int index) { Rectangle rectTab = GetTabRectangle(index); rectTab.X -= rectTab.Height / 2; rectTab.Intersect(TabsRectangle); rectTab = RectangleToScreen(DrawHelper.RtlTransform(this, rectTab)); Rectangle rectPaneClient = DockPane.RectangleToScreen(DockPane.ClientRectangle); GraphicsPath path = new GraphicsPath(); GraphicsPath pathTab = GetTabOutline_Document(Tabs[index], true, true, true); path.AddPath(pathTab, true); if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) { path.AddLine(rectTab.Right, rectTab.Top, rectPaneClient.Right, rectTab.Top); path.AddLine(rectPaneClient.Right, rectTab.Top, rectPaneClient.Right, rectPaneClient.Top); path.AddLine(rectPaneClient.Right, rectPaneClient.Top, rectPaneClient.Left, rectPaneClient.Top); path.AddLine(rectPaneClient.Left, rectPaneClient.Top, rectPaneClient.Left, rectTab.Top); path.AddLine(rectPaneClient.Left, rectTab.Top, rectTab.Right, rectTab.Top); } else { path.AddLine(rectTab.Right, rectTab.Bottom, rectPaneClient.Right, rectTab.Bottom); path.AddLine(rectPaneClient.Right, rectTab.Bottom, rectPaneClient.Right, rectPaneClient.Bottom); path.AddLine(rectPaneClient.Right, rectPaneClient.Bottom, rectPaneClient.Left, rectPaneClient.Bottom); path.AddLine(rectPaneClient.Left, rectPaneClient.Bottom, rectPaneClient.Left, rectTab.Bottom); path.AddLine(rectPaneClient.Left, rectTab.Bottom, rectTab.Right, rectTab.Bottom); } return path; } private GraphicsPath GetOutline_ToolWindow(int index) { Rectangle rectTab = GetTabRectangle(index); rectTab.Intersect(TabsRectangle); rectTab = RectangleToScreen(DrawHelper.RtlTransform(this, rectTab)); Rectangle rectPaneClient = DockPane.RectangleToScreen(DockPane.ClientRectangle); GraphicsPath path = new GraphicsPath(); GraphicsPath pathTab = GetTabOutline(Tabs[index], true, true); path.AddPath(pathTab, true); path.AddLine(rectTab.Left, rectTab.Top, rectPaneClient.Left, rectTab.Top); path.AddLine(rectPaneClient.Left, rectTab.Top, rectPaneClient.Left, rectPaneClient.Top); path.AddLine(rectPaneClient.Left, rectPaneClient.Top, rectPaneClient.Right, rectPaneClient.Top); path.AddLine(rectPaneClient.Right, rectPaneClient.Top, rectPaneClient.Right, rectTab.Top); path.AddLine(rectPaneClient.Right, rectTab.Top, rectTab.Right, rectTab.Top); return path; } private void CalculateTabs() { if (Appearance == DockPane.AppearanceStyle.ToolWindow) CalculateTabs_ToolWindow(); else CalculateTabs_Document(); } private void CalculateTabs_ToolWindow() { if (Tabs.Count <= 1 || DockPane.IsAutoHide) return; Rectangle rectTabStrip = TabStripRectangle; // Calculate tab widths int countTabs = Tabs.Count; foreach (TabVS2005 tab in Tabs) { tab.MaxWidth = GetMaxTabWidth(Tabs.IndexOf(tab)); tab.Flag = false; } // Set tab whose max width less than average width bool anyWidthWithinAverage = true; int totalWidth = rectTabStrip.Width - ToolWindowStripGapLeft - ToolWindowStripGapRight; int totalAllocatedWidth = 0; int averageWidth = totalWidth / countTabs; int remainedTabs = countTabs; for (anyWidthWithinAverage = true; anyWidthWithinAverage && remainedTabs > 0; ) { anyWidthWithinAverage = false; foreach (TabVS2005 tab in Tabs) { if (tab.Flag) continue; if (tab.MaxWidth <= averageWidth) { tab.Flag = true; tab.TabWidth = tab.MaxWidth; totalAllocatedWidth += tab.TabWidth; anyWidthWithinAverage = true; remainedTabs--; } } if (remainedTabs != 0) averageWidth = (totalWidth - totalAllocatedWidth) / remainedTabs; } // If any tab width not set yet, set it to the average width if (remainedTabs > 0) { int roundUpWidth = (totalWidth - totalAllocatedWidth) - (averageWidth * remainedTabs); foreach (TabVS2005 tab in Tabs) { if (tab.Flag) continue; tab.Flag = true; if (roundUpWidth > 0) { tab.TabWidth = averageWidth + 1; roundUpWidth--; } else tab.TabWidth = averageWidth; } } // Set the X position of the tabs int x = rectTabStrip.X + ToolWindowStripGapLeft; foreach (TabVS2005 tab in Tabs) { tab.TabX = x; x += tab.TabWidth; } } private bool CalculateDocumentTab(Rectangle rectTabStrip, ref int x, int index) { bool overflow = false; TabVS2005 tab = Tabs[index] as TabVS2005; tab.MaxWidth = GetMaxTabWidth(index); int width = Math.Min(tab.MaxWidth, DocumentTabMaxWidth); if (x + width < rectTabStrip.Right || index == StartDisplayingTab) { tab.TabX = x; tab.TabWidth = width; EndDisplayingTab = index; } else { tab.TabX = 0; tab.TabWidth = 0; overflow = true; } x += width; return overflow; } /// <summary> /// Calculate which tabs are displayed and in what order. /// </summary> private void CalculateTabs_Document() { if (m_startDisplayingTab >= Tabs.Count) m_startDisplayingTab = 0; Rectangle rectTabStrip = TabsRectangle; int x = rectTabStrip.X + rectTabStrip.Height / 2; bool overflow = false; // Originally all new documents that were considered overflow // (not enough pane strip space to show all tabs) were added to // the far left (assuming not right to left) and the tabs on the // right were dropped from view. If StartDisplayingTab is not 0 // then we are dealing with making sure a specific tab is kept in focus. if (m_startDisplayingTab > 0) { int tempX = x; TabVS2005 tab = Tabs[m_startDisplayingTab] as TabVS2005; tab.MaxWidth = GetMaxTabWidth(m_startDisplayingTab); // Add the active tab and tabs to the left for (int i = StartDisplayingTab; i >= 0; i--) CalculateDocumentTab(rectTabStrip, ref tempX, i); // Store which tab is the first one displayed so that it // will be drawn correctly (without part of the tab cut off) FirstDisplayingTab = EndDisplayingTab; tempX = x; // Reset X location because we are starting over // Start with the first tab displayed - name is a little misleading. // Loop through each tab and set its location. If there is not enough // room for all of them overflow will be returned. for (int i = EndDisplayingTab; i < Tabs.Count; i++) overflow = CalculateDocumentTab(rectTabStrip, ref tempX, i); // If not all tabs are shown then we have an overflow. if (FirstDisplayingTab != 0) overflow = true; } else { for (int i = StartDisplayingTab; i < Tabs.Count; i++) overflow = CalculateDocumentTab(rectTabStrip, ref x, i); for (int i = 0; i < StartDisplayingTab; i++) overflow = CalculateDocumentTab(rectTabStrip, ref x, i); FirstDisplayingTab = StartDisplayingTab; } if (!overflow) { m_startDisplayingTab = 0; FirstDisplayingTab = 0; x = rectTabStrip.X + rectTabStrip.Height / 2; foreach (TabVS2005 tab in Tabs) { tab.TabX = x; x += tab.TabWidth; } } DocumentTabsOverflow = overflow; } protected internal override void EnsureTabVisible(IDockContent content) { if (Appearance != DockPane.AppearanceStyle.Document || !Tabs.Contains(content)) return; CalculateTabs(); EnsureDocumentTabVisible(content, true); } private bool EnsureDocumentTabVisible(IDockContent content, bool repaint) { int index = Tabs.IndexOf(content); TabVS2005 tab = Tabs[index] as TabVS2005; if (tab.TabWidth != 0) return false; StartDisplayingTab = index; if (repaint) Invalidate(); return true; } private int GetMaxTabWidth(int index) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return GetMaxTabWidth_ToolWindow(index); else return GetMaxTabWidth_Document(index); } private int GetMaxTabWidth_ToolWindow(int index) { IDockContent content = Tabs[index].Content; Size sizeString = TextRenderer.MeasureText(content.DockHandler.TabText, TextFont); return ToolWindowImageWidth + sizeString.Width + ToolWindowImageGapLeft + ToolWindowImageGapRight + ToolWindowTextGapRight; } private int GetMaxTabWidth_Document(int index) { IDockContent content = Tabs[index].Content; int height = GetTabRectangle_Document(index).Height; Size sizeText = TextRenderer.MeasureText(content.DockHandler.TabText, BoldFont, new Size(DocumentTabMaxWidth, height), DocumentTextFormat); if (DockPane.DockPanel.ShowDocumentIcon) return sizeText.Width + DocumentIconWidth + DocumentIconGapLeft + DocumentIconGapRight + DocumentTextGapRight; else return sizeText.Width + DocumentIconGapLeft + DocumentTextGapRight; } private void DrawTabStrip(Graphics g) { if (Appearance == DockPane.AppearanceStyle.Document) DrawTabStrip_Document(g); else DrawTabStrip_ToolWindow(g); } private void DrawTabStrip_Document(Graphics g) { int count = Tabs.Count; if (count == 0) return; Rectangle rectTabStrip = TabStripRectangle; // Draw the tabs Rectangle rectTabOnly = TabsRectangle; Rectangle rectTab = Rectangle.Empty; TabVS2005 tabActive = null; g.SetClip(DrawHelper.RtlTransform(this, rectTabOnly)); for (int i = 0; i < count; i++) { rectTab = GetTabRectangle(i); if (Tabs[i].Content == DockPane.ActiveContent) { tabActive = Tabs[i] as TabVS2005; continue; } if (rectTab.IntersectsWith(rectTabOnly)) DrawTab(g, Tabs[i] as TabVS2005, rectTab); } g.SetClip(rectTabStrip); if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) g.DrawLine(PenDocumentTabActiveBorder, rectTabStrip.Left, rectTabStrip.Top + 1, rectTabStrip.Right, rectTabStrip.Top + 1); else g.DrawLine(PenDocumentTabActiveBorder, rectTabStrip.Left, rectTabStrip.Bottom - 1, rectTabStrip.Right, rectTabStrip.Bottom - 1); g.SetClip(DrawHelper.RtlTransform(this, rectTabOnly)); if (tabActive != null) { rectTab = GetTabRectangle(Tabs.IndexOf(tabActive)); if (rectTab.IntersectsWith(rectTabOnly)) DrawTab(g, tabActive, rectTab); } } private void DrawTabStrip_ToolWindow(Graphics g) { Rectangle rectTabStrip = TabStripRectangle; g.DrawLine(PenToolWindowTabBorder, rectTabStrip.Left, rectTabStrip.Top, rectTabStrip.Right, rectTabStrip.Top); for (int i = 0; i < Tabs.Count; i++) DrawTab(g, Tabs[i] as TabVS2005, GetTabRectangle(i)); } private Rectangle GetTabRectangle(int index) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return GetTabRectangle_ToolWindow(index); else return GetTabRectangle_Document(index); } private Rectangle GetTabRectangle_ToolWindow(int index) { Rectangle rectTabStrip = TabStripRectangle; TabVS2005 tab = (TabVS2005)(Tabs[index]); return new Rectangle(tab.TabX, rectTabStrip.Y, tab.TabWidth, rectTabStrip.Height); } private Rectangle GetTabRectangle_Document(int index) { Rectangle rectTabStrip = TabStripRectangle; TabVS2005 tab = (TabVS2005)Tabs[index]; Rectangle rect = new Rectangle(); rect.X = tab.TabX; rect.Width = tab.TabWidth; rect.Height = rectTabStrip.Height - DocumentTabGapTop; if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) rect.Y = rectTabStrip.Y + DocumentStripGapBottom; else rect.Y = rectTabStrip.Y + DocumentTabGapTop; return rect; } private void DrawTab(Graphics g, TabVS2005 tab, Rectangle rect) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) DrawTab_ToolWindow(g, tab, rect); else DrawTab_Document(g, tab, rect); } private GraphicsPath GetTabOutline(Tab tab, bool rtlTransform, bool toScreen) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return GetTabOutline_ToolWindow(tab, rtlTransform, toScreen); else return GetTabOutline_Document(tab, rtlTransform, toScreen, false); } private GraphicsPath GetTabOutline_ToolWindow(Tab tab, bool rtlTransform, bool toScreen) { Rectangle rect = GetTabRectangle(Tabs.IndexOf(tab)); if (rtlTransform) rect = DrawHelper.RtlTransform(this, rect); if (toScreen) rect = RectangleToScreen(rect); DrawHelper.GetRoundedCornerTab(GraphicsPath, rect, false); return GraphicsPath; } private GraphicsPath GetTabOutline_Document(Tab tab, bool rtlTransform, bool toScreen, bool full) { int curveSize = 6; GraphicsPath.Reset(); Rectangle rect = GetTabRectangle(Tabs.IndexOf(tab)); if (rtlTransform) rect = DrawHelper.RtlTransform(this, rect); if (toScreen) rect = RectangleToScreen(rect); // Draws the full angle piece for active content (or first tab) if (tab.Content == DockPane.ActiveContent || full || Tabs.IndexOf(tab) == FirstDisplayingTab) { if (RightToLeft == RightToLeft.Yes) { if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) { // For some reason the next line draws a line that is not hidden like it is when drawing the tab strip on top. // It is not needed so it has been commented out. //GraphicsPath.AddLine(rect.Right, rect.Bottom, rect.Right + rect.Height / 2, rect.Bottom); GraphicsPath.AddLine(rect.Right + rect.Height / 2, rect.Top, rect.Right - rect.Height / 2 + curveSize / 2, rect.Bottom - curveSize / 2); } else { GraphicsPath.AddLine(rect.Right, rect.Bottom, rect.Right + rect.Height / 2, rect.Bottom); GraphicsPath.AddLine(rect.Right + rect.Height / 2, rect.Bottom, rect.Right - rect.Height / 2 + curveSize / 2, rect.Top + curveSize / 2); } } else { if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) { // For some reason the next line draws a line that is not hidden like it is when drawing the tab strip on top. // It is not needed so it has been commented out. //GraphicsPath.AddLine(rect.Left, rect.Top, rect.Left - rect.Height / 2, rect.Top); GraphicsPath.AddLine(rect.Left - rect.Height / 2, rect.Top, rect.Left + rect.Height / 2 - curveSize / 2, rect.Bottom - curveSize / 2); } else { GraphicsPath.AddLine(rect.Left, rect.Bottom, rect.Left - rect.Height / 2, rect.Bottom); GraphicsPath.AddLine(rect.Left - rect.Height / 2, rect.Bottom, rect.Left + rect.Height / 2 - curveSize / 2, rect.Top + curveSize / 2); } } } // Draws the partial angle for non-active content else { if (RightToLeft == RightToLeft.Yes) { if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) { GraphicsPath.AddLine(rect.Right, rect.Top, rect.Right, rect.Top + rect.Height / 2); GraphicsPath.AddLine(rect.Right, rect.Top + rect.Height / 2, rect.Right - rect.Height / 2 + curveSize / 2, rect.Bottom - curveSize / 2); } else { GraphicsPath.AddLine(rect.Right, rect.Bottom, rect.Right, rect.Bottom - rect.Height / 2); GraphicsPath.AddLine(rect.Right, rect.Bottom - rect.Height / 2, rect.Right - rect.Height / 2 + curveSize / 2, rect.Top + curveSize / 2); } } else { if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) { GraphicsPath.AddLine(rect.Left, rect.Top, rect.Left, rect.Top + rect.Height / 2); GraphicsPath.AddLine(rect.Left, rect.Top + rect.Height / 2, rect.Left + rect.Height / 2 - curveSize / 2, rect.Bottom - curveSize / 2); } else { GraphicsPath.AddLine(rect.Left, rect.Bottom, rect.Left, rect.Bottom - rect.Height / 2); GraphicsPath.AddLine(rect.Left, rect.Bottom - rect.Height / 2, rect.Left + rect.Height / 2 - curveSize / 2, rect.Top + curveSize / 2); } } } if (RightToLeft == RightToLeft.Yes) { if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) { // Draws the bottom horizontal line (short side) GraphicsPath.AddLine(rect.Right - rect.Height / 2 - curveSize / 2, rect.Bottom, rect.Left + curveSize / 2, rect.Bottom); // Drawing the rounded corner is not necessary. The path is automatically connected //GraphicsPath.AddArc(new Rectangle(rect.Left, rect.Top, curveSize, curveSize), 180, 90); } else { // Draws the bottom horizontal line (short side) GraphicsPath.AddLine(rect.Right - rect.Height / 2 - curveSize / 2, rect.Top, rect.Left + curveSize / 2, rect.Top); GraphicsPath.AddArc(new Rectangle(rect.Left, rect.Top, curveSize, curveSize), 180, 90); } } else { if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) { // Draws the bottom horizontal line (short side) GraphicsPath.AddLine(rect.Left + rect.Height / 2 + curveSize / 2, rect.Bottom, rect.Right - curveSize / 2, rect.Bottom); // Drawing the rounded corner is not necessary. The path is automatically connected //GraphicsPath.AddArc(new Rectangle(rect.Right - curveSize, rect.Bottom, curveSize, curveSize), 90, -90); } else { // Draws the top horizontal line (short side) GraphicsPath.AddLine(rect.Left + rect.Height / 2 + curveSize / 2, rect.Top, rect.Right - curveSize / 2, rect.Top); // Draws the rounded corner oppposite the angled side GraphicsPath.AddArc(new Rectangle(rect.Right - curveSize, rect.Top, curveSize, curveSize), -90, 90); } } if (Tabs.IndexOf(tab) != EndDisplayingTab && (Tabs.IndexOf(tab) != Tabs.Count - 1 && Tabs[Tabs.IndexOf(tab) + 1].Content == DockPane.ActiveContent) && !full) { if (RightToLeft == RightToLeft.Yes) { if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) { GraphicsPath.AddLine(rect.Left, rect.Bottom - curveSize / 2, rect.Left, rect.Bottom - rect.Height / 2); GraphicsPath.AddLine(rect.Left, rect.Bottom - rect.Height / 2, rect.Left + rect.Height / 2, rect.Top); } else { GraphicsPath.AddLine(rect.Left, rect.Top + curveSize / 2, rect.Left, rect.Top + rect.Height / 2); GraphicsPath.AddLine(rect.Left, rect.Top + rect.Height / 2, rect.Left + rect.Height / 2, rect.Bottom); } } else { if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) { GraphicsPath.AddLine(rect.Right, rect.Bottom - curveSize / 2, rect.Right, rect.Bottom - rect.Height / 2); GraphicsPath.AddLine(rect.Right, rect.Bottom - rect.Height / 2, rect.Right - rect.Height / 2, rect.Top); } else { GraphicsPath.AddLine(rect.Right, rect.Top + curveSize / 2, rect.Right, rect.Top + rect.Height / 2); GraphicsPath.AddLine(rect.Right, rect.Top + rect.Height / 2, rect.Right - rect.Height / 2, rect.Bottom); } } } else { // Draw the vertical line opposite the angled side if (RightToLeft == RightToLeft.Yes) { if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) GraphicsPath.AddLine(rect.Left, rect.Bottom - curveSize / 2, rect.Left, rect.Top); else GraphicsPath.AddLine(rect.Left, rect.Top + curveSize / 2, rect.Left, rect.Bottom); } else { if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) GraphicsPath.AddLine(rect.Right, rect.Bottom - curveSize / 2, rect.Right, rect.Top); else GraphicsPath.AddLine(rect.Right, rect.Top + curveSize / 2, rect.Right, rect.Bottom); } } return GraphicsPath; } private void DrawTab_ToolWindow(Graphics g, TabVS2005 tab, Rectangle rect) { Rectangle rectIcon = new Rectangle( rect.X + ToolWindowImageGapLeft, rect.Y + rect.Height - 1 - ToolWindowImageGapBottom - ToolWindowImageHeight, ToolWindowImageWidth, ToolWindowImageHeight); Rectangle rectText = rectIcon; //2015 - haha01haha01 if (DockPane.DockPanel.ShowDocumentIcon) { rectText.X += rectIcon.Width + ToolWindowImageGapRight; rectText.Width = rect.Width - rectIcon.Width - ToolWindowImageGapLeft - ToolWindowImageGapRight - ToolWindowTextGapRight; } else rectText.Width = rect.Width - ToolWindowImageGapLeft - ToolWindowTextGapRight; /*rectText.X += rectIcon.Width + ToolWindowImageGapRight; rectText.Width = rect.Width - rectIcon.Width - ToolWindowImageGapLeft - ToolWindowImageGapRight - ToolWindowTextGapRight;*/ Rectangle rectTab = DrawHelper.RtlTransform(this, rect); rectText = DrawHelper.RtlTransform(this, rectText); rectIcon = DrawHelper.RtlTransform(this, rectIcon); GraphicsPath path = GetTabOutline(tab, true, false); if (DockPane.ActiveContent == tab.Content) { Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.StartColor; Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.EndColor; LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.LinearGradientMode; g.FillPath(new LinearGradientBrush(rectTab, startColor, endColor, gradientMode), path); g.DrawPath(PenToolWindowTabBorder, path); Color textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.TextColor; TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, ToolWindowTextFormat); } else { Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.StartColor; Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.EndColor; LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.LinearGradientMode; g.FillPath(new LinearGradientBrush(rectTab, startColor, endColor, gradientMode), path); if (Tabs.IndexOf(DockPane.ActiveContent) != Tabs.IndexOf(tab) + 1) { Point pt1 = new Point(rect.Right, rect.Top + ToolWindowTabSeperatorGapTop); Point pt2 = new Point(rect.Right, rect.Bottom - ToolWindowTabSeperatorGapBottom); g.DrawLine(PenToolWindowTabBorder, DrawHelper.RtlTransform(this, pt1), DrawHelper.RtlTransform(this, pt2)); } Color textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.TextColor; TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, ToolWindowTextFormat); } //2015 - haha01haha01 if (rectTab.Contains(rectIcon) && DockPane.DockPanel.ShowDocumentIcon) g.DrawIcon(tab.Content.DockHandler.Icon, rectIcon); } private void DrawTab_Document(Graphics g, TabVS2005 tab, Rectangle rect) { if (tab.TabWidth == 0) return; Rectangle rectIcon = new Rectangle( rect.X + DocumentIconGapLeft, rect.Y + rect.Height - 1 - DocumentIconGapBottom - DocumentIconHeight, DocumentIconWidth, DocumentIconHeight); Rectangle rectText = rectIcon; if (DockPane.DockPanel.ShowDocumentIcon) { rectText.X += rectIcon.Width + DocumentIconGapRight; rectText.Y = rect.Y; rectText.Width = rect.Width - rectIcon.Width - DocumentIconGapLeft - DocumentIconGapRight - DocumentTextGapRight; rectText.Height = rect.Height; } else rectText.Width = rect.Width - DocumentIconGapLeft - DocumentTextGapRight; Rectangle rectTab = DrawHelper.RtlTransform(this, rect); Rectangle rectBack = DrawHelper.RtlTransform(this, rect); rectBack.Width += rect.X; rectBack.X = 0; rectText = DrawHelper.RtlTransform(this, rectText); rectIcon = DrawHelper.RtlTransform(this, rectIcon); GraphicsPath path = GetTabOutline(tab, true, false); if (DockPane.ActiveContent == tab.Content) { Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.StartColor; Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.EndColor; LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.LinearGradientMode; g.FillPath(new LinearGradientBrush(rectBack, startColor, endColor, gradientMode), path); g.DrawPath(PenDocumentTabActiveBorder, path); Color textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.TextColor; if (DockPane.IsActiveDocumentPane) TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, BoldFont, rectText, textColor, DocumentTextFormat); else TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, DocumentTextFormat); } else { Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.StartColor; Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.EndColor; LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.LinearGradientMode; g.FillPath(new LinearGradientBrush(rectBack, startColor, endColor, gradientMode), path); g.DrawPath(PenDocumentTabInactiveBorder, path); Color textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.TextColor; TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, DocumentTextFormat); } if (rectTab.Contains(rectIcon) && DockPane.DockPanel.ShowDocumentIcon) g.DrawIcon(tab.Content.DockHandler.Icon, rectIcon); } private void WindowList_Click(object sender, EventArgs e) { int x = 0; int y = ButtonWindowList.Location.Y + ButtonWindowList.Height; SelectMenu.Items.Clear(); foreach (TabVS2005 tab in Tabs) { IDockContent content = tab.Content; ToolStripItem item = SelectMenu.Items.Add(content.DockHandler.TabText, content.DockHandler.Icon.ToBitmap()); item.Tag = tab.Content; item.Click += new EventHandler(ContextMenuItem_Click); } SelectMenu.Show(ButtonWindowList, x, y); } private void ContextMenuItem_Click(object sender, EventArgs e) { ToolStripMenuItem item = sender as ToolStripMenuItem; if (item != null) { IDockContent content = (IDockContent)item.Tag; DockPane.ActiveContent = content; } } private void SetInertButtons() { if (Appearance == DockPane.AppearanceStyle.ToolWindow) { if (m_buttonClose != null) m_buttonClose.Left = -m_buttonClose.Width; if (m_buttonWindowList != null) m_buttonWindowList.Left = -m_buttonWindowList.Width; } else { ButtonClose.Enabled = DockPane.ActiveContent == null ? true : DockPane.ActiveContent.DockHandler.CloseButton; m_closeButtonVisible = DockPane.ActiveContent == null ? true : DockPane.ActiveContent.DockHandler.CloseButtonVisible; ButtonClose.Visible = m_closeButtonVisible; ButtonClose.RefreshChanges(); ButtonWindowList.RefreshChanges(); } } protected override void OnLayout(LayoutEventArgs levent) { if (Appearance == DockPane.AppearanceStyle.Document) { LayoutButtons(); OnRefreshChanges(); } base.OnLayout(levent); } private void LayoutButtons() { Rectangle rectTabStrip = TabStripRectangle; // Set position and size of the buttons int buttonWidth = ButtonClose.Image.Width; int buttonHeight = ButtonClose.Image.Height; int height = rectTabStrip.Height - DocumentButtonGapTop - DocumentButtonGapBottom; if (buttonHeight < height) { buttonWidth = buttonWidth * (height / buttonHeight); buttonHeight = height; } Size buttonSize = new Size(buttonWidth, buttonHeight); int x = rectTabStrip.X + rectTabStrip.Width - DocumentTabGapLeft - DocumentButtonGapRight - buttonWidth; int y = rectTabStrip.Y + DocumentButtonGapTop; Point point = new Point(x, y); ButtonClose.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize)); // If the close button is not visible draw the window list button overtop. // Otherwise it is drawn to the left of the close button. if (m_closeButtonVisible) point.Offset(-(DocumentButtonGapBetween + buttonWidth), 0); ButtonWindowList.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize)); } private void Close_Click(object sender, EventArgs e) { DockPane.CloseActiveContent(); } protected internal override int HitTest(Point ptMouse) { if (!TabsRectangle.Contains(ptMouse)) return -1; foreach (Tab tab in Tabs) { GraphicsPath path = GetTabOutline(tab, true, false); if (path.IsVisible(ptMouse)) return Tabs.IndexOf(tab); } return -1; } protected override void OnMouseHover(EventArgs e) { int index = HitTest(PointToClient(Control.MousePosition)); string toolTip = string.Empty; base.OnMouseHover(e); if (index != -1) { TabVS2005 tab = Tabs[index] as TabVS2005; if (!String.IsNullOrEmpty(tab.Content.DockHandler.ToolTipText)) toolTip = tab.Content.DockHandler.ToolTipText; else if (tab.MaxWidth > tab.TabWidth) toolTip = tab.Content.DockHandler.TabText; } if (m_toolTip.GetToolTip(this) != toolTip) { m_toolTip.Active = false; m_toolTip.SetToolTip(this, toolTip); m_toolTip.Active = true; } // requires further tracking of mouse hover behavior, ResetMouseEventArgs(); } protected override void OnRightToLeftChanged(EventArgs e) { base.OnRightToLeftChanged(e); PerformLayout(); } } }
// LzmaEncoder.cs using System; using System.IO; using SevenZip.Compression.LZ; using SevenZip.Compression.RangeCoder; namespace SevenZip.Compression.LZMA { internal class Encoder : ICoder, ISetCoderProperties, IWriteCoderProperties { private const UInt32 kIfinityPrice = 0xFFFFFFF; private const int kDefaultDictionaryLogSize = 22; private const UInt32 kNumFastBytesDefault = 0x20; private const UInt32 kNumLenSpecSymbols = Base.kNumLowLenSymbols + Base.kNumMidLenSymbols; private const UInt32 kNumOpts = 1 << 12; private const int kPropSize = 5; private static readonly Byte[] g_FastPos = new Byte[1 << 11]; private static readonly string[] kMatchFinderIDs = { "BT2", "BT4" }; private readonly UInt32[] _alignPrices = new UInt32[Base.kAlignTableSize]; private readonly UInt32[] _distancesPrices = new UInt32[Base.kNumFullDistances << Base.kNumLenToPosStatesBits]; private readonly BitEncoder[] _isMatch = new BitEncoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; private readonly BitEncoder[] _isRep = new BitEncoder[Base.kNumStates]; private readonly BitEncoder[] _isRep0Long = new BitEncoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; private readonly BitEncoder[] _isRepG0 = new BitEncoder[Base.kNumStates]; private readonly BitEncoder[] _isRepG1 = new BitEncoder[Base.kNumStates]; private readonly BitEncoder[] _isRepG2 = new BitEncoder[Base.kNumStates]; private readonly LenPriceTableEncoder _lenEncoder = new LenPriceTableEncoder(); private readonly LiteralEncoder _literalEncoder = new LiteralEncoder(); private readonly UInt32[] _matchDistances = new UInt32[Base.kMatchMaxLen * 2 + 2]; private readonly Optimal[] _optimum = new Optimal[kNumOpts]; private readonly BitEncoder[] _posEncoders = new BitEncoder[Base.kNumFullDistances - Base.kEndPosModelIndex]; private readonly BitTreeEncoder[] _posSlotEncoder = new BitTreeEncoder[Base.kNumLenToPosStates]; private readonly UInt32[] _posSlotPrices = new UInt32[1 << (Base.kNumPosSlotBits + Base.kNumLenToPosStatesBits)]; private readonly RangeCoder.Encoder _rangeEncoder = new RangeCoder.Encoder(); private readonly UInt32[] _repDistances = new UInt32[Base.kNumRepDistances]; private readonly LenPriceTableEncoder _repMatchLenEncoder = new LenPriceTableEncoder(); private readonly Byte[] properties = new Byte[kPropSize]; private readonly UInt32[] repLens = new UInt32[Base.kNumRepDistances]; private readonly UInt32[] reps = new UInt32[Base.kNumRepDistances]; private readonly UInt32[] tempPrices = new UInt32[Base.kNumFullDistances]; private UInt32 _additionalOffset; private UInt32 _alignPriceCount; private UInt32 _dictionarySize = (1 << kDefaultDictionaryLogSize); private UInt32 _dictionarySizePrev = 0xFFFFFFFF; private UInt32 _distTableSize = (kDefaultDictionaryLogSize * 2); private bool _finished; private Stream _inStream; private UInt32 _longestMatchLength; private bool _longestMatchWasFound; private IMatchFinder _matchFinder; private EMatchFinderType _matchFinderType = EMatchFinderType.BT4; private UInt32 _matchPriceCount; private bool _needReleaseMFStream; private UInt32 _numDistancePairs; private UInt32 _numFastBytes = kNumFastBytesDefault; private UInt32 _numFastBytesPrev = 0xFFFFFFFF; private int _numLiteralContextBits = 3; private int _numLiteralPosStateBits; private UInt32 _optimumCurrentIndex; private UInt32 _optimumEndIndex; private BitTreeEncoder _posAlignEncoder = new BitTreeEncoder(Base.kNumAlignBits); private int _posStateBits = 2; private UInt32 _posStateMask = (4 - 1); private Byte _previousByte; private Base.State _state = new Base.State(); private uint _trainSize; private bool _writeEndMark; private Int64 nowPos64; static Encoder() { const Byte kFastSlots = 22; int c = 2; g_FastPos[0] = 0; g_FastPos[1] = 1; for (Byte slotFast = 2; slotFast < kFastSlots; slotFast++) { UInt32 k = ((UInt32)1 << ((slotFast >> 1) - 1)); for (UInt32 j = 0; j < k; j++, c++) g_FastPos[c] = slotFast; } } public Encoder() { for (int i = 0; i < kNumOpts; i++) _optimum[i] = new Optimal(); for (int i = 0; i < Base.kNumLenToPosStates; i++) _posSlotEncoder[i] = new BitTreeEncoder(Base.kNumPosSlotBits); } public void Code(Stream inStream, Stream outStream, Int64 inSize, Int64 outSize, ICodeProgress progress) { _needReleaseMFStream = false; try { SetStreams(inStream, outStream, inSize, outSize); while (true) { Int64 processedInSize; Int64 processedOutSize; bool finished; CodeOneBlock(out processedInSize, out processedOutSize, out finished); if (finished) return; if (progress != null) { progress.SetProgress(processedInSize, processedOutSize); } } } finally { ReleaseStreams(); } } public void SetCoderProperties(CoderPropID[] propIDs, object[] properties) { for (UInt32 i = 0; i < properties.Length; i++) { object prop = properties[i]; switch (propIDs[i]) { case CoderPropID.NumFastBytes: { if (!(prop is Int32)) throw new InvalidParamException(); var numFastBytes = (Int32)prop; if (numFastBytes < 5 || numFastBytes > Base.kMatchMaxLen) throw new InvalidParamException(); _numFastBytes = (UInt32)numFastBytes; break; } case CoderPropID.Algorithm: { /* if (!(prop is Int32)) throw new InvalidParamException(); Int32 maximize = (Int32)prop; _fastMode = (maximize == 0); _maxMode = (maximize >= 2); */ break; } case CoderPropID.MatchFinder: { if (!(prop is String)) throw new InvalidParamException(); EMatchFinderType matchFinderIndexPrev = _matchFinderType; int m = FindMatchFinder(((string)prop).ToUpper()); if (m < 0) throw new InvalidParamException(); _matchFinderType = (EMatchFinderType)m; if (_matchFinder != null && matchFinderIndexPrev != _matchFinderType) { _dictionarySizePrev = 0xFFFFFFFF; _matchFinder = null; } break; } case CoderPropID.DictionarySize: { const int kDicLogSizeMaxCompress = 30; if (!(prop is Int32)) throw new InvalidParamException(); ; var dictionarySize = (Int32)prop; if (dictionarySize < (UInt32)(1 << Base.kDicLogSizeMin) || dictionarySize > (UInt32)(1 << kDicLogSizeMaxCompress)) throw new InvalidParamException(); _dictionarySize = (UInt32)dictionarySize; int dicLogSize; for (dicLogSize = 0; dicLogSize < (UInt32)kDicLogSizeMaxCompress; dicLogSize++) if (dictionarySize <= ((UInt32)(1) << dicLogSize)) break; _distTableSize = (UInt32)dicLogSize * 2; break; } case CoderPropID.PosStateBits: { if (!(prop is Int32)) throw new InvalidParamException(); var v = (Int32)prop; if (v < 0 || v > (UInt32)Base.kNumPosStatesBitsEncodingMax) throw new InvalidParamException(); _posStateBits = v; _posStateMask = (((UInt32)1) << _posStateBits) - 1; break; } case CoderPropID.LitPosBits: { if (!(prop is Int32)) throw new InvalidParamException(); var v = (Int32)prop; if (v < 0 || v > Base.kNumLitPosStatesBitsEncodingMax) throw new InvalidParamException(); _numLiteralPosStateBits = v; break; } case CoderPropID.LitContextBits: { if (!(prop is Int32)) throw new InvalidParamException(); var v = (Int32)prop; if (v < 0 || v > Base.kNumLitContextBitsMax) throw new InvalidParamException(); ; _numLiteralContextBits = v; break; } case CoderPropID.EndMarker: { if (!(prop is Boolean)) throw new InvalidParamException(); SetWriteEndMarkerMode((Boolean)prop); break; } default: throw new InvalidParamException(); } } } public void WriteCoderProperties(Stream outStream) { properties[0] = (Byte)((_posStateBits * 5 + _numLiteralPosStateBits) * 9 + _numLiteralContextBits); for (int i = 0; i < 4; i++) properties[1 + i] = (Byte)((_dictionarySize >> (8 * i)) & 0xFF); outStream.Write(properties, 0, kPropSize); } private static UInt32 GetPosSlot(UInt32 pos) { if (pos < (1 << 11)) return g_FastPos[pos]; if (pos < (1 << 21)) return (UInt32)(g_FastPos[pos >> 10] + 20); return (UInt32)(g_FastPos[pos >> 20] + 40); } private static UInt32 GetPosSlot2(UInt32 pos) { if (pos < (1 << 17)) return (UInt32)(g_FastPos[pos >> 6] + 12); if (pos < (1 << 27)) return (UInt32)(g_FastPos[pos >> 16] + 32); return (UInt32)(g_FastPos[pos >> 26] + 52); } private void BaseInit() { _state.Init(); _previousByte = 0; for (UInt32 i = 0; i < Base.kNumRepDistances; i++) _repDistances[i] = 0; } private void Create() { if (_matchFinder == null) { var bt = new BinTree(); int numHashBytes = 4; if (_matchFinderType == EMatchFinderType.BT2) numHashBytes = 2; bt.SetType(numHashBytes); _matchFinder = bt; } _literalEncoder.Create(_numLiteralPosStateBits, _numLiteralContextBits); if (_dictionarySize == _dictionarySizePrev && _numFastBytesPrev == _numFastBytes) return; _matchFinder.Create(_dictionarySize, kNumOpts, _numFastBytes, Base.kMatchMaxLen + 1); _dictionarySizePrev = _dictionarySize; _numFastBytesPrev = _numFastBytes; } private void SetWriteEndMarkerMode(bool writeEndMarker) { _writeEndMark = writeEndMarker; } private void Init() { BaseInit(); _rangeEncoder.Init(); uint i; for (i = 0; i < Base.kNumStates; i++) { for (uint j = 0; j <= _posStateMask; j++) { uint complexState = (i << Base.kNumPosStatesBitsMax) + j; _isMatch[complexState].Init(); _isRep0Long[complexState].Init(); } _isRep[i].Init(); _isRepG0[i].Init(); _isRepG1[i].Init(); _isRepG2[i].Init(); } _literalEncoder.Init(); for (i = 0; i < Base.kNumLenToPosStates; i++) _posSlotEncoder[i].Init(); for (i = 0; i < Base.kNumFullDistances - Base.kEndPosModelIndex; i++) _posEncoders[i].Init(); _lenEncoder.Init((UInt32)1 << _posStateBits); _repMatchLenEncoder.Init((UInt32)1 << _posStateBits); _posAlignEncoder.Init(); _longestMatchWasFound = false; _optimumEndIndex = 0; _optimumCurrentIndex = 0; _additionalOffset = 0; } private void ReadMatchDistances(out UInt32 lenRes, out UInt32 numDistancePairs) { lenRes = 0; numDistancePairs = _matchFinder.GetMatches(_matchDistances); if (numDistancePairs > 0) { lenRes = _matchDistances[numDistancePairs - 2]; if (lenRes == _numFastBytes) lenRes += _matchFinder.GetMatchLen((int)lenRes - 1, _matchDistances[numDistancePairs - 1], Base.kMatchMaxLen - lenRes); } _additionalOffset++; } private void MovePos(UInt32 num) { if (num > 0) { _matchFinder.Skip(num); _additionalOffset += num; } } private UInt32 GetRepLen1Price(Base.State state, UInt32 posState) { return _isRepG0[state.Index].GetPrice0() + _isRep0Long[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice0(); } private UInt32 GetPureRepPrice(UInt32 repIndex, Base.State state, UInt32 posState) { UInt32 price; if (repIndex == 0) { price = _isRepG0[state.Index].GetPrice0(); price += _isRep0Long[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice1(); } else { price = _isRepG0[state.Index].GetPrice1(); if (repIndex == 1) price += _isRepG1[state.Index].GetPrice0(); else { price += _isRepG1[state.Index].GetPrice1(); price += _isRepG2[state.Index].GetPrice(repIndex - 2); } } return price; } private UInt32 GetRepPrice(UInt32 repIndex, UInt32 len, Base.State state, UInt32 posState) { UInt32 price = _repMatchLenEncoder.GetPrice(len - Base.kMatchMinLen, posState); return price + GetPureRepPrice(repIndex, state, posState); } private UInt32 GetPosLenPrice(UInt32 pos, UInt32 len, UInt32 posState) { UInt32 price; UInt32 lenToPosState = Base.GetLenToPosState(len); if (pos < Base.kNumFullDistances) price = _distancesPrices[(lenToPosState * Base.kNumFullDistances) + pos]; else price = _posSlotPrices[(lenToPosState << Base.kNumPosSlotBits) + GetPosSlot2(pos)] + _alignPrices[pos & Base.kAlignMask]; return price + _lenEncoder.GetPrice(len - Base.kMatchMinLen, posState); } private UInt32 Backward(out UInt32 backRes, UInt32 cur) { _optimumEndIndex = cur; UInt32 posMem = _optimum[cur].PosPrev; UInt32 backMem = _optimum[cur].BackPrev; do { if (_optimum[cur].Prev1IsChar) { _optimum[posMem].MakeAsChar(); _optimum[posMem].PosPrev = posMem - 1; if (_optimum[cur].Prev2) { _optimum[posMem - 1].Prev1IsChar = false; _optimum[posMem - 1].PosPrev = _optimum[cur].PosPrev2; _optimum[posMem - 1].BackPrev = _optimum[cur].BackPrev2; } } UInt32 posPrev = posMem; UInt32 backCur = backMem; backMem = _optimum[posPrev].BackPrev; posMem = _optimum[posPrev].PosPrev; _optimum[posPrev].BackPrev = backCur; _optimum[posPrev].PosPrev = cur; cur = posPrev; } while (cur > 0); backRes = _optimum[0].BackPrev; _optimumCurrentIndex = _optimum[0].PosPrev; return _optimumCurrentIndex; } private UInt32 GetOptimum(UInt32 position, out UInt32 backRes) { if (_optimumEndIndex != _optimumCurrentIndex) { UInt32 lenRes = _optimum[_optimumCurrentIndex].PosPrev - _optimumCurrentIndex; backRes = _optimum[_optimumCurrentIndex].BackPrev; _optimumCurrentIndex = _optimum[_optimumCurrentIndex].PosPrev; return lenRes; } _optimumCurrentIndex = _optimumEndIndex = 0; UInt32 lenMain, numDistancePairs; if (!_longestMatchWasFound) { ReadMatchDistances(out lenMain, out numDistancePairs); } else { lenMain = _longestMatchLength; numDistancePairs = _numDistancePairs; _longestMatchWasFound = false; } UInt32 numAvailableBytes = _matchFinder.GetNumAvailableBytes() + 1; if (numAvailableBytes < 2) { backRes = 0xFFFFFFFF; return 1; } if (numAvailableBytes > Base.kMatchMaxLen) numAvailableBytes = Base.kMatchMaxLen; UInt32 repMaxIndex = 0; UInt32 i; for (i = 0; i < Base.kNumRepDistances; i++) { reps[i] = _repDistances[i]; repLens[i] = _matchFinder.GetMatchLen(0 - 1, reps[i], Base.kMatchMaxLen); if (repLens[i] > repLens[repMaxIndex]) repMaxIndex = i; } if (repLens[repMaxIndex] >= _numFastBytes) { backRes = repMaxIndex; UInt32 lenRes = repLens[repMaxIndex]; MovePos(lenRes - 1); return lenRes; } if (lenMain >= _numFastBytes) { backRes = _matchDistances[numDistancePairs - 1] + Base.kNumRepDistances; MovePos(lenMain - 1); return lenMain; } Byte currentByte = _matchFinder.GetIndexByte(0 - 1); Byte matchByte = _matchFinder.GetIndexByte((Int32)(0 - _repDistances[0] - 1 - 1)); if (lenMain < 2 && currentByte != matchByte && repLens[repMaxIndex] < 2) { backRes = 0xFFFFFFFF; return 1; } _optimum[0].State = _state; UInt32 posState = (position & _posStateMask); _optimum[1].Price = _isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice0() + _literalEncoder.GetSubCoder(position, _previousByte).GetPrice(!_state.IsCharState(), matchByte, currentByte); _optimum[1].MakeAsChar(); UInt32 matchPrice = _isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice1(); UInt32 repMatchPrice = matchPrice + _isRep[_state.Index].GetPrice1(); if (matchByte == currentByte) { UInt32 shortRepPrice = repMatchPrice + GetRepLen1Price(_state, posState); if (shortRepPrice < _optimum[1].Price) { _optimum[1].Price = shortRepPrice; _optimum[1].MakeAsShortRep(); } } UInt32 lenEnd = ((lenMain >= repLens[repMaxIndex]) ? lenMain : repLens[repMaxIndex]); if (lenEnd < 2) { backRes = _optimum[1].BackPrev; return 1; } _optimum[1].PosPrev = 0; _optimum[0].Backs0 = reps[0]; _optimum[0].Backs1 = reps[1]; _optimum[0].Backs2 = reps[2]; _optimum[0].Backs3 = reps[3]; UInt32 len = lenEnd; do _optimum[len--].Price = kIfinityPrice; while (len >= 2); for (i = 0; i < Base.kNumRepDistances; i++) { UInt32 repLen = repLens[i]; if (repLen < 2) continue; UInt32 price = repMatchPrice + GetPureRepPrice(i, _state, posState); do { UInt32 curAndLenPrice = price + _repMatchLenEncoder.GetPrice(repLen - 2, posState); Optimal optimum = _optimum[repLen]; if (curAndLenPrice < optimum.Price) { optimum.Price = curAndLenPrice; optimum.PosPrev = 0; optimum.BackPrev = i; optimum.Prev1IsChar = false; } } while (--repLen >= 2); } UInt32 normalMatchPrice = matchPrice + _isRep[_state.Index].GetPrice0(); len = ((repLens[0] >= 2) ? repLens[0] + 1 : 2); if (len <= lenMain) { UInt32 offs = 0; while (len > _matchDistances[offs]) offs += 2; for (;; len++) { UInt32 distance = _matchDistances[offs + 1]; UInt32 curAndLenPrice = normalMatchPrice + GetPosLenPrice(distance, len, posState); Optimal optimum = _optimum[len]; if (curAndLenPrice < optimum.Price) { optimum.Price = curAndLenPrice; optimum.PosPrev = 0; optimum.BackPrev = distance + Base.kNumRepDistances; optimum.Prev1IsChar = false; } if (len == _matchDistances[offs]) { offs += 2; if (offs == numDistancePairs) break; } } } UInt32 cur = 0; while (true) { cur++; if (cur == lenEnd) return Backward(out backRes, cur); UInt32 newLen; ReadMatchDistances(out newLen, out numDistancePairs); if (newLen >= _numFastBytes) { _numDistancePairs = numDistancePairs; _longestMatchLength = newLen; _longestMatchWasFound = true; return Backward(out backRes, cur); } position++; UInt32 posPrev = _optimum[cur].PosPrev; Base.State state; if (_optimum[cur].Prev1IsChar) { posPrev--; if (_optimum[cur].Prev2) { state = _optimum[_optimum[cur].PosPrev2].State; if (_optimum[cur].BackPrev2 < Base.kNumRepDistances) state.UpdateRep(); else state.UpdateMatch(); } else state = _optimum[posPrev].State; state.UpdateChar(); } else state = _optimum[posPrev].State; if (posPrev == cur - 1) { if (_optimum[cur].IsShortRep()) state.UpdateShortRep(); else state.UpdateChar(); } else { UInt32 pos; if (_optimum[cur].Prev1IsChar && _optimum[cur].Prev2) { posPrev = _optimum[cur].PosPrev2; pos = _optimum[cur].BackPrev2; state.UpdateRep(); } else { pos = _optimum[cur].BackPrev; if (pos < Base.kNumRepDistances) state.UpdateRep(); else state.UpdateMatch(); } Optimal opt = _optimum[posPrev]; if (pos < Base.kNumRepDistances) { if (pos == 0) { reps[0] = opt.Backs0; reps[1] = opt.Backs1; reps[2] = opt.Backs2; reps[3] = opt.Backs3; } else if (pos == 1) { reps[0] = opt.Backs1; reps[1] = opt.Backs0; reps[2] = opt.Backs2; reps[3] = opt.Backs3; } else if (pos == 2) { reps[0] = opt.Backs2; reps[1] = opt.Backs0; reps[2] = opt.Backs1; reps[3] = opt.Backs3; } else { reps[0] = opt.Backs3; reps[1] = opt.Backs0; reps[2] = opt.Backs1; reps[3] = opt.Backs2; } } else { reps[0] = (pos - Base.kNumRepDistances); reps[1] = opt.Backs0; reps[2] = opt.Backs1; reps[3] = opt.Backs2; } } _optimum[cur].State = state; _optimum[cur].Backs0 = reps[0]; _optimum[cur].Backs1 = reps[1]; _optimum[cur].Backs2 = reps[2]; _optimum[cur].Backs3 = reps[3]; UInt32 curPrice = _optimum[cur].Price; currentByte = _matchFinder.GetIndexByte(0 - 1); matchByte = _matchFinder.GetIndexByte((Int32)(0 - reps[0] - 1 - 1)); posState = (position & _posStateMask); UInt32 curAnd1Price = curPrice + _isMatch[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice0() + _literalEncoder.GetSubCoder(position, _matchFinder.GetIndexByte(0 - 2)). GetPrice(!state.IsCharState(), matchByte, currentByte); Optimal nextOptimum = _optimum[cur + 1]; bool nextIsChar = false; if (curAnd1Price < nextOptimum.Price) { nextOptimum.Price = curAnd1Price; nextOptimum.PosPrev = cur; nextOptimum.MakeAsChar(); nextIsChar = true; } matchPrice = curPrice + _isMatch[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice1(); repMatchPrice = matchPrice + _isRep[state.Index].GetPrice1(); if (matchByte == currentByte && !(nextOptimum.PosPrev < cur && nextOptimum.BackPrev == 0)) { UInt32 shortRepPrice = repMatchPrice + GetRepLen1Price(state, posState); if (shortRepPrice <= nextOptimum.Price) { nextOptimum.Price = shortRepPrice; nextOptimum.PosPrev = cur; nextOptimum.MakeAsShortRep(); nextIsChar = true; } } UInt32 numAvailableBytesFull = _matchFinder.GetNumAvailableBytes() + 1; numAvailableBytesFull = Math.Min(kNumOpts - 1 - cur, numAvailableBytesFull); numAvailableBytes = numAvailableBytesFull; if (numAvailableBytes < 2) continue; if (numAvailableBytes > _numFastBytes) numAvailableBytes = _numFastBytes; if (!nextIsChar && matchByte != currentByte) { // try Literal + rep0 UInt32 t = Math.Min(numAvailableBytesFull - 1, _numFastBytes); UInt32 lenTest2 = _matchFinder.GetMatchLen(0, reps[0], t); if (lenTest2 >= 2) { Base.State state2 = state; state2.UpdateChar(); UInt32 posStateNext = (position + 1) & _posStateMask; UInt32 nextRepMatchPrice = curAnd1Price + _isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice1() + _isRep[state2.Index].GetPrice1(); { UInt32 offset = cur + 1 + lenTest2; while (lenEnd < offset) _optimum[++lenEnd].Price = kIfinityPrice; UInt32 curAndLenPrice = nextRepMatchPrice + GetRepPrice( 0, lenTest2, state2, posStateNext); Optimal optimum = _optimum[offset]; if (curAndLenPrice < optimum.Price) { optimum.Price = curAndLenPrice; optimum.PosPrev = cur + 1; optimum.BackPrev = 0; optimum.Prev1IsChar = true; optimum.Prev2 = false; } } } } UInt32 startLen = 2; // speed optimization for (UInt32 repIndex = 0; repIndex < Base.kNumRepDistances; repIndex++) { UInt32 lenTest = _matchFinder.GetMatchLen(0 - 1, reps[repIndex], numAvailableBytes); if (lenTest < 2) continue; UInt32 lenTestTemp = lenTest; do { while (lenEnd < cur + lenTest) _optimum[++lenEnd].Price = kIfinityPrice; UInt32 curAndLenPrice = repMatchPrice + GetRepPrice(repIndex, lenTest, state, posState); Optimal optimum = _optimum[cur + lenTest]; if (curAndLenPrice < optimum.Price) { optimum.Price = curAndLenPrice; optimum.PosPrev = cur; optimum.BackPrev = repIndex; optimum.Prev1IsChar = false; } } while (--lenTest >= 2); lenTest = lenTestTemp; if (repIndex == 0) startLen = lenTest + 1; // if (_maxMode) if (lenTest < numAvailableBytesFull) { UInt32 t = Math.Min(numAvailableBytesFull - 1 - lenTest, _numFastBytes); UInt32 lenTest2 = _matchFinder.GetMatchLen((Int32)lenTest, reps[repIndex], t); if (lenTest2 >= 2) { Base.State state2 = state; state2.UpdateRep(); UInt32 posStateNext = (position + lenTest) & _posStateMask; UInt32 curAndLenCharPrice = repMatchPrice + GetRepPrice(repIndex, lenTest, state, posState) + _isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice0() + _literalEncoder.GetSubCoder(position + lenTest, _matchFinder.GetIndexByte((Int32)lenTest - 1 - 1)).GetPrice(true, _matchFinder.GetIndexByte((Int32)lenTest - 1 - (Int32)(reps[repIndex] + 1)), _matchFinder.GetIndexByte((Int32)lenTest - 1)); state2.UpdateChar(); posStateNext = (position + lenTest + 1) & _posStateMask; UInt32 nextMatchPrice = curAndLenCharPrice + _isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice1(); UInt32 nextRepMatchPrice = nextMatchPrice + _isRep[state2.Index].GetPrice1(); // for(; lenTest2 >= 2; lenTest2--) { UInt32 offset = lenTest + 1 + lenTest2; while (lenEnd < cur + offset) _optimum[++lenEnd].Price = kIfinityPrice; UInt32 curAndLenPrice = nextRepMatchPrice + GetRepPrice(0, lenTest2, state2, posStateNext); Optimal optimum = _optimum[cur + offset]; if (curAndLenPrice < optimum.Price) { optimum.Price = curAndLenPrice; optimum.PosPrev = cur + lenTest + 1; optimum.BackPrev = 0; optimum.Prev1IsChar = true; optimum.Prev2 = true; optimum.PosPrev2 = cur; optimum.BackPrev2 = repIndex; } } } } } if (newLen > numAvailableBytes) { newLen = numAvailableBytes; for (numDistancePairs = 0; newLen > _matchDistances[numDistancePairs]; numDistancePairs += 2) ; _matchDistances[numDistancePairs] = newLen; numDistancePairs += 2; } if (newLen >= startLen) { normalMatchPrice = matchPrice + _isRep[state.Index].GetPrice0(); while (lenEnd < cur + newLen) _optimum[++lenEnd].Price = kIfinityPrice; UInt32 offs = 0; while (startLen > _matchDistances[offs]) offs += 2; for (UInt32 lenTest = startLen;; lenTest++) { UInt32 curBack = _matchDistances[offs + 1]; UInt32 curAndLenPrice = normalMatchPrice + GetPosLenPrice(curBack, lenTest, posState); Optimal optimum = _optimum[cur + lenTest]; if (curAndLenPrice < optimum.Price) { optimum.Price = curAndLenPrice; optimum.PosPrev = cur; optimum.BackPrev = curBack + Base.kNumRepDistances; optimum.Prev1IsChar = false; } if (lenTest == _matchDistances[offs]) { if (lenTest < numAvailableBytesFull) { UInt32 t = Math.Min(numAvailableBytesFull - 1 - lenTest, _numFastBytes); UInt32 lenTest2 = _matchFinder.GetMatchLen((Int32)lenTest, curBack, t); if (lenTest2 >= 2) { Base.State state2 = state; state2.UpdateMatch(); UInt32 posStateNext = (position + lenTest) & _posStateMask; UInt32 curAndLenCharPrice = curAndLenPrice + _isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice0() + _literalEncoder.GetSubCoder(position + lenTest, _matchFinder.GetIndexByte((Int32)lenTest - 1 - 1)). GetPrice(true, _matchFinder.GetIndexByte((Int32)lenTest - (Int32)(curBack + 1) - 1), _matchFinder.GetIndexByte((Int32)lenTest - 1)); state2.UpdateChar(); posStateNext = (position + lenTest + 1) & _posStateMask; UInt32 nextMatchPrice = curAndLenCharPrice + _isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice1(); UInt32 nextRepMatchPrice = nextMatchPrice + _isRep[state2.Index].GetPrice1(); UInt32 offset = lenTest + 1 + lenTest2; while (lenEnd < cur + offset) _optimum[++lenEnd].Price = kIfinityPrice; curAndLenPrice = nextRepMatchPrice + GetRepPrice(0, lenTest2, state2, posStateNext); optimum = _optimum[cur + offset]; if (curAndLenPrice < optimum.Price) { optimum.Price = curAndLenPrice; optimum.PosPrev = cur + lenTest + 1; optimum.BackPrev = 0; optimum.Prev1IsChar = true; optimum.Prev2 = true; optimum.PosPrev2 = cur; optimum.BackPrev2 = curBack + Base.kNumRepDistances; } } } offs += 2; if (offs == numDistancePairs) break; } } } } } private bool ChangePair(UInt32 smallDist, UInt32 bigDist) { const int kDif = 7; return (smallDist < ((UInt32)(1) << (32 - kDif)) && bigDist >= (smallDist << kDif)); } private void WriteEndMarker(UInt32 posState) { if (!_writeEndMark) return; _isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].Encode(_rangeEncoder, 1); _isRep[_state.Index].Encode(_rangeEncoder, 0); _state.UpdateMatch(); UInt32 len = Base.kMatchMinLen; _lenEncoder.Encode(_rangeEncoder, len - Base.kMatchMinLen, posState); UInt32 posSlot = (1 << Base.kNumPosSlotBits) - 1; UInt32 lenToPosState = Base.GetLenToPosState(len); _posSlotEncoder[lenToPosState].Encode(_rangeEncoder, posSlot); int footerBits = 30; UInt32 posReduced = (((UInt32)1) << footerBits) - 1; _rangeEncoder.EncodeDirectBits(posReduced >> Base.kNumAlignBits, footerBits - Base.kNumAlignBits); _posAlignEncoder.ReverseEncode(_rangeEncoder, posReduced & Base.kAlignMask); } private void Flush(UInt32 nowPos) { ReleaseMFStream(); WriteEndMarker(nowPos & _posStateMask); _rangeEncoder.FlushData(); _rangeEncoder.FlushStream(); } public void CodeOneBlock(out Int64 inSize, out Int64 outSize, out bool finished) { inSize = 0; outSize = 0; finished = true; if (_inStream != null) { _matchFinder.SetStream(_inStream); _matchFinder.Init(); _needReleaseMFStream = true; _inStream = null; if (_trainSize > 0) _matchFinder.Skip(_trainSize); } if (_finished) return; _finished = true; Int64 progressPosValuePrev = nowPos64; if (nowPos64 == 0) { if (_matchFinder.GetNumAvailableBytes() == 0) { Flush((UInt32)nowPos64); return; } UInt32 len, numDistancePairs; // it's not used ReadMatchDistances(out len, out numDistancePairs); UInt32 posState = (UInt32)(nowPos64) & _posStateMask; _isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].Encode(_rangeEncoder, 0); _state.UpdateChar(); Byte curByte = _matchFinder.GetIndexByte((Int32)(0 - _additionalOffset)); _literalEncoder.GetSubCoder((UInt32)(nowPos64), _previousByte).Encode(_rangeEncoder, curByte); _previousByte = curByte; _additionalOffset--; nowPos64++; } if (_matchFinder.GetNumAvailableBytes() == 0) { Flush((UInt32)nowPos64); return; } while (true) { UInt32 pos; UInt32 len = GetOptimum((UInt32)nowPos64, out pos); UInt32 posState = ((UInt32)nowPos64) & _posStateMask; UInt32 complexState = (_state.Index << Base.kNumPosStatesBitsMax) + posState; if (len == 1 && pos == 0xFFFFFFFF) { _isMatch[complexState].Encode(_rangeEncoder, 0); Byte curByte = _matchFinder.GetIndexByte((Int32)(0 - _additionalOffset)); LiteralEncoder.Encoder2 subCoder = _literalEncoder.GetSubCoder((UInt32)nowPos64, _previousByte); if (!_state.IsCharState()) { Byte matchByte = _matchFinder.GetIndexByte((Int32)(0 - _repDistances[0] - 1 - _additionalOffset)); subCoder.EncodeMatched(_rangeEncoder, matchByte, curByte); } else subCoder.Encode(_rangeEncoder, curByte); _previousByte = curByte; _state.UpdateChar(); } else { _isMatch[complexState].Encode(_rangeEncoder, 1); if (pos < Base.kNumRepDistances) { _isRep[_state.Index].Encode(_rangeEncoder, 1); if (pos == 0) { _isRepG0[_state.Index].Encode(_rangeEncoder, 0); if (len == 1) _isRep0Long[complexState].Encode(_rangeEncoder, 0); else _isRep0Long[complexState].Encode(_rangeEncoder, 1); } else { _isRepG0[_state.Index].Encode(_rangeEncoder, 1); if (pos == 1) _isRepG1[_state.Index].Encode(_rangeEncoder, 0); else { _isRepG1[_state.Index].Encode(_rangeEncoder, 1); _isRepG2[_state.Index].Encode(_rangeEncoder, pos - 2); } } if (len == 1) _state.UpdateShortRep(); else { _repMatchLenEncoder.Encode(_rangeEncoder, len - Base.kMatchMinLen, posState); _state.UpdateRep(); } UInt32 distance = _repDistances[pos]; if (pos != 0) { for (UInt32 i = pos; i >= 1; i--) _repDistances[i] = _repDistances[i - 1]; _repDistances[0] = distance; } } else { _isRep[_state.Index].Encode(_rangeEncoder, 0); _state.UpdateMatch(); _lenEncoder.Encode(_rangeEncoder, len - Base.kMatchMinLen, posState); pos -= Base.kNumRepDistances; UInt32 posSlot = GetPosSlot(pos); UInt32 lenToPosState = Base.GetLenToPosState(len); _posSlotEncoder[lenToPosState].Encode(_rangeEncoder, posSlot); if (posSlot >= Base.kStartPosModelIndex) { var footerBits = (int)((posSlot >> 1) - 1); UInt32 baseVal = ((2 | (posSlot & 1)) << footerBits); UInt32 posReduced = pos - baseVal; if (posSlot < Base.kEndPosModelIndex) BitTreeEncoder.ReverseEncode(_posEncoders, baseVal - posSlot - 1, _rangeEncoder, footerBits, posReduced); else { _rangeEncoder.EncodeDirectBits(posReduced >> Base.kNumAlignBits, footerBits - Base.kNumAlignBits); _posAlignEncoder.ReverseEncode(_rangeEncoder, posReduced & Base.kAlignMask); _alignPriceCount++; } } UInt32 distance = pos; for (UInt32 i = Base.kNumRepDistances - 1; i >= 1; i--) _repDistances[i] = _repDistances[i - 1]; _repDistances[0] = distance; _matchPriceCount++; } _previousByte = _matchFinder.GetIndexByte((Int32)(len - 1 - _additionalOffset)); } _additionalOffset -= len; nowPos64 += len; if (_additionalOffset == 0) { // if (!_fastMode) if (_matchPriceCount >= (1 << 7)) FillDistancesPrices(); if (_alignPriceCount >= Base.kAlignTableSize) FillAlignPrices(); inSize = nowPos64; outSize = _rangeEncoder.GetProcessedSizeAdd(); if (_matchFinder.GetNumAvailableBytes() == 0) { Flush((UInt32)nowPos64); return; } if (nowPos64 - progressPosValuePrev >= (1 << 12)) { _finished = false; finished = false; return; } } } } private void ReleaseMFStream() { if (_matchFinder != null && _needReleaseMFStream) { _matchFinder.ReleaseStream(); _needReleaseMFStream = false; } } private void SetOutStream(Stream outStream) { _rangeEncoder.SetStream(outStream); } private void ReleaseOutStream() { _rangeEncoder.ReleaseStream(); } private void ReleaseStreams() { ReleaseMFStream(); ReleaseOutStream(); } private void SetStreams(Stream inStream, Stream outStream, Int64 inSize, Int64 outSize) { _inStream = inStream; _finished = false; Create(); SetOutStream(outStream); Init(); // if (!_fastMode) { FillDistancesPrices(); FillAlignPrices(); } _lenEncoder.SetTableSize(_numFastBytes + 1 - Base.kMatchMinLen); _lenEncoder.UpdateTables((UInt32)1 << _posStateBits); _repMatchLenEncoder.SetTableSize(_numFastBytes + 1 - Base.kMatchMinLen); _repMatchLenEncoder.UpdateTables((UInt32)1 << _posStateBits); nowPos64 = 0; } private void FillDistancesPrices() { for (UInt32 i = Base.kStartPosModelIndex; i < Base.kNumFullDistances; i++) { UInt32 posSlot = GetPosSlot(i); var footerBits = (int)((posSlot >> 1) - 1); UInt32 baseVal = ((2 | (posSlot & 1)) << footerBits); tempPrices[i] = BitTreeEncoder.ReverseGetPrice(_posEncoders, baseVal - posSlot - 1, footerBits, i - baseVal); } for (UInt32 lenToPosState = 0; lenToPosState < Base.kNumLenToPosStates; lenToPosState++) { UInt32 posSlot; BitTreeEncoder encoder = _posSlotEncoder[lenToPosState]; UInt32 st = (lenToPosState << Base.kNumPosSlotBits); for (posSlot = 0; posSlot < _distTableSize; posSlot++) _posSlotPrices[st + posSlot] = encoder.GetPrice(posSlot); for (posSlot = Base.kEndPosModelIndex; posSlot < _distTableSize; posSlot++) _posSlotPrices[st + posSlot] += ((((posSlot >> 1) - 1) - Base.kNumAlignBits) << BitEncoder.kNumBitPriceShiftBits); UInt32 st2 = lenToPosState * Base.kNumFullDistances; UInt32 i; for (i = 0; i < Base.kStartPosModelIndex; i++) _distancesPrices[st2 + i] = _posSlotPrices[st + i]; for (; i < Base.kNumFullDistances; i++) _distancesPrices[st2 + i] = _posSlotPrices[st + GetPosSlot(i)] + tempPrices[i]; } _matchPriceCount = 0; } private void FillAlignPrices() { for (UInt32 i = 0; i < Base.kAlignTableSize; i++) _alignPrices[i] = _posAlignEncoder.ReverseGetPrice(i); _alignPriceCount = 0; } private static int FindMatchFinder(string s) { for (int m = 0; m < kMatchFinderIDs.Length; m++) if (s == kMatchFinderIDs[m]) return m; return -1; } public void SetTrainSize(uint trainSize) { _trainSize = trainSize; } private enum EMatchFinderType { BT2, BT4, }; private class LenEncoder { private readonly BitTreeEncoder[] _lowCoder = new BitTreeEncoder[Base.kNumPosStatesEncodingMax]; private readonly BitTreeEncoder[] _midCoder = new BitTreeEncoder[Base.kNumPosStatesEncodingMax]; private BitEncoder _choice = new BitEncoder(); private BitEncoder _choice2 = new BitEncoder(); private BitTreeEncoder _highCoder = new BitTreeEncoder(Base.kNumHighLenBits); public LenEncoder() { for (UInt32 posState = 0; posState < Base.kNumPosStatesEncodingMax; posState++) { _lowCoder[posState] = new BitTreeEncoder(Base.kNumLowLenBits); _midCoder[posState] = new BitTreeEncoder(Base.kNumMidLenBits); } } public void Init(UInt32 numPosStates) { _choice.Init(); _choice2.Init(); for (UInt32 posState = 0; posState < numPosStates; posState++) { _lowCoder[posState].Init(); _midCoder[posState].Init(); } _highCoder.Init(); } public void Encode(RangeCoder.Encoder rangeEncoder, UInt32 symbol, UInt32 posState) { if (symbol < Base.kNumLowLenSymbols) { _choice.Encode(rangeEncoder, 0); _lowCoder[posState].Encode(rangeEncoder, symbol); } else { symbol -= Base.kNumLowLenSymbols; _choice.Encode(rangeEncoder, 1); if (symbol < Base.kNumMidLenSymbols) { _choice2.Encode(rangeEncoder, 0); _midCoder[posState].Encode(rangeEncoder, symbol); } else { _choice2.Encode(rangeEncoder, 1); _highCoder.Encode(rangeEncoder, symbol - Base.kNumMidLenSymbols); } } } public void SetPrices(UInt32 posState, UInt32 numSymbols, UInt32[] prices, UInt32 st) { UInt32 a0 = _choice.GetPrice0(); UInt32 a1 = _choice.GetPrice1(); UInt32 b0 = a1 + _choice2.GetPrice0(); UInt32 b1 = a1 + _choice2.GetPrice1(); UInt32 i = 0; for (i = 0; i < Base.kNumLowLenSymbols; i++) { if (i >= numSymbols) return; prices[st + i] = a0 + _lowCoder[posState].GetPrice(i); } for (; i < Base.kNumLowLenSymbols + Base.kNumMidLenSymbols; i++) { if (i >= numSymbols) return; prices[st + i] = b0 + _midCoder[posState].GetPrice(i - Base.kNumLowLenSymbols); } for (; i < numSymbols; i++) prices[st + i] = b1 + _highCoder.GetPrice(i - Base.kNumLowLenSymbols - Base.kNumMidLenSymbols); } }; private class LenPriceTableEncoder : LenEncoder { private readonly UInt32[] _counters = new UInt32[Base.kNumPosStatesEncodingMax]; private readonly UInt32[] _prices = new UInt32[Base.kNumLenSymbols << Base.kNumPosStatesBitsEncodingMax]; private UInt32 _tableSize; public void SetTableSize(UInt32 tableSize) { _tableSize = tableSize; } public UInt32 GetPrice(UInt32 symbol, UInt32 posState) { return _prices[posState * Base.kNumLenSymbols + symbol]; } private void UpdateTable(UInt32 posState) { SetPrices(posState, _tableSize, _prices, posState * Base.kNumLenSymbols); _counters[posState] = _tableSize; } public void UpdateTables(UInt32 numPosStates) { for (UInt32 posState = 0; posState < numPosStates; posState++) UpdateTable(posState); } public new void Encode(RangeCoder.Encoder rangeEncoder, UInt32 symbol, UInt32 posState) { base.Encode(rangeEncoder, symbol, posState); if (--_counters[posState] == 0) UpdateTable(posState); } } private class LiteralEncoder { private Encoder2[] m_Coders; private int m_NumPosBits; private int m_NumPrevBits; private uint m_PosMask; public void Create(int numPosBits, int numPrevBits) { if (m_Coders != null && m_NumPrevBits == numPrevBits && m_NumPosBits == numPosBits) return; m_NumPosBits = numPosBits; m_PosMask = ((uint)1 << numPosBits) - 1; m_NumPrevBits = numPrevBits; uint numStates = (uint)1 << (m_NumPrevBits + m_NumPosBits); m_Coders = new Encoder2[numStates]; for (uint i = 0; i < numStates; i++) m_Coders[i].Create(); } public void Init() { uint numStates = (uint)1 << (m_NumPrevBits + m_NumPosBits); for (uint i = 0; i < numStates; i++) m_Coders[i].Init(); } public Encoder2 GetSubCoder(UInt32 pos, Byte prevByte) { return m_Coders[((pos & m_PosMask) << m_NumPrevBits) + (uint)(prevByte >> (8 - m_NumPrevBits))]; } public struct Encoder2 { private BitEncoder[] m_Encoders; public void Create() { m_Encoders = new BitEncoder[0x300]; } public void Init() { for (int i = 0; i < 0x300; i++) m_Encoders[i].Init(); } public void Encode(RangeCoder.Encoder rangeEncoder, byte symbol) { uint context = 1; for (int i = 7; i >= 0; i--) { var bit = (uint)((symbol >> i) & 1); m_Encoders[context].Encode(rangeEncoder, bit); context = (context << 1) | bit; } } public void EncodeMatched(RangeCoder.Encoder rangeEncoder, byte matchByte, byte symbol) { uint context = 1; bool same = true; for (int i = 7; i >= 0; i--) { var bit = (uint)((symbol >> i) & 1); uint state = context; if (same) { var matchBit = (uint)((matchByte >> i) & 1); state += ((1 + matchBit) << 8); same = (matchBit == bit); } m_Encoders[state].Encode(rangeEncoder, bit); context = (context << 1) | bit; } } public uint GetPrice(bool matchMode, byte matchByte, byte symbol) { uint price = 0; uint context = 1; int i = 7; if (matchMode) { for (; i >= 0; i--) { uint matchBit = (uint)(matchByte >> i) & 1; uint bit = (uint)(symbol >> i) & 1; price += m_Encoders[((1 + matchBit) << 8) + context].GetPrice(bit); context = (context << 1) | bit; if (matchBit != bit) { i--; break; } } } for (; i >= 0; i--) { uint bit = (uint)(symbol >> i) & 1; price += m_Encoders[context].GetPrice(bit); context = (context << 1) | bit; } return price; } } } private class Optimal { public UInt32 BackPrev; public UInt32 BackPrev2; public UInt32 Backs0; public UInt32 Backs1; public UInt32 Backs2; public UInt32 Backs3; public UInt32 PosPrev; public UInt32 PosPrev2; public bool Prev1IsChar; public bool Prev2; public UInt32 Price; public Base.State State; public void MakeAsChar() { BackPrev = 0xFFFFFFFF; Prev1IsChar = false; } public void MakeAsShortRep() { BackPrev = 0; ; Prev1IsChar = false; } public bool IsShortRep() { return (BackPrev == 0); } }; } }
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace SPCrossDomainLibraryDemoWeb { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted app. /// </summary> /// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns> public string GetDatabaseConnectionString() { string dbConnectionString = null; using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost()) { if (clientContext != null) { var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext); clientContext.ExecuteQuery(); dbConnectionString = result.Value; } } if (dbConnectionString == null) { const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging"; var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey]; dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null; } return dbConnectionString; } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey])) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
// // 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.Data; using System.Data.Common; using System.Runtime.InteropServices; namespace IBM.Data.DB2 { public class DB2Command : DbCommand, ICloneable { #region Private data members private WeakReference refDataReader; private string commandText; private CommandType commandType = CommandType.Text; private DB2Connection db2Conn; private DB2Transaction db2Trans; private int commandTimeout = 30; private bool prepared = false; private bool binded = false; private IntPtr hwndStmt = IntPtr.Zero; //Our statement handle private DB2ParameterCollection parameters = new DB2ParameterCollection(); private bool disposed = false; private bool statementOpen; private CommandBehavior previousBehavior; private UpdateRowSource updatedRowSource = UpdateRowSource.Both; private IntPtr statementParametersMemory; private int statementParametersMemorySize; #endregion #region Constructors public DB2Command() { hwndStmt = IntPtr.Zero; } public DB2Command(string commandStr) : this() { commandText = commandStr; } public DB2Command(string commandStr, DB2Connection con) : this() { db2Conn = con; commandText = commandStr; if (con != null) { con.AddCommand(this); } } public DB2Command(string commandStr, DB2Connection con, DB2Transaction trans) { commandText = commandStr; db2Conn = con; db2Trans = trans; if (con != null) { con.AddCommand(this); } } #endregion #region Dispose public new void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected override void Dispose(bool disposing) { if (!disposed) { if (disposing) { ConnectionClosed(); if (db2Conn != null) { db2Conn.RemoveCommand(this); db2Conn = null; } } if (statementParametersMemory != IntPtr.Zero) { Marshal.FreeHGlobal(statementParametersMemory); statementParametersMemory = IntPtr.Zero; } } base.Dispose(disposing); disposed = true; } ~DB2Command() { Dispose(false); } internal void DataReaderClosed() { CloseStatementHandle(false); if ((previousBehavior & CommandBehavior.CloseConnection) != 0) Connection.Close(); refDataReader = null; } private void CloseStatementHandle(bool dispose) { if (hwndStmt != IntPtr.Zero) { if (statementOpen) { short sqlRet = DB2CLIWrapper.SQLFreeStmt(hwndStmt, DB2Constants.SQL_CLOSE); } if ((!prepared && statementOpen) || dispose) { short sqlRet = DB2CLIWrapper.SQLFreeHandle(DB2Constants.SQL_HANDLE_STMT, hwndStmt); hwndStmt = IntPtr.Zero; prepared = false; } statementOpen = false; } } internal void ConnectionClosed() { DB2DataReader reader = null; if ((refDataReader != null) && refDataReader.IsAlive) { reader = (DB2DataReader)refDataReader.Target; } if ((reader != null) && refDataReader.IsAlive) { reader.Dispose(); refDataReader = null; } CloseStatementHandle(true); db2Trans = null; } #endregion #region SelfDescribe property /// /// Property dictates whether or not any paramter markers will get their describe info /// from the database, or if the user will supply the information /// bool selfDescribe = false; public bool SelfDescribe { get { return selfDescribe; } set { selfDescribe = value; } } #endregion #region CommandText property /// ///The query; If it gets set, reset the prepared property /// public override string CommandText { get { return commandText; } set { prepared = false; commandText = value; } } #endregion #region CommandTimeout property /// /// The Timeout property states how long we wait for results to return /// public override int CommandTimeout { get { return commandTimeout; } set { commandTimeout = value; if (hwndStmt != IntPtr.Zero) SetStatementTimeout(); } } #endregion #region CommandType property public override CommandType CommandType { get { return commandType; } set { commandType = value; } } #endregion #region Connection property /// /// The connection we'll be executing on. /// public DB2Connection Connection { get { return db2Conn; } set { if (db2Conn != null) { db2Conn.RemoveCommand(this); } db2Conn = value; if (db2Conn != null) { db2Conn.AddCommand(this); } } } #endregion #region Parameters property /// /// Parameter list, Not yet implemented /// public DB2ParameterCollection Parameters { get { return parameters; } } #endregion #region Transaction property public DB2Transaction Transaction { get { return db2Trans; } set { db2Trans = value; } } #endregion #region UpdatedRowSource property public override UpdateRowSource UpdatedRowSource { get { return updatedRowSource; } set { updatedRowSource = value; } } #endregion #region Statement Handle /// /// returns the DB2Client statement handle /// public IntPtr statementHandle { get { return hwndStmt; } } protected override DbConnection DbConnection { get { return (DbConnection)Connection; } set { Connection = (DB2Connection)value; } } protected override DbParameterCollection DbParameterCollection { get { return parameters; } } protected override DbTransaction DbTransaction { get { return db2Trans; } set { db2Trans = (DB2Transaction)value; } } public override bool DesignTimeVisible { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } #endregion #region AllocateStatement function internal void AllocateStatement(string location) { if (db2Conn.DBHandle.ToInt32() == 0) return; DB2Constants.RetCode sqlRet; sqlRet = (DB2Constants.RetCode)DB2CLIWrapper.SQLAllocHandle(DB2Constants.SQL_HANDLE_STMT, db2Conn.DBHandle, out hwndStmt); if ((sqlRet != DB2Constants.RetCode.SQL_SUCCESS) && (sqlRet != DB2Constants.RetCode.SQL_SUCCESS_WITH_INFO)) throw new DB2Exception(DB2Constants.SQL_HANDLE_DBC, db2Conn.DBHandle, location + ": Unable to allocate statement handle."); parameters.HwndStmt = hwndStmt; SetStatementTimeout(); } private void SetStatementTimeout() { short sqlRet = DB2CLIWrapper.SQLSetStmtAttr(hwndStmt, DB2Constants.SQL_ATTR_QUERY_TIMEOUT, new IntPtr(commandTimeout), 0); DB2ClientUtils.DB2CheckReturn(sqlRet, DB2Constants.SQL_HANDLE_STMT, hwndStmt, "Set statement timeout.", db2Conn); } #endregion #region Cancel /// <summary> /// Attempt to cancel an executing command /// </summary> public override void Cancel() { if (hwndStmt == IntPtr.Zero) { throw new InvalidOperationException("Nothing to Cancel."); } DB2CLIWrapper.SQLCancel(hwndStmt); } #endregion #region CreateParameter /// ///Returns a parameter /// public IDbDataParameter CreateParameter() { return new DB2Parameter(); } #endregion #region ExecuteNonQuery public override int ExecuteNonQuery() { ExecuteNonQueryInternal(CommandBehavior.Default); int numRows; //How many rows affected. numRows will be -1 if we aren't dealing with an Insert, Delete or Update, or if the statement did not execute successfully short sqlRet = DB2CLIWrapper.SQLRowCount(hwndStmt, out numRows); DB2ClientUtils.DB2CheckReturn(sqlRet, DB2Constants.SQL_HANDLE_STMT, hwndStmt, "SQLExecDirect error.", db2Conn); do { sqlRet = DB2CLIWrapper.SQLMoreResults(this.hwndStmt); DB2ClientUtils.DB2CheckReturn(sqlRet, DB2Constants.SQL_HANDLE_STMT, hwndStmt, "DB2ClientDataReader - SQLMoreResults", db2Conn); } while (sqlRet != DB2Constants.SQL_NO_DATA_FOUND); CloseStatementHandle(false); return numRows; } public void ExecuteNonQueryInternal(CommandBehavior behavior) { short sqlRet; if (prepared && binded) { sqlRet = DB2CLIWrapper.SQLExecute(hwndStmt); DB2ClientUtils.DB2CheckReturn(sqlRet, DB2Constants.SQL_HANDLE_STMT, hwndStmt, "SQLExecute error.", db2Conn); return; } if ((db2Conn == null) || (db2Conn.State != ConnectionState.Open)) throw new InvalidOperationException("Prepare needs an open connection"); if ((refDataReader != null) && (refDataReader.IsAlive)) throw new InvalidOperationException("There is already an open DataReader associated with this Connection which must be closed first."); DB2Transaction connectionTransaction = null; if (db2Conn.WeakRefTransaction != null) connectionTransaction = (DB2Transaction)db2Conn.WeakRefTransaction.Target; if (!object.ReferenceEquals(connectionTransaction, Transaction)) { if (Transaction == null) throw new InvalidOperationException("A transaction was started in the connection, but the command doesn't specify a transaction"); throw new InvalidOperationException("The transaction specified at the connection doesn't belong to the connection"); } if (hwndStmt == IntPtr.Zero) { AllocateStatement("InternalExecuteNonQuery"); previousBehavior = 0; } if (previousBehavior != behavior) { if (((previousBehavior ^ behavior) & CommandBehavior.SchemaOnly) != 0) { sqlRet = DB2CLIWrapper.SQLSetStmtAttr(hwndStmt, DB2Constants.SQL_ATTR_DEFERRED_PREPARE, new IntPtr((behavior & CommandBehavior.SchemaOnly) != 0 ? 0 : 1), 0); // TODO: don't check. what if it is not supported??? DB2ClientUtils.DB2CheckReturn(sqlRet, DB2Constants.SQL_HANDLE_STMT, hwndStmt, "Defered prepare.", db2Conn); previousBehavior = (previousBehavior & ~CommandBehavior.SchemaOnly) | (behavior & CommandBehavior.SchemaOnly); } if (((previousBehavior ^ behavior) & CommandBehavior.SingleRow) != 0) { sqlRet = DB2CLIWrapper.SQLSetStmtAttr(hwndStmt, DB2Constants.SQL_ATTR_MAX_ROWS, new IntPtr((behavior & CommandBehavior.SingleRow) == 0 ? 0 : 1), 0); // TODO: don't check. what if it is not supported??? DB2ClientUtils.DB2CheckReturn(sqlRet, DB2Constants.SQL_HANDLE_STMT, hwndStmt, "Set max rows", db2Conn); previousBehavior = (previousBehavior & ~CommandBehavior.SingleRow) | (behavior & CommandBehavior.SingleRow); } previousBehavior = behavior; } //sqlRet = DB2CLIWrapper.SQLSetStmtAttr(hwndStmt, DB2Constants.SQL_ATTR_MAX_ROWS, new IntPtr(100), 0); //DB2ClientUtils.DB2CheckReturn(sqlRet, DB2Constants.SQL_HANDLE_STMT, hwndStmt, "Set max rows", db2Conn); //AutoCommit if ((Transaction == null) && !db2Conn.AutoCommit) { sqlRet = DB2CLIWrapper.SQLSetConnectAttr(db2Conn.DBHandle, DB2Constants.SQL_ATTR_AUTOCOMMIT, new IntPtr(DB2Constants.SQL_AUTOCOMMIT_ON), 0); DB2ClientUtils.DB2CheckReturn(sqlRet, DB2Constants.SQL_HANDLE_DBC, db2Conn.DBHandle, "Error setting AUTOCOMMIT ON in transaction CTOR.", db2Conn); db2Conn.AutoCommit = true; sqlRet = DB2CLIWrapper.SQLSetConnectAttr(db2Conn.DBHandle, DB2Constants.SQL_ATTR_TXN_ISOLATION, new IntPtr(DB2Constants.SQL_TXN_READ_COMMITTED), 0); DB2ClientUtils.DB2CheckReturn(sqlRet, DB2Constants.SQL_HANDLE_DBC, db2Conn.DBHandle, "Error setting isolation level.", db2Conn); } if ((commandText == null) || (commandText.Length == 0)) throw new InvalidOperationException("Command string is empty"); if (commandText.Contains("@")) throw new ArgumentException("Named Parameters are not supported"); if (CommandType.StoredProcedure == commandType && !commandText.StartsWith("CALL ")) commandText = "CALL " + commandText + " ()"; if ((behavior & CommandBehavior.SchemaOnly) != 0) { if (!prepared) { Prepare(); } } else { if (statementParametersMemory != IntPtr.Zero) { Marshal.FreeHGlobal(statementParametersMemory); statementParametersMemory = IntPtr.Zero; } Prepare(); BindParams(); if (prepared) { sqlRet = DB2CLIWrapper.SQLExecute(hwndStmt); DB2ClientUtils.DB2CheckReturn(sqlRet, DB2Constants.SQL_HANDLE_STMT, hwndStmt, "SQLExecute error.", db2Conn); } else { sqlRet = DB2CLIWrapper.SQLExecDirect(hwndStmt, commandText, commandText.Length); DB2ClientUtils.DB2CheckReturn(sqlRet, DB2Constants.SQL_HANDLE_STMT, hwndStmt, "SQLExecDirect error.", db2Conn); } statementOpen = true; parameters.GetOutValues(); if (statementParametersMemory != IntPtr.Zero) { Marshal.FreeHGlobal(statementParametersMemory); statementParametersMemory = IntPtr.Zero; } } } #endregion #region ExecuteReader calls /// ///ExecuteReader /// public DB2DataReader ExecuteReader() { return ExecuteReader(CommandBehavior.Default); } public DB2DataReader ExecuteReader(CommandBehavior behavior) { if ((db2Conn == null) || (db2Conn.State != ConnectionState.Open)) throw new InvalidOperationException("Prepare needs an open connection"); DB2DataReader reader; ExecuteNonQueryInternal(behavior); reader = new DB2DataReader(db2Conn, this, behavior); refDataReader = new WeakReference(reader); return reader; } #endregion #region ExecuteScalar /// /// ExecuteScalar /// public override object ExecuteScalar() { if ((db2Conn == null) || (db2Conn.State != ConnectionState.Open)) throw new InvalidOperationException("Prepare needs an open connection"); using (DB2DataReader reader = ExecuteReader(CommandBehavior.SingleResult | CommandBehavior.SingleRow)) { if (reader.Read() && (reader.FieldCount > 0)) { return reader[0]; } } return null; } #endregion #region Prepare() public override void Prepare() { if ((db2Conn == null) || (db2Conn.State != ConnectionState.Open)) throw new InvalidOperationException("Prepare needs an open connection"); CloseStatementHandle(false); if (hwndStmt == IntPtr.Zero) { AllocateStatement("InternalExecuteNonQuery"); } short sqlRet = 0; IntPtr numParams = IntPtr.Zero; sqlRet = DB2CLIWrapper.SQLPrepare(hwndStmt, commandText, commandText.Length); DB2ClientUtils.DB2CheckReturn(sqlRet, DB2Constants.SQL_HANDLE_STMT, hwndStmt, "SQLPrepare error.", db2Conn); statementOpen = true; prepared = true; } #endregion private string AddCallParam(string _cmString) { if (_cmString.IndexOf("()") != -1) { return _cmString.Replace("()", "(?)"); } return _cmString.Replace(")", ",?)"); } private void BindParams() { if (parameters.Count > 0) { statementParametersMemorySize = 0; int offset = 0; short sqlRet; for (int i = 0; i < parameters.Count; i++) { if (commandType == CommandType.StoredProcedure) { commandText = AddCallParam(commandText); } DB2Parameter param = parameters[i]; param.CalculateRequiredmemory(); statementParametersMemorySize += param.requiredMemory + 8; param.internalBuffer = Marshal.AllocHGlobal(param.requiredMemory); offset += param.requiredMemory; param.internalLengthBuffer = Marshal.AllocHGlobal(4); Marshal.WriteInt32(param.internalLengthBuffer, param.requiredMemory); sqlRet = param.Bind(this.hwndStmt, (short)(i + 1)); DB2ClientUtils.DB2CheckReturn(sqlRet, DB2Constants.SQL_HANDLE_STMT, hwndStmt, "Error binding parameter in DB2Command: ", db2Conn); } binded = true; } } #region ICloneable Members object ICloneable.Clone() { DB2Command clone = new DB2Command(); clone.Connection = Connection; clone.commandText = commandText; clone.commandType = commandType; clone.Transaction = db2Trans; clone.commandTimeout = commandTimeout; clone.updatedRowSource = updatedRowSource; clone.parameters = new DB2ParameterCollection(); for (int i = 0; i < parameters.Count; i++) clone.Parameters.Add(((ICloneable)parameters[i]).Clone()); return clone; } protected override DbParameter CreateDbParameter() { return (DbParameter)CreateParameter(); } protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior) { return (DbDataReader)ExecuteReader(behavior); } #endregion } }
// 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.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Net.Sockets.Tests { public partial class UnixDomainSocketTest { [Fact] [PlatformSpecific(TestPlatforms.Windows)] // new UnixDomainSocketEndPoint should throw on Windows public void UnixDomainSocketEndPoint_Throws_OnWindows() { Assert.Throws<PlatformNotSupportedException>(() => new UnixDomainSocketEndPoint("/path")); } [OuterLoop] // TODO: Issue #11345 [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Tests ConnectAsyncUnixDomainSocketEndPoint success on Unix public async Task Socket_ConnectAsyncUnixDomainSocketEndPoint_Success() { string path = null; SocketTestServer server = null; UnixDomainSocketEndPoint endPoint = null; for (int attempt = 0; attempt < 5; attempt++) { path = GetRandomNonExistingFilePath(); endPoint = new UnixDomainSocketEndPoint(path); try { server = SocketTestServer.SocketTestServerFactory(SocketImplementationType.Async, endPoint, ProtocolType.Unspecified); break; } catch (SocketException) { //Path selection is contingent on a successful Bind(). //If it fails, the next iteration will try another path. } } try { Assert.NotNull(server); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = endPoint; args.Completed += (s, e) => ((TaskCompletionSource<bool>)e.UserToken).SetResult(true); var complete = new TaskCompletionSource<bool>(); args.UserToken = complete; using (Socket sock = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified)) { bool willRaiseEvent = sock.ConnectAsync(args); if (willRaiseEvent) { await complete.Task; } Assert.Equal(SocketError.Success, args.SocketError); Assert.Null(args.ConnectByNameError); } } finally { server.Dispose(); try { File.Delete(path); } catch { } } } [OuterLoop] // TODO: Issue #11345 [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Tests ConnectAsyncUnixDomainSocketEndPoint seccess on Unix public async Task Socket_ConnectAsyncUnixDomainSocketEndPoint_NotServer() { string path = GetRandomNonExistingFilePath(); var endPoint = new UnixDomainSocketEndPoint(path); try { SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = endPoint; args.Completed += (s, e) => ((TaskCompletionSource<bool>)e.UserToken).SetResult(true); var complete = new TaskCompletionSource<bool>(); args.UserToken = complete; using (Socket sock = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified)) { bool willRaiseEvent = sock.ConnectAsync(args); if (willRaiseEvent) { await complete.Task; } Assert.Equal(SocketError.AddressNotAvailable, args.SocketError); } } finally { try { File.Delete(path); } catch { } } } [OuterLoop] // TODO: Issue #11345 [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Tests SendReceive success for UnixDomainSocketEndPoint on Unix public void Socket_SendReceive_Success() { string path = GetRandomNonExistingFilePath(); var endPoint = new UnixDomainSocketEndPoint(path); try { using (var server = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified)) using (var client = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified)) { server.Bind(endPoint); server.Listen(1); client.Connect(endPoint); using (Socket accepted = server.Accept()) { var data = new byte[1]; for (int i = 0; i < 10; i++) { data[0] = (byte)i; accepted.Send(data); data[0] = 0; Assert.Equal(1, client.Receive(data)); Assert.Equal(i, data[0]); } } } } finally { try { File.Delete(path); } catch { } } } [OuterLoop] // TODO: Issue #11345 [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Tests SendReceiveAsync success for UnixDomainSocketEndPoint on Unix public async Task Socket_SendReceiveAsync_Success() { string path = GetRandomNonExistingFilePath(); var endPoint = new UnixDomainSocketEndPoint(path); try { using (var server = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified)) using (var client = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified)) { server.Bind(endPoint); server.Listen(1); await client.ConnectAsync(endPoint); using (Socket accepted = await server.AcceptAsync()) { var data = new byte[1]; for (int i = 0; i < 10; i++) { data[0] = (byte)i; await accepted.SendAsync(new ArraySegment<byte>(data), SocketFlags.None); data[0] = 0; Assert.Equal(1, await client.ReceiveAsync(new ArraySegment<byte>(data), SocketFlags.None)); Assert.Equal(i, data[0]); } } } } finally { try { File.Delete(path); } catch { } } } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(5000, 1, 1)] [InlineData(500, 18, 21)] [InlineData(500, 21, 18)] [InlineData(5, 128000, 64000)] [PlatformSpecific(TestPlatforms.AnyUnix)] // Tests SendReceiveAsync success for UnixDomainSocketEndPoint on Unix public async Task Socket_SendReceiveAsync_PropagateToStream_Success(int iterations, int writeBufferSize, int readBufferSize) { var writeBuffer = new byte[writeBufferSize * iterations]; new Random().NextBytes(writeBuffer); var readData = new MemoryStream(); string path = GetRandomNonExistingFilePath(); var endPoint = new UnixDomainSocketEndPoint(path); try { using (var server = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified)) using (var client = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified)) { server.Bind(endPoint); server.Listen(1); Task<Socket> serverAccept = server.AcceptAsync(); await Task.WhenAll(serverAccept, client.ConnectAsync(endPoint)); Task clientReceives = Task.Run(async () => { int bytesRead; byte[] buffer = new byte[readBufferSize]; while ((bytesRead = await client.ReceiveAsync(new ArraySegment<byte>(buffer), SocketFlags.None)) > 0) { readData.Write(buffer, 0, bytesRead); } }); using (Socket accepted = await serverAccept) { for (int iter = 0; iter < iterations; iter++) { Task<int> sendTask = accepted.SendAsync(new ArraySegment<byte>(writeBuffer, iter * writeBufferSize, writeBufferSize), SocketFlags.None); await await Task.WhenAny(clientReceives, sendTask); Assert.Equal(writeBufferSize, await sendTask); } } await clientReceives; } Assert.Equal(writeBuffer.Length, readData.Length); Assert.Equal(writeBuffer, readData.ToArray()); } finally { try { File.Delete(path); } catch { } } } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(false)] [InlineData(true)] [PlatformSpecific(TestPlatforms.AnyUnix)] // Tests ConcurrentSendReceive success for UnixDomainSocketEndPoint on Unix public async Task ConcurrentSendReceive(bool forceNonBlocking) { using (Socket server = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified)) using (Socket client = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified)) { const int Iters = 25; byte[] sendData = new byte[Iters]; byte[] receiveData = new byte[sendData.Length]; new Random().NextBytes(sendData); string path = GetRandomNonExistingFilePath(); server.Bind(new UnixDomainSocketEndPoint(path)); server.Listen(1); Task<Socket> acceptTask = server.AcceptAsync(); client.Connect(new UnixDomainSocketEndPoint(path)); await acceptTask; Socket accepted = acceptTask.Result; client.ForceNonBlocking(forceNonBlocking); accepted.ForceNonBlocking(forceNonBlocking); Task[] writes = new Task[Iters]; Task<int>[] reads = new Task<int>[Iters]; for (int i = 0; i < Iters; i++) { reads[i] = Task.Factory.StartNew(s => accepted.Receive(receiveData, (int)s, 1, SocketFlags.None), i, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); } for (int i = 0; i < Iters; i++) { writes[i] = Task.Factory.StartNew(s => client.Send(sendData, (int)s, 1, SocketFlags.None), i, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); } await TestSettings.WhenAllOrAnyFailedWithTimeout(writes.Concat(reads).ToArray()); Assert.Equal(sendData.OrderBy(i => i), receiveData.OrderBy(i => i)); } } [OuterLoop] // TODO: Issue #11345 [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Tests ConcurrentSendReceive success for UnixDomainSocketEndPoint on Unix public async Task ConcurrentSendReceiveAsync() { using (Socket server = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified)) using (Socket client = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified)) { const int Iters = 2048; byte[] sendData = new byte[Iters]; byte[] receiveData = new byte[sendData.Length]; new Random().NextBytes(sendData); string path = GetRandomNonExistingFilePath(); server.Bind(new UnixDomainSocketEndPoint(path)); server.Listen(1); Task<Socket> acceptTask = server.AcceptAsync(); client.Connect(new UnixDomainSocketEndPoint(path)); await acceptTask; Socket accepted = acceptTask.Result; Task[] writes = new Task[Iters]; Task<int>[] reads = new Task<int>[Iters]; for (int i = 0; i < Iters; i++) { writes[i] = client.SendAsync(new ArraySegment<byte>(sendData, i, 1), SocketFlags.None); } for (int i = 0; i < Iters; i++) { reads[i] = accepted.ReceiveAsync(new ArraySegment<byte>(receiveData, i, 1), SocketFlags.None); } await TestSettings.WhenAllOrAnyFailedWithTimeout(writes.Concat(reads).ToArray()); Assert.Equal(sendData, receiveData); } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Tests new UnixDomainSocketEndPoint throws the correct exception for invalid args public void UnixDomainSocketEndPoint_InvalidPaths_Throws() { Assert.Throws<ArgumentNullException>(() => new UnixDomainSocketEndPoint(null)); Assert.Throws<ArgumentOutOfRangeException>(() => new UnixDomainSocketEndPoint(string.Empty)); int maxNativeSize = (int)typeof(UnixDomainSocketEndPoint) .GetField("s_nativePathLength", BindingFlags.Static | BindingFlags.NonPublic) .GetValue(null); string invalidLengthString = new string('a', maxNativeSize + 1); Assert.Throws<ArgumentOutOfRangeException>(() => new UnixDomainSocketEndPoint(invalidLengthString)); } [Theory] [PlatformSpecific(TestPlatforms.AnyUnix)] [InlineData(false)] [InlineData(true)] public void UnixDomainSocketEndPoint_RemoteEndPointEqualsBindAddress(bool abstractAddress) { string serverAddress; string clientAddress; string expectedClientAddress; if (abstractAddress) { // abstract socket addresses are a Linux feature. if (!RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { return; } // An abstract socket address starts with a zero byte. serverAddress = '\0' + Guid.NewGuid().ToString(); clientAddress = '\0' + Guid.NewGuid().ToString(); expectedClientAddress = '@' + clientAddress.Substring(1); } else { serverAddress = GetRandomNonExistingFilePath(); clientAddress = GetRandomNonExistingFilePath(); expectedClientAddress = clientAddress; } try { using (Socket server = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified)) { server.Bind(new UnixDomainSocketEndPoint(serverAddress)); server.Listen(1); using (Socket client = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified)) { // Bind the client. client.Bind(new UnixDomainSocketEndPoint(clientAddress)); client.Connect(new UnixDomainSocketEndPoint(serverAddress)); using (Socket acceptedClient = server.Accept()) { // Verify the client address on the server. EndPoint clientAddressOnServer = acceptedClient.RemoteEndPoint; Assert.True(string.CompareOrdinal(expectedClientAddress, clientAddressOnServer.ToString()) == 0); } } } } finally { if (!abstractAddress) { try { File.Delete(serverAddress); } catch { } try { File.Delete(clientAddress); } catch { } } } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix & ~TestPlatforms.Linux)] // Don't support abstract socket addresses. public void UnixDomainSocketEndPoint_UsingAbstractSocketAddressOnUnsupported_Throws() { // An abstract socket address starts with a zero byte. string address = '\0' + Guid.NewGuid().ToString(); // Bind using (Socket socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified)) { Assert.ThrowsAny<SocketException>(() => socket.Bind(new UnixDomainSocketEndPoint(address))); } // Connect using (Socket socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified)) { Assert.ThrowsAny<SocketException>(() => socket.Connect(new UnixDomainSocketEndPoint(address))); } } private static string GetRandomNonExistingFilePath() { string result; do { result = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); } while (File.Exists(result)); return result; } } }
// 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. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsUrlMultiCollectionFormat { using Microsoft.Rest; using Models; /// <summary> /// Queries operations. /// </summary> public partial class Queries : Microsoft.Rest.IServiceOperations<AutoRestUrlMutliCollectionFormatTestService>, IQueries { /// <summary> /// Initializes a new instance of the Queries class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public Queries(AutoRestUrlMutliCollectionFormatTestService client) { if (client == null) { throw new System.ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the AutoRestUrlMutliCollectionFormatTestService /// </summary> public AutoRestUrlMutliCollectionFormatTestService Client { get; private set; } /// <summary> /// Get a null array of string using the multi-array format /// </summary> /// <param name='arrayQuery'> /// a null array of string using the multi-array format /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> ArrayStringMultiNullWithHttpMessagesAsync(System.Collections.Generic.IList<string> arrayQuery = default(System.Collections.Generic.IList<string>), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("arrayQuery", arrayQuery); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ArrayStringMultiNull", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "queries/array/multi/string/null").ToString(); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (arrayQuery != null) { if (arrayQuery.Count == 0) { _queryParameters.Add(string.Format("arrayQuery={0}", System.Uri.EscapeDataString(string.Empty))); } else { foreach (var _item in arrayQuery) { _queryParameters.Add(string.Format("arrayQuery={0}", System.Uri.EscapeDataString(_item ?? string.Empty))); } } } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.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 = null; // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get an empty array [] of string using the multi-array format /// </summary> /// <param name='arrayQuery'> /// an empty array [] of string using the multi-array format /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> ArrayStringMultiEmptyWithHttpMessagesAsync(System.Collections.Generic.IList<string> arrayQuery = default(System.Collections.Generic.IList<string>), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("arrayQuery", arrayQuery); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ArrayStringMultiEmpty", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "queries/array/multi/string/empty").ToString(); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (arrayQuery != null) { if (arrayQuery.Count == 0) { _queryParameters.Add(string.Format("arrayQuery={0}", System.Uri.EscapeDataString(string.Empty))); } else { foreach (var _item in arrayQuery) { _queryParameters.Add(string.Format("arrayQuery={0}", System.Uri.EscapeDataString(_item ?? string.Empty))); } } } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.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 = null; // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get an array of string ['ArrayQuery1', 'begin!*'();:@ &amp;=+$,/?#[]end' , /// null, ''] using the mult-array format /// </summary> /// <param name='arrayQuery'> /// an array of string ['ArrayQuery1', 'begin!*'();:@ &amp;=+$,/?#[]end' , /// null, ''] using the mult-array format /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> ArrayStringMultiValidWithHttpMessagesAsync(System.Collections.Generic.IList<string> arrayQuery = default(System.Collections.Generic.IList<string>), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("arrayQuery", arrayQuery); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ArrayStringMultiValid", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "queries/array/multi/string/valid").ToString(); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (arrayQuery != null) { if (arrayQuery.Count == 0) { _queryParameters.Add(string.Format("arrayQuery={0}", System.Uri.EscapeDataString(string.Empty))); } else { foreach (var _item in arrayQuery) { _queryParameters.Add(string.Format("arrayQuery={0}", System.Uri.EscapeDataString(_item ?? string.Empty))); } } } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.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 = null; // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
namespace XenAdmin.TabPages { partial class PhysicalStoragePage { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { Host = null; Connection = null; if (disposing) { if (selectionManager != null) selectionManager.Dispose(); 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.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PhysicalStoragePage)); this.contextMenuStrip = new System.Windows.Forms.ContextMenuStrip(this.components); this.labelNetworkheadings = new System.Windows.Forms.Label(); this.TitleLabel = new System.Windows.Forms.Label(); this.columnVirtAlloc = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.columnSize = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.columnUsage = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.columnShared = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.columnType = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.columnDescription = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.columnName = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.columnImage = new System.Windows.Forms.DataGridViewImageColumn(); this.dataGridViewSr = new XenAdmin.Controls.DataGridViewEx.DataGridViewEx(); this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel(); this.newSRButton = new XenAdmin.Commands.CommandButton(); this.trimButtonContainer = new XenAdmin.Controls.ToolTipContainer(); this.trimButton = new XenAdmin.Commands.CommandButton(); this.buttonProperties = new System.Windows.Forms.Button(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.pageContainerPanel.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridViewSr)).BeginInit(); this.flowLayoutPanel1.SuspendLayout(); this.trimButtonContainer.SuspendLayout(); this.tableLayoutPanel1.SuspendLayout(); this.SuspendLayout(); // // pageContainerPanel // this.pageContainerPanel.Controls.Add(this.tableLayoutPanel1); resources.ApplyResources(this.pageContainerPanel, "pageContainerPanel"); // // contextMenuStrip // this.contextMenuStrip.Name = "contextMenuStrip"; resources.ApplyResources(this.contextMenuStrip, "contextMenuStrip"); this.contextMenuStrip.Opening += new System.ComponentModel.CancelEventHandler(this.contextMenuStrip_Opening); // // labelNetworkheadings // resources.ApplyResources(this.labelNetworkheadings, "labelNetworkheadings"); this.labelNetworkheadings.Name = "labelNetworkheadings"; // // TitleLabel // resources.ApplyResources(this.TitleLabel, "TitleLabel"); this.TitleLabel.ForeColor = System.Drawing.Color.White; this.TitleLabel.Name = "TitleLabel"; // // columnVirtAlloc // this.columnVirtAlloc.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; resources.ApplyResources(this.columnVirtAlloc, "columnVirtAlloc"); this.columnVirtAlloc.Name = "columnVirtAlloc"; // // columnSize // this.columnSize.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; resources.ApplyResources(this.columnSize, "columnSize"); this.columnSize.Name = "columnSize"; // // columnUsage // this.columnUsage.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; resources.ApplyResources(this.columnUsage, "columnUsage"); this.columnUsage.Name = "columnUsage"; // // columnShared // this.columnShared.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; resources.ApplyResources(this.columnShared, "columnShared"); this.columnShared.Name = "columnShared"; // // columnType // this.columnType.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; resources.ApplyResources(this.columnType, "columnType"); this.columnType.Name = "columnType"; // // columnDescription // this.columnDescription.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; resources.ApplyResources(this.columnDescription, "columnDescription"); this.columnDescription.Name = "columnDescription"; // // columnName // this.columnName.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; resources.ApplyResources(this.columnName, "columnName"); this.columnName.Name = "columnName"; // // columnImage // this.columnImage.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; resources.ApplyResources(this.columnImage, "columnImage"); this.columnImage.Name = "columnImage"; this.columnImage.Resizable = System.Windows.Forms.DataGridViewTriState.False; // // dataGridViewSr // resources.ApplyResources(this.dataGridViewSr, "dataGridViewSr"); this.dataGridViewSr.BackgroundColor = System.Drawing.SystemColors.Window; this.dataGridViewSr.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None; this.dataGridViewSr.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing; this.dataGridViewSr.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.columnImage, this.columnName, this.columnDescription, this.columnType, this.columnShared, this.columnUsage, this.columnSize, this.columnVirtAlloc}); this.dataGridViewSr.MultiSelect = true; this.dataGridViewSr.Name = "dataGridViewSr"; this.dataGridViewSr.SelectionChanged += new System.EventHandler(this.dataGridViewSrs_SelectedIndexChanged); this.dataGridViewSr.SortCompare += new System.Windows.Forms.DataGridViewSortCompareEventHandler(this.dataGridViewSr_SortCompare); this.dataGridViewSr.MouseUp += new System.Windows.Forms.MouseEventHandler(this.dataGridViewSr_MouseUp); // // flowLayoutPanel1 // this.flowLayoutPanel1.Controls.Add(this.newSRButton); this.flowLayoutPanel1.Controls.Add(this.trimButtonContainer); this.flowLayoutPanel1.Controls.Add(this.buttonProperties); resources.ApplyResources(this.flowLayoutPanel1, "flowLayoutPanel1"); this.flowLayoutPanel1.Name = "flowLayoutPanel1"; // // newSRButton // this.newSRButton.Command = new XenAdmin.Commands.NewSRCommand(); resources.ApplyResources(this.newSRButton, "newSRButton"); this.newSRButton.Name = "newSRButton"; this.newSRButton.UseVisualStyleBackColor = true; // // trimButtonContainer // this.trimButtonContainer.Controls.Add(this.trimButton); resources.ApplyResources(this.trimButtonContainer, "trimButtonContainer"); this.trimButtonContainer.Name = "trimButtonContainer"; // // trimButton // this.trimButton.Command = new XenAdmin.Commands.TrimSRCommand(); resources.ApplyResources(this.trimButton, "trimButton"); this.trimButton.Name = "trimButton"; this.trimButton.UseVisualStyleBackColor = true; // // buttonProperties // resources.ApplyResources(this.buttonProperties, "buttonProperties"); this.buttonProperties.Name = "buttonProperties"; this.buttonProperties.UseVisualStyleBackColor = true; this.buttonProperties.Click += new System.EventHandler(this.buttonProperties_Click); // // tableLayoutPanel1 // resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1"); this.tableLayoutPanel1.Controls.Add(this.labelNetworkheadings, 0, 0); this.tableLayoutPanel1.Controls.Add(this.flowLayoutPanel1, 0, 2); this.tableLayoutPanel1.Controls.Add(this.dataGridViewSr, 0, 1); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; // // PhysicalStoragePage // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.BackColor = System.Drawing.Color.Transparent; this.DoubleBuffered = true; this.Name = "PhysicalStoragePage"; this.Controls.SetChildIndex(this.pageContainerPanel, 0); this.pageContainerPanel.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.dataGridViewSr)).EndInit(); this.flowLayoutPanel1.ResumeLayout(false); this.trimButtonContainer.ResumeLayout(false); this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.ContextMenuStrip contextMenuStrip; private System.Windows.Forms.Label TitleLabel; private System.Windows.Forms.Label labelNetworkheadings; private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1; private Commands.CommandButton newSRButton; private Commands.CommandButton trimButton; private Controls.ToolTipContainer trimButtonContainer; private Controls.DataGridViewEx.DataGridViewEx dataGridViewSr; private System.Windows.Forms.Button buttonProperties; private System.Windows.Forms.DataGridViewImageColumn columnImage; private System.Windows.Forms.DataGridViewTextBoxColumn columnName; private System.Windows.Forms.DataGridViewTextBoxColumn columnDescription; private System.Windows.Forms.DataGridViewTextBoxColumn columnType; private System.Windows.Forms.DataGridViewTextBoxColumn columnShared; private System.Windows.Forms.DataGridViewTextBoxColumn columnUsage; private System.Windows.Forms.DataGridViewTextBoxColumn columnSize; private System.Windows.Forms.DataGridViewTextBoxColumn columnVirtAlloc; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; } }
// 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.Generic; using System.Diagnostics; using System.Security.Permissions; namespace System.DirectoryServices.AccountManagement { [DirectoryRdnPrefix("CN")] public class GroupPrincipal : Principal { // // Public constructors // public GroupPrincipal(PrincipalContext context) { if (context == null) throw new ArgumentException(SR.NullArguments); this.ContextRaw = context; this.unpersisted = true; } public GroupPrincipal(PrincipalContext context, string samAccountName) : this(context) { if (samAccountName == null) throw new ArgumentException(SR.NullArguments); if (Context.ContextType != ContextType.ApplicationDirectory) this.SamAccountName = samAccountName; this.Name = samAccountName; } // // Public properties // // IsSecurityGroup property private bool _isSecurityGroup = false; // the actual property value private LoadState _isSecurityGroupChanged = LoadState.NotSet; // change-tracking public Nullable<bool> IsSecurityGroup { get { // Make sure we're not disposed or deleted. Although HandleGet/HandleSet will check this, // we need to check these before we do anything else. CheckDisposedOrDeleted(); // Different stores have different defaults as to the Enabled setting // (AD: creates disabled by default; SAM: creates enabled by default). // So if the principal is unpersisted (and thus we may not know what store it's // going to end up in), we'll just return null unless they previously // set an explicit value. if (this.unpersisted && (_isSecurityGroupChanged != LoadState.Changed)) { GlobalDebug.WriteLineIf( GlobalDebug.Info, "Group", "Enabled: returning null, unpersisted={0}, enabledChanged={1}", this.unpersisted, _isSecurityGroupChanged); return null; } return HandleGet<bool>(ref _isSecurityGroup, PropertyNames.GroupIsSecurityGroup, ref _isSecurityGroupChanged); } set { // Make sure we're not disposed or deleted. Although HandleGet/HandleSet will check this, // we need to check these before we do anything else. CheckDisposedOrDeleted(); // We don't want to let them set a null value. if (!value.HasValue) throw new ArgumentNullException(nameof(value)); HandleSet<bool>(ref _isSecurityGroup, value.Value, ref _isSecurityGroupChanged, PropertyNames.GroupIsSecurityGroup); } } // GroupScope property private GroupScope _groupScope = System.DirectoryServices.AccountManagement.GroupScope.Local; // the actual property value private LoadState _groupScopeChanged = LoadState.NotSet; // change-tracking public Nullable<GroupScope> GroupScope { get { // Make sure we're not disposed or deleted. Although HandleGet/HandleSet will check this, // we need to check these before we do anything else. CheckDisposedOrDeleted(); // Different stores have different defaults for the GroupScope setting // (AD: Global; SAM: Local). // So if the principal is unpersisted (and thus we may not know what store it's // going to end up in), we'll just return null unless they previously // set an explicit value. if (this.unpersisted && (_groupScopeChanged != LoadState.Changed)) { GlobalDebug.WriteLineIf( GlobalDebug.Info, "Group", "GroupScope: returning null, unpersisted={0}, groupScopeChanged={1}", this.unpersisted, _groupScopeChanged); return null; } return HandleGet<GroupScope>(ref _groupScope, PropertyNames.GroupGroupScope, ref _groupScopeChanged); } set { // Make sure we're not disposed or deleted. Although HandleGet/HandleSet will check this, // we need to check these before we do anything else. CheckDisposedOrDeleted(); // We don't want to let them set a null value. if (!value.HasValue) throw new ArgumentNullException(nameof(value)); HandleSet<GroupScope>(ref _groupScope, value.Value, ref _groupScopeChanged, PropertyNames.GroupGroupScope); } } // Members property private PrincipalCollection _members = null; public PrincipalCollection Members { get { // We don't use HandleGet<T> here because we have to load in the PrincipalCollection // using a special procedure. It's not loaded as part of the regular LoadIfNeeded call. // Make sure we're not disposed or deleted. CheckDisposedOrDeleted(); // Check that we actually support this propery in our store //CheckSupportedProperty(PropertyNames.GroupMembers); if (_members == null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "Group", "Members: creating fresh PrincipalCollection"); if (!this.unpersisted) { // Retrieve the members from the store. // QueryCtx because when this group was retrieved, it was // assigned a _specific_ context for its store GlobalDebug.WriteLineIf(GlobalDebug.Info, "Group", "Members: persisted, querying group membership"); BookmarkableResultSet refs = ContextRaw.QueryCtx.GetGroupMembership(this, false); _members = new PrincipalCollection(refs, this); } else { // unpersisted means there's no values to retrieve from the store GlobalDebug.WriteLineIf(GlobalDebug.Info, "Group", "Members: unpersisted, creating empty PrincipalCollection"); _members = new PrincipalCollection(new EmptySet(), this); } } return _members; } } // // Public methods // public static new GroupPrincipal FindByIdentity(PrincipalContext context, string identityValue) { return (GroupPrincipal)FindByIdentityWithType(context, typeof(GroupPrincipal), identityValue); } public static new GroupPrincipal FindByIdentity(PrincipalContext context, IdentityType identityType, string identityValue) { return (GroupPrincipal)FindByIdentityWithType(context, typeof(GroupPrincipal), identityType, identityValue); } public PrincipalSearchResult<Principal> GetMembers() { return GetMembers(false); } public PrincipalSearchResult<Principal> GetMembers(bool recursive) { // Make sure we're not disposed or deleted. CheckDisposedOrDeleted(); if (!this.unpersisted) { // Retrieve the members from the store. // QueryCtx because when this group was retrieved, it was // assigned a _specific_ context for its store GlobalDebug.WriteLineIf(GlobalDebug.Info, "Group", "GetMembers: persisted, querying for members (recursive={0}", recursive); return new PrincipalSearchResult<Principal>(ContextRaw.QueryCtx.GetGroupMembership(this, recursive)); } else { // unpersisted means there's no values to retrieve from the store GlobalDebug.WriteLineIf(GlobalDebug.Info, "Group", "GetMembers: unpersisted, creating empty PrincipalSearchResult"); return new PrincipalSearchResult<Principal>(null); } } private bool _disposed = false; public override void Dispose() { try { if (!_disposed) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "Group", "Dispose: disposing"); if (_members != null) _members.Dispose(); _disposed = true; GC.SuppressFinalize(this); } } finally { base.Dispose(); } } // // Internal "constructor": Used for constructing Groups returned by a query // static internal GroupPrincipal MakeGroup(PrincipalContext ctx) { GroupPrincipal g = new GroupPrincipal(ctx); g.unpersisted = false; return g; } // // Load/Store implementation // // // Loading with query results // internal override void LoadValueIntoProperty(string propertyName, object value) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "Group", "LoadValueIntoProperty: name=" + propertyName + " value=" + (value != null ? value.ToString() : "null")); switch (propertyName) { case PropertyNames.GroupIsSecurityGroup: _isSecurityGroup = (bool)value; _isSecurityGroupChanged = LoadState.Loaded; break; case PropertyNames.GroupGroupScope: _groupScope = (GroupScope)value; _groupScopeChanged = LoadState.Loaded; break; case PropertyNames.GroupMembers: Debug.Fail("Group.LoadValueIntoProperty: Trying to load Members, but Members is demand-loaded."); break; default: base.LoadValueIntoProperty(propertyName, value); break; } } // // Getting changes to persist (or to build a query from a QBE filter) // // Given a property name, returns true if that property has changed since it was loaded, false otherwise. internal override bool GetChangeStatusForProperty(string propertyName) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "Group", "GetChangeStatusForProperty: name=" + propertyName); switch (propertyName) { case PropertyNames.GroupIsSecurityGroup: return _isSecurityGroupChanged == LoadState.Changed; case PropertyNames.GroupGroupScope: return _groupScopeChanged == LoadState.Changed; case PropertyNames.GroupMembers: // If Members was never loaded, it couldn't possibly have changed if (_members != null) return _members.Changed; else { GlobalDebug.WriteLineIf(GlobalDebug.Info, "Group", "GetChangeStatusForProperty: members was never loaded"); return false; } default: return base.GetChangeStatusForProperty(propertyName); } } // Given a property name, returns the current value for the property. internal override object GetValueForProperty(string propertyName) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "Group", "GetValueForProperty: name=" + propertyName); switch (propertyName) { case PropertyNames.GroupIsSecurityGroup: return _isSecurityGroup; case PropertyNames.GroupGroupScope: return _groupScope; case PropertyNames.GroupMembers: return _members; default: return base.GetValueForProperty(propertyName); } } // Reset all change-tracking status for all properties on the object to "unchanged". internal override void ResetAllChangeStatus() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "Group", "ResetAllChangeStatus"); _groupScopeChanged = (_groupScopeChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet; _isSecurityGroupChanged = (_isSecurityGroupChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet; if (_members != null) _members.ResetTracking(); base.ResetAllChangeStatus(); } /// <summary> /// if isSmallGroup has a value, it means we already checked if the group is small /// </summary> private bool? _isSmallGroup; /// <summary> /// cache the search result for the member attribute /// it will only be set for small groups! /// </summary> internal SearchResult SmallGroupMemberSearchResult { get; private set; } /// <summary> /// Finds if the group is "small", meaning that it has less than MaxValRange values (usually 1500) /// The property list for the searcher of a group has "member" attribute. if there are more results than MaxValRange, there will also be a "member;range=..." attribute /// we can cache the result and don't fear from changes through Add/Remove/Save because the completed/pending lists are looked up before the actual values are /// </summary> internal bool IsSmallGroup() { if (_isSmallGroup.HasValue) { return _isSmallGroup.Value; } _isSmallGroup = false; DirectoryEntry de = (DirectoryEntry)this.UnderlyingObject; Debug.Assert(de != null); if (de != null) { using (DirectorySearcher ds = new DirectorySearcher(de, "(objectClass=*)", new string[] { "member" }, SearchScope.Base)) { SearchResult sr = ds.FindOne(); if (sr != null) { bool rangePropertyFound = false; foreach (string propName in sr.Properties.PropertyNames) { if (propName.StartsWith("member;range=", StringComparison.OrdinalIgnoreCase)) { rangePropertyFound = true; break; } } // we only consider the group "small" if there is a "member" property but no "member;range..." property if (!rangePropertyFound) { _isSmallGroup = true; SmallGroupMemberSearchResult = sr; } } } } return _isSmallGroup.Value; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using OptionsApi.Areas.HelpPage.ModelDescriptions; using OptionsApi.Areas.HelpPage.Models; namespace OptionsApi.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
/* Copyright (C) 2008-2015 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * 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.Win32.SafeHandles; using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.InteropServices; using System.Text; namespace Alphaleonis.Win32.Filesystem { internal static partial class NativeMethods { /// <summary>Defines, redefines, or deletes MS-DOS device names.</summary> /// <returns> /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// </returns> /// <remarks>Minimum supported client: Windows XP [desktop apps only]</remarks> /// <remarks>Minimum supported server: Windows Server 2003 [desktop apps only]</remarks> [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "DefineDosDeviceW")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool DefineDosDevice(DosDeviceAttributes dwFlags, [MarshalAs(UnmanagedType.LPWStr)] string lpDeviceName, [MarshalAs(UnmanagedType.LPWStr)] string lpTargetPath); /// <summary>Deletes a drive letter or mounted folder.</summary> /// <returns> /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// </returns> /// <remarks>Minimum supported client: Windows XP [desktop apps only]</remarks> /// <remarks>Minimum supported server: Windows Server 2003 [desktop apps only]</remarks> [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "DeleteVolumeMountPointW")] [return: MarshalAs(UnmanagedType.Bool)] internal extern static bool DeleteVolumeMountPoint([MarshalAs(UnmanagedType.LPWStr)] string lpszVolumeMountPoint); /// <summary>Retrieves the name of a volume on a computer. FindFirstVolume is used to begin scanning the volumes of a computer.</summary> /// <returns> /// If the function succeeds, the return value is a search handle used in a subsequent call to the FindNextVolume and FindVolumeClose functions. /// If the function fails to find any volumes, the return value is the INVALID_HANDLE_VALUE error code. To get extended error information, call GetLastError. /// </returns> /// <remarks>Minimum supported client: Windows XP [desktop apps only]</remarks> /// <remarks>Minimum supported server: Windows Server 2003 [desktop apps only]</remarks> [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "FindFirstVolumeW")] internal extern static SafeFindVolumeHandle FindFirstVolume(StringBuilder lpszVolumeName, [MarshalAs(UnmanagedType.U4)] uint cchBufferLength); /// <summary>Retrieves the name of a mounted folder on the specified volume. FindFirstVolumeMountPoint is used to begin scanning the mounted folders on a volume.</summary> /// <returns> /// If the function succeeds, the return value is a search handle used in a subsequent call to the FindNextVolumeMountPoint and FindVolumeMountPointClose functions. /// If the function fails to find a mounted folder on the volume, the return value is the INVALID_HANDLE_VALUE error code. /// </returns> /// <remarks>Minimum supported client: Windows XP [desktop apps only]</remarks> /// <remarks>Minimum supported server: Windows Server 2003 [desktop apps only]</remarks> [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "FindFirstVolumeMountPointW")] internal extern static SafeFindVolumeMountPointHandle FindFirstVolumeMountPoint([MarshalAs(UnmanagedType.LPWStr)] string lpszRootPathName, StringBuilder lpszVolumeMountPoint, [MarshalAs(UnmanagedType.U4)] uint cchBufferLength); /// <summary>Continues a volume search started by a call to the FindFirstVolume function. FindNextVolume finds one volume per call.</summary> /// <returns> /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// </returns> /// <remarks>Minimum supported client: Windows XP [desktop apps only]</remarks> /// <remarks>Minimum supported server: Windows Server 2003 [desktop apps only]</remarks> [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "FindNextVolumeW")] [return: MarshalAs(UnmanagedType.Bool)] internal extern static bool FindNextVolume(SafeFindVolumeHandle hFindVolume, StringBuilder lpszVolumeName, [MarshalAs(UnmanagedType.U4)] uint cchBufferLength); /// <summary>Continues a mounted folder search started by a call to the FindFirstVolumeMountPoint function. FindNextVolumeMountPoint finds one mounted folder per call.</summary> /// <returns> /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. If no more mounted folders can be found, the GetLastError function returns the ERROR_NO_MORE_FILES error code. /// In that case, close the search with the FindVolumeMountPointClose function. /// </returns> /// <remarks>Minimum supported client: Windows XP</remarks> /// <remarks>Minimum supported server: Windows Server 2003</remarks> [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "FindNextVolumeMountPointW")] [return: MarshalAs(UnmanagedType.Bool)] internal extern static bool FindNextVolumeMountPoint(SafeFindVolumeMountPointHandle hFindVolume, StringBuilder lpszVolumeName, [MarshalAs(UnmanagedType.U4)] uint cchBufferLength); /// <summary>Closes the specified volume search handle.</summary> /// <remarks> /// <para>SetLastError is set to <see langword="false"/>.</para> /// Minimum supported client: Windows XP [desktop apps only]. Minimum supported server: Windows Server 2003 [desktop apps only]. /// </remarks> /// <returns> /// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error /// information, call GetLastError. /// </returns> [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = false, CharSet = CharSet.Unicode)] [return: MarshalAs(UnmanagedType.Bool)] internal extern static bool FindVolumeClose(IntPtr hFindVolume); /// <summary>Closes the specified mounted folder search handle.</summary> /// <remarks> /// <para>SetLastError is set to <see langword="false"/>.</para> /// <para>Minimum supported client: Windows XP</para> /// <para>Minimum supported server: Windows Server 2003</para> /// </remarks> /// <returns> /// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error /// information, call GetLastError. /// </returns> [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = false, CharSet = CharSet.Unicode)] [return: MarshalAs(UnmanagedType.Bool)] internal extern static bool FindVolumeMountPointClose(IntPtr hFindVolume); /// <summary> /// Determines whether a disk drive is a removable, fixed, CD-ROM, RAM disk, or network drive. /// <para>To determine whether a drive is a USB-type drive, call <see cref="SetupDiGetDeviceRegistryProperty"/> and specify the /// SPDRP_REMOVAL_POLICY property.</para> /// </summary> /// <remarks> /// <para>SMB does not support volume management functions.</para> /// <para>Minimum supported client: Windows XP [desktop apps only]</para> /// <para>Minimum supported server: Windows Server 2003 [desktop apps only]</para> /// </remarks> /// <param name="lpRootPathName">Full pathname of the root file.</param> /// <returns> /// <para>The return value specifies the type of drive, see <see cref="DriveType"/>.</para> /// <para>If the function fails, the return value is zero. To get extended error information, call GetLastError.</para> /// </returns> [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetDriveTypeW")] [return: MarshalAs(UnmanagedType.U4)] internal extern static DriveType GetDriveType([MarshalAs(UnmanagedType.LPWStr)] string lpRootPathName); /// <summary> /// Retrieves a bitmask representing the currently available disk drives. /// </summary> /// <remarks> /// <para>SMB does not support volume management functions.</para> /// <para>Minimum supported client: Windows XP [desktop apps only]</para> /// <para>Minimum supported server: Windows Server 2003 [desktop apps only]</para> /// </remarks> /// <returns> /// <para>If the function succeeds, the return value is a bitmask representing the currently available disk drives.</para> /// <para>Bit position 0 (the least-significant bit) is drive A, bit position 1 is drive B, bit position 2 is drive C, and so on.</para> /// <para>If the function fails, the return value is zero. To get extended error information, call GetLastError.</para> /// </returns> [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] [return: MarshalAs(UnmanagedType.U4)] internal static extern uint GetLogicalDrives(); /// <summary>Retrieves information about the file system and volume associated with the specified root directory.</summary> /// <returns> /// If all the requested information is retrieved, the return value is nonzero. /// If not all the requested information is retrieved, the return value is zero. /// </returns> /// <remarks>Minimum supported client: Windows XP [desktop apps only]</remarks> /// <remarks>Minimum supported server: Windows Server 2003 [desktop apps only]</remarks> /// <remarks>"lpRootPathName" must end with a trailing backslash.</remarks> [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetVolumeInformationW")] [return: MarshalAs(UnmanagedType.Bool)] internal extern static bool GetVolumeInformation([MarshalAs(UnmanagedType.LPWStr)] string lpRootPathName, StringBuilder lpVolumeNameBuffer, [MarshalAs(UnmanagedType.U4)] uint nVolumeNameSize, [MarshalAs(UnmanagedType.U4)] out uint lpVolumeSerialNumber, [MarshalAs(UnmanagedType.U4)] out int lpMaximumComponentLength, [MarshalAs(UnmanagedType.U4)] out VolumeInfoAttributes lpFileSystemAttributes, StringBuilder lpFileSystemNameBuffer, [MarshalAs(UnmanagedType.U4)] uint nFileSystemNameSize); /// <summary>Retrieves information about the file system and volume associated with the specified file.</summary> /// <returns> /// If all the requested information is retrieved, the return value is nonzero. /// If not all the requested information is retrieved, the return value is zero. To get extended error information, call GetLastError. /// </returns> /// <remarks>To retrieve the current compression state of a file or directory, use FSCTL_GET_COMPRESSION.</remarks> /// <remarks>SMB does not support volume management functions.</remarks> /// <remarks>Minimum supported client: Windows Vista [desktop apps only]</remarks> /// <remarks>Minimum supported server: Windows Server 2008 [desktop apps only]</remarks> [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetVolumeInformationByHandleW")] [return: MarshalAs(UnmanagedType.Bool)] internal extern static bool GetVolumeInformationByHandle(SafeFileHandle hFile, StringBuilder lpVolumeNameBuffer, [MarshalAs(UnmanagedType.U4)] uint nVolumeNameSize, [MarshalAs(UnmanagedType.U4)] out uint lpVolumeSerialNumber, [MarshalAs(UnmanagedType.U4)] out int lpMaximumComponentLength, out VolumeInfoAttributes lpFileSystemAttributes, StringBuilder lpFileSystemNameBuffer, [MarshalAs(UnmanagedType.U4)] uint nFileSystemNameSize); /// <summary>Retrieves a volume GUID path for the volume that is associated with the specified volume mount point (drive letter, volume GUID path, or mounted folder).</summary> /// <returns> /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// </returns> /// <remarks>Use GetVolumeNameForVolumeMountPoint to obtain a volume GUID path for use with functions such as SetVolumeMountPoint and FindFirstVolumeMountPoint that require a volume GUID path as an input parameter.</remarks> /// <remarks>SMB does not support volume management functions.</remarks> /// <remarks>Mount points aren't supported by ReFS volumes.</remarks> /// <remarks>Minimum supported client: Windows XP [desktop apps only]</remarks> /// <remarks>Minimum supported server: Windows Server 2003 [desktop apps only]</remarks> [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetVolumeNameForVolumeMountPointW")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetVolumeNameForVolumeMountPoint([MarshalAs(UnmanagedType.LPWStr)] string lpszVolumeMountPoint, StringBuilder lpszVolumeName, [MarshalAs(UnmanagedType.U4)] uint cchBufferLength); /// <summary>Retrieves the volume mount point where the specified path is mounted.</summary> /// <remarks> /// <para>If a specified path is passed, GetVolumePathName returns the path to the volume mount point, which means that it returns the /// root of the volume where the end point of the specified path is located.</para> /// <para>For example, assume that you have volume D mounted at C:\Mnt\Ddrive and volume E mounted at "C:\Mnt\Ddrive\Mnt\Edrive". Also /// assume that you have a file with the path "E:\Dir\Subdir\MyFile".</para> /// <para>If you pass "C:\Mnt\Ddrive\Mnt\Edrive\Dir\Subdir\MyFile" to GetVolumePathName, it returns the path "C:\Mnt\Ddrive\Mnt\Edrive\".</para> /// <para>If a network share is specified, GetVolumePathName returns the shortest path for which GetDriveType returns DRIVE_REMOTE, /// which means that the path is validated as a remote drive that exists, which the current user can access.</para> /// <para>Minimum supported client: Windows XP [desktop apps only]</para> /// <para>Minimum supported server: Windows Server 2003 [desktop apps only]</para> /// </remarks> /// <returns> /// <para>If the function succeeds, the return value is nonzero.</para> /// <para>If the function fails, the return value is zero. To get extended error information, call GetLastError.</para> /// </returns> [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetVolumePathNameW")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetVolumePathName([MarshalAs(UnmanagedType.LPWStr)] string lpszFileName, StringBuilder lpszVolumePathName, [MarshalAs(UnmanagedType.U4)] uint cchBufferLength); /// <summary>Retrieves a list of drive letters and mounted folder paths for the specified volume.</summary> /// <remarks>Minimum supported client: Windows XP.</remarks> /// <remarks>Minimum supported server: Windows Server 2003.</remarks> /// <returns> /// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error /// information, call GetLastError. /// </returns> [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "GetVolumePathNamesForVolumeNameW")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetVolumePathNamesForVolumeName([MarshalAs(UnmanagedType.LPWStr)] string lpszVolumeName, char[] lpszVolumePathNames, [MarshalAs(UnmanagedType.U4)] uint cchBuferLength, [MarshalAs(UnmanagedType.U4)] out uint lpcchReturnLength); /// <summary>Sets the label of a file system volume.</summary> /// <remarks>Minimum supported client: Windows XP [desktop apps only].</remarks> /// <remarks>Minimum supported server: Windows Server 2003 [desktop apps only].</remarks> /// <remarks>"lpRootPathName" must end with a trailing backslash.</remarks> /// <returns> /// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error /// information, call GetLastError. /// </returns> [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "SetVolumeLabelW")] [return: MarshalAs(UnmanagedType.Bool)] internal extern static bool SetVolumeLabel([MarshalAs(UnmanagedType.LPWStr)] string lpRootPathName, [MarshalAs(UnmanagedType.LPWStr)] string lpVolumeName); /// <summary>Associates a volume with a drive letter or a directory on another volume.</summary> /// <remarks>Minimum supported client: Windows XP [desktop apps only].</remarks> /// <remarks>Minimum supported server: Windows Server 2003 [desktop apps only].</remarks> /// <returns> /// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error /// information, call GetLastError. /// </returns> [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "SetVolumeMountPointW")] [return: MarshalAs(UnmanagedType.Bool)] internal extern static bool SetVolumeMountPoint([MarshalAs(UnmanagedType.LPWStr)] string lpszVolumeMountPoint, [MarshalAs(UnmanagedType.LPWStr)] string lpszVolumeName); /// <summary>Retrieves information about MS-DOS device names.</summary> /// <remarks>Minimum supported client: Windows XP [desktop apps only].</remarks> /// <remarks>Minimum supported server: Windows Server 2003 [desktop apps only].</remarks> /// <returns> /// If the function succeeds, the return value is the number of TCHARs stored into the buffer pointed to by lpTargetPath. If the /// function fails, the return value is zero. To get extended error information, call GetLastError. If the buffer is too small, the /// function fails and the last error code is ERROR_INSUFFICIENT_BUFFER. /// </returns> [SuppressMessage("Microsoft.Security", "CA5122:PInvokesShouldNotBeSafeCriticalFxCopRule")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "QueryDosDeviceW")] [return: MarshalAs(UnmanagedType.U4)] internal static extern uint QueryDosDevice([MarshalAs(UnmanagedType.LPWStr)] string lpDeviceName, char[] lpTargetPath, [MarshalAs(UnmanagedType.U4)] uint ucchMax); } }
using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using System.Drawing; namespace JustGestures { public struct Win32 { #region Sturctures //[StructLayout(LayoutKind.Sequential)] //public struct KEYBOARD_INPUT //{ // public uint type; // public ushort vk; // public ushort scanCode; // public uint flags; // public uint time; // public uint extrainfo; // public uint padding1; // public uint padding2; // public KEYBOARD_INPUT(ushort key) // { // type = Win32.INPUT_KEYBOARD; // vk = key; // scanCode = 0; // flags = 0; // time = 0; // extrainfo = 0; // padding1 = 0; // padding2 = 0; // } //} public struct POINT { public int x; public int y; public POINT(int x, int y) { this.x = x; this.y = y; } } public struct SIZE { public int cx; public int cy; public SIZE(int cx, int cy) { this.cx = cx; this.cy = cy; } } public static bool IsKeyDown(ushort KeyCode) { ushort state = GetKeyState(KeyCode); return ((state & 0x10000) == 0x10000); } [StructLayout(LayoutKind.Sequential)] public struct RECT { public Int32 left; public Int32 top; public Int32 right; public Int32 bottom; public RECT(Rectangle _rect) { left = _rect.Left; top = _rect.Top; right = _rect.Right; bottom = _rect.Bottom; } public RECT(RectangleF _rect) { left = (int)_rect.Left; top = (int)_rect.Top; right = (int)_rect.Right; bottom = (int)_rect.Bottom; } } [StructLayout(LayoutKind.Sequential)] public struct WINDOWINFO { public UInt32 cbSize; public RECT rcWindow; public RECT rcClient; public UInt32 dwStyle; public UInt32 dwExStyle; public UInt32 dwWindowStatus; public UInt32 cxWindowBorders; public UInt32 cyWindowBorders; public UInt16 atomWindowType; public UInt16 wCreatorVersion; } [StructLayout(LayoutKind.Sequential)] public struct WINDOWPLACEMENT { public int length; public int flags; public int showCmd; public POINT ptMinPosition; public POINT ptMaxPosition; public RECT rcNormalPosition; } public struct BLENDFUNCTION { public byte BlendOp; public byte BlendFlags; public byte SourceConstantAlpha; public byte AlphaFormat; } public enum TernaryRasterOperations { SRCCOPY = 0x00CC0020, /* dest = source */ SRCPAINT = 0x00EE0086, /* dest = source OR dest */ SRCAND = 0x008800C6, /* dest = source AND dest */ SRCINVERT = 0x00660046, /* dest = source XOR dest */ SRCERASE = 0x00440328, /* dest = source AND (NOT dest ) */ NOTSRCCOPY = 0x00330008, /* dest = (NOT source) */ NOTSRCERASE = 0x001100A6, /* dest = (NOT src) AND (NOT dest) */ MERGECOPY = 0x00C000CA, /* dest = (source AND pattern) */ MERGEPAINT = 0x00BB0226, /* dest = (NOT source) OR dest */ PATCOPY = 0x00F00021, /* dest = pattern */ PATPAINT = 0x00FB0A09, /* dest = DPSnoo */ PATINVERT = 0x005A0049, /* dest = pattern XOR dest */ DSTINVERT = 0x00550009, /* dest = (NOT dest) */ BLACKNESS = 0x00000042, /* dest = BLACK */ WHITENESS = 0x00FF0062, /* dest = WHITE */ }; public delegate bool EnumDelegate(IntPtr hWnd, int lParam); public const int INPUT_MOUSE = 0; public const int INPUT_KEYBOARD = 1; public const int INPUT_HARDWARE = 2; #if (!X64) [StructLayout(LayoutKind.Explicit)] public struct INPUT { [FieldOffset(0)] public int type; [FieldOffset(4)] public MOUSEINPUT mi; [FieldOffset(4)] public KEYBDINPUT ki; [FieldOffset(4)] public HARDWAREINPUT hi; } #else [StructLayout(LayoutKind.Explicit)] public struct INPUT { [FieldOffset(0)] public int type; [FieldOffset(8)] public MOUSEINPUT mi; [FieldOffset(8)] public KEYBDINPUT ki; [FieldOffset(8)] public HARDWAREINPUT hi; } #endif [StructLayout(LayoutKind.Sequential)] public struct MOUSEINPUT { public int dx; public int dy; public int mouseData; public int dwFlags; public uint time; public IntPtr dwExtraInfo; } [StructLayout(LayoutKind.Sequential)] public struct KEYBDINPUT { public ushort wVk; public ushort wScan; public uint dwFlags; public uint time; public IntPtr dwExtraInfo; } [StructLayout(LayoutKind.Sequential)] public struct HARDWAREINPUT { public uint uMsg; public ushort wParamL; public ushort wParamH; } public static KEYBDINPUT CreateKeybdInput(ushort wVK, uint flag) { KEYBDINPUT i = new KEYBDINPUT(); i.wVk = wVK; i.wScan = 0; i.time = 0; i.dwExtraInfo = IntPtr.Zero; i.dwFlags = flag; return i; } public static MOUSEINPUT CreateMouseInput(int x, int y, int data, uint t, int flag) { MOUSEINPUT mi = new MOUSEINPUT(); mi.dx = x; mi.dy = y; mi.mouseData = data; mi.time = t; //mi.dwFlags = MOUSEEVENTF_ABSOLUTE| MOUSEEVENTF_MOVE; mi.dwFlags = flag; return mi; } #endregion Sturctures #region DllImport USER32.dll [DllImport("user32.dll", SetLastError = true)] public static extern uint SendInput(uint nInputs, INPUT[] pInputs, int cbSize); [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll")] public static extern IntPtr GetTopWindow(IntPtr hWnd); [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hWnd); [DllImport("user32.dll")] public static extern int SetActiveWindow(IntPtr hWnd); [DllImport("User32")] public static extern int ShowWindow(IntPtr hWnd, int nCmdShow); [DllImport("user32.dll")] public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow); [DllImport("User32")] public static extern bool CloseWindow(IntPtr hWnd); [DllImport("User32")] public static extern bool DestroyWindow(IntPtr hWnd); [DllImport("user32.dll")] public static extern IntPtr GetWindowText(IntPtr hWnd, StringBuilder text, int count); [DllImport("user32.dll")] public static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam); [DllImport("user32.dll")] public static extern bool PostMessage(IntPtr hWnd, uint Msg, int wParam, int lParam); [DllImport("user32.dll")] public static extern IntPtr FindWindow(string lpClassName, string lpWindowName); [DllImport("user32.dll")] public static extern IntPtr WindowFromPoint(Point pt); [DllImport("user32.dll")] public static extern short GetAsyncKeyState(int nVirtKey); [DllImport("user32.dll")] public static extern ushort GetKeyState(int nVirtKey); [DllImport("user32.dll")] public static extern IntPtr GetWindowDC(IntPtr hWnd); [DllImport("user32.dll")] public static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount); public delegate bool EnumWindowProc(IntPtr hWnd, IntPtr parameter); [DllImport("user32")] public static extern int EnumWindows(EnumWindowProc lpEnumFunc, IntPtr lParam); [DllImport("user32")] public static extern int EnumChildWindows(IntPtr hWndParent, EnumWindowProc lpEnumFunc, IntPtr lParam); [DllImport("user32.dll", SetLastError = true)] public static extern bool EnumDesktopWindows(IntPtr hDesktop, EnumDelegate lpEnumCallbackFunction, IntPtr lParam); [DllImport("user32.dll", ExactSpelling = true)] public static extern IntPtr GetAncestor(IntPtr hwnd, uint gaFlags); [DllImport("user32.dll")] public static extern void mouse_event(int dwFlags, int dx, int dy, int dwData, IntPtr dwExtraInfo); [DllImport("user32.dll")] public static extern bool SetCursorPos(int X, int Y); [DllImport("user32.dll")] public static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, int dwExtraInfo); [DllImport("kernel32.dll")] public static extern int GetLongPathName(string path, StringBuilder longPath, int longPathLength); [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId); [DllImport("user32.dll")] public static extern IntPtr GetWindow(IntPtr hWnd, int wFlag); [DllImport("user32.dll")] public static extern int ExitWindowsEx(int uFlags, int dwReason); [DllImport("user32.dll", EntryPoint = "GetSystemMetrics")] public static extern int GetSystemMetrics(int which); [DllImport("user32.dll")] public static extern void SetWindowPos(IntPtr hWnd, int hwndInsertAfter, int X, int Y, int width, int height, uint flags); [DllImport("USER32.DLL")] public static extern int GetWindowLong(IntPtr hWnd, int nIndex); [DllImport("USER32.DLL")] public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong); [DllImport("user32.dll")] public static extern bool GetWindowInfo(IntPtr hwnd, ref WINDOWINFO pwi); [DllImport("user32")] public static extern int SetLayeredWindowAttributes(IntPtr Handle, int crKey, byte bAlpha, int dwFlags); [DllImport("user32.dll")] public static extern bool GetLayeredWindowAttributes(IntPtr hwnd, out uint crKey, out byte bAlpha, out uint dwFlags); [DllImport("user32", SetLastError = true)] public static extern IntPtr MoveWindow(IntPtr hwnd, int x, int y, int w, int l, bool repaint); [DllImport("user32.dll")] public static extern bool InvalidateRect(IntPtr hWnd, ref RECT lpRect, bool bErase); [DllImport("user32.dll")] public static extern bool InvalidateRect(IntPtr hWnd, IntPtr lpRect, bool bErase); [DllImport("user32")] public static extern int UpdateWindow(IntPtr hwnd); [DllImportAttribute("user32.dll")] public extern static bool UpdateLayeredWindow(IntPtr handle, IntPtr hdcDst, ref POINT pptDst, ref SIZE psize, IntPtr hdcSrc, ref POINT pprSrc, int crKey, ref BLENDFUNCTION pblend, int dwFlags); [DllImportAttribute("user32.dll")] public extern static IntPtr GetDC(IntPtr handle); [DllImportAttribute("user32.dll", ExactSpelling = true)] public extern static int ReleaseDC(IntPtr handle, IntPtr hDC); [DllImport("user32.dll")] public static extern IntPtr GetDesktopWindow(); [DllImport("user32.dll")] public static extern bool OpenIcon(IntPtr hWnd); [DllImport("user32.dll")] public static extern IntPtr LoadCursorFromFile(string lpFileName); [DllImport("user32.dll")] public static extern bool InvalidateRgn(IntPtr hWnd, IntPtr hRgn, bool bErase); [DllImport("user32.dll")] public static extern bool RedrawWindow(IntPtr hWnd, [In] ref RECT lprcUpdate, IntPtr hrgnUpdate, int flags); [DllImport("user32.dll")] public static extern bool GetWindowPlacement(IntPtr hWnd, ref WINDOWPLACEMENT lpwndpl); [DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr hWnd); [DllImport("user32.dll")] public static extern bool IsWindow(IntPtr hWnd); [DllImport("user32.dll")] public static extern IntPtr GetClassLong(IntPtr hWnd, int nIndex); //public static extern IntPtr GetClassLongPtr(HandleRef hWnd, int nIndex); [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] public static extern uint GetWindowModuleFileName(IntPtr hwnd, [Out] StringBuilder lpszFileName, int cchFileNameMax); [DllImport("kernel32.dll")] public static extern IntPtr OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId); [DllImport("psapi.dll")] public static extern uint GetModuleFileNameEx(IntPtr hProcess, IntPtr hModule, [Out] StringBuilder lpBaseName, [In] [MarshalAs(UnmanagedType.U4)] int nSize); [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool CloseHandle(IntPtr hObject); [DllImport("shell32.dll")] public static extern IntPtr ExtractIcon(IntPtr hInst, string lpszExeFileName, int nIconIndex); [DllImport("kernel32.dll", SetLastError = true)] [PreserveSig] public static extern uint GetModuleFileName ( [In] IntPtr hModule, [Out] StringBuilder lpFilename, [In] [MarshalAs(UnmanagedType.U4)] int nSize ); [DllImport("uxtheme", ExactSpelling = true, CharSet = CharSet.Unicode)] public static extern Int32 SetWindowTheme (IntPtr hWnd, String textSubAppName, String textSubIdList); [DllImport("user32.dll")] public static extern IntPtr SetFocus(IntPtr hWnd); [DllImport("user32", EntryPoint = "LoadCursorFromFile")] public static extern int LoadCursorFromFileA(string lpFileName); [DllImport("user32.dll")] public static extern IntPtr SetCapture(IntPtr hWnd); [DllImport("user32.dll")] public static extern bool ReleaseCapture(); [DllImport("user32.dll")] public static extern bool GetCursorPos(out POINT lpPoint); [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr hWnd, ref RECT lpRect); #endregion DllImport USER32.dll #region DllImport GDI32.dll [DllImport("gdi32.dll")] public static extern bool StretchBlt(IntPtr hdcDest, int nXOriginDest, int nYOriginDest, int nWidthDest, int nHeightDest, IntPtr hdcSrc, int nXOriginSrc, int nYOriginSrc, int nWidthSrc, int nHeightSrc, TernaryRasterOperations dwRop); [DllImport("GDI32.dll")] public static extern bool BitBlt(IntPtr hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, TernaryRasterOperations dwRop); [DllImport("GDI32.dll")] public static extern IntPtr CreateCompatibleBitmap(IntPtr hdc, int nWidth, int nHeight); [DllImport("GDI32.dll")] public static extern IntPtr CreateCompatibleDC(IntPtr hdc); [DllImport("GDI32.dll")] public static extern bool DeleteDC(IntPtr hdc); [DllImport("GDI32.dll")] public static extern bool DeleteObject(IntPtr hObject); [DllImport("GDI32.dll")] public static extern IntPtr SelectObject(IntPtr hdc, IntPtr hgdiobj); [DllImport("gdi32.dll", EntryPoint = "GdiAlphaBlend")] public static extern bool AlphaBlend(IntPtr hdcDest, int nXOriginDest, int nYOriginDest, int nWidthDest, int nHeightDest, IntPtr hdcSrc, int nXOriginSrc, int nYOriginSrc, int nWidthSrc, int nHeightSrc, BLENDFUNCTION blendFunction); [DllImport("Gdi32.dll", EntryPoint = "CreateRoundRectRgn")] public static extern IntPtr CreateRoundRectRgn ( int nLeftRect, // x-coordinate of upper-left corner int nTopRect, // y-coordinate of upper-left corner int nRightRect, // x-coordinate of lower-right corner int nBottomRect, // y-coordinate of lower-right corner int nWidthEllipse, // height of ellipse int nHeightEllipse // width of ellipse ); #endregion DllImport GDI32.dll #region Constants public const uint KEYEVENTF_EXTENDEDKEY = 0x0001; public const uint KEYEVENTF_KEYUP = 0x0002; public const uint KEYEVENTF_UNICODE = 0x0004; public const uint KEYEVENTF_SCANCODE = 0x0008; #region Virtual Key Constatns public const ushort VK_LBUTTON = 0x01; //Left mouse button public const ushort VK_RBUTTON = 0x02; //Right mouse button public const ushort VK_CANCEL = 0x03; //Control-break processing public const ushort VK_MBUTTON = 0x04; //Middle mouse button (three-button mouse) public const ushort VK_XBUTTON1 = 0x05; //Windows 2000/XP: X1 mouse button public const ushort VK_XBUTTON2 = 0x06; //Windows 2000/XP: X2 mouse button // - (0x07) Undefined public const ushort VK_BACK = 0x08; //BACKSPACE key public const ushort VK_TAB = 0x09; //TAB key //- (0x0A-0B) Reserved public const ushort VK_CLEAR = 0x0C; //CLEAR key public const ushort VK_RETURN = 0x0D; //ENTER key //- (0x0E-0F) Undefined public const ushort VK_SHIFT = 0x10; //SHIFT key public const ushort VK_CONTROL = 0x11; //CTRL key public const ushort VK_MENU = 0x12; //ALT key public const ushort VK_PAUSE = 0x13; //PAUSE key public const ushort VK_CAPITAL = 0x14; //CAPS LOCK key public const ushort VK_KANA = 0x15; //Input Method Editor (IME) Kana mode public const ushort VK_HANGUEL = 0x15; //IME Hanguel mode (maintained for compatibility; use VK_HANGUL) public const ushort VK_HANGUL = 0x15; //IME Hangul mode //- (0x16) Undefined public const ushort VK_JUNJA = 0x17; //IME Junja mode public const ushort VK_FINAL = 0x18; //IME final mode public const ushort VK_HANJA = 0x19; //IME Hanja mode public const ushort VK_KANJI = 0x19; //IME Kanji mode //- (0x1A) Undefined public const ushort VK_ESCAPE = 0x1B; //ESC key public const ushort VK_CONVERT = 0x1C; //IME convert public const ushort VK_NONCONVERT = 0x1D; //IME nonconvert public const ushort VK_ACCEPT = 0x1E; //IME accept public const ushort VK_MODECHANGE = 0x1F; //IME mode change request public const ushort VK_SPACE = 0x20; //SPACEBAR public const ushort VK_PRIOR = 0x21; //PAGE UP key public const ushort VK_NEXT = 0x22; //PAGE DOWN key public const ushort VK_END = 0x23; //END key public const ushort VK_HOME = 0x24; //HOME key public const ushort VK_LEFT = 0x25; //LEFT ARROW key public const ushort VK_UP = 0x26; //UP ARROW key public const ushort VK_RIGHT = 0x27; //RIGHT ARROW key public const ushort VK_DOWN = 0x28; //DOWN ARROW key public const ushort VK_SELECT = 0x29; //SELECT key public const ushort VK_PRINT = 0x2A; //PRINT key public const ushort VK_EXECUTE = 0x2B; //EXECUTE key public const ushort VK_SNAPSHOT = 0x2C; //PRINT SCREEN key public const ushort VK_INSERT = 0x2D; //INS key public const ushort VK_DELETE = 0x2E; //DEL key public const ushort VK_HELP = 0x2F; //HELP key public const ushort VK_0 = 0x30; //0 key public const ushort VK_1 = 0x31; //1 key public const ushort VK_2 = 0x32; //2 key public const ushort VK_3 = 0x33; //3 key public const ushort VK_4 = 0x34; //4 key public const ushort VK_5 = 0x35; //5 key public const ushort VK_6 = 0x36; //6 key public const ushort VK_7 = 0x37; //7 key public const ushort VK_8 = 0x38; //8 key public const ushort VK_9 = 0x39; //9 key //- (0x3A-40) Undefined public const ushort VK_A = 0x41; //A key public const ushort VK_B = 0x42; //B key public const ushort VK_C = 0x43; //C key public const ushort VK_D = 0x44; //D key public const ushort VK_E = 0x45; //E key public const ushort VK_F = 0x46; //F key public const ushort VK_G = 0x47; //G key public const ushort VK_H = 0x48; //H key public const ushort VK_I = 0x49; //I key public const ushort VK_J = 0x4A; //J key public const ushort VK_K = 0x4B; //K key public const ushort VK_L = 0x4C; //L key public const ushort VK_M = 0x4D; //M key public const ushort VK_N = 0x4E; //N key public const ushort VK_O = 0x4F; //O key public const ushort VK_P = 0x50; //P key public const ushort VK_Q = 0x51; //Q key public const ushort VK_R = 0x52; //R key public const ushort VK_S = 0x53; //S key public const ushort VK_T = 0x54; //T key public const ushort VK_U = 0x55; //U key public const ushort VK_V = 0x56; //V key public const ushort VK_W = 0x57; //W key public const ushort VK_X = 0x58; //X key public const ushort VK_Y = 0x59; //Y key public const ushort VK_Z = 0x5A; //Z key public const ushort VK_LWIN = 0x5B; //Left Windows key (Microsoft Natural keyboard) public const ushort VK_RWIN = 0x5C; //Right Windows key (Natural keyboard) public const ushort VK_APPS = 0x5D; //Applications key (Natural keyboard) //- (0x5E) Reserved public const ushort VK_SLEEP = 0x5F; //Computer Sleep key public const ushort VK_NUMPAD0 = 0x60; //Numeric keypad 0 key public const ushort VK_NUMPAD1 = 0x61; //Numeric keypad 1 key public const ushort VK_NUMPAD2 = 0x62; //Numeric keypad 2 key public const ushort VK_NUMPAD3 = 0x63; //Numeric keypad 3 key public const ushort VK_NUMPAD4 = 0x64; //Numeric keypad 4 key public const ushort VK_NUMPAD5 = 0x65; //Numeric keypad 5 key public const ushort VK_NUMPAD6 = 0x66; //Numeric keypad 6 key public const ushort VK_NUMPAD7 = 0x67; //Numeric keypad 7 key public const ushort VK_NUMPAD8 = 0x68; //Numeric keypad 8 key public const ushort VK_NUMPAD9 = 0x69; //Numeric keypad 9 key public const ushort VK_MULTIPLY = 0x6A; //Multiply key public const ushort VK_ADD = 0x6B; //Add key public const ushort VK_SEPARATOR = 0x6C; //Separator key public const ushort VK_SUBTRACT = 0x6D; //Subtract key public const ushort VK_DECIMAL = 0x6E; //Decimal key public const ushort VK_DIVIDE = 0x6F; //Divide key public const ushort VK_F1 = 0x70; //F1 key public const ushort VK_F2 = 0x71; //F2 key public const ushort VK_F3 = 0x72; //F3 key public const ushort VK_F4 = 0x73; //F4 key public const ushort VK_F5 = 0x74; //F5 key public const ushort VK_F6 = 0x75; //F6 key public const ushort VK_F7 = 0x76; //F7 key public const ushort VK_F8 = 0x77; //F8 key public const ushort VK_F9 = 0x78; //F9 key public const ushort VK_F10 = 0x79; //F10 key public const ushort VK_F11 = 0x7A; //F11 key public const ushort VK_F12 = 0x7B; //F12 key public const ushort VK_F13 = 0x7C; //F13 key public const ushort VK_F14 = 0x7D; //F14 key public const ushort VK_F15 = 0x7E; //F15 key public const ushort VK_F16 = 0x7F; //F16 key //public const ushort VK_F17 = 0x80H; //F17 key //public const ushort VK_F18 = 0x81H; //F18 key //public const ushort VK_F19 = 0x82H; //F19 key //public const ushort VK_F20 = 0x83H; //F20 key //public const ushort VK_F21 = 0x84H; //F21 key //public const ushort VK_F22 = 0x85H; //F22 key //public const ushort VK_F23 = 0x86H; //F23 key //public const ushort VK_F24 = 0x87H; //F24 key //- (0x88-8F) Unassigned public const ushort VK_NUMLOCK = 0x90; //NUM LOCK key public const ushort VK_SCROLL = 0x91; //SCROLL LOCK key //- (0x92-96) OEM specific //- (0x97-9F) // Unassigned public const ushort VK_LSHIFT = 0xA0; //Left SHIFT key public const ushort VK_RSHIFT = 0xA1; //Right SHIFT key public const ushort VK_LCONTROL = 0xA2; //Left CONTROL key public const ushort VK_RCONTROL = 0xA3; //Right CONTROL key public const ushort VK_LMENU = 0xA4; //Left MENU key public const ushort VK_RMENU = 0xA5; //Right MENU key public const ushort VK_BROWSER_BACK = 0xA6; //Windows 2000/XP: Browser Back key public const ushort VK_BROWSER_FORWARD = 0xA7; //Windows 2000/XP: Browser Forward key public const ushort VK_BROWSER_REFRESH = 0xA8; //Windows 2000/XP: Browser Refresh key public const ushort VK_BROWSER_STOP = 0xA9; //Windows 2000/XP: Browser Stop key public const ushort VK_BROWSER_SEARCH = 0xAA; //Windows 2000/XP: Browser Search key public const ushort VK_BROWSER_FAVORITES = 0xAB; //Windows 2000/XP: Browser Favorites key public const ushort VK_BROWSER_HOME = 0xAC; //Windows 2000/XP: Browser Start and Home key public const ushort VK_VOLUME_MUTE = 0xAD; //Windows 2000/XP: Volume Mute key public const ushort VK_VOLUME_DOWN = 0xAE; //Windows 2000/XP: Volume Down key public const ushort VK_VOLUME_UP = 0xAF; //Windows 2000/XP: Volume Up key public const ushort VK_MEDIA_NEXT_TRACK = 0xB0; //Windows 2000/XP: Next Track key public const ushort VK_MEDIA_PREV_TRACK = 0xB1; //Windows 2000/XP: Previous Track key public const ushort VK_MEDIA_STOP = 0xB2; //Windows 2000/XP: Stop Media key public const ushort VK_MEDIA_PLAY_PAUSE = 0xB3; //Windows 2000/XP: Play/Pause Media key public const ushort VK_LAUNCH_MAIL = 0xB4; //Windows 2000/XP: Start Mail key public const ushort VK_LAUNCH_MEDIA_SELECT = 0xB5; //Windows 2000/XP: Select Media key public const ushort VK_LAUNCH_APP1 = 0xB6; //Windows 2000/XP: Start Application 1 key public const ushort VK_LAUNCH_APP2 = 0xB7; //Windows 2000/XP: Start Application 2 key //- (0xB8-B9) Reserved public const ushort VK_OEM_1 = 0xBA; // Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the ';:' key public const ushort VK_OEM_PLUS = 0xBB; //Windows 2000/XP: For any country/region, the '+' key public const ushort VK_OEM_COMMA = 0xBC; //Windows 2000/XP: For any country/region, the ',' key public const ushort VK_OEM_MINUS = 0xBD; //Windows 2000/XP: For any country/region, the '-' key public const ushort VK_OEM_PERIOD = 0xBE; //Windows 2000/XP: For any country/region, the '.' key public const ushort VK_OEM_2 = 0xBF; //Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '/?' key public const ushort VK_OEM_3 = 0xC0; //Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '`~' key //- (0xC1-D7) Reserved //- (0xD8-DA) Unassigned public const ushort VK_OEM_4 = 0xDB; //Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '[{' key public const ushort VK_OEM_5 = 0xDC; //Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '\|' key public const ushort VK_OEM_6 = 0xDD; //Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the ']}' key public const ushort VK_OEM_7 = 0xDE; //Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the 'single-quote/double-quote' key public const ushort VK_OEM_8 = 0xDF; //Used for miscellaneous characters; it can vary by keyboard. //- (0xE0) Reserved //- (0xE1) OEM specific public const ushort VK_OEM_102 = 0xE2; //Windows 2000/XP: Either the angle bracket key or the backslash key on the RT 102-key keyboard //- (0xE3-E4) OEM specific public const ushort VK_PROCESSKEY = 0xE5; //Windows 95/98/Me, Windows NT 4.0, Windows 2000/XP: IME PROCESS key //- (0xE6) OEM specific public const ushort VK_PACKET = 0xE7; //Windows 2000/XP: Used to pass Unicode characters as if they were keystrokes. The VK_PACKET key is the low word of a 32-bit Virtual Key value used for non-keyboard input methods. For more information, see Remark in KEYBDINPUT, SendInput, WM_KEYDOWN, and WM_KEYUP //- (0xE8) Unassigned //- (0xE9-F5) OEM specific public const ushort VK_ATTN = 0xF6; //Attn key public const ushort VK_CRSEL = 0xF7; //CrSel key public const ushort VK_EXSEL = 0xF8; //ExSel key public const ushort VK_EREOF = 0xF9; //Erase EOF key public const ushort VK_PLAY = 0xFA; //Play key public const ushort VK_ZOOM = 0xFB; //Zoom key public const ushort VK_NONAME = 0xFC; //Reserved public const ushort VK_PA1 = 0xFD; //PA1 key public const ushort VK_OEM_CLEAR = 0xFE; //Clear key #endregion #Virtual Key Constatns public const int STRETCH_ANDSCANS = 1; public const int STRETCH_ORSCANS = 2; public const int STRETCH_DELETESCANS = 3; public const int STRETCH_HALFTONE = 4; public const int RDW_INVALIDATE = 0x0001; public const int RDW_INTERNALPAINT = 0x0002; public const int RDW_ERASE = 0x0004; public const int RDW_VALIDATE = 0x0008; public const int RDW_NOINTERNALPAINT = 0x0010; public const int RDW_NOERASE = 0x0020; public const int RDW_NOCHILDREN = 0x0040; public const int RDW_ALLCHILDREN = 0x0080; public const int RDW_UPDATENOW = 0x0100; public const int RDW_ERASENOW = 0x0200; public const int RDW_FRAME = 0x0400; public const int RDW_NOFRAME = 0x0800; public const byte AC_SRC_OVER = 0x00; public const byte AC_SRC_ALPHA = 0x01; public const int ULW_ALPHA = 2; //public const int ULW_COLORKEY = 1; //public const int ULW_OPAQUE = 0; public const int SHFS_SHOWTASKBAR = 0x1; public const int SHFS_HIDETASKBAR = 0x2; public const int SHFS_SHOWSIPBUTTON = 0x4; public const int SHFS_HIDESIPBUTTON = 0x8; public const int SHFS_SHOWSTARTICON = 0x10; public const int SHFS_HIDESTARTICON = 0x20; public const int LWA_ALPHA = 2; public const int LWA_COLORKEY = 1; public const int WS_CLIPCHILDREN = 0x02000000; public const int GWL_EXSTYLE = -20; public const int GWL_STYLE = -16; public const int WS_EX_LAYERED = 0x80000; public const int WS_EX_TRANSPARENT = 0x00000020; public const int WS_EX_TOOLWINDOW = 0x00000080; public const int WS_EX_NOACTIVATE = 0x08000000; public const int WS_OVERLAPPED = 0x00000000; public const uint WS_POPUP = 0x80000000; public const int WS_CHILD = 0x40000000; public const int WS_MINIMIZE = 0x20000000; public const int WS_VISIBLE = 0x10000000; public const int WS_DISABLED = 0x08000000; public const int WS_CLIPSIBLINGS = 0x04000000; public const int WS_MAXIMIZE = 0x01000000; public const int WS_CAPTION = 0x00C00000; /* WS_BORDER | WS_DLGFRAME */ public const int WS_BORDER = 0x00800000; public const int WS_DLGFRAME = 0x00400000; public const int WS_VSCROLL = 0x00200000; public const int WS_HSCROLL = 0x00100000; public const int WS_SYSMENU = 0x00080000; public const int WS_THICKFRAME = 0x00040000; public const int WS_GROUP = 0x00020000; public const int WS_TABSTOP = 0x00010000; public const int SM_CXSCREEN = 0; public const int SM_CYSCREEN = 1; public const int SM_SWAPBUTTON = 23; public const int SWP_ASYNCWINDOWPOS = 0x4000; public const int SWP_DEFERERASE = 0x2000; public const int SWP_DRAWFRAME = 0x0020; public const int SWP_FRAMECHANGED = 0x0020; public const int SWP_HIDEWINDOW = 0x0080; public const int SWP_NOACTIVATE = 0x0010; public const int SWP_NOCOPYBITS = 0x0100; public const int SWP_NOMOVE = 0x0002; public const int SWP_NOOWNERZORDER = 0x0200; public const int SWP_NOREDRAW = 0x0008; public const int SWP_NOREPOSITION = 0x0200; public const int SWP_NOSENDCHANGING = 0x0400; public const int SWP_NOSIZE = 0x0001; public const int SWP_NOZORDER = 0x0004; public const int SWP_SHOWWINDOW = 0x0040; public const int HWND_TOP = 0; public const int HWND_BOTTOM = 1; public const int HWND_TOPMOST = -1; public const int HWND_NOTOPMOST = -2; public const int EWX_FORCE = 4; public const int EWX_LOGOFF = 0; public const int EWX_REBOOT = 2; public const int EWX_SHUTDOWN = 1; public const int GW_HWNDFIRST = 0; public const int GW_HWNDLAST = 1; public const int GW_HWNDNEXT = 2; public const int GW_HWNDPREV = 3; public const int GW_OWNER = 4; public const int GW_CHILD = 5; public const uint GA_PARENT = 1; public const uint GA_ROOT = 2; public const uint GA_ROOTOWNER = 3; public static ushort LOWORD(int l) { return (ushort)(l); } public static ushort HIWORD(int l) { return (ushort)(((int)(l) >> 16) & 0xFFFF); } public const int MOUSEEVENTF_MOVE = 0x0001; public const int MOUSEEVENTF_LEFTDOWN = 0x0002; public const int MOUSEEVENTF_LEFTUP = 0x0004; public const int MOUSEEVENTF_RIGHTDOWN = 0x0008; public const int MOUSEEVENTF_RIGHTUP = 0x0010; public const int MOUSEEVENTF_MIDDLEDOWN = 0x0020; public const int MOUSEEVENTF_MIDDLEUP = 0x0040; public const int MOUSEEVENTF_XDOWN = 0x0080; public const int MOUSEEVENTF_XUP = 0x0100; public const int MOUSEEVENTF_WHEEL = 0x0800; public const int MOUSEEVENTF_VIRTUALDESK = 0x4000; public const int MOUSEEVENTF_ABSOLUTE = 0x8000; public const int XBUTTON1 = 0x0001; public const int XBUTTON2 = 0x0002; public const int WM_LBUTTONDOWN = 0x0201; public const int WM_LBUTTONUP = 0x0202; public const int WM_CANCELMODE = 0x001F; public const int HC_ACTION = 0; public const int HC_NOREMOVE = 3; public const int WM_COPY = 0x301; public const int WM_PASTE = 0x302; public const int WM_KEYDOWN = 0x0100; public const int WM_KEYUP = 0x0101; public const int WM_SYSKEYDOWN = 0x0104; public const int WM_SYSKEYUP = 0x0105; public const int WM_COMMAND = 0x0111; public const int WM_SYSCOMMAND = 0x0112; public const uint WM_CLOSE = 0x10; public const int WM_ACTIVATE = 0x0006; public const int WM_ACTIVATEAPP = 0x001C; public const int WM_NCACTIVATE = 0x0086; public const int WM_MOUSEACTIVATE = 0x0021; public const int WA_ACTIVE = 1; public const int WA_INACTIVE = 0; public const int HTCLIENT = 1; public const int WM_QUERYDRAGICON = 0x37; public const int WM_GETICON = 0x007F; public const int ICON_SMALL = 0; public const int ICON_BIG = 1; public const int ICON_SMALL2 = 2; public const int GCL_HICON = -14; public const int GCL_HICONSM = -34; public const int DISPLAY_STARTUP = 305; public const int DISPLAY_RUN_DIALOG = 401; public const int WINS_ARRANGE_HRZ = 404; public const int WINS_ARRANGE_VRT = 405; public const int WINS_MIN_ALL = 415; public const int WINS_MAX_ALL = 416; public const int SHOW_DESKTOP = 419; public const int SHOW_TASKMNG = 420; public const int CONTROL_PANEL = 505; public const int TURN_OFF_DIALOG = 506; public const int SC_MINIMIZE = 0xF020; public const int SC_MAXIMIZE = 0xF030; public const int SC_CLOSE = 0xF060; public const int SC_RESTORE = 0xF120; public const int SW_HIDE = 0; public const int SW_SHOWNORMAL = 1; public const int SW_NORMAL = 1; public const int SW_SHOWMINIMIZED = 2; public const int SW_SHOWMAXIMIZED = 3; public const int SW_MAXIMIZE = 3; public const int SW_SHOWNOACTIVATE = 4; public const int SW_SHOW = 5; public const int SW_MINIMIZE = 6; public const int SW_SHOWMINNOACTIVE = 7; public const int SW_SHOWNA = 8;//Visible but no activate public const int SW_RESTORE = 9; public const int SW_SHOWDEFAULT = 10; public const int SW_FORCEMINIMIZE = 11; public const int SW_MAX = 11; public const int WA_PREVIOUS = 40044; public const int WA_PLAY = 40045; public const int WA_PAUSE = 40046; public const int WA_STOP = 40047; public const int WA_NEXT = 40048; public const int WA_CLOSE = 40001; #endregion Constants } }
//------------------------------------------------------------------------------ // <copyright file="TransferLocation.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation // </copyright> //------------------------------------------------------------------------------ namespace Microsoft.WindowsAzure.Storage.DataMovement { using System; using System.Globalization; using System.IO; using System.Runtime.Serialization; using Microsoft.WindowsAzure.Storage.Auth; using Microsoft.WindowsAzure.Storage.Blob; using Microsoft.WindowsAzure.Storage.DataMovement.SerializationHelper; using Microsoft.WindowsAzure.Storage.File; [Serializable] internal sealed class TransferLocation : ISerializable { private const string TransferLocationTypeName = "LocationType"; private const string FilePathName = "FilePath"; private const string SourceUriName = "SourceUri"; private const string BlobName = "Blob"; private const string AzureFileName = "AzureFile"; private const string AccessConditionName = "AccessCondition"; private const string CheckedAccessConditionName = "CheckedAccessCondition"; private const string RequestOptionsName = "RequestOptions"; private const string ETagName = "ETag"; private const string BlockIDPrefixName = "BlockIDPrefix"; private SerializableAccessCondition accessCondition; private SerializableRequestOptions requestOptions; private SerializableCloudBlob blobSerializer; private SerializableCloudFile fileSerializer; private TransferLocation(SerializationInfo info, StreamingContext context) { if (info == null) { throw new System.ArgumentNullException("info"); } this.TransferLocationType = (TransferLocationType)info.GetValue(TransferLocationTypeName, typeof(TransferLocationType)); switch (this.TransferLocationType) { case TransferLocationType.FilePath: this.FilePath = info.GetString(FilePathName); break; case TransferLocationType.Stream: throw new InvalidOperationException(Resources.CannotSerializeStreamLocation); case TransferLocationType.SourceUri: this.SourceUri = (Uri)info.GetValue(SourceUriName, typeof(Uri)); break; case TransferLocationType.AzureBlob: this.blobSerializer = (SerializableCloudBlob)info.GetValue(BlobName, typeof(SerializableCloudBlob)); break; case TransferLocationType.AzureFile: this.fileSerializer = (SerializableCloudFile)info.GetValue(AzureFileName, typeof(SerializableCloudFile)); break; default: break; } this.accessCondition = (SerializableAccessCondition)info.GetValue(AccessConditionName, typeof(SerializableAccessCondition)); this.CheckedAccessCondition = info.GetBoolean(CheckedAccessConditionName); this.requestOptions = (SerializableRequestOptions)info.GetValue(RequestOptionsName, typeof(SerializableRequestOptions)); this.ETag = info.GetString(ETagName); this.BlockIdPrefix = info.GetString(BlockIDPrefixName); } /// <summary> /// Initializes a new instance of the <see cref="TransferLocation"/> class. /// </summary> /// <param name="filePath">Path to the local file as a source/destination to be read from/written to in a transfer.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1057:StringUriOverloadsCallSystemUriOverloads", Justification="We need to distinct from local file with URI")] public TransferLocation(string filePath) { if (null == filePath) { throw new ArgumentNullException("filePath"); } if (string.IsNullOrWhiteSpace(filePath)) { throw new ArgumentException("message, should not be an empty string", "filePath"); } this.FilePath = filePath; this.TransferLocationType = TransferLocationType.FilePath; } /// <summary> /// Initializes a new instance of the <see cref="TransferLocation"/> class. /// </summary> /// <param name="stream">Stream instance as a source/destination to be read from/written to in a transfer.</param> public TransferLocation(Stream stream) { if (null == stream) { throw new ArgumentNullException("stream"); } this.Stream = stream; this.TransferLocationType = TransferLocationType.Stream; } /// <summary> /// Initializes a new instance of the <see cref="TransferLocation"/> class. /// </summary> /// <param name="blob">Blob instance as a location in a transfer job. /// It could be a source, a destination.</param> public TransferLocation(CloudBlob blob) { if (null == blob) { throw new ArgumentNullException("blob"); } this.Blob = blob; this.TransferLocationType = TransferLocationType.AzureBlob; } /// <summary> /// Initializes a new instance of the <see cref="TransferLocation"/> class. /// </summary> /// <param name="azureFile">CloudFile instance as a location in a transfer job. /// It could be a source, a destination.</param> public TransferLocation(CloudFile azureFile) { if (null == azureFile) { throw new ArgumentNullException("azureFile"); } this.AzureFile = azureFile; this.TransferLocationType = TransferLocationType.AzureFile; } /// <summary> /// Initializes a new instance of the <see cref="TransferLocation"/> class. /// </summary> /// <param name="sourceUri">Uri to the source in an asynchronously copying job.</param> public TransferLocation(Uri sourceUri) { if (null == sourceUri) { throw new ArgumentNullException("sourceUri"); } this.SourceUri = sourceUri; this.TransferLocationType = TransferLocationType.SourceUri; } /// <summary> /// Gets or sets access condition for this location. /// This property only takes effact when the location is a blob or an azure file. /// </summary> public AccessCondition AccessCondition { get { return SerializableAccessCondition.GetAccessCondition(this.accessCondition); } set { SerializableAccessCondition.SetAccessCondition(ref this.accessCondition, value); } } /// <summary> /// Gets or sets request options when send request to this location. /// Only a FileRequestOptions instance takes effact when the location is an azure file; /// Only a BlobRequestOptions instance takes effact when the locaiton is a blob. /// </summary> public IRequestOptions RequestOptions { get { return SerializableRequestOptions.GetRequestOptions(this.requestOptions); } set { SerializableRequestOptions.SetRequestOptions(ref this.requestOptions, value); } } /// <summary> /// Gets the type for this location. /// </summary> public TransferLocationType TransferLocationType { get; private set; } /// <summary> /// Gets path to the local file location. /// </summary> public string FilePath { get; private set; } /// <summary> /// Gets an stream instance representing the location for this instance. /// </summary> public Stream Stream { get; private set; } /// <summary> /// Gets Uri to the source location in asynchronously copying job. /// </summary> public Uri SourceUri { get; private set; } /// <summary> /// Gets blob location in this instance. /// </summary> public CloudBlob Blob { get { return SerializableCloudBlob.GetBlob(this.blobSerializer); } private set { SerializableCloudBlob.SetBlob(ref this.blobSerializer, value); } } /// <summary> /// Gets azure file location in this instance. /// </summary> public CloudFile AzureFile { get { return SerializableCloudFile.GetFile(this.fileSerializer); } private set { SerializableCloudFile.SetFile(ref this.fileSerializer, value); } } internal string ETag { get; set; } internal bool CheckedAccessCondition { get; set; } internal BlobRequestOptions BlobRequestOptions { get { return this.RequestOptions as BlobRequestOptions; } } internal FileRequestOptions FileRequestOptions { get { return this.RequestOptions as FileRequestOptions; } } internal string BlockIdPrefix { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1057:StringUriOverloadsCallSystemUriOverloads", Justification="We need to distinct from local file with URI")] public static implicit operator TransferLocation(string filePath) { return new TransferLocation(filePath); } public static implicit operator TransferLocation(Stream stream) { return new TransferLocation(stream); } public static implicit operator TransferLocation(CloudBlockBlob blob) { return new TransferLocation(blob); } public static implicit operator TransferLocation(CloudPageBlob blob) { return new TransferLocation(blob); } public static implicit operator TransferLocation(CloudFile azureFile) { return new TransferLocation(azureFile); } public static implicit operator TransferLocation(Uri sourceUri) { return ToTransferLocation(sourceUri); } public static TransferLocation ToTransferLocation(Uri sourceUri) { return new TransferLocation(sourceUri); } /// <summary> /// Serializes the object. /// </summary> /// <param name="info">Serialization info object.</param> /// <param name="context">Streaming context.</param> public void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new System.ArgumentNullException("info"); } info.AddValue(TransferLocationTypeName, this.TransferLocationType); switch (this.TransferLocationType) { case TransferLocationType.FilePath: info.AddValue(FilePathName, this.FilePath); break; case TransferLocationType.SourceUri: info.AddValue(SourceUriName, this.SourceUri, typeof(Uri)); break; case TransferLocationType.AzureBlob: info.AddValue(BlobName, this.blobSerializer, typeof(SerializableCloudBlob)); break; case TransferLocationType.AzureFile: info.AddValue(AzureFileName, this.fileSerializer, typeof(SerializableCloudFile)); break; case TransferLocationType.Stream: default: throw new InvalidOperationException( string.Format( CultureInfo.CurrentCulture, Resources.CannotDeserializeLocationType, this.TransferLocationType)); } info.AddValue(AccessConditionName, this.accessCondition, typeof(SerializableAccessCondition)); info.AddValue(CheckedAccessConditionName, this.CheckedAccessCondition); info.AddValue(RequestOptionsName, this.requestOptions, typeof(SerializableRequestOptions)); info.AddValue(ETagName, this.ETag); info.AddValue(BlockIDPrefixName, this.BlockIdPrefix); } /// <summary> /// Update credentials of blob or azure file location. /// </summary> /// <param name="credentials">Storage credentials to be updated in blob or azure file location.</param> public void UpdateCredentials(StorageCredentials credentials) { if (null != this.blobSerializer) { this.blobSerializer.UpdateStorageCredentials(credentials); } else if (null != this.fileSerializer) { this.fileSerializer.UpdateStorageCredentials(credentials); } } // // Summary: // Returns a string that represents the transfer location. // // Returns: // A string that represents the transfer location. public override string ToString() { switch(this.TransferLocationType) { case TransferLocationType.FilePath: return this.FilePath; case TransferLocationType.AzureBlob: return this.Blob.SnapshotQualifiedUri.ToString(); case TransferLocationType.AzureFile: return this.AzureFile.Uri.ToString(); case TransferLocationType.SourceUri: return this.SourceUri.ToString(); case TransferLocationType.Stream: return this.Stream.ToString(); default: throw new ArgumentException("TransferLocationType"); } } // Summary: // Determines whether the specified transfer location is equal to the current transfer location. // // Parameters: // obj: // The transfer location to compare with the current transfer location. // // Returns: // true if the specified transfer location is equal to the current transfer location; otherwise, false. public override bool Equals(object obj) { TransferLocation location = obj as TransferLocation; if (location == null || this.TransferLocationType != location.TransferLocationType) return false; switch (this.TransferLocationType) { case TransferLocationType.AzureBlob: case TransferLocationType.AzureFile: case TransferLocationType.FilePath: case TransferLocationType.SourceUri: return this.ToString() == location.ToString(); case TransferLocationType.Stream: default: return false; } } // // Summary: // Returns the hash code for the transfer location. // // Returns: // A 32-bit signed integer hash code. public override int GetHashCode() { return this.ToString().GetHashCode(); } } }
//---------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //---------------------------------------------------------------------------- namespace System.ServiceModel.Channels { using System.Runtime; using System.ServiceModel; class ReliableChannelFactory<TChannel, InnerChannel> : ChannelFactoryBase<TChannel>, IReliableFactorySettings where InnerChannel : class, IChannel { TimeSpan acknowledgementInterval; FaultHelper faultHelper; bool flowControlEnabled; TimeSpan inactivityTimeout; int maxPendingChannels; int maxRetryCount; int maxTransferWindowSize; MessageVersion messageVersion; bool ordered; ReliableMessagingVersion reliableMessagingVersion; IChannelFactory<InnerChannel> innerChannelFactory; public ReliableChannelFactory(ReliableSessionBindingElement settings, IChannelFactory<InnerChannel> innerChannelFactory, Binding binding) : base(binding) { this.acknowledgementInterval = settings.AcknowledgementInterval; this.flowControlEnabled = settings.FlowControlEnabled; this.inactivityTimeout = settings.InactivityTimeout; this.maxPendingChannels = settings.MaxPendingChannels; this.maxRetryCount = settings.MaxRetryCount; this.maxTransferWindowSize = settings.MaxTransferWindowSize; this.messageVersion = binding.MessageVersion; this.ordered = settings.Ordered; this.reliableMessagingVersion = settings.ReliableMessagingVersion; this.innerChannelFactory = innerChannelFactory; this.faultHelper = new SendFaultHelper(binding.SendTimeout, binding.CloseTimeout); } public TimeSpan AcknowledgementInterval { get { return this.acknowledgementInterval; } } public FaultHelper FaultHelper { get { return this.faultHelper; } } public bool FlowControlEnabled { get { return this.flowControlEnabled; } } public TimeSpan InactivityTimeout { get { return this.inactivityTimeout; } } protected IChannelFactory<InnerChannel> InnerChannelFactory { get { return this.innerChannelFactory; } } public int MaxPendingChannels { get { return this.maxPendingChannels; } } public int MaxRetryCount { get { return this.maxRetryCount; } } public MessageVersion MessageVersion { get { return this.messageVersion; } } public int MaxTransferWindowSize { get { return this.maxTransferWindowSize; } } public bool Ordered { get { return this.ordered; } } public ReliableMessagingVersion ReliableMessagingVersion { get { return this.reliableMessagingVersion; } } public override T GetProperty<T>() { if (typeof(T) == typeof(IChannelFactory<TChannel>)) { return (T)(object)this; } T baseProperty = base.GetProperty<T>(); if (baseProperty != null) { return baseProperty; } return this.innerChannelFactory.GetProperty<T>(); } public TimeSpan SendTimeout { get { return this.InternalSendTimeout; } } protected override void OnAbort() { // Aborting base first to abort channels. Must abort higher channels before aborting lower channels. base.OnAbort(); this.faultHelper.Abort(); this.innerChannelFactory.Abort(); } protected override void OnOpen(TimeSpan timeout) { this.innerChannelFactory.Open(timeout); } protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { return this.innerChannelFactory.BeginOpen(callback, state); } protected override void OnEndOpen(IAsyncResult result) { this.innerChannelFactory.EndOpen(result); } protected override void OnClose(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); // Closing base first to close channels. Must close higher channels before closing lower channels. base.OnClose(timeoutHelper.RemainingTime()); this.faultHelper.Close(timeoutHelper.RemainingTime()); this.innerChannelFactory.Close(timeoutHelper.RemainingTime()); } protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { // Closing base first to close channels. Must close higher channels before closing lower channels. return OperationWithTimeoutComposer.BeginComposeAsyncOperations( timeout, new OperationWithTimeoutBeginCallback[] { new OperationWithTimeoutBeginCallback(base.OnBeginClose), new OperationWithTimeoutBeginCallback(this.faultHelper.BeginClose), new OperationWithTimeoutBeginCallback(this.innerChannelFactory.BeginClose) }, new OperationEndCallback[] { new OperationEndCallback(base.OnEndClose), new OperationEndCallback(this.faultHelper.EndClose), new OperationEndCallback(this.innerChannelFactory.EndClose) }, callback, state); } protected override void OnEndClose(IAsyncResult result) { OperationWithTimeoutComposer.EndComposeAsyncOperations(result); } protected override TChannel OnCreateChannel(EndpointAddress address, Uri via) { LateBoundChannelParameterCollection channelParameters = new LateBoundChannelParameterCollection(); IClientReliableChannelBinder binder = ClientReliableChannelBinder<InnerChannel>.CreateBinder(address, via, this.InnerChannelFactory, MaskingMode.All, TolerateFaultsMode.IfNotSecuritySession, channelParameters, this.DefaultCloseTimeout, this.DefaultSendTimeout); if (typeof(TChannel) == typeof(IOutputSessionChannel)) { if (typeof(InnerChannel) == typeof(IDuplexChannel) || typeof(InnerChannel) == typeof(IDuplexSessionChannel)) return (TChannel)(object)new ReliableOutputSessionChannelOverDuplex(this, this, binder, this.faultHelper, channelParameters); // typeof(InnerChannel) == typeof(IRequestChannel) || typeof(InnerChannel) == typeof(IRequestSessionChannel)) return (TChannel)(object)new ReliableOutputSessionChannelOverRequest(this, this, binder, this.faultHelper, channelParameters); } else if (typeof(TChannel) == typeof(IDuplexSessionChannel)) { return (TChannel)(object)new ClientReliableDuplexSessionChannel(this, this, binder, this.faultHelper, channelParameters, WsrmUtilities.NextSequenceId()); } // (typeof(TChannel) == typeof(IRequestSessionChannel) return (TChannel)(object)new ReliableRequestSessionChannel(this, this, binder, this.faultHelper, channelParameters, WsrmUtilities.NextSequenceId()); } } }
// 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.Linq; using System.Collections; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; using Xunit; namespace System.Security.Cryptography.X509Certificates.Tests { public static class CollectionTests { [Fact] public static void X509CertificateCollectionsProperties() { IList ilist = new X509CertificateCollection(); Assert.False(ilist.IsSynchronized); Assert.False(ilist.IsFixedSize); Assert.False(ilist.IsReadOnly); ilist = new X509Certificate2Collection(); Assert.False(ilist.IsSynchronized); Assert.False(ilist.IsFixedSize); Assert.False(ilist.IsReadOnly); } [Fact] public static void X509CertificateCollectionConstructors() { using (X509Certificate c1 = new X509Certificate()) using (X509Certificate c2 = new X509Certificate()) using (X509Certificate c3 = new X509Certificate()) { X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 }); Assert.Equal(3, cc.Count); Assert.Same(c1, cc[0]); Assert.Same(c2, cc[1]); Assert.Same(c3, cc[2]); X509CertificateCollection cc2 = new X509CertificateCollection(cc); Assert.Equal(3, cc2.Count); Assert.Same(c1, cc2[0]); Assert.Same(c2, cc2[1]); Assert.Same(c3, cc2[2]); Assert.Throws<ArgumentNullException>(() => new X509CertificateCollection(new X509Certificate[] { c1, c2, null, c3 })); } } [Fact] public static void X509Certificate2CollectionConstructors() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) using (X509Certificate2 c3 = new X509Certificate2()) { X509Certificate2Collection cc = new X509Certificate2Collection(new X509Certificate2[] { c1, c2, c3 }); Assert.Equal(3, cc.Count); Assert.Same(c1, cc[0]); Assert.Same(c2, cc[1]); Assert.Same(c3, cc[2]); X509Certificate2Collection cc2 = new X509Certificate2Collection(cc); Assert.Equal(3, cc2.Count); Assert.Same(c1, cc2[0]); Assert.Same(c2, cc2[1]); Assert.Same(c3, cc2[2]); Assert.Throws<ArgumentNullException>(() => new X509Certificate2Collection(new X509Certificate2[] { c1, c2, null, c3 })); using (X509Certificate c4 = new X509Certificate()) { X509Certificate2Collection collection = new X509Certificate2Collection { c1, c2, c3 }; ((IList)collection).Add(c4); // Add non-X509Certificate2 object Assert.Throws<InvalidCastException>(() => new X509Certificate2Collection(collection)); } } } [Fact] public static void X509Certificate2CollectionEnumerator() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) using (X509Certificate2 c3 = new X509Certificate2()) { X509Certificate2Collection cc = new X509Certificate2Collection(new X509Certificate2[] { c1, c2, c3 }); object ignored; X509Certificate2Enumerator e = cc.GetEnumerator(); for (int i = 0; i < 2; i++) { // Not started Assert.Throws<InvalidOperationException>(() => ignored = e.Current); Assert.True(e.MoveNext()); Assert.Same(c1, e.Current); Assert.True(e.MoveNext()); Assert.Same(c2, e.Current); Assert.True(e.MoveNext()); Assert.Same(c3, e.Current); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); // Ended Assert.Throws<InvalidOperationException>(() => ignored = e.Current); e.Reset(); } IEnumerator e2 = cc.GetEnumerator(); TestNonGenericEnumerator(e2, c1, c2, c3); IEnumerator e3 = ((IEnumerable)cc).GetEnumerator(); TestNonGenericEnumerator(e3, c1, c2, c3); } } [Fact] public static void X509CertificateCollectionEnumerator() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) using (X509Certificate2 c3 = new X509Certificate2()) { X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 }); object ignored; X509CertificateCollection.X509CertificateEnumerator e = cc.GetEnumerator(); for (int i = 0; i < 2; i++) { // Not started Assert.Throws<InvalidOperationException>(() => ignored = e.Current); Assert.True(e.MoveNext()); Assert.Same(c1, e.Current); Assert.True(e.MoveNext()); Assert.Same(c2, e.Current); Assert.True(e.MoveNext()); Assert.Same(c3, e.Current); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); // Ended Assert.Throws<InvalidOperationException>(() => ignored = e.Current); e.Reset(); } IEnumerator e2 = cc.GetEnumerator(); TestNonGenericEnumerator(e2, c1, c2, c3); IEnumerator e3 = ((IEnumerable)cc).GetEnumerator(); TestNonGenericEnumerator(e3, c1, c2, c3); } } private static void TestNonGenericEnumerator(IEnumerator e, object c1, object c2, object c3) { object ignored; for (int i = 0; i < 2; i++) { // Not started Assert.Throws<InvalidOperationException>(() => ignored = e.Current); Assert.True(e.MoveNext()); Assert.Same(c1, e.Current); Assert.True(e.MoveNext()); Assert.Same(c2, e.Current); Assert.True(e.MoveNext()); Assert.Same(c3, e.Current); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); // Ended Assert.Throws<InvalidOperationException>(() => ignored = e.Current); e.Reset(); } } [Fact] public static void X509CertificateCollectionThrowsArgumentNullException() { using (X509Certificate certificate = new X509Certificate()) { Assert.Throws<ArgumentNullException>(() => new X509CertificateCollection((X509Certificate[])null)); Assert.Throws<ArgumentNullException>(() => new X509CertificateCollection((X509CertificateCollection)null)); X509CertificateCollection collection = new X509CertificateCollection { certificate }; Assert.Throws<ArgumentNullException>(() => collection[0] = null); Assert.Throws<ArgumentNullException>(() => collection.Add(null)); Assert.Throws<ArgumentNullException>(() => collection.AddRange((X509Certificate[])null)); Assert.Throws<ArgumentNullException>(() => collection.AddRange((X509CertificateCollection)null)); Assert.Throws<ArgumentNullException>(() => collection.CopyTo(null, 0)); Assert.Throws<ArgumentNullException>(() => collection.Insert(0, null)); Assert.Throws<ArgumentNullException>(() => collection.Remove(null)); IList ilist = (IList)collection; Assert.Throws<ArgumentNullException>(() => ilist[0] = null); Assert.Throws<ArgumentNullException>(() => ilist.Add(null)); Assert.Throws<ArgumentNullException>(() => ilist.CopyTo(null, 0)); Assert.Throws<ArgumentNullException>(() => ilist.Insert(0, null)); Assert.Throws<ArgumentNullException>(() => ilist.Remove(null)); } AssertExtensions.Throws<ArgumentNullException, NullReferenceException>( () => new X509CertificateCollection.X509CertificateEnumerator(null)); } [Fact] public static void X509Certificate2CollectionThrowsArgumentNullException() { using (X509Certificate2 certificate = new X509Certificate2()) { Assert.Throws<ArgumentNullException>(() => new X509Certificate2Collection((X509Certificate2[])null)); Assert.Throws<ArgumentNullException>(() => new X509Certificate2Collection((X509Certificate2Collection)null)); X509Certificate2Collection collection = new X509Certificate2Collection { certificate }; Assert.Throws<ArgumentNullException>(() => collection[0] = null); Assert.Throws<ArgumentNullException>(() => collection.Add((X509Certificate)null)); Assert.Throws<ArgumentNullException>(() => collection.Add((X509Certificate2)null)); Assert.Throws<ArgumentNullException>(() => collection.AddRange((X509Certificate[])null)); Assert.Throws<ArgumentNullException>(() => collection.AddRange((X509CertificateCollection)null)); Assert.Throws<ArgumentNullException>(() => collection.AddRange((X509Certificate2[])null)); Assert.Throws<ArgumentNullException>(() => collection.AddRange((X509Certificate2Collection)null)); Assert.Throws<ArgumentNullException>(() => collection.CopyTo(null, 0)); Assert.Throws<ArgumentNullException>(() => collection.Insert(0, (X509Certificate)null)); Assert.Throws<ArgumentNullException>(() => collection.Insert(0, (X509Certificate2)null)); Assert.Throws<ArgumentNullException>(() => collection.Remove((X509Certificate)null)); Assert.Throws<ArgumentNullException>(() => collection.Remove((X509Certificate2)null)); Assert.Throws<ArgumentNullException>(() => collection.RemoveRange((X509Certificate2[])null)); Assert.Throws<ArgumentNullException>(() => collection.RemoveRange((X509Certificate2Collection)null)); Assert.Throws<ArgumentNullException>(() => collection.Import((byte[])null)); Assert.Throws<ArgumentNullException>(() => collection.Import((string)null)); IList ilist = (IList)collection; Assert.Throws<ArgumentNullException>(() => ilist[0] = null); Assert.Throws<ArgumentNullException>(() => ilist.Add(null)); Assert.Throws<ArgumentNullException>(() => ilist.CopyTo(null, 0)); Assert.Throws<ArgumentNullException>(() => ilist.Insert(0, null)); Assert.Throws<ArgumentNullException>(() => ilist.Remove(null)); } } [Fact] public static void X509CertificateCollectionThrowsArgumentOutOfRangeException() { using (X509Certificate certificate = new X509Certificate()) { X509CertificateCollection collection = new X509CertificateCollection { certificate }; Assert.Throws<ArgumentOutOfRangeException>(() => collection[-1]); Assert.Throws<ArgumentOutOfRangeException>(() => collection[collection.Count]); Assert.Throws<ArgumentOutOfRangeException>(() => collection[-1] = certificate); Assert.Throws<ArgumentOutOfRangeException>(() => collection[collection.Count] = certificate); Assert.Throws<ArgumentOutOfRangeException>(() => collection.Insert(-1, certificate)); Assert.Throws<ArgumentOutOfRangeException>(() => collection.Insert(collection.Count + 1, certificate)); Assert.Throws<ArgumentOutOfRangeException>(() => collection.RemoveAt(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => collection.RemoveAt(collection.Count)); IList ilist = (IList)collection; Assert.Throws<ArgumentOutOfRangeException>(() => ilist[-1]); Assert.Throws<ArgumentOutOfRangeException>(() => ilist[collection.Count]); Assert.Throws<ArgumentOutOfRangeException>(() => ilist[-1] = certificate); Assert.Throws<ArgumentOutOfRangeException>(() => ilist[collection.Count] = certificate); Assert.Throws<ArgumentOutOfRangeException>(() => ilist.Insert(-1, certificate)); Assert.Throws<ArgumentOutOfRangeException>(() => ilist.Insert(collection.Count + 1, certificate)); Assert.Throws<ArgumentOutOfRangeException>(() => ilist.RemoveAt(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => ilist.RemoveAt(collection.Count)); } } [Fact] public static void X509Certificate2CollectionThrowsArgumentOutOfRangeException() { using (X509Certificate2 certificate = new X509Certificate2()) { X509Certificate2Collection collection = new X509Certificate2Collection { certificate }; Assert.Throws<ArgumentOutOfRangeException>(() => collection[-1]); Assert.Throws<ArgumentOutOfRangeException>(() => collection[collection.Count]); Assert.Throws<ArgumentOutOfRangeException>(() => collection[-1] = certificate); Assert.Throws<ArgumentOutOfRangeException>(() => collection[collection.Count] = certificate); Assert.Throws<ArgumentOutOfRangeException>(() => collection.Insert(-1, certificate)); Assert.Throws<ArgumentOutOfRangeException>(() => collection.Insert(collection.Count + 1, certificate)); Assert.Throws<ArgumentOutOfRangeException>(() => collection.RemoveAt(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => collection.RemoveAt(collection.Count)); IList ilist = (IList)collection; Assert.Throws<ArgumentOutOfRangeException>(() => ilist[-1]); Assert.Throws<ArgumentOutOfRangeException>(() => ilist[collection.Count]); Assert.Throws<ArgumentOutOfRangeException>(() => ilist[-1] = certificate); Assert.Throws<ArgumentOutOfRangeException>(() => ilist[collection.Count] = certificate); Assert.Throws<ArgumentOutOfRangeException>(() => ilist.Insert(-1, certificate)); Assert.Throws<ArgumentOutOfRangeException>(() => ilist.Insert(collection.Count + 1, certificate)); Assert.Throws<ArgumentOutOfRangeException>(() => ilist.RemoveAt(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => ilist.RemoveAt(collection.Count)); } } [Fact] public static void X509CertificateCollectionContains() { using (X509Certificate c1 = new X509Certificate()) using (X509Certificate c2 = new X509Certificate()) using (X509Certificate c3 = new X509Certificate()) { X509CertificateCollection collection = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 }); Assert.True(collection.Contains(c1)); Assert.True(collection.Contains(c2)); Assert.True(collection.Contains(c3)); Assert.False(collection.Contains(null)); IList ilist = (IList)collection; Assert.True(ilist.Contains(c1)); Assert.True(ilist.Contains(c2)); Assert.True(ilist.Contains(c3)); Assert.False(ilist.Contains(null)); Assert.False(ilist.Contains("Bogus")); } } [Fact] public static void X509Certificate2CollectionContains() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) using (X509Certificate2 c3 = new X509Certificate2()) { X509Certificate2Collection collection = new X509Certificate2Collection(new X509Certificate2[] { c1, c2, c3 }); Assert.True(collection.Contains(c1)); Assert.True(collection.Contains(c2)); Assert.True(collection.Contains(c3)); // Note: X509Certificate2Collection.Contains used to throw ArgumentNullException, but it // has been deliberately changed to no longer throw to match the behavior of // X509CertificateCollection.Contains and the IList.Contains implementation, which do not // throw. Assert.False(collection.Contains(null)); IList ilist = (IList)collection; Assert.True(ilist.Contains(c1)); Assert.True(ilist.Contains(c2)); Assert.True(ilist.Contains(c3)); Assert.False(ilist.Contains(null)); Assert.False(ilist.Contains("Bogus")); } } [Fact] public static void X509CertificateCollectionEnumeratorModification() { using (X509Certificate c1 = new X509Certificate()) using (X509Certificate c2 = new X509Certificate()) using (X509Certificate c3 = new X509Certificate()) { X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 }); X509CertificateCollection.X509CertificateEnumerator e = cc.GetEnumerator(); cc.Add(c1); // Collection changed. Assert.Throws<InvalidOperationException>(() => e.MoveNext()); Assert.Throws<InvalidOperationException>(() => e.Reset()); } } [Fact] public static void X509Certificate2CollectionEnumeratorModification() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) using (X509Certificate2 c3 = new X509Certificate2()) { X509Certificate2Collection cc = new X509Certificate2Collection(new X509Certificate2[] { c1, c2, c3 }); X509Certificate2Enumerator e = cc.GetEnumerator(); cc.Add(c1); // Collection changed. Assert.Throws<InvalidOperationException>(() => e.MoveNext()); Assert.Throws<InvalidOperationException>(() => e.Reset()); } } [Fact] public static void X509CertificateCollectionAdd() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) { X509CertificateCollection cc = new X509CertificateCollection(); int idx = cc.Add(c1); Assert.Equal(0, idx); Assert.Same(c1, cc[0]); idx = cc.Add(c2); Assert.Equal(1, idx); Assert.Same(c2, cc[1]); Assert.Throws<ArgumentNullException>(() => cc.Add(null)); IList il = new X509CertificateCollection(); idx = il.Add(c1); Assert.Equal(0, idx); Assert.Same(c1, il[0]); idx = il.Add(c2); Assert.Equal(1, idx); Assert.Same(c2, il[1]); Assert.Throws<ArgumentNullException>(() => il.Add(null)); } } [Fact] public static void X509CertificateCollectionAsIList() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) { IList il = new X509CertificateCollection(); il.Add(c1); il.Add(c2); Assert.Throws<ArgumentNullException>(() => il[0] = null); } } [Fact] // On Desktop, list is untyped so it allows arbitrary types in it public static void X509CertificateCollectionAsIListBogusEntry() { using (X509Certificate2 c = new X509Certificate2()) { IList il = new X509CertificateCollection(); il.Add(c); string bogus = "Bogus"; AssertExtensions.Throws<ArgumentException>("value", () => il[0] = bogus); AssertExtensions.Throws<ArgumentException>("value", () => il.Add(bogus)); AssertExtensions.Throws<ArgumentException>("value", () => il.Remove(bogus)); AssertExtensions.Throws<ArgumentException>("value", () => il.Insert(0, bogus)); } } [Fact] public static void AddDoesNotClone() { using (X509Certificate2 c1 = new X509Certificate2()) { X509Certificate2Collection coll = new X509Certificate2Collection(); coll.Add(c1); Assert.Same(c1, coll[0]); } } [Fact] public static void ImportStoreSavedAsCerData() { using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword)) { using (ImportedCollection ic = Cert.Import(TestData.StoreSavedAsCerData)) { X509Certificate2Collection cc2 = ic.Collection; int count = cc2.Count; Assert.Equal(1, count); using (X509Certificate2 c = cc2[0]) { // pfxCer was loaded directly, cc2[0] was Imported, two distinct copies. Assert.NotSame(pfxCer, c); Assert.Equal(pfxCer, c); Assert.Equal(pfxCer.Thumbprint, c.Thumbprint); } } } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // StoreSavedAsSerializedCerData not supported on Unix public static void ImportStoreSavedAsSerializedCerData_Windows() { using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, Cert.EphemeralIfPossible)) { using (ImportedCollection ic = Cert.Import(TestData.StoreSavedAsSerializedCerData)) { X509Certificate2Collection cc2 = ic.Collection; int count = cc2.Count; Assert.Equal(1, count); using (X509Certificate2 c = cc2[0]) { // pfxCer was loaded directly, cc2[0] was Imported, two distinct copies. Assert.NotSame(pfxCer, c); Assert.Equal(pfxCer, c); Assert.Equal(pfxCer.Thumbprint, c.Thumbprint); } } } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // StoreSavedAsSerializedCerData not supported on Unix public static void ImportStoreSavedAsSerializedCerData_Unix() { X509Certificate2Collection cc2 = new X509Certificate2Collection(); Assert.ThrowsAny<CryptographicException>(() => cc2.Import(TestData.StoreSavedAsSerializedCerData)); Assert.Equal(0, cc2.Count); } [Theory] [MemberData(nameof(StorageFlags))] [PlatformSpecific(TestPlatforms.Windows)] // StoreSavedAsSerializedStoreData not supported on Unix public static void ImportStoreSavedAsSerializedStoreData_Windows(X509KeyStorageFlags keyStorageFlags) { using (var msCer = new X509Certificate2(TestData.MsCertificate)) using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, keyStorageFlags)) using (ImportedCollection ic = Cert.Import(TestData.StoreSavedAsSerializedStoreData)) { X509Certificate2Collection cc2 = ic.Collection; int count = cc2.Count; Assert.Equal(2, count); X509Certificate2[] cs = cc2.ToArray().OrderBy(c => c.Subject).ToArray(); Assert.NotSame(msCer, cs[0]); Assert.Equal(msCer, cs[0]); Assert.Equal(msCer.Thumbprint, cs[0].Thumbprint); Assert.NotSame(pfxCer, cs[1]); Assert.Equal(pfxCer, cs[1]); Assert.Equal(pfxCer.Thumbprint, cs[1].Thumbprint); } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // StoreSavedAsSerializedStoreData not supported on Unix public static void ImportStoreSavedAsSerializedStoreData_Unix() { X509Certificate2Collection cc2 = new X509Certificate2Collection(); Assert.ThrowsAny<CryptographicException>(() => cc2.Import(TestData.StoreSavedAsSerializedStoreData)); Assert.Equal(0, cc2.Count); } [Fact] public static void ImportStoreSavedAsPfxData() { using (var msCer = new X509Certificate2(TestData.MsCertificate)) using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, Cert.EphemeralIfPossible)) using (ImportedCollection ic = Cert.Import(TestData.StoreSavedAsPfxData)) { X509Certificate2Collection cc2 = ic.Collection; int count = cc2.Count; Assert.Equal(2, count); X509Certificate2[] cs = cc2.ToArray().OrderBy(c => c.Subject).ToArray(); Assert.NotSame(msCer, cs[0]); Assert.Equal(msCer, cs[0]); Assert.Equal(msCer.Thumbprint, cs[0].Thumbprint); Assert.NotSame(pfxCer, cs[1]); Assert.Equal(pfxCer, cs[1]); Assert.Equal(pfxCer.Thumbprint, cs[1].Thumbprint); } } [Fact] public static void ImportInvalidData() { X509Certificate2Collection cc2 = new X509Certificate2Collection(); Assert.ThrowsAny<CryptographicException>(() => cc2.Import(new byte[] { 0, 1, 1, 2, 3, 5, 8, 13, 21 })); } [Theory] [MemberData(nameof(StorageFlags))] public static void ImportFromFileTests(X509KeyStorageFlags storageFlags) { using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, storageFlags)) { using (ImportedCollection ic = Cert.Import(Path.Combine("TestData", "My.pfx"), TestData.PfxDataPassword, storageFlags)) { X509Certificate2Collection cc2 = ic.Collection; int count = cc2.Count; Assert.Equal(1, count); using (X509Certificate2 c = cc2[0]) { // pfxCer was loaded directly, cc2[0] was Imported, two distinct copies. Assert.NotSame(pfxCer, c); Assert.Equal(pfxCer, c); Assert.Equal(pfxCer.Thumbprint, c.Thumbprint); } } } } [Fact] [ActiveIssue(2745, TestPlatforms.AnyUnix)] public static void ImportMultiplePrivateKeysPfx() { using (ImportedCollection ic = Cert.Import(TestData.MultiPrivateKeyPfx)) { X509Certificate2Collection collection = ic.Collection; Assert.Equal(2, collection.Count); foreach (X509Certificate2 cert in collection) { Assert.True(cert.HasPrivateKey, "cert.HasPrivateKey"); } } } [Fact] public static void ExportCert() { TestExportSingleCert(X509ContentType.Cert); } [Fact] public static void ExportCert_SecureString() { TestExportSingleCert_SecureStringPassword(X509ContentType.Cert); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // SerializedCert not supported on Unix public static void ExportSerializedCert_Windows() { TestExportSingleCert(X509ContentType.SerializedCert); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // SerializedCert not supported on Unix public static void ExportSerializedCert_Unix() { using (var msCer = new X509Certificate2(TestData.MsCertificate)) using (var ecdsa256Cer = new X509Certificate2(TestData.ECDsa256Certificate)) { X509Certificate2Collection cc = new X509Certificate2Collection(new[] { msCer, ecdsa256Cer }); Assert.Throws<PlatformNotSupportedException>(() => cc.Export(X509ContentType.SerializedCert)); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // SerializedStore not supported on Unix public static void ExportSerializedStore_Windows() { TestExportStore(X509ContentType.SerializedStore); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // SerializedStore not supported on Unix public static void ExportSerializedStore_Unix() { using (var msCer = new X509Certificate2(TestData.MsCertificate)) using (var ecdsa256Cer = new X509Certificate2(TestData.ECDsa256Certificate)) { X509Certificate2Collection cc = new X509Certificate2Collection(new[] { msCer, ecdsa256Cer }); Assert.Throws<PlatformNotSupportedException>(() => cc.Export(X509ContentType.SerializedStore)); } } [Fact] public static void ExportPkcs7() { TestExportStore(X509ContentType.Pkcs7); } [Fact] public static void X509CertificateCollectionSyncRoot() { var cc = new X509CertificateCollection(); Assert.NotNull(((ICollection)cc).SyncRoot); Assert.Same(((ICollection)cc).SyncRoot, ((ICollection)cc).SyncRoot); } [Fact] public static void ExportEmpty_Cert() { var collection = new X509Certificate2Collection(); byte[] exported = collection.Export(X509ContentType.Cert); Assert.Null(exported); } [Fact] [ActiveIssue(2746, TestPlatforms.AnyUnix)] public static void ExportEmpty_Pkcs12() { var collection = new X509Certificate2Collection(); byte[] exported = collection.Export(X509ContentType.Pkcs12); // The empty PFX is legal, the answer won't be null. Assert.NotNull(exported); } [Fact] [ActiveIssue(16705, TestPlatforms.OSX)] public static void ExportUnrelatedPfx() { // Export multiple certificates which are not part of any kind of certificate chain. // Nothing in the PKCS12 structure requires they're related, but it might be an underlying // assumption of the provider. using (var cert1 = new X509Certificate2(TestData.MsCertificate)) using (var cert2 = new X509Certificate2(TestData.ComplexNameInfoCert)) using (var cert3 = new X509Certificate2(TestData.CertWithPolicies)) { var collection = new X509Certificate2Collection { cert1, cert2, cert3, }; byte[] exported = collection.Export(X509ContentType.Pkcs12); using (ImportedCollection ic = Cert.Import(exported)) { X509Certificate2Collection importedCollection = ic.Collection; // Verify that the two collections contain the same certificates, // but the order isn't really a factor. Assert.Equal(collection.Count, importedCollection.Count); // Compare just the subject names first, because it's the easiest thing to read out of the failure message. string[] subjects = new string[collection.Count]; string[] importedSubjects = new string[collection.Count]; for (int i = 0; i < collection.Count; i++) { subjects[i] = collection[i].GetNameInfo(X509NameType.SimpleName, false); importedSubjects[i] = importedCollection[i].GetNameInfo(X509NameType.SimpleName, false); } Assert.Equal(subjects, importedSubjects); // But, really, the collections should be equivalent // (after being coerced to IEnumerable<X509Certificate2>) Assert.Equal(collection.OfType<X509Certificate2>(), importedCollection.OfType<X509Certificate2>()); } } } [Fact] public static void MultipleImport() { var collection = new X509Certificate2Collection(); try { collection.Import(Path.Combine("TestData", "DummyTcpServer.pfx"), (string)null, Cert.EphemeralIfPossible); collection.Import(TestData.PfxData, TestData.PfxDataPassword, Cert.EphemeralIfPossible); Assert.Equal(3, collection.Count); } finally { foreach (X509Certificate2 cert in collection) { cert.Dispose(); } } } [Fact] [ActiveIssue(2743, TestPlatforms.AnyUnix & ~TestPlatforms.OSX)] public static void ExportMultiplePrivateKeys() { var collection = new X509Certificate2Collection(); try { collection.Import(Path.Combine("TestData", "DummyTcpServer.pfx"), (string)null, X509KeyStorageFlags.Exportable | Cert.EphemeralIfPossible); collection.Import(TestData.PfxData, TestData.PfxDataPassword, X509KeyStorageFlags.Exportable | Cert.EphemeralIfPossible); // Pre-condition, we have multiple private keys int originalPrivateKeyCount = collection.OfType<X509Certificate2>().Count(c => c.HasPrivateKey); Assert.Equal(2, originalPrivateKeyCount); // Export, re-import. byte[] exported; bool expectSuccess = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX); try { exported = collection.Export(X509ContentType.Pkcs12); } catch (PlatformNotSupportedException) { // [ActiveIssue(2743, TestPlatforms.AnyUnix)] // Our Unix builds can't export more than one private key in a single PFX, so this is // their exit point. // // If Windows gets here, or any exception other than PlatformNotSupportedException is raised, // let that fail the test. if (expectSuccess) { throw; } return; } // As the other half of issue 2743, if we make it this far we better be Windows (or remove the catch // above) Assert.True(expectSuccess, "Test is expected to fail on this platform"); using (ImportedCollection ic = Cert.Import(exported)) { X509Certificate2Collection importedCollection = ic.Collection; Assert.Equal(collection.Count, importedCollection.Count); int importedPrivateKeyCount = importedCollection.OfType<X509Certificate2>().Count(c => c.HasPrivateKey); Assert.Equal(originalPrivateKeyCount, importedPrivateKeyCount); } } finally { foreach (X509Certificate2 cert in collection) { cert.Dispose(); } } } [Fact] [ActiveIssue(26397, TestPlatforms.OSX)] public static void CanAddMultipleCertsWithSinglePrivateKey() { using (var oneWithKey = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, X509KeyStorageFlags.Exportable | Cert.EphemeralIfPossible)) using (var twoWithoutKey = new X509Certificate2(TestData.ComplexNameInfoCert)) { Assert.True(oneWithKey.HasPrivateKey); var col = new X509Certificate2Collection { oneWithKey, twoWithoutKey, }; Assert.Equal(1, col.Cast<X509Certificate2>().Count(x => x.HasPrivateKey)); Assert.Equal(2, col.Count); byte[] buffer = col.Export(X509ContentType.Pfx); using (ImportedCollection newCollection = Cert.Import(buffer)) { Assert.Equal(2, newCollection.Collection.Count); } } } [Fact] public static void X509CertificateCollectionCopyTo() { using (X509Certificate c1 = new X509Certificate()) using (X509Certificate c2 = new X509Certificate()) using (X509Certificate c3 = new X509Certificate()) { X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 }); X509Certificate[] array1 = new X509Certificate[cc.Count]; cc.CopyTo(array1, 0); Assert.Same(c1, array1[0]); Assert.Same(c2, array1[1]); Assert.Same(c3, array1[2]); X509Certificate[] array2 = new X509Certificate[cc.Count]; ((ICollection)cc).CopyTo(array2, 0); Assert.Same(c1, array2[0]); Assert.Same(c2, array2[1]); Assert.Same(c3, array2[2]); } } [Fact] public static void X509ChainElementCollection_CopyTo_NonZeroLowerBound_ThrowsIndexOutOfRangeException() { using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes)) using (var microsoftDotComIssuer = new X509Certificate2(TestData.MicrosoftDotComIssuerBytes)) using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes)) using (var chainHolder = new ChainHolder()) { X509Chain chain = chainHolder.Chain; chain.ChainPolicy.ExtraStore.Add(microsoftDotComRoot); chain.ChainPolicy.ExtraStore.Add(microsoftDotComIssuer); chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags; chain.Build(microsoftDotCom); ICollection collection = chain.ChainElements; Array array = Array.CreateInstance(typeof(object), new int[] { 10 }, new int[] { 10 }); Assert.Throws<IndexOutOfRangeException>(() => collection.CopyTo(array, 0)); } } [Fact] public static void X509ExtensionCollection_CopyTo_NonZeroLowerBound_ThrowsIndexOutOfRangeException() { using (X509Certificate2 cert = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, Cert.EphemeralIfPossible)) { ICollection collection = cert.Extensions; Array array = Array.CreateInstance(typeof(object), new int[] { 10 }, new int[] { 10 }); Assert.Throws<IndexOutOfRangeException>(() => collection.CopyTo(array, 0)); } } [Fact] public static void X509CertificateCollectionIndexOf() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, Cert.EphemeralIfPossible)) { X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2 }); Assert.Equal(0, cc.IndexOf(c1)); Assert.Equal(1, cc.IndexOf(c2)); IList il = cc; Assert.Equal(0, il.IndexOf(c1)); Assert.Equal(1, il.IndexOf(c2)); } } [Fact] public static void X509CertificateCollectionRemove() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, Cert.EphemeralIfPossible)) { X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2 }); cc.Remove(c1); Assert.Equal(1, cc.Count); Assert.Same(c2, cc[0]); cc.Remove(c2); Assert.Equal(0, cc.Count); AssertExtensions.Throws<ArgumentException>(null, () => cc.Remove(c2)); IList il = new X509CertificateCollection(new X509Certificate[] { c1, c2 }); il.Remove(c1); Assert.Equal(1, il.Count); Assert.Same(c2, il[0]); il.Remove(c2); Assert.Equal(0, il.Count); AssertExtensions.Throws<ArgumentException>(null, () => il.Remove(c2)); } } [Fact] public static void X509CertificateCollectionRemoveAt() { using (X509Certificate c1 = new X509Certificate()) using (X509Certificate c2 = new X509Certificate()) using (X509Certificate c3 = new X509Certificate()) { X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 }); cc.RemoveAt(0); Assert.Equal(2, cc.Count); Assert.Same(c2, cc[0]); Assert.Same(c3, cc[1]); cc.RemoveAt(1); Assert.Equal(1, cc.Count); Assert.Same(c2, cc[0]); cc.RemoveAt(0); Assert.Equal(0, cc.Count); IList il = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 }); il.RemoveAt(0); Assert.Equal(2, il.Count); Assert.Same(c2, il[0]); Assert.Same(c3, il[1]); il.RemoveAt(1); Assert.Equal(1, il.Count); Assert.Same(c2, il[0]); il.RemoveAt(0); Assert.Equal(0, il.Count); } } [Fact] public static void X509Certificate2CollectionRemoveRangeArray() { using (X509Certificate2 c1 = new X509Certificate2(TestData.MsCertificate)) using (X509Certificate2 c2 = new X509Certificate2(TestData.DssCer)) using (X509Certificate2 c1Clone = new X509Certificate2(TestData.MsCertificate)) { X509Certificate2[] array = new X509Certificate2[] { c1, c2 }; X509Certificate2Collection cc = new X509Certificate2Collection(array); cc.RemoveRange(array); Assert.Equal(0, cc.Count); cc = new X509Certificate2Collection(array); cc.RemoveRange(new X509Certificate2[] { c2, c1 }); Assert.Equal(0, cc.Count); cc = new X509Certificate2Collection(array); cc.RemoveRange(new X509Certificate2[] { c1 }); Assert.Equal(1, cc.Count); Assert.Same(c2, cc[0]); cc = new X509Certificate2Collection(array); Assert.Throws<ArgumentNullException>(() => cc.RemoveRange(new X509Certificate2[] { c1, c2, null })); Assert.Equal(2, cc.Count); Assert.Same(c1, cc[0]); Assert.Same(c2, cc[1]); cc = new X509Certificate2Collection(array); Assert.Throws<ArgumentNullException>(() => cc.RemoveRange(new X509Certificate2[] { c1, null, c2 })); Assert.Equal(2, cc.Count); Assert.Same(c2, cc[0]); Assert.Same(c1, cc[1]); // Remove c1Clone (success) // Remove c1 (exception) // Add c1Clone back // End state: { c1, c2 } => { c2, c1Clone } cc = new X509Certificate2Collection(array); AssertExtensions.Throws<ArgumentException>(null, () => cc.RemoveRange(new X509Certificate2[] { c1Clone, c1, c2 })); Assert.Equal(2, cc.Count); Assert.Same(c2, cc[0]); Assert.Same(c1Clone, cc[1]); } } [Fact] public static void X509Certificate2CollectionRemoveRangeCollection() { using (X509Certificate2 c1 = new X509Certificate2(TestData.MsCertificate)) using (X509Certificate2 c2 = new X509Certificate2(TestData.DssCer)) using (X509Certificate2 c1Clone = new X509Certificate2(TestData.MsCertificate)) using (X509Certificate c3 = new X509Certificate()) { X509Certificate2[] array = new X509Certificate2[] { c1, c2 }; X509Certificate2Collection cc = new X509Certificate2Collection(array); cc.RemoveRange(new X509Certificate2Collection { c1, c2 }); Assert.Equal(0, cc.Count); cc = new X509Certificate2Collection(array); cc.RemoveRange(new X509Certificate2Collection { c2, c1 }); Assert.Equal(0, cc.Count); cc = new X509Certificate2Collection(array); cc.RemoveRange(new X509Certificate2Collection { c1 }); Assert.Equal(1, cc.Count); Assert.Same(c2, cc[0]); cc = new X509Certificate2Collection(array); X509Certificate2Collection collection = new X509Certificate2Collection(); collection.Add(c1); collection.Add(c2); ((IList)collection).Add(c3); // Add non-X509Certificate2 object Assert.Throws<InvalidCastException>(() => cc.RemoveRange(collection)); Assert.Equal(2, cc.Count); Assert.Same(c1, cc[0]); Assert.Same(c2, cc[1]); cc = new X509Certificate2Collection(array); collection = new X509Certificate2Collection(); collection.Add(c1); ((IList)collection).Add(c3); // Add non-X509Certificate2 object collection.Add(c2); Assert.Throws<InvalidCastException>(() => cc.RemoveRange(collection)); Assert.Equal(2, cc.Count); Assert.Same(c2, cc[0]); Assert.Same(c1, cc[1]); // Remove c1Clone (success) // Remove c1 (exception) // Add c1Clone back // End state: { c1, c2 } => { c2, c1Clone } cc = new X509Certificate2Collection(array); collection = new X509Certificate2Collection { c1Clone, c1, c2, }; AssertExtensions.Throws<ArgumentException>(null, () => cc.RemoveRange(collection)); Assert.Equal(2, cc.Count); Assert.Same(c2, cc[0]); Assert.Same(c1Clone, cc[1]); } } [Fact] public static void X509CertificateCollectionIndexer() { using (X509Certificate c1 = new X509Certificate()) using (X509Certificate c2 = new X509Certificate()) using (X509Certificate c3 = new X509Certificate()) { X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 }); cc[0] = c3; cc[1] = c2; cc[2] = c1; Assert.Same(c3, cc[0]); Assert.Same(c2, cc[1]); Assert.Same(c1, cc[2]); IList il = cc; il[0] = c1; il[1] = c2; il[2] = c3; Assert.Same(c1, il[0]); Assert.Same(c2, il[1]); Assert.Same(c3, il[2]); } } [Fact] public static void X509Certificate2CollectionIndexer() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) using (X509Certificate2 c3 = new X509Certificate2()) { X509Certificate2Collection cc = new X509Certificate2Collection(new X509Certificate2[] { c1, c2, c3 }); cc[0] = c3; cc[1] = c2; cc[2] = c1; Assert.Same(c3, cc[0]); Assert.Same(c2, cc[1]); Assert.Same(c1, cc[2]); IList il = cc; il[0] = c1; il[1] = c2; il[2] = c3; Assert.Same(c1, il[0]); Assert.Same(c2, il[1]); Assert.Same(c3, il[2]); } } [Fact] public static void X509CertificateCollectionInsertAndClear() { using (X509Certificate c1 = new X509Certificate()) using (X509Certificate c2 = new X509Certificate()) using (X509Certificate c3 = new X509Certificate()) { X509CertificateCollection cc = new X509CertificateCollection(); cc.Insert(0, c1); cc.Insert(1, c2); cc.Insert(2, c3); Assert.Equal(3, cc.Count); Assert.Same(c1, cc[0]); Assert.Same(c2, cc[1]); Assert.Same(c3, cc[2]); cc.Clear(); Assert.Equal(0, cc.Count); cc.Add(c1); cc.Add(c3); Assert.Equal(2, cc.Count); Assert.Same(c1, cc[0]); Assert.Same(c3, cc[1]); cc.Insert(1, c2); Assert.Equal(3, cc.Count); Assert.Same(c1, cc[0]); Assert.Same(c2, cc[1]); Assert.Same(c3, cc[2]); cc.Clear(); Assert.Equal(0, cc.Count); IList il = cc; il.Insert(0, c1); il.Insert(1, c2); il.Insert(2, c3); Assert.Equal(3, il.Count); Assert.Same(c1, il[0]); Assert.Same(c2, il[1]); Assert.Same(c3, il[2]); il.Clear(); Assert.Equal(0, il.Count); il.Add(c1); il.Add(c3); Assert.Equal(2, il.Count); Assert.Same(c1, il[0]); Assert.Same(c3, il[1]); il.Insert(1, c2); Assert.Equal(3, il.Count); Assert.Same(c1, il[0]); Assert.Same(c2, il[1]); Assert.Same(c3, il[2]); il.Clear(); Assert.Equal(0, il.Count); } } [Fact] public static void X509Certificate2CollectionInsert() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) using (X509Certificate2 c3 = new X509Certificate2()) { X509Certificate2Collection cc = new X509Certificate2Collection(); cc.Insert(0, c3); cc.Insert(0, c2); cc.Insert(0, c1); Assert.Equal(3, cc.Count); Assert.Same(c1, cc[0]); Assert.Same(c2, cc[1]); Assert.Same(c3, cc[2]); } } [Fact] public static void X509Certificate2CollectionCopyTo() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) using (X509Certificate2 c3 = new X509Certificate2()) { X509Certificate2Collection cc = new X509Certificate2Collection(new X509Certificate2[] { c1, c2, c3 }); X509Certificate2[] array1 = new X509Certificate2[cc.Count]; cc.CopyTo(array1, 0); Assert.Same(c1, array1[0]); Assert.Same(c2, array1[1]); Assert.Same(c3, array1[2]); X509Certificate2[] array2 = new X509Certificate2[cc.Count]; ((ICollection)cc).CopyTo(array2, 0); Assert.Same(c1, array2[0]); Assert.Same(c2, array2[1]); Assert.Same(c3, array2[2]); } } [Fact] public static void X509CertificateCollectionGetHashCode() { using (X509Certificate c1 = new X509Certificate()) using (X509Certificate c2 = new X509Certificate()) using (X509Certificate c3 = new X509Certificate()) { X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 }); int expected = c1.GetHashCode() + c2.GetHashCode() + c3.GetHashCode(); Assert.Equal(expected, cc.GetHashCode()); } } [Fact] public static void X509Certificate2CollectionGetHashCode() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) using (X509Certificate2 c3 = new X509Certificate2()) { X509Certificate2Collection cc = new X509Certificate2Collection(new X509Certificate2[] { c1, c2, c3 }); int expected = c1.GetHashCode() + c2.GetHashCode() + c3.GetHashCode(); Assert.Equal(expected, cc.GetHashCode()); } } [Fact] public static void X509ChainElementCollection_IndexerVsEnumerator() { using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes)) using (var microsoftDotComIssuer = new X509Certificate2(TestData.MicrosoftDotComIssuerBytes)) using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes)) using (var chainHolder = new ChainHolder()) { X509Chain chain = chainHolder.Chain; chain.ChainPolicy.ExtraStore.Add(microsoftDotComRoot); chain.ChainPolicy.ExtraStore.Add(microsoftDotComIssuer); chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority; // Halfway between microsoftDotCom's NotBefore and NotAfter // This isn't a boundary condition test. chain.ChainPolicy.VerificationTime = new DateTime(2015, 10, 15, 12, 01, 01, DateTimeKind.Local); chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; bool valid = chain.Build(microsoftDotCom); Assert.True(valid, "Precondition: Chain built validly"); int position = 0; foreach (X509ChainElement chainElement in chain.ChainElements) { X509ChainElement indexerElement = chain.ChainElements[position]; Assert.NotNull(chainElement); Assert.NotNull(indexerElement); Assert.Same(indexerElement, chainElement); position++; } } } [Fact] public static void X509ExtensionCollection_OidIndexer_ByOidValue() { const string SubjectKeyIdentifierOidValue = "2.5.29.14"; using (var cert = new X509Certificate2(TestData.MsCertificate)) { X509ExtensionCollection extensions = cert.Extensions; // Stable index can be counted on by ExtensionsTests.ReadExtensions(). X509Extension skidExtension = extensions[1]; // Precondition: We've found the SKID extension. Assert.Equal(SubjectKeyIdentifierOidValue, skidExtension.Oid.Value); X509Extension byValue = extensions[SubjectKeyIdentifierOidValue]; Assert.Same(skidExtension, byValue); } } [Fact] public static void X509ExtensionCollection_OidIndexer_ByOidFriendlyName() { const string SubjectKeyIdentifierOidValue = "2.5.29.14"; using (var cert = new X509Certificate2(TestData.MsCertificate)) { X509ExtensionCollection extensions = cert.Extensions; // Stable index can be counted on by ExtensionsTests.ReadExtensions(). X509Extension skidExtension = extensions[1]; // Precondition: We've found the SKID extension. Assert.Equal(SubjectKeyIdentifierOidValue, skidExtension.Oid.Value); // The friendly name of "Subject Key Identifier" is localized, but // we can use the invariant form to ask for the friendly name to ask // for the extension by friendly name. X509Extension byFriendlyName = extensions[new Oid(SubjectKeyIdentifierOidValue).FriendlyName]; Assert.Same(skidExtension, byFriendlyName); } } [Fact] public static void X509ExtensionCollection_OidIndexer_NoMatchByValue() { const string RsaOidValue = "1.2.840.113549.1.1.1"; using (var cert = new X509Certificate2(TestData.MsCertificate)) { X509ExtensionCollection extensions = cert.Extensions; X509Extension byValue = extensions[RsaOidValue]; Assert.Null(byValue); } } [Fact] public static void X509ExtensionCollection_OidIndexer_NoMatchByFriendlyName() { const string RsaOidValue = "1.2.840.113549.1.1.1"; using (var cert = new X509Certificate2(TestData.MsCertificate)) { X509ExtensionCollection extensions = cert.Extensions; // While "RSA" is actually invariant, this just guarantees that we're doing // the system-preferred lookup. X509Extension byFriendlyName = extensions[new Oid(RsaOidValue).FriendlyName]; Assert.Null(byFriendlyName); } } private static void TestExportSingleCert_SecureStringPassword(X509ContentType ct) { using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.CreatePfxDataPasswordSecureString(), Cert.EphemeralIfPossible)) { TestExportSingleCert(ct, pfxCer); } } private static void TestExportSingleCert(X509ContentType ct) { using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, Cert.EphemeralIfPossible)) { TestExportSingleCert(ct, pfxCer); } } private static void TestExportSingleCert(X509ContentType ct, X509Certificate2 pfxCer) { using (var msCer = new X509Certificate2(TestData.MsCertificate)) { X509Certificate2Collection cc = new X509Certificate2Collection(new X509Certificate2[] { msCer, pfxCer }); byte[] blob = cc.Export(ct); Assert.Equal(ct, X509Certificate2.GetCertContentType(blob)); using (ImportedCollection ic = Cert.Import(blob)) { X509Certificate2Collection cc2 = ic.Collection; int count = cc2.Count; Assert.Equal(1, count); using (X509Certificate2 c = cc2[0]) { Assert.NotSame(msCer, c); Assert.NotSame(pfxCer, c); Assert.True(msCer.Equals(c) || pfxCer.Equals(c)); } } } } private static void TestExportStore(X509ContentType ct) { using (var msCer = new X509Certificate2(TestData.MsCertificate)) using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, Cert.EphemeralIfPossible)) { X509Certificate2Collection cc = new X509Certificate2Collection(new X509Certificate2[] { msCer, pfxCer }); byte[] blob = cc.Export(ct); Assert.Equal(ct, X509Certificate2.GetCertContentType(blob)); using (ImportedCollection ic = Cert.Import(blob)) { X509Certificate2Collection cc2 = ic.Collection; int count = cc2.Count; Assert.Equal(2, count); X509Certificate2[] cs = cc2.ToArray().OrderBy(c => c.Subject).ToArray(); using (X509Certificate2 first = cs[0]) { Assert.NotSame(msCer, first); Assert.Equal(msCer, first); } using (X509Certificate2 second = cs[1]) { Assert.NotSame(pfxCer, second); Assert.Equal(pfxCer, second); } } } } public static IEnumerable<object[]> StorageFlags => CollectionImportTests.StorageFlags; private static X509Certificate2[] ToArray(this X509Certificate2Collection col) { X509Certificate2[] array = new X509Certificate2[col.Count]; for (int i = 0; i < col.Count; i++) { array[i] = col[i]; } return array; } } }