context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System.Collections; using System.Collections.Generic; using NUnit.Framework; using XSerializer.Encryption; using XSerializer.Tests.Encryption; namespace XSerializer.Tests { public class ListJsonSerializerTests { [Test] public void CanSerializeGenericIEnumerable() { var serializer = new JsonSerializer<List<string>>(); var json = serializer.Serialize(new List<string> { "abc", "xyz" }); Assert.That(json, Is.EqualTo(@"[""abc"",""xyz""]")); } [Test] public void CanSerializeGenericIEnumerableEncrypted() { var encryptionMechanism = new Base64EncryptionMechanism(); var configuration = new JsonSerializerConfiguration { EncryptionMechanism = encryptionMechanism, EncryptRootObject = true }; var serializer = new JsonSerializer<List<string>>(configuration); var json = serializer.Serialize(new List<string> { "abc", "xyz" }); var expected = @"""" + encryptionMechanism.Encrypt(@"[""abc"",""xyz""]") + @""""; Assert.That(json, Is.EqualTo(expected)); } [Test] public void CanSerializeNonGenericIEnumerable() { var serializer = new JsonSerializer<ArrayList>(); var json = serializer.Serialize(new ArrayList { "abc", "xyz" }); Assert.That(json, Is.EqualTo(@"[""abc"",""xyz""]")); } [Test] public void CanSerializeSerializeNonGenericIEnumerableEncrypted() { var encryptionMechanism = new Base64EncryptionMechanism(); var configuration = new JsonSerializerConfiguration { EncryptionMechanism = encryptionMechanism, EncryptRootObject = true }; var serializer = new JsonSerializer<ArrayList>(configuration); var json = serializer.Serialize(new ArrayList { "abc", "xyz" }); var expected = @"""" + encryptionMechanism.Encrypt(@"[""abc"",""xyz""]") + @""""; Assert.That(json, Is.EqualTo(expected)); } [Test] public void CanSerializeGenericIEnumerableOfObjectWhenAnItemTypeIsDecoratedWithEncrypteAttribute() { var encryptionMechanism = new Base64EncryptionMechanism(); var configuration = new JsonSerializerConfiguration { EncryptionMechanism = encryptionMechanism, }; var serializer = new JsonSerializer<List<object>>(configuration); var json = serializer.Serialize(new List<object> { new Foo { Bar = "abc", Baz = true }, new Foo { Bar = "xyz", Baz = false } }); var expected = "[" + @"""" + encryptionMechanism.Encrypt(@"{""Bar"":""abc"",""Baz"":true}") + @"""" + "," + @"""" + encryptionMechanism.Encrypt(@"{""Bar"":""xyz"",""Baz"":false}") + @"""" + "]"; Assert.That(json, Is.EqualTo(expected)); } [Test] public void CanSerializeGenericIEnumerableOfObjectWhenAnItemTypePropertyIsDecoratedWithEncrypteAttribute() { var encryptionMechanism = new Base64EncryptionMechanism(); var configuration = new JsonSerializerConfiguration { EncryptionMechanism = encryptionMechanism, }; var serializer = new JsonSerializer<List<object>>(configuration); var json = serializer.Serialize(new List<object> { new Qux { Bar = "abc", Baz = true }, new Qux { Bar = "xyz", Baz = false } }); var expected = @"[{""Bar"":" + @"""" + encryptionMechanism.Encrypt(@"""abc""") + @"""" + @",""Baz"":true},{""Bar"":" + @"""" + encryptionMechanism.Encrypt(@"""xyz""") + @"""" + @",""Baz"":false}]"; Assert.That(json, Is.EqualTo(expected)); } [Test] public void CanDeserializeGenericList() { var serializer = new JsonSerializer<List<string>>(); var result = serializer.Deserialize(@"[""abc"",""xyz""]"); Assert.That(result, Is.InstanceOf<List<string>>()); Assert.That(result, Is.EqualTo(new List<string> { "abc", "xyz" })); } [Test] public void CanDeserializeGenericIEnumerable() { var serializer = new JsonSerializer<IEnumerable<string>>(); var result = serializer.Deserialize(@"[""abc"",""xyz""]"); Assert.That(result, Is.InstanceOf<List<string>>()); Assert.That(result, Is.EqualTo(new List<string> { "abc", "xyz" })); } [Test] public void CanDeserializeNonGenericIEnumerable() { var serializer = new JsonSerializer<IEnumerable>(); var result = serializer.Deserialize(@"[""abc"",""xyz""]"); Assert.That(result, Is.InstanceOf<List<object>>()); Assert.That(result, Is.EqualTo(new List<object> { "abc", "xyz" })); } [Test] public void CanDeserializeArrayList() { var serializer = new JsonSerializer<ArrayList>(); var result = serializer.Deserialize(@"[""abc"",""xyz""]"); Assert.That(result, Is.InstanceOf<ArrayList>()); Assert.That(result, Is.EqualTo(new ArrayList { "abc", "xyz" })); } [Test] public void CanDeserializeCustomGenericList() { var serializer = new JsonSerializer<CustomList<string>>(); var result = serializer.Deserialize(@"[""abc"",""xyz""]"); Assert.That(result, Is.InstanceOf<CustomList<string>>()); Assert.That(result, Is.EqualTo(new CustomList<string> { "abc", "xyz" })); } public class CustomList<T> : List<T> { } [Test] public void CanDeserializeTypedCustomGenericList() { var serializer = new JsonSerializer<CustomStringList>(); var result = serializer.Deserialize(@"[""abc"",""xyz""]"); Assert.That(result, Is.InstanceOf<CustomStringList>()); Assert.That(result, Is.EqualTo(new CustomStringList { "abc", "xyz" })); } public class CustomStringList : List<string> { } [Test] public void CanDeserializeCustomNonGenericList() { var serializer = new JsonSerializer<CustomArrayList>(); var result = serializer.Deserialize(@"[""abc"",""xyz""]"); Assert.That(result, Is.InstanceOf<CustomArrayList>()); Assert.That(result, Is.EqualTo(new CustomArrayList { "abc", "xyz" })); } public class CustomArrayList : ArrayList { } [Test] public void CanDeserializeEmptyGenericList() { var serializer = new JsonSerializer<List<string>>(); var result = serializer.Deserialize(@"[]"); Assert.That(result, Is.InstanceOf<List<string>>()); Assert.That(result, Is.EqualTo(new List<string>())); } [Test] public void CanDeserializeEmptyGenericIEnumerable() { var serializer = new JsonSerializer<IEnumerable<string>>(); var result = serializer.Deserialize(@"[]"); Assert.That(result, Is.InstanceOf<List<string>>()); Assert.That(result, Is.EqualTo(new List<string>())); } [Test] public void CanDeserializeEmptyNonGenericIEnumerable() { var serializer = new JsonSerializer<IEnumerable>(); var result = serializer.Deserialize(@"[]"); Assert.That(result, Is.InstanceOf<List<object>>()); Assert.That(result, Is.EqualTo(new List<object>())); } [Test] public void CanDeserializeNullGenericList() { var serializer = new JsonSerializer<List<string>>(); var result = serializer.Deserialize(@"null"); Assert.That(result, Is.Null); } [Test] public void CanDeserializeNullGenericIEnumerable() { var serializer = new JsonSerializer<IEnumerable<string>>(); var result = serializer.Deserialize(@"null"); Assert.That(result, Is.Null); } [Test] public void CanDeserializeNullNonGenericIEnumerable() { var serializer = new JsonSerializer<IEnumerable>(); var result = serializer.Deserialize(@"null"); Assert.That(result, Is.Null); } [Test] public void CanDeserializeReadonlyNonGenericIListProperty() { var serializer = new JsonSerializer<GarplyNonGenericIList>(); var json = @"{""Graults"":[true,false,null]}"; var garply = serializer.Deserialize(json); Assert.That(garply.Graults[0], Is.True); Assert.That(garply.Graults[1], Is.False); Assert.That(garply.Graults[2], Is.Null); } [Test] public void CanDeserializeReadonlyNonGenericImplementationOfNonGenericIListProperty() { var serializer = new JsonSerializer<GarplyNonGenericImplementationOfNonGenericIList>(); var json = @"{""Graults"":[true,false,null]}"; var garply = serializer.Deserialize(json); Assert.That(garply.Graults[0], Is.True); Assert.That(garply.Graults[1], Is.False); Assert.That(garply.Graults[2], Is.Null); } [Test] public void CanDeserializeReadonlyGenericListProperty() { var serializer = new JsonSerializer<GarplyGenericList>(); var json = @"{""Graults"":[1,2,3]}"; var garply = serializer.Deserialize(json); Assert.That(garply.Graults[0], Is.EqualTo(1)); Assert.That(garply.Graults[1], Is.EqualTo(2)); Assert.That(garply.Graults[2], Is.EqualTo(3)); } [Test] public void CanDeserializeReadonlyNonGenericImplementationOfGenericListProperty() { var serializer = new JsonSerializer<GarplyNonGenericImplementationOfGenericIList>(); var json = @"{""Graults"":[1,2,3]}"; var garply = serializer.Deserialize(json); Assert.That(garply.Graults[0], Is.EqualTo(1)); Assert.That(garply.Graults[1], Is.EqualTo(2)); Assert.That(garply.Graults[2], Is.EqualTo(3)); } [Test] public void CanDeserializeReadonlyGenericIListProperty() { var serializer = new JsonSerializer<GarplyGenericIList>(); var json = @"{""Graults"":[1,2,3]}"; var garply = serializer.Deserialize(json); Assert.That(garply.Graults[0], Is.EqualTo(1)); Assert.That(garply.Graults[1], Is.EqualTo(2)); Assert.That(garply.Graults[2], Is.EqualTo(3)); } [Test] public void CanDeserializeReadonlyNonGenericInterfaceImplementationOfGenericListProperty() { var serializer = new JsonSerializer<GarplyNonGenericInterfaceImplementationOfGenericIList>(); var json = @"{""Graults"":[1,2,3]}"; var garply = serializer.Deserialize(json); Assert.That(garply.Graults[0], Is.EqualTo(1)); Assert.That(garply.Graults[1], Is.EqualTo(2)); Assert.That(garply.Graults[2], Is.EqualTo(3)); } [Test] public void CanDeserializeReadonlyGenericImplementationOfGenericIListProperty() { var serializer = new JsonSerializer<GarplyGenericImplementationOfGenericIList>(); var json = @"{""Graults"":[1,2,3]}"; var garply = serializer.Deserialize(json); Assert.That(garply.Graults[0], Is.EqualTo(1)); Assert.That(garply.Graults[1], Is.EqualTo(2)); Assert.That(garply.Graults[2], Is.EqualTo(3)); } [Encrypt] public class Foo { public string Bar { get; set; } public bool Baz { get; set; } } public class Qux { [Encrypt] public string Bar { get; set; } public bool Baz { get; set; } } public class GarplyNonGenericIList { private readonly IList _graults = new ArrayList(); public IList Graults { get { return _graults; } } } public class GarplyNonGenericImplementationOfNonGenericIList { private readonly ArrayList _graults = new ArrayList(); public ArrayList Graults { get { return _graults; } } } public class GarplyGenericList { private readonly List<int> _graults = new List<int>(); public List<int> Graults { get { return _graults; } } } public class GarplyNonGenericImplementationOfGenericIList { private readonly IntList _graults = new IntList(); public IntList Graults { get { return _graults; } } } public class GarplyGenericIList { private readonly IList<int> _graults = new List<int>(); public IList<int> Graults { get { return _graults; } } } public class GarplyNonGenericInterfaceImplementationOfGenericIList { private readonly IIntList _graults = new IntList(); public IIntList Graults { get { return _graults; } } } public class GarplyGenericImplementationOfGenericIList { private readonly CustomIList<int> _graults = new CustomIList<int>(); public CustomIList<int> Graults { get { return _graults; } } } public class CustomIList<T> : IList<T> { private readonly IList<T> _list = new List<T>(); public IEnumerator<T> GetEnumerator() { return _list.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)_list).GetEnumerator(); } public void Add(T item) { _list.Add(item); } public void Clear() { _list.Clear(); } public bool Contains(T item) { return _list.Contains(item); } public void CopyTo(T[] array, int arrayIndex) { _list.CopyTo(array, arrayIndex); } public bool Remove(T item) { return _list.Remove(item); } public int Count { get { return _list.Count; } } public bool IsReadOnly { get { return _list.IsReadOnly; } } public int IndexOf(T item) { return _list.IndexOf(item); } public void Insert(int index, T item) { _list.Insert(index, item); } public void RemoveAt(int index) { _list.RemoveAt(index); } public T this[int index] { get { return _list[index]; } set { _list[index] = value; } } } public interface IIntList : IList<int> { } public class IntList : IIntList { private readonly IList<int> _list = new List<int>(); public IEnumerator<int> GetEnumerator() { return _list.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)_list).GetEnumerator(); } public void Add(int item) { _list.Add(item); } public void Clear() { _list.Clear(); } public bool Contains(int item) { return _list.Contains(item); } public void CopyTo(int[] array, int arrayIndex) { _list.CopyTo(array, arrayIndex); } public bool Remove(int item) { return _list.Remove(item); } public int Count { get { return _list.Count; } } public bool IsReadOnly { get { return _list.IsReadOnly; } } public int IndexOf(int item) { return _list.IndexOf(item); } public void Insert(int index, int item) { _list.Insert(index, item); } public void RemoveAt(int index) { _list.RemoveAt(index); } public int this[int index] { get { return _list[index]; } set { _list[index] = value; } } } } }
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using DiscUtils.Internal; namespace DiscUtils.Ntfs { using DirectoryIndexEntry = KeyValuePair<FileNameRecord, FileRecordReference>; internal class Directory : File { private IndexView<FileNameRecord, FileRecordReference> _index; public Directory(INtfsContext context, FileRecord baseRecord) : base(context, baseRecord) {} private IndexView<FileNameRecord, FileRecordReference> Index { get { if (_index == null && StreamExists(AttributeType.IndexRoot, "$I30")) { _index = new IndexView<FileNameRecord, FileRecordReference>(GetIndex("$I30")); } return _index; } } public bool IsEmpty { get { return Index.Count == 0; } } public IEnumerable<DirectoryEntry> GetAllEntries(bool filter) { IEnumerable<DirectoryIndexEntry> entries = filter ? FilterEntries(Index.Entries) : Index.Entries; foreach (DirectoryIndexEntry entry in entries) { yield return new DirectoryEntry(this, entry.Value, entry.Key); } } public void UpdateEntry(DirectoryEntry entry) { Index[entry.Details] = entry.Reference; UpdateRecordInMft(); } public override void Dump(TextWriter writer, string indent) { writer.WriteLine(indent + "DIRECTORY (" + base.ToString() + ")"); writer.WriteLine(indent + " File Number: " + IndexInMft); if (Index != null) { foreach (DirectoryIndexEntry entry in Index.Entries) { writer.WriteLine(indent + " DIRECTORY ENTRY (" + entry.Key.FileName + ")"); writer.WriteLine(indent + " MFT Ref: " + entry.Value); entry.Key.Dump(writer, indent + " "); } } } public override string ToString() { return base.ToString() + @"\"; } internal new static Directory CreateNew(INtfsContext context, FileAttributeFlags parentDirFlags) { Directory dir = (Directory)context.AllocateFile(FileRecordFlags.IsDirectory); StandardInformation.InitializeNewFile( dir, FileAttributeFlags.Archive | (parentDirFlags & FileAttributeFlags.Compressed)); // Create the index root attribute by instantiating a new index dir.CreateIndex("$I30", AttributeType.FileName, AttributeCollationRule.Filename); dir.UpdateRecordInMft(); return dir; } internal DirectoryEntry GetEntryByName(string name) { string searchName = name; int streamSepPos = name.IndexOf(':'); if (streamSepPos >= 0) { searchName = name.Substring(0, streamSepPos); } DirectoryIndexEntry entry = Index.FindFirst(new FileNameQuery(searchName, _context.UpperCase)); if (entry.Key != null) { return new DirectoryEntry(this, entry.Value, entry.Key); } return null; } internal DirectoryEntry AddEntry(File file, string name, FileNameNamespace nameNamespace) { if (name.Length > 255) { throw new IOException("Invalid file name, more than 255 characters: " + name); } if (name.IndexOfAny(new[] { '\0', '/' }) != -1) { throw new IOException(@"Invalid file name, contains '\0' or '/': " + name); } FileNameRecord newNameRecord = file.GetFileNameRecord(null, true); newNameRecord.FileNameNamespace = nameNamespace; newNameRecord.FileName = name; newNameRecord.ParentDirectory = MftReference; NtfsStream nameStream = file.CreateStream(AttributeType.FileName, null); nameStream.SetContent(newNameRecord); file.HardLinkCount++; file.UpdateRecordInMft(); Index[newNameRecord] = file.MftReference; Modified(); UpdateRecordInMft(); return new DirectoryEntry(this, file.MftReference, newNameRecord); } internal void RemoveEntry(DirectoryEntry dirEntry) { File file = _context.GetFileByRef(dirEntry.Reference); FileNameRecord nameRecord = dirEntry.Details; Index.Remove(dirEntry.Details); foreach (NtfsStream stream in file.GetStreams(AttributeType.FileName, null)) { FileNameRecord streamName = stream.GetContent<FileNameRecord>(); if (nameRecord.Equals(streamName)) { file.RemoveStream(stream); break; } } file.HardLinkCount--; file.UpdateRecordInMft(); Modified(); UpdateRecordInMft(); } internal string CreateShortName(string name) { string baseName = string.Empty; string ext = string.Empty; int lastPeriod = name.LastIndexOf('.'); int i = 0; while (baseName.Length < 6 && i < name.Length && i != lastPeriod) { char upperChar = char.ToUpperInvariant(name[i]); if (Utilities.Is8Dot3Char(upperChar)) { baseName += upperChar; } ++i; } if (lastPeriod >= 0) { i = lastPeriod + 1; while (ext.Length < 3 && i < name.Length) { char upperChar = char.ToUpperInvariant(name[i]); if (Utilities.Is8Dot3Char(upperChar)) { ext += upperChar; } ++i; } } i = 1; string candidate; do { string suffix = string.Format(CultureInfo.InvariantCulture, "~{0}", i); candidate = baseName.Substring(0, Math.Min(8 - suffix.Length, baseName.Length)) + suffix + (ext.Length > 0 ? "." + ext : string.Empty); i++; } while (GetEntryByName(candidate) != null); return candidate; } private List<DirectoryIndexEntry> FilterEntries(IEnumerable<DirectoryIndexEntry> entriesIter) { List<DirectoryIndexEntry> entries = new List<DirectoryIndexEntry>(); // Weed out short-name entries for files and any hidden / system / metadata files. foreach (var entry in entriesIter) { if ((entry.Key.Flags & FileAttributeFlags.Hidden) != 0 && _context.Options.HideHiddenFiles) { continue; } if ((entry.Key.Flags & FileAttributeFlags.System) != 0 && _context.Options.HideSystemFiles) { continue; } if (entry.Value.MftIndex < 24 && _context.Options.HideMetafiles) { continue; } if (entry.Key.FileNameNamespace == FileNameNamespace.Dos && _context.Options.HideDosFileNames) { continue; } entries.Add(entry); } return entries; } private sealed class FileNameQuery : IComparable<byte[]> { private readonly byte[] _query; private readonly UpperCase _upperCase; public FileNameQuery(string query, UpperCase upperCase) { _query = Encoding.Unicode.GetBytes(query); _upperCase = upperCase; } public int CompareTo(byte[] buffer) { // Note: this is internal knowledge of FileNameRecord structure - but for performance // reasons, we don't want to decode the entire structure. In fact can avoid the string // conversion as well. byte fnLen = buffer[0x40]; return _upperCase.Compare(_query, 0, _query.Length, buffer, 0x42, fnLen * 2); } } } }
// FastZip.cs // // Copyright 2005 John Reilly // // 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. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. using System; using System.IO; using ICSharpCode.SharpZipLib.Core; namespace ICSharpCode.SharpZipLib.Zip { /// <summary> /// FastZipEvents supports all events applicable to <see cref="FastZip">FastZip</see> operations. /// </summary> public class FastZipEvents { /// <summary> /// Delegate to invoke when processing directories. /// </summary> public ProcessDirectoryDelegate ProcessDirectory; /// <summary> /// Delegate to invoke when processing files. /// </summary> public ProcessFileDelegate ProcessFile; /// <summary> /// Delegate to invoke when processing directory failures. /// </summary> public DirectoryFailureDelegate DirectoryFailure; /// <summary> /// Delegate to invoke when processing file failures. /// </summary> public FileFailureDelegate FileFailure; /// <summary> /// Raise the <see cref="DirectoryFailure">directory failure</see> event. /// </summary> /// <param name="directory">The directory causing the failure.</param> /// <param name="e">The exception for this event.</param> /// <returns>A boolean indicating if execution should continue or not.</returns> public bool OnDirectoryFailure(string directory, Exception e) { bool result = false; if ( DirectoryFailure != null ) { ScanFailureEventArgs args = new ScanFailureEventArgs(directory, e); DirectoryFailure(this, args); result = args.ContinueRunning; } return result; } /// <summary> /// Raises the <see cref="FileFailure">file failure delegate</see>. /// </summary> /// <param name="file">The file causing the failure.</param> /// <param name="e">The exception for this failure.</param> /// <returns>A boolean indicating if execution should continue or not.</returns> public bool OnFileFailure(string file, Exception e) { bool result = false; if ( FileFailure != null ) { ScanFailureEventArgs args = new ScanFailureEventArgs(file, e); FileFailure(this, args); result = args.ContinueRunning; } return result; } /// <summary> /// Raises the <see cref="ProcessFile">Process File delegate</see>. /// </summary> /// <param name="file">The file being processed.</param> /// <returns>A boolean indicating if execution should continue or not.</returns> public bool OnProcessFile(string file) { bool result = true; if ( ProcessFile != null ) { ScanEventArgs args = new ScanEventArgs(file); ProcessFile(this, args); result = args.ContinueRunning; } return result; } /// <summary> /// Fires the <see cref="ProcessDirectory">process directory</see> delegate. /// </summary> /// <param name="directory">The directory being processed.</param> /// <param name="hasMatchingFiles">Flag indicating if directory has matching files as determined by the current filter.</param> public bool OnProcessDirectory(string directory, bool hasMatchingFiles) { bool result = true; if ( ProcessDirectory != null ) { DirectoryEventArgs args = new DirectoryEventArgs(directory, hasMatchingFiles); ProcessDirectory(this, args); result = args.ContinueRunning; } return result; } } /// <summary> /// FastZip provides facilities for creating and extracting zip files. /// </summary> public class FastZip { #region Enumerations /// <summary> /// Defines the desired handling when overwriting files during extraction. /// </summary> public enum Overwrite { /// <summary> /// Prompt the user to confirm overwriting /// </summary> Prompt, /// <summary> /// Never overwrite files. /// </summary> Never, /// <summary> /// Always overwrite files. /// </summary> Always } #endregion #region Constructors /// <summary> /// Initialise a default instance of <see cref="FastZip"/>. /// </summary> public FastZip() { } /// <summary> /// Initialise a new instance of <see cref="FastZip"/> /// </summary> /// <param name="events">The <see cref="FastZipEvents">events</see> to use during operations.</param> public FastZip(FastZipEvents events) { events_ = events; } #endregion #region Properties /// <summary> /// Get/set a value indicating wether empty directories should be created. /// </summary> public bool CreateEmptyDirectories { get { return createEmptyDirectories_; } set { createEmptyDirectories_ = value; } } #if !NETCF_1_0 /// <summary> /// Get / set the password value. /// </summary> public string Password { get { return password_; } set { password_ = value; } } #endif /// <summary> /// Get or set the <see cref="INameTransform"></see> active when creating Zip files. /// </summary> /// <seealso cref="EntryFactory"></seealso> public INameTransform NameTransform { get { return entryFactory_.NameTransform; } set { entryFactory_.NameTransform = value; } } /// <summary> /// Get or set the <see cref="IEntryFactory"></see> active when creating Zip files. /// </summary> public IEntryFactory EntryFactory { get { return entryFactory_; } set { if ( value == null ) { entryFactory_ = new ZipEntryFactory(); } else { entryFactory_ = value; } } } /// <summary> /// Get/set a value indicating wether file dates and times should /// be restored when extracting files from an archive. /// </summary> /// <remarks>The default value is false.</remarks> public bool RestoreDateTimeOnExtract { get { return restoreDateTimeOnExtract_; } set { restoreDateTimeOnExtract_ = value; } } /// <summary> /// Get/set a value indicating wether file attributes should /// be restored during extract operations /// </summary> public bool RestoreAttributesOnExtract { get { return restoreAttributesOnExtract_; } set { restoreAttributesOnExtract_ = value; } } #endregion #region Delegates /// <summary> /// Delegate called when confirming overwriting of files. /// </summary> public delegate bool ConfirmOverwriteDelegate(string fileName); #endregion #region CreateZip /// <summary> /// Create a zip file. /// </summary> /// <param name="zipFileName">The name of the zip file to create.</param> /// <param name="sourceDirectory">The directory to source files from.</param> /// <param name="recurse">True to recurse directories, false for no recursion.</param> /// <param name="fileFilter">The <see cref="PathFilter">file filter</see> to apply.</param> /// <param name="directoryFilter">The <see cref="PathFilter">directory filter</see> to apply.</param> public void CreateZip(string zipFileName, string sourceDirectory, bool recurse, string fileFilter, string directoryFilter) { CreateZip(File.Create(zipFileName), sourceDirectory, recurse, fileFilter, directoryFilter); } /// <summary> /// Create a zip file/archive. /// </summary> /// <param name="zipFileName">The name of the zip file to create.</param> /// <param name="sourceDirectory">The directory to obtain files and directories from.</param> /// <param name="recurse">True to recurse directories, false for no recursion.</param> /// <param name="fileFilter">The file filter to apply.</param> public void CreateZip(string zipFileName, string sourceDirectory, bool recurse, string fileFilter) { CreateZip(File.Create(zipFileName), sourceDirectory, recurse, fileFilter, null); } /// <summary> /// Create a zip archive sending output to the <paramref name="outputStream"/> passed. /// </summary> /// <param name="outputStream">The stream to write archive data to.</param> /// <param name="sourceDirectory">The directory to source files from.</param> /// <param name="recurse">True to recurse directories, false for no recursion.</param> /// <param name="fileFilter">The <see cref="PathFilter">file filter</see> to apply.</param> /// <param name="directoryFilter">The <see cref="PathFilter">directory filter</see> to apply.</param> public void CreateZip(Stream outputStream, string sourceDirectory, bool recurse, string fileFilter, string directoryFilter) { NameTransform = new ZipNameTransform(sourceDirectory); sourceDirectory_ = sourceDirectory; using ( outputStream_ = new ZipOutputStream(outputStream) ) { #if !NETCF_1_0 if ( password_ != null ) { outputStream_.Password = password_; } #endif FileSystemScanner scanner = new FileSystemScanner(fileFilter, directoryFilter); scanner.ProcessFile += new ProcessFileDelegate(ProcessFile); if ( this.CreateEmptyDirectories ) { scanner.ProcessDirectory += new ProcessDirectoryDelegate(ProcessDirectory); } if (events_ != null) { if ( events_.FileFailure != null ) { scanner.FileFailure += events_.FileFailure; } if ( events_.DirectoryFailure != null ) { scanner.DirectoryFailure += events_.DirectoryFailure; } } scanner.Scan(sourceDirectory, recurse); } } #endregion #region ExtractZip /// <summary> /// Extract the contents of a zip file. /// </summary> /// <param name="zipFileName">The zip file to extract from.</param> /// <param name="targetDirectory">The directory to save extracted information in.</param> /// <param name="fileFilter">A filter to apply to files.</param> public void ExtractZip(string zipFileName, string targetDirectory, string fileFilter) { ExtractZip(zipFileName, targetDirectory, Overwrite.Always, null, fileFilter, null, restoreDateTimeOnExtract_); } /// <summary> /// Extract the contents of a zip file. /// </summary> /// <param name="zipFileName">The zip file to extract from.</param> /// <param name="targetDirectory">The directory to save extracted information in.</param> /// <param name="overwrite">The style of <see cref="Overwrite">overwriting</see> to apply.</param> /// <param name="confirmDelegate">A delegate to invoke when confirming overwriting.</param> /// <param name="fileFilter">A filter to apply to files.</param> /// <param name="directoryFilter">A filter to apply to directories.</param> /// <param name="restoreDateTime">Flag indicating wether to restore the date and time for extracted files.</param> public void ExtractZip(string zipFileName, string targetDirectory, Overwrite overwrite, ConfirmOverwriteDelegate confirmDelegate, string fileFilter, string directoryFilter, bool restoreDateTime) { if ( (overwrite == Overwrite.Prompt) && (confirmDelegate == null) ) { throw new ArgumentNullException("confirmDelegate"); } continueRunning_ = true; overwrite_ = overwrite; confirmDelegate_ = confirmDelegate; targetDirectory_ = targetDirectory; fileFilter_ = new NameFilter(fileFilter); directoryFilter_ = new NameFilter(directoryFilter); restoreDateTimeOnExtract_ = restoreDateTime; using ( zipFile_ = new ZipFile(zipFileName) ) { #if !NETCF_1_0 if (password_ != null) { zipFile_.Password = password_; } #endif System.Collections.IEnumerator enumerator = zipFile_.GetEnumerator(); while ( continueRunning_ && enumerator.MoveNext()) { ZipEntry entry = (ZipEntry) enumerator.Current; if ( entry.IsFile ) { if ( directoryFilter_.IsMatch(Path.GetDirectoryName(entry.Name)) && fileFilter_.IsMatch(entry.Name) ) { ExtractEntry(entry); } } else if ( entry.IsDirectory ) { if ( directoryFilter_.IsMatch(entry.Name) && CreateEmptyDirectories ) { ExtractEntry(entry); } } else { // Do nothing for volume labels etc... } } } } #endregion #region Internal Processing void ProcessDirectory(object sender, DirectoryEventArgs e) { if ( !e.HasMatchingFiles && CreateEmptyDirectories ) { if ( events_ != null ) { events_.OnProcessDirectory(e.Name, e.HasMatchingFiles); } if ( e.ContinueRunning ) { if (e.Name != sourceDirectory_) { ZipEntry entry = entryFactory_.MakeDirectoryEntry(e.Name); outputStream_.PutNextEntry(entry); } } } } void ProcessFile(object sender, ScanEventArgs e) { if ( (events_ != null) && (events_.ProcessFile != null) ) { events_.ProcessFile(sender, e); } if ( e.ContinueRunning ) { ZipEntry entry = entryFactory_.MakeFileEntry(e.Name); outputStream_.PutNextEntry(entry); AddFileContents(e.Name); } } void AddFileContents(string name) { if ( buffer_ == null ) { buffer_ = new byte[4096]; } using (FileStream stream = File.OpenRead(name)) { StreamUtils.Copy(stream, outputStream_, buffer_); } } void ExtractFileEntry(ZipEntry entry, string targetName) { bool proceed = true; if ( overwrite_ != Overwrite.Always ) { if ( File.Exists(targetName) ) { if ( (overwrite_ == Overwrite.Prompt) && (confirmDelegate_ != null) ) { proceed = confirmDelegate_(targetName); } else { proceed = false; } } } if ( proceed ) { if ( events_ != null ) { continueRunning_ = events_.OnProcessFile(entry.Name); } if ( continueRunning_ ) { try { using ( FileStream outputStream = File.Create(targetName) ) { if ( buffer_ == null ) { buffer_ = new byte[4096]; } StreamUtils.Copy(zipFile_.GetInputStream(entry), outputStream, buffer_); } #if !NETCF_1_0 && !NETCF_2_0 if ( restoreDateTimeOnExtract_ ) { File.SetLastWriteTime(targetName, entry.DateTime); } if ( RestoreAttributesOnExtract && entry.IsDOSEntry && (entry.ExternalFileAttributes != -1)) { FileAttributes fileAttributes = (FileAttributes) entry.ExternalFileAttributes; // TODO: FastZip - Setting of other file attributes on extraction is a little trickier. fileAttributes &= (FileAttributes.Archive | FileAttributes.Normal | FileAttributes.ReadOnly | FileAttributes.Hidden); File.SetAttributes(targetName, fileAttributes); } #endif } catch(Exception ex) { if ( events_ != null ) { continueRunning_ = events_.OnFileFailure(targetName, ex); } else { continueRunning_ = false; } } } } } void ExtractEntry(ZipEntry entry) { bool doExtraction = false; string nameText = entry.Name; if ( entry.IsFile ) { doExtraction = NameIsValid(nameText) && entry.IsCompressionMethodSupported(); } else if ( entry.IsDirectory ) { doExtraction = NameIsValid(nameText); } // TODO: Fire delegate were compression method not supported, or name is invalid. string dirName = null; string targetName = null; if ( doExtraction ) { // Handle invalid entry names by chopping of path root. if (Path.IsPathRooted(nameText)) { string workName = Path.GetPathRoot(nameText); nameText = nameText.Substring(workName.Length); } if ( nameText.Length > 0 ) { targetName = Path.Combine(targetDirectory_, nameText); if ( entry.IsDirectory ) { dirName = targetName; } else { dirName = Path.GetDirectoryName(Path.GetFullPath(targetName)); } } else { doExtraction = false; } } if ( doExtraction && !Directory.Exists(dirName) ) { if ( !entry.IsDirectory || CreateEmptyDirectories ) { try { Directory.CreateDirectory(dirName); } catch (Exception ex) { doExtraction = false; if ( events_ != null ) { if ( entry.IsDirectory ) { continueRunning_ = events_.OnDirectoryFailure(targetName, ex); } else { continueRunning_ = events_.OnFileFailure(targetName, ex); } } else { continueRunning_ = false; } } } } if ( doExtraction && entry.IsFile ) { ExtractFileEntry(entry, targetName); } } #if NET_1_0 || NET_1_1 || NETCF_1_0 static bool NameIsValid(string name) { return (name != null) && (name.Length > 0) && (name.IndexOfAny(Path.InvalidPathChars) < 0); } #else static bool NameIsValid(string name) { return (name != null) && (name.Length > 0) && (name.IndexOfAny(Path.GetInvalidPathChars()) < 0); } #endif #endregion #region Instance Fields bool continueRunning_; byte[] buffer_; ZipOutputStream outputStream_; ZipFile zipFile_; string targetDirectory_; string sourceDirectory_; NameFilter fileFilter_; NameFilter directoryFilter_; Overwrite overwrite_; ConfirmOverwriteDelegate confirmDelegate_; bool restoreDateTimeOnExtract_; bool restoreAttributesOnExtract_; bool createEmptyDirectories_; FastZipEvents events_; IEntryFactory entryFactory_ = new ZipEntryFactory(); #if !NETCF_1_0 string password_; #endif #endregion } }
using Lucene.Net.Support; using System; using System.Diagnostics; namespace Lucene.Net.Codecs.Compressing { /* * 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 DataInput = Lucene.Net.Store.DataInput; using DataOutput = Lucene.Net.Store.DataOutput; using PackedInt32s = Lucene.Net.Util.Packed.PackedInt32s; /// <summary> /// LZ4 compression and decompression routines. /// <para/> /// http://code.google.com/p/lz4/ /// http://fastcompression.blogspot.fr/p/lz4.html /// </summary> public sealed class LZ4 { private LZ4() { } internal const int MEMORY_USAGE = 14; internal const int MIN_MATCH = 4; // minimum length of a match internal static readonly int MAX_DISTANCE = 1 << 16; // maximum distance of a reference internal const int LAST_LITERALS = 5; // the last 5 bytes must be encoded as literals internal const int HASH_LOG_HC = 15; // log size of the dictionary for compressHC internal static readonly int HASH_TABLE_SIZE_HC = 1 << HASH_LOG_HC; internal static readonly int OPTIMAL_ML = 0x0F + 4 - 1; // match length that doesn't require an additional byte private static int Hash(int i, int hashBits) { return Number.URShift((i * -1640531535), (32 - hashBits)); } private static int HashHC(int i) { return Hash(i, HASH_LOG_HC); } /// <summary> /// NOTE: This was readInt() in Lucene. /// </summary> private static int ReadInt32(byte[] buf, int i) { return ((((sbyte)buf[i]) & 0xFF) << 24) | ((((sbyte)buf[i + 1]) & 0xFF) << 16) | ((((sbyte)buf[i + 2]) & 0xFF) << 8) | (((sbyte)buf[i + 3]) & 0xFF); } /// <summary> /// NOTE: This was readIntEquals() in Lucene. /// </summary> private static bool ReadInt32Equals(byte[] buf, int i, int j) { return ReadInt32(buf, i) == ReadInt32(buf, j); } private static int CommonBytes(byte[] b, int o1, int o2, int limit) { Debug.Assert(o1 < o2); int count = 0; while (o2 < limit && b[o1++] == b[o2++]) { ++count; } return count; } private static int CommonBytesBackward(byte[] b, int o1, int o2, int l1, int l2) { int count = 0; while (o1 > l1 && o2 > l2 && b[--o1] == b[--o2]) { ++count; } return count; } /// <summary> /// Decompress at least <paramref name="decompressedLen"/> bytes into /// <c>dest[dOff]</c>. Please note that <paramref name="dest"/> must be large /// enough to be able to hold <b>all</b> decompressed data (meaning that you /// need to know the total decompressed length). /// </summary> public static int Decompress(DataInput compressed, int decompressedLen, byte[] dest, int dOff) { int destEnd = dest.Length; do { // literals int token = compressed.ReadByte() & 0xFF; int literalLen = (int)(((uint)token) >> 4); if (literalLen != 0) { if (literalLen == 0x0F) { byte len; while ((len = compressed.ReadByte()) == 0xFF) { literalLen += 0xFF; } literalLen += len & 0xFF; } compressed.ReadBytes(dest, dOff, literalLen); dOff += literalLen; } if (dOff >= decompressedLen) { break; } // matchs var byte1 = compressed.ReadByte(); var byte2 = compressed.ReadByte(); int matchDec = (byte1 & 0xFF) | ((byte2 & 0xFF) << 8); Debug.Assert(matchDec > 0); int matchLen = token & 0x0F; if (matchLen == 0x0F) { int len; while ((len = compressed.ReadByte()) == 0xFF) { matchLen += 0xFF; } matchLen += len & 0xFF; } matchLen += MIN_MATCH; // copying a multiple of 8 bytes can make decompression from 5% to 10% faster int fastLen = (int)((matchLen + 7) & 0xFFFFFFF8); if (matchDec < matchLen || dOff + fastLen > destEnd) { // overlap -> naive incremental copy for (int @ref = dOff - matchDec, end = dOff + matchLen; dOff < end; ++@ref, ++dOff) { dest[dOff] = dest[@ref]; } } else { // no overlap -> arraycopy Array.Copy(dest, dOff - matchDec, dest, dOff, fastLen); dOff += matchLen; } } while (dOff < decompressedLen); return dOff; } private static void EncodeLen(int l, DataOutput @out) { while (l >= 0xFF) { @out.WriteByte(unchecked((byte)(sbyte)0xFF)); l -= 0xFF; } @out.WriteByte((byte)(sbyte)l); } private static void EncodeLiterals(byte[] bytes, int token, int anchor, int literalLen, DataOutput @out) { @out.WriteByte((byte)(sbyte)token); // encode literal length if (literalLen >= 0x0F) { EncodeLen(literalLen - 0x0F, @out); } // encode literals @out.WriteBytes(bytes, anchor, literalLen); } private static void EncodeLastLiterals(byte[] bytes, int anchor, int literalLen, DataOutput @out) { int token = Math.Min(literalLen, 0x0F) << 4; EncodeLiterals(bytes, token, anchor, literalLen, @out); } private static void EncodeSequence(byte[] bytes, int anchor, int matchRef, int matchOff, int matchLen, DataOutput @out) { int literalLen = matchOff - anchor; Debug.Assert(matchLen >= 4); // encode token int token = (Math.Min(literalLen, 0x0F) << 4) | Math.Min(matchLen - 4, 0x0F); EncodeLiterals(bytes, token, anchor, literalLen, @out); // encode match dec int matchDec = matchOff - matchRef; Debug.Assert(matchDec > 0 && matchDec < 1 << 16); @out.WriteByte((byte)(sbyte)matchDec); @out.WriteByte((byte)(sbyte)((int)((uint)matchDec >> 8))); // encode match len if (matchLen >= MIN_MATCH + 0x0F) { EncodeLen(matchLen - 0x0F - MIN_MATCH, @out); } } public sealed class HashTable { internal int hashLog; internal PackedInt32s.Mutable hashTable; internal void Reset(int len) { int bitsPerOffset = PackedInt32s.BitsRequired(len - LAST_LITERALS); int bitsPerOffsetLog = 32 - Number.NumberOfLeadingZeros(bitsPerOffset - 1); hashLog = MEMORY_USAGE + 3 - bitsPerOffsetLog; if (hashTable == null || hashTable.Count < 1 << hashLog || hashTable.BitsPerValue < bitsPerOffset) { hashTable = PackedInt32s.GetMutable(1 << hashLog, bitsPerOffset, PackedInt32s.DEFAULT); } else { hashTable.Clear(); } } } /// <summary> /// Compress <c>bytes[off:off+len]</c> into <paramref name="out"/> using /// at most 16KB of memory. <paramref name="ht"/> shouldn't be shared across threads /// but can safely be reused. /// </summary> public static void Compress(byte[] bytes, int off, int len, DataOutput @out, HashTable ht) { int @base = off; int end = off + len; int anchor = off++; if (len > LAST_LITERALS + MIN_MATCH) { int limit = end - LAST_LITERALS; int matchLimit = limit - MIN_MATCH; ht.Reset(len); int hashLog = ht.hashLog; PackedInt32s.Mutable hashTable = ht.hashTable; while (off <= limit) { // find a match int @ref; while (true) { if (off >= matchLimit) { goto mainBreak; } int v = ReadInt32(bytes, off); int h = Hash(v, hashLog); @ref = @base + (int)hashTable.Get(h); Debug.Assert(PackedInt32s.BitsRequired(off - @base) <= hashTable.BitsPerValue); hashTable.Set(h, off - @base); if (off - @ref < MAX_DISTANCE && ReadInt32(bytes, @ref) == v) { break; } ++off; } // compute match length int matchLen = MIN_MATCH + CommonBytes(bytes, @ref + MIN_MATCH, off + MIN_MATCH, limit); EncodeSequence(bytes, anchor, @ref, off, matchLen, @out); off += matchLen; anchor = off; //mainContinue: ; // LUCENENET NOTE: Not Referenced } mainBreak: ; } // last literals int literalLen = end - anchor; Debug.Assert(literalLen >= LAST_LITERALS || literalLen == len); EncodeLastLiterals(bytes, anchor, end - anchor, @out); } public class Match { internal int start, @ref, len; internal virtual void Fix(int correction) { start += correction; @ref += correction; len -= correction; } internal virtual int End() { return start + len; } } private static void CopyTo(Match m1, Match m2) { m2.len = m1.len; m2.start = m1.start; m2.@ref = m1.@ref; } public sealed class HCHashTable { internal const int MAX_ATTEMPTS = 256; internal static readonly int MASK = MAX_DISTANCE - 1; internal int nextToUpdate; private int @base; private readonly int[] hashTable; private readonly short[] chainTable; internal HCHashTable() { hashTable = new int[HASH_TABLE_SIZE_HC]; chainTable = new short[MAX_DISTANCE]; } internal void Reset(int @base) { this.@base = @base; nextToUpdate = @base; Arrays.Fill(hashTable, -1); Arrays.Fill(chainTable, (short)0); } private int HashPointer(byte[] bytes, int off) { int v = ReadInt32(bytes, off); int h = HashHC(v); return hashTable[h]; } private int Next(int off) { return off - (chainTable[off & MASK] & 0xFFFF); } private void AddHash(byte[] bytes, int off) { int v = ReadInt32(bytes, off); int h = HashHC(v); int delta = off - hashTable[h]; Debug.Assert(delta > 0, delta.ToString()); if (delta >= MAX_DISTANCE) { delta = MAX_DISTANCE - 1; } chainTable[off & MASK] = (short)delta; hashTable[h] = off; } internal void Insert(int off, byte[] bytes) { for (; nextToUpdate < off; ++nextToUpdate) { AddHash(bytes, nextToUpdate); } } internal bool InsertAndFindBestMatch(byte[] buf, int off, int matchLimit, Match match) { match.start = off; match.len = 0; int delta = 0; int repl = 0; Insert(off, buf); int @ref = HashPointer(buf, off); if (@ref >= off - 4 && @ref <= off && @ref >= @base) // potential repetition { if (ReadInt32Equals(buf, @ref, off)) // confirmed { delta = off - @ref; repl = match.len = MIN_MATCH + CommonBytes(buf, @ref + MIN_MATCH, off + MIN_MATCH, matchLimit); match.@ref = @ref; } @ref = Next(@ref); } for (int i = 0; i < MAX_ATTEMPTS; ++i) { if (@ref < Math.Max(@base, off - MAX_DISTANCE + 1) || @ref > off) { break; } if (buf[@ref + match.len] == buf[off + match.len] && ReadInt32Equals(buf, @ref, off)) { int matchLen = MIN_MATCH + CommonBytes(buf, @ref + MIN_MATCH, off + MIN_MATCH, matchLimit); if (matchLen > match.len) { match.@ref = @ref; match.len = matchLen; } } @ref = Next(@ref); } if (repl != 0) { int ptr = off; int end = off + repl - (MIN_MATCH - 1); while (ptr < end - delta) { chainTable[ptr & MASK] = (short)delta; // pre load ++ptr; } do { chainTable[ptr & MASK] = (short)delta; hashTable[HashHC(ReadInt32(buf, ptr))] = ptr; ++ptr; } while (ptr < end); nextToUpdate = end; } return match.len != 0; } internal bool InsertAndFindWiderMatch(byte[] buf, int off, int startLimit, int matchLimit, int minLen, Match match) { match.len = minLen; Insert(off, buf); int delta = off - startLimit; int @ref = HashPointer(buf, off); for (int i = 0; i < MAX_ATTEMPTS; ++i) { if (@ref < Math.Max(@base, off - MAX_DISTANCE + 1) || @ref > off) { break; } if (buf[@ref - delta + match.len] == buf[startLimit + match.len] && ReadInt32Equals(buf, @ref, off)) { int matchLenForward = MIN_MATCH + CommonBytes(buf, @ref + MIN_MATCH, off + MIN_MATCH, matchLimit); int matchLenBackward = CommonBytesBackward(buf, @ref, off, @base, startLimit); int matchLen = matchLenBackward + matchLenForward; if (matchLen > match.len) { match.len = matchLen; match.@ref = @ref - matchLenBackward; match.start = off - matchLenBackward; } } @ref = Next(@ref); } return match.len > minLen; } } /// <summary> /// Compress <c>bytes[off:off+len]</c> into <paramref name="out"/>. Compared to /// <see cref="LZ4.Compress(byte[], int, int, DataOutput, HashTable)"/>, this method /// is slower and uses more memory (~ 256KB per thread) but should provide /// better compression ratios (especially on large inputs) because it chooses /// the best match among up to 256 candidates and then performs trade-offs to /// fix overlapping matches. <paramref name="ht"/> shouldn't be shared across threads /// but can safely be reused. /// </summary> public static void CompressHC(byte[] src, int srcOff, int srcLen, DataOutput @out, HCHashTable ht) { int srcEnd = srcOff + srcLen; int matchLimit = srcEnd - LAST_LITERALS; int mfLimit = matchLimit - MIN_MATCH; int sOff = srcOff; int anchor = sOff++; ht.Reset(srcOff); Match match0 = new Match(); Match match1 = new Match(); Match match2 = new Match(); Match match3 = new Match(); while (sOff <= mfLimit) { if (!ht.InsertAndFindBestMatch(src, sOff, matchLimit, match1)) { ++sOff; continue; } // saved, in case we would skip too much CopyTo(match1, match0); while (true) { Debug.Assert(match1.start >= anchor); if (match1.End() >= mfLimit || !ht.InsertAndFindWiderMatch(src, match1.End() - 2, match1.start + 1, matchLimit, match1.len, match2)) { // no better match EncodeSequence(src, anchor, match1.@ref, match1.start, match1.len, @out); anchor = sOff = match1.End(); goto mainContinue; } if (match0.start < match1.start) { if (match2.start < match1.start + match0.len) // empirical { CopyTo(match0, match1); } } Debug.Assert(match2.start > match1.start); if (match2.start - match1.start < 3) // First Match too small : removed { CopyTo(match2, match1); goto search2Continue; } while (true) { if (match2.start - match1.start < OPTIMAL_ML) { int newMatchLen = match1.len; if (newMatchLen > OPTIMAL_ML) { newMatchLen = OPTIMAL_ML; } if (match1.start + newMatchLen > match2.End() - MIN_MATCH) { newMatchLen = match2.start - match1.start + match2.len - MIN_MATCH; } int correction = newMatchLen - (match2.start - match1.start); if (correction > 0) { match2.Fix(correction); } } if (match2.start + match2.len >= mfLimit || !ht.InsertAndFindWiderMatch(src, match2.End() - 3, match2.start, matchLimit, match2.len, match3)) { // no better match -> 2 sequences to encode if (match2.start < match1.End()) { match1.len = match2.start - match1.start; } // encode seq 1 EncodeSequence(src, anchor, match1.@ref, match1.start, match1.len, @out); anchor = sOff = match1.End(); // encode seq 2 EncodeSequence(src, anchor, match2.@ref, match2.start, match2.len, @out); anchor = sOff = match2.End(); goto mainContinue; } if (match3.start < match1.End() + 3) // Not enough space for match 2 : remove it { if (match3.start >= match1.End()) // // can write Seq1 immediately ==> Seq2 is removed, so Seq3 becomes Seq1 { if (match2.start < match1.End()) { int correction = match1.End() - match2.start; match2.Fix(correction); if (match2.len < MIN_MATCH) { CopyTo(match3, match2); } } EncodeSequence(src, anchor, match1.@ref, match1.start, match1.len, @out); anchor = sOff = match1.End(); CopyTo(match3, match1); CopyTo(match2, match0); goto search2Continue; } CopyTo(match3, match2); goto search3Continue; } // OK, now we have 3 ascending matches; let's write at least the first one if (match2.start < match1.End()) { if (match2.start - match1.start < 0x0F) { if (match1.len > OPTIMAL_ML) { match1.len = OPTIMAL_ML; } if (match1.End() > match2.End() - MIN_MATCH) { match1.len = match2.End() - match1.start - MIN_MATCH; } int correction = match1.End() - match2.start; match2.Fix(correction); } else { match1.len = match2.start - match1.start; } } EncodeSequence(src, anchor, match1.@ref, match1.start, match1.len, @out); anchor = sOff = match1.End(); CopyTo(match2, match1); CopyTo(match3, match2); goto search3Continue; search3Continue: ; } //search3Break: ; // LUCENENET NOTE: Unreachable search2Continue: ; } //search2Break: ; // LUCENENET NOTE: Not referenced mainContinue: ; } //mainBreak: // LUCENENET NOTE: Not referenced EncodeLastLiterals(src, anchor, srcEnd - anchor, @out); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using System.Web.Caching; using System.Web.Compilation; using System.Web.UI; using System.Xml; using System.Xml.Serialization; using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Host; using DotNetNuke.Entities.Portals; using DotNetNuke.Entities.Tabs; using DotNetNuke.Entities.Users; using DotNetNuke.Security.Permissions; using DotNetNuke.Web.DDRMenu.DNNCommon; using DotNetNuke.Web.DDRMenu.Localisation; using DotNetNuke.Web.DDRMenu.TemplateEngine; namespace DotNetNuke.Web.DDRMenu { public class MenuBase { public static MenuBase Instantiate(string menuStyle) { try { var templateDef = TemplateDefinition.FromName(menuStyle, "*menudef.xml"); return new MenuBase {TemplateDef = templateDef}; } catch (Exception exc) { throw new ApplicationException(String.Format("Couldn't load menu style '{0}': {1}", menuStyle, exc)); } } private Settings menuSettings; internal MenuNode RootNode { get; set; } internal Boolean SkipLocalisation { get; set; } public TemplateDefinition TemplateDef { get; set; } private HttpContext currentContext; private HttpContext CurrentContext { get { return currentContext ?? (currentContext = HttpContext.Current); } } private PortalSettings hostPortalSettings; internal PortalSettings HostPortalSettings { get { return hostPortalSettings ?? (hostPortalSettings = PortalController.Instance.GetCurrentPortalSettings()); } } private readonly Dictionary<string, string> nodeSelectorAliases = new Dictionary<string, string> { {"rootonly", "*,0,0"}, {"rootchildren", "+0"}, {"currentchildren", "."} }; internal void ApplySettings(Settings settings) { menuSettings = settings; } internal virtual void PreRender() { TemplateDef.AddTemplateArguments(menuSettings.TemplateArguments, true); TemplateDef.AddClientOptions(menuSettings.ClientOptions, true); if (!String.IsNullOrEmpty(menuSettings.NodeXmlPath)) { LoadNodeXml(); } if (!String.IsNullOrEmpty(menuSettings.NodeSelector)) { ApplyNodeSelector(); } if (!String.IsNullOrEmpty(menuSettings.IncludeNodes)) { FilterNodes(menuSettings.IncludeNodes, false); } if (!String.IsNullOrEmpty(menuSettings.ExcludeNodes)) { FilterNodes(menuSettings.ExcludeNodes, true); } if (String.IsNullOrEmpty(menuSettings.NodeXmlPath) && !SkipLocalisation) { new Localiser(HostPortalSettings.PortalId).LocaliseNode(RootNode); } if (!String.IsNullOrEmpty(menuSettings.NodeManipulator)) { ApplyNodeManipulator(); } var imagePathOption = menuSettings.ClientOptions.Find(o => o.Name.Equals("PathImage", StringComparison.InvariantCultureIgnoreCase)); RootNode.ApplyContext( imagePathOption == null ? DNNContext.Current.PortalSettings.HomeDirectory : imagePathOption.Value); TemplateDef.PreRender(); } internal void Render(HtmlTextWriter htmlWriter) { if (Host.DebugMode) { htmlWriter.Write("<!-- DDRmenu v07.04.01 - {0} template -->", menuSettings.MenuStyle); } UserInfo user = null; if (menuSettings.IncludeContext) { user = UserController.Instance.GetCurrentUserInfo(); user.Roles = user.Roles; // Touch roles to populate } TemplateDef.AddClientOptions(new List<ClientOption> {new ClientString("MenuStyle", menuSettings.MenuStyle)}, false); TemplateDef.Render(new MenuXml {root = RootNode, user = user}, htmlWriter); } private void LoadNodeXml() { menuSettings.NodeXmlPath = MapPath( new PathResolver(TemplateDef.Folder).Resolve( menuSettings.NodeXmlPath, PathResolver.RelativeTo.Manifest, PathResolver.RelativeTo.Skin, PathResolver.RelativeTo.Module, PathResolver.RelativeTo.Portal, PathResolver.RelativeTo.Dnn)); var cache = CurrentContext.Cache; RootNode = cache[menuSettings.NodeXmlPath] as MenuNode; if (RootNode != null) { return; } using (var reader = XmlReader.Create(menuSettings.NodeXmlPath)) { reader.ReadToFollowing("root"); RootNode = (MenuNode)(new XmlSerializer(typeof(MenuNode), "").Deserialize(reader)); } cache.Insert(menuSettings.NodeXmlPath, RootNode, new CacheDependency(menuSettings.NodeXmlPath)); } private void FilterNodes(string nodeString, bool exclude) { var nodeTextStrings = SplitAndTrim(nodeString); var filteredNodes = new List<MenuNode>(); var tc = new TabController(); var flattenedNodes = new MenuNode(); foreach (var nodeText in nodeTextStrings) { if (nodeText.StartsWith("[")) { var roleName = nodeText.Substring(1, nodeText.Length - 2); filteredNodes.AddRange( RootNode.Children.FindAll( n => { var tab = TabController.Instance.GetTab(n.TabId, Null.NullInteger, false); foreach (TabPermissionInfo perm in tab.TabPermissions) { if (perm.AllowAccess && (perm.PermissionKey == "VIEW") && ((perm.RoleID == -1) || (perm.RoleName.ToLowerInvariant() == roleName))) { return true; } } return false; })); } else if (nodeText.StartsWith("#")) { var tagName = nodeText.Substring(1, nodeText.Length - 1); if (!string.IsNullOrEmpty(tagName)) { //flatten nodes first. tagged pages should be flattened and not heirarchical if (flattenedNodes != new MenuNode()) flattenedNodes.Children = RootNode.FlattenChildren(RootNode); filteredNodes.AddRange( flattenedNodes.Children.FindAll( n => { var tab = tc.GetTab(n.TabId, Null.NullInteger, false); return (tab.Terms.Any(x => x.Name.ToLower() == tagName)); })); } } else { var nodeText2 = nodeText; filteredNodes.AddRange( RootNode.Children.FindAll( n => { var nodeName = n.Text.ToLowerInvariant(); var nodeId = n.TabId.ToString(); return (nodeText2 == nodeName || nodeText2 == nodeId); })); } } // if filtered for foksonomy tags, use flat tree to get all related pages in nodeselection if (flattenedNodes.HasChildren()) RootNode = flattenedNodes; RootNode.Children.RemoveAll(n => filteredNodes.Contains(n) == exclude); } private void ApplyNodeSelector() { string selector; if (!nodeSelectorAliases.TryGetValue(menuSettings.NodeSelector.ToLowerInvariant(), out selector)) { selector = menuSettings.NodeSelector; } var selectorSplit = SplitAndTrim(selector); var currentTabId = HostPortalSettings.ActiveTab.TabID; var newRoot = RootNode; var rootSelector = selectorSplit[0]; if (rootSelector != "*") { if (rootSelector.StartsWith("+")) { var depth = Convert.ToInt32(rootSelector); newRoot = RootNode; for (var i = 0; i <= depth; i++) { newRoot = newRoot.Children.Find(n => n.Breadcrumb); if (newRoot == null) { RootNode = new MenuNode(); return; } } } else if (rootSelector.StartsWith("-") || rootSelector == "0" || rootSelector == ".") { newRoot = RootNode.FindById(currentTabId); if (newRoot == null) { RootNode = new MenuNode(); return; } if (rootSelector.StartsWith("-")) { for (var n = Convert.ToInt32(rootSelector); n < 0; n++) { if (newRoot.Parent != null) { newRoot = newRoot.Parent; } } } } else { newRoot = RootNode.FindByNameOrId(rootSelector); if (newRoot == null) { RootNode = new MenuNode(); return; } } } // ReSharper disable PossibleNullReferenceException RootNode = new MenuNode(newRoot.Children); // ReSharper restore PossibleNullReferenceException if (selectorSplit.Count > 1) { for (var n = Convert.ToInt32(selectorSplit[1]); n > 0; n--) { var newChildren = new List<MenuNode>(); foreach (var child in RootNode.Children) { newChildren.AddRange(child.Children); } RootNode = new MenuNode(newChildren); } } if (selectorSplit.Count > 2) { var newChildren = RootNode.Children; for (var n = Convert.ToInt32(selectorSplit[2]); n > 0; n--) { var nextChildren = new List<MenuNode>(); foreach (var child in newChildren) { nextChildren.AddRange(child.Children); } newChildren = nextChildren; } foreach (var node in newChildren) { node.Children = null; } } } private void ApplyNodeManipulator() { RootNode = new MenuNode( ((INodeManipulator)Activator.CreateInstance(BuildManager.GetType(menuSettings.NodeManipulator, true, true))). ManipulateNodes(RootNode.Children, HostPortalSettings)); } protected string MapPath(string path) { return String.IsNullOrEmpty(path) ? "" : Path.GetFullPath(CurrentContext.Server.MapPath(path)); } private static List<string> SplitAndTrim(string str) { return new List<String>(str.Split(',')).ConvertAll(s => s.Trim().ToLowerInvariant()); } } }
using J2N.Collections.Generic.Extensions; using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Text.RegularExpressions; namespace Lucene.Net.Index { /* * 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 Codec = Lucene.Net.Codecs.Codec; using Directory = Lucene.Net.Store.Directory; using Lucene3xSegmentInfoFormat = Lucene.Net.Codecs.Lucene3x.Lucene3xSegmentInfoFormat; using TrackingDirectoryWrapper = Lucene.Net.Store.TrackingDirectoryWrapper; /// <summary> /// Information about a segment such as it's name, directory, and files related /// to the segment. /// <para/> /// @lucene.experimental /// </summary> public sealed class SegmentInfo { // TODO: remove these from this class, for now this is the representation /// <summary> /// Used by some member fields to mean not present (e.g., /// norms, deletions). /// </summary> public static readonly int NO = -1; // e.g. no norms; no deletes; /// <summary> /// Used by some member fields to mean present (e.g., /// norms, deletions). /// </summary> public static readonly int YES = 1; // e.g. have norms; have deletes; /// <summary> /// Unique segment name in the directory. </summary> public string Name { get; private set; } private int docCount; // number of docs in seg /// <summary> /// Where this segment resides. </summary> public Directory Dir { get; private set; } private bool isCompoundFile; private Codec codec; private IDictionary<string, string> diagnostics; [Obsolete("not used anymore")] private IDictionary<string, string> attributes; // Tracks the Lucene version this segment was created with, since 3.1. Null // indicates an older than 3.0 index, and it's used to detect a too old index. // The format expected is "x.y" - "2.x" for pre-3.0 indexes (or null), and // specific versions afterwards ("3.0", "3.1" etc.). // see Constants.LUCENE_MAIN_VERSION. private string version; /// <summary> /// Gets or Sets diagnostics saved into the segment when it was written. /// </summary> public IDictionary<string, string> Diagnostics { get => diagnostics; set => this.diagnostics = value; } /// <summary> /// Construct a new complete <see cref="SegmentInfo"/> instance from input. /// <para>Note: this is public only to allow access from /// the codecs package.</para> /// </summary> public SegmentInfo(Directory dir, string version, string name, int docCount, bool isCompoundFile, Codec codec, IDictionary<string, string> diagnostics) : this(dir, version, name, docCount, isCompoundFile, codec, diagnostics, null) { } /// <summary> /// Construct a new complete <see cref="SegmentInfo"/> instance from input. /// <para>Note: this is public only to allow access from /// the codecs package.</para> /// </summary> public SegmentInfo(Directory dir, string version, string name, int docCount, bool isCompoundFile, Codec codec, IDictionary<string, string> diagnostics, IDictionary<string, string> attributes) { Debug.Assert(!(dir is TrackingDirectoryWrapper)); this.Dir = dir; this.version = version; this.Name = name; this.docCount = docCount; this.isCompoundFile = isCompoundFile; this.codec = codec; this.diagnostics = diagnostics; #pragma warning disable 612, 618 this.attributes = attributes; #pragma warning restore 612, 618 } [Obsolete("separate norms are not supported in >= 4.0")] internal bool HasSeparateNorms => GetAttribute(Lucene3xSegmentInfoFormat.NORMGEN_KEY) != null; /// <summary> /// Gets or Sets whether this segment is stored as a compound file. /// <c>true</c> if this is a compound file; /// else, <c>false</c> /// </summary> public bool UseCompoundFile { get => isCompoundFile; set => this.isCompoundFile = value; } /// <summary> /// Gets or Sets <see cref="Codecs.Codec"/> that wrote this segment. /// Setter can only be called once. </summary> public Codec Codec { get => codec; set { Debug.Assert(this.codec == null); if (value == null) { throw new ArgumentException("codec must be non-null"); } this.codec = value; } } /// <summary> /// Returns number of documents in this segment (deletions /// are not taken into account). /// </summary> public int DocCount { get { if (this.docCount == -1) { throw new InvalidOperationException("docCount isn't set yet"); } return docCount; } internal set // NOTE: leave package private { if (this.docCount != -1) { throw new InvalidOperationException("docCount was already set"); } this.docCount = value; } } /// <summary> /// Return all files referenced by this <see cref="SegmentInfo"/>. </summary> public ISet<string> GetFiles() { if (setFiles == null) { throw new InvalidOperationException("files were not computed yet"); } return setFiles.AsReadOnly(); } public override string ToString() { return ToString(Dir, 0); } /// <summary> /// Used for debugging. Format may suddenly change. /// /// <para>Current format looks like /// <c>_a(3.1):c45/4</c>, which means the segment's /// name is <c>_a</c>; it was created with Lucene 3.1 (or /// '?' if it's unknown); it's using compound file /// format (would be <c>C</c> if not compound); it /// has 45 documents; it has 4 deletions (this part is /// left off when there are no deletions).</para> /// </summary> public string ToString(Directory dir, int delCount) { StringBuilder s = new StringBuilder(); s.Append(Name).Append('(').Append(version == null ? "?" : version).Append(')').Append(':'); char cfs = UseCompoundFile ? 'c' : 'C'; s.Append(cfs); if (this.Dir != dir) { s.Append('x'); } s.Append(docCount); if (delCount != 0) { s.Append('/').Append(delCount); } // TODO: we could append toString of attributes() here? return s.ToString(); } /// <summary> /// We consider another <see cref="SegmentInfo"/> instance equal if it /// has the same dir and same name. /// </summary> public override bool Equals(object obj) { if (this == obj) { return true; } if (obj is SegmentInfo) { SegmentInfo other = (SegmentInfo)obj; return other.Dir == Dir && other.Name.Equals(Name, StringComparison.Ordinal); } else { return false; } } public override int GetHashCode() { return Dir.GetHashCode() + Name.GetHashCode(); } /// <summary> /// Used by DefaultSegmentInfosReader to upgrade a 3.0 segment to record its /// version is "3.0". this method can be removed when we're not required to /// support 3x indexes anymore, e.g. in 5.0. /// <para/> /// <b>NOTE:</b> this method is used for internal purposes only - you should /// not modify the version of a <see cref="SegmentInfo"/>, or it may result in unexpected /// exceptions thrown when you attempt to open the index. /// <para/> /// @lucene.internal /// </summary> public string Version { get => version; set => this.version = value; } private ISet<string> setFiles; /// <summary> /// Sets the files written for this segment. </summary> public void SetFiles(ISet<string> files) { CheckFileNames(files); setFiles = files; } /// <summary> /// Add these files to the set of files written for this /// segment. /// </summary> public void AddFiles(ICollection<string> files) { CheckFileNames(files); setFiles.UnionWith(files); } /// <summary> /// Add this file to the set of files written for this /// segment. /// </summary> public void AddFile(string file) { CheckFileNames(new[] { file }); setFiles.Add(file); } private void CheckFileNames(ICollection<string> files) { Regex r = IndexFileNames.CODEC_FILE_PATTERN; foreach (string file in files) { if (!r.IsMatch(file)) { throw new ArgumentException("invalid codec filename '" + file + "', must match: " + IndexFileNames.CODEC_FILE_PATTERN.ToString()); } } } /// <summary> /// Get a codec attribute value, or null if it does not exist /// </summary> [Obsolete("no longer supported")] public string GetAttribute(string key) { if (attributes == null) { return null; } else { string attribute; attributes.TryGetValue(key, out attribute); return attribute; } } /// <summary> /// Puts a codec attribute value. /// <para/> /// This is a key-value mapping for the field that the codec can use to store /// additional metadata, and will be available to the codec when reading the /// segment via <see cref="GetAttribute(string)"/> /// <para/> /// If a value already exists for the field, it will be replaced with the new /// value. /// </summary> [Obsolete("no longer supported")] public string PutAttribute(string key, string value) { if (attributes == null) { attributes = new Dictionary<string, string>(); } return attributes[key] = value; } /// <summary> /// Returns the internal codec attributes map. May be null if no mappings exist. /// </summary> [Obsolete("no longer supported")] public IDictionary<string, string> Attributes => attributes; } }
/* * The MIT License (MIT) * * Copyright (c) 2013 Alistair Leslie-Hughes * * 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.ComponentModel; using System.Drawing; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Microsoft.DirectX.PrivateImplementationDetails; namespace Microsoft.DirectX.Direct3D { public class Font : IDisposable { public event EventHandler Disposing { [MethodImpl(MethodImplOptions.Synchronized)] add { throw new NotImplementedException (); } [MethodImpl(MethodImplOptions.Synchronized)] remove { throw new NotImplementedException (); } } public event EventHandler Reset { [MethodImpl(MethodImplOptions.Synchronized)] add { throw new NotImplementedException (); } [MethodImpl(MethodImplOptions.Synchronized)] remove { throw new NotImplementedException (); } } public event EventHandler Lost { [MethodImpl(MethodImplOptions.Synchronized)] add { throw new NotImplementedException (); } [MethodImpl(MethodImplOptions.Synchronized)] remove { throw new NotImplementedException (); } } [CLSCompliant(false)] public unsafe ID3DXFont* UnmanagedComPointer { get { throw new NotImplementedException (); } } public bool Disposed { get { throw new NotImplementedException (); } } [EditorBrowsable(EditorBrowsableState.Never)] public virtual IntPtr NativePointer { get { throw new NotImplementedException (); } } public bool IsDisposed { get { throw new NotImplementedException (); } } public IntPtr DeviceContext { get { throw new NotImplementedException (); } } public FontDescription Description { get { throw new NotImplementedException (); } } public Device Device { get { throw new NotImplementedException (); } } public static bool operator == (Font left, Font right) { throw new NotImplementedException (); } public static bool operator != (Font left, Font right) { throw new NotImplementedException (); } public override bool Equals (object compare) { throw new NotImplementedException (); } public override int GetHashCode () { throw new NotImplementedException (); } public int DrawText (Sprite sprite, string text, int x, int y, Color color) { throw new NotImplementedException (); } public int DrawText (Sprite sprite, string text, int x, int y, int color) { throw new NotImplementedException (); } public int DrawText (Sprite sprite, string text, Point pos, Color color) { throw new NotImplementedException (); } public int DrawText (Sprite sprite, string text, Point pos, int color) { throw new NotImplementedException (); } public int DrawText (Sprite sprite, string text, Rectangle rect, DrawTextFormat format, Color color) { throw new NotImplementedException (); } public int DrawText (Sprite sprite, string text, Rectangle rect, DrawTextFormat format, int color) { throw new NotImplementedException (); } public Font (IntPtr pInterface) { throw new NotImplementedException (); } public Font (Device device, Font font) { throw new NotImplementedException (); } public Font (Device device, FontDescription description) { throw new NotImplementedException (); } public Font (Device device, int height, int width, FontWeight weight, int miplevels, bool italic, CharacterSet charset, Precision outputPrecision, FontQuality quality, PitchAndFamily pitchFamily, string faceName) { throw new NotImplementedException (); } public void OnLostDevice () { throw new NotImplementedException (); } public void OnResetDevice () { throw new NotImplementedException (); } public int DrawString (Sprite sprite, string text, int x, int y, Color color) { throw new NotImplementedException (); } public int DrawString (Sprite sprite, string text, int x, int y, int color) { throw new NotImplementedException (); } public int DrawString (Sprite sprite, string text, Point? position, Color color) { throw new NotImplementedException (); } public int DrawString (Sprite sprite, string text, Point? position, int color) { throw new NotImplementedException (); } public int DrawString (Sprite sprite, string text, Rectangle? rect, DrawStringFormat format, Color color) { throw new NotImplementedException (); } public int DrawString (Sprite sprite, string text, Rectangle? rect, DrawStringFormat format, int color) { throw new NotImplementedException (); } public Rectangle MeasureString (Sprite sprite, string text, DrawStringFormat format, Color color) { throw new NotImplementedException (); } public Rectangle MeasureString (Sprite sprite, string text, DrawStringFormat format, int color) { throw new NotImplementedException (); } public void PreloadCharacters (int first, int last) { throw new NotImplementedException (); } public void PreloadGlyphs (int first, int last) { throw new NotImplementedException (); } public void PreloadText (string text) { throw new NotImplementedException (); } public Texture GetGlyphData (int glyph) { throw new NotImplementedException (); } protected void raise_Lost (object value0, EventArgs value1) { throw new NotImplementedException (); } protected void raise_Reset (object value0, EventArgs value1) { throw new NotImplementedException (); } protected void raise_Disposing (object value0, EventArgs value1) { throw new NotImplementedException (); } public override string ToString () { throw new NotImplementedException (); } [EditorBrowsable(EditorBrowsableState.Never)] public virtual void UpdateNativePointer (IntPtr pInterface) { throw new NotImplementedException (); } protected virtual void Dispose (bool flag) { throw new NotImplementedException (); } public void Dispose () { throw new NotImplementedException (); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using StructureMap.Pipeline; using StructureMap.Query; namespace StructureMap { /// <summary> /// The main "container" object that implements the Service Locator pattern /// </summary> public interface IContainer : IDisposable { /// <summary> /// Provides queryable access to the configured PluginType's and Instances of this Container /// </summary> IModel Model { get; } /// <summary> /// Creates or finds the named instance of the pluginType /// </summary> /// <param name="pluginType"></param> /// <param name="instanceKey"></param> /// <returns></returns> object GetInstance(Type pluginType, string instanceKey); /// <summary> /// Creates or finds the default instance of the pluginType /// </summary> /// <param name="pluginType"></param> /// <returns></returns> object GetInstance(Type pluginType); /// <summary> /// Creates a new instance of the requested type using the supplied Instance. Mostly used internally /// </summary> /// <param name="pluginType"></param> /// <param name="instance"></param> /// <returns></returns> object GetInstance(Type pluginType, Instance instance); /// <summary> /// Creates or finds the named instance of T /// </summary> /// <typeparam name="T"></typeparam> /// <param name="instanceKey"></param> /// <returns></returns> T GetInstance<T>(string instanceKey); /// <summary> /// Creates or finds the default instance of type T /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> T GetInstance<T>(); /// <summary> /// Creates a new instance of the requested type T using the supplied Instance. Mostly used internally /// </summary> /// <param name="instance"></param> /// <returns></returns> T GetInstance<T>(Instance instance); /// <summary> /// Creates or resolves all registered instances of type T /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> IEnumerable<T> GetAllInstances<T>(); /// <summary> /// Creates or resolves all registered instances of the pluginType /// </summary> /// <param name="pluginType"></param> /// <returns></returns> IEnumerable GetAllInstances(Type pluginType); /// <summary> /// Creates or finds the named instance of the pluginType. Returns null if the named instance is not known to the container. /// </summary> /// <param name="pluginType"></param> /// <param name="instanceKey"></param> /// <returns></returns> object TryGetInstance(Type pluginType, string instanceKey); /// <summary> /// Creates or finds the default instance of the pluginType. Returns null if the pluginType is not known to the container. /// </summary> /// <param name="pluginType"></param> /// <returns></returns> object TryGetInstance(Type pluginType); /// <summary> /// Creates or finds the default instance of type T. Returns the default value of T if it is not known to the container. /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> T TryGetInstance<T>(); /// <summary> /// Creates or finds the named instance of type T. Returns the default value of T if the named instance is not known to the container. /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> T TryGetInstance<T>(string instanceKey); /// <summary> /// Used to add additional configuration to a Container *after* the initialization. /// </summary> /// <param name="configure"></param> void Configure(Action<ConfigurationExpression> configure); /// <summary> /// Injects the given object into a Container as the default for the designated /// TPluginType. Mostly used for temporarily setting up return values of the Container /// to introduce mocks or stubs during automated testing scenarios /// </summary> /// <typeparam name="TPluginType"></typeparam> /// <param name="instance"></param> void Inject<TPluginType>(TPluginType instance) where TPluginType : class; /// <summary> /// Injects the given object into a Container as the default for the designated /// pluginType. Mostly used for temporarily setting up return values of the Container /// to introduce mocks or stubs during automated testing scenarios /// </summary> /// <param name="pluginType"></param> /// <param name="object"></param> void Inject(Type pluginType, object @object); /// <summary> /// Gets a new child container for the named profile using that profile's defaults with /// fallback to the original parent /// </summary> /// <param name="profileName"></param> /// <returns></returns> IContainer GetProfile(string profileName); /// <summary> /// Returns a report detailing the complete configuration of all PluginTypes and Instances /// </summary> /// <returns></returns> /// <param name="pluginType">Optional parameter to filter the results down to just this plugin type</param> /// <param name="assembly">Optional parameter to filter the results down to only plugin types from this Assembly</param> /// <param name="@namespace">Optional parameter to filter the results down to only plugin types from this namespace</param> /// <param name="typeName">Optional parameter to filter the results down to any plugin type whose name contains this text</param> string WhatDoIHave(Type pluginType = null, Assembly assembly = null, string @namespace = null, string typeName = null); /// <summary> /// Use with caution! Does a full environment test of the configuration of this container. Will try to create every configured /// instance and afterward calls any methods marked with the [ValidationMethod] attribute /// </summary> void AssertConfigurationIsValid(); /// <summary> /// Gets all configured instances of type T using explicitly configured arguments from the "args" /// </summary> /// <typeparam name="T"></typeparam> /// <param name="args"></param> /// <returns></returns> IEnumerable<T> GetAllInstances<T>(ExplicitArguments args); /// <summary> /// Gets the default instance of type T using the explicitly configured arguments from the "args" /// </summary> /// <param name="type"></param> /// <param name="args"></param> /// <returns></returns> IEnumerable GetAllInstances(Type type, ExplicitArguments args); /// <summary> /// Gets the default instance of T, but built with the overridden /// arguments from args /// </summary> /// <typeparam name="T"></typeparam> /// <param name="args"></param> /// <returns></returns> T GetInstance<T>(ExplicitArguments args); /// <summary> /// Starts a request for an instance or instances with explicitly configured arguments. Specifies that any dependency /// of type T should be "arg" /// </summary> /// <typeparam name="T"></typeparam> /// <param name="arg"></param> /// <returns></returns> ExplicitArgsExpression With<T>(T arg); /// <summary> /// Starts a request for an instance or instances with explicitly configured arguments. Specifies that any dependency or primitive argument /// with the designated name should be the next value. /// </summary> /// <param name="argName"></param> /// <returns></returns> IExplicitProperty With(string argName); /// <summary> /// Gets the default instance of the pluginType using the explicitly configured arguments from the "args" /// </summary> /// <param name="pluginType"></param> /// <param name="args"></param> /// <returns></returns> object GetInstance(Type pluginType, ExplicitArguments args); /// <summary> /// Removes all configured instances of type T from the Container. Use with caution! /// </summary> /// <typeparam name="T"></typeparam> void EjectAllInstancesOf<T>(); /// <summary> /// The "BuildUp" method takes in an already constructed object /// and uses Setter Injection to push in configured dependencies /// of that object /// </summary> /// <param name="target"></param> void BuildUp(object target); /// <summary> /// Convenience method to request an object using an Open Generic /// Type and its parameter Types /// </summary> /// <param name="templateType"></param> /// <returns></returns> /// <example> /// IFlattener flattener1 = container.ForGenericType(typeof (IFlattener&lt;&gt;)) /// .WithParameters(typeof (Address)).GetInstanceAs&lt;IFlattener&gt;(); /// </example> Container.OpenGenericTypeExpression ForGenericType(Type templateType); /// <summary> /// Gets the named instance of the pluginType using the explicitly configured arguments from the "args" /// </summary> /// <typeparam name="T"></typeparam> /// <param name="args"></param> /// <param name="name"></param> /// <returns></returns> T GetInstance<T>(ExplicitArguments args, string name); /// <summary> /// Starts a request for an instance or instances with explicitly configured arguments. Specifies that any dependency /// of type T should be "arg" /// </summary> /// <param name="pluginType"></param> /// <param name="arg"></param> /// <returns></returns> ExplicitArgsExpression With(Type pluginType, object arg); /// <summary> /// Shortcut syntax for using an object to find a service that handles /// that type of object by using an open generic type /// </summary> /// <example> /// IHandler handler = container.ForObject(shipment) /// .GetClosedTypeOf(typeof (IHandler<>)) /// .As<IHandler>(); /// </example> /// <param name="subject"></param> /// <returns></returns> CloseGenericTypeExpression ForObject(object subject); /// <summary> /// Starts a "Nested" Container for atomic, isolated access /// </summary> /// <returns></returns> IContainer GetNestedContainer(); /// <summary> /// Starts a new "Nested" Container for atomic, isolated service location. Opens /// </summary> /// <param name="profileName"></param> /// <returns></returns> IContainer GetNestedContainer(string profileName); /// <summary> /// The name of the container. By default this is set to /// a random Guid. This is a convience property to /// assist with debugging. Feel free to set to anything, /// as this is not used in any logic. /// </summary> string Name { get; set; } /// <summary> /// Is this container the root, a profile or child, or a nested container? /// </summary> ContainerRole Role { get; } /// <summary> /// The profile name of this container /// </summary> string ProfileName { get; } /// <summary> /// Starts a request for an instance or instances with explicitly configured /// arguments /// </summary> /// <param name="action"></param> /// <returns></returns> ExplicitArgsExpression With(Action<IExplicitArgsExpression> action); } }
/* * 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 System; using NUnit.Framework; using Analyzer = Lucene.Net.Analysis.Analyzer; using LowerCaseTokenizer = Lucene.Net.Analysis.LowerCaseTokenizer; using Token = Lucene.Net.Analysis.Token; using TokenFilter = Lucene.Net.Analysis.TokenFilter; using TokenStream = Lucene.Net.Analysis.TokenStream; using PayloadAttribute = Lucene.Net.Analysis.Tokenattributes.PayloadAttribute; using Document = Lucene.Net.Documents.Document; using Field = Lucene.Net.Documents.Field; using IndexWriter = Lucene.Net.Index.IndexWriter; using Payload = Lucene.Net.Index.Payload; using Term = Lucene.Net.Index.Term; using DefaultSimilarity = Lucene.Net.Search.DefaultSimilarity; using IndexSearcher = Lucene.Net.Search.IndexSearcher; using QueryUtils = Lucene.Net.Search.QueryUtils; using ScoreDoc = Lucene.Net.Search.ScoreDoc; using Searcher = Lucene.Net.Search.Searcher; using TopDocs = Lucene.Net.Search.TopDocs; using SpanQuery = Lucene.Net.Search.Spans.SpanQuery; using RAMDirectory = Lucene.Net.Store.RAMDirectory; using SpanNearQuery = Lucene.Net.Search.Spans.SpanNearQuery; using English = Lucene.Net.Util.English; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; namespace Lucene.Net.Search.Payloads { [TestFixture] public class TestPayloadNearQuery:LuceneTestCase { private void InitBlock() { similarity = new BoostingSimilarity(); } private IndexSearcher searcher; private BoostingSimilarity similarity; private byte[] payload2 = new byte[]{2}; private byte[] payload4 = new byte[]{4}; public TestPayloadNearQuery():base() { InitBlock(); } private class PayloadAnalyzer:Analyzer { public PayloadAnalyzer(TestPayloadNearQuery enclosingInstance) { InitBlock(enclosingInstance); } private void InitBlock(TestPayloadNearQuery enclosingInstance) { this.enclosingInstance = enclosingInstance; } private TestPayloadNearQuery enclosingInstance; public TestPayloadNearQuery Enclosing_Instance { get { return enclosingInstance; } } public override TokenStream TokenStream(System.String fieldName, System.IO.TextReader reader) { TokenStream result = new LowerCaseTokenizer(reader); result = new PayloadFilter(enclosingInstance, result, fieldName); return result; } } private class PayloadFilter:TokenFilter { private void InitBlock(TestPayloadNearQuery enclosingInstance) { this.enclosingInstance = enclosingInstance; } private TestPayloadNearQuery enclosingInstance; public TestPayloadNearQuery Enclosing_Instance { get { return enclosingInstance; } } internal System.String fieldName; internal int numSeen = 0; protected internal PayloadAttribute payAtt; public PayloadFilter(TestPayloadNearQuery enclosingInstance, TokenStream input, System.String fieldName):base(input) { InitBlock(enclosingInstance); this.fieldName = fieldName; payAtt = (PayloadAttribute) AddAttribute(typeof(PayloadAttribute)); } public override bool IncrementToken() { bool result = false; if (input.IncrementToken() == true) { if (numSeen % 2 == 0) { payAtt.SetPayload(new Payload(Enclosing_Instance.payload2)); } else { payAtt.SetPayload(new Payload(Enclosing_Instance.payload4)); } numSeen++; result = true; } return result; } } private PayloadNearQuery NewPhraseQuery(System.String fieldName, System.String phrase, bool inOrder) { int n; System.String[] words = System.Text.RegularExpressions.Regex.Split(phrase, "[\\s]+"); SpanQuery[] clauses = new SpanQuery[words.Length]; for (int i = 0; i < clauses.Length; i++) { clauses[i] = new PayloadTermQuery(new Term(fieldName, words[i]), new AveragePayloadFunction()); } return new PayloadNearQuery(clauses, 0, inOrder); } [SetUp] public override void SetUp() { base.SetUp(); RAMDirectory directory = new RAMDirectory(); PayloadAnalyzer analyzer = new PayloadAnalyzer(this); IndexWriter writer = new IndexWriter(directory, analyzer, true, IndexWriter.MaxFieldLength.LIMITED); writer.SetSimilarity(similarity); //writer.infoStream = System.out; for (int i = 0; i < 1000; i++) { Document doc = new Document(); doc.Add(new Field("field", English.IntToEnglish(i), Field.Store.YES, Field.Index.ANALYZED)); System.String txt = English.IntToEnglish(i) + ' ' + English.IntToEnglish(i + 1); doc.Add(new Field("field2", txt, Field.Store.YES, Field.Index.ANALYZED)); writer.AddDocument(doc); } writer.Optimize(); writer.Close(); searcher = new IndexSearcher(directory, true); searcher.SetSimilarity(similarity); } [Test] public virtual void Test() { PayloadNearQuery query; TopDocs hits; query = NewPhraseQuery("field", "twenty two", true); QueryUtils.Check(query); // all 10 hits should have score = 3 because adjacent terms have payloads of 2,4 // and all the similarity factors are set to 1 hits = searcher.Search(query, null, 100); Assert.IsTrue(hits != null, "hits is null and it shouldn't be"); Assert.IsTrue(hits.TotalHits == 10, "should be 10 hits"); for (int j = 0; j < hits.ScoreDocs.Length; j++) { ScoreDoc doc = hits.ScoreDocs[j]; Assert.IsTrue(doc.score == 3, doc.score + " does not equal: " + 3); } for (int i = 1; i < 10; i++) { query = NewPhraseQuery("field", English.IntToEnglish(i) + " hundred", true); // all should have score = 3 because adjacent terms have payloads of 2,4 // and all the similarity factors are set to 1 hits = searcher.Search(query, null, 100); Assert.IsTrue(hits != null, "hits is null and it shouldn't be"); Assert.IsTrue(hits.TotalHits == 100, "should be 100 hits"); for (int j = 0; j < hits.ScoreDocs.Length; j++) { ScoreDoc doc = hits.ScoreDocs[j]; // System.out.println("Doc: " + doc.toString()); // System.out.println("Explain: " + searcher.explain(query, doc.doc)); Assert.IsTrue(doc.score == 3, doc.score + " does not equal: " + 3); } } } [Test] public virtual void TestPayloadNear() { SpanNearQuery q1, q2; PayloadNearQuery query; TopDocs hits; // SpanNearQuery(clauses, 10000, false) q1 = SpanNearQuery_Renamed("field2", "twenty two"); q2 = SpanNearQuery_Renamed("field2", "twenty three"); SpanQuery[] clauses = new SpanQuery[2]; clauses[0] = q1; clauses[1] = q2; query = new PayloadNearQuery(clauses, 10, false); // System.out.println(query.toString()); Assert.AreEqual(12, searcher.Search(query, null, 100).TotalHits); /* * System.out.println(hits.totalHits); for (int j = 0; j < * hits.scoreDocs.length; j++) { ScoreDoc doc = hits.scoreDocs[j]; * System.out.println("doc: "+doc.doc+", score: "+doc.score); } */ } private SpanNearQuery SpanNearQuery_Renamed(System.String fieldName, System.String words) { System.String[] wordList = System.Text.RegularExpressions.Regex.Split(words, "[\\s]+"); SpanQuery[] clauses = new SpanQuery[wordList.Length]; for (int i = 0; i < clauses.Length; i++) { clauses[i] = new PayloadTermQuery(new Term(fieldName, wordList[i]), new AveragePayloadFunction()); } return new SpanNearQuery(clauses, 10000, false); } [Test] public virtual void TestLongerSpan() { PayloadNearQuery query; TopDocs hits; query = NewPhraseQuery("field", "nine hundred ninety nine", true); hits = searcher.Search(query, null, 100); ScoreDoc doc = hits.ScoreDocs[0]; // System.out.println("Doc: " + doc.toString()); // System.out.println("Explain: " + searcher.explain(query, doc.doc)); Assert.IsTrue(hits != null, "hits is null and it shouldn't be"); Assert.IsTrue(hits.TotalHits == 1, "there should only be one hit"); // should have score = 3 because adjacent terms have payloads of 2,4 Assert.IsTrue(doc.score == 3, doc.score + " does not equal: " + 3); } [Test] public virtual void TestComplexNested() { PayloadNearQuery query; TopDocs hits; // combine ordered and unordered spans with some nesting to make sure all payloads are counted SpanQuery q1 = NewPhraseQuery("field", "nine hundred", true); SpanQuery q2 = NewPhraseQuery("field", "ninety nine", true); SpanQuery q3 = NewPhraseQuery("field", "nine ninety", false); SpanQuery q4 = NewPhraseQuery("field", "hundred nine", false); SpanQuery[] clauses = new SpanQuery[]{new PayloadNearQuery(new SpanQuery[]{q1, q2}, 0, true), new PayloadNearQuery(new SpanQuery[]{q3, q4}, 0, false)}; query = new PayloadNearQuery(clauses, 0, false); hits = searcher.Search(query, null, 100); Assert.IsTrue(hits != null, "hits is null and it shouldn't be"); // should be only 1 hit - doc 999 Assert.IsTrue(hits.ScoreDocs.Length == 1, "should only be one hit"); // the score should be 3 - the average of all the underlying payloads ScoreDoc doc = hits.ScoreDocs[0]; // System.out.println("Doc: " + doc.toString()); // System.out.println("Explain: " + searcher.explain(query, doc.doc)); Assert.IsTrue(doc.score == 3, doc.score + " does not equal: " + 3); } // must be static for weight serialization tests [Serializable] internal class BoostingSimilarity:DefaultSimilarity { // TODO: Remove warning after API has been finalized public override float ScorePayload(int docId, System.String fieldName, int start, int end, byte[] payload, int offset, int length) { //we know it is size 4 here, so ignore the offset/length return payload[0]; } //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //Make everything else 1 so we see the effect of the payload //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! public override float LengthNorm(System.String fieldName, int numTerms) { return 1; } public override float QueryNorm(float sumOfSquaredWeights) { return 1; } public override float SloppyFreq(int distance) { return 1; } public override float Coord(int overlap, int maxOverlap) { return 1; } public override float Tf(float freq) { return 1; } // idf used for phrase queries public override float Idf(System.Collections.ICollection terms, Searcher searcher) { return 1; } } } }
//------------------------------------------------------------------------------ // <copyright file="WebException.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Net { using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.Serialization; using System.Security.Permissions; /*++ Abstract: Contains the defintion for the WebException object. This is a subclass of Exception that contains a WebExceptionStatus and possible a reference to a WebResponse. --*/ /// <devdoc> /// <para> /// Provides network communication exceptions to the application. /// /// This is the exception that is thrown by WebRequests when something untoward /// happens. It's a subclass of WebException that contains a WebExceptionStatus and possibly /// a reference to a WebResponse. The WebResponse is only present if we actually /// have a response from the remote server. /// </para> /// </devdoc> [Serializable] public class WebException : InvalidOperationException, ISerializable { private WebExceptionStatus m_Status = WebExceptionStatus.UnknownError; //Should be changed to GeneralFailure; private WebResponse m_Response; [NonSerialized] private WebExceptionInternalStatus m_InternalStatus = WebExceptionInternalStatus.RequestFatal; /// <devdoc> /// <para> /// Creates a new instance of the <see cref='System.Net.WebException'/> /// class with the default status /// <see langword='Error'/> from the /// <see cref='System.Net.WebExceptionStatus'/> values. /// </para> /// </devdoc> public WebException() { } /// <devdoc> /// <para> /// Creates a new instance of the <see cref='System.Net.WebException'/> class with the specified error /// message. /// </para> /// </devdoc> public WebException(string message) : this(message, null) { } /// <devdoc> /// <para> /// Creates a new instance of the <see cref='System.Net.WebException'/> class with the specified error /// message and nested exception. /// /// Message - Message string for exception. /// InnerException - Exception that caused this exception. /// /// </para> /// </devdoc> public WebException(string message, Exception innerException) : base(message, innerException) { } public WebException(string message, WebExceptionStatus status) : this(message, null, status, null) { } /// <devdoc> /// <para> /// Creates a new instance of the <see cref='System.Net.WebException'/> class with the specified error /// message and status. /// /// Message - Message string for exception. /// Status - Network status of exception /// </para> /// </devdoc> internal WebException(string message, WebExceptionStatus status, WebExceptionInternalStatus internalStatus, Exception innerException) : this(message, innerException, status, null, internalStatus) { } /// <devdoc> /// <para> /// Creates a new instance of the <see cref='System.Net.WebException'/> class with the specified error /// message, nested exception, status and response. /// /// Message - Message string for exception. /// InnerException - The exception that caused this one. /// Status - Network status of exception /// Response - The WebResponse we have. /// </para> /// </devdoc> public WebException(string message, Exception innerException, WebExceptionStatus status, WebResponse response) : this(message, null, innerException, status, response) { } internal WebException(string message, string data, Exception innerException, WebExceptionStatus status, WebResponse response) : base(message + (data != null ? ": '" + data + "'" : ""), innerException) { m_Status = status; m_Response = response; } internal WebException(string message, Exception innerException, WebExceptionStatus status, WebResponse response, WebExceptionInternalStatus internalStatus) : this(message, null, innerException, status, response, internalStatus) { } internal WebException(string message, string data, Exception innerException, WebExceptionStatus status, WebResponse response, WebExceptionInternalStatus internalStatus) : base(message + (data != null ? ": '" + data + "'" : ""), innerException) { m_Status = status; m_Response = response; m_InternalStatus = internalStatus; } protected WebException(SerializationInfo serializationInfo, StreamingContext streamingContext) : base(serializationInfo, streamingContext) { // m_Status = (WebExceptionStatus)serializationInfo.GetInt32("Status"); // m_InternalStatus = (WebExceptionInternalStatus)serializationInfo.GetInt32("InternalStatus"); } /// <internalonly/> [SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Justification = "System.dll is still using pre-v4 security model and needs this demand")] [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)] void ISerializable.GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext) { GetObjectData(serializationInfo, streamingContext); } [SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Justification = "System.dll is still using pre-v4 security model and needs this demand")] [SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.SerializationFormatter)] public override void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext){ base.GetObjectData(serializationInfo, streamingContext); //serializationInfo.AddValue("Status", (int)m_Status, typeof(int)); //serializationInfo.AddValue("InternalStatus", (int)m_InternalStatus, typeof(int)); } /// <devdoc> /// <para> /// Gets the status of the response. /// </para> /// </devdoc> public WebExceptionStatus Status { get { return m_Status; } } /// <devdoc> /// <para> /// Gets the error message returned from the remote host. /// </para> /// </devdoc> public WebResponse Response { get { return m_Response; } } /// <devdoc> /// <para> /// Gets the error message returned from the remote host. /// </para> /// </devdoc> internal WebExceptionInternalStatus InternalStatus { get { return m_InternalStatus; } } }; // class WebException internal enum WebExceptionInternalStatus { RequestFatal = 0, ServicePointFatal = 1, Recoverable = 2, Isolated = 3, } } // namespace System.Net
// // Copyright (c) 2009-2010 Krueger Systems, Inc. // // 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 MonoTouch.UIKit; using MonoTouch.Foundation; using System.Collections.Generic; using System.Drawing; namespace OData.Touch { public class DialogSection { public string Header { get; private set; } public string Footer { get; private set; } List<DialogElement> _elements = new List<DialogElement> (); public DialogSection () : this("", "") { } public DialogSection (string header) : this(header, "") { } public DialogSection (string header, string footer) { Header = header; Footer = footer; } public void Add (DialogElement element) { element.Section = this; _elements.Add (element); } public void Remove (DialogElement element) { element.Section = null; _elements.Remove (element); } public DialogElement NextElement (DialogElement element, Type elementType) { var start = _elements.IndexOf (element); for (var i = start + 1; i < _elements.Count; i++) { var e = _elements[i]; if (e.GetType () == elementType) { return e; } } return null; } public DialogElement GetElement (int row) { return _elements[row]; } public int NumElements { get { return _elements.Count; } } public void Clear () { foreach (var e in _elements) { e.Section = null; } _elements.Clear (); } } public abstract class DialogElement { bool _needsMeasure; public NSString ReuseIdentifier { get; private set; } public UITableViewCellAccessory Accessory { get; protected set; } public UITableViewCellStyle CellStyle { get; protected set; } public bool CanEdit { get; protected set; } public DialogSection Section { get; set; } public delegate void SelectedEventHandler (DialogViewController sender); public event SelectedEventHandler Selected; public DialogElement () { Accessory = UITableViewCellAccessory.None; CanEdit = false; _needsMeasure = true; ReuseIdentifier = new NSString (GetType ().Name); CellStyle = UITableViewCellStyle.Default; } public abstract void RefreshCell (UITableViewCell cell); public DialogElement NextElement (Type elementType) { if (Section == null) return null; else return Section.NextElement (this, elementType); } public UITableViewCell GetCell (UITableView table) { var c = table.DequeueReusableCell (ReuseIdentifier); c = new UITableViewCell (CellStyle, ReuseIdentifier); c.Accessory = Accessory; RefreshCell (c); return c; } protected virtual float GetHeight (float width) { return 44.0f; } float _height = 0; public void SetNeedsMeasure () { _needsMeasure = true; } public float Height { get { if (_needsMeasure) { _height = GetHeight (300); _needsMeasure = false; } return _height; } } public virtual void OnSelected (DialogViewController sender, NSIndexPath indexPath) { if (Selected != null) { Selected (sender); } } public virtual void OnDelete (DialogViewController sender, NSIndexPath indexPath) { } } public class TextFieldElement : DialogElement { public string Caption { get; private set; } public float CaptionWidth { get; private set; } public UITextField TextField { get; private set; } public string Value { get { return TextField.Text ?? ""; } set { TextField.Text = value; } } public TextFieldElement (string caption, string placeholder, float captionWidth) { Caption = caption; CaptionWidth = captionWidth; TextField = new UITextField (); TextField.Placeholder = placeholder; TextField.ReturnKeyType = UIReturnKeyType.Next; TextField.Tag = 42; TextField.TextColor = UIColor.FromRGB(56/255.0f, 84/255.0f, 135/255.0f); TextField.ShouldReturn += delegate { try { var next = NextElement (typeof(TextFieldElement)); if (next != null) { ((TextFieldElement)next).TextField.BecomeFirstResponder (); } else { TextField.ResignFirstResponder (); } return true; } catch (Exception error) { Log.Error (error); return true; } }; } public override void RefreshCell (UITableViewCell cell) { cell.SelectionStyle = UITableViewCellSelectionStyle.None; cell.TextLabel.Text = Caption; TextField.ReturnKeyType = NextElement (typeof(TextFieldElement)) != null ? UIReturnKeyType.Next : UIReturnKeyType.Default; var v = cell.ViewWithTag (42); if (v == null) { cell.ContentView.AddSubview (TextField); } else { if (v.Handle != TextField.Handle) { v.RemoveFromSuperview (); cell.ContentView.AddSubview (TextField); } } TextField.Frame = new RectangleF (CaptionWidth, 11, 300 - CaptionWidth, 22); } } public class TextViewElement : DialogElement { public string Caption { get; private set; } public UITextView TextView { get; private set; } public float TextViewHeight { get; private set; } public string Value { get { return TextView.Text ?? ""; } set { TextView.Text = value; } } public TextViewElement (string caption, float height) { Caption = caption; TextViewHeight = height; TextView = new UITextView(); TextView.Tag = 42; TextView.TextColor = UIColor.FromRGB(56/255.0f, 84/255.0f, 135/255.0f); } protected override float GetHeight (float width) { return 22.0f + TextViewHeight; } public override void RefreshCell (UITableViewCell cell) { cell.SelectionStyle = UITableViewCellSelectionStyle.None; cell.TextLabel.Text = Caption; var v = cell.ViewWithTag (42); if (v == null) { cell.ContentView.AddSubview (TextView); } else { if (v.Handle != TextView.Handle) { v.RemoveFromSuperview (); cell.ContentView.AddSubview (TextView); } } TextView.Frame = new RectangleF (70, 11, 220, TextViewHeight); } } public class StaticElement : DialogElement { public string Caption { get; private set; } public StaticElement (string caption) { Caption = caption; } public override void RefreshCell (UITableViewCell cell) { cell.TextLabel.Text = Caption; } } public class ActionElement : StaticElement { public Action Action { get; set; } public ActionElement (string caption, Action action) : base(caption) { Action = action; } public override void OnSelected (DialogViewController sender, NSIndexPath indexPath) { sender.TableView.DeselectRow (indexPath, true); Action (); base.OnSelected (sender, indexPath); } } public class LoadingElement : StaticElement { UIActivityIndicatorView _activity; public LoadingElement () : base("Loading...") { _activity = new UIActivityIndicatorView (UIActivityIndicatorViewStyle.Gray); var w = 22.0f; _activity.Frame = new System.Drawing.RectangleF (300 - w - 11, (44.0f - w) / 2, w, w); _activity.Tag = 42; } public void Start () { _activity.StartAnimating (); } public void Stop () { _activity.StopAnimating (); } public override void RefreshCell (UITableViewCell cell) { base.RefreshCell (cell); var v = cell.ViewWithTag (42); if (v == null) { cell.ContentView.AddSubview (_activity); } } } public class DialogViewController : UITableViewController { public List<DialogSection> Sections { get; private set; } Del _del; Data _data; public DialogViewController (UITableViewStyle s) : base(s) { try { Sections = new List<DialogSection> (); _del = new Del (this); _data = new Data (this); TableView.Delegate = _del; TableView.DataSource = _data; } catch (Exception error) { Log.Error (error); } } DialogElement GetElement (NSIndexPath path) { return Sections[path.Section].GetElement (path.Row); } class Del : UITableViewDelegate { DialogViewController _c; public Del (DialogViewController c) { _c = c; } public override void RowSelected (UITableView tableView, NSIndexPath indexPath) { try { _c.GetElement (indexPath).OnSelected (_c, indexPath); } catch (Exception error) { Log.Error (error); } } public override float GetHeightForRow (UITableView tableView, NSIndexPath indexPath) { return _c.GetElement (indexPath).Height; } } class Data : UITableViewDataSource { DialogViewController _c; public Data (DialogViewController c) { _c = c; } public override string TitleForHeader (UITableView tableView, int section) { try { return _c.Sections[section].Header; } catch (Exception error) { Log.Error (error); return ""; } } public override string TitleForFooter (UITableView tableView, int section) { try { return _c.Sections[section].Footer; } catch (Exception error) { Log.Error (error); return ""; } } public override int NumberOfSections (UITableView tableView) { try { return _c.Sections.Count; } catch (Exception error) { Log.Error (error); return 0; } } public override int RowsInSection (UITableView tableview, int section) { try { return _c.Sections[section].NumElements; } catch (Exception error) { Log.Error (error); return 0; } } public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { try { var e = _c.GetElement (indexPath); return e.GetCell (tableView); } catch (Exception error) { Log.Error (error); return new UITableViewCell (UITableViewCellStyle.Default, "ERROR"); } } public override void CommitEditingStyle (UITableView tableView, UITableViewCellEditingStyle editingStyle, NSIndexPath indexPath) { try { if (editingStyle == UITableViewCellEditingStyle.Delete) { var e = _c.GetElement (indexPath); e.OnDelete (_c, indexPath); tableView.DeleteRows (new NSIndexPath[] { indexPath }, UITableViewRowAnimation.Fade); } } catch (Exception error) { Log.Error (error); } } public override bool CanEditRow (UITableView tableView, NSIndexPath indexPath) { try { return _c.GetElement (indexPath).CanEdit; } catch (Exception error) { Log.Error (error); return false; } } } } }
using UnityEngine; using System.Collections.Generic; using Ecosim.SceneData; using Ecosim.SceneData.VegetationRules; using Ecosim; namespace Ecosim.SceneEditor { public class ExportPanel : Panel { public Scene scene; public EditorCtrl ctrl; public ExportMgr mgr; private bool graphOpened; private bool sheetOpened; private bool selectionOpened; private bool targetAreasOpened; private bool paramsOpened; private bool animalsOpened; private bool plantsOpened; public void Setup (EditorCtrl ctrl, Scene scene) { this.ctrl = ctrl; this.scene = scene; if (scene == null) return; } public bool Render (int mx, int my) { if (this.scene == null) return false; if (this.mgr == null) this.mgr = scene.exporter; GUILayout.BeginVertical (); { RenderGraph (mx, my); GUILayout.Space (2); RenderSheet (mx, my); GUILayout.FlexibleSpace (); } GUILayout.EndVertical (); return false; } private void RenderGraph (int mx, int my) { GUILayout.BeginVertical (ctrl.skin.box); { EcoGUI.Foldout ("Graph export", ref graphOpened); if (graphOpened) { EcoGUI.Toggle ("Graph Export enabled", ref mgr.graphExportEnabled); if (mgr.graphExportEnabled) { EcoGUI.EnumButton<ExportMgr.GraphCostTypes>("Cost type:", mgr.graphCostType, OnGraphCostTypeChanged, 80f, 150f); if (mgr.graphCostType != ExportMgr.GraphCostTypes.None) { EcoGUI.IntField ("Price:", ref mgr.graphCosts, 80f, 150f); } } } } GUILayout.EndVertical (); } private void RenderSheet (int mx, int my) { GUILayout.BeginVertical (ctrl.skin.box); { EcoGUI.Foldout ("Sheet export", ref sheetOpened); if (sheetOpened) { EcoGUI.Toggle ("Data Export enabled", ref mgr.exportEnabled); if (mgr.exportEnabled) { EcoGUI.EnumButton<ExportMgr.SelectionTypes>("Selection type:", mgr.selectionType, OnSelectionTypeChanged, 80f, 150f); EcoGUI.EnumButton<ExportMgr.DataTypes>("Data type:", mgr.dataType, OnDataTypeChanged, 80f, 150f); EcoGUI.EnumButton<ExportMgr.CostTypes>("Cost type:", mgr.costType, OnCostTypeChanged, 80f, 150f); if (mgr.costType != ExportMgr.CostTypes.None) { EcoGUI.IntField ("Price:", ref mgr.costs, 80f, 150f); } EcoGUI.Toggle ("Export succession type", ref mgr.exportSuccessionTypes); EcoGUI.Toggle ("Export vegetation type", ref mgr.exportVegetationTypes); switch (mgr.selectionType) { case ExportMgr.SelectionTypes.Selection : RenderSelectionType (mgr, mx, my); break; } } } } GUILayout.EndVertical (); } private void RenderSelectionType (ExportMgr mgr, int mx, int my) { GUILayout.Space (5f); GUILayout.BeginVertical (ctrl.skin.box); { EcoGUI.Foldout ("Selection", ref selectionOpened); GUILayout.Space (2f); if (selectionOpened) { GUILayout.BeginVertical (ctrl.skin.box); { GUILayout.BeginHorizontal (); { EcoGUI.Foldout ("Target areas", ref targetAreasOpened); GUILayout.FlexibleSpace (); if (GUILayout.Button ("+", GUILayout.Width (20f))) { GUILayout.Space (3f); List<string> targetAreas = new List<string> (); for (int i = 0; i < scene.progression.targetAreas; i++) { targetAreas.Add ((i + 1).ToString()); } foreach (int area in mgr.targetAreas) { targetAreas.Remove (area.ToString()); } if (targetAreas.Count > 0) { ctrl.StartSelection (targetAreas.ToArray(), 0, delegate(int index, string result) { mgr.AddTargetArea (int.Parse(result)); }); } else { ctrl.StartOkDialog ("No target areas to add.", null); } } } GUILayout.EndHorizontal (); GUILayout.Space (2f); if (targetAreasOpened) { int idx = 0; foreach (int area in mgr.targetAreas) { GUILayout.BeginHorizontal (); { GUILayout.Space (5f); if (GUILayout.Button ("-", GUILayout.Width (20f))) { mgr.RemoveTargetArea (area); break; } GUILayout.Space (5f); GUILayout.Label ("Target area " + area); } GUILayout.EndHorizontal (); } } } GUILayout.EndVertical (); GUILayout.BeginVertical (ctrl.skin.box); { GUILayout.BeginHorizontal (); { EcoGUI.Foldout ("Parameters", ref paramsOpened); GUILayout.FlexibleSpace (); if (GUILayout.Button ("+", GUILayout.Width (20f))) { GUILayout.Space (3f); List<string> names = scene.progression.GetAllDataNames (false); foreach (string param in mgr.parameters) { names.Remove (param); } if (names.Count > 0) { ctrl.StartSelection (names.ToArray(), 0, delegate(int index, string result) { mgr.AddParameter (result); }); } else { ctrl.StartOkDialog ("No parameters to add.", null); } } } GUILayout.EndHorizontal (); GUILayout.Space (2f); if (paramsOpened) { int idx = 0; foreach (string param in mgr.parameters) { GUILayout.BeginHorizontal (); { GUILayout.Space (5f); if (GUILayout.Button ("-", GUILayout.Width (20f))) { mgr.RemoveParameter (param); break; } GUILayout.Space (5f); GUILayout.Label (param); } GUILayout.EndHorizontal (); } } } GUILayout.EndVertical (); // Exception time! When we only show data when OnlyWhenSurveyed // then the data of animals and plants will NEVER show up, // so we won't have to make a selection for them. The data only shows up // and will only be available when using a survey/inventarisation. if (mgr.dataType == ExportMgr.DataTypes.Always) { GUILayout.BeginVertical (ctrl.skin.box); { GUILayout.BeginHorizontal (); { EcoGUI.Foldout ("Animals", ref animalsOpened); GUILayout.FlexibleSpace (); if (scene.animalTypes.Length > 0 && GUILayout.Button ("+", GUILayout.Width (20f))) { GUILayout.Space (3f); List<string> names = new List<string> (); foreach (AnimalType t in scene.animalTypes) { names.Add (t.name); } foreach (string animal in mgr.animals) { names.Remove (animal); } if (names.Count > 0) { ctrl.StartSelection (names.ToArray(), 0, delegate(int index, string result) { mgr.AddAnimal (result); }); } else { ctrl.StartOkDialog ("No animals to add.", null); } } } GUILayout.EndHorizontal (); GUILayout.Space (2f); if (animalsOpened) { int idx = 0; foreach (string animal in mgr.animals) { GUILayout.BeginHorizontal (); { GUILayout.Space (5f); if (GUILayout.Button ("-", GUILayout.Width (20f))) { mgr.RemoveAnimal (animal); break; } GUILayout.Space (5f); GUILayout.Label (animal); } GUILayout.EndHorizontal (); } if (scene.animalTypes.Length == 0) { GUILayout.Label ("No animals to add."); } } } GUILayout.EndVertical (); GUILayout.BeginVertical (ctrl.skin.box); { GUILayout.BeginHorizontal (); { EcoGUI.Foldout ("Plants", ref plantsOpened); GUILayout.FlexibleSpace (); if (scene.plantTypes.Length > 0 && GUILayout.Button ("+", GUILayout.Width (20f))) { GUILayout.Space (3f); List<string> names = new List<string> (); foreach (PlantType t in scene.plantTypes) { names.Add (t.name); } foreach (string plant in mgr.plants) { names.Remove (plant); } if (names.Count > 0) { ctrl.StartSelection (names.ToArray(), 0, delegate(int index, string result) { mgr.AddPlant (result); }); } else { ctrl.StartOkDialog ("No plants to add.", null); } } } GUILayout.EndHorizontal (); GUILayout.Space (2f); if (plantsOpened) { int idx = 0; foreach (string plant in mgr.plants) { GUILayout.BeginHorizontal (); { GUILayout.Space (5f); if (GUILayout.Button ("-", GUILayout.Width (20f))) { mgr.RemovePlant (plant); break; } GUILayout.Space (5f); GUILayout.Label (plant); } GUILayout.EndHorizontal (); } if (scene.plantTypes.Length == 0) { GUILayout.Label ("No plants to add."); } } } GUILayout.EndVertical (); } } } GUILayout.EndVertical (); } private void OnGraphCostTypeChanged (ExportMgr.GraphCostTypes newType) { scene.exporter.graphCostType = newType; } private void OnSelectionTypeChanged (ExportMgr.SelectionTypes newType) { scene.exporter.selectionType = newType; } private void OnCostTypeChanged (ExportMgr.CostTypes newType) { scene.exporter.costType = newType; } private void OnDataTypeChanged (ExportMgr.DataTypes newType) { scene.exporter.dataType = newType; } public void RenderExtra (int mx, int my) { } public void RenderSide (int mx, int my) { } public bool NeedSidePanel () { return false; } public bool IsAvailable () { return (scene != null); } public void Activate () { } public void Deactivate () { } public void Update () { } } }
/******************************************************************************* * Copyright 2009-2015 Amazon Services. 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://aws.amazon.com/apache2.0 * This file 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. ******************************************************************************* * Get Matching Product For Id Request * API Version: 2011-10-01 * Library Version: 2015-09-01 * Generated: Thu Sep 10 06:52:19 PDT 2015 */ using System; using System.Xml; using System.Xml.Serialization; using MWSClientCsRuntime; namespace MarketplaceWebServiceProducts.Model { [XmlTypeAttribute(Namespace = "http://mws.amazonservices.com/schema/Products/2011-10-01")] [XmlRootAttribute(Namespace = "http://mws.amazonservices.com/schema/Products/2011-10-01", IsNullable = false)] public class GetMatchingProductForIdRequest : AbstractMwsObject { private string _sellerId; private string _mwsAuthToken; private string _marketplaceId; private string _idType; private IdListType _idList; /// <summary> /// Gets and sets the SellerId property. /// </summary> [XmlElementAttribute(ElementName = "SellerId")] public string SellerId { get { return this._sellerId; } set { this._sellerId = value; } } /// <summary> /// Sets the SellerId property. /// </summary> /// <param name="sellerId">SellerId property.</param> /// <returns>this instance.</returns> public GetMatchingProductForIdRequest WithSellerId(string sellerId) { this._sellerId = sellerId; return this; } /// <summary> /// Checks if SellerId property is set. /// </summary> /// <returns>true if SellerId property is set.</returns> public bool IsSetSellerId() { return this._sellerId != null; } /// <summary> /// Gets and sets the MWSAuthToken property. /// </summary> [XmlElementAttribute(ElementName = "MWSAuthToken")] public string MWSAuthToken { get { return this._mwsAuthToken; } set { this._mwsAuthToken = value; } } /// <summary> /// Sets the MWSAuthToken property. /// </summary> /// <param name="mwsAuthToken">MWSAuthToken property.</param> /// <returns>this instance.</returns> public GetMatchingProductForIdRequest WithMWSAuthToken(string mwsAuthToken) { this._mwsAuthToken = mwsAuthToken; return this; } /// <summary> /// Checks if MWSAuthToken property is set. /// </summary> /// <returns>true if MWSAuthToken property is set.</returns> public bool IsSetMWSAuthToken() { return this._mwsAuthToken != null; } /// <summary> /// Gets and sets the MarketplaceId property. /// </summary> [XmlElementAttribute(ElementName = "MarketplaceId")] public string MarketplaceId { get { return this._marketplaceId; } set { this._marketplaceId = value; } } /// <summary> /// Sets the MarketplaceId property. /// </summary> /// <param name="marketplaceId">MarketplaceId property.</param> /// <returns>this instance.</returns> public GetMatchingProductForIdRequest WithMarketplaceId(string marketplaceId) { this._marketplaceId = marketplaceId; return this; } /// <summary> /// Checks if MarketplaceId property is set. /// </summary> /// <returns>true if MarketplaceId property is set.</returns> public bool IsSetMarketplaceId() { return this._marketplaceId != null; } /// <summary> /// Gets and sets the IdType property. /// </summary> [XmlElementAttribute(ElementName = "IdType")] public string IdType { get { return this._idType; } set { this._idType = value; } } /// <summary> /// Sets the IdType property. /// </summary> /// <param name="idType">IdType property.</param> /// <returns>this instance.</returns> public GetMatchingProductForIdRequest WithIdType(string idType) { this._idType = idType; return this; } /// <summary> /// Checks if IdType property is set. /// </summary> /// <returns>true if IdType property is set.</returns> public bool IsSetIdType() { return this._idType != null; } /// <summary> /// Gets and sets the IdList property. /// </summary> [XmlElementAttribute(ElementName = "IdList")] public IdListType IdList { get { return this._idList; } set { this._idList = value; } } /// <summary> /// Sets the IdList property. /// </summary> /// <param name="idList">IdList property.</param> /// <returns>this instance.</returns> public GetMatchingProductForIdRequest WithIdList(IdListType idList) { this._idList = idList; return this; } /// <summary> /// Checks if IdList property is set. /// </summary> /// <returns>true if IdList property is set.</returns> public bool IsSetIdList() { return this._idList != null; } public override void ReadFragmentFrom(IMwsReader reader) { _sellerId = reader.Read<string>("SellerId"); _mwsAuthToken = reader.Read<string>("MWSAuthToken"); _marketplaceId = reader.Read<string>("MarketplaceId"); _idType = reader.Read<string>("IdType"); _idList = reader.Read<IdListType>("IdList"); } public override void WriteFragmentTo(IMwsWriter writer) { writer.Write("SellerId", _sellerId); writer.Write("MWSAuthToken", _mwsAuthToken); writer.Write("MarketplaceId", _marketplaceId); writer.Write("IdType", _idType); writer.Write("IdList", _idList); } public override void WriteTo(IMwsWriter writer) { writer.Write("http://mws.amazonservices.com/schema/Products/2011-10-01", "GetMatchingProductForIdRequest", this); } public GetMatchingProductForIdRequest() : base() { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Globalization; using System.Net.Http; using System.Net.Http.Headers; using System.Security.Claims; using System.Security.Cryptography; using System.Text; using System.Text.Encodings.Web; using System.Text.Json; using Microsoft.AspNetCore.WebUtilities; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.Extensions.Primitives; namespace Microsoft.AspNetCore.Authentication.OAuth { /// <summary> /// An authentication handler that supports OAuth. /// </summary> /// <typeparam name="TOptions">The type of options.</typeparam> public class OAuthHandler<TOptions> : RemoteAuthenticationHandler<TOptions> where TOptions : OAuthOptions, new() { /// <summary> /// Gets the <see cref="HttpClient"/> instance used to communicate with the remote authentication provider. /// </summary> protected HttpClient Backchannel => Options.Backchannel; /// <summary> /// The handler calls methods on the events which give the application control at certain points where processing is occurring. /// If it is not provided a default instance is supplied which does nothing when the methods are called. /// </summary> protected new OAuthEvents Events { get { return (OAuthEvents)base.Events; } set { base.Events = value; } } /// <summary> /// Initializes a new instance of <see cref="OAuthHandler{TOptions}"/>. /// </summary> /// <inheritdoc /> public OAuthHandler(IOptionsMonitor<TOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock) { } /// <summary> /// Creates a new instance of the events instance. /// </summary> /// <returns>A new instance of the events instance.</returns> protected override Task<object> CreateEventsAsync() => Task.FromResult<object>(new OAuthEvents()); /// <inheritdoc /> protected override async Task<HandleRequestResult> HandleRemoteAuthenticateAsync() { var query = Request.Query; var state = query["state"]; var properties = Options.StateDataFormat.Unprotect(state); if (properties == null) { return HandleRequestResult.Fail("The oauth state was missing or invalid."); } // OAuth2 10.12 CSRF if (!ValidateCorrelationId(properties)) { return HandleRequestResult.Fail("Correlation failed.", properties); } var error = query["error"]; if (!StringValues.IsNullOrEmpty(error)) { // Note: access_denied errors are special protocol errors indicating the user didn't // approve the authorization demand requested by the remote authorization server. // Since it's a frequent scenario (that is not caused by incorrect configuration), // denied errors are handled differently using HandleAccessDeniedErrorAsync(). // Visit https://tools.ietf.org/html/rfc6749#section-4.1.2.1 for more information. var errorDescription = query["error_description"]; var errorUri = query["error_uri"]; if (StringValues.Equals(error, "access_denied")) { var result = await HandleAccessDeniedErrorAsync(properties); if (!result.None) { return result; } var deniedEx = new Exception("Access was denied by the resource owner or by the remote server."); deniedEx.Data["error"] = error.ToString(); deniedEx.Data["error_description"] = errorDescription.ToString(); deniedEx.Data["error_uri"] = errorUri.ToString(); return HandleRequestResult.Fail(deniedEx, properties); } var failureMessage = new StringBuilder(); failureMessage.Append(error); if (!StringValues.IsNullOrEmpty(errorDescription)) { failureMessage.Append(";Description=").Append(errorDescription); } if (!StringValues.IsNullOrEmpty(errorUri)) { failureMessage.Append(";Uri=").Append(errorUri); } var ex = new Exception(failureMessage.ToString()); ex.Data["error"] = error.ToString(); ex.Data["error_description"] = errorDescription.ToString(); ex.Data["error_uri"] = errorUri.ToString(); return HandleRequestResult.Fail(ex, properties); } var code = query["code"]; if (StringValues.IsNullOrEmpty(code)) { return HandleRequestResult.Fail("Code was not found.", properties); } var codeExchangeContext = new OAuthCodeExchangeContext(properties, code.ToString(), BuildRedirectUri(Options.CallbackPath)); using var tokens = await ExchangeCodeAsync(codeExchangeContext); if (tokens.Error != null) { return HandleRequestResult.Fail(tokens.Error, properties); } if (string.IsNullOrEmpty(tokens.AccessToken)) { return HandleRequestResult.Fail("Failed to retrieve access token.", properties); } var identity = new ClaimsIdentity(ClaimsIssuer); if (Options.SaveTokens) { var authTokens = new List<AuthenticationToken>(); authTokens.Add(new AuthenticationToken { Name = "access_token", Value = tokens.AccessToken }); if (!string.IsNullOrEmpty(tokens.RefreshToken)) { authTokens.Add(new AuthenticationToken { Name = "refresh_token", Value = tokens.RefreshToken }); } if (!string.IsNullOrEmpty(tokens.TokenType)) { authTokens.Add(new AuthenticationToken { Name = "token_type", Value = tokens.TokenType }); } if (!string.IsNullOrEmpty(tokens.ExpiresIn)) { int value; if (int.TryParse(tokens.ExpiresIn, NumberStyles.Integer, CultureInfo.InvariantCulture, out value)) { // https://www.w3.org/TR/xmlschema-2/#dateTime // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx var expiresAt = Clock.UtcNow + TimeSpan.FromSeconds(value); authTokens.Add(new AuthenticationToken { Name = "expires_at", Value = expiresAt.ToString("o", CultureInfo.InvariantCulture) }); } } properties.StoreTokens(authTokens); } var ticket = await CreateTicketAsync(identity, properties, tokens); if (ticket != null) { return HandleRequestResult.Success(ticket); } else { return HandleRequestResult.Fail("Failed to retrieve user information from remote server.", properties); } } /// <summary> /// Exchanges the authorization code for a authorization token from the remote provider. /// </summary> /// <param name="context">The <see cref="OAuthCodeExchangeContext"/>.</param> /// <returns>The response <see cref="OAuthTokenResponse"/>.</returns> protected virtual async Task<OAuthTokenResponse> ExchangeCodeAsync(OAuthCodeExchangeContext context) { var tokenRequestParameters = new Dictionary<string, string>() { { "client_id", Options.ClientId }, { "redirect_uri", context.RedirectUri }, { "client_secret", Options.ClientSecret }, { "code", context.Code }, { "grant_type", "authorization_code" }, }; // PKCE https://tools.ietf.org/html/rfc7636#section-4.5, see BuildChallengeUrl if (context.Properties.Items.TryGetValue(OAuthConstants.CodeVerifierKey, out var codeVerifier)) { tokenRequestParameters.Add(OAuthConstants.CodeVerifierKey, codeVerifier!); context.Properties.Items.Remove(OAuthConstants.CodeVerifierKey); } var requestContent = new FormUrlEncodedContent(tokenRequestParameters!); var requestMessage = new HttpRequestMessage(HttpMethod.Post, Options.TokenEndpoint); requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); requestMessage.Content = requestContent; requestMessage.Version = Backchannel.DefaultRequestVersion; var response = await Backchannel.SendAsync(requestMessage, Context.RequestAborted); var body = await response.Content.ReadAsStringAsync(); return response.IsSuccessStatusCode switch { true => OAuthTokenResponse.Success(JsonDocument.Parse(body)), false => PrepareFailedOAuthTokenReponse(response, body) }; } private static OAuthTokenResponse PrepareFailedOAuthTokenReponse(HttpResponseMessage response, string body) { var exception = OAuthTokenResponse.GetStandardErrorException(JsonDocument.Parse(body)); if (exception is null) { var errorMessage = $"OAuth token endpoint failure: Status: {response.StatusCode};Headers: {response.Headers};Body: {body};"; return OAuthTokenResponse.Failed(new Exception(errorMessage)); } return OAuthTokenResponse.Failed(exception); } /// <summary> /// Creates an <see cref="AuthenticationTicket"/> from the specified <paramref name="tokens"/>. /// </summary> /// <param name="identity">The <see cref="ClaimsIdentity"/>.</param> /// <param name="properties">The <see cref="AuthenticationProperties"/>.</param> /// <param name="tokens">The <see cref="OAuthTokenResponse"/>.</param> /// <returns>The <see cref="AuthenticationTicket"/>.</returns> protected virtual async Task<AuthenticationTicket> CreateTicketAsync(ClaimsIdentity identity, AuthenticationProperties properties, OAuthTokenResponse tokens) { using (var user = JsonDocument.Parse("{}")) { var context = new OAuthCreatingTicketContext(new ClaimsPrincipal(identity), properties, Context, Scheme, Options, Backchannel, tokens, user.RootElement); await Events.CreatingTicket(context); return new AuthenticationTicket(context.Principal!, context.Properties, Scheme.Name); } } /// <inheritdoc /> protected override async Task HandleChallengeAsync(AuthenticationProperties properties) { if (string.IsNullOrEmpty(properties.RedirectUri)) { properties.RedirectUri = OriginalPathBase + OriginalPath + Request.QueryString; } // OAuth2 10.12 CSRF GenerateCorrelationId(properties); var authorizationEndpoint = BuildChallengeUrl(properties, BuildRedirectUri(Options.CallbackPath)); var redirectContext = new RedirectContext<OAuthOptions>( Context, Scheme, Options, properties, authorizationEndpoint); await Events.RedirectToAuthorizationEndpoint(redirectContext); var location = Context.Response.Headers.Location; if (location == StringValues.Empty) { location = "(not set)"; } var cookie = Context.Response.Headers.SetCookie; if (cookie == StringValues.Empty) { cookie = "(not set)"; } Logger.HandleChallenge(location.ToString(), cookie.ToString()); } /// <summary> /// Constructs the OAuth challenge url. /// </summary> /// <param name="properties">The <see cref="AuthenticationProperties"/>.</param> /// <param name="redirectUri">The url to redirect to once the challenge is completed.</param> /// <returns>The challenge url.</returns> protected virtual string BuildChallengeUrl(AuthenticationProperties properties, string redirectUri) { var scopeParameter = properties.GetParameter<ICollection<string>>(OAuthChallengeProperties.ScopeKey); var scope = scopeParameter != null ? FormatScope(scopeParameter) : FormatScope(); var parameters = new Dictionary<string, string> { { "client_id", Options.ClientId }, { "scope", scope }, { "response_type", "code" }, { "redirect_uri", redirectUri }, }; if (Options.UsePkce) { var bytes = new byte[32]; RandomNumberGenerator.Fill(bytes); var codeVerifier = Base64UrlTextEncoder.Encode(bytes); // Store this for use during the code redemption. properties.Items.Add(OAuthConstants.CodeVerifierKey, codeVerifier); var challengeBytes = SHA256.HashData(Encoding.UTF8.GetBytes(codeVerifier)); var codeChallenge = WebEncoders.Base64UrlEncode(challengeBytes); parameters[OAuthConstants.CodeChallengeKey] = codeChallenge; parameters[OAuthConstants.CodeChallengeMethodKey] = OAuthConstants.CodeChallengeMethodS256; } parameters["state"] = Options.StateDataFormat.Protect(properties); return QueryHelpers.AddQueryString(Options.AuthorizationEndpoint, parameters!); } /// <summary> /// Format a list of OAuth scopes. /// </summary> /// <param name="scopes">List of scopes.</param> /// <returns>Formatted scopes.</returns> protected virtual string FormatScope(IEnumerable<string> scopes) => string.Join(" ", scopes); // OAuth2 3.3 space separated /// <summary> /// Format the <see cref="OAuthOptions.Scope"/> property. /// </summary> /// <returns>Formatted scopes.</returns> /// <remarks>Subclasses should rather override <see cref="FormatScope(IEnumerable{string})"/>.</remarks> protected virtual string FormatScope() => FormatScope(Options.Scope); } }
using System; using System.IO; using System.Xml; using bv.common.Core; using bv.common.Diagnostics; using System.Collections.Generic; namespace bv.common.Configuration { /// ----------------------------------------------------------------------------- /// <summary> /// Reads and writes the information form the xml configuration files /// </summary> /// <remarks> /// By default <i>ConfigWriter</i> reads/writes the settings of the configuration file <b>appSettings</b> section. /// If configuration file name is not specified, it works with application config file (app.config) /// Shared <i>Instance</i> method always works to the <i>ConfigWriter</i> instance related with application config file. /// </remarks> /// <history> /// [Mike] 22.03.2006 Created /// </history> /// ----------------------------------------------------------------------------- public class ConfigWriter { public delegate ConfigWriter CreateConfigWriterDelegate(); protected static CreateConfigWriterDelegate Creator { get; set; } private List<string> m_RestrictedKeys = null; private class NodeAttribute { public string Name; public string Value; public NodeAttribute(string aName, string aValue) { Name = aName; Value = aValue; } } private static ConfigWriter s_Instance; private readonly XmlDocument m_AppConfig = new XmlDocument(); private string m_FileName; private bool m_Initialized; private bool m_Modified; private readonly string m_DefaultConfigFileName = Utils.GetExecutingPath() + Utils.GetConfigFileName(); private XmlNamespaceManager m_Namespaces; private string m_Prefix; public ConfigWriter() { } public ConfigWriter(List<string> keys, string fileName) { Config.InitSettings(); m_RestrictedKeys = keys; foreach (string key in Config.m_Settings.Keys) { SetItem(key, Config.m_Settings[key]); } m_Modified = false; m_Initialized = true; if (!string.IsNullOrEmpty(Path.GetFileName(fileName))) m_FileName = fileName; else m_FileName = m_DefaultConfigFileName; } /// ----------------------------------------------------------------------------- /// <summary> /// Defines whether <i>ConfigWriter</i> initialized by reading configuration file /// </summary> /// <returns> /// returns <b>True</b> if <i>Read</i> method was called successfully and <b>False</b> in other case. /// </returns> /// <remarks> /// Use this method to indicate was the data successfully read from configuration file or no. /// If <i>Read</i> method was called for absent configuration file for example the property will return <b>False</b>. /// </remarks> /// <history> /// [Mike] 23.03.2006 Created /// </history> /// ----------------------------------------------------------------------------- public bool IsInitialized { get { return m_Initialized; } } public string FileName { get { return m_FileName; } } /// ----------------------------------------------------------------------------- /// <summary> /// Returns the default instance of <i>ConfigWriter</i> related with application configuration file. /// </summary> /// <returns> /// Returns the default instance of <i>ConfigWriter</i> related with application configuration file. /// </returns> /// <remarks> /// When requested first time the instance of <i>ConfigWriter</i> related with application configuration file is created and read. /// Any next call of this property returns this created instance and no additional read is performed. /// </remarks> /// <history> /// [Mike] 23.03.2006 Created /// </history> /// ----------------------------------------------------------------------------- private static object g_lock = new object(); public static ConfigWriter Instance { get { lock (g_lock) { if (s_Instance == null) { s_Instance = Creator == null ? new ConfigWriter() : Creator(); s_Instance.Read(null); } } return s_Instance; } } private static object g_readlock = new object(); /// ----------------------------------------------------------------------------- /// <summary> /// Reads the configuration file and stores xml document inside the class /// </summary> /// <param name="fileName"> /// Xml file name to read /// </param> /// <remarks> /// If <i>fileName</i> is not passed (or set to <b>Nothing</b>) the default application config file is read. /// If specified file doesn't exist new xml document with <i>&lt;configuration&gt;/&lt;appConfig&gt;</i> section is created. /// </remarks> /// <history> /// [Mike] 22.03.2006 Created /// </history> /// ----------------------------------------------------------------------------- public void Read(string fileName) { lock (g_readlock) { //Save settings in app config file if (string.IsNullOrEmpty(fileName)) { if (string.IsNullOrEmpty(m_FileName)) { Config.FindLocalConfigFile(); m_FileName = Config.FileName; if (fileName == null) m_FileName = m_DefaultConfigFileName; } } else { m_FileName = fileName; } if (File.Exists(m_FileName) == false) { GetAppSettingsNode(); return; } m_Namespaces = null; m_NamespaceInitialized = false; m_AppConfig.Load(m_FileName); InitNamespace(); m_Modified = false; m_Initialized = true; } } private bool m_NamespaceInitialized = false; private void InitNamespace() { if (!m_NamespaceInitialized) { if (m_AppConfig != null && m_AppConfig.DocumentElement != null) { XmlAttribute xmlnsAttribute = m_AppConfig.DocumentElement.Attributes["xmlns"]; m_Prefix = ""; if (xmlnsAttribute != null) { m_Prefix = "ns"; m_Namespaces = new XmlNamespaceManager(m_AppConfig.NameTable); m_Namespaces.AddNamespace(m_Prefix, xmlnsAttribute.Value); //Re-configure xPath with included the prefix m_Prefix = String.Concat(m_Prefix, ":"); } m_NamespaceInitialized = true; } } } private XmlNode _GetAppSettingsNode() { if (m_AppConfig != null && m_AppConfig.DocumentElement != null) { var xPath = string.Format("/{0}configuration/{0}appSettings", m_Prefix); return m_AppConfig.SelectSingleNode(xPath, m_Namespaces); } return null; } /// ----------------------------------------------------------------------------- /// <summary> /// Sets the value for specific setting defined by parent node and setting's key. /// </summary> /// <param name="appSettingsNode"> /// defines the <b>XmlNode</b> that contains the setting nodes. /// </param> /// <param name="nodeName"> /// the value of <i>key</i> attribute of setting node /// </param> /// <param name="value"> /// the string that should be assigned to the <i>value</i> attribute of setting node /// </param> /// <returns> /// Returns <b>True</b> if setting node was modified and <b>False</b> in other case /// </returns> /// <remarks> /// This method is used to set the values of setting nodes with predefined node parameters: <br/> /// <i>add</i> - the tag name of setting node /// <b>key</b> - the attribute that defines the unique node identifier /// <b>value</b> - the attribute that defines the setting value <br/> /// If requested setting is absent the new setting node is added to the parent <b>XmlNode</b> /// </remarks> /// <history> /// [Mike] 23.03.2006 Created /// </history> /// ----------------------------------------------------------------------------- private bool SetAttributeValue(XmlNode appSettingsNode, string nodeName, string value) { XmlNode node = FindNodeByAttribute(appSettingsNode, "add", "key", nodeName); if (node == null && appSettingsNode != null && appSettingsNode.OwnerDocument != null) { node = appSettingsNode.OwnerDocument.CreateElement("add"); node.Attributes.Append(appSettingsNode.OwnerDocument.CreateAttribute("key")); node.Attributes["key"].InnerText = nodeName; node.Attributes.Append(appSettingsNode.OwnerDocument.CreateAttribute("value")); node.Attributes["value"].InnerText = value; appSettingsNode.AppendChild(node); Dbg.ConditionalDebug(DebugDetalizationLevel.High, "attribute value {0} for node {1} is added ", value, nodeName); return true; } if (node.Attributes["value"].InnerText != value) { Dbg.ConditionalDebug(DebugDetalizationLevel.High, "attribute value for node {0} was changed from {1} to {2} ", nodeName, node.Attributes["value"].InnerText, value); node.Attributes["value"].InnerText = value; return true; } Dbg.ConditionalDebug(DebugDetalizationLevel.High, "attribute value for node {0} was changed not changed", nodeName); return false; } /// ----------------------------------------------------------------------------- /// <summary> /// Searches the <b>XmlNode</b> with specific name and specific attribute value in the section defined by <i>appSettingsNode</i> parameter. /// </summary> /// <param name="appSettingsNode"> /// parent <b>XmlNode</b> node. The result node will be searched among the children of this node. /// </param> /// <param name="nodeName"> /// the tag name of xml node to search /// </param> /// <param name="attrName"> /// the name of key attribute /// </param> /// <param name="attrValue"> /// the value of key attribute /// </param> /// <returns> /// Returns the first <b>XmlNode</b> that match to specified conditions or <b>Nothing</b> if node is not found /// </returns> /// <remarks> /// Use this method to find <b>XmlNode</b> with arbitrary tag name and key attribute /// </remarks> /// <history> /// [Mike] 23.03.2006 Created /// </history> /// ----------------------------------------------------------------------------- public XmlNode FindNodeByAttribute(XmlNode appSettingsNode, string nodeName, string attrName, string attrValue) { if (appSettingsNode == null) { appSettingsNode = _GetAppSettingsNode(); } if (appSettingsNode != null) { string xPath = string.Format("descendant::{0}{1}[@{2}=\'{3}\']", m_Prefix, nodeName, attrName, attrValue); return appSettingsNode.SelectSingleNode(xPath, m_Namespaces); } return null; } /// ----------------------------------------------------------------------------- /// <summary> /// Searches the <b>XmlNode</b> with specific name and specific attribute value in descendant nodes of parent node and sets values for the set of node attributes. /// </summary> /// <param name="appSettingsNode"> /// parent <b>XmlNode</b> node. The node that should be modified will be searched among the children of this node. /// </param> /// <param name="nodeName"> /// the tag name of xml node that should be modified /// </param> /// <param name="attr"> /// the array of <i>NodeAttribute</i> objects that defines the name/value pairs for modified attributes /// </param> /// <returns> /// Returns <b>True</b> if any of the passed attributes values was modified or new node was created and <b>False</b> in other case. /// </returns> /// <remarks> /// Call this method if you need to modify several attributes of <i>XmlNode</i> with custom node name. /// </remarks> /// <history> /// [Mike] 23.03.2006 Created /// </history> /// ----------------------------------------------------------------------------- private bool SetAttributeValue(XmlNode appSettingsNode, string nodeName, NodeAttribute[] attr) { if (attr.Length == 0) { return false; } XmlNode node = FindNodeByAttribute(appSettingsNode, nodeName, attr[0].Name, attr[0].Value); if (node == null && appSettingsNode != null && appSettingsNode.OwnerDocument != null) { node = appSettingsNode.OwnerDocument.CreateElement(nodeName); for (int i = 0; i <= attr.Length - 1; i++) { node.Attributes.Append(appSettingsNode.OwnerDocument.CreateAttribute(attr[i].Name)); node.Attributes[attr[i].Name].InnerText = attr[i].Value; Dbg.ConditionalDebug(DebugDetalizationLevel.High, "attribute value {0} for node {1} is added ", attr[i].Value, attr[i].Name); } appSettingsNode.AppendChild(node); m_Modified = true; return true; } for (int i = 1; i <= attr.Length - 1; i++) { if (node.Attributes[attr[i].Name] == null) { node.Attributes.Append(appSettingsNode.OwnerDocument.CreateAttribute(attr[i].Name)); Dbg.ConditionalDebug(DebugDetalizationLevel.High, "attribute value {0} for node {1} is added ", attr[i].Value, attr[i].Name); m_Modified = true; } if (node.Attributes[attr[i].Name].InnerText != attr[i].Value) { Dbg.ConditionalDebug(DebugDetalizationLevel.High, "attribute value for node {0} was changed from {1} to {2} ", attr[i].Name, node.Attributes[attr[i].Name].InnerText, attr[i].Value); node.Attributes[attr[i].Name].InnerText = attr[i].Value; m_Modified = true; } } return m_Modified; } /// ----------------------------------------------------------------------------- /// <summary> /// Sets several attribute values for the specific <b>XmlNode</b>. /// </summary> /// <param name="node"> /// the <b>XmlNode</b> that should be modified /// </param> /// <param name="attr"> /// the array of <i>NodeAttribute</i> objects that defines the name/value pairs for modified attributes /// </param> /// <returns> /// Returns <b>True</b> if any of the passed attributes values was modified or new node was created and <b>False</b> in other case. /// </returns> /// <remarks> /// Call this method if you need to modify several attributes of the specific <i>XmlNode</i>. /// </remarks> /// <history> /// [Mike] 23.03.2006 Created /// </history> /// ----------------------------------------------------------------------------- private bool SetAttributeValue(XmlNode node, NodeAttribute[] attr) { if (attr.Length == 0) { return false; } if (node != null) { for (int i = 0; i <= attr.Length - 1; i++) { if (node.Attributes[attr[i].Name] == null) { node.Attributes.Append(node.OwnerDocument.CreateAttribute(attr[i].Name)); } if (node.Attributes[attr[i].Name].InnerText != attr[i].Value) { node.Attributes[attr[i].Name].InnerText = attr[i].Value; m_Modified = true; } } return true; } return false; } /// ----------------------------------------------------------------------------- /// <summary> /// Gets or sets the specific setting in the appSettings section of configuration file /// </summary> /// <param name="keyValue"> /// the value key attribute of the appSettings node /// </param> /// <returns> /// the value attribute of the appSettings node /// </returns> /// <remarks> /// If requested settings node doesn't exist the <b>Nothing</b> is returned. If you set value for non existing setting node, the new setting is created. /// </remarks> /// <history> /// [Mike] 22.03.2006 Created /// </history> /// ----------------------------------------------------------------------------- public string GetItem(string keyValue) { if (m_AppConfig == null) return ""; XmlNode root = m_AppConfig.DocumentElement; if (root != null) { XmlNode appSettingsNode = _GetAppSettingsNode(); if (appSettingsNode == null || appSettingsNode.OwnerDocument == null) { return ""; } XmlNode node = FindNodeByAttribute(appSettingsNode, "add", "key", keyValue); if (node != null) { return node.Attributes["value"].InnerText; } } return ""; } public void SetItem(string keyValue, string value) { if (m_RestrictedKeys != null && !m_RestrictedKeys.Contains(keyValue)) return; XmlNode appSettingsNode = GetAppSettingsNode(); m_Modified = m_Modified | SetAttributeValue(appSettingsNode, keyValue, value); } /// ----------------------------------------------------------------------------- /// <summary> /// Searches and returns <b>XmlNode</b> defined by node name and attribute name/value pair in the <b>appSettings</b> section of configuration file. /// </summary> /// <param name="nodeName"> /// xml node name to find /// </param> /// <param name="attrName"> /// the key attribute name /// </param> /// <param name="attrValue"> /// the key attribute value /// </param> /// <returns> /// Returns <b>XmlNode</b> with specific node name and attribute name/value pair or <b>Nothing</b> is node is not found. /// </returns> /// <remarks> /// The node is searched inside <b>appSettings</b> section of configuration file only. /// </remarks> /// <history> /// [Mike] 23.03.2006 Created /// </history> /// ----------------------------------------------------------------------------- public XmlNode GetNode(string nodeName, string attrName, string attrValue) { return GetNode(null, nodeName, attrName, attrValue); } /// ----------------------------------------------------------------------------- /// <summary> /// Searches and returns <b>XmlNode</b> defined by node name and attribute name/value pair in the specific section of configuration file. /// </summary> /// <param name="parentNode"> /// <b>XmlNode</b> of section to search /// </param> /// <param name="nodeName"> /// xml node name to find /// </param> /// <param name="attrName"> /// the key attribute name /// </param> /// <param name="attrValue"> /// the key attribute value /// </param> /// <returns> /// Returns <b>XmlNode</b> with specific node name and attribute name/value pair or <b>Nothing</b> is node is not found. /// </returns> /// <remarks> /// The node is searched inside section of configuration file defined by <i>parentNode</i>. /// </remarks> /// <history> /// [Mike] 23.03.2006 Created /// </history> /// ----------------------------------------------------------------------------- public XmlNode GetNode(XmlNode parentNode, string nodeName, string attrName, string attrValue) { if (parentNode == null) { parentNode = _GetAppSettingsNode(); if (parentNode == null) return null; } XmlNode sectionNode = FindNodeByAttribute(parentNode, nodeName, attrName, attrValue); if (sectionNode != null) { return sectionNode; } sectionNode = parentNode.OwnerDocument.CreateElement(nodeName); SetAttributeValue(sectionNode, new NodeAttribute[] { new NodeAttribute(attrName, attrValue) }); parentNode.AppendChild(sectionNode); m_Modified = true; return sectionNode; } /// ----------------------------------------------------------------------------- /// <summary> /// Returns the string value of specific attribute for passed <b>XmlNode</b> /// </summary> /// <param name="node"> /// <b>XmlNode</b> that contains the attribute /// </param> /// <param name="attrName"> /// the attribute name /// </param> /// <returns> /// the string representation of the requested attribute /// </returns> /// <remarks> /// No additional checks for existence of passed node or attribute is performed. If <i>node</i> is <b>Nothing</b> or contains no requested attribute the exception will be thrown /// </remarks> /// <history> /// [Mike] 23.03.2006 Created /// </history> /// ----------------------------------------------------------------------------- public string GetAttributeValue(XmlNode node, string attrName) { return node.Attributes[attrName].InnerText; } /// ----------------------------------------------------------------------------- /// <summary> /// Saves the configuration file previously read using <i>Read</i> method. /// </summary> /// <returns> /// Returns <b>False</b> if error occur during saving or <b>True</b> in other case. /// </returns> /// <remarks> /// When the application is run from VS IDE the changes for default application configuration /// file are saved not only to configuration file in the <b>bin</b> folder but to the original /// <b>app.config</b> file too. If error occurs during saving the error is written to /// the application log but no error reported to end user /// </remarks> /// <history> /// [Mike] 23.03.2006 Created /// </history> /// ----------------------------------------------------------------------------- public bool Save(bool forceSaving = false, bool throwExeption = false) { if (!m_Modified && !forceSaving) { Dbg.ConditionalDebug(DebugDetalizationLevel.High, "configuration file {0} is not saved, there is no changes", m_FileName); return true; } //!!We should never update web.config from code. Only manual changes are allowed var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(m_FileName); if (fileNameWithoutExtension != null && fileNameWithoutExtension.ToLowerInvariant() == "web") return true; bool ret = true; try { if (!File.Exists(FileName)) { Utils.ForceDirectories(Path.GetDirectoryName(FileName)); FileStream fs = File.Create(FileName); fs.Close(); } FileAttributes attr = File.GetAttributes(FileName); if ((attr & FileAttributes.ReadOnly) != 0) { attr = attr & (~FileAttributes.ReadOnly); File.SetAttributes(FileName, attr); } m_AppConfig.Save(m_FileName); m_Modified = false; } catch (Exception ex) { ret = false; Dbg.Debug("the changes to configuration file {0} was not written, {1}", m_FileName, ex.Message); if (throwExeption) throw; } string appConfigFileName = ""; try { if (m_FileName == m_DefaultConfigFileName) { appConfigFileName = Utils.GetExecutingPath() + "\\..\\app.config"; if (File.Exists(appConfigFileName)) { m_AppConfig.Save(appConfigFileName); } } } catch (Exception ex) { ret = false; Dbg.Debug("the changes to configuration file {0} was not written, {1}", appConfigFileName, ex.Message); if (throwExeption) throw; } //Config.ReloadSettings(); //Instance.Read(null); return ret; } public bool SaveAs(string fileName, bool forceSaving = false, bool throwExeption = false) { m_FileName = fileName; return Save(forceSaving, throwExeption); } private XmlNode GetAppSettingsNode() { XmlNode appSettingsNode = _GetAppSettingsNode(); if (appSettingsNode == null) { XmlNode root = m_AppConfig.DocumentElement; if (root == null) { root = m_AppConfig.CreateNode(XmlNodeType.XmlDeclaration, "", ""); m_AppConfig.AppendChild(root); } root = m_AppConfig.SelectSingleNode("/configuration"); if (root == null) { root = m_AppConfig.CreateNode(XmlNodeType.Element, "configuration", ""); } appSettingsNode = m_AppConfig.CreateNode(XmlNodeType.Element, "appSettings", ""); root.AppendChild(appSettingsNode); m_AppConfig.AppendChild(root); } return appSettingsNode; } } }
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; using Avalonia.Platform.Interop; using static Avalonia.OpenGL.GlConsts; namespace Avalonia.OpenGL { public delegate IntPtr GlGetProcAddressDelegate(string procName); public unsafe class GlInterface : GlBasicInfoInterface<GlInterface.GlContextInfo> { public string Version { get; } public string Vendor { get; } public string Renderer { get; } public GlContextInfo ContextInfo { get; } public class GlContextInfo { public GlVersion Version { get; } public HashSet<string> Extensions { get; } public GlContextInfo(GlVersion version, HashSet<string> extensions) { Version = version; Extensions = extensions; } public static GlContextInfo Create(GlVersion version, Func<string, IntPtr> getProcAddress) { var basicInfoInterface = new GlBasicInfoInterface(getProcAddress); var exts = basicInfoInterface.GetExtensions(); return new GlContextInfo(version, new HashSet<string>(exts)); } } private GlInterface(GlContextInfo info, Func<string, IntPtr> getProcAddress) : base(getProcAddress, info) { ContextInfo = info; Version = GetString(GlConsts.GL_VERSION); Renderer = GetString(GlConsts.GL_RENDERER); Vendor = GetString(GlConsts.GL_VENDOR); } public GlInterface(GlVersion version, Func<string, IntPtr> getProcAddress) : this( GlContextInfo.Create(version, getProcAddress), getProcAddress) { } public GlInterface(GlVersion version, Func<Utf8Buffer, IntPtr> n) : this(version, ConvertNative(n)) { } public static GlInterface FromNativeUtf8GetProcAddress(GlVersion version, Func<Utf8Buffer, IntPtr> getProcAddress) => new GlInterface(version, getProcAddress); public T GetProcAddress<T>(string proc) => Marshal.GetDelegateForFunctionPointer<T>(GetProcAddress(proc)); // ReSharper disable UnassignedGetOnlyAutoProperty [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate int GlGetError(); [GlEntryPoint("glGetError")] public GlGetError GetError { get; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GlClearStencil(int s); [GlEntryPoint("glClearStencil")] public GlClearStencil ClearStencil { get; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GlClearColor(float r, float g, float b, float a); [GlEntryPoint("glClearColor")] public GlClearColor ClearColor { get; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GlClear(int bits); [GlEntryPoint("glClear")] public GlClear Clear { get; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GlViewport(int x, int y, int width, int height); [GlEntryPoint("glViewport")] public GlViewport Viewport { get; } [GlEntryPoint("glFlush")] public UnmanagedAction Flush { get; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void UnmanagedAction(); [GlEntryPoint("glFinish")] public UnmanagedAction Finish { get; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate IntPtr GlGetString(int v); [GlEntryPoint("glGetString")] public GlGetString GetStringNative { get; } public string GetString(int v) { var ptr = GetStringNative(v); if (ptr != IntPtr.Zero) return Marshal.PtrToStringAnsi(ptr); return null; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GlGetIntegerv(int name, out int rv); [GlEntryPoint("glGetIntegerv")] public GlGetIntegerv GetIntegerv { get; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GlGenFramebuffers(int count, int[] res); [GlEntryPoint("glGenFramebuffers")] public GlGenFramebuffers GenFramebuffers { get; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GlDeleteFramebuffers(int count, int[] framebuffers); [GlEntryPoint("glDeleteFramebuffers")] public GlDeleteFramebuffers DeleteFramebuffers { get; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GlBindFramebuffer(int target, int fb); [GlEntryPoint("glBindFramebuffer")] public GlBindFramebuffer BindFramebuffer { get; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate int GlCheckFramebufferStatus(int target); [GlEntryPoint("glCheckFramebufferStatus")] public GlCheckFramebufferStatus CheckFramebufferStatus { get; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GlBlitFramebuffer(int srcX0, int srcY0, int srcX1, int srcY1, int dstX0, int dstY0, int dstX1, int dstY1, int mask, int filter); [GlMinVersionEntryPoint("glBlitFramebuffer", 3, 0), GlOptionalEntryPoint] public GlBlitFramebuffer BlitFramebuffer { get; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GlGenRenderbuffers(int count, int[] res); [GlEntryPoint("glGenRenderbuffers")] public GlGenRenderbuffers GenRenderbuffers { get; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GlDeleteRenderbuffers(int count, int[] renderbuffers); [GlEntryPoint("glDeleteRenderbuffers")] public GlDeleteTextures DeleteRenderbuffers { get; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GlBindRenderbuffer(int target, int fb); [GlEntryPoint("glBindRenderbuffer")] public GlBindRenderbuffer BindRenderbuffer { get; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GlRenderbufferStorage(int target, int internalFormat, int width, int height); [GlEntryPoint("glRenderbufferStorage")] public GlRenderbufferStorage RenderbufferStorage { get; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GlFramebufferRenderbuffer(int target, int attachment, int renderbufferTarget, int renderbuffer); [GlEntryPoint("glFramebufferRenderbuffer")] public GlFramebufferRenderbuffer FramebufferRenderbuffer { get; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GlGenTextures(int count, int[] res); [GlEntryPoint("glGenTextures")] public GlGenTextures GenTextures { get; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GlBindTexture(int target, int fb); [GlEntryPoint("glBindTexture")] public GlBindTexture BindTexture { get; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GlActiveTexture(int texture); [GlEntryPoint("glActiveTexture")] public GlActiveTexture ActiveTexture { get; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GlDeleteTextures(int count, int[] textures); [GlEntryPoint("glDeleteTextures")] public GlDeleteTextures DeleteTextures { get; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GlTexImage2D(int target, int level, int internalFormat, int width, int height, int border, int format, int type, IntPtr data); [GlEntryPoint("glTexImage2D")] public GlTexImage2D TexImage2D { get; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GlCopyTexSubImage2D(int target, int level, int xoffset, int yoffset, int x, int y, int width, int height); [GlEntryPoint("glCopyTexSubImage2D")] public GlCopyTexSubImage2D CopyTexSubImage2D { get; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GlTexParameteri(int target, int name, int value); [GlEntryPoint("glTexParameteri")] public GlTexParameteri TexParameteri { get; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GlFramebufferTexture2D(int target, int attachment, int texTarget, int texture, int level); [GlEntryPoint("glFramebufferTexture2D")] public GlFramebufferTexture2D FramebufferTexture2D { get; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate int GlCreateShader(int shaderType); [GlEntryPoint("glCreateShader")] public GlCreateShader CreateShader { get; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GlShaderSource(int shader, int count, IntPtr strings, IntPtr lengths); [GlEntryPoint("glShaderSource")] public GlShaderSource ShaderSource { get; } public void ShaderSourceString(int shader, string source) { using (var b = new Utf8Buffer(source)) { var ptr = b.DangerousGetHandle(); var len = new IntPtr(b.ByteLen); ShaderSource(shader, 1, new IntPtr(&ptr), new IntPtr(&len)); } } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GlCompileShader(int shader); [GlEntryPoint("glCompileShader")] public GlCompileShader CompileShader { get; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GlGetShaderiv(int shader, int name, int* parameters); [GlEntryPoint("glGetShaderiv")] public GlGetShaderiv GetShaderiv { get; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GlGetShaderInfoLog(int shader, int maxLength, out int length, void*infoLog); [GlEntryPoint("glGetShaderInfoLog")] public GlGetShaderInfoLog GetShaderInfoLog { get; } public unsafe string CompileShaderAndGetError(int shader, string source) { ShaderSourceString(shader, source); CompileShader(shader); int compiled; GetShaderiv(shader, GL_COMPILE_STATUS, &compiled); if (compiled != 0) return null; int logLength; GetShaderiv(shader, GL_INFO_LOG_LENGTH, &logLength); if (logLength == 0) logLength = 4096; var logData = new byte[logLength]; int len; fixed (void* ptr = logData) GetShaderInfoLog(shader, logLength, out len, ptr); return Encoding.UTF8.GetString(logData,0, len); } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate int GlCreateProgram(); [GlEntryPoint("glCreateProgram")] public GlCreateProgram CreateProgram { get; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GlAttachShader(int program, int shader); [GlEntryPoint("glAttachShader")] public GlAttachShader AttachShader { get; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GlLinkProgram(int program); [GlEntryPoint("glLinkProgram")] public GlLinkProgram LinkProgram { get; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GlGetProgramiv(int program, int name, int* parameters); [GlEntryPoint("glGetProgramiv")] public GlGetProgramiv GetProgramiv { get; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GlGetProgramInfoLog(int program, int maxLength, out int len, void* infoLog); [GlEntryPoint("glGetProgramInfoLog")] public GlGetProgramInfoLog GetProgramInfoLog { get; } public unsafe string LinkProgramAndGetError(int program) { LinkProgram(program); int compiled; GetProgramiv(program, GL_LINK_STATUS, &compiled); if (compiled != 0) return null; int logLength; GetProgramiv(program, GL_INFO_LOG_LENGTH, &logLength); var logData = new byte[logLength]; int len; fixed (void* ptr = logData) GetProgramInfoLog(program, logLength, out len, ptr); return Encoding.UTF8.GetString(logData,0, len); } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GlBindAttribLocation(int program, int index, IntPtr name); [GlEntryPoint("glBindAttribLocation")] public GlBindAttribLocation BindAttribLocation { get; } public void BindAttribLocationString(int program, int index, string name) { using (var b = new Utf8Buffer(name)) BindAttribLocation(program, index, b.DangerousGetHandle()); } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GlGenBuffers(int len, int[] rv); [GlEntryPoint("glGenBuffers")] public GlGenBuffers GenBuffers { get; } public int GenBuffer() { var rv = new int[1]; GenBuffers(1, rv); return rv[0]; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GlBindBuffer(int target, int buffer); [GlEntryPoint("glBindBuffer")] public GlBindBuffer BindBuffer { get; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GlBufferData(int target, IntPtr size, IntPtr data, int usage); [GlEntryPoint("glBufferData")] public GlBufferData BufferData { get; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate int GlGetAttribLocation(int program, IntPtr name); [GlEntryPoint("glGetAttribLocation")] public GlGetAttribLocation GetAttribLocation { get; } public int GetAttribLocationString(int program, string name) { using (var b = new Utf8Buffer(name)) return GetAttribLocation(program, b.DangerousGetHandle()); } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GlVertexAttribPointer(int index, int size, int type, int normalized, int stride, IntPtr pointer); [GlEntryPoint("glVertexAttribPointer")] public GlVertexAttribPointer VertexAttribPointer { get; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GlEnableVertexAttribArray(int index); [GlEntryPoint("glEnableVertexAttribArray")] public GlEnableVertexAttribArray EnableVertexAttribArray { get; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GlUseProgram(int program); [GlEntryPoint("glUseProgram")] public GlUseProgram UseProgram { get; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GlDrawArrays(int mode, int first, IntPtr count); [GlEntryPoint("glDrawArrays")] public GlDrawArrays DrawArrays { get; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GlDrawElements(int mode, int count, int type, IntPtr indices); [GlEntryPoint("glDrawElements")] public GlDrawElements DrawElements { get; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate int GlGetUniformLocation(int program, IntPtr name); [GlEntryPoint("glGetUniformLocation")] public GlGetUniformLocation GetUniformLocation { get; } public int GetUniformLocationString(int program, string name) { using (var b = new Utf8Buffer(name)) return GetUniformLocation(program, b.DangerousGetHandle()); } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GlUniform1f(int location, float falue); [GlEntryPoint("glUniform1f")] public GlUniform1f Uniform1f { get; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GlUniformMatrix4fv(int location, int count, bool transpose, void* value); [GlEntryPoint("glUniformMatrix4fv")] public GlUniformMatrix4fv UniformMatrix4fv { get; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GlEnable(int what); [GlEntryPoint("glEnable")] public GlEnable Enable { get; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GlDeleteBuffers(int count, int[] buffers); [GlEntryPoint("glDeleteBuffers")] public GlDeleteBuffers DeleteBuffers { get; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GlDeleteProgram(int program); [GlEntryPoint("glDeleteProgram")] public GlDeleteProgram DeleteProgram { get; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GlDeleteShader(int shader); [GlEntryPoint("glDeleteShader")] public GlDeleteShader DeleteShader { get; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void GLGetRenderbufferParameteriv(int target, int name, int[] value); [GlEntryPoint("glGetRenderbufferParameteriv")] public GLGetRenderbufferParameteriv GetRenderbufferParameteriv { get; } // ReSharper restore UnassignedGetOnlyAutoProperty } }
/* * Copyright (c) 2007-2009, openmetaverse.org * 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. * - Neither the name of the openmetaverse.org nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ //#define DEBUG_VOICE using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Threading; using OpenMetaverse; using OpenMetaverse.StructuredData; #if (COGBOT_LIBOMV || USE_STHREADS) using ThreadPoolUtil; using Thread = ThreadPoolUtil.Thread; using ThreadPool = ThreadPoolUtil.ThreadPool; using Monitor = ThreadPoolUtil.Monitor; #endif namespace OpenMetaverse.Voice { public partial class VoiceGateway : IDisposable { // These states should be in increasing order of 'completeness' // so that the (int) values can drive a progress bar. public enum ConnectionState { None = 0, Provisioned, DaemonStarted, DaemonConnected, ConnectorConnected, AccountLogin, RegionCapAvailable, SessionRunning } internal string sipServer = ""; private string acctServer = "https://www.bhr.vivox.com/api2/"; private string connectionHandle; private string accountHandle; private string sessionHandle; // Parameters to Vivox daemon private string slvoicePath = ""; private string slvoiceArgs = "-ll 5"; private string daemonNode = "127.0.0.1"; private int daemonPort = 37331; private string voiceUser; private string voicePassword; private string spatialUri; private string spatialCredentials; // Session management private Dictionary<string, VoiceSession> sessions; private VoiceSession spatialSession; private Uri currentParcelCap; private Uri nextParcelCap; private string regionName; // Position update thread private Thread posThread; private ManualResetEvent posRestart; public GridClient Client; private VoicePosition position; private Vector3d oldPosition; private Vector3d oldAt; // Audio interfaces private List<string> inputDevices; /// <summary> /// List of audio input devices /// </summary> public List<string> CaptureDevices { get { return inputDevices; } } private List<string> outputDevices; /// <summary> /// List of audio output devices /// </summary> public List<string> PlaybackDevices { get { return outputDevices; } } private string currentCaptureDevice; private string currentPlaybackDevice; private bool testing = false; public event EventHandler OnSessionCreate; public event EventHandler OnSessionRemove; public delegate void VoiceConnectionChangeCallback(ConnectionState state); public event VoiceConnectionChangeCallback OnVoiceConnectionChange; public delegate void VoiceMicTestCallback(float level); public event VoiceMicTestCallback OnVoiceMicTest; public VoiceGateway(GridClient c) { Random rand = new Random(); daemonPort = rand.Next(34000, 44000); Client = c; sessions = new Dictionary<string, VoiceSession>(); position = new VoicePosition(); position.UpOrientation = new Vector3d(0.0, 1.0, 0.0); position.Velocity = new Vector3d(0.0, 0.0, 0.0); oldPosition = new Vector3d(0, 0, 0); oldAt = new Vector3d(1, 0, 0); slvoiceArgs = " -ll -1"; // Min logging slvoiceArgs += " -i 127.0.0.1:" + daemonPort.ToString(); // slvoiceArgs += " -lf " + control.instance.ClientDir; } /// <summary> /// Start up the Voice service. /// </summary> public void Start() { // Start the background thread if (posThread != null && posThread.IsAlive) posThread.Abort(); posThread = new Thread(new ThreadStart(PositionThreadBody)); posThread.Name = "VoicePositionUpdate"; posThread.IsBackground = true; posRestart = new ManualResetEvent(false); posThread.Start(); Client.Network.EventQueueRunning += new EventHandler<EventQueueRunningEventArgs>(Network_EventQueueRunning); // Connection events OnDaemonRunning += new VoiceGateway.DaemonRunningCallback(connector_OnDaemonRunning); OnDaemonCouldntRun += new VoiceGateway.DaemonCouldntRunCallback(connector_OnDaemonCouldntRun); OnConnectorCreateResponse += new EventHandler<VoiceGateway.VoiceConnectorEventArgs>(connector_OnConnectorCreateResponse); OnDaemonConnected += new DaemonConnectedCallback(connector_OnDaemonConnected); OnDaemonCouldntConnect += new DaemonCouldntConnectCallback(connector_OnDaemonCouldntConnect); OnAuxAudioPropertiesEvent += new EventHandler<AudioPropertiesEventArgs>(connector_OnAuxAudioPropertiesEvent); // Session events OnSessionStateChangeEvent += new EventHandler<SessionStateChangeEventArgs>(connector_OnSessionStateChangeEvent); OnSessionAddedEvent += new EventHandler<SessionAddedEventArgs>(connector_OnSessionAddedEvent); // Session Participants events OnSessionParticipantUpdatedEvent += new EventHandler<ParticipantUpdatedEventArgs>(connector_OnSessionParticipantUpdatedEvent); OnSessionParticipantAddedEvent += new EventHandler<ParticipantAddedEventArgs>(connector_OnSessionParticipantAddedEvent); // Device events OnAuxGetCaptureDevicesResponse += new EventHandler<VoiceDevicesEventArgs>(connector_OnAuxGetCaptureDevicesResponse); OnAuxGetRenderDevicesResponse += new EventHandler<VoiceDevicesEventArgs>(connector_OnAuxGetRenderDevicesResponse); // Generic status response OnVoiceResponse += new EventHandler<VoiceResponseEventArgs>(connector_OnVoiceResponse); // Account events OnAccountLoginResponse += new EventHandler<VoiceAccountEventArgs>(connector_OnAccountLoginResponse); Logger.Log("Voice initialized", Helpers.LogLevel.Info); // If voice provisioning capability is already available, // proceed with voice startup. Otherwise the EventQueueRunning // event will do it. System.Uri vCap = Client.Network.CurrentSim.Caps.CapabilityURI("ProvisionVoiceAccountRequest"); if (vCap != null) RequestVoiceProvision(vCap); } /// <summary> /// Handle miscellaneous request status /// </summary> /// <param name="sender"></param> /// <param name="e"></param> /// ///<remarks>If something goes wrong, we log it.</remarks> void connector_OnVoiceResponse(object sender, VoiceGateway.VoiceResponseEventArgs e) { if (e.StatusCode == 0) return; Logger.Log(e.Message + " on " + sender as string, Helpers.LogLevel.Error); } public void Stop() { Client.Network.EventQueueRunning -= new EventHandler<EventQueueRunningEventArgs>(Network_EventQueueRunning); // Connection events OnDaemonRunning -= new VoiceGateway.DaemonRunningCallback(connector_OnDaemonRunning); OnDaemonCouldntRun -= new VoiceGateway.DaemonCouldntRunCallback(connector_OnDaemonCouldntRun); OnConnectorCreateResponse -= new EventHandler<VoiceGateway.VoiceConnectorEventArgs>(connector_OnConnectorCreateResponse); OnDaemonConnected -= new VoiceGateway.DaemonConnectedCallback(connector_OnDaemonConnected); OnDaemonCouldntConnect -= new VoiceGateway.DaemonCouldntConnectCallback(connector_OnDaemonCouldntConnect); OnAuxAudioPropertiesEvent -= new EventHandler<AudioPropertiesEventArgs>(connector_OnAuxAudioPropertiesEvent); // Session events OnSessionStateChangeEvent -= new EventHandler<SessionStateChangeEventArgs>(connector_OnSessionStateChangeEvent); OnSessionAddedEvent -= new EventHandler<SessionAddedEventArgs>(connector_OnSessionAddedEvent); // Session Participants events OnSessionParticipantUpdatedEvent -= new EventHandler<ParticipantUpdatedEventArgs>(connector_OnSessionParticipantUpdatedEvent); OnSessionParticipantAddedEvent -= new EventHandler<ParticipantAddedEventArgs>(connector_OnSessionParticipantAddedEvent); OnSessionParticipantRemovedEvent -= new EventHandler<ParticipantRemovedEventArgs>(connector_OnSessionParticipantRemovedEvent); // Tuning events OnAuxGetCaptureDevicesResponse -= new EventHandler<VoiceGateway.VoiceDevicesEventArgs>(connector_OnAuxGetCaptureDevicesResponse); OnAuxGetRenderDevicesResponse -= new EventHandler<VoiceGateway.VoiceDevicesEventArgs>(connector_OnAuxGetRenderDevicesResponse); // Account events OnAccountLoginResponse -= new EventHandler<VoiceGateway.VoiceAccountEventArgs>(connector_OnAccountLoginResponse); // Stop the background thread if (posThread != null) { PosUpdating(false); if (posThread.IsAlive) posThread.Abort(); posThread = null; } // Close all sessions foreach (VoiceSession s in sessions.Values) { if (OnSessionRemove != null) OnSessionRemove(s, EventArgs.Empty); s.Close(); } // Clear out lots of state so in case of restart we begin at the beginning. currentParcelCap = null; sessions.Clear(); accountHandle = null; voiceUser = null; voicePassword = null; SessionTerminate(sessionHandle); sessionHandle = null; AccountLogout(accountHandle); accountHandle = null; ConnectorInitiateShutdown(connectionHandle); connectionHandle = null; StopDaemon(); } /// <summary> /// Cleanup oject resources /// </summary> public void Dispose() { Stop(); } internal string GetVoiceDaemonPath() { string myDir = Path.GetDirectoryName( (System.Reflection.Assembly.GetEntryAssembly() ?? typeof (VoiceGateway).Assembly).Location); if (Environment.OSVersion.Platform != PlatformID.MacOSX && Environment.OSVersion.Platform != PlatformID.Unix) { string localDaemon = Path.Combine(myDir, Path.Combine("voice", "SLVoice.exe")); if (File.Exists(localDaemon)) return localDaemon; string progFiles; if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("ProgramFiles(x86)"))) { progFiles = Environment.GetEnvironmentVariable("ProgramFiles(x86)"); } else { progFiles = Environment.GetEnvironmentVariable("ProgramFiles"); } if (System.IO.File.Exists(Path.Combine(progFiles, @"SecondLife" + Path.DirectorySeparatorChar + @"SLVoice.exe"))) { return Path.Combine(progFiles, @"SecondLife" + Path.DirectorySeparatorChar + @"SLVoice.exe"); } return Path.Combine(myDir, @"SLVoice.exe"); } else { string localDaemon = Path.Combine(myDir, Path.Combine("voice", "SLVoice")); if (File.Exists(localDaemon)) return localDaemon; return Path.Combine(myDir,"SLVoice"); } } void RequestVoiceProvision(System.Uri cap) { OpenMetaverse.Http.CapsClient capClient = new OpenMetaverse.Http.CapsClient(cap); capClient.OnComplete += new OpenMetaverse.Http.CapsClient.CompleteCallback(cClient_OnComplete); OSD postData = new OSD(); // STEP 0 Logger.Log("Requesting voice capability", Helpers.LogLevel.Info); capClient.BeginGetResponse(postData, OSDFormat.Xml, 10000); } /// <summary> /// Request voice cap when changing regions /// </summary> void Network_EventQueueRunning(object sender, EventQueueRunningEventArgs e) { // We only care about the sim we are in. if (e.Simulator != Client.Network.CurrentSim) return; // Did we provision voice login info? if (string.IsNullOrEmpty(voiceUser)) { // The startup steps are // 0. Get voice account info // 1. Start Daemon // 2. Create TCP connection // 3. Create Connector // 4. Account login // 5. Create session // Get the voice provisioning data System.Uri vCap = Client.Network.CurrentSim.Caps.CapabilityURI("ProvisionVoiceAccountRequest"); // Do we have voice capability? if (vCap == null) { Logger.Log("Null voice capability after event queue running", Helpers.LogLevel.Warning); } else { RequestVoiceProvision(vCap); } return; } else { // Change voice session for this region. ParcelChanged(); } } #region Participants void connector_OnSessionParticipantUpdatedEvent(object sender, ParticipantUpdatedEventArgs e) { VoiceSession s = FindSession(e.SessionHandle, false); if (s == null) return; s.ParticipantUpdate(e.URI, e.IsMuted, e.IsSpeaking, e.Volume, e.Energy); } public string SIPFromUUID(UUID id) { return "sip:" + nameFromID(id) + "@" + sipServer; } private static string nameFromID(UUID id) { string result = null; if (id == UUID.Zero) return result; // Prepending this apparently prevents conflicts with reserved names inside the vivox and diamondware code. result = "x"; // Base64 encode and replace the pieces of base64 that are less compatible // with e-mail local-parts. // See RFC-4648 "Base 64 Encoding with URL and Filename Safe Alphabet" byte[] encbuff = id.GetBytes(); result += Convert.ToBase64String(encbuff); result = result.Replace('+', '-'); result = result.Replace('/', '_'); return result; } void connector_OnSessionParticipantAddedEvent(object sender, ParticipantAddedEventArgs e) { VoiceSession s = FindSession(e.SessionHandle, false); if (s == null) { Logger.Log("Orphan participant", Helpers.LogLevel.Error); return; } s.AddParticipant(e.URI); } void connector_OnSessionParticipantRemovedEvent(object sender, ParticipantRemovedEventArgs e) { VoiceSession s = FindSession(e.SessionHandle, false); if (s == null) return; s.RemoveParticipant(e.URI); } #endregion #region Sessions void connector_OnSessionAddedEvent(object sender, SessionAddedEventArgs e) { sessionHandle = e.SessionHandle; // Create our session context. VoiceSession s = FindSession(sessionHandle, true); s.RegionName = regionName; spatialSession = s; // Tell any user-facing code. if (OnSessionCreate != null) OnSessionCreate(s, null); Logger.Log("Added voice session in " + regionName, Helpers.LogLevel.Info); } /// <summary> /// Handle a change in session state /// </summary> void connector_OnSessionStateChangeEvent(object sender, SessionStateChangeEventArgs e) { VoiceSession s; switch (e.State) { case VoiceGateway.SessionState.Connected: s = FindSession(e.SessionHandle, true); sessionHandle = e.SessionHandle; s.RegionName = regionName; spatialSession = s; Logger.Log("Voice connected in " + regionName, Helpers.LogLevel.Info); // Tell any user-facing code. if (OnSessionCreate != null) OnSessionCreate(s, null); break; case VoiceGateway.SessionState.Disconnected: s = FindSession(sessionHandle, false); sessions.Remove(sessionHandle); if (s != null) { Logger.Log("Voice disconnected in " + s.RegionName, Helpers.LogLevel.Info); // Inform interested parties if (OnSessionRemove != null) OnSessionRemove(s, null); if (s == spatialSession) spatialSession = null; } // The previous session is now ended. Check for a new one and // start it going. if (nextParcelCap != null) { currentParcelCap = nextParcelCap; nextParcelCap = null; RequestParcelInfo(currentParcelCap); } break; } } /// <summary> /// Close a voice session /// </summary> /// <param name="sessionHandle"></param> internal void CloseSession(string sessionHandle) { if (!sessions.ContainsKey(sessionHandle)) return; PosUpdating(false); ReportConnectionState(ConnectionState.AccountLogin); // Clean up spatial pointers. VoiceSession s = sessions[sessionHandle]; if (s.IsSpatial) { spatialSession = null; currentParcelCap = null; } // Remove this session from the master session list sessions.Remove(sessionHandle); // Let any user-facing code clean up. if (OnSessionRemove != null) OnSessionRemove(s, null); // Tell SLVoice to clean it up as well. SessionTerminate(sessionHandle); } /// <summary> /// Locate a Session context from its handle /// </summary> /// <remarks>Creates the session context if it does not exist.</remarks> VoiceSession FindSession(string sessionHandle, bool make) { if (sessions.ContainsKey(sessionHandle)) return sessions[sessionHandle]; if (!make) return null; // Create a new session and add it to the sessions list. VoiceSession s = new VoiceSession(this, sessionHandle); // Turn on position updating for spatial sessions // (For now, only spatial sessions are supported) if (s.IsSpatial) PosUpdating(true); // Register the session by its handle sessions.Add(sessionHandle, s); return s; } #endregion #region MinorResponses void connector_OnAuxAudioPropertiesEvent(object sender, AudioPropertiesEventArgs e) { if (OnVoiceMicTest != null) OnVoiceMicTest(e.MicEnergy); } #endregion private void ReportConnectionState(ConnectionState s) { if (OnVoiceConnectionChange == null) return; OnVoiceConnectionChange(s); } /// <summary> /// Handle completion of main voice cap request. /// </summary> /// <param name="client"></param> /// <param name="result"></param> /// <param name="error"></param> void cClient_OnComplete(OpenMetaverse.Http.CapsClient client, OpenMetaverse.StructuredData.OSD result, Exception error) { if (error != null) { Logger.Log("Voice cap error " + error.Message, Helpers.LogLevel.Error); return; } Logger.Log("Voice provisioned", Helpers.LogLevel.Info); ReportConnectionState(ConnectionState.Provisioned); OpenMetaverse.StructuredData.OSDMap pMap = result as OpenMetaverse.StructuredData.OSDMap; // We can get back 4 interesting values: // voice_sip_uri_hostname // voice_account_server_name (actually a full URI) // username // password if (pMap.ContainsKey("voice_sip_uri_hostname")) sipServer = pMap["voice_sip_uri_hostname"].AsString(); if (pMap.ContainsKey("voice_account_server_name")) acctServer = pMap["voice_account_server_name"].AsString(); voiceUser = pMap["username"].AsString(); voicePassword = pMap["password"].AsString(); // Start the SLVoice daemon slvoicePath = GetVoiceDaemonPath(); // Test if the executable exists if (!System.IO.File.Exists(slvoicePath)) { Logger.Log("SLVoice is missing", Helpers.LogLevel.Error); return; } // STEP 1 StartDaemon(slvoicePath, slvoiceArgs); } #region Daemon void connector_OnDaemonCouldntConnect() { Logger.Log("No voice daemon connect", Helpers.LogLevel.Error); } void connector_OnDaemonCouldntRun() { Logger.Log("Daemon not started", Helpers.LogLevel.Error); } /// <summary> /// Daemon has started so connect to it. /// </summary> void connector_OnDaemonRunning() { OnDaemonRunning -= new VoiceGateway.DaemonRunningCallback(connector_OnDaemonRunning); Logger.Log("Daemon started", Helpers.LogLevel.Info); ReportConnectionState(ConnectionState.DaemonStarted); // STEP 2 ConnectToDaemon(daemonNode, daemonPort); } /// <summary> /// The daemon TCP connection is open. /// </summary> void connector_OnDaemonConnected() { Logger.Log("Daemon connected", Helpers.LogLevel.Info); ReportConnectionState(ConnectionState.DaemonConnected); // The connector is what does the logging. VoiceGateway.VoiceLoggingSettings vLog = new VoiceGateway.VoiceLoggingSettings(); #if DEBUG_VOICE vLog.Enabled = true; vLog.FileNamePrefix = "OpenmetaverseVoice"; vLog.FileNameSuffix = ".log"; vLog.LogLevel = 4; #endif // STEP 3 int reqId = ConnectorCreate( "V2 SDK", // Magic value keeps SLVoice happy acctServer, // Account manager server 30000, 30099, // port range vLog); if (reqId < 0) { Logger.Log("No voice connector request", Helpers.LogLevel.Error); } } /// <summary> /// Handle creation of the Connector. /// </summary> void connector_OnConnectorCreateResponse( object sender, VoiceGateway.VoiceConnectorEventArgs e) { Logger.Log("Voice daemon protocol started " + e.Message, Helpers.LogLevel.Info); connectionHandle = e.Handle; if (e.StatusCode != 0) return; // STEP 4 AccountLogin( connectionHandle, voiceUser, voicePassword, "VerifyAnswer", // This can also be "AutoAnswer" "", // Default account management server URI 10, // Throttle state changes true); // Enable buddies and presence } #endregion void connector_OnAccountLoginResponse( object sender, VoiceGateway.VoiceAccountEventArgs e) { Logger.Log("Account Login " + e.Message, Helpers.LogLevel.Info); accountHandle = e.AccountHandle; ReportConnectionState(ConnectionState.AccountLogin); ParcelChanged(); } #region Audio devices /// <summary> /// Handle response to audio output device query /// </summary> void connector_OnAuxGetRenderDevicesResponse( object sender, VoiceGateway.VoiceDevicesEventArgs e) { outputDevices = e.Devices; currentPlaybackDevice = e.CurrentDevice; } /// <summary> /// Handle response to audio input device query /// </summary> void connector_OnAuxGetCaptureDevicesResponse( object sender, VoiceGateway.VoiceDevicesEventArgs e) { inputDevices = e.Devices; currentCaptureDevice = e.CurrentDevice; } public string CurrentCaptureDevice { get { return currentCaptureDevice; } set { currentCaptureDevice = value; AuxSetCaptureDevice(value); } } public string PlaybackDevice { get { return currentPlaybackDevice; } set { currentPlaybackDevice = value; AuxSetRenderDevice(value); } } public int MicLevel { set { ConnectorSetLocalMicVolume(connectionHandle, value); } } public int SpkrLevel { set { ConnectorSetLocalSpeakerVolume(connectionHandle, value); } } public bool MicMute { set { ConnectorMuteLocalMic(connectionHandle, value); } } public bool SpkrMute { set { ConnectorMuteLocalSpeaker(connectionHandle, value); } } /// <summary> /// Set audio test mode /// </summary> public bool TestMode { get { return testing; } set { testing = value; if (testing) { if (spatialSession != null) { spatialSession.Close(); spatialSession = null; } AuxCaptureAudioStart(0); } else { AuxCaptureAudioStop(); ParcelChanged(); } } } #endregion /// <summary> /// Set voice channel for new parcel /// </summary> /// internal void ParcelChanged() { // Get the capability for this parcel. Caps c = Client.Network.CurrentSim.Caps; System.Uri pCap = c.CapabilityURI("ParcelVoiceInfoRequest"); if (pCap == null) { Logger.Log("Null voice capability", Helpers.LogLevel.Error); return; } // Parcel has changed. If we were already in a spatial session, we have to close it first. if (spatialSession != null) { nextParcelCap = pCap; CloseSession(spatialSession.Handle); } // Not already in a session, so can start the new one. RequestParcelInfo(pCap); } private OpenMetaverse.Http.CapsClient parcelCap; /// <summary> /// Request info from a parcel capability Uri. /// </summary> /// <param name="cap"></param> void RequestParcelInfo(Uri cap) { Logger.Log("Requesting region voice info", Helpers.LogLevel.Info); parcelCap = new OpenMetaverse.Http.CapsClient(cap); parcelCap.OnComplete += new OpenMetaverse.Http.CapsClient.CompleteCallback(pCap_OnComplete); OSD postData = new OSD(); currentParcelCap = cap; parcelCap.BeginGetResponse(postData, OSDFormat.Xml, 10000); } /// <summary> /// Receive parcel voice cap /// </summary> /// <param name="client"></param> /// <param name="result"></param> /// <param name="error"></param> void pCap_OnComplete(OpenMetaverse.Http.CapsClient client, OpenMetaverse.StructuredData.OSD result, Exception error) { parcelCap.OnComplete -= new OpenMetaverse.Http.CapsClient.CompleteCallback(pCap_OnComplete); parcelCap = null; if (error != null) { Logger.Log("Region voice cap " + error.Message, Helpers.LogLevel.Error); return; } OpenMetaverse.StructuredData.OSDMap pMap = result as OpenMetaverse.StructuredData.OSDMap; regionName = pMap["region_name"].AsString(); ReportConnectionState(ConnectionState.RegionCapAvailable); if (pMap.ContainsKey("voice_credentials")) { OpenMetaverse.StructuredData.OSDMap cred = pMap["voice_credentials"] as OpenMetaverse.StructuredData.OSDMap; if (cred.ContainsKey("channel_uri")) spatialUri = cred["channel_uri"].AsString(); if (cred.ContainsKey("channel_credentials")) spatialCredentials = cred["channel_credentials"].AsString(); } if (spatialUri == null || spatialUri == "") { // "No voice chat allowed here"); return; } Logger.Log("Voice connecting for region " + regionName, Helpers.LogLevel.Info); // STEP 5 int reqId = SessionCreate( accountHandle, spatialUri, // uri "", // Channel name seems to be always null spatialCredentials, // spatialCredentials, // session password true, // Join Audio false, // Join Text ""); if (reqId < 0) { Logger.Log("Voice Session ReqID " + reqId.ToString(), Helpers.LogLevel.Error); } } #region Location Update /// <summary> /// Tell Vivox where we are standing /// </summary> /// <remarks>This has to be called when we move or turn.</remarks> internal void UpdatePosition(AgentManager self) { // Get position in Global coordinates Vector3d OMVpos = new Vector3d(self.GlobalPosition); // Do not send trivial updates. if (OMVpos.ApproxEquals(oldPosition, 1.0)) return; oldPosition = OMVpos; // Convert to the coordinate space that Vivox uses // OMV X is East, Y is North, Z is up // VVX X is East, Y is up, Z is South position.Position = new Vector3d(OMVpos.X, OMVpos.Z, -OMVpos.Y); // TODO Rotate these two vectors // Get azimuth from the facing Quaternion. // By definition, facing.W = Cos( angle/2 ) double angle = 2.0 * Math.Acos(self.Movement.BodyRotation.W); position.LeftOrientation = new Vector3d(-1.0, 0.0, 0.0); position.AtOrientation = new Vector3d((float)Math.Acos(angle), 0.0, -(float)Math.Asin(angle)); SessionSet3DPosition( sessionHandle, position, position); } /// <summary> /// Start and stop updating out position. /// </summary> /// <param name="go"></param> internal void PosUpdating(bool go) { if (go) posRestart.Set(); else posRestart.Reset(); } private void PositionThreadBody() { while (true) { posRestart.WaitOne(); Thread.Sleep(1500); UpdatePosition(Client.Self); } } #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.Diagnostics; using System.Dynamic.Utils; using System.Reflection; using System.Reflection.Emit; namespace System.Linq.Expressions.Compiler { internal static class ILGen { internal static void Emit(this ILGenerator il, OpCode opcode, MethodBase methodBase) { Debug.Assert(methodBase is MethodInfo || methodBase is ConstructorInfo); var ctor = methodBase as ConstructorInfo; if ((object)ctor != null) { il.Emit(opcode, ctor); } else { il.Emit(opcode, (MethodInfo)methodBase); } } #region Instruction helpers internal static void EmitLoadArg(this ILGenerator il, int index) { Debug.Assert(index >= 0); switch (index) { case 0: il.Emit(OpCodes.Ldarg_0); break; case 1: il.Emit(OpCodes.Ldarg_1); break; case 2: il.Emit(OpCodes.Ldarg_2); break; case 3: il.Emit(OpCodes.Ldarg_3); break; default: if (index <= Byte.MaxValue) { il.Emit(OpCodes.Ldarg_S, (byte)index); } else { il.Emit(OpCodes.Ldarg, index); } break; } } internal static void EmitLoadArgAddress(this ILGenerator il, int index) { Debug.Assert(index >= 0); if (index <= Byte.MaxValue) { il.Emit(OpCodes.Ldarga_S, (byte)index); } else { il.Emit(OpCodes.Ldarga, index); } } internal static void EmitStoreArg(this ILGenerator il, int index) { Debug.Assert(index >= 0); if (index <= Byte.MaxValue) { il.Emit(OpCodes.Starg_S, (byte)index); } else { il.Emit(OpCodes.Starg, index); } } /// <summary> /// Emits a Ldind* instruction for the appropriate type /// </summary> internal static void EmitLoadValueIndirect(this ILGenerator il, Type type) { ContractUtils.RequiresNotNull(type, "type"); if (type.GetTypeInfo().IsValueType) { if (type == typeof(int)) { il.Emit(OpCodes.Ldind_I4); } else if (type == typeof(uint)) { il.Emit(OpCodes.Ldind_U4); } else if (type == typeof(short)) { il.Emit(OpCodes.Ldind_I2); } else if (type == typeof(ushort)) { il.Emit(OpCodes.Ldind_U2); } else if (type == typeof(long) || type == typeof(ulong)) { il.Emit(OpCodes.Ldind_I8); } else if (type == typeof(char)) { il.Emit(OpCodes.Ldind_I2); } else if (type == typeof(bool)) { il.Emit(OpCodes.Ldind_I1); } else if (type == typeof(float)) { il.Emit(OpCodes.Ldind_R4); } else if (type == typeof(double)) { il.Emit(OpCodes.Ldind_R8); } else { il.Emit(OpCodes.Ldobj, type); } } else { il.Emit(OpCodes.Ldind_Ref); } } /// <summary> /// Emits a Stind* instruction for the appropriate type. /// </summary> internal static void EmitStoreValueIndirect(this ILGenerator il, Type type) { ContractUtils.RequiresNotNull(type, "type"); if (type.GetTypeInfo().IsValueType) { if (type == typeof(int)) { il.Emit(OpCodes.Stind_I4); } else if (type == typeof(short)) { il.Emit(OpCodes.Stind_I2); } else if (type == typeof(long) || type == typeof(ulong)) { il.Emit(OpCodes.Stind_I8); } else if (type == typeof(char)) { il.Emit(OpCodes.Stind_I2); } else if (type == typeof(bool)) { il.Emit(OpCodes.Stind_I1); } else if (type == typeof(float)) { il.Emit(OpCodes.Stind_R4); } else if (type == typeof(double)) { il.Emit(OpCodes.Stind_R8); } else { il.Emit(OpCodes.Stobj, type); } } else { il.Emit(OpCodes.Stind_Ref); } } // Emits the Ldelem* instruction for the appropriate type internal static void EmitLoadElement(this ILGenerator il, Type type) { ContractUtils.RequiresNotNull(type, "type"); if (!type.GetTypeInfo().IsValueType) { il.Emit(OpCodes.Ldelem_Ref); } else if (type.GetTypeInfo().IsEnum) { il.Emit(OpCodes.Ldelem, type); } else { switch (type.GetTypeCode()) { case TypeCode.Boolean: case TypeCode.SByte: il.Emit(OpCodes.Ldelem_I1); break; case TypeCode.Byte: il.Emit(OpCodes.Ldelem_U1); break; case TypeCode.Int16: il.Emit(OpCodes.Ldelem_I2); break; case TypeCode.Char: case TypeCode.UInt16: il.Emit(OpCodes.Ldelem_U2); break; case TypeCode.Int32: il.Emit(OpCodes.Ldelem_I4); break; case TypeCode.UInt32: il.Emit(OpCodes.Ldelem_U4); break; case TypeCode.Int64: case TypeCode.UInt64: il.Emit(OpCodes.Ldelem_I8); break; case TypeCode.Single: il.Emit(OpCodes.Ldelem_R4); break; case TypeCode.Double: il.Emit(OpCodes.Ldelem_R8); break; default: il.Emit(OpCodes.Ldelem, type); break; } } } /// <summary> /// Emits a Stelem* instruction for the appropriate type. /// </summary> internal static void EmitStoreElement(this ILGenerator il, Type type) { ContractUtils.RequiresNotNull(type, "type"); if (type.GetTypeInfo().IsEnum) { il.Emit(OpCodes.Stelem, type); return; } switch (type.GetTypeCode()) { case TypeCode.Boolean: case TypeCode.SByte: case TypeCode.Byte: il.Emit(OpCodes.Stelem_I1); break; case TypeCode.Char: case TypeCode.Int16: case TypeCode.UInt16: il.Emit(OpCodes.Stelem_I2); break; case TypeCode.Int32: case TypeCode.UInt32: il.Emit(OpCodes.Stelem_I4); break; case TypeCode.Int64: case TypeCode.UInt64: il.Emit(OpCodes.Stelem_I8); break; case TypeCode.Single: il.Emit(OpCodes.Stelem_R4); break; case TypeCode.Double: il.Emit(OpCodes.Stelem_R8); break; default: if (type.GetTypeInfo().IsValueType) { il.Emit(OpCodes.Stelem, type); } else { il.Emit(OpCodes.Stelem_Ref); } break; } } internal static void EmitType(this ILGenerator il, Type type) { ContractUtils.RequiresNotNull(type, "type"); il.Emit(OpCodes.Ldtoken, type); il.Emit(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle")); } #endregion #region Fields, properties and methods internal static void EmitFieldAddress(this ILGenerator il, FieldInfo fi) { ContractUtils.RequiresNotNull(fi, "fi"); if (fi.IsStatic) { il.Emit(OpCodes.Ldsflda, fi); } else { il.Emit(OpCodes.Ldflda, fi); } } internal static void EmitFieldGet(this ILGenerator il, FieldInfo fi) { ContractUtils.RequiresNotNull(fi, "fi"); if (fi.IsStatic) { il.Emit(OpCodes.Ldsfld, fi); } else { il.Emit(OpCodes.Ldfld, fi); } } internal static void EmitFieldSet(this ILGenerator il, FieldInfo fi) { ContractUtils.RequiresNotNull(fi, "fi"); if (fi.IsStatic) { il.Emit(OpCodes.Stsfld, fi); } else { il.Emit(OpCodes.Stfld, fi); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] internal static void EmitNew(this ILGenerator il, ConstructorInfo ci) { ContractUtils.RequiresNotNull(ci, "ci"); if (ci.DeclaringType.GetTypeInfo().ContainsGenericParameters) { throw Error.IllegalNewGenericParams(ci.DeclaringType); } il.Emit(OpCodes.Newobj, ci); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] internal static void EmitNew(this ILGenerator il, Type type, Type[] paramTypes) { ContractUtils.RequiresNotNull(type, "type"); ContractUtils.RequiresNotNull(paramTypes, "paramTypes"); ConstructorInfo ci = type.GetConstructor(paramTypes); if (ci == null) throw Error.TypeDoesNotHaveConstructorForTheSignature(); il.EmitNew(ci); } #endregion #region Constants internal static void EmitNull(this ILGenerator il) { il.Emit(OpCodes.Ldnull); } internal static void EmitString(this ILGenerator il, string value) { ContractUtils.RequiresNotNull(value, "value"); il.Emit(OpCodes.Ldstr, value); } internal static void EmitBoolean(this ILGenerator il, bool value) { if (value) { il.Emit(OpCodes.Ldc_I4_1); } else { il.Emit(OpCodes.Ldc_I4_0); } } internal static void EmitChar(this ILGenerator il, char value) { il.EmitInt(value); il.Emit(OpCodes.Conv_U2); } internal static void EmitByte(this ILGenerator il, byte value) { il.EmitInt(value); il.Emit(OpCodes.Conv_U1); } internal static void EmitSByte(this ILGenerator il, sbyte value) { il.EmitInt(value); il.Emit(OpCodes.Conv_I1); } internal static void EmitShort(this ILGenerator il, short value) { il.EmitInt(value); il.Emit(OpCodes.Conv_I2); } internal static void EmitUShort(this ILGenerator il, ushort value) { il.EmitInt(value); il.Emit(OpCodes.Conv_U2); } internal static void EmitInt(this ILGenerator il, int value) { OpCode c; switch (value) { case -1: c = OpCodes.Ldc_I4_M1; break; case 0: c = OpCodes.Ldc_I4_0; break; case 1: c = OpCodes.Ldc_I4_1; break; case 2: c = OpCodes.Ldc_I4_2; break; case 3: c = OpCodes.Ldc_I4_3; break; case 4: c = OpCodes.Ldc_I4_4; break; case 5: c = OpCodes.Ldc_I4_5; break; case 6: c = OpCodes.Ldc_I4_6; break; case 7: c = OpCodes.Ldc_I4_7; break; case 8: c = OpCodes.Ldc_I4_8; break; default: if (value >= -128 && value <= 127) { il.Emit(OpCodes.Ldc_I4_S, (sbyte)value); } else { il.Emit(OpCodes.Ldc_I4, value); } return; } il.Emit(c); } internal static void EmitUInt(this ILGenerator il, uint value) { il.EmitInt((int)value); il.Emit(OpCodes.Conv_U4); } internal static void EmitLong(this ILGenerator il, long value) { il.Emit(OpCodes.Ldc_I8, value); // // Now, emit convert to give the constant type information. // // Otherwise, it is treated as unsigned and overflow is not // detected if it's used in checked ops. // il.Emit(OpCodes.Conv_I8); } internal static void EmitULong(this ILGenerator il, ulong value) { il.Emit(OpCodes.Ldc_I8, (long)value); il.Emit(OpCodes.Conv_U8); } internal static void EmitDouble(this ILGenerator il, double value) { il.Emit(OpCodes.Ldc_R8, value); } internal static void EmitSingle(this ILGenerator il, float value) { il.Emit(OpCodes.Ldc_R4, value); } // matches TryEmitConstant internal static bool CanEmitConstant(object value, Type type) { if (value == null || CanEmitILConstant(type)) { return true; } Type t = value as Type; if (t != null && ShouldLdtoken(t)) { return true; } MethodBase mb = value as MethodBase; if (mb != null && ShouldLdtoken(mb)) { return true; } return false; } // matches TryEmitILConstant private static bool CanEmitILConstant(Type type) { switch (type.GetTypeCode()) { case TypeCode.Boolean: case TypeCode.SByte: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Char: case TypeCode.Byte: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: case TypeCode.Decimal: case TypeCode.String: return true; } return false; } internal static void EmitConstant(this ILGenerator il, object value) { Debug.Assert(value != null); EmitConstant(il, value, value.GetType()); } // // Note: we support emitting more things as IL constants than // Linq does internal static void EmitConstant(this ILGenerator il, object value, Type type) { if (value == null) { // Smarter than the Linq implementation which uses the initobj // pattern for all value types (works, but requires a local and // more IL) il.EmitDefault(type); return; } // Handle the easy cases if (il.TryEmitILConstant(value, type)) { return; } // Check for a few more types that we support emitting as constants Type t = value as Type; if (t != null && ShouldLdtoken(t)) { il.EmitType(t); if (type != typeof(Type)) { il.Emit(OpCodes.Castclass, type); } return; } MethodBase mb = value as MethodBase; if (mb != null && ShouldLdtoken(mb)) { il.Emit(OpCodes.Ldtoken, mb); Type dt = mb.DeclaringType; if (dt != null && dt.GetTypeInfo().IsGenericType) { il.Emit(OpCodes.Ldtoken, dt); il.Emit(OpCodes.Call, typeof(MethodBase).GetMethod("GetMethodFromHandle", new Type[] { typeof(RuntimeMethodHandle), typeof(RuntimeTypeHandle) })); } else { il.Emit(OpCodes.Call, typeof(MethodBase).GetMethod("GetMethodFromHandle", new Type[] { typeof(RuntimeMethodHandle) })); } if (type != typeof(MethodBase)) { il.Emit(OpCodes.Castclass, type); } return; } throw ContractUtils.Unreachable; } internal static bool ShouldLdtoken(Type t) { return t.GetTypeInfo() is TypeBuilder || t.IsGenericParameter || t.GetTypeInfo().IsVisible; } internal static bool ShouldLdtoken(MethodBase mb) { // Can't ldtoken on a DynamicMethod if (mb is DynamicMethod) { return false; } Type dt = mb.DeclaringType; return dt == null || ShouldLdtoken(dt); } private static bool TryEmitILConstant(this ILGenerator il, object value, Type type) { switch (type.GetTypeCode()) { case TypeCode.Boolean: il.EmitBoolean((bool)value); return true; case TypeCode.SByte: il.EmitSByte((sbyte)value); return true; case TypeCode.Int16: il.EmitShort((short)value); return true; case TypeCode.Int32: il.EmitInt((int)value); return true; case TypeCode.Int64: il.EmitLong((long)value); return true; case TypeCode.Single: il.EmitSingle((float)value); return true; case TypeCode.Double: il.EmitDouble((double)value); return true; case TypeCode.Char: il.EmitChar((char)value); return true; case TypeCode.Byte: il.EmitByte((byte)value); return true; case TypeCode.UInt16: il.EmitUShort((ushort)value); return true; case TypeCode.UInt32: il.EmitUInt((uint)value); return true; case TypeCode.UInt64: il.EmitULong((ulong)value); return true; case TypeCode.Decimal: il.EmitDecimal((decimal)value); return true; case TypeCode.String: il.EmitString((string)value); return true; default: return false; } } #endregion #region Linq Conversions internal static void EmitConvertToType(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked) { if (TypeUtils.AreEquivalent(typeFrom, typeTo)) { return; } if (typeFrom == typeof(void) || typeTo == typeof(void)) { throw ContractUtils.Unreachable; } bool isTypeFromNullable = TypeUtils.IsNullableType(typeFrom); bool isTypeToNullable = TypeUtils.IsNullableType(typeTo); Type nnExprType = TypeUtils.GetNonNullableType(typeFrom); Type nnType = TypeUtils.GetNonNullableType(typeTo); if (typeFrom.GetTypeInfo().IsInterface || // interface cast typeTo.GetTypeInfo().IsInterface || typeFrom == typeof(object) || // boxing cast typeTo == typeof(object) || typeFrom == typeof(System.Enum) || typeFrom == typeof(System.ValueType) || TypeUtils.IsLegalExplicitVariantDelegateConversion(typeFrom, typeTo)) { il.EmitCastToType(typeFrom, typeTo); } else if (isTypeFromNullable || isTypeToNullable) { il.EmitNullableConversion(typeFrom, typeTo, isChecked); } else if (!(TypeUtils.IsConvertible(typeFrom) && TypeUtils.IsConvertible(typeTo)) // primitive runtime conversion && (nnExprType.IsAssignableFrom(nnType) || // down cast nnType.IsAssignableFrom(nnExprType))) // up cast { il.EmitCastToType(typeFrom, typeTo); } else if (typeFrom.IsArray && typeTo.IsArray) { // See DevDiv Bugs #94657. il.EmitCastToType(typeFrom, typeTo); } else { il.EmitNumericConversion(typeFrom, typeTo, isChecked); } } private static void EmitCastToType(this ILGenerator il, Type typeFrom, Type typeTo) { if (!typeFrom.GetTypeInfo().IsValueType && typeTo.GetTypeInfo().IsValueType) { il.Emit(OpCodes.Unbox_Any, typeTo); } else if (typeFrom.GetTypeInfo().IsValueType && !typeTo.GetTypeInfo().IsValueType) { il.Emit(OpCodes.Box, typeFrom); if (typeTo != typeof(object)) { il.Emit(OpCodes.Castclass, typeTo); } } else if (!typeFrom.GetTypeInfo().IsValueType && !typeTo.GetTypeInfo().IsValueType) { il.Emit(OpCodes.Castclass, typeTo); } else { throw Error.InvalidCast(typeFrom, typeTo); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] private static void EmitNumericConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked) { bool isFromUnsigned = TypeUtils.IsUnsigned(typeFrom); bool isFromFloatingPoint = TypeUtils.IsFloatingPoint(typeFrom); if (typeTo == typeof(Single)) { if (isFromUnsigned) il.Emit(OpCodes.Conv_R_Un); il.Emit(OpCodes.Conv_R4); } else if (typeTo == typeof(Double)) { if (isFromUnsigned) il.Emit(OpCodes.Conv_R_Un); il.Emit(OpCodes.Conv_R8); } else { TypeCode tc = typeTo.GetTypeCode(); if (isChecked) { // Overflow checking needs to know if the source value on the IL stack is unsigned or not. if (isFromUnsigned) { switch (tc) { case TypeCode.SByte: il.Emit(OpCodes.Conv_Ovf_I1_Un); break; case TypeCode.Int16: il.Emit(OpCodes.Conv_Ovf_I2_Un); break; case TypeCode.Int32: il.Emit(OpCodes.Conv_Ovf_I4_Un); break; case TypeCode.Int64: il.Emit(OpCodes.Conv_Ovf_I8_Un); break; case TypeCode.Byte: il.Emit(OpCodes.Conv_Ovf_U1_Un); break; case TypeCode.UInt16: case TypeCode.Char: il.Emit(OpCodes.Conv_Ovf_U2_Un); break; case TypeCode.UInt32: il.Emit(OpCodes.Conv_Ovf_U4_Un); break; case TypeCode.UInt64: il.Emit(OpCodes.Conv_Ovf_U8_Un); break; default: throw Error.UnhandledConvert(typeTo); } } else { switch (tc) { case TypeCode.SByte: il.Emit(OpCodes.Conv_Ovf_I1); break; case TypeCode.Int16: il.Emit(OpCodes.Conv_Ovf_I2); break; case TypeCode.Int32: il.Emit(OpCodes.Conv_Ovf_I4); break; case TypeCode.Int64: il.Emit(OpCodes.Conv_Ovf_I8); break; case TypeCode.Byte: il.Emit(OpCodes.Conv_Ovf_U1); break; case TypeCode.UInt16: case TypeCode.Char: il.Emit(OpCodes.Conv_Ovf_U2); break; case TypeCode.UInt32: il.Emit(OpCodes.Conv_Ovf_U4); break; case TypeCode.UInt64: il.Emit(OpCodes.Conv_Ovf_U8); break; default: throw Error.UnhandledConvert(typeTo); } } } else { switch (tc) { case TypeCode.SByte: il.Emit(OpCodes.Conv_I1); break; case TypeCode.Byte: il.Emit(OpCodes.Conv_U1); break; case TypeCode.Int16: il.Emit(OpCodes.Conv_I2); break; case TypeCode.UInt16: case TypeCode.Char: il.Emit(OpCodes.Conv_U2); break; case TypeCode.Int32: il.Emit(OpCodes.Conv_I4); break; case TypeCode.UInt32: il.Emit(OpCodes.Conv_U4); break; case TypeCode.Int64: if (isFromUnsigned) { il.Emit(OpCodes.Conv_U8); } else { il.Emit(OpCodes.Conv_I8); } break; case TypeCode.UInt64: if (isFromUnsigned || isFromFloatingPoint) { il.Emit(OpCodes.Conv_U8); } else { il.Emit(OpCodes.Conv_I8); } break; default: throw Error.UnhandledConvert(typeTo); } } } } private static void EmitNullableToNullableConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked) { Debug.Assert(TypeUtils.IsNullableType(typeFrom)); Debug.Assert(TypeUtils.IsNullableType(typeTo)); Label labIfNull = default(Label); Label labEnd = default(Label); LocalBuilder locFrom = null; LocalBuilder locTo = null; locFrom = il.DeclareLocal(typeFrom); il.Emit(OpCodes.Stloc, locFrom); locTo = il.DeclareLocal(typeTo); // test for null il.Emit(OpCodes.Ldloca, locFrom); il.EmitHasValue(typeFrom); labIfNull = il.DefineLabel(); il.Emit(OpCodes.Brfalse_S, labIfNull); il.Emit(OpCodes.Ldloca, locFrom); il.EmitGetValueOrDefault(typeFrom); Type nnTypeFrom = TypeUtils.GetNonNullableType(typeFrom); Type nnTypeTo = TypeUtils.GetNonNullableType(typeTo); il.EmitConvertToType(nnTypeFrom, nnTypeTo, isChecked); // construct result type ConstructorInfo ci = typeTo.GetConstructor(new Type[] { nnTypeTo }); il.Emit(OpCodes.Newobj, ci); il.Emit(OpCodes.Stloc, locTo); labEnd = il.DefineLabel(); il.Emit(OpCodes.Br_S, labEnd); // if null then create a default one il.MarkLabel(labIfNull); il.Emit(OpCodes.Ldloca, locTo); il.Emit(OpCodes.Initobj, typeTo); il.MarkLabel(labEnd); il.Emit(OpCodes.Ldloc, locTo); } private static void EmitNonNullableToNullableConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked) { Debug.Assert(!TypeUtils.IsNullableType(typeFrom)); Debug.Assert(TypeUtils.IsNullableType(typeTo)); LocalBuilder locTo = null; locTo = il.DeclareLocal(typeTo); Type nnTypeTo = TypeUtils.GetNonNullableType(typeTo); il.EmitConvertToType(typeFrom, nnTypeTo, isChecked); ConstructorInfo ci = typeTo.GetConstructor(new Type[] { nnTypeTo }); il.Emit(OpCodes.Newobj, ci); il.Emit(OpCodes.Stloc, locTo); il.Emit(OpCodes.Ldloc, locTo); } private static void EmitNullableToNonNullableConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked) { Debug.Assert(TypeUtils.IsNullableType(typeFrom)); Debug.Assert(!TypeUtils.IsNullableType(typeTo)); if (typeTo.GetTypeInfo().IsValueType) il.EmitNullableToNonNullableStructConversion(typeFrom, typeTo, isChecked); else il.EmitNullableToReferenceConversion(typeFrom); } private static void EmitNullableToNonNullableStructConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked) { Debug.Assert(TypeUtils.IsNullableType(typeFrom)); Debug.Assert(!TypeUtils.IsNullableType(typeTo)); Debug.Assert(typeTo.GetTypeInfo().IsValueType); LocalBuilder locFrom = null; locFrom = il.DeclareLocal(typeFrom); il.Emit(OpCodes.Stloc, locFrom); il.Emit(OpCodes.Ldloca, locFrom); il.EmitGetValue(typeFrom); Type nnTypeFrom = TypeUtils.GetNonNullableType(typeFrom); il.EmitConvertToType(nnTypeFrom, typeTo, isChecked); } private static void EmitNullableToReferenceConversion(this ILGenerator il, Type typeFrom) { Debug.Assert(TypeUtils.IsNullableType(typeFrom)); // We've got a conversion from nullable to Object, ValueType, Enum, etc. Just box it so that // we get the nullable semantics. il.Emit(OpCodes.Box, typeFrom); } private static void EmitNullableConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked) { bool isTypeFromNullable = TypeUtils.IsNullableType(typeFrom); bool isTypeToNullable = TypeUtils.IsNullableType(typeTo); Debug.Assert(isTypeFromNullable || isTypeToNullable); if (isTypeFromNullable && isTypeToNullable) il.EmitNullableToNullableConversion(typeFrom, typeTo, isChecked); else if (isTypeFromNullable) il.EmitNullableToNonNullableConversion(typeFrom, typeTo, isChecked); else il.EmitNonNullableToNullableConversion(typeFrom, typeTo, isChecked); } internal static void EmitHasValue(this ILGenerator il, Type nullableType) { MethodInfo mi = nullableType.GetMethod("get_HasValue", BindingFlags.Instance | BindingFlags.Public); Debug.Assert(nullableType.GetTypeInfo().IsValueType); il.Emit(OpCodes.Call, mi); } internal static void EmitGetValue(this ILGenerator il, Type nullableType) { MethodInfo mi = nullableType.GetMethod("get_Value", BindingFlags.Instance | BindingFlags.Public); Debug.Assert(nullableType.GetTypeInfo().IsValueType); il.Emit(OpCodes.Call, mi); } internal static void EmitGetValueOrDefault(this ILGenerator il, Type nullableType) { MethodInfo mi = nullableType.GetMethod("GetValueOrDefault", System.Type.EmptyTypes); Debug.Assert(nullableType.GetTypeInfo().IsValueType); il.Emit(OpCodes.Call, mi); } #endregion #region Arrays /// <summary> /// Emits an array of constant values provided in the given list. /// The array is strongly typed. /// </summary> internal static void EmitArray<T>(this ILGenerator il, IList<T> items) { ContractUtils.RequiresNotNull(items, "items"); il.EmitInt(items.Count); il.Emit(OpCodes.Newarr, typeof(T)); for (int i = 0; i < items.Count; i++) { il.Emit(OpCodes.Dup); il.EmitInt(i); il.EmitConstant(items[i], typeof(T)); il.EmitStoreElement(typeof(T)); } } /// <summary> /// Emits an array of values of count size. The items are emitted via the callback /// which is provided with the current item index to emit. /// </summary> internal static void EmitArray(this ILGenerator il, Type elementType, int count, Action<int> emit) { ContractUtils.RequiresNotNull(elementType, "elementType"); ContractUtils.RequiresNotNull(emit, "emit"); if (count < 0) throw Error.CountCannotBeNegative(); il.EmitInt(count); il.Emit(OpCodes.Newarr, elementType); for (int i = 0; i < count; i++) { il.Emit(OpCodes.Dup); il.EmitInt(i); emit(i); il.EmitStoreElement(elementType); } } /// <summary> /// Emits an array construction code. /// The code assumes that bounds for all dimensions /// are already emitted. /// </summary> internal static void EmitArray(this ILGenerator il, Type arrayType) { ContractUtils.RequiresNotNull(arrayType, "arrayType"); if (!arrayType.IsArray) throw Error.ArrayTypeMustBeArray(); if (arrayType.IsVector()) { il.Emit(OpCodes.Newarr, arrayType.GetElementType()); } else { int rank = arrayType.GetArrayRank(); Type[] types = new Type[rank]; for (int i = 0; i < rank; i++) { types[i] = typeof(int); } il.EmitNew(arrayType, types); } } #endregion #region Support for emitting constants internal static void EmitDecimal(this ILGenerator il, decimal value) { if (Decimal.Truncate(value) == value) { if (Int32.MinValue <= value && value <= Int32.MaxValue) { int intValue = Decimal.ToInt32(value); il.EmitInt(intValue); il.EmitNew(typeof(Decimal).GetConstructor(new Type[] { typeof(int) })); } else if (Int64.MinValue <= value && value <= Int64.MaxValue) { long longValue = Decimal.ToInt64(value); il.EmitLong(longValue); il.EmitNew(typeof(Decimal).GetConstructor(new Type[] { typeof(long) })); } else { il.EmitDecimalBits(value); } } else { il.EmitDecimalBits(value); } } private static void EmitDecimalBits(this ILGenerator il, decimal value) { int[] bits = Decimal.GetBits(value); il.EmitInt(bits[0]); il.EmitInt(bits[1]); il.EmitInt(bits[2]); il.EmitBoolean((bits[3] & 0x80000000) != 0); il.EmitByte((byte)(bits[3] >> 16)); il.EmitNew(typeof(decimal).GetConstructor(new Type[] { typeof(int), typeof(int), typeof(int), typeof(bool), typeof(byte) })); } /// <summary> /// Emits default(T) /// Semantics match C# compiler behavior /// </summary> internal static void EmitDefault(this ILGenerator il, Type type) { switch (type.GetTypeCode()) { case TypeCode.Object: case TypeCode.DateTime: if (type.GetTypeInfo().IsValueType) { // Type.GetTypeCode on an enum returns the underlying // integer TypeCode, so we won't get here. Debug.Assert(!type.GetTypeInfo().IsEnum); // This is the IL for default(T) if T is a generic type // parameter, so it should work for any type. It's also // the standard pattern for structs. LocalBuilder lb = il.DeclareLocal(type); il.Emit(OpCodes.Ldloca, lb); il.Emit(OpCodes.Initobj, type); il.Emit(OpCodes.Ldloc, lb); } else { il.Emit(OpCodes.Ldnull); } break; case TypeCode.Empty: case TypeCode.String: il.Emit(OpCodes.Ldnull); break; case TypeCode.Boolean: case TypeCode.Char: case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: il.Emit(OpCodes.Ldc_I4_0); break; case TypeCode.Int64: case TypeCode.UInt64: il.Emit(OpCodes.Ldc_I4_0); il.Emit(OpCodes.Conv_I8); break; case TypeCode.Single: il.Emit(OpCodes.Ldc_R4, default(Single)); break; case TypeCode.Double: il.Emit(OpCodes.Ldc_R8, default(Double)); break; case TypeCode.Decimal: il.Emit(OpCodes.Ldc_I4_0); il.Emit(OpCodes.Newobj, typeof(Decimal).GetConstructor(new Type[] { typeof(int) })); break; default: throw ContractUtils.Unreachable; } } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using Microsoft.CodeAnalysis.Editor.Commands; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Composition; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Operations; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests { internal abstract class AbstractCommandHandlerTestState : IDisposable { public readonly TestWorkspace Workspace; public readonly IEditorOperations EditorOperations; public readonly ITextUndoHistoryRegistry UndoHistoryRegistry; private readonly ITextView _textView; private readonly ITextBuffer _subjectBuffer; public AbstractCommandHandlerTestState( XElement workspaceElement, ComposableCatalog extraParts = null, bool useMinimumCatalog = false, string workspaceKind = null) : this(workspaceElement, GetExportProvider(useMinimumCatalog, extraParts), workspaceKind) { } /// <summary> /// This can use input files with an (optionally) annotated span 'Selection' and a cursor position ($$), /// and use it to create a selected span in the TextView. /// /// For instance, the following will create a TextView that has a multiline selection with the cursor at the end. /// /// Sub Foo /// {|Selection:SomeMethodCall() /// AnotherMethodCall()$$|} /// End Sub /// </summary> public AbstractCommandHandlerTestState( XElement workspaceElement, ExportProvider exportProvider, string workspaceKind) { this.Workspace = TestWorkspaceFactory.CreateWorkspace( workspaceElement, exportProvider: exportProvider, workspaceKind: workspaceKind); var cursorDocument = this.Workspace.Documents.First(d => d.CursorPosition.HasValue); _textView = cursorDocument.GetTextView(); _subjectBuffer = cursorDocument.GetTextBuffer(); IList<Text.TextSpan> selectionSpanList; if (cursorDocument.AnnotatedSpans.TryGetValue("Selection", out selectionSpanList)) { var span = selectionSpanList.First(); var cursorPosition = cursorDocument.CursorPosition.Value; Assert.True(cursorPosition == span.Start || cursorPosition == span.Start + span.Length, "cursorPosition wasn't at an endpoint of the 'Selection' annotated span"); _textView.Selection.Select( new SnapshotSpan(_subjectBuffer.CurrentSnapshot, new Span(span.Start, span.Length)), isReversed: cursorPosition == span.Start); if (selectionSpanList.Count > 1) { _textView.Selection.Mode = TextSelectionMode.Box; foreach (var additionalSpan in selectionSpanList.Skip(1)) { _textView.Selection.Select( new SnapshotSpan(_subjectBuffer.CurrentSnapshot, new Span(additionalSpan.Start, additionalSpan.Length)), isReversed: false); } } } else { _textView.Caret.MoveTo( new SnapshotPoint( _textView.TextBuffer.CurrentSnapshot, cursorDocument.CursorPosition.Value)); } this.EditorOperations = GetService<IEditorOperationsFactoryService>().GetEditorOperations(_textView); this.UndoHistoryRegistry = GetService<ITextUndoHistoryRegistry>(); } public void Dispose() { Workspace.Dispose(); } public T GetService<T>() { return Workspace.GetService<T>(); } private static ExportProvider GetExportProvider(bool useMinimumCatalog, ComposableCatalog extraParts) { var baseCatalog = useMinimumCatalog ? TestExportProvider.MinimumCatalogWithCSharpAndVisualBasic : TestExportProvider.EntireAssemblyCatalogWithCSharpAndVisualBasic; if (extraParts == null) { return MinimalTestExportProvider.CreateExportProvider(baseCatalog); } return MinimalTestExportProvider.CreateExportProvider(baseCatalog.WithParts(extraParts)); } public virtual ITextView TextView { get { return _textView; } } public virtual ITextBuffer SubjectBuffer { get { return _subjectBuffer; } } #region MEF public Lazy<TExport, TMetadata> GetExport<TExport, TMetadata>() { return (Lazy<TExport, TMetadata>)(object)Workspace.ExportProvider.GetExport<TExport, TMetadata>(); } public IEnumerable<Lazy<TExport, TMetadata>> GetExports<TExport, TMetadata>() { return Workspace.ExportProvider.GetExports<TExport, TMetadata>(); } public T GetExportedValue<T>() { return Workspace.ExportProvider.GetExportedValue<T>(); } public IEnumerable<T> GetExportedValues<T>() { return Workspace.ExportProvider.GetExportedValues<T>(); } protected static IEnumerable<Lazy<TProvider, OrderableLanguageMetadata>> CreateLazyProviders<TProvider>( TProvider[] providers, string languageName) { if (providers == null) { return Array.Empty<Lazy<TProvider, OrderableLanguageMetadata>>(); } return providers.Select(p => new Lazy<TProvider, OrderableLanguageMetadata>( () => p, new OrderableLanguageMetadata( new Dictionary<string, object> { {"Language", languageName }, {"Name", string.Empty }}), true)); } protected static IEnumerable<Lazy<TProvider, OrderableLanguageAndRoleMetadata>> CreateLazyProviders<TProvider>( TProvider[] providers, string languageName, string[] roles) { if (providers == null) { return Array.Empty<Lazy<TProvider, OrderableLanguageAndRoleMetadata>>(); } return providers.Select(p => new Lazy<TProvider, OrderableLanguageAndRoleMetadata>( () => p, new OrderableLanguageAndRoleMetadata( new Dictionary<string, object> { {"Language", languageName }, {"Name", string.Empty }, {"Roles", roles }}), true)); } #endregion #region editor related operation public void SendBackspace() { EditorOperations.Backspace(); } public void SendDelete() { EditorOperations.Delete(); } public void SendRightKey(bool extendSelection = false) { EditorOperations.MoveToNextCharacter(extendSelection); } public void SendLeftKey(bool extendSelection = false) { EditorOperations.MoveToPreviousCharacter(extendSelection); } public void SendMoveToPreviousCharacter(bool extendSelection = false) { EditorOperations.MoveToPreviousCharacter(extendSelection); } public void SendDeleteWordToLeft() { EditorOperations.DeleteWordToLeft(); } public void SendUndo(int count = 1) { var history = UndoHistoryRegistry.GetHistory(SubjectBuffer); history.Undo(count); } #endregion #region test/information/verification public ITextSnapshotLine GetLineFromCurrentCaretPosition() { var caretPosition = GetCaretPoint(); return SubjectBuffer.CurrentSnapshot.GetLineFromPosition(caretPosition.BufferPosition); } public string GetLineTextFromCaretPosition() { var caretPosition = Workspace.Documents.Single(d => d.CursorPosition.HasValue).CursorPosition.Value; return SubjectBuffer.CurrentSnapshot.GetLineFromPosition(caretPosition).GetText(); } public string GetDocumentText() { return SubjectBuffer.CurrentSnapshot.GetText(); } public CaretPosition GetCaretPoint() { return TextView.Caret.Position; } public void WaitForAsynchronousOperations() { var waiters = Workspace.ExportProvider.GetExportedValues<IAsynchronousOperationWaiter>(); var tasks = waiters.Select(w => w.CreateWaitTask()).ToList(); tasks.PumpingWaitAll(); } public void AssertMatchesTextStartingAtLine(int line, string text) { var lines = text.Split('\r'); foreach (var expectedLine in lines) { Assert.Equal(expectedLine.Trim(), SubjectBuffer.CurrentSnapshot.GetLineFromLineNumber(line).GetText().Trim()); line += 1; } } #endregion #region command handler public void SendBackspace(Action<BackspaceKeyCommandArgs, Action> commandHandler, Action nextHandler) { commandHandler(new BackspaceKeyCommandArgs(TextView, SubjectBuffer), nextHandler); } public void SendDelete(Action<DeleteKeyCommandArgs, Action> commandHandler, Action nextHandler) { commandHandler(new DeleteKeyCommandArgs(TextView, SubjectBuffer), nextHandler); } public void SendWordDeleteToStart(Action<WordDeleteToStartCommandArgs, Action> commandHandler, Action nextHandler) { commandHandler(new WordDeleteToStartCommandArgs(TextView, SubjectBuffer), nextHandler); } public void SendEscape(Action<EscapeKeyCommandArgs, Action> commandHandler, Action nextHandler) { commandHandler(new EscapeKeyCommandArgs(TextView, SubjectBuffer), nextHandler); } public void SendUpKey(Action<UpKeyCommandArgs, Action> commandHandler, Action nextHandler) { commandHandler(new UpKeyCommandArgs(TextView, SubjectBuffer), nextHandler); } public void SendDownKey(Action<DownKeyCommandArgs, Action> commandHandler, Action nextHandler) { commandHandler(new DownKeyCommandArgs(TextView, SubjectBuffer), nextHandler); } public void SendTab(Action<TabKeyCommandArgs, Action> commandHandler, Action nextHandler) { commandHandler(new TabKeyCommandArgs(TextView, SubjectBuffer), nextHandler); } public void SendBackTab(Action<BackTabKeyCommandArgs, Action> commandHandler, Action nextHandler) { commandHandler(new BackTabKeyCommandArgs(TextView, SubjectBuffer), nextHandler); } public void SendReturn(Action<ReturnKeyCommandArgs, Action> commandHandler, Action nextHandler) { commandHandler(new ReturnKeyCommandArgs(TextView, SubjectBuffer), nextHandler); } public void SendPageUp(Action<PageUpKeyCommandArgs, Action> commandHandler, Action nextHandler) { commandHandler(new PageUpKeyCommandArgs(TextView, SubjectBuffer), nextHandler); } public void SendPageDown(Action<PageDownKeyCommandArgs, Action> commandHandler, Action nextHandler) { commandHandler(new PageDownKeyCommandArgs(TextView, SubjectBuffer), nextHandler); } public void SendCut(Action<CutCommandArgs, Action> commandHandler, Action nextHandler) { commandHandler(new CutCommandArgs(TextView, SubjectBuffer), nextHandler); } public void SendPaste(Action<PasteCommandArgs, Action> commandHandler, Action nextHandler) { commandHandler(new PasteCommandArgs(TextView, SubjectBuffer), nextHandler); } public void SendInvokeCompletionList(Action<InvokeCompletionListCommandArgs, Action> commandHandler, Action nextHandler) { commandHandler(new InvokeCompletionListCommandArgs(TextView, SubjectBuffer), nextHandler); } public void SendCommitUniqueCompletionListItem(Action<CommitUniqueCompletionListItemCommandArgs, Action> commandHandler, Action nextHandler) { commandHandler(new CommitUniqueCompletionListItemCommandArgs(TextView, SubjectBuffer), nextHandler); } public void SendInsertSnippetCommand(Action<InsertSnippetCommandArgs, Action> commandHandler, Action nextHandler) { commandHandler(new InsertSnippetCommandArgs(TextView, SubjectBuffer), nextHandler); } public void SendSurroundWithCommand(Action<SurroundWithCommandArgs, Action> commandHandler, Action nextHandler) { commandHandler(new SurroundWithCommandArgs(TextView, SubjectBuffer), nextHandler); } public void SendInvokeSignatureHelp(Action<InvokeSignatureHelpCommandArgs, Action> commandHandler, Action nextHandler) { commandHandler(new InvokeSignatureHelpCommandArgs(TextView, SubjectBuffer), nextHandler); } public void SendTypeChar(char typeChar, Action<TypeCharCommandArgs, Action> commandHandler, Action nextHandler) { commandHandler(new TypeCharCommandArgs(TextView, SubjectBuffer, typeChar), nextHandler); } public void SendTypeChars(string typeChars, Action<TypeCharCommandArgs, Action> commandHandler) { foreach (var ch in typeChars) { var localCh = ch; SendTypeChar(ch, commandHandler, () => EditorOperations.InsertText(localCh.ToString())); } } public void SendSave(Action<SaveCommandArgs, Action> commandHandler, Action nextHandler) { commandHandler(new SaveCommandArgs(TextView, SubjectBuffer), nextHandler); } public void SendSelectAll(Action<SelectAllCommandArgs, Action> commandHandler, Action nextHandler) { commandHandler(new SelectAllCommandArgs(TextView, SubjectBuffer), nextHandler); } #endregion } }
#region --- License --- /* Copyright (c) 2006 - 2008 The Open Toolkit library. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion using System; using System.Runtime.InteropServices; using System.Xml.Serialization; #pragma warning disable 3021 namespace OpenTK { /// <summary>Represents a 4D vector using four single-precision floating-point numbers.</summary> /// <remarks> /// The Vector4 structure is suitable for interoperation with unmanaged code requiring four consecutive floats. /// </remarks> [Serializable] [StructLayout(LayoutKind.Sequential)] public struct Vector4 : IEquatable<Vector4> { #region Fields /// <summary> /// The X component of the Vector4. /// </summary> public float X; /// <summary> /// The Y component of the Vector4. /// </summary> public float Y; /// <summary> /// The Z component of the Vector4. /// </summary> public float Z; /// <summary> /// The W component of the Vector4. /// </summary> public float W; /// <summary> /// Defines a unit-length Vector4 that points towards the X-axis. /// </summary> public static Vector4 UnitX = new Vector4(1, 0, 0, 0); /// <summary> /// Defines a unit-length Vector4 that points towards the Y-axis. /// </summary> public static Vector4 UnitY = new Vector4(0, 1, 0, 0); /// <summary> /// Defines a unit-length Vector4 that points towards the Z-axis. /// </summary> public static Vector4 UnitZ = new Vector4(0, 0, 1, 0); /// <summary> /// Defines a unit-length Vector4 that points towards the W-axis. /// </summary> public static Vector4 UnitW = new Vector4(0, 0, 0, 1); /// <summary> /// Defines a zero-length Vector4. /// </summary> public static Vector4 Zero = new Vector4(0, 0, 0, 0); /// <summary> /// Defines an instance with all components set to 1. /// </summary> public static readonly Vector4 One = new Vector4(1, 1, 1, 1); /// <summary> /// Defines the size of the Vector4 struct in bytes. /// </summary> public static readonly int SizeInBytes = Marshal.SizeOf(new Vector4()); #endregion #region Constructors /// <summary> /// Constructs a new instance. /// </summary> /// <param name="value">The value that will initialize this instance.</param> public Vector4(float value) { X = value; Y = value; Z = value; W = value; } /// <summary> /// Constructs a new Vector4. /// </summary> /// <param name="x">The x component of the Vector4.</param> /// <param name="y">The y component of the Vector4.</param> /// <param name="z">The z component of the Vector4.</param> /// <param name="w">The w component of the Vector4.</param> public Vector4(float x, float y, float z, float w) { X = x; Y = y; Z = z; W = w; } /// <summary> /// Constructs a new Vector4 from the given Vector2. /// </summary> /// <param name="v">The Vector2 to copy components from.</param> public Vector4(Vector2 v) { X = v.X; Y = v.Y; Z = 0.0f; W = 0.0f; } /// <summary> /// Constructs a new Vector4 from the given Vector3. /// The w component is initialized to 0. /// </summary> /// <param name="v">The Vector3 to copy components from.</param> /// <remarks><seealso cref="Vector4(Vector3, float)"/></remarks> public Vector4(Vector3 v) { X = v.X; Y = v.Y; Z = v.Z; W = 0.0f; } /// <summary> /// Constructs a new Vector4 from the specified Vector3 and w component. /// </summary> /// <param name="v">The Vector3 to copy components from.</param> /// <param name="w">The w component of the new Vector4.</param> public Vector4(Vector3 v, float w) { X = v.X; Y = v.Y; Z = v.Z; W = w; } /// <summary> /// Constructs a new Vector4 from the given Vector4. /// </summary> /// <param name="v">The Vector4 to copy components from.</param> public Vector4(Vector4 v) { X = v.X; Y = v.Y; Z = v.Z; W = v.W; } #endregion #region Public Members #region Instance #region public void Add() /// <summary>Add the Vector passed as parameter to this instance.</summary> /// <param name="right">Right operand. This parameter is only read from.</param> [Obsolete("Use static Add() method instead.")] public void Add(Vector4 right) { this.X += right.X; this.Y += right.Y; this.Z += right.Z; this.W += right.W; } /// <summary>Add the Vector passed as parameter to this instance.</summary> /// <param name="right">Right operand. This parameter is only read from.</param> [CLSCompliant(false)] [Obsolete("Use static Add() method instead.")] public void Add(ref Vector4 right) { this.X += right.X; this.Y += right.Y; this.Z += right.Z; this.W += right.W; } #endregion public void Add() #region public void Sub() /// <summary>Subtract the Vector passed as parameter from this instance.</summary> /// <param name="right">Right operand. This parameter is only read from.</param> [Obsolete("Use static Subtract() method instead.")] public void Sub(Vector4 right) { this.X -= right.X; this.Y -= right.Y; this.Z -= right.Z; this.W -= right.W; } /// <summary>Subtract the Vector passed as parameter from this instance.</summary> /// <param name="right">Right operand. This parameter is only read from.</param> [CLSCompliant(false)] [Obsolete("Use static Subtract() method instead.")] public void Sub(ref Vector4 right) { this.X -= right.X; this.Y -= right.Y; this.Z -= right.Z; this.W -= right.W; } #endregion public void Sub() #region public void Mult() /// <summary>Multiply this instance by a scalar.</summary> /// <param name="f">Scalar operand.</param> [Obsolete("Use static Multiply() method instead.")] public void Mult(float f) { this.X *= f; this.Y *= f; this.Z *= f; this.W *= f; } #endregion public void Mult() #region public void Div() /// <summary>Divide this instance by a scalar.</summary> /// <param name="f">Scalar operand.</param> [Obsolete("Use static Divide() method instead.")] public void Div(float f) { float mult = 1.0f / f; this.X *= mult; this.Y *= mult; this.Z *= mult; this.W *= mult; } #endregion public void Div() #region public float Length /// <summary> /// Gets the length (magnitude) of the vector. /// </summary> /// <see cref="LengthFast"/> /// <seealso cref="LengthSquared"/> public float Length { get { return (float)System.Math.Sqrt(X * X + Y * Y + Z * Z + W * W); } } #endregion #region public float LengthFast /// <summary> /// Gets an approximation of the vector length (magnitude). /// </summary> /// <remarks> /// This property uses an approximation of the square root function to calculate vector magnitude, with /// an upper error bound of 0.001. /// </remarks> /// <see cref="Length"/> /// <seealso cref="LengthSquared"/> public float LengthFast { get { return 1.0f / MathHelper.InverseSqrtFast(X * X + Y * Y + Z * Z + W * W); } } #endregion #region public float LengthSquared /// <summary> /// Gets the square of the vector length (magnitude). /// </summary> /// <remarks> /// This property avoids the costly square root operation required by the Length property. This makes it more suitable /// for comparisons. /// </remarks> /// <see cref="Length"/> /// <seealso cref="LengthFast"/> public float LengthSquared { get { return X * X + Y * Y + Z * Z + W * W; } } #endregion #region public void Normalize() /// <summary> /// Scales the Vector4 to unit length. /// </summary> public void Normalize() { float scale = 1.0f / this.Length; X *= scale; Y *= scale; Z *= scale; W *= scale; } #endregion #region public void NormalizeFast() /// <summary> /// Scales the Vector4 to approximately unit length. /// </summary> public void NormalizeFast() { float scale = MathHelper.InverseSqrtFast(X * X + Y * Y + Z * Z + W * W); X *= scale; Y *= scale; Z *= scale; W *= scale; } #endregion #region public void Scale() /// <summary> /// Scales the current Vector4 by the given amounts. /// </summary> /// <param name="sx">The scale of the X component.</param> /// <param name="sy">The scale of the Y component.</param> /// <param name="sz">The scale of the Z component.</param> /// <param name="sw">The scale of the Z component.</param> [Obsolete("Use static Multiply() method instead.")] public void Scale(float sx, float sy, float sz, float sw) { this.X = X * sx; this.Y = Y * sy; this.Z = Z * sz; this.W = W * sw; } /// <summary>Scales this instance by the given parameter.</summary> /// <param name="scale">The scaling of the individual components.</param> [Obsolete("Use static Multiply() method instead.")] public void Scale(Vector4 scale) { this.X *= scale.X; this.Y *= scale.Y; this.Z *= scale.Z; this.W *= scale.W; } /// <summary>Scales this instance by the given parameter.</summary> /// <param name="scale">The scaling of the individual components.</param> [CLSCompliant(false)] [Obsolete("Use static Multiply() method instead.")] public void Scale(ref Vector4 scale) { this.X *= scale.X; this.Y *= scale.Y; this.Z *= scale.Z; this.W *= scale.W; } #endregion public void Scale() #endregion #region Static #region Obsolete #region Sub /// <summary> /// Subtract one Vector from another /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <returns>Result of subtraction</returns> public static Vector4 Sub(Vector4 a, Vector4 b) { a.X -= b.X; a.Y -= b.Y; a.Z -= b.Z; a.W -= b.W; return a; } /// <summary> /// Subtract one Vector from another /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">Result of subtraction</param> public static void Sub(ref Vector4 a, ref Vector4 b, out Vector4 result) { result.X = a.X - b.X; result.Y = a.Y - b.Y; result.Z = a.Z - b.Z; result.W = a.W - b.W; } #endregion #region Mult /// <summary> /// Multiply a vector and a scalar /// </summary> /// <param name="a">Vector operand</param> /// <param name="f">Scalar operand</param> /// <returns>Result of the multiplication</returns> public static Vector4 Mult(Vector4 a, float f) { a.X *= f; a.Y *= f; a.Z *= f; a.W *= f; return a; } /// <summary> /// Multiply a vector and a scalar /// </summary> /// <param name="a">Vector operand</param> /// <param name="f">Scalar operand</param> /// <param name="result">Result of the multiplication</param> public static void Mult(ref Vector4 a, float f, out Vector4 result) { result.X = a.X * f; result.Y = a.Y * f; result.Z = a.Z * f; result.W = a.W * f; } #endregion #region Div /// <summary> /// Divide a vector by a scalar /// </summary> /// <param name="a">Vector operand</param> /// <param name="f">Scalar operand</param> /// <returns>Result of the division</returns> public static Vector4 Div(Vector4 a, float f) { float mult = 1.0f / f; a.X *= mult; a.Y *= mult; a.Z *= mult; a.W *= mult; return a; } /// <summary> /// Divide a vector by a scalar /// </summary> /// <param name="a">Vector operand</param> /// <param name="f">Scalar operand</param> /// <param name="result">Result of the division</param> public static void Div(ref Vector4 a, float f, out Vector4 result) { float mult = 1.0f / f; result.X = a.X * mult; result.Y = a.Y * mult; result.Z = a.Z * mult; result.W = a.W * mult; } #endregion #endregion #region Add /// <summary> /// Adds two vectors. /// </summary> /// <param name="a">Left operand.</param> /// <param name="b">Right operand.</param> /// <returns>Result of operation.</returns> public static Vector4 Add(Vector4 a, Vector4 b) { Add(ref a, ref b, out a); return a; } /// <summary> /// Adds two vectors. /// </summary> /// <param name="a">Left operand.</param> /// <param name="b">Right operand.</param> /// <param name="result">Result of operation.</param> public static void Add(ref Vector4 a, ref Vector4 b, out Vector4 result) { result = new Vector4(a.X + b.X, a.Y + b.Y, a.Z + b.Z, a.W + b.W); } #endregion #region Subtract /// <summary> /// Subtract one Vector from another /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <returns>Result of subtraction</returns> public static Vector4 Subtract(Vector4 a, Vector4 b) { Subtract(ref a, ref b, out a); return a; } /// <summary> /// Subtract one Vector from another /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">Result of subtraction</param> public static void Subtract(ref Vector4 a, ref Vector4 b, out Vector4 result) { result = new Vector4(a.X - b.X, a.Y - b.Y, a.Z - b.Z, a.W - b.W); } #endregion #region Multiply /// <summary> /// Multiplies a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of the operation.</returns> public static Vector4 Multiply(Vector4 vector, float scale) { Multiply(ref vector, scale, out vector); return vector; } /// <summary> /// Multiplies a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Multiply(ref Vector4 vector, float scale, out Vector4 result) { result = new Vector4(vector.X * scale, vector.Y * scale, vector.Z * scale, vector.W * scale); } /// <summary> /// Multiplies a vector by the components a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of the operation.</returns> public static Vector4 Multiply(Vector4 vector, Vector4 scale) { Multiply(ref vector, ref scale, out vector); return vector; } /// <summary> /// Multiplies a vector by the components of a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Multiply(ref Vector4 vector, ref Vector4 scale, out Vector4 result) { result = new Vector4(vector.X * scale.X, vector.Y * scale.Y, vector.Z * scale.Z, vector.W * scale.W); } #endregion #region Divide /// <summary> /// Divides a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of the operation.</returns> public static Vector4 Divide(Vector4 vector, float scale) { Divide(ref vector, scale, out vector); return vector; } /// <summary> /// Divides a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Divide(ref Vector4 vector, float scale, out Vector4 result) { Multiply(ref vector, 1 / scale, out result); } /// <summary> /// Divides a vector by the components of a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of the operation.</returns> public static Vector4 Divide(Vector4 vector, Vector4 scale) { Divide(ref vector, ref scale, out vector); return vector; } /// <summary> /// Divide a vector by the components of a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Divide(ref Vector4 vector, ref Vector4 scale, out Vector4 result) { result = new Vector4(vector.X / scale.X, vector.Y / scale.Y, vector.Z / scale.Z, vector.W / scale.W); } #endregion #region Min /// <summary> /// Calculate the component-wise minimum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <returns>The component-wise minimum</returns> public static Vector4 Min(Vector4 a, Vector4 b) { a.X = a.X < b.X ? a.X : b.X; a.Y = a.Y < b.Y ? a.Y : b.Y; a.Z = a.Z < b.Z ? a.Z : b.Z; a.W = a.W < b.W ? a.W : b.W; return a; } /// <summary> /// Calculate the component-wise minimum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">The component-wise minimum</param> public static void Min(ref Vector4 a, ref Vector4 b, out Vector4 result) { result.X = a.X < b.X ? a.X : b.X; result.Y = a.Y < b.Y ? a.Y : b.Y; result.Z = a.Z < b.Z ? a.Z : b.Z; result.W = a.W < b.W ? a.W : b.W; } #endregion #region Max /// <summary> /// Calculate the component-wise maximum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <returns>The component-wise maximum</returns> public static Vector4 Max(Vector4 a, Vector4 b) { a.X = a.X > b.X ? a.X : b.X; a.Y = a.Y > b.Y ? a.Y : b.Y; a.Z = a.Z > b.Z ? a.Z : b.Z; a.W = a.W > b.W ? a.W : b.W; return a; } /// <summary> /// Calculate the component-wise maximum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">The component-wise maximum</param> public static void Max(ref Vector4 a, ref Vector4 b, out Vector4 result) { result.X = a.X > b.X ? a.X : b.X; result.Y = a.Y > b.Y ? a.Y : b.Y; result.Z = a.Z > b.Z ? a.Z : b.Z; result.W = a.W > b.W ? a.W : b.W; } #endregion #region Clamp /// <summary> /// Clamp a vector to the given minimum and maximum vectors /// </summary> /// <param name="vec">Input vector</param> /// <param name="min">Minimum vector</param> /// <param name="max">Maximum vector</param> /// <returns>The clamped vector</returns> public static Vector4 Clamp(Vector4 vec, Vector4 min, Vector4 max) { vec.X = vec.X < min.X ? min.X : vec.X > max.X ? max.X : vec.X; vec.Y = vec.Y < min.Y ? min.Y : vec.Y > max.Y ? max.Y : vec.Y; vec.Z = vec.X < min.Z ? min.Z : vec.Z > max.Z ? max.Z : vec.Z; vec.W = vec.Y < min.W ? min.W : vec.W > max.W ? max.W : vec.W; return vec; } /// <summary> /// Clamp a vector to the given minimum and maximum vectors /// </summary> /// <param name="vec">Input vector</param> /// <param name="min">Minimum vector</param> /// <param name="max">Maximum vector</param> /// <param name="result">The clamped vector</param> public static void Clamp(ref Vector4 vec, ref Vector4 min, ref Vector4 max, out Vector4 result) { result.X = vec.X < min.X ? min.X : vec.X > max.X ? max.X : vec.X; result.Y = vec.Y < min.Y ? min.Y : vec.Y > max.Y ? max.Y : vec.Y; result.Z = vec.X < min.Z ? min.Z : vec.Z > max.Z ? max.Z : vec.Z; result.W = vec.Y < min.W ? min.W : vec.W > max.W ? max.W : vec.W; } #endregion #region Normalize /// <summary> /// Scale a vector to unit length /// </summary> /// <param name="vec">The input vector</param> /// <returns>The normalized vector</returns> public static Vector4 Normalize(Vector4 vec) { float scale = 1.0f / vec.Length; vec.X *= scale; vec.Y *= scale; vec.Z *= scale; vec.W *= scale; return vec; } /// <summary> /// Scale a vector to unit length /// </summary> /// <param name="vec">The input vector</param> /// <param name="result">The normalized vector</param> public static void Normalize(ref Vector4 vec, out Vector4 result) { float scale = 1.0f / vec.Length; result.X = vec.X * scale; result.Y = vec.Y * scale; result.Z = vec.Z * scale; result.W = vec.W * scale; } #endregion #region NormalizeFast /// <summary> /// Scale a vector to approximately unit length /// </summary> /// <param name="vec">The input vector</param> /// <returns>The normalized vector</returns> public static Vector4 NormalizeFast(Vector4 vec) { float scale = MathHelper.InverseSqrtFast(vec.X * vec.X + vec.Y * vec.Y + vec.Z * vec.Z + vec.W * vec.W); vec.X *= scale; vec.Y *= scale; vec.Z *= scale; vec.W *= scale; return vec; } /// <summary> /// Scale a vector to approximately unit length /// </summary> /// <param name="vec">The input vector</param> /// <param name="result">The normalized vector</param> public static void NormalizeFast(ref Vector4 vec, out Vector4 result) { float scale = MathHelper.InverseSqrtFast(vec.X * vec.X + vec.Y * vec.Y + vec.Z * vec.Z + vec.W * vec.W); result.X = vec.X * scale; result.Y = vec.Y * scale; result.Z = vec.Z * scale; result.W = vec.W * scale; } #endregion #region Dot /// <summary> /// Calculate the dot product of two vectors /// </summary> /// <param name="left">First operand</param> /// <param name="right">Second operand</param> /// <returns>The dot product of the two inputs</returns> public static float Dot(Vector4 left, Vector4 right) { return left.X * right.X + left.Y * right.Y + left.Z * right.Z + left.W * right.W; } /// <summary> /// Calculate the dot product of two vectors /// </summary> /// <param name="left">First operand</param> /// <param name="right">Second operand</param> /// <param name="result">The dot product of the two inputs</param> public static void Dot(ref Vector4 left, ref Vector4 right, out float result) { result = left.X * right.X + left.Y * right.Y + left.Z * right.Z + left.W * right.W; } #endregion #region Lerp /// <summary> /// Returns a new Vector that is the linear blend of the 2 given Vectors /// </summary> /// <param name="a">First input vector</param> /// <param name="b">Second input vector</param> /// <param name="blend">The blend factor. a when blend=0, b when blend=1.</param> /// <returns>a when blend=0, b when blend=1, and a linear combination otherwise</returns> public static Vector4 Lerp(Vector4 a, Vector4 b, float blend) { a.X = blend * (b.X - a.X) + a.X; a.Y = blend * (b.Y - a.Y) + a.Y; a.Z = blend * (b.Z - a.Z) + a.Z; a.W = blend * (b.W - a.W) + a.W; return a; } /// <summary> /// Returns a new Vector that is the linear blend of the 2 given Vectors /// </summary> /// <param name="a">First input vector</param> /// <param name="b">Second input vector</param> /// <param name="blend">The blend factor. a when blend=0, b when blend=1.</param> /// <param name="result">a when blend=0, b when blend=1, and a linear combination otherwise</param> public static void Lerp(ref Vector4 a, ref Vector4 b, float blend, out Vector4 result) { result.X = blend * (b.X - a.X) + a.X; result.Y = blend * (b.Y - a.Y) + a.Y; result.Z = blend * (b.Z - a.Z) + a.Z; result.W = blend * (b.W - a.W) + a.W; } #endregion #region Barycentric /// <summary> /// Interpolate 3 Vectors using Barycentric coordinates /// </summary> /// <param name="a">First input Vector</param> /// <param name="b">Second input Vector</param> /// <param name="c">Third input Vector</param> /// <param name="u">First Barycentric Coordinate</param> /// <param name="v">Second Barycentric Coordinate</param> /// <returns>a when u=v=0, b when u=1,v=0, c when u=0,v=1, and a linear combination of a,b,c otherwise</returns> public static Vector4 BaryCentric(Vector4 a, Vector4 b, Vector4 c, float u, float v) { return a + u * (b - a) + v * (c - a); } /// <summary>Interpolate 3 Vectors using Barycentric coordinates</summary> /// <param name="a">First input Vector.</param> /// <param name="b">Second input Vector.</param> /// <param name="c">Third input Vector.</param> /// <param name="u">First Barycentric Coordinate.</param> /// <param name="v">Second Barycentric Coordinate.</param> /// <param name="result">Output Vector. a when u=v=0, b when u=1,v=0, c when u=0,v=1, and a linear combination of a,b,c otherwise</param> public static void BaryCentric(ref Vector4 a, ref Vector4 b, ref Vector4 c, float u, float v, out Vector4 result) { result = a; // copy Vector4 temp = b; // copy Subtract(ref temp, ref a, out temp); Multiply(ref temp, u, out temp); Add(ref result, ref temp, out result); temp = c; // copy Subtract(ref temp, ref a, out temp); Multiply(ref temp, v, out temp); Add(ref result, ref temp, out result); } #endregion #region Transform /// <summary>Transform a Vector by the given Matrix</summary> /// <param name="vec">The vector to transform</param> /// <param name="mat">The desired transformation</param> /// <returns>The transformed vector</returns> public static Vector4 Transform(Vector4 vec, Matrix4 mat) { Vector4 result; Transform(ref vec, ref mat, out result); return result; } /// <summary>Transform a Vector by the given Matrix</summary> /// <param name="vec">The vector to transform</param> /// <param name="mat">The desired transformation</param> /// <param name="result">The transformed vector</param> public static void Transform(ref Vector4 vec, ref Matrix4 mat, out Vector4 result) { result = new Vector4( vec.X * mat.Row0.X + vec.Y * mat.Row1.X + vec.Z * mat.Row2.X + vec.W * mat.Row3.X, vec.X * mat.Row0.Y + vec.Y * mat.Row1.Y + vec.Z * mat.Row2.Y + vec.W * mat.Row3.Y, vec.X * mat.Row0.Z + vec.Y * mat.Row1.Z + vec.Z * mat.Row2.Z + vec.W * mat.Row3.Z, vec.X * mat.Row0.W + vec.Y * mat.Row1.W + vec.Z * mat.Row2.W + vec.W * mat.Row3.W); } /// <summary> /// Transforms a vector by a quaternion rotation. /// </summary> /// <param name="vec">The vector to transform.</param> /// <param name="quat">The quaternion to rotate the vector by.</param> /// <returns>The result of the operation.</returns> public static Vector4 Transform(Vector4 vec, Quaternion quat) { Vector4 result; Transform(ref vec, ref quat, out result); return result; } /// <summary> /// Transforms a vector by a quaternion rotation. /// </summary> /// <param name="vec">The vector to transform.</param> /// <param name="quat">The quaternion to rotate the vector by.</param> /// <param name="result">The result of the operation.</param> public static void Transform(ref Vector4 vec, ref Quaternion quat, out Vector4 result) { Quaternion v = new Quaternion(vec.X, vec.Y, vec.Z, vec.W), i, t; Quaternion.Invert(ref quat, out i); Quaternion.Multiply(ref quat, ref v, out t); Quaternion.Multiply(ref t, ref i, out v); result = new Vector4(v.X, v.Y, v.Z, v.W); } #endregion #endregion #region Swizzle /// <summary> /// Gets or sets an OpenTK.Vector2 with the X and Y components of this instance. /// </summary> [XmlIgnore] public Vector2 Xy { get { return new Vector2(X, Y); } set { X = value.X; Y = value.Y; } } /// <summary> /// Gets or sets an OpenTK.Vector3 with the X, Y and Z components of this instance. /// </summary> [XmlIgnore] public Vector3 Xyz { get { return new Vector3(X, Y, Z); } set { X = value.X; Y = value.Y; Z = value.Z; } } #endregion #region Operators /// <summary> /// Adds two instances. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>The result of the calculation.</returns> public static Vector4 operator +(Vector4 left, Vector4 right) { left.X += right.X; left.Y += right.Y; left.Z += right.Z; left.W += right.W; return left; } /// <summary> /// Subtracts two instances. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>The result of the calculation.</returns> public static Vector4 operator -(Vector4 left, Vector4 right) { left.X -= right.X; left.Y -= right.Y; left.Z -= right.Z; left.W -= right.W; return left; } /// <summary> /// Negates an instance. /// </summary> /// <param name="vec">The instance.</param> /// <returns>The result of the calculation.</returns> public static Vector4 operator -(Vector4 vec) { vec.X = -vec.X; vec.Y = -vec.Y; vec.Z = -vec.Z; vec.W = -vec.W; return vec; } /// <summary> /// Multiplies an instance by a scalar. /// </summary> /// <param name="vec">The instance.</param> /// <param name="scale">The scalar.</param> /// <returns>The result of the calculation.</returns> public static Vector4 operator *(Vector4 vec, float scale) { vec.X *= scale; vec.Y *= scale; vec.Z *= scale; vec.W *= scale; return vec; } /// <summary> /// Multiplies an instance by a scalar. /// </summary> /// <param name="scale">The scalar.</param> /// <param name="vec">The instance.</param> /// <returns>The result of the calculation.</returns> public static Vector4 operator *(float scale, Vector4 vec) { vec.X *= scale; vec.Y *= scale; vec.Z *= scale; vec.W *= scale; return vec; } /// <summary> /// Divides an instance by a scalar. /// </summary> /// <param name="vec">The instance.</param> /// <param name="scale">The scalar.</param> /// <returns>The result of the calculation.</returns> public static Vector4 operator /(Vector4 vec, float scale) { float mult = 1.0f / scale; vec.X *= mult; vec.Y *= mult; vec.Z *= mult; vec.W *= mult; return vec; } /// <summary> /// Compares two instances for equality. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>True, if left equals right; false otherwise.</returns> public static bool operator ==(Vector4 left, Vector4 right) { return left.Equals(right); } /// <summary> /// Compares two instances for inequality. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>True, if left does not equa lright; false otherwise.</returns> public static bool operator !=(Vector4 left, Vector4 right) { return !left.Equals(right); } /// <summary> /// Returns a pointer to the first element of the specified instance. /// </summary> /// <param name="v">The instance.</param> /// <returns>A pointer to the first element of v.</returns> [CLSCompliant(false)] unsafe public static explicit operator float*(Vector4 v) { return &v.X; } /// <summary> /// Returns a pointer to the first element of the specified instance. /// </summary> /// <param name="v">The instance.</param> /// <returns>A pointer to the first element of v.</returns> public static explicit operator IntPtr(Vector4 v) { unsafe { return (IntPtr)(&v.X); } } #endregion #region Overrides #region public override string ToString() /// <summary> /// Returns a System.String that represents the current Vector4. /// </summary> /// <returns></returns> public override string ToString() { return String.Format("({0}, {1}, {2}, {3})", X, Y, Z, W); } #endregion #region public override int GetHashCode() /// <summary> /// Returns the hashcode for this instance. /// </summary> /// <returns>A System.Int32 containing the unique hashcode for this instance.</returns> public override int GetHashCode() { return X.GetHashCode() ^ Y.GetHashCode() ^ Z.GetHashCode() ^ W.GetHashCode(); } #endregion #region public override bool Equals(object obj) /// <summary> /// Indicates whether this instance and a specified object are equal. /// </summary> /// <param name="obj">The object to compare to.</param> /// <returns>True if the instances are equal; false otherwise.</returns> public override bool Equals(object obj) { if (!(obj is Vector4)) return false; return this.Equals((Vector4)obj); } #endregion #endregion #endregion #region IEquatable<Vector4> Members /// <summary>Indicates whether the current vector is equal to another vector.</summary> /// <param name="other">A vector to compare with this vector.</param> /// <returns>true if the current vector is equal to the vector parameter; otherwise, false.</returns> public bool Equals(Vector4 other) { return X == other.X && Y == other.Y && Z == other.Z && W == other.W; } #endregion } }
using System; using System.Collections.Generic; namespace Lucene.Net.Search { using Lucene.Net.Randomized.Generators; using Lucene.Net.Support; using NUnit.Framework; using BytesRef = Lucene.Net.Util.BytesRef; /* * 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 IndexReader = Lucene.Net.Index.IndexReader; using IndexReaderContext = Lucene.Net.Index.IndexReaderContext; using MultiFields = Lucene.Net.Index.MultiFields; using MultiReader = Lucene.Net.Index.MultiReader; using Term = Lucene.Net.Index.Term; using TermsEnum = Lucene.Net.Index.TermsEnum; using TestUtil = Lucene.Net.Util.TestUtil; // TODO // - other queries besides PrefixQuery & TermQuery (but: // FuzzyQ will be problematic... the top N terms it // takes means results will differ) // - NRQ/F // - BQ, negated clauses, negated prefix clauses // - test pulling docs in 2nd round trip... // - filter too [TestFixture] public class TestShardSearching : ShardSearchingTestBase { private class PreviousSearchState { public readonly long SearchTimeNanos; public readonly long[] Versions; public readonly ScoreDoc SearchAfterLocal; public readonly ScoreDoc SearchAfterShard; public readonly Sort Sort; public readonly Query Query; public readonly int NumHitsPaged; public PreviousSearchState(Query query, Sort sort, ScoreDoc searchAfterLocal, ScoreDoc searchAfterShard, long[] versions, int numHitsPaged) { this.Versions = (long[])versions.Clone(); this.SearchAfterLocal = searchAfterLocal; this.SearchAfterShard = searchAfterShard; this.Sort = sort; this.Query = query; this.NumHitsPaged = numHitsPaged; SearchTimeNanos = TimeHelper.NanoTime(); } } [Test] public virtual void TestSimple() { int numNodes = TestUtil.NextInt(Random(), 1, 10); double runTimeSec = AtLeast(3); int minDocsToMakeTerms = TestUtil.NextInt(Random(), 5, 20); int maxSearcherAgeSeconds = TestUtil.NextInt(Random(), 1, 3); if (VERBOSE) { Console.WriteLine("TEST: numNodes=" + numNodes + " runTimeSec=" + runTimeSec + " maxSearcherAgeSeconds=" + maxSearcherAgeSeconds); } Start(numNodes, runTimeSec, maxSearcherAgeSeconds); List<PreviousSearchState> priorSearches = new List<PreviousSearchState>(); List<BytesRef> terms = null; while (DateTime.UtcNow < EndTime) { bool doFollowon = priorSearches.Count > 0 && Random().Next(7) == 1; // Pick a random node; we will run the query on this node: int myNodeID = Random().Next(numNodes); NodeState.ShardIndexSearcher localShardSearcher; PreviousSearchState prevSearchState; if (doFollowon) { // Pretend user issued a followon query: prevSearchState = priorSearches[Random().Next(priorSearches.Count)]; if (VERBOSE) { Console.WriteLine("\nTEST: follow-on query age=" + ((TimeHelper.NanoTime() - prevSearchState.SearchTimeNanos) / 1000000000.0)); } try { localShardSearcher = Nodes[myNodeID].Acquire(prevSearchState.Versions); } catch (SearcherExpiredException see) { // Expected, sometimes; in a "real" app we would // either forward this error to the user ("too // much time has passed; please re-run your // search") or sneakily just switch to newest // searcher w/o telling them... if (VERBOSE) { Console.WriteLine(" searcher expired during local shard searcher init: " + see); } priorSearches.Remove(prevSearchState); continue; } } else { if (VERBOSE) { Console.WriteLine("\nTEST: fresh query"); } // Do fresh query: localShardSearcher = Nodes[myNodeID].Acquire(); prevSearchState = null; } IndexReader[] subs = new IndexReader[numNodes]; PreviousSearchState searchState = null; try { // Mock: now make a single reader (MultiReader) from all node // searchers. In a real shard env you can't do this... we // do it to confirm results from the shard searcher // are correct: int docCount = 0; try { for (int nodeID = 0; nodeID < numNodes; nodeID++) { long subVersion = localShardSearcher.NodeVersions[nodeID]; IndexSearcher sub = Nodes[nodeID].Searchers.Acquire(subVersion); if (sub == null) { nodeID--; while (nodeID >= 0) { subs[nodeID].DecRef(); subs[nodeID] = null; nodeID--; } throw new SearcherExpiredException("nodeID=" + nodeID + " version=" + subVersion); } subs[nodeID] = sub.IndexReader; docCount += subs[nodeID].MaxDoc; } } catch (SearcherExpiredException see) { // Expected if (VERBOSE) { Console.WriteLine(" searcher expired during mock reader init: " + see); } continue; } IndexReader mockReader = new MultiReader(subs); IndexSearcher mockSearcher = new IndexSearcher(mockReader); Query query; Sort sort; if (prevSearchState != null) { query = prevSearchState.Query; sort = prevSearchState.Sort; } else { if (terms == null && docCount > minDocsToMakeTerms) { // TODO: try to "focus" on high freq terms sometimes too // TODO: maybe also periodically reset the terms...? TermsEnum termsEnum = MultiFields.GetTerms(mockReader, "body").Iterator(null); terms = new List<BytesRef>(); while (termsEnum.Next() != null) { terms.Add(BytesRef.DeepCopyOf(termsEnum.Term())); } if (VERBOSE) { Console.WriteLine("TEST: init terms: " + terms.Count + " terms"); } if (terms.Count == 0) { terms = null; } } if (VERBOSE) { Console.WriteLine(" maxDoc=" + mockReader.MaxDoc); } if (terms != null) { if (Random().NextBoolean()) { query = new TermQuery(new Term("body", terms[Random().Next(terms.Count)])); } else { string t = terms[Random().Next(terms.Count)].Utf8ToString(); string prefix; if (t.Length <= 1) { prefix = t; } else { prefix = t.Substring(0, TestUtil.NextInt(Random(), 1, 2)); } query = new PrefixQuery(new Term("body", prefix)); } if (Random().NextBoolean()) { sort = null; } else { // TODO: sort by more than 1 field int what = Random().Next(3); if (what == 0) { sort = new Sort(SortField.FIELD_SCORE); } else if (what == 1) { // TODO: this sort doesn't merge // correctly... it's tricky because you // could have > 2.1B docs across all shards: //sort = new Sort(SortField.FIELD_DOC); sort = null; } else if (what == 2) { sort = new Sort(new SortField[] { new SortField("docid", SortField.Type_e.INT, Random().NextBoolean()) }); } else { sort = new Sort(new SortField[] { new SortField("title", SortField.Type_e.STRING, Random().NextBoolean()) }); } } } else { query = null; sort = null; } } if (query != null) { try { searchState = AssertSame(mockSearcher, localShardSearcher, query, sort, prevSearchState); } catch (SearcherExpiredException see) { // Expected; in a "real" app we would // either forward this error to the user ("too // much time has passed; please re-run your // search") or sneakily just switch to newest // searcher w/o telling them... if (VERBOSE) { Console.WriteLine(" searcher expired during search: " + see); Console.Out.Write(see.StackTrace); } // We can't do this in general: on a very slow // computer it's possible the local searcher // expires before we can finish our search: // assert prevSearchState != null; if (prevSearchState != null) { priorSearches.Remove(prevSearchState); } } } } finally { Nodes[myNodeID].Release(localShardSearcher); foreach (IndexReader sub in subs) { if (sub != null) { sub.DecRef(); } } } if (searchState != null && searchState.SearchAfterLocal != null && Random().Next(5) == 3) { priorSearches.Add(searchState); if (priorSearches.Count > 200) { priorSearches = (List<PreviousSearchState>)CollectionsHelper.Shuffle(priorSearches); priorSearches.SubList(100, priorSearches.Count).Clear(); } } } Finish(); } private PreviousSearchState AssertSame(IndexSearcher mockSearcher, NodeState.ShardIndexSearcher shardSearcher, Query q, Sort sort, PreviousSearchState state) { int numHits = TestUtil.NextInt(Random(), 1, 100); if (state != null && state.SearchAfterLocal == null) { // In addition to what we last searched: numHits += state.NumHitsPaged; } if (VERBOSE) { Console.WriteLine("TEST: query=" + q + " sort=" + sort + " numHits=" + numHits); if (state != null) { Console.WriteLine(" prev: searchAfterLocal=" + state.SearchAfterLocal + " searchAfterShard=" + state.SearchAfterShard + " numHitsPaged=" + state.NumHitsPaged); } } // Single (mock local) searcher: TopDocs hits; if (sort == null) { if (state != null && state.SearchAfterLocal != null) { hits = mockSearcher.SearchAfter(state.SearchAfterLocal, q, numHits); } else { hits = mockSearcher.Search(q, numHits); } } else { hits = mockSearcher.Search(q, numHits, sort); } // Shard searcher TopDocs shardHits; if (sort == null) { if (state != null && state.SearchAfterShard != null) { shardHits = shardSearcher.SearchAfter(state.SearchAfterShard, q, numHits); } else { shardHits = shardSearcher.Search(q, numHits); } } else { shardHits = shardSearcher.Search(q, numHits, sort); } int numNodes = shardSearcher.NodeVersions.Length; int[] @base = new int[numNodes]; IList<IndexReaderContext> subs = mockSearcher.TopReaderContext.Children; Assert.AreEqual(numNodes, subs.Count); for (int nodeID = 0; nodeID < numNodes; nodeID++) { @base[nodeID] = subs[nodeID].DocBaseInParent; } if (VERBOSE) { /* for(int shardID=0;shardID<shardSearchers.Length;shardID++) { System.out.println(" shard=" + shardID + " maxDoc=" + shardSearchers[shardID].searcher.getIndexReader().MaxDoc); } */ Console.WriteLine(" single searcher: " + hits.TotalHits + " totalHits maxScore=" + hits.MaxScore); for (int i = 0; i < hits.ScoreDocs.Length; i++) { ScoreDoc sd = hits.ScoreDocs[i]; Console.WriteLine(" doc=" + sd.Doc + " score=" + sd.Score); } Console.WriteLine(" shard searcher: " + shardHits.TotalHits + " totalHits maxScore=" + shardHits.MaxScore); for (int i = 0; i < shardHits.ScoreDocs.Length; i++) { ScoreDoc sd = shardHits.ScoreDocs[i]; Console.WriteLine(" doc=" + sd.Doc + " (rebased: " + (sd.Doc + @base[sd.ShardIndex]) + ") score=" + sd.Score + " shard=" + sd.ShardIndex); } } int numHitsPaged; if (state != null && state.SearchAfterLocal != null) { numHitsPaged = hits.ScoreDocs.Length; if (state != null) { numHitsPaged += state.NumHitsPaged; } } else { numHitsPaged = hits.ScoreDocs.Length; } bool moreHits; ScoreDoc bottomHit; ScoreDoc bottomHitShards; if (numHitsPaged < hits.TotalHits) { // More hits to page through moreHits = true; if (sort == null) { bottomHit = hits.ScoreDocs[hits.ScoreDocs.Length - 1]; ScoreDoc sd = shardHits.ScoreDocs[shardHits.ScoreDocs.Length - 1]; // Must copy because below we rebase: bottomHitShards = new ScoreDoc(sd.Doc, sd.Score, sd.ShardIndex); if (VERBOSE) { Console.WriteLine(" save bottomHit=" + bottomHit); } } else { bottomHit = null; bottomHitShards = null; } } else { Assert.AreEqual(hits.TotalHits, numHitsPaged); bottomHit = null; bottomHitShards = null; moreHits = false; } // Must rebase so Assert.AreEqual passes: for (int hitID = 0; hitID < shardHits.ScoreDocs.Length; hitID++) { ScoreDoc sd = shardHits.ScoreDocs[hitID]; sd.Doc += @base[sd.ShardIndex]; } TestUtil.AssertEquals(hits, shardHits); if (moreHits) { // Return a continuation: return new PreviousSearchState(q, sort, bottomHit, bottomHitShards, shardSearcher.NodeVersions, numHitsPaged); } else { return null; } } } }
namespace Microsoft.PythonTools.Project { partial class PythonGeneralPropertyPageControl { /// <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() { this._applicationGroup = new System.Windows.Forms.GroupBox(); this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel(); this._startupFileLabel = new System.Windows.Forms.Label(); this._startupFile = new System.Windows.Forms.TextBox(); this._workingDirLabel = new System.Windows.Forms.Label(); this._workingDirectory = new System.Windows.Forms.TextBox(); this._windowsApplication = new System.Windows.Forms.CheckBox(); this._defaultInterpreterLabel = new System.Windows.Forms.Label(); this._defaultInterpreter = new System.Windows.Forms.ComboBox(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this._applicationGroup.SuspendLayout(); this.tableLayoutPanel2.SuspendLayout(); this.tableLayoutPanel1.SuspendLayout(); this.SuspendLayout(); // // _applicationGroup // this._applicationGroup.AutoSize = true; this._applicationGroup.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this._applicationGroup.Controls.Add(this.tableLayoutPanel2); this._applicationGroup.Dock = System.Windows.Forms.DockStyle.Fill; this._applicationGroup.Location = new System.Drawing.Point(6, 8); this._applicationGroup.Margin = new System.Windows.Forms.Padding(6, 8, 6, 8); this._applicationGroup.Name = "_applicationGroup"; this._applicationGroup.Padding = new System.Windows.Forms.Padding(6, 8, 6, 8); this._applicationGroup.Size = new System.Drawing.Size(447, 137); this._applicationGroup.TabIndex = 0; this._applicationGroup.TabStop = false; this._applicationGroup.Text = "Application"; // // tableLayoutPanel2 // this.tableLayoutPanel2.AutoSize = true; this.tableLayoutPanel2.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.tableLayoutPanel2.ColumnCount = 2; this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel2.Controls.Add(this._startupFileLabel, 0, 0); this.tableLayoutPanel2.Controls.Add(this._startupFile, 1, 0); this.tableLayoutPanel2.Controls.Add(this._workingDirLabel, 0, 1); this.tableLayoutPanel2.Controls.Add(this._workingDirectory, 1, 1); this.tableLayoutPanel2.Controls.Add(this._windowsApplication, 0, 2); this.tableLayoutPanel2.Controls.Add(this._defaultInterpreterLabel, 0, 3); this.tableLayoutPanel2.Controls.Add(this._defaultInterpreter, 1, 3); this.tableLayoutPanel2.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel2.Location = new System.Drawing.Point(6, 23); this.tableLayoutPanel2.Name = "tableLayoutPanel2"; this.tableLayoutPanel2.RowCount = 4; this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel2.Size = new System.Drawing.Size(435, 106); this.tableLayoutPanel2.TabIndex = 0; // // _startupFileLabel // this._startupFileLabel.Anchor = System.Windows.Forms.AnchorStyles.Left; this._startupFileLabel.AutoEllipsis = true; this._startupFileLabel.AutoSize = true; this._startupFileLabel.Location = new System.Drawing.Point(6, 7); this._startupFileLabel.Margin = new System.Windows.Forms.Padding(6, 0, 6, 0); this._startupFileLabel.Name = "_startupFileLabel"; this._startupFileLabel.Size = new System.Drawing.Size(66, 13); this._startupFileLabel.TabIndex = 0; this._startupFileLabel.Text = "Startup File"; this._startupFileLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // _startupFile // this._startupFile.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); this._startupFile.Location = new System.Drawing.Point(119, 3); this._startupFile.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3); this._startupFile.MinimumSize = new System.Drawing.Size(50, 4); this._startupFile.Name = "_startupFile"; this._startupFile.Size = new System.Drawing.Size(310, 22); this._startupFile.TabIndex = 1; this._startupFile.TextChanged += new System.EventHandler(this.Changed); // // _workingDirLabel // this._workingDirLabel.Anchor = System.Windows.Forms.AnchorStyles.Left; this._workingDirLabel.AutoEllipsis = true; this._workingDirLabel.AutoSize = true; this._workingDirLabel.Location = new System.Drawing.Point(6, 35); this._workingDirLabel.Margin = new System.Windows.Forms.Padding(6, 0, 6, 0); this._workingDirLabel.Name = "_workingDirLabel"; this._workingDirLabel.Size = new System.Drawing.Size(101, 13); this._workingDirLabel.TabIndex = 2; this._workingDirLabel.Text = "Working Directory"; this._workingDirLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // _workingDirectory // this._workingDirectory.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); this._workingDirectory.Location = new System.Drawing.Point(119, 31); this._workingDirectory.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3); this._workingDirectory.MinimumSize = new System.Drawing.Size(50, 4); this._workingDirectory.Name = "_workingDirectory"; this._workingDirectory.Size = new System.Drawing.Size(310, 22); this._workingDirectory.TabIndex = 3; this._workingDirectory.TextChanged += new System.EventHandler(this.Changed); // // _windowsApplication // this._windowsApplication.Anchor = System.Windows.Forms.AnchorStyles.Left; this._windowsApplication.AutoSize = true; this.tableLayoutPanel2.SetColumnSpan(this._windowsApplication, 2); this._windowsApplication.Location = new System.Drawing.Point(6, 59); this._windowsApplication.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3); this._windowsApplication.Name = "_windowsApplication"; this._windowsApplication.Size = new System.Drawing.Size(137, 17); this._windowsApplication.TabIndex = 4; this._windowsApplication.Text = "Windows Application"; this._windowsApplication.UseVisualStyleBackColor = true; this._windowsApplication.CheckedChanged += new System.EventHandler(this.Changed); // // _defaultInterpreterLabel // this._defaultInterpreterLabel.Anchor = System.Windows.Forms.AnchorStyles.Left; this._defaultInterpreterLabel.AutoEllipsis = true; this._defaultInterpreterLabel.AutoSize = true; this._defaultInterpreterLabel.Location = new System.Drawing.Point(6, 86); this._defaultInterpreterLabel.Margin = new System.Windows.Forms.Padding(6, 0, 6, 0); this._defaultInterpreterLabel.Name = "_defaultInterpreterLabel"; this._defaultInterpreterLabel.Size = new System.Drawing.Size(65, 13); this._defaultInterpreterLabel.TabIndex = 5; this._defaultInterpreterLabel.Text = "Interpreter:"; this._defaultInterpreterLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // _defaultInterpreter // this._defaultInterpreter.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); this._defaultInterpreter.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this._defaultInterpreter.FormattingEnabled = true; this._defaultInterpreter.Location = new System.Drawing.Point(119, 82); this._defaultInterpreter.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3); this._defaultInterpreter.MinimumSize = new System.Drawing.Size(50, 0); this._defaultInterpreter.Name = "_defaultInterpreter"; this._defaultInterpreter.Size = new System.Drawing.Size(310, 21); this._defaultInterpreter.TabIndex = 6; this._defaultInterpreter.SelectedIndexChanged += new System.EventHandler(this.Changed); this._defaultInterpreter.Format += new System.Windows.Forms.ListControlConvertEventHandler(this.Interpreter_Format); // // tableLayoutPanel1 // this.tableLayoutPanel1.AutoSize = true; this.tableLayoutPanel1.ColumnCount = 1; this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel1.Controls.Add(this._applicationGroup, 0, 0); this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 0); this.tableLayoutPanel1.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; this.tableLayoutPanel1.RowCount = 2; this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel1.Size = new System.Drawing.Size(459, 153); this.tableLayoutPanel1.TabIndex = 0; // // PythonGeneralPropertyPageControl // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoSize = true; this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.Controls.Add(this.tableLayoutPanel1); this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Margin = new System.Windows.Forms.Padding(6, 8, 6, 8); this.Name = "PythonGeneralPropertyPageControl"; this.Size = new System.Drawing.Size(459, 153); this._applicationGroup.ResumeLayout(false); this._applicationGroup.PerformLayout(); this.tableLayoutPanel2.ResumeLayout(false); this.tableLayoutPanel2.PerformLayout(); this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.GroupBox _applicationGroup; private System.Windows.Forms.Label _startupFileLabel; private System.Windows.Forms.TextBox _startupFile; private System.Windows.Forms.CheckBox _windowsApplication; private System.Windows.Forms.TextBox _workingDirectory; private System.Windows.Forms.Label _workingDirLabel; private System.Windows.Forms.Label _defaultInterpreterLabel; private System.Windows.Forms.ComboBox _defaultInterpreter; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; } }
/* * Authors: Benton Stark * * Copyright (c) 2007-2009 Starksoft, LLC (http://www.starksoft.com) * * 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.Text; using System.Net.Sockets; using System.Threading; using System.Globalization; using System.ComponentModel; namespace Starksoft.Net.Proxy { /// <summary> /// HTTP connection proxy class. This class implements the HTTP standard proxy protocol. /// <para> /// You can use this class to set up a connection to an HTTP proxy server. Calling the /// CreateConnection() method initiates the proxy connection and returns a standard /// System.Net.Socks.TcpClient object that can be used as normal. The proxy plumbing /// is all handled for you. /// </para> /// <code> /// /// </code> /// </summary> public class HttpProxyClient : IProxyClient { private string _proxyHost; private int _proxyPort; private HttpResponseCodes _respCode; private string _respText; private TcpClient _tcpClient; private const int HTTP_PROXY_DEFAULT_PORT = 8080; private const string HTTP_PROXY_CONNECT_CMD = "CONNECT {0}:{1} HTTP/1.0\r\nHost: {0}:{1}\r\n\r\n"; private const int WAIT_FOR_DATA_INTERVAL = 50; // 50 ms private const int WAIT_FOR_DATA_TIMEOUT = 15000; // 15 seconds private const string PROXY_NAME = "HTTP"; private enum HttpResponseCodes { None = 0, Continue = 100, SwitchingProtocols = 101, OK = 200, Created = 201, Accepted = 202, NonAuthoritiveInformation = 203, NoContent = 204, ResetContent = 205, PartialContent = 206, MultipleChoices = 300, MovedPermanetly = 301, Found = 302, SeeOther = 303, NotModified = 304, UserProxy = 305, TemporaryRedirect = 307, BadRequest = 400, Unauthorized = 401, PaymentRequired = 402, Forbidden = 403, NotFound = 404, MethodNotAllowed = 405, NotAcceptable = 406, ProxyAuthenticantionRequired = 407, RequestTimeout = 408, Conflict = 409, Gone = 410, PreconditionFailed = 411, RequestEntityTooLarge = 413, RequestURITooLong = 414, UnsupportedMediaType = 415, RequestedRangeNotSatisfied = 416, ExpectationFailed = 417, InternalServerError = 500, NotImplemented = 501, BadGateway = 502, ServiceUnavailable = 503, GatewayTimeout = 504, HTTPVersionNotSupported = 505 } /// <summary> /// Constructor. /// </summary> public HttpProxyClient() { } /// <summary> /// Creates a HTTP proxy client object using the supplied TcpClient object connection. /// </summary> /// <param name="tcpClient">A TcpClient connection object.</param> public HttpProxyClient(TcpClient tcpClient) { if (tcpClient == null) throw new ArgumentNullException("tcpClient"); _tcpClient = tcpClient; } /// <summary> /// Constructor. The default HTTP proxy port 8080 is used. /// </summary> /// <param name="proxyHost">Host name or IP address of the proxy.</param> public HttpProxyClient(string proxyHost) { if (String.IsNullOrEmpty(proxyHost)) throw new ArgumentNullException("proxyHost"); _proxyHost = proxyHost; _proxyPort = HTTP_PROXY_DEFAULT_PORT; } /// <summary> /// Constructor. /// </summary> /// <param name="proxyHost">Host name or IP address of the proxy server.</param> /// <param name="proxyPort">Port number for the proxy server.</param> public HttpProxyClient(string proxyHost, int proxyPort) { if (String.IsNullOrEmpty(proxyHost)) throw new ArgumentNullException("proxyHost"); if (proxyPort <= 0 || proxyPort > 65535) throw new ArgumentOutOfRangeException("proxyPort", "port must be greater than zero and less than 65535"); _proxyHost = proxyHost; _proxyPort = proxyPort; } /// <summary> /// Gets or sets host name or IP address of the proxy server. /// </summary> public string ProxyHost { get { return _proxyHost; } set { _proxyHost = value; } } /// <summary> /// Gets or sets port number for the proxy server. /// </summary> public int ProxyPort { get { return _proxyPort; } set { _proxyPort = value; } } /// <summary> /// Gets String representing the name of the proxy. /// </summary> /// <remarks>This property will always return the value 'HTTP'</remarks> public string ProxyName { get { return PROXY_NAME; } } /// <summary> /// Gets or sets the TcpClient object. /// This property can be set prior to executing CreateConnection to use an existing TcpClient connection. /// </summary> public TcpClient TcpClient { get { return _tcpClient; } set { _tcpClient = value; } } /// <summary> /// Creates a remote TCP connection through a proxy server to the destination host on the destination port. /// </summary> /// <param name="destinationHost">Destination host name or IP address.</param> /// <param name="destinationPort">Port number to connect to on the destination host.</param> /// <returns> /// Returns an open TcpClient object that can be used normally to communicate /// with the destination server /// </returns> /// <remarks> /// This method creates a connection to the proxy server and instructs the proxy server /// to make a pass through connection to the specified destination host on the specified /// port. /// </remarks> public TcpClient CreateConnection(string destinationHost, int destinationPort) { try { // if we have no connection, create one if (_tcpClient == null) { if (String.IsNullOrEmpty(_proxyHost)) throw new ProxyException("ProxyHost property must contain a value."); if (_proxyPort <= 0 || _proxyPort > 65535) throw new ProxyException("ProxyPort value must be greater than zero and less than 65535"); // create new tcp client object to the proxy server _tcpClient = new TcpClient(); // attempt to open the connection _tcpClient.Connect(_proxyHost, _proxyPort); } // send connection command to proxy host for the specified destination host and port SendConnectionCommand(destinationHost, destinationPort); // return the open proxied tcp client object to the caller for normal use return _tcpClient; } catch (SocketException ex) { throw new ProxyException(String.Format(CultureInfo.InvariantCulture, "Connection to proxy host {0} on port {1} failed.", Utils.GetHost(_tcpClient), Utils.GetPort(_tcpClient)), ex); } } private void SendConnectionCommand(string host, int port) { NetworkStream stream = _tcpClient.GetStream(); // PROXY SERVER REQUEST // ======================================================================= //CONNECT starksoft.com:443 HTTP/1.0 <CR><LF> //HOST starksoft.com:443<CR><LF> //[... other HTTP header lines ending with <CR><LF> if required]> //<CR><LF> // Last Empty Line string connectCmd = String.Format(CultureInfo.InvariantCulture, HTTP_PROXY_CONNECT_CMD, host, port.ToString(CultureInfo.InvariantCulture)); byte[] request = ASCIIEncoding.ASCII.GetBytes(connectCmd); // send the connect request stream.Write(request, 0, request.Length); // wait for the proxy server to respond WaitForData(stream); // PROXY SERVER RESPONSE // ======================================================================= //HTTP/1.0 200 Connection Established<CR><LF> //[.... other HTTP header lines ending with <CR><LF>.. //ignore all of them] //<CR><LF> // Last Empty Line // create an byte response array byte[] response = new byte[_tcpClient.ReceiveBufferSize]; StringBuilder sbuilder = new StringBuilder(); int bytes = 0; long total = 0; do { bytes = stream.Read(response, 0, _tcpClient.ReceiveBufferSize); total += bytes; sbuilder.Append(System.Text.ASCIIEncoding.UTF8.GetString(response, 0, bytes)); } while (stream.DataAvailable); ParseResponse(sbuilder.ToString()); // evaluate the reply code for an error condition if (_respCode != HttpResponseCodes.OK) HandleProxyCommandError(host, port); } private void HandleProxyCommandError(string host, int port) { string msg; switch (_respCode) { case HttpResponseCodes.None: msg = String.Format(CultureInfo.InvariantCulture, "Proxy destination {0} on port {1} failed to return a recognized HTTP response code. Server response: {2}", Utils.GetHost(_tcpClient), Utils.GetPort(_tcpClient), _respText); break; case HttpResponseCodes.BadGateway: //HTTP/1.1 502 Proxy Error (The specified Secure Sockets Layer (SSL) port is not allowed. ISA Server is not configured to allow SSL requests from this port. Most Web browsers use port 443 for SSL requests.) msg = String.Format(CultureInfo.InvariantCulture, "Proxy destination {0} on port {1} responded with a 502 code - Bad Gateway. If you are connecting to a Microsoft ISA destination please refer to knowledge based article Q283284 for more information. Server response: {2}", Utils.GetHost(_tcpClient), Utils.GetPort(_tcpClient), _respText); break; default: msg = String.Format(CultureInfo.InvariantCulture, "Proxy destination {0} on port {1} responded with a {2} code - {3}", Utils.GetHost(_tcpClient), Utils.GetPort(_tcpClient), ((int)_respCode).ToString(CultureInfo.InvariantCulture), _respText); break; } // throw a new application exception throw new ProxyException(msg); } private void WaitForData(NetworkStream stream) { int sleepTime = 0; while (!stream.DataAvailable) { Thread.Sleep(WAIT_FOR_DATA_INTERVAL); sleepTime += WAIT_FOR_DATA_INTERVAL; if (sleepTime > WAIT_FOR_DATA_TIMEOUT) throw new ProxyException(String.Format("A timeout while waiting for the proxy server at {0} on port {1} to respond.", Utils.GetHost(_tcpClient), Utils.GetPort(_tcpClient) )); } } private void ParseResponse(string response) { string[] data = null; // get rid of the LF character if it exists and then split the string on all CR data = response.Replace('\n', ' ').Split('\r'); ParseCodeAndText(data[0]); } private void ParseCodeAndText(string line) { int begin = 0; int end = 0; string val = null; if (line.IndexOf("HTTP") == -1) throw new ProxyException(String.Format("No HTTP response received from proxy destination. Server response: {0}.", line)); begin = line.IndexOf(" ") + 1; end = line.IndexOf(" ", begin); val = line.Substring(begin, end - begin); Int32 code = 0; if (!Int32.TryParse(val, out code)) throw new ProxyException(String.Format("An invalid response code was received from proxy destination. Server response: {0}.", line)); _respCode = (HttpResponseCodes)code; _respText = line.Substring(end + 1).Trim(); } #region "Async Methods" private BackgroundWorker _asyncWorker; private Exception _asyncException; bool _asyncCancelled; /// <summary> /// Gets a value indicating whether an asynchronous operation is running. /// </summary> /// <remarks>Returns true if an asynchronous operation is running; otherwise, false. /// </remarks> public bool IsBusy { get { return _asyncWorker == null ? false : _asyncWorker.IsBusy; } } /// <summary> /// Gets a value indicating whether an asynchronous operation is cancelled. /// </summary> /// <remarks>Returns true if an asynchronous operation is cancelled; otherwise, false. /// </remarks> public bool IsAsyncCancelled { get { return _asyncCancelled; } } /// <summary> /// Cancels any asychronous operation that is currently active. /// </summary> public void CancelAsync() { if (_asyncWorker != null && !_asyncWorker.CancellationPending && _asyncWorker.IsBusy) { _asyncCancelled = true; _asyncWorker.CancelAsync(); } } private void CreateAsyncWorker() { if (_asyncWorker != null) _asyncWorker.Dispose(); _asyncException = null; _asyncWorker = null; _asyncCancelled = false; _asyncWorker = new BackgroundWorker(); } /// <summary> /// Event handler for CreateConnectionAsync method completed. /// </summary> public event EventHandler<CreateConnectionAsyncCompletedEventArgs> CreateConnectionAsyncCompleted; /// <summary> /// Asynchronously creates a remote TCP connection through a proxy server to the destination host on the destination port. /// </summary> /// <param name="destinationHost">Destination host name or IP address.</param> /// <param name="destinationPort">Port number to connect to on the destination host.</param> /// <returns> /// Returns an open TcpClient object that can be used normally to communicate /// with the destination server /// </returns> /// <remarks> /// This method creates a connection to the proxy server and instructs the proxy server /// to make a pass through connection to the specified destination host on the specified /// port. /// </remarks> public void CreateConnectionAsync(string destinationHost, int destinationPort) { if (_asyncWorker != null && _asyncWorker.IsBusy) throw new InvalidOperationException("The HttpProxy object is already busy executing another asynchronous operation. You can only execute one asychronous method at a time."); CreateAsyncWorker(); _asyncWorker.WorkerSupportsCancellation = true; _asyncWorker.DoWork += new DoWorkEventHandler(CreateConnectionAsync_DoWork); _asyncWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(CreateConnectionAsync_RunWorkerCompleted); Object[] args = new Object[2]; args[0] = destinationHost; args[1] = destinationPort; _asyncWorker.RunWorkerAsync(args); } private void CreateConnectionAsync_DoWork(object sender, DoWorkEventArgs e) { try { Object[] args = (Object[])e.Argument; e.Result = CreateConnection((string)args[0], (int)args[1]); } catch (Exception ex) { _asyncException = ex; } } private void CreateConnectionAsync_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { if (CreateConnectionAsyncCompleted != null) CreateConnectionAsyncCompleted(this, new CreateConnectionAsyncCompletedEventArgs(_asyncException, _asyncCancelled, (TcpClient)e.Result)); } #endregion } }
using System; using System.ComponentModel; using System.Diagnostics; using System.Drawing.Design; using GuruComponents.Netrix.ComInterop; using GuruComponents.Netrix.UserInterface.TypeConverters; using GuruComponents.Netrix.UserInterface.TypeEditors; using GuruComponents.Netrix.WebEditing.Styles; using DisplayNameAttribute=GuruComponents.Netrix.UserInterface.TypeEditors.DisplayNameAttribute; using TE=GuruComponents.Netrix.UserInterface.TypeEditors; namespace GuruComponents.Netrix.WebEditing.Elements { /// <summary> /// The STYLE element embeds a style sheet in the document. /// </summary> /// <remarks> /// Any number of STYLE elements may be contained in the HEAD of a document. /// </remarks> public sealed class StyleElement : Element { private StyleRuleCollection _styleselectorcollection; [Browsable(false)] private new string InnerHtml { get { return String.Empty; } } /// <summary> /// This member overwrites the existings member to correct the PropertyGrid display. /// </summary> /// <remarks> /// This property cannot be used in user code. It supports the NetRix infrastructure only. /// </remarks> /// <exception cref="System.NotImplementedException">Always fired on call.</exception> [Browsable(false)] public new IEffectiveStyle EffectiveStyle { get { throw new NotImplementedException("Effective Style not available for that kind of element"); } } /// <summary> /// The MEDIA attribute specifies the media on which the style sheet should be applied. /// </summary> /// <remarks> /// This allows authors to restrict a style sheet to certain output devices, such as printers or aural browsers. The attribute's value is a comma-separated list of media descriptors. The following media descriptors are defined in HTML 4.0 and are case-sensitive: /// <list type="bullet"> /// <item>screen (the default), for non-paged computer screens; </item> /// <item>tty, for fixed-pitch character grid displays (such as the display used by Lynx); </item> /// <item>tv, for television-type devices with low resolution and limited scrollability; </item> /// <item>projection, for projectors; </item> /// <item>handheld, for handheld devices (characterized by a small, monochrome display and limited bandwidth); </item> /// <item>print, for output to a printer; </item> /// <item>braille, for braille tactile feedback devices; </item> /// <item>aural, for speech synthesizers; </item> /// <item>all, for all devices. </item> /// </list> /// To assign one of these values use the <see cref="GuruComponents.Netrix.WebEditing.Elements.LinkElementMedia">LinkElementMedia</see> enumaration constants. /// </remarks> [CategoryAttribute("Element Behavior")] [DescriptionAttribute("")] [TypeConverter(typeof(UITypeConverterDropList))] [DisplayNameAttribute()] public LinkElementMedia media { set { this.SetEnumAttribute ("media", (LinkElementMedia) value, (LinkElementMedia) 0); return; } get { return (LinkElementMedia) base.GetEnumAttribute ("media", (LinkElementMedia) 0); } } /// <summary> /// Gets or sets the title attribute for this element. /// </summary> /// <remarks> /// Visible elements may render the title as a tooltip. /// Invisible elements may not render, but use internally to support design time environments. /// Some elements may neither render nor use but still accept the attribute. /// </remarks> [CategoryAttribute("Element Behavior")] [DescriptionAttribute("")] [EditorAttribute( typeof(UITypeEditorString), typeof(UITypeEditor))] [DisplayName()] public string title { get { return base.GetStringAttribute("title"); } set { base.SetStringAttribute("title", value); } } /// <summary> /// The TYPE attribute of STYLE is used to specify the Internet media. Required. /// </summary> /// <remarks> /// The TYPE attribute specify the type of the style language. For Cascading Style Sheets, /// the TYPE attribute value should be text/css. /// <para> /// If the property is not assigned the value "text/css" will be returned. /// </para> /// </remarks> [CategoryAttribute("Element Behavior")] [DescriptionAttribute("")] [EditorAttribute( typeof(UITypeEditorString), typeof(UITypeEditor))] [DisplayName()] public string type { get { return base.GetStringAttribute("type", "text/css"); } set { base.SetStringAttribute("type", value); } } /// <summary> /// The embedded content of the container. /// </summary> /// <remarks> /// This property gives access to the content of the style container. It is recommended /// to provide a style editor within the host application that can access this content and /// the content of an external style file linked with the LINK tag. /// <seealso cref="GuruComponents.Netrix.WebEditing.Elements.LinkElement">LinkElement (LINK)</seealso> /// </remarks> [Browsable(false)] [CategoryAttribute("Content")] [DescriptionAttribute("")] [EditorAttribute( typeof(UITypeEditorScript), typeof(UITypeEditor))] [DisplayName()] public string Content { get { Interop.IHTMLStyleSheet ss = ((Interop.IHTMLStyleElement) base.GetBaseElement()).styleSheet; return ss.GetCssText(); } set { Interop.IHTMLStyleSheet ss = ((Interop.IHTMLStyleElement) base.GetBaseElement()).styleSheet; ss.SetCssText( (value == null) ? String.Empty : value); } } [CategoryAttribute("Content")] [DescriptionAttribute("")] [EditorAttribute( typeof(StyleSelectorEditor), typeof(UITypeEditor))] [DisplayName()] public StyleRuleCollection Selector { get { RefreshPeer(base.GetBaseElement()); return _styleselectorcollection; } } private void RefreshPeer(Interop.IHTMLElement peer) { _styleselectorcollection = new StyleRuleCollection(peer); _styleselectorcollection.OnInsertHandler += new CollectionInsertHandler(_styleselectorcollection_OnInsertHandler); _styleselectorcollection.OnClearHandler += new CollectionClearHandler(_styleselectorcollection_OnClearHandler); } private Interop.IHTMLStyleSheet BaseStylesheet { get { return ((Interop.IHTMLStyleElement) base.GetBaseElement()).styleSheet; } } private void _styleselectorcollection_OnInsertHandler(int index, object value) { StyleRule rule = (StyleRule) value; // do not add rules without a name if (!rule.RuleName.Equals(String.Empty) && !rule.style.Equals(String.Empty) && BaseStylesheet != null) { try { BaseStylesheet.AddRule(rule.RuleName, rule.style, index); } catch(Exception) { } } } private void _styleselectorcollection_OnClearHandler() { Interop.IHTMLStyleSheetRulesCollection rules = BaseStylesheet.GetRules(); int length = rules.GetLength(); for(int i = 0; i < length; i++) { BaseStylesheet.RemoveRule(0); } } /// <summary> /// Creates the specified element. /// </summary> /// <remarks> /// The element is being created and attached to the current document, but nevertheless not visible, /// until it's being placed anywhere within the DOM. To attach an element it's possible to either /// use the <see cref="ElementDom"/> property of any other already placed element and refer to this /// DOM or use the body element (<see cref="HtmlEditor.GetBodyElement"/>) and add the element there. Also, in /// case of user interactive solutions, it's possible to add an element near the current caret /// position, using <see cref="HtmlEditor.CreateElementAtCaret(string)"/> method. /// <para> /// Note: Invisible elements do neither appear in the DOM nor do they get saved. /// </para> /// </remarks> /// <param name="editor">The editor this element belongs to.</param> public StyleElement(IHtmlEditor editor) : base("style", editor) { } internal StyleElement(Interop.IHTMLElement peer, IHtmlEditor editor) : base (peer, editor) { RefreshPeer(peer); } } }
// 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 Microsoft.DotNet.Cli.Build; using System; using System.Collections.Generic; using System.IO; using Xunit; namespace Microsoft.DotNet.CoreSetup.Test.HostActivation { public class SDKLookup : IDisposable { private static readonly IDictionary<string, string> s_DefaultEnvironment = new Dictionary<string, string>() { {"COREHOST_TRACE", "1" }, // The SDK being used may be crossgen'd for a different architecture than we are building for. // Turn off ready to run, so an x64 crossgen'd SDK can be loaded in an x86 process. {"COMPlus_ReadyToRun", "0" }, }; private readonly RepoDirectoriesProvider RepoDirectories; private readonly DotNetCli DotNet; private readonly string _baseDir; private readonly string _currentWorkingDir; private readonly string _userDir; private readonly string _executableDir; private readonly string _cwdSdkBaseDir; private readonly string _userSdkBaseDir; private readonly string _exeSdkBaseDir; private readonly string _exeSelectedMessage; private const string _dotnetSdkDllMessageTerminator = "dotnet.dll]"; public SDKLookup() { // The dotnetSDKLookup dir will contain some folders and files that will be // necessary to perform the tests string baseDir = Path.Combine(TestArtifact.TestArtifactsPath, "dotnetSDKLookup"); _baseDir = SharedFramework.CalculateUniqueTestDirectory(baseDir); // The three tested locations will be the cwd, the user folder and the exe dir. cwd and user are no longer supported. // All dirs will be placed inside the base folder _currentWorkingDir = Path.Combine(_baseDir, "cwd"); _userDir = Path.Combine(_baseDir, "user"); _executableDir = Path.Combine(_baseDir, "exe"); DotNet = new DotNetBuilder(_baseDir, Path.Combine(TestArtifact.TestArtifactsPath, "sharedFrameworkPublish"), "exe") .AddMicrosoftNETCoreAppFrameworkMockHostPolicy("9999.0.0") .Build(); RepoDirectories = new RepoDirectoriesProvider(builtDotnet: DotNet.BinPath); // SdkBaseDirs contain all available version folders _cwdSdkBaseDir = Path.Combine(_currentWorkingDir, "sdk"); _userSdkBaseDir = Path.Combine(_userDir, ".dotnet", RepoDirectories.BuildArchitecture, "sdk"); _exeSdkBaseDir = Path.Combine(_executableDir, "sdk"); // Create directories Directory.CreateDirectory(_cwdSdkBaseDir); Directory.CreateDirectory(_userSdkBaseDir); Directory.CreateDirectory(_exeSdkBaseDir); // Trace messages used to identify from which folder the SDK was picked _exeSelectedMessage = $"Using .NET Core SDK dll=[{_exeSdkBaseDir}"; } public void Dispose() { if (!TestArtifact.PreserveTestRuns()) { Directory.Delete(_baseDir, true); } } [Fact] public void SdkLookup_Global_Json_Single_Digit_Patch_Rollup() { // Set specified SDK version = 9999.3.4-global-dummy CopyGlobalJson("SingleDigit-global.json"); // Specified SDK version: 9999.3.4-global-dummy // Exe: empty // Expected: no compatible version and a specific error messages DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining("A compatible installed .NET Core SDK for global.json version") .And.HaveStdErrContaining("It was not possible to find any installed .NET Core SDKs") .And.HaveStdErrContaining("aka.ms/dotnet-download") .And.NotHaveStdErrContaining("Checking if resolved SDK dir"); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.4.1", "9999.3.4-dummy"); // Specified SDK version: 9999.3.4-global-dummy // Exe: 9999.4.1, 9999.3.4-dummy // Expected: no compatible version and a specific error message DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining("A compatible installed .NET Core SDK for global.json version") .And.NotHaveStdErrContaining("It was not possible to find any installed .NET Core SDKs"); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.3"); // Specified SDK version: 9999.3.4-global-dummy // Exe: 9999.4.1, 9999.3.4-dummy, 9999.3.3 // Expected: no compatible version and a specific error message DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining("A compatible installed .NET Core SDK for global.json version") .And.NotHaveStdErrContaining("It was not possible to find any installed .NET Core SDKs"); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.4"); // Specified SDK version: 9999.3.4-global-dummy // Exe: 9999.4.1, 9999.3.4-dummy, 9999.3.3, 9999.3.4 // Expected: 9999.3.4 from exe dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.3.4", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.5-dummy"); // Specified SDK version: 9999.3.4-global-dummy // Exe: 9999.4.1, 9999.3.4-dummy, 9999.3.3, 9999.3.4, 9999.3.5-dummy // Expected: 9999.3.5-dummy from exe dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.3.5-dummy", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.600"); // Specified SDK version: 9999.3.4-global-dummy // Exe: 9999.4.1, 9999.3.4-dummy, 9999.3.3, 9999.3.4, 9999.3.5-dummy, 9999.3.600 // Expected: 9999.3.5-dummy from exe dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.3.5-dummy", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.4-global-dummy"); // Specified SDK version: 9999.3.4-global-dummy // Exe: 9999.4.1, 9999.3.4-dummy, 9999.3.3, 9999.3.4, 9999.3.5-dummy, 9999.3.600, 9999.3.4-global-dummy // Expected: 9999.3.4-global-dummy from exe dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.3.4-global-dummy", _dotnetSdkDllMessageTerminator)); // Verify we have the expected SDK versions DotNet.Exec("--list-sdks") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .Execute() .Should().Pass() .And.HaveStdOutContaining("9999.3.4-dummy") .And.HaveStdOutContaining("9999.3.4-global-dummy") .And.HaveStdOutContaining("9999.4.1") .And.HaveStdOutContaining("9999.3.3") .And.HaveStdOutContaining("9999.3.4") .And.HaveStdOutContaining("9999.3.600") .And.HaveStdOutContaining("9999.3.5-dummy"); } [Fact] public void SdkLookup_Global_Json_Two_Part_Patch_Rollup() { // Set specified SDK version = 9999.3.304-global-dummy CopyGlobalJson("TwoPart-global.json"); // Specified SDK version: 9999.3.304-global-dummy // Exe: empty // Expected: no compatible version and a specific error messages DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining("A compatible installed .NET Core SDK for global.json version") .And.HaveStdErrContaining("It was not possible to find any installed .NET Core SDKs"); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.57", "9999.3.4-dummy"); // Specified SDK version: 9999.3.304-global-dummy // Exe: 9999.3.57, 9999.3.4-dummy // Expected: no compatible version and a specific error message DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining("A compatible installed .NET Core SDK for global.json version") .And.NotHaveStdErrContaining("It was not possible to find any installed .NET Core SDKs"); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.300", "9999.7.304-global-dummy"); // Specified SDK version: 9999.3.304-global-dummy // Exe: 9999.3.57, 9999.3.4-dummy, 9999.3.300, 9999.7.304-global-dummy // Expected: no compatible version and a specific error message DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining("A compatible installed .NET Core SDK for global.json version") .And.NotHaveStdErrContaining("It was not possible to find any installed .NET Core SDKs"); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.304"); // Specified SDK version: 9999.3.304-global-dummy // Exe: 99999.3.57, 9999.3.4-dummy, 9999.3.300, 9999.7.304-global-dummy, 9999.3.304 // Expected: 9999.3.304 from exe dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.3.304", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.399", "9999.3.399-dummy", "9999.3.400"); // Specified SDK version: 9999.3.304-global-dummy // Exe: 9999.3.57, 9999.3.4-dummy, 9999.3.300, 9999.7.304-global-dummy, 9999.3.304, 9999.3.399, 9999.3.399-dummy, 9999.3.400 // Expected: 9999.3.399 from exe dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.3.399", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.2400", "9999.3.3004"); // Specified SDK version: 9999.3.304-global-dummy // Exe: 9999.3.57, 9999.3.4-dummy, 9999.3.300, 9999.7.304-global-dummy, 9999.3.304, 9999.3.399, 9999.3.399-dummy, 9999.3.400, 9999.3.2400, 9999.3.3004 // Expected: 9999.3.399 from exe dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.3.399", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.3.304-global-dummy"); // Specified SDK version: 9999.3.304-global-dummy // Exe: 9999.3.57, 9999.3.4-dummy, 9999.3.300, 9999.7.304-global-dummy, 9999.3.304, 9999.3.399, 9999.3.399-dummy, 9999.3.400, 9999.3.2400, 9999.3.3004, 9999.3.304-global-dummy // Expected: 9999.3.304-global-dummy from exe dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.3.304-global-dummy", _dotnetSdkDllMessageTerminator)); // Verify we have the expected SDK versions DotNet.Exec("--list-sdks") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .Execute() .Should().Pass() .And.HaveStdOutContaining("9999.3.57") .And.HaveStdOutContaining("9999.3.4-dummy") .And.HaveStdOutContaining("9999.3.300") .And.HaveStdOutContaining("9999.7.304-global-dummy") .And.HaveStdOutContaining("9999.3.399") .And.HaveStdOutContaining("9999.3.399-dummy") .And.HaveStdOutContaining("9999.3.400") .And.HaveStdOutContaining("9999.3.2400") .And.HaveStdOutContaining("9999.3.3004") .And.HaveStdOutContaining("9999.3.304") .And.HaveStdOutContaining("9999.3.304-global-dummy"); } [Fact] public void SdkLookup_Negative_Version() { // Add a negative SDK version AddAvailableSdkVersions(_exeSdkBaseDir, "-1.-1.-1"); // Specified SDK version: none // Exe: -1.-1.-1 // Expected: no compatible version and a specific error messages DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should().Fail() .And.HaveStdErrContaining("It was not possible to find any installed .NET Core SDKs") .And.HaveStdErrContaining("Did you mean to run .NET Core SDK commands? Install a .NET Core SDK from"); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.4"); // Specified SDK version: none // Exe: -1.-1.-1, 9999.0.4 // Expected: 9999.0.4 from exe dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.0.4", _dotnetSdkDllMessageTerminator)); // Verify we have the expected SDK versions DotNet.Exec("--list-sdks") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .Execute() .Should().Pass() .And.HaveStdOutContaining("9999.0.4"); } [Fact] public void SdkLookup_Must_Pick_The_Highest_Semantic_Version() { // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.0", "9999.0.3-dummy.9", "9999.0.3-dummy.10"); // Specified SDK version: none // Cwd: empty // User: empty // Exe: 9999.0.0, 9999.0.3-dummy.9, 9999.0.3-dummy.10 // Expected: 9999.0.3-dummy.10 from exe dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.0.3-dummy.10", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.3"); // Specified SDK version: none // Cwd: empty // User: empty // Exe: 9999.0.0, 9999.0.3-dummy.9, 9999.0.3-dummy.10, 9999.0.3 // Expected: 9999.0.3 from exe dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.0.3", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_userSdkBaseDir, "9999.0.200"); AddAvailableSdkVersions(_cwdSdkBaseDir, "10000.0.0"); AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.100"); // Specified SDK version: none // Cwd: 10000.0.0 --> should not be picked // User: 9999.0.200 --> should not be picked // Exe: 9999.0.0, 9999.0.3-dummy.9, 9999.0.3-dummy.10, 9999.0.3, 9999.0.100 // Expected: 9999.0.100 from exe dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.0.100", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.80"); // Specified SDK version: none // Cwd: 10000.0.0 --> should not be picked // User: 9999.0.200 --> should not be picked // Exe: 9999.0.0, 9999.0.3-dummy.9, 9999.0.3-dummy.10, 9999.0.3, 9999.0.100, 9999.0.80 // Expected: 9999.0.100 from exe dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.0.100", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.5500000"); // Specified SDK version: none // Cwd: 10000.0.0 --> should not be picked // User: 9999.0.200 --> should not be picked // Exe: 9999.0.0, 9999.0.3-dummy.9, 9999.0.3-dummy.10, 9999.0.3, 9999.0.100, 9999.0.80, 9999.0.5500000 // Expected: 9999.0.5500000 from exe dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.0.5500000", _dotnetSdkDllMessageTerminator)); // Add SDK versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.52000000"); // Specified SDK version: none // Cwd: 10000.0.0 --> should not be picked // User: 9999.0.200 --> should not be picked // Exe: 9999.0.0, 9999.0.3-dummy.9, 9999.0.3-dummy.10, 9999.0.3, 9999.0.100, 9999.0.80, 9999.0.5500000, 9999.0.52000000 // Expected: 9999.0.52000000 from exe dir DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should().Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.0.52000000", _dotnetSdkDllMessageTerminator)); // Verify we have the expected SDK versions DotNet.Exec("--list-sdks") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .Execute() .Should().Pass() .And.HaveStdOutContaining("9999.0.0") .And.HaveStdOutContaining("9999.0.3-dummy.9") .And.HaveStdOutContaining("9999.0.3-dummy.10") .And.HaveStdOutContaining("9999.0.3") .And.HaveStdOutContaining("9999.0.100") .And.HaveStdOutContaining("9999.0.80") .And.HaveStdOutContaining("9999.0.5500000") .And.HaveStdOutContaining("9999.0.52000000"); } [Theory] [InlineData("diSABle")] [InlineData("PaTCh")] [InlineData("FeaturE")] [InlineData("MINOR")] [InlineData("maJor")] [InlineData("LatestPatch")] [InlineData("Latestfeature")] [InlineData("latestMINOR")] [InlineData("latESTMajor")] public void It_allows_case_insensitive_roll_forward_policy_names(string rollForward) { const string Requested = "9999.0.100"; AddAvailableSdkVersions(_exeSdkBaseDir, Requested); WriteGlobalJson(FormatGlobalJson(policy: rollForward, version: Requested)); DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, Requested, _dotnetSdkDllMessageTerminator)); } [Theory] [MemberData(nameof(InvalidGlobalJsonData))] public void It_falls_back_to_latest_sdk_for_invalid_global_json(string globalJsonContents, string[] messages) { AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.100", "9999.0.300-dummy.9", "9999.1.402"); WriteGlobalJson(globalJsonContents); var expectation = DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And.HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.1.402", _dotnetSdkDllMessageTerminator)); foreach (var message in messages) { expectation = expectation.And.HaveStdErrContaining(message); } } [Theory] [MemberData(nameof(SdkRollForwardData))] public void It_rolls_forward_as_expected(string policy, string requested, bool allowPrerelease, string expected, string[] installed) { AddAvailableSdkVersions(_exeSdkBaseDir, installed); WriteGlobalJson(FormatGlobalJson(policy: policy, version: requested, allowPrerelease: allowPrerelease)); var result = DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute(); var globalJson = Path.Combine(_currentWorkingDir, "global.json"); if (expected == null) { result .Should() .Fail() .And.HaveStdErrContaining($"A compatible installed .NET Core SDK for global.json version [{requested}] from [{globalJson}] was not found") .And.HaveStdErrContaining($"Install the [{requested}] .NET Core SDK or update [{globalJson}] with an installed .NET Core SDK:"); } else { result .Should() .Pass() .And.HaveStdErrContaining($"SDK path resolved to [{Path.Combine(_exeSdkBaseDir, expected)}]"); } } [Fact] public void It_uses_latest_stable_sdk_if_allow_prerelease_is_false() { var installed = new string[] { "9999.1.702", "9999.2.101", "9999.2.203", "9999.2.204-preview1", "10000.0.100-preview3", "10000.0.100-preview7", "10000.0.100", "10000.1.102", "10000.1.106", "10000.0.200-preview5", "10000.1.100-preview3", "10001.0.100-preview3", }; const string ExpectedVersion = "10000.1.106"; AddAvailableSdkVersions(_exeSdkBaseDir, installed); WriteGlobalJson(FormatGlobalJson(allowPrerelease: false)); var result = DotNet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And.HaveStdErrContaining($"SDK path resolved to [{Path.Combine(_exeSdkBaseDir, ExpectedVersion)}]"); } public static IEnumerable<object[]> InvalidGlobalJsonData { get { const string IgnoringSDKSettings = "Ignoring SDK settings in global.json: the latest installed .NET Core SDK (including prereleases) will be used"; // Use invalid JSON yield return new object[] { "{ sdk: { \"version\": \"9999.0.100\" } }", new[] { "A JSON parsing exception occurred", IgnoringSDKSettings } }; // Use something other than a JSON object yield return new object[] { "true", new[] { "Expected a JSON object", IgnoringSDKSettings } }; // Use a non-string version yield return new object[] { "{ \"sdk\": { \"version\": 1 } }", new[] { "Expected a string for the 'sdk/version' value", IgnoringSDKSettings } }; // Use an invalid version value yield return new object[] { FormatGlobalJson(version: "invalid"), new[] { "Version 'invalid' is not valid for the 'sdk/version' value", IgnoringSDKSettings } }; // Use a non-string policy yield return new object[] { "{ \"sdk\": { \"rollForward\": true } }", new[] { "Expected a string for the 'sdk/rollForward' value", IgnoringSDKSettings } }; // Use a policy but no version yield return new object[] { FormatGlobalJson(policy: "latestPatch"), new[] { "The roll-forward policy 'latestPatch' requires a 'sdk/version' value", IgnoringSDKSettings } }; // Use an invalid policy value yield return new object[] { FormatGlobalJson(policy: "invalid"), new[] { "The roll-forward policy 'invalid' is not supported for the 'sdk/rollForward' value", IgnoringSDKSettings } }; // Use a non-boolean allow prerelease yield return new object[] { "{ \"sdk\": { \"allowPrerelease\": \"true\" } }", new[] { "Expected a boolean for the 'sdk/allowPrerelease' value", IgnoringSDKSettings } }; // Use a prerelease version and allowPrerelease = false yield return new object[] { FormatGlobalJson(version: "9999.1.402-preview1", allowPrerelease: false), new[] { "Ignoring the 'sdk/allowPrerelease' value" } }; } } public static IEnumerable<object[]> SdkRollForwardData { get { const string Requested = "9999.1.501"; var installed = new string[] { "9999.1.500", }; // Array of (policy, expected) tuples var policies = new[] { ((string)null, (string)null), ("patch", (string)null), ("feature", (string)null), ("minor", (string)null), ("major", (string)null), ("latestPatch", (string)null), ("latestFeature", (string)null), ("latestMinor", (string)null), ("latestMajor", (string)null), ("disable", (string)null), ("invalid", "9999.1.500"), }; foreach (var policy in policies) { yield return new object[] { policy.Item1, // policy Requested, // requested true, // allow prerelease policy.Item2, // expected installed // installed }; } installed = new string[] { "9999.1.500", "9999.2.100-preview1", }; // Array of (policy, expected) tuples policies = new[] { ((string)null, (string)null), ("patch", (string)null), ("feature", (string)null), ("minor", (string)null), ("major", (string)null), ("latestPatch", (string)null), ("latestFeature", (string)null), ("latestMinor", (string)null), ("latestMajor", (string)null), ("disable", (string)null), ("invalid", "9999.2.100-preview1"), }; foreach (var policy in policies) { yield return new object[] { policy.Item1, // policy Requested, // requested false, // do not allow prerelease policy.Item2, // expected installed // installed }; } installed = new string[] { "9998.0.300", "9999.1.500", "9999.1.501", "9999.1.503-preview5", "9999.1.503", "9999.1.504-preview1", "9999.1.504-preview2", }; // Array of (policy, expected) tuples policies = new[] { ((string)null, "9999.1.501"), ("patch", "9999.1.501"), ("feature", "9999.1.504-preview2"), ("minor", "9999.1.504-preview2"), ("major", "9999.1.504-preview2"), ("latestPatch", "9999.1.504-preview2"), ("latestFeature", "9999.1.504-preview2"), ("latestMinor", "9999.1.504-preview2"), ("latestMajor", "9999.1.504-preview2"), ("disable", "9999.1.501"), ("invalid", "9999.1.504-preview2"), }; foreach (var policy in policies) { yield return new object[] { policy.Item1, // policy Requested, // requested true, // allow prerelease policy.Item2, // expected installed // installed }; } installed = new string[] { "9998.0.300", "9999.1.500", "9999.1.501", "9999.1.503-preview5", "9999.1.503", "9999.1.504-preview1", "9999.1.504-preview2", }; // Array of (policy, expected) tuples policies = new[] { ((string)null, "9999.1.501"), ("patch", "9999.1.501"), ("feature", "9999.1.503"), ("minor", "9999.1.503"), ("major", "9999.1.503"), ("latestPatch", "9999.1.503"), ("latestFeature", "9999.1.503"), ("latestMinor", "9999.1.503"), ("latestMajor", "9999.1.503"), ("disable", "9999.1.501"), ("invalid", "9999.1.504-preview2"), }; foreach (var policy in policies) { yield return new object[] { policy.Item1, // policy Requested, // requested false, // don't allow prerelease policy.Item2, // expected installed // installed }; } installed = new string[] { "9998.0.300", "9999.1.500", "9999.1.503", "9999.1.505-preview2", "9999.1.505", "9999.1.506-preview1", "9999.1.601", "9999.1.608-preview3", "9999.1.609", "9999.2.101", "9999.2.203-preview1", "9999.2.203", "10000.0.100", "10000.1.100-preview1" }; // Array of (policy, expected) tuples policies = new[] { (null, "9999.1.506-preview1"), ("patch", "9999.1.506-preview1"), ("feature", "9999.1.506-preview1"), ("minor", "9999.1.506-preview1"), ("major", "9999.1.506-preview1"), ("latestPatch", "9999.1.506-preview1"), ("latestFeature", "9999.1.609"), ("latestMinor", "9999.2.203"), ("latestMajor", "10000.1.100-preview1"), ("disable", (string)null), ("invalid", "10000.1.100-preview1"), }; foreach (var policy in policies) { yield return new object[] { policy.Item1, // policy Requested, // requested true, // allow prerelease policy.Item2, // expected installed // installed }; } installed = new string[] { "9998.0.300", "9999.1.500", "9999.1.503", "9999.1.505-preview2", "9999.1.505", "9999.1.506-preview1", "9999.1.601", "9999.1.608-preview3", "9999.1.609", "9999.2.101", "9999.2.203-preview1", "9999.2.203", "10000.0.100", "10000.1.100-preview1" }; // Array of (policy, expected) tuples policies = new[] { (null, "9999.1.505"), ("patch", "9999.1.505"), ("feature", "9999.1.505"), ("minor", "9999.1.505"), ("major", "9999.1.505"), ("latestPatch", "9999.1.505"), ("latestFeature", "9999.1.609"), ("latestMinor", "9999.2.203"), ("latestMajor", "10000.0.100"), ("disable", (string)null), ("invalid", "10000.1.100-preview1"), }; foreach (var policy in policies) { yield return new object[] { policy.Item1, // policy Requested, // requested false, // don't allow prerelease policy.Item2, // expected installed // installed }; } installed = new string[] { "9998.0.300", "9999.1.500", "9999.1.601", "9999.1.604-preview3", "9999.1.604", "9999.1.605-preview4", "9999.1.701", "9999.1.702-preview1", "9999.1.702", "9999.2.101", "9999.2.203", "9999.2.204-preview1", "10000.0.100-preview7", "10000.0.100", }; // Array of (policy, expected) tuples policies = new[] { ((string)null, (string)null), ("patch", (string)null), ("feature", "9999.1.605-preview4"), ("minor", "9999.1.605-preview4"), ("major", "9999.1.605-preview4"), ("latestPatch", (string)null), ("latestFeature", "9999.1.702"), ("latestMinor", "9999.2.204-preview1"), ("latestMajor", "10000.0.100"), ("disable", (string)null), ("invalid", "10000.0.100"), }; foreach (var policy in policies) { yield return new object[] { policy.Item1, // policy Requested, // requested true, // allow prerelease policy.Item2, // expected installed // installed }; } installed = new string[] { "9998.0.300", "9999.1.500", "9999.1.601", "9999.1.604-preview3", "9999.1.604", "9999.1.605-preview4", "9999.1.701", "9999.1.702-preview1", "9999.1.702", "9999.2.101", "9999.2.203", "9999.2.204-preview1", "10000.0.100-preview7", "10000.0.100", }; // Array of (policy, expected) tuples policies = new[] { ((string)null, (string)null), ("patch", (string)null), ("feature", "9999.1.604"), ("minor", "9999.1.604"), ("major", "9999.1.604"), ("latestPatch", (string)null), ("latestFeature", "9999.1.702"), ("latestMinor", "9999.2.203"), ("latestMajor", "10000.0.100"), ("disable", (string)null), ("invalid", "10000.0.100"), }; foreach (var policy in policies) { yield return new object[] { policy.Item1, // policy Requested, // requested false, // don't allow prerelease policy.Item2, // expected installed // installed }; } installed = new string[] { "9998.0.300", "9999.1.500", "9999.2.101-preview4", "9999.2.101", "9999.2.102-preview1", "9999.2.203", "9999.3.501", "9999.4.205-preview3", "10000.0.100", "10000.1.100-preview1" }; // Array of (policy, expected) tuples policies = new[] { ((string)null, (string)null), ("patch", (string)null), ("feature", (string)null), ("minor", "9999.2.102-preview1"), ("major", "9999.2.102-preview1"), ("latestPatch", (string)null), ("latestFeature", (string)null), ("latestMinor", "9999.4.205-preview3"), ("latestMajor", "10000.1.100-preview1"), ("disable", (string)null), ("invalid", "10000.1.100-preview1"), }; foreach (var policy in policies) { yield return new object[] { policy.Item1, // policy Requested, // requested true, // allow prerelease policy.Item2, // expected installed // installed }; } installed = new string[] { "9998.0.300", "9999.1.500", "9999.2.101-preview4", "9999.2.101", "9999.2.102-preview1", "9999.2.203", "9999.3.501", "9999.4.205-preview3", "10000.0.100", "10000.1.100-preview1" }; // Array of (policy, expected) tuples policies = new[] { ((string)null, (string)null), ("patch", (string)null), ("feature", (string)null), ("minor", "9999.2.101"), ("major", "9999.2.101"), ("latestPatch", (string)null), ("latestFeature", (string)null), ("latestMinor", "9999.3.501"), ("latestMajor", "10000.0.100"), ("disable", (string)null), ("invalid", "10000.1.100-preview1"), }; foreach (var policy in policies) { yield return new object[] { policy.Item1, // policy Requested, // requested false, // don't allow prerelease policy.Item2, // expected installed // installed }; } installed = new string[] { "9998.0.300", "9999.1.500", "10000.0.100", "10000.0.105-preview1", "10000.0.105", "10000.0.106-preview1", "10000.1.102", "10000.1.107", "10000.3.100", "10000.3.102-preview3", }; // Array of (policy, expected) tuples policies = new[] { ((string)null, (string)null), ("patch", (string)null), ("feature", (string)null), ("minor", (string)null), ("major", "10000.0.106-preview1"), ("latestPatch", (string)null), ("latestFeature", (string)null), ("latestMinor", (string)null), ("latestMajor", "10000.3.102-preview3"), ("disable", (string)null), ("invalid", "10000.3.102-preview3"), }; foreach (var policy in policies) { yield return new object[] { policy.Item1, // policy Requested, // requested true, // allow prerelease policy.Item2, // expected installed // installed }; } installed = new string[] { "9998.0.300", "9999.1.500", "10000.0.100", "10000.0.105-preview1", "10000.0.105", "10000.0.106-preview1", "10000.1.102", "10000.1.107", "10000.3.100", "10000.3.102-preview3", }; // Array of (policy, expected) tuples policies = new[] { ((string)null, (string)null), ("patch", (string)null), ("feature", (string)null), ("minor", (string)null), ("major", "10000.0.105"), ("latestPatch", (string)null), ("latestFeature", (string)null), ("latestMinor", (string)null), ("latestMajor", "10000.3.100"), ("disable", (string)null), ("invalid", "10000.3.102-preview3"), }; foreach (var policy in policies) { yield return new object[] { policy.Item1, // policy Requested, // requested false, // don't allow prerelease policy.Item2, // expected installed // installed }; } } } // This method adds a list of new sdk version folders in the specified directory. // The actual contents are 'fake' and the mininum required for SDK discovery. // The dotnet.runtimeconfig.json created uses a dummy framework version (9999.0.0) private void AddAvailableSdkVersions(string sdkBaseDir, params string[] availableVersions) { string dummyRuntimeConfig = Path.Combine(RepoDirectories.RepoRoot, "src", "test", "Assets", "TestUtils", "SDKLookup", "dotnet.runtimeconfig.json"); foreach (string version in availableVersions) { string newSdkDir = Path.Combine(sdkBaseDir, version); Directory.CreateDirectory(newSdkDir); // ./dotnet.dll File.WriteAllText(Path.Combine(newSdkDir, "dotnet.dll"), string.Empty); // ./dotnet.runtimeconfig.json string runtimeConfig = Path.Combine(newSdkDir, "dotnet.runtimeconfig.json"); File.Copy(dummyRuntimeConfig, runtimeConfig, true); } } // Put a global.json file in the cwd in order to specify a CLI private void CopyGlobalJson(string globalJsonFileName) { string destFile = Path.Combine(_currentWorkingDir, "global.json"); string srcFile = Path.Combine(RepoDirectories.RepoRoot, "src", "test", "Assets", "TestUtils", "SDKLookup", globalJsonFileName); File.Copy(srcFile, destFile, true); } private static string FormatGlobalJson(string version = null, string policy = null, bool? allowPrerelease = null) { version = version == null ? "null" : string.Format("\"{0}\"", version); policy = policy == null ? "null" : string.Format("\"{0}\"", policy); string allow = allowPrerelease.HasValue ? (allowPrerelease.Value ? "true" : "false") : "null"; return $@"{{ ""sdk"": {{ ""version"": {version}, ""rollForward"": {policy}, ""allowPrerelease"": {allow} }} }}"; } private void WriteGlobalJson(string contents) { File.WriteAllText(Path.Combine(_currentWorkingDir, "global.json"), contents); } } }
using System; using NBitcoin.BouncyCastle.Utilities; namespace NBitcoin.BouncyCastle.Crypto.Digests { /** * implementation of RipeMD128 */ public class RipeMD128Digest : GeneralDigest { private const int DigestLength = 16; private int H0, H1, H2, H3; // IV's private int[] X = new int[16]; private int xOff; /** * Standard constructor */ public RipeMD128Digest() { Reset(); } /** * Copy constructor. This will copy the state of the provided * message digest. */ public RipeMD128Digest(RipeMD128Digest t) : base(t) { CopyIn(t); } private void CopyIn(RipeMD128Digest t) { base.CopyIn(t); H0 = t.H0; H1 = t.H1; H2 = t.H2; H3 = t.H3; Array.Copy(t.X, 0, X, 0, t.X.Length); xOff = t.xOff; } public override string AlgorithmName { get { return "RIPEMD128"; } } public override int GetDigestSize() { return DigestLength; } internal override void ProcessWord( byte[] input, int inOff) { X[xOff++] = (input[inOff] & 0xff) | ((input[inOff + 1] & 0xff) << 8) | ((input[inOff + 2] & 0xff) << 16) | ((input[inOff + 3] & 0xff) << 24); if (xOff == 16) { ProcessBlock(); } } internal override void ProcessLength( long bitLength) { if (xOff > 14) { ProcessBlock(); } X[14] = (int)(bitLength & 0xffffffff); X[15] = (int)((ulong) bitLength >> 32); } private void UnpackWord( int word, byte[] outBytes, int outOff) { outBytes[outOff] = (byte)word; outBytes[outOff + 1] = (byte)((uint) word >> 8); outBytes[outOff + 2] = (byte)((uint) word >> 16); outBytes[outOff + 3] = (byte)((uint) word >> 24); } public override int DoFinal( byte[] output, int outOff) { Finish(); UnpackWord(H0, output, outOff); UnpackWord(H1, output, outOff + 4); UnpackWord(H2, output, outOff + 8); UnpackWord(H3, output, outOff + 12); Reset(); return DigestLength; } /** * reset the chaining variables to the IV values. */ public override void Reset() { base.Reset(); H0 = unchecked((int) 0x67452301); H1 = unchecked((int) 0xefcdab89); H2 = unchecked((int) 0x98badcfe); H3 = unchecked((int) 0x10325476); xOff = 0; for (int i = 0; i != X.Length; i++) { X[i] = 0; } } /* * rotate int x left n bits. */ private int RL( int x, int n) { return (x << n) | (int) ((uint) x >> (32 - n)); } /* * f1,f2,f3,f4 are the basic RipeMD128 functions. */ /* * F */ private int F1( int x, int y, int z) { return x ^ y ^ z; } /* * G */ private int F2( int x, int y, int z) { return (x & y) | (~x & z); } /* * H */ private int F3( int x, int y, int z) { return (x | ~y) ^ z; } /* * I */ private int F4( int x, int y, int z) { return (x & z) | (y & ~z); } private int F1( int a, int b, int c, int d, int x, int s) { return RL(a + F1(b, c, d) + x, s); } private int F2( int a, int b, int c, int d, int x, int s) { return RL(a + F2(b, c, d) + x + unchecked((int) 0x5a827999), s); } private int F3( int a, int b, int c, int d, int x, int s) { return RL(a + F3(b, c, d) + x + unchecked((int) 0x6ed9eba1), s); } private int F4( int a, int b, int c, int d, int x, int s) { return RL(a + F4(b, c, d) + x + unchecked((int) 0x8f1bbcdc), s); } private int FF1( int a, int b, int c, int d, int x, int s) { return RL(a + F1(b, c, d) + x, s); } private int FF2( int a, int b, int c, int d, int x, int s) { return RL(a + F2(b, c, d) + x + unchecked((int) 0x6d703ef3), s); } private int FF3( int a, int b, int c, int d, int x, int s) { return RL(a + F3(b, c, d) + x + unchecked((int) 0x5c4dd124), s); } private int FF4( int a, int b, int c, int d, int x, int s) { return RL(a + F4(b, c, d) + x + unchecked((int) 0x50a28be6), s); } internal override void ProcessBlock() { int a, aa; int b, bb; int c, cc; int d, dd; a = aa = H0; b = bb = H1; c = cc = H2; d = dd = H3; // // Round 1 // a = F1(a, b, c, d, X[ 0], 11); d = F1(d, a, b, c, X[ 1], 14); c = F1(c, d, a, b, X[ 2], 15); b = F1(b, c, d, a, X[ 3], 12); a = F1(a, b, c, d, X[ 4], 5); d = F1(d, a, b, c, X[ 5], 8); c = F1(c, d, a, b, X[ 6], 7); b = F1(b, c, d, a, X[ 7], 9); a = F1(a, b, c, d, X[ 8], 11); d = F1(d, a, b, c, X[ 9], 13); c = F1(c, d, a, b, X[10], 14); b = F1(b, c, d, a, X[11], 15); a = F1(a, b, c, d, X[12], 6); d = F1(d, a, b, c, X[13], 7); c = F1(c, d, a, b, X[14], 9); b = F1(b, c, d, a, X[15], 8); // // Round 2 // a = F2(a, b, c, d, X[ 7], 7); d = F2(d, a, b, c, X[ 4], 6); c = F2(c, d, a, b, X[13], 8); b = F2(b, c, d, a, X[ 1], 13); a = F2(a, b, c, d, X[10], 11); d = F2(d, a, b, c, X[ 6], 9); c = F2(c, d, a, b, X[15], 7); b = F2(b, c, d, a, X[ 3], 15); a = F2(a, b, c, d, X[12], 7); d = F2(d, a, b, c, X[ 0], 12); c = F2(c, d, a, b, X[ 9], 15); b = F2(b, c, d, a, X[ 5], 9); a = F2(a, b, c, d, X[ 2], 11); d = F2(d, a, b, c, X[14], 7); c = F2(c, d, a, b, X[11], 13); b = F2(b, c, d, a, X[ 8], 12); // // Round 3 // a = F3(a, b, c, d, X[ 3], 11); d = F3(d, a, b, c, X[10], 13); c = F3(c, d, a, b, X[14], 6); b = F3(b, c, d, a, X[ 4], 7); a = F3(a, b, c, d, X[ 9], 14); d = F3(d, a, b, c, X[15], 9); c = F3(c, d, a, b, X[ 8], 13); b = F3(b, c, d, a, X[ 1], 15); a = F3(a, b, c, d, X[ 2], 14); d = F3(d, a, b, c, X[ 7], 8); c = F3(c, d, a, b, X[ 0], 13); b = F3(b, c, d, a, X[ 6], 6); a = F3(a, b, c, d, X[13], 5); d = F3(d, a, b, c, X[11], 12); c = F3(c, d, a, b, X[ 5], 7); b = F3(b, c, d, a, X[12], 5); // // Round 4 // a = F4(a, b, c, d, X[ 1], 11); d = F4(d, a, b, c, X[ 9], 12); c = F4(c, d, a, b, X[11], 14); b = F4(b, c, d, a, X[10], 15); a = F4(a, b, c, d, X[ 0], 14); d = F4(d, a, b, c, X[ 8], 15); c = F4(c, d, a, b, X[12], 9); b = F4(b, c, d, a, X[ 4], 8); a = F4(a, b, c, d, X[13], 9); d = F4(d, a, b, c, X[ 3], 14); c = F4(c, d, a, b, X[ 7], 5); b = F4(b, c, d, a, X[15], 6); a = F4(a, b, c, d, X[14], 8); d = F4(d, a, b, c, X[ 5], 6); c = F4(c, d, a, b, X[ 6], 5); b = F4(b, c, d, a, X[ 2], 12); // // Parallel round 1 // aa = FF4(aa, bb, cc, dd, X[ 5], 8); dd = FF4(dd, aa, bb, cc, X[14], 9); cc = FF4(cc, dd, aa, bb, X[ 7], 9); bb = FF4(bb, cc, dd, aa, X[ 0], 11); aa = FF4(aa, bb, cc, dd, X[ 9], 13); dd = FF4(dd, aa, bb, cc, X[ 2], 15); cc = FF4(cc, dd, aa, bb, X[11], 15); bb = FF4(bb, cc, dd, aa, X[ 4], 5); aa = FF4(aa, bb, cc, dd, X[13], 7); dd = FF4(dd, aa, bb, cc, X[ 6], 7); cc = FF4(cc, dd, aa, bb, X[15], 8); bb = FF4(bb, cc, dd, aa, X[ 8], 11); aa = FF4(aa, bb, cc, dd, X[ 1], 14); dd = FF4(dd, aa, bb, cc, X[10], 14); cc = FF4(cc, dd, aa, bb, X[ 3], 12); bb = FF4(bb, cc, dd, aa, X[12], 6); // // Parallel round 2 // aa = FF3(aa, bb, cc, dd, X[ 6], 9); dd = FF3(dd, aa, bb, cc, X[11], 13); cc = FF3(cc, dd, aa, bb, X[ 3], 15); bb = FF3(bb, cc, dd, aa, X[ 7], 7); aa = FF3(aa, bb, cc, dd, X[ 0], 12); dd = FF3(dd, aa, bb, cc, X[13], 8); cc = FF3(cc, dd, aa, bb, X[ 5], 9); bb = FF3(bb, cc, dd, aa, X[10], 11); aa = FF3(aa, bb, cc, dd, X[14], 7); dd = FF3(dd, aa, bb, cc, X[15], 7); cc = FF3(cc, dd, aa, bb, X[ 8], 12); bb = FF3(bb, cc, dd, aa, X[12], 7); aa = FF3(aa, bb, cc, dd, X[ 4], 6); dd = FF3(dd, aa, bb, cc, X[ 9], 15); cc = FF3(cc, dd, aa, bb, X[ 1], 13); bb = FF3(bb, cc, dd, aa, X[ 2], 11); // // Parallel round 3 // aa = FF2(aa, bb, cc, dd, X[15], 9); dd = FF2(dd, aa, bb, cc, X[ 5], 7); cc = FF2(cc, dd, aa, bb, X[ 1], 15); bb = FF2(bb, cc, dd, aa, X[ 3], 11); aa = FF2(aa, bb, cc, dd, X[ 7], 8); dd = FF2(dd, aa, bb, cc, X[14], 6); cc = FF2(cc, dd, aa, bb, X[ 6], 6); bb = FF2(bb, cc, dd, aa, X[ 9], 14); aa = FF2(aa, bb, cc, dd, X[11], 12); dd = FF2(dd, aa, bb, cc, X[ 8], 13); cc = FF2(cc, dd, aa, bb, X[12], 5); bb = FF2(bb, cc, dd, aa, X[ 2], 14); aa = FF2(aa, bb, cc, dd, X[10], 13); dd = FF2(dd, aa, bb, cc, X[ 0], 13); cc = FF2(cc, dd, aa, bb, X[ 4], 7); bb = FF2(bb, cc, dd, aa, X[13], 5); // // Parallel round 4 // aa = FF1(aa, bb, cc, dd, X[ 8], 15); dd = FF1(dd, aa, bb, cc, X[ 6], 5); cc = FF1(cc, dd, aa, bb, X[ 4], 8); bb = FF1(bb, cc, dd, aa, X[ 1], 11); aa = FF1(aa, bb, cc, dd, X[ 3], 14); dd = FF1(dd, aa, bb, cc, X[11], 14); cc = FF1(cc, dd, aa, bb, X[15], 6); bb = FF1(bb, cc, dd, aa, X[ 0], 14); aa = FF1(aa, bb, cc, dd, X[ 5], 6); dd = FF1(dd, aa, bb, cc, X[12], 9); cc = FF1(cc, dd, aa, bb, X[ 2], 12); bb = FF1(bb, cc, dd, aa, X[13], 9); aa = FF1(aa, bb, cc, dd, X[ 9], 12); dd = FF1(dd, aa, bb, cc, X[ 7], 5); cc = FF1(cc, dd, aa, bb, X[10], 15); bb = FF1(bb, cc, dd, aa, X[14], 8); dd += c + H1; // final result for H0 // // combine the results // H1 = H2 + d + aa; H2 = H3 + a + bb; H3 = H0 + b + cc; H0 = dd; // // reset the offset and clean out the word buffer. // xOff = 0; for (int i = 0; i != X.Length; i++) { X[i] = 0; } } public override IMemoable Copy() { return new RipeMD128Digest(this); } public override void Reset(IMemoable other) { RipeMD128Digest d = (RipeMD128Digest)other; CopyIn(d); } } }
// 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.Globalization; /// <summary> /// System.Globalization.StringInfo.GetTestElementEnumerator(string,Int32) /// </summary> public class StringInfoGetTextElementEnumerator2 { private const int c_MINI_STRING_LENGTH = 8; private const int c_MAX_STRING_LENGTH = 256; #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: The argument is a random string,and start at a random index"); try { string str = TestLibrary.Generator.GetString(-55, true, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH); int len = str.Length; int index = this.GetInt32(8, len); TextElementEnumerator TextElementEnumerator = StringInfo.GetTextElementEnumerator(str, index); TextElementEnumerator.MoveNext(); for (int i = 0; i < len - index; i++) { if (TextElementEnumerator.Current.ToString() != str[i + index].ToString()) { TestLibrary.TestFramework.LogError("001", "The result is not the value as expected,the str is: " + str[i + index]); retVal = false; } TextElementEnumerator.MoveNext(); } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: The string has a surrogate pair"); try { string str = "\uDBFF\uDFFF"; TextElementEnumerator TextElementEnumerator = StringInfo.GetTextElementEnumerator("s\uDBFF\uDFFF$", 1); TextElementEnumerator.MoveNext(); if (TextElementEnumerator.Current.ToString() != str) { TestLibrary.TestFramework.LogError("003", "The result is not the value as expected,the current is: " + TextElementEnumerator.Current.ToString()); retVal = false; } TextElementEnumerator.MoveNext(); if (TextElementEnumerator.Current.ToString() != "$") { TestLibrary.TestFramework.LogError("004", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("005", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: The string has a combining character"); try { string str = "a\u20D1"; TextElementEnumerator TextElementEnumerator = StringInfo.GetTextElementEnumerator("13229^a\u20D1a", 6); TextElementEnumerator.MoveNext(); if (TextElementEnumerator.Current.ToString() != str) { TestLibrary.TestFramework.LogError("006", "The result is not the value as expected,the current is: " + TextElementEnumerator.Current.ToString()); retVal = false; } TextElementEnumerator.MoveNext(); if (TextElementEnumerator.Current.ToString() != "a") { TestLibrary.TestFramework.LogError("007", "The result is not the value as expected,the current is: " + TextElementEnumerator.Current.ToString()); retVal = false; } if (TextElementEnumerator.MoveNext()) { TestLibrary.TestFramework.LogError("008", "The result is not the value as expected,the current is: " + TextElementEnumerator.Current.ToString()); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("009", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: The string is a null reference"); try { string str = null; TextElementEnumerator TextElementEnumerator = StringInfo.GetTextElementEnumerator(str, 0); TestLibrary.TestFramework.LogError("101", "The ArgumentNullException was not thrown as expected"); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2: The index is out of the range of the string"); try { string str = "dur8&p!"; TextElementEnumerator TextElementEnumerator = StringInfo.GetTextElementEnumerator(str, 10); TestLibrary.TestFramework.LogError("103", "The ArgumentOutOfRangeException was not thrown as expected"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest3: The index is a negative number"); try { string str = "dur8&p!"; TextElementEnumerator TextElementEnumerator = StringInfo.GetTextElementEnumerator(str, -10); TestLibrary.TestFramework.LogError("105", "The ArgumentOutOfRangeException was not thrown as expected"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("106", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #endregion public static int Main() { StringInfoGetTextElementEnumerator2 test = new StringInfoGetTextElementEnumerator2(); TestLibrary.TestFramework.BeginTestCase("StringInfoGetTextElementEnumerator2"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } private Int32 GetInt32(Int32 minValue, Int32 maxValue) { try { if (minValue == maxValue) { return minValue; } if (minValue < maxValue) { return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue); } } catch { throw; } return minValue; } }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace System.ServiceModel.Channels { using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime; using System.ServiceModel; using System.ServiceModel.Diagnostics; using System.ServiceModel.Dispatcher; using System.Threading; using System.ServiceModel.Diagnostics.Application; class DatagramAdapter { internal delegate T Source<T>(); internal static IOutputChannel GetOutputChannel(Source<IOutputSessionChannel> channelSource, IDefaultCommunicationTimeouts timeouts) { return new OutputDatagramAdapterChannel(channelSource, timeouts); } internal static IRequestChannel GetRequestChannel(Source<IRequestSessionChannel> channelSource, IDefaultCommunicationTimeouts timeouts) { return new RequestDatagramAdapterChannel(channelSource, timeouts); } internal static IChannelListener<IInputChannel> GetInputListener(IChannelListener<IInputSessionChannel> inner, ServiceThrottle throttle, IDefaultCommunicationTimeouts timeouts) { return new InputDatagramAdapterListener(inner, throttle, timeouts); } internal static IChannelListener<IReplyChannel> GetReplyListener(IChannelListener<IReplySessionChannel> inner, ServiceThrottle throttle, IDefaultCommunicationTimeouts timeouts) { return new ReplyDatagramAdapterListener(inner, throttle, timeouts); } abstract class DatagramAdapterListenerBase<TChannel, TSessionChannel, ItemType> : DelegatingChannelListener<TChannel>, ISessionThrottleNotification where TChannel : class, IChannel where TSessionChannel : class, IChannel where ItemType : class { static AsyncCallback acceptCallbackDelegate = Fx.ThunkCallback(new AsyncCallback(AcceptCallbackStatic)); static Action<object> channelPumpDelegate = new Action<object>(ChannelPump); Action channelPumpAfterExceptionDelegate; SessionChannelCollection channels; IChannelListener<TSessionChannel> listener; ServiceThrottle throttle; int usageCount; // When this goes to zero we Abort all the session channels. bool acceptLoopDone; IWaiter waiter; protected DatagramAdapterListenerBase(IChannelListener<TSessionChannel> listener, ServiceThrottle throttle, IDefaultCommunicationTimeouts timeouts) : base(timeouts, listener) { if (listener == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("listener"); } this.channels = new SessionChannelCollection(this.ThisLock); this.listener = listener; this.throttle = throttle; this.channelPumpAfterExceptionDelegate = new Action(this.ChannelPump); } internal SessionChannelCollection Channels { get { return this.channels; } } new internal object ThisLock { get { return base.ThisLock; } } protected abstract IAsyncResult CallBeginReceive(TSessionChannel channel, AsyncCallback callback, object state); protected abstract ItemType CallEndReceive(TSessionChannel channel, IAsyncResult result); protected abstract void Enqueue(ItemType item, Action callback); protected abstract void Enqueue(Exception exception, Action callback); static void AcceptCallbackStatic(IAsyncResult result) { ((DatagramAdapterListenerBase<TChannel, TSessionChannel, ItemType>)result.AsyncState).AcceptCallback(result); } void AcceptCallback(IAsyncResult result) { if (!result.CompletedSynchronously && this.FinishAccept(result)) { this.ChannelPump(); } } void AcceptLoopDone() { lock (this.ThisLock) { if (this.acceptLoopDone) { Fx.Assert("DatagramAdapter Accept loop is already done"); } this.acceptLoopDone = true; if (this.waiter != null) { this.waiter.Signal(); } } } static void ChannelPump(object state) { ((DatagramAdapterListenerBase<TChannel, TSessionChannel, ItemType>)state).ChannelPump(); } void ChannelPump() { while (this.listener.State == CommunicationState.Opened) { IAsyncResult result = null; Exception exception = null; try { result = this.listener.BeginAcceptChannel(TimeSpan.MaxValue, acceptCallbackDelegate, this); } catch (ObjectDisposedException e) { DiagnosticUtility.TraceHandledException(e, TraceEventType.Information); } catch (CommunicationException e) { DiagnosticUtility.TraceHandledException(e, TraceEventType.Information); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } exception = e; } if (exception != null) { this.Enqueue(exception, channelPumpAfterExceptionDelegate); break; } else if (!result.CompletedSynchronously || !this.FinishAccept(result)) { break; } } } bool FinishAccept(IAsyncResult result) { TSessionChannel channel = null; Exception exception = null; try { channel = this.listener.EndAcceptChannel(result); } catch (ObjectDisposedException e) { DiagnosticUtility.TraceHandledException(e, TraceEventType.Information); } catch (CommunicationException e) { DiagnosticUtility.TraceHandledException(e, TraceEventType.Information); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } exception = e; } if (exception != null) { this.Enqueue(exception, channelPumpAfterExceptionDelegate); } else if (channel == null) { this.AcceptLoopDone(); } else { if (this.State == CommunicationState.Opened) { DatagramAdapterReceiver.Pump(this, channel); } else { try { channel.Close(); } catch (CommunicationException e) { DiagnosticUtility.TraceHandledException(e, TraceEventType.Information); } catch (TimeoutException e) { if (TD.CloseTimeoutIsEnabled()) { TD.CloseTimeout(e.Message); } DiagnosticUtility.TraceHandledException(e, TraceEventType.Information); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } exception = e; } if (exception != null) { this.Enqueue(exception, channelPumpAfterExceptionDelegate); } } } return (channel != null) && this.throttle.AcquireSession(this); } internal void DecrementUsageCount() { bool done; lock (this.ThisLock) { this.usageCount--; done = this.usageCount == 0; } if (done) { this.channels.AbortChannels(); } } internal void IncrementUsageCount() { lock (this.ThisLock) { this.usageCount++; } } protected override void OnOpen(TimeSpan timeout) { base.OnOpen(timeout); ActionItem.Schedule(channelPumpDelegate, this); } protected override void OnEndOpen(IAsyncResult result) { base.OnEndOpen(result); ActionItem.Schedule(channelPumpDelegate, this); } public void ThrottleAcquired() { ActionItem.Schedule(DatagramAdapterListenerBase<TChannel, TSessionChannel, ItemType>.channelPumpDelegate, this); } protected override void OnClose(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); base.OnClose(timeoutHelper.RemainingTime()); this.WaitForAcceptLoop(timeoutHelper.RemainingTime()); } protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return new ChainedAsyncResult(timeout, callback, state, base.OnBeginClose, base.OnEndClose, this.BeginWaitForAcceptLoop, this.EndWaitForAcceptLoop); } protected override void OnEndClose(IAsyncResult result) { ChainedAsyncResult.End(result); } void WaitForAcceptLoop(TimeSpan timeout) { SyncWaiter waiter = null; lock (this.ThisLock) { if (!this.acceptLoopDone) { waiter = new SyncWaiter(this); this.waiter = waiter; } } if (waiter != null) { waiter.Wait(timeout); } } IAsyncResult BeginWaitForAcceptLoop(TimeSpan timeout, AsyncCallback callback, object state) { AsyncWaiter waiter = null; lock (this.ThisLock) { if (!this.acceptLoopDone) { waiter = new AsyncWaiter(timeout, callback, state); this.waiter = waiter; } } if (waiter != null) { return waiter; } else { return new CompletedAsyncResult(callback, state); } } void EndWaitForAcceptLoop(IAsyncResult result) { if (result is CompletedAsyncResult) { CompletedAsyncResult.End(result); } else { AsyncWaiter.End(result); } } class DatagramAdapterReceiver { static AsyncCallback receiveCallbackDelegate = Fx.ThunkCallback(new AsyncCallback(ReceiveCallbackStatic)); static Action<object> startNextReceiveDelegate = new Action<object>(StartNextReceive); static EventHandler faultedDelegate; DatagramAdapterListenerBase<TChannel, TSessionChannel, ItemType> parent; TSessionChannel channel; Action itemDequeuedDelegate; ServiceModelActivity activity; DatagramAdapterReceiver(DatagramAdapterListenerBase<TChannel, TSessionChannel, ItemType> parent, TSessionChannel channel) { this.parent = parent; this.channel = channel; if (DiagnosticUtility.ShouldUseActivity) { activity = ServiceModelActivity.Current; } if (DatagramAdapterReceiver.faultedDelegate == null) { DatagramAdapterReceiver.faultedDelegate = new EventHandler(FaultedCallback); } this.channel.Faulted += DatagramAdapterReceiver.faultedDelegate; this.channel.Closed += new EventHandler(this.ClosedCallback); this.itemDequeuedDelegate = this.StartNextReceive; this.parent.channels.Add(channel); try { channel.Open(); } catch (CommunicationException e) { DiagnosticUtility.TraceHandledException(e, TraceEventType.Information); } catch (TimeoutException e) { if (TD.OpenTimeoutIsEnabled()) { TD.OpenTimeout(e.Message); } DiagnosticUtility.TraceHandledException(e, TraceEventType.Information); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } if (DiagnosticUtility.ShouldTraceWarning) { TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.FailedToOpenIncomingChannel, SR.GetString(SR.TraceCodeFailedToOpenIncomingChannel)); } channel.Abort(); this.parent.Enqueue(e, null); } } void ClosedCallback(object sender, EventArgs e) { TSessionChannel channel = (TSessionChannel)sender; this.parent.channels.Remove(channel); this.parent.throttle.DeactivateChannel(); } static void FaultedCallback(object sender, EventArgs e) { ((IChannel)sender).Abort(); } static void StartNextReceive(object state) { ((DatagramAdapterReceiver)state).StartNextReceive(); } void StartNextReceive() { if (this.channel.State == CommunicationState.Opened) { using (ServiceModelActivity.BoundOperation(this.activity)) { IAsyncResult result = null; Exception exception = null; try { result = this.parent.CallBeginReceive(this.channel, receiveCallbackDelegate, this); } catch (ObjectDisposedException e) { DiagnosticUtility.TraceHandledException(e, TraceEventType.Information); } catch (CommunicationException e) { DiagnosticUtility.TraceHandledException(e, TraceEventType.Information); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } exception = e; } if (exception != null) { this.parent.Enqueue(exception, this.itemDequeuedDelegate); } else if (result.CompletedSynchronously) { this.FinishReceive(result); } } } } internal static void Pump(DatagramAdapterListenerBase<TChannel, TSessionChannel, ItemType> listener, TSessionChannel channel) { DatagramAdapterReceiver receiver = new DatagramAdapterReceiver(listener, channel); ActionItem.Schedule(startNextReceiveDelegate, receiver); } static void ReceiveCallbackStatic(IAsyncResult result) { if (!result.CompletedSynchronously) { ((DatagramAdapterReceiver)result.AsyncState).FinishReceive(result); } } void FinishReceive(IAsyncResult result) { ItemType item = null; Exception exception = null; try { item = this.parent.CallEndReceive(this.channel, result); } catch (ObjectDisposedException e) { DiagnosticUtility.TraceHandledException(e, TraceEventType.Information); } catch (CommunicationException e) { DiagnosticUtility.TraceHandledException(e, TraceEventType.Information); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } exception = e; } if (exception != null) { this.parent.Enqueue(exception, this.itemDequeuedDelegate); } else if (item != null) { this.parent.Enqueue(item, this.itemDequeuedDelegate); } else { try { this.channel.Close(); } catch (CommunicationException e) { DiagnosticUtility.TraceHandledException(e, TraceEventType.Information); } catch (TimeoutException e) { if (TD.CloseTimeoutIsEnabled()) { TD.CloseTimeout(e.Message); } DiagnosticUtility.TraceHandledException(e, TraceEventType.Information); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } exception = e; } if (exception != null) { this.parent.Enqueue(exception, this.itemDequeuedDelegate); } } } } internal class SessionChannelCollection : SynchronizedCollection<TSessionChannel> { EventHandler onChannelClosed; EventHandler onChannelFaulted; internal SessionChannelCollection(object syncRoot) : base(syncRoot) { this.onChannelClosed = new EventHandler(OnChannelClosed); this.onChannelFaulted = new EventHandler(OnChannelFaulted); } public void AbortChannels() { lock (this.SyncRoot) { for (int i = this.Count - 1; i >= 0; i--) { this[i].Abort(); } } } void AddingChannel(TSessionChannel channel) { channel.Faulted += this.onChannelFaulted; channel.Closed += this.onChannelClosed; } void RemovingChannel(TSessionChannel channel) { channel.Faulted -= this.onChannelFaulted; channel.Closed -= this.onChannelClosed; channel.Abort(); } void OnChannelClosed(object sender, EventArgs args) { TSessionChannel channel = (TSessionChannel)sender; this.Remove(channel); } void OnChannelFaulted(object sender, EventArgs args) { TSessionChannel channel = (TSessionChannel)sender; this.Remove(channel); } protected override void ClearItems() { List<TSessionChannel> items = this.Items; for (int i = 0; i < items.Count; i++) { this.RemovingChannel(items[i]); } base.ClearItems(); } protected override void InsertItem(int index, TSessionChannel item) { this.AddingChannel(item); base.InsertItem(index, item); } protected override void RemoveItem(int index) { TSessionChannel oldItem = this.Items[index]; base.RemoveItem(index); this.RemovingChannel(oldItem); } protected override void SetItem(int index, TSessionChannel item) { TSessionChannel oldItem = this.Items[index]; this.AddingChannel(item); base.SetItem(index, item); this.RemovingChannel(oldItem); } } internal interface IWaiter { void Signal(); } internal class AsyncWaiter : AsyncResult, IWaiter { static Action<object> timerCallback = new Action<object>(AsyncWaiter.TimerCallback); bool timedOut; readonly IOThreadTimer timer; internal AsyncWaiter(TimeSpan timeout, AsyncCallback callback, object state) : base(callback, state) { if (timeout != TimeSpan.MaxValue) { this.timer = new IOThreadTimer(timerCallback, this, false); this.timer.Set(timeout); } } internal static bool End(IAsyncResult result) { AsyncResult.End<AsyncWaiter>(result); return !((AsyncWaiter)result).timedOut; } public void Signal() { if ((this.timer == null) || this.timer.Cancel()) { this.Complete(false); } } static void TimerCallback(object state) { AsyncWaiter waiter = (AsyncWaiter)state; waiter.timedOut = true; waiter.Complete(false); } } internal class SyncWaiter : IWaiter { bool didSignal; object thisLock; ManualResetEvent wait; internal SyncWaiter(object thisLock) { this.thisLock = thisLock; } object ThisLock { get { return this.thisLock; } } public void Signal() { lock (this.ThisLock) { this.didSignal = true; if (this.wait != null) { this.wait.Set(); } } } public bool Wait(TimeSpan timeout) { lock (this.ThisLock) { if (!this.didSignal) { this.wait = new ManualResetEvent(false); } } if ((this.wait == null) || TimeoutHelper.WaitOne(this.wait, timeout)) { if (this.wait != null) { this.wait.Close(); this.wait = null; } return true; } else { lock (this.ThisLock) { this.wait.Close(); this.wait = null; } return false; } } } } class InputDatagramAdapterListener : DatagramAdapterListenerBase<IInputChannel, IInputSessionChannel, Message> { SingletonChannelAcceptor<IInputChannel, InputChannel, Message> acceptor; internal InputDatagramAdapterListener(IChannelListener<IInputSessionChannel> listener, ServiceThrottle throttle, IDefaultCommunicationTimeouts timeouts) : base(listener, throttle, timeouts) { this.acceptor = new InputDatagramAdapterAcceptor(this); this.Acceptor = this.acceptor; } protected override IAsyncResult CallBeginReceive(IInputSessionChannel channel, AsyncCallback callback, object state) { return channel.BeginReceive(TimeSpan.MaxValue, callback, state); } protected override Message CallEndReceive(IInputSessionChannel channel, IAsyncResult result) { return channel.EndReceive(result); } protected override void Enqueue(Message message, Action callback) { this.acceptor.Enqueue(message, callback); } protected override void Enqueue(Exception exception, Action callback) { this.acceptor.Enqueue(exception, callback); } } class InputDatagramAdapterAcceptor : InputChannelAcceptor { internal InputDatagramAdapterListener listener; internal InputDatagramAdapterAcceptor(InputDatagramAdapterListener listener) : base(listener) { this.listener = listener; } protected override InputChannel OnCreateChannel() { return new InputDatagramAdapterChannel(this.listener); } } class InputDatagramAdapterChannel : InputChannel { InputDatagramAdapterListener listener; internal InputDatagramAdapterChannel(InputDatagramAdapterListener listener) : base(listener, null) { this.listener = listener; } public override T GetProperty<T>() { lock (this.listener.ThisLock) { if (this.listener.Channels.Count > 0) { return this.listener.Channels[0].GetProperty<T>(); } else { return null; } } } protected override void OnOpening() { this.listener.IncrementUsageCount(); base.OnOpening(); } protected override void OnClosed() { base.OnClosed(); this.listener.DecrementUsageCount(); } } class ReplyDatagramAdapterListener : DatagramAdapterListenerBase<IReplyChannel, IReplySessionChannel, RequestContext> { SingletonChannelAcceptor<IReplyChannel, ReplyChannel, RequestContext> acceptor; internal ReplyDatagramAdapterListener(IChannelListener<IReplySessionChannel> listener, ServiceThrottle throttle, IDefaultCommunicationTimeouts timeouts) : base(listener, throttle, timeouts) { this.acceptor = new ReplyDatagramAdapterAcceptor(this); this.Acceptor = this.acceptor; } protected override IAsyncResult CallBeginReceive(IReplySessionChannel channel, AsyncCallback callback, object state) { return channel.BeginReceiveRequest(TimeSpan.MaxValue, callback, state); } protected override RequestContext CallEndReceive(IReplySessionChannel channel, IAsyncResult result) { return channel.EndReceiveRequest(result); } protected override void Enqueue(RequestContext request, Action callback) { this.acceptor.Enqueue(request, callback); } protected override void Enqueue(Exception exception, Action callback) { this.acceptor.Enqueue(exception, callback); } } class ReplyDatagramAdapterAcceptor : ReplyChannelAcceptor { internal ReplyDatagramAdapterListener listener; internal ReplyDatagramAdapterAcceptor(ReplyDatagramAdapterListener listener) : base(listener) { this.listener = listener; } protected override ReplyChannel OnCreateChannel() { return new ReplyDatagramAdapterChannel(this.listener); } } class ReplyDatagramAdapterChannel : ReplyChannel { ReplyDatagramAdapterListener listener; internal ReplyDatagramAdapterChannel(ReplyDatagramAdapterListener listener) : base(listener, null) { this.listener = listener; } public override T GetProperty<T>() { lock (this.listener.ThisLock) { if (this.listener.Channels.Count > 0) { return this.listener.Channels[0].GetProperty<T>(); } else { return null; } } } protected override void OnOpening() { this.listener.IncrementUsageCount(); base.OnOpening(); } protected override void OnClosed() { base.OnClosed(); this.listener.DecrementUsageCount(); } } abstract class DatagramAdapterChannelBase<TSessionChannel> : CommunicationObject, IChannel where TSessionChannel : class, IChannel { ChannelParameterCollection channelParameters; Source<TSessionChannel> channelSource; TSessionChannel channel; TimeSpan defaultCloseTimeout; TimeSpan defaultOpenTimeout; TimeSpan defaultSendTimeout; List<TSessionChannel> activeChannels; protected DatagramAdapterChannelBase(Source<TSessionChannel> channelSource, IDefaultCommunicationTimeouts timeouts) { if (channelSource == null) { Fx.Assert("DatagramAdapterChannelBase.ctor: (channelSource == null)"); throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("channelSource"); } this.channelParameters = new ChannelParameterCollection(this); this.channelSource = channelSource; this.defaultCloseTimeout = timeouts.CloseTimeout; this.defaultOpenTimeout = timeouts.OpenTimeout; this.defaultSendTimeout = timeouts.SendTimeout; this.activeChannels = new List<TSessionChannel>(); } protected ChannelParameterCollection ChannelParameters { get { return this.channelParameters; } } protected override TimeSpan DefaultCloseTimeout { get { return this.defaultCloseTimeout; } } protected override TimeSpan DefaultOpenTimeout { get { return this.defaultOpenTimeout; } } protected TimeSpan DefaultSendTimeout { get { return this.defaultSendTimeout; } } protected override void OnOpen(TimeSpan timeout) { } protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { return new CompletedAsyncResult(callback, state); } protected override void OnEndOpen(IAsyncResult result) { CompletedAsyncResult.End(result); } protected TSessionChannel TakeChannel() { TSessionChannel channel; lock (this.ThisLock) { this.ThrowIfDisposedOrNotOpen(); if (this.channel == null) { channel = this.channelSource(); } else { channel = this.channel; this.channel = null; } this.activeChannels.Add(channel); } return channel; } protected bool ReturnChannel(TSessionChannel channel) { lock (this.ThisLock) { if (this.channel == null) { this.activeChannels.Remove(channel); this.channel = channel; return true; } } return false; } protected void RemoveChannel(TSessionChannel channel) { lock (this.ThisLock) { this.activeChannels.Remove(channel); } } public T GetProperty<T>() where T : class { if (typeof(T) == typeof(ChannelParameterCollection)) { return (T)(object)this.channelParameters; } TSessionChannel inner = channelSource(); inner.Abort(); return inner.GetProperty<T>(); } protected override void OnAbort() { TSessionChannel channel; TSessionChannel[] activeChannels; lock (this.ThisLock) { channel = this.channel; activeChannels = new TSessionChannel[this.activeChannels.Count]; this.activeChannels.CopyTo(activeChannels); } if (channel != null) channel.Abort(); foreach (TSessionChannel currentChannel in activeChannels) currentChannel.Abort(); } protected override void OnClose(TimeSpan timeout) { TSessionChannel channel; TSessionChannel[] activeChannels; lock (this.ThisLock) { channel = this.channel; activeChannels = new TSessionChannel[this.activeChannels.Count]; this.activeChannels.CopyTo(activeChannels); } TimeoutHelper helper = new TimeoutHelper(timeout); if (channel != null) channel.Close(helper.RemainingTime()); foreach (TSessionChannel currentChannel in activeChannels) currentChannel.Close(helper.RemainingTime()); } protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { TSessionChannel channel; TSessionChannel[] activeChannels; lock (this.ThisLock) { channel = this.channel; activeChannels = new TSessionChannel[this.activeChannels.Count]; this.activeChannels.CopyTo(activeChannels); } if (this.channel == null) return new CloseCollectionAsyncResult(timeout, callback, state, activeChannels); else return new ChainedCloseAsyncResult(timeout, callback, state, channel.BeginClose, channel.EndClose, activeChannels); } protected override void OnEndClose(IAsyncResult result) { if (result is CloseCollectionAsyncResult) CloseCollectionAsyncResult.End(result); else ChainedCloseAsyncResult.End(result); } } class OutputDatagramAdapterChannel : DatagramAdapterChannelBase<IOutputSessionChannel>, IOutputChannel { EndpointAddress remoteAddress; Uri via; internal OutputDatagramAdapterChannel(Source<IOutputSessionChannel> channelSource, IDefaultCommunicationTimeouts timeouts) : base(channelSource, timeouts) { IOutputSessionChannel inner = channelSource(); try { if (inner == null) { Fx.Assert("OutputDatagramAdapterChannel.ctor: (inner == null)"); } this.remoteAddress = inner.RemoteAddress; this.via = inner.Via; inner.Close(); } finally { inner.Abort(); } } public EndpointAddress RemoteAddress { get { return this.remoteAddress; } } public Uri Via { get { return this.via; } } public void Send(Message message) { this.Send(message, this.DefaultSendTimeout); } public void Send(Message message, TimeSpan timeout) { TimeoutHelper helper = new TimeoutHelper(timeout); IOutputSessionChannel channel = this.TakeChannel(); bool throwing = true; try { if (channel.State == CommunicationState.Created) { this.ChannelParameters.PropagateChannelParameters(channel); channel.Open(helper.RemainingTime()); } channel.Send(message, helper.RemainingTime()); throwing = false; } finally { if (throwing) { channel.Abort(); this.RemoveChannel(channel); } } if (this.ReturnChannel(channel)) return; try { channel.Close(helper.RemainingTime()); } finally { this.RemoveChannel(channel); } } public IAsyncResult BeginSend(Message message, AsyncCallback callback, object state) { return this.BeginSend(message, this.DefaultSendTimeout, callback, state); } public IAsyncResult BeginSend(Message message, TimeSpan timeout, AsyncCallback callback, object state) { return new SendAsyncResult(this, message, timeout, callback, state); } public void EndSend(IAsyncResult result) { SendAsyncResult.End(result); } class SendAsyncResult : AsyncResult { OutputDatagramAdapterChannel adapter; Message message; TimeoutHelper timeoutHelper; bool hasCompletedAsynchronously = true; public SendAsyncResult(OutputDatagramAdapterChannel adapter, Message message, TimeSpan timeout, AsyncCallback callback, object state) : base(callback, state) { this.adapter = adapter; this.message = message; this.timeoutHelper = new TimeoutHelper(timeout); IOutputSessionChannel channel = this.adapter.TakeChannel(); try { if (channel.State == CommunicationState.Created) { this.adapter.ChannelParameters.PropagateChannelParameters(channel); channel.BeginOpen(this.timeoutHelper.RemainingTime(), Fx.ThunkCallback(new AsyncCallback(OnOpenComplete)), channel); } else { channel.BeginSend(message, this.timeoutHelper.RemainingTime(), Fx.ThunkCallback(new AsyncCallback(OnSendComplete)), channel); } } catch { channel.Abort(); this.adapter.RemoveChannel(channel); throw; } } void OnOpenComplete(IAsyncResult result) { this.hasCompletedAsynchronously &= result.CompletedSynchronously; IOutputSessionChannel channel = (IOutputSessionChannel)result.AsyncState; try { channel.EndOpen(result); channel.BeginSend(this.message, this.timeoutHelper.RemainingTime(), Fx.ThunkCallback(new AsyncCallback(OnSendComplete)), channel); } catch (Exception exception) { if (Fx.IsFatal(exception)) { throw; } channel.Abort(); this.adapter.RemoveChannel(channel); this.Complete(this.hasCompletedAsynchronously, exception); } } void OnSendComplete(IAsyncResult result) { this.hasCompletedAsynchronously &= result.CompletedSynchronously; IOutputSessionChannel channel = (IOutputSessionChannel)result.AsyncState; try { channel.EndSend(result); } catch (Exception exception) { if (Fx.IsFatal(exception)) { throw; } channel.Abort(); this.adapter.RemoveChannel(channel); this.Complete(this.hasCompletedAsynchronously, exception); return; } if (this.adapter.ReturnChannel(channel)) { this.Complete(this.hasCompletedAsynchronously); return; } try { channel.BeginClose(this.timeoutHelper.RemainingTime(), Fx.ThunkCallback(new AsyncCallback(OnCloseComplete)), channel); } catch (Exception exception) { if (Fx.IsFatal(exception)) { throw; } this.adapter.RemoveChannel(channel); this.Complete(this.hasCompletedAsynchronously, exception); } } void OnCloseComplete(IAsyncResult result) { this.hasCompletedAsynchronously &= result.CompletedSynchronously; IOutputSessionChannel channel = (IOutputSessionChannel)result.AsyncState; Exception exception = null; try { channel.EndClose(result); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } exception = e; } this.adapter.RemoveChannel(channel); this.Complete(this.hasCompletedAsynchronously, exception); } public static void End(IAsyncResult result) { AsyncResult.End<SendAsyncResult>(result); } } } class RequestDatagramAdapterChannel : DatagramAdapterChannelBase<IRequestSessionChannel>, IRequestChannel { EndpointAddress remoteAddress; Uri via; internal RequestDatagramAdapterChannel(Source<IRequestSessionChannel> channelSource, IDefaultCommunicationTimeouts timeouts) : base(channelSource, timeouts) { IRequestSessionChannel inner = channelSource(); try { if (inner == null) { Fx.Assert("RequestDatagramAdapterChannel.ctor: (inner == null)"); } this.remoteAddress = inner.RemoteAddress; this.via = inner.Via; inner.Close(); } finally { inner.Abort(); } } public EndpointAddress RemoteAddress { get { return this.remoteAddress; } } public Uri Via { get { return this.via; } } public Message Request(Message request) { return this.Request(request, this.DefaultSendTimeout); } public Message Request(Message request, TimeSpan timeout) { TimeoutHelper helper = new TimeoutHelper(timeout); IRequestSessionChannel channel = this.TakeChannel(); bool throwing = true; Message reply = null; try { if (channel.State == CommunicationState.Created) { this.ChannelParameters.PropagateChannelParameters(channel); channel.Open(helper.RemainingTime()); } reply = channel.Request(request, helper.RemainingTime()); throwing = false; } finally { if (throwing) { channel.Abort(); this.RemoveChannel(channel); } } if (this.ReturnChannel(channel)) return reply; try { channel.Close(helper.RemainingTime()); } finally { this.RemoveChannel(channel); } return reply; } public IAsyncResult BeginRequest(Message message, AsyncCallback callback, object state) { return this.BeginRequest(message, this.DefaultSendTimeout, callback, state); } public IAsyncResult BeginRequest(Message message, TimeSpan timeout, AsyncCallback callback, object state) { return new RequestAsyncResult(this, message, timeout, callback, state); } public Message EndRequest(IAsyncResult result) { return RequestAsyncResult.End(result); } class RequestAsyncResult : AsyncResult { RequestDatagramAdapterChannel adapter; Message message; Message reply = null; TimeoutHelper timeoutHelper; bool hasCompletedAsynchronously = true; public RequestAsyncResult(RequestDatagramAdapterChannel adapter, Message message, TimeSpan timeout, AsyncCallback callback, object state) : base(callback, state) { this.adapter = adapter; this.message = message; this.timeoutHelper = new TimeoutHelper(timeout); IRequestSessionChannel channel = this.adapter.TakeChannel(); try { if (channel.State == CommunicationState.Created) { this.adapter.ChannelParameters.PropagateChannelParameters(channel); channel.BeginOpen(this.timeoutHelper.RemainingTime(), Fx.ThunkCallback(new AsyncCallback(OnOpenComplete)), channel); } else { channel.BeginRequest(message, this.timeoutHelper.RemainingTime(), Fx.ThunkCallback(new AsyncCallback(OnRequestComplete)), channel); } } catch { channel.Abort(); this.adapter.RemoveChannel(channel); throw; } } void OnOpenComplete(IAsyncResult result) { this.hasCompletedAsynchronously &= result.CompletedSynchronously; IRequestSessionChannel channel = (IRequestSessionChannel)result.AsyncState; try { channel.EndOpen(result); channel.BeginRequest(this.message, this.timeoutHelper.RemainingTime(), Fx.ThunkCallback(new AsyncCallback(OnRequestComplete)), channel); } catch (Exception exception) { if (Fx.IsFatal(exception)) { throw; } channel.Abort(); this.adapter.RemoveChannel(channel); this.Complete(this.hasCompletedAsynchronously, exception); } } void OnRequestComplete(IAsyncResult result) { this.hasCompletedAsynchronously &= result.CompletedSynchronously; IRequestSessionChannel channel = (IRequestSessionChannel)result.AsyncState; try { this.reply = channel.EndRequest(result); } catch (Exception exception) { if (Fx.IsFatal(exception)) { throw; } channel.Abort(); this.adapter.RemoveChannel(channel); this.Complete(this.hasCompletedAsynchronously, exception); return; } if (this.adapter.ReturnChannel(channel)) { this.Complete(this.hasCompletedAsynchronously); return; } try { channel.BeginClose(this.timeoutHelper.RemainingTime(), Fx.ThunkCallback(new AsyncCallback(OnCloseComplete)), channel); } catch (Exception exception) { if (Fx.IsFatal(exception)) { throw; } this.adapter.RemoveChannel(channel); this.Complete(this.hasCompletedAsynchronously, exception); } } void OnCloseComplete(IAsyncResult result) { this.hasCompletedAsynchronously &= result.CompletedSynchronously; IRequestSessionChannel channel = (IRequestSessionChannel)result.AsyncState; Exception exception = null; try { channel.EndClose(result); } catch (Exception e) { if (Fx.IsFatal(exception)) { throw; } exception = e; } this.adapter.RemoveChannel(channel); this.Complete(this.hasCompletedAsynchronously, exception); } public static Message End(IAsyncResult result) { RequestAsyncResult requestResult = AsyncResult.End<RequestAsyncResult>(result); return requestResult.reply; } } } } }
#region License // Distributed under the MIT License // ============================================================ // Copyright (c) 2019 Hotcakes Commerce, LLC // Copyright (c) 2020 Upendo Ventures, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, publish, distribute, // sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Web.UI.WebControls; using DotNetNuke.Entities.Modules; using DotNetNuke.Services.Localization; using Hotcakes.Commerce.Catalog; using Hotcakes.Commerce.Dnn.Utils; using Hotcakes.Commerce.Dnn.Web; using Hotcakes.Modules.Core.Models; using Newtonsoft.Json; namespace Hotcakes.Modules.ProductGrid { partial class Settings : HotcakesSettingsBase { protected override void OnInit(EventArgs e) { base.OnInit(e); btnAdd.Click += btnAdd_Click; rgProducts.RowDeleting += rgProducts_OnDeleteCommand; rgProducts.RowCommand += rgProducts_OnItemCommand; } public override void LoadSettings() { var viewText = Convert.ToString(ModuleSettings["View"]); ViewContentLabel.Text = LocalizeString("NoneSelectedText"); if (!string.IsNullOrEmpty(viewText)) { ViewComboBox.SelectedValue = viewText; ViewContentLabel.Text = viewText; } } public override void UpdateSettings() { var controller = new ModuleController(); controller.UpdateModuleSetting(ModuleId, "GridColumns", GridColumnsField.Text.Trim()); controller.UpdateModuleSetting(ModuleId, "View", ViewComboBox.SelectedValue); ModuleController.SynchronizeModule(ModuleId); } protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (!Page.IsPostBack) { LocalizeView(); var sortedProducts = GetSelectedProducts(); LoadItems(sortedProducts); int gridColumns; if (!int.TryParse(Convert.ToString(ModuleSettings["GridColumns"]), out gridColumns)) gridColumns = 3; GridColumnsField.Text = gridColumns.ToString(); // load the view names into the combobox ViewComboBox.Items.Add(new System.Web.UI.WebControls.ListItem(LocalizeString("NoneSelectedText"), string.Empty)); ViewComboBox.AppendDataBoundItems = true; ViewComboBox.DataSource = DnnPathHelper.GetViewNames("ProductGrid"); ViewComboBox.DataBind(); } } private void LocalizeView() { Localization.LocalizeGridView(ref rgProducts, LocalResourceFile); valGridColumns.ErrorMessage = LocalizeString("valGridColumns.ErrorMessage"); } private void LoadItems(SortedList<int, Product> list) { if (list != null) { // the list can contain null values for products in certain scenarios // (mainly in cases where there is orphaned or corrupt data) var safeList = list.Where(p => p.Value != null); // select products to bind to the UI var productModels = safeList.Select(i => new {i.Key, Value = new SingleProductViewModel(i.Value, HccApp)}) .OrderBy(i => i.Key); rgProducts.DataSource = productModels; rgProducts.DataBind(); } } private void SaveItems(SortedList<int, Product> sortedProducts) { var items = sortedProducts.ToDictionary(item => item.Key, item => item.Value.Bvin); SaveItems(items); } private void SaveItems(Dictionary<int, string> items) { var controller = new ModuleController(); controller.UpdateModuleSetting(ModuleId, "ProductList", JsonConvert.SerializeObject(items)); } private SortedList<int, Product> GetSelectedProducts() { var productBvins = GetProductBvins(); return GetProducts(productBvins); } private SortedList<int, Product> GetProducts(Dictionary<int, string> productBvins) { var sortedProducts = new SortedList<int, Product>(); if (productBvins.Count > 0) { var listProducts = HccApp.CatalogServices.Products.FindManyWithCache(productBvins.Values); foreach (var item in productBvins) { sortedProducts.Add(item.Key, listProducts.FirstOrDefault(p => p.Bvin == item.Value)); } } return sortedProducts; } private Dictionary<int, string> GetProductBvins() { Dictionary<int, string> productBvins = null; try { var productSettingsString = Convert.ToString(ModuleSettings["ProductList"]); productBvins = JsonConvert.DeserializeObject<Dictionary<int, string>>(productSettingsString) ?? new Dictionary<int, string>(); } catch { productBvins = new Dictionary<int, string>(); } return productBvins; } protected void btnAdd_Click(object sender, EventArgs e) { var products = HccApp.CatalogServices.Products.FindManyWithCache( ProductPicker.SelectedProducts.OfType<string>().ToList()); var sortedProducts = GetSelectedProducts(); foreach (var p in products) { sortedProducts.Add(sortedProducts.Keys.DefaultIfEmpty(0).Max() + 1, p); } SaveItems(sortedProducts); LoadItems(sortedProducts); } protected void rgProducts_OnDeleteCommand(object sender, GridViewDeleteEventArgs e) { var bvinsList = GetProductBvins(); var key = int.Parse(rgProducts.DataKeys[e.RowIndex].ToString(), NumberStyles.Integer); bvinsList.Remove(key); SaveItems(bvinsList); LoadItems(GetProducts(bvinsList)); } protected void rgProducts_OnItemCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName.Equals("Up") || e.CommandName.Equals("Down")) { var bvinsList = GetProductBvins(); var key = int.Parse(e.CommandArgument.ToString(), NumberStyles.Integer); int key2; if (e.CommandName.Equals("Up")) key2 = bvinsList.Where(i => i.Key < key) .DefaultIfEmpty(new KeyValuePair<int, string>(-1, null)) .Max(i => i.Key); else key2 = bvinsList.Where(i => i.Key > key) .DefaultIfEmpty(new KeyValuePair<int, string>(-1, null)) .Min(i => i.Key); if (key2 < 0) return; var val = bvinsList[key]; bvinsList[key] = bvinsList[key2]; bvinsList[key2] = val; SaveItems(bvinsList); LoadItems(GetProducts(bvinsList)); } } } }
// 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.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using NUnit.Framework; using osu.Framework.Audio.Track; using osu.Framework.Graphics.Textures; using osu.Framework.IO.Stores; using osu.Game.Beatmaps; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Beatmaps.Formats; using osu.Game.Beatmaps.Legacy; using osu.Game.IO; using osu.Game.IO.Serialization; using osu.Game.Rulesets.Catch; using osu.Game.Rulesets.Mania; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Objects.Types; using osu.Game.Rulesets.Osu; using osu.Game.Rulesets.Osu.Objects; using osu.Game.Rulesets.Taiko; using osu.Game.Skinning; using osu.Game.Tests.Resources; using osuTK; namespace osu.Game.Tests.Beatmaps.Formats { [TestFixture] public class LegacyBeatmapEncoderTest { private static readonly DllResourceStore beatmaps_resource_store = TestResources.GetStore(); private static IEnumerable<string> allBeatmaps = beatmaps_resource_store.GetAvailableResources().Where(res => res.EndsWith(".osu", StringComparison.Ordinal)); [TestCaseSource(nameof(allBeatmaps))] public void TestEncodeDecodeStability(string name) { var decoded = decodeFromLegacy(beatmaps_resource_store.GetStream(name), name); var decodedAfterEncode = decodeFromLegacy(encodeToLegacy(decoded), name); sort(decoded.beatmap); sort(decodedAfterEncode.beatmap); compareBeatmaps(decoded, decodedAfterEncode); } [TestCaseSource(nameof(allBeatmaps))] public void TestEncodeDecodeStabilityDoubleConvert(string name) { var decoded = decodeFromLegacy(beatmaps_resource_store.GetStream(name), name); var decodedAfterEncode = decodeFromLegacy(encodeToLegacy(decoded), name); // run an extra convert. this is expected to be stable. decodedAfterEncode.beatmap = convert(decodedAfterEncode.beatmap); sort(decoded.beatmap); sort(decodedAfterEncode.beatmap); compareBeatmaps(decoded, decodedAfterEncode); } [TestCaseSource(nameof(allBeatmaps))] public void TestEncodeDecodeStabilityWithNonLegacyControlPoints(string name) { var decoded = decodeFromLegacy(beatmaps_resource_store.GetStream(name), name); // we are testing that the transfer of relevant data to hitobjects (from legacy control points) sticks through encode/decode. // before the encode step, the legacy information is removed here. decoded.beatmap.ControlPointInfo = removeLegacyControlPointTypes(decoded.beatmap.ControlPointInfo); var decodedAfterEncode = decodeFromLegacy(encodeToLegacy(decoded), name); compareBeatmaps(decoded, decodedAfterEncode); ControlPointInfo removeLegacyControlPointTypes(ControlPointInfo controlPointInfo) { // emulate non-legacy control points by cloning the non-legacy portion. // the assertion is that the encoder can recreate this losslessly from hitobject data. Assert.IsInstanceOf<LegacyControlPointInfo>(controlPointInfo); var newControlPoints = new ControlPointInfo(); foreach (var point in controlPointInfo.AllControlPoints) { // completely ignore "legacy" types, which have been moved to HitObjects. // even though these would mostly be ignored by the Add call, they will still be available in groups, // which isn't what we want to be testing here. if (point is SampleControlPoint || point is DifficultyControlPoint) continue; newControlPoints.Add(point.Time, point.DeepClone()); } return newControlPoints; } } private void compareBeatmaps((IBeatmap beatmap, TestLegacySkin skin) expected, (IBeatmap beatmap, TestLegacySkin skin) actual) { // Check all control points that are still considered to be at a global level. Assert.That(expected.beatmap.ControlPointInfo.TimingPoints.Serialize(), Is.EqualTo(actual.beatmap.ControlPointInfo.TimingPoints.Serialize())); Assert.That(expected.beatmap.ControlPointInfo.EffectPoints.Serialize(), Is.EqualTo(actual.beatmap.ControlPointInfo.EffectPoints.Serialize())); // Check all hitobjects. Assert.That(expected.beatmap.HitObjects.Serialize(), Is.EqualTo(actual.beatmap.HitObjects.Serialize())); // Check skin. Assert.IsTrue(areComboColoursEqual(expected.skin.Configuration, actual.skin.Configuration)); } [Test] public void TestEncodeMultiSegmentSliderWithFloatingPointError() { var beatmap = new Beatmap { HitObjects = { new Slider { Position = new Vector2(0.6f), Path = new SliderPath(new[] { new PathControlPoint(Vector2.Zero, PathType.Bezier), new PathControlPoint(new Vector2(0.5f)), new PathControlPoint(new Vector2(0.51f)), // This is actually on the same position as the previous one in legacy beatmaps (truncated to int). new PathControlPoint(new Vector2(1f), PathType.Bezier), new PathControlPoint(new Vector2(2f)) }) }, } }; var decodedAfterEncode = decodeFromLegacy(encodeToLegacy((beatmap, new TestLegacySkin(beatmaps_resource_store, string.Empty))), string.Empty); var decodedSlider = (Slider)decodedAfterEncode.beatmap.HitObjects[0]; Assert.That(decodedSlider.Path.ControlPoints.Count, Is.EqualTo(5)); } private bool areComboColoursEqual(IHasComboColours a, IHasComboColours b) { // equal to null, no need to SequenceEqual if (a.ComboColours == null && b.ComboColours == null) return true; if (a.ComboColours == null || b.ComboColours == null) return false; return a.ComboColours.SequenceEqual(b.ComboColours); } private void sort(IBeatmap beatmap) { // Sort control points to ensure a sane ordering, as they may be parsed in different orders. This works because each group contains only uniquely-typed control points. foreach (var g in beatmap.ControlPointInfo.Groups) { ArrayList.Adapter((IList)g.ControlPoints).Sort( Comparer<ControlPoint>.Create((c1, c2) => string.Compare(c1.GetType().ToString(), c2.GetType().ToString(), StringComparison.Ordinal))); } } private (IBeatmap beatmap, TestLegacySkin skin) decodeFromLegacy(Stream stream, string name) { using (var reader = new LineBufferedReader(stream)) { var beatmap = new LegacyBeatmapDecoder { ApplyOffsets = false }.Decode(reader); var beatmapSkin = new TestLegacySkin(beatmaps_resource_store, name); return (convert(beatmap), beatmapSkin); } } private class TestLegacySkin : LegacySkin { public TestLegacySkin(IResourceStore<byte[]> storage, string fileName) : base(new SkinInfo { Name = "Test Skin", Creator = "Craftplacer" }, storage, null, fileName) { } } private MemoryStream encodeToLegacy((IBeatmap beatmap, ISkin skin) fullBeatmap) { var (beatmap, beatmapSkin) = fullBeatmap; var stream = new MemoryStream(); using (var writer = new StreamWriter(stream, Encoding.UTF8, 1024, true)) new LegacyBeatmapEncoder(beatmap, beatmapSkin).Encode(writer); stream.Position = 0; return stream; } private IBeatmap convert(IBeatmap beatmap) { switch (beatmap.BeatmapInfo.RulesetID) { case 0: beatmap.BeatmapInfo.Ruleset = new OsuRuleset().RulesetInfo; break; case 1: beatmap.BeatmapInfo.Ruleset = new TaikoRuleset().RulesetInfo; break; case 2: beatmap.BeatmapInfo.Ruleset = new CatchRuleset().RulesetInfo; break; case 3: beatmap.BeatmapInfo.Ruleset = new ManiaRuleset().RulesetInfo; break; } return new TestWorkingBeatmap(beatmap).GetPlayableBeatmap(beatmap.BeatmapInfo.Ruleset); } private class TestWorkingBeatmap : WorkingBeatmap { private readonly IBeatmap beatmap; public TestWorkingBeatmap(IBeatmap beatmap) : base(beatmap.BeatmapInfo, null) { this.beatmap = beatmap; } protected override IBeatmap GetBeatmap() => beatmap; protected override Texture GetBackground() => throw new NotImplementedException(); protected override Track GetBeatmapTrack() => throw new NotImplementedException(); protected internal override ISkin GetSkin() => throw new NotImplementedException(); public override Stream GetStream(string storagePath) => throw new NotImplementedException(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace NewsPlus.Api.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// // GeneratedCode\SimpleAPIClient.cs // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Test { using System.Linq; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; public partial class SimpleAPIClient : Microsoft.Rest.ServiceClient<SimpleAPIClient>, ISimpleAPIClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public Microsoft.Rest.ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Initializes a new instance of the SimpleAPIClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected SimpleAPIClient(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the SimpleAPIClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected SimpleAPIClient(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the SimpleAPIClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected SimpleAPIClient(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the SimpleAPIClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected SimpleAPIClient(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the SimpleAPIClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public SimpleAPIClient(Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the SimpleAPIClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public SimpleAPIClient(Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the SimpleAPIClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public SimpleAPIClient(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the SimpleAPIClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public SimpleAPIClient(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.BaseUri = new System.Uri("http://localhost"); this.AcceptLanguage = "en-US"; this.LongRunningOperationRetryTimeout = 30; this.GenerateClientRequestId = true; SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter() } }; DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new Microsoft.Rest.Azure.CloudErrorJsonConverter()); } /// <summary> /// Gets those integers. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<int?>>> ListWithHttpMessagesAsync(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("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "getIntegers").ToString(); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _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 (this.GenerateClientRequestId != null && this.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.AcceptLanguage); } 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; // Set Credentials if (this.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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 Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); 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 (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<int?>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<int?>>(_responseContent, this.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets those integers. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<int?>>> ListMoreWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (nextPageLink == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "nextPageLink"); } // 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("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ListMore", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _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 (this.GenerateClientRequestId != null && this.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.AcceptLanguage); } 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; // Set Credentials if (this.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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 Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); 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 (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<int?>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<int?>>(_responseContent, this.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } } // // GeneratedCode\ISimpleAPIClient.cs // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Test { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// </summary> public partial interface ISimpleAPIClient : System.IDisposable { /// <summary> /// The base URI of the service. /// </summary> System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> Microsoft.Rest.ServiceClientCredentials Credentials { get; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running /// Operations. Default value is 30. /// </summary> int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated /// and included in each request. Default is true. /// </summary> bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets those integers. /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<int?>>> ListWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Gets those integers. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<int?>>> ListMoreWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); } } // // GeneratedCode\SimpleAPIClientExtensions.cs // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Test { using System.Threading.Tasks; using Microsoft.Rest.Azure; using Models; /// <summary> /// Extension methods for SimpleAPIClient. /// </summary> public static partial class SimpleAPIClientExtensions { /// <summary> /// Gets those integers. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Microsoft.Rest.Azure.IPage<int?> List(this ISimpleAPIClient operations) { return ((ISimpleAPIClient)operations).ListAsync().GetAwaiter().GetResult(); } /// <summary> /// Gets those integers. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Microsoft.Rest.Azure.IPage<int?>> ListAsync(this ISimpleAPIClient operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets those integers. /// </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 Microsoft.Rest.Azure.IPage<int?> ListMore(this ISimpleAPIClient operations, string nextPageLink) { return ((ISimpleAPIClient)operations).ListMoreAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets those integers. /// </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<Microsoft.Rest.Azure.IPage<int?>> ListMoreAsync(this ISimpleAPIClient operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ListMoreWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } } // // GeneratedCode\Models\Page.cs // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Test.Models { /// <summary> /// Defines a page in Azure responses. /// </summary> /// <typeparam name="T">Type of the page content items</typeparam> [Newtonsoft.Json.JsonObject] public class Page<T> : Microsoft.Rest.Azure.IPage<T> { /// <summary> /// Gets the link to the next page. /// </summary> [Newtonsoft.Json.JsonProperty("nextIntegersUrl")] public System.String NextPageLink { get; private set; } [Newtonsoft.Json.JsonProperty("value")] private System.Collections.Generic.IList<T> Items{ get; set; } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns>A an enumerator that can be used to iterate through the collection.</returns> public System.Collections.Generic.IEnumerator<T> GetEnumerator() { return (Items == null) ? System.Linq.Enumerable.Empty<T>().GetEnumerator() : Items.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns>A an enumerator that can be used to iterate through the collection.</returns> System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.Automation; using Microsoft.Azure.Management.Automation.Models; namespace Microsoft.Azure.Management.Automation { public static partial class JobStreamOperationsExtensions { /// <summary> /// Retrieve the job stream identified by job stream id. (see /// http://aka.ms/azureautomationsdk/jobstreamoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IJobStreamOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='jobId'> /// Required. The job id. /// </param> /// <param name='jobStreamId'> /// Required. The job stream id. /// </param> /// <returns> /// The response model for the get job stream operation. /// </returns> public static JobStreamGetResponse Get(this IJobStreamOperations operations, string resourceGroupName, string automationAccount, Guid jobId, string jobStreamId) { return Task.Factory.StartNew((object s) => { return ((IJobStreamOperations)s).GetAsync(resourceGroupName, automationAccount, jobId, jobStreamId); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve the job stream identified by job stream id. (see /// http://aka.ms/azureautomationsdk/jobstreamoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IJobStreamOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='jobId'> /// Required. The job id. /// </param> /// <param name='jobStreamId'> /// Required. The job stream id. /// </param> /// <returns> /// The response model for the get job stream operation. /// </returns> public static Task<JobStreamGetResponse> GetAsync(this IJobStreamOperations operations, string resourceGroupName, string automationAccount, Guid jobId, string jobStreamId) { return operations.GetAsync(resourceGroupName, automationAccount, jobId, jobStreamId, CancellationToken.None); } /// <summary> /// Retrieve a test job streams identified by runbook name and stream /// id. (see http://aka.ms/azureautomationsdk/jobstreamoperations for /// more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IJobStreamOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='runbookName'> /// Required. The runbook name. /// </param> /// <param name='jobStreamId'> /// Required. The job stream id. /// </param> /// <returns> /// The response model for the get job stream operation. /// </returns> public static JobStreamGetResponse GetTestJobStream(this IJobStreamOperations operations, string resourceGroupName, string automationAccount, string runbookName, string jobStreamId) { return Task.Factory.StartNew((object s) => { return ((IJobStreamOperations)s).GetTestJobStreamAsync(resourceGroupName, automationAccount, runbookName, jobStreamId); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve a test job streams identified by runbook name and stream /// id. (see http://aka.ms/azureautomationsdk/jobstreamoperations for /// more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IJobStreamOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='runbookName'> /// Required. The runbook name. /// </param> /// <param name='jobStreamId'> /// Required. The job stream id. /// </param> /// <returns> /// The response model for the get job stream operation. /// </returns> public static Task<JobStreamGetResponse> GetTestJobStreamAsync(this IJobStreamOperations operations, string resourceGroupName, string automationAccount, string runbookName, string jobStreamId) { return operations.GetTestJobStreamAsync(resourceGroupName, automationAccount, runbookName, jobStreamId, CancellationToken.None); } /// <summary> /// Retrieve a list of jobs streams identified by job id. (see /// http://aka.ms/azureautomationsdk/jobstreamoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IJobStreamOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='jobId'> /// Required. The job Id. /// </param> /// <param name='parameters'> /// Optional. The parameters supplied to the list job stream's stream /// items operation. /// </param> /// <returns> /// The response model for the list job stream operation. /// </returns> public static JobStreamListResponse List(this IJobStreamOperations operations, string resourceGroupName, string automationAccount, Guid jobId, JobStreamListParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IJobStreamOperations)s).ListAsync(resourceGroupName, automationAccount, jobId, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve a list of jobs streams identified by job id. (see /// http://aka.ms/azureautomationsdk/jobstreamoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IJobStreamOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='jobId'> /// Required. The job Id. /// </param> /// <param name='parameters'> /// Optional. The parameters supplied to the list job stream's stream /// items operation. /// </param> /// <returns> /// The response model for the list job stream operation. /// </returns> public static Task<JobStreamListResponse> ListAsync(this IJobStreamOperations operations, string resourceGroupName, string automationAccount, Guid jobId, JobStreamListParameters parameters) { return operations.ListAsync(resourceGroupName, automationAccount, jobId, parameters, CancellationToken.None); } /// <summary> /// Gets the next page of job streams using next link. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IJobStreamOperations. /// </param> /// <param name='nextLink'> /// Required. NextLink from the previous successful call to List /// operation. /// </param> /// <returns> /// The response model for the list job stream operation. /// </returns> public static JobStreamListResponse ListNext(this IJobStreamOperations operations, string nextLink) { return Task.Factory.StartNew((object s) => { return ((IJobStreamOperations)s).ListNextAsync(nextLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the next page of job streams using next link. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IJobStreamOperations. /// </param> /// <param name='nextLink'> /// Required. NextLink from the previous successful call to List /// operation. /// </param> /// <returns> /// The response model for the list job stream operation. /// </returns> public static Task<JobStreamListResponse> ListNextAsync(this IJobStreamOperations operations, string nextLink) { return operations.ListNextAsync(nextLink, CancellationToken.None); } /// <summary> /// Retrieve a list of test job streams identified by runbook name. /// (see http://aka.ms/azureautomationsdk/jobstreamoperations for /// more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IJobStreamOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='runbookName'> /// Required. The runbook name. /// </param> /// <param name='parameters'> /// Optional. The parameters supplied to the list job stream's stream /// items operation. /// </param> /// <returns> /// The response model for the list job stream operation. /// </returns> public static JobStreamListResponse ListTestJobStreams(this IJobStreamOperations operations, string resourceGroupName, string automationAccount, string runbookName, JobStreamListParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IJobStreamOperations)s).ListTestJobStreamsAsync(resourceGroupName, automationAccount, runbookName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve a list of test job streams identified by runbook name. /// (see http://aka.ms/azureautomationsdk/jobstreamoperations for /// more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IJobStreamOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='runbookName'> /// Required. The runbook name. /// </param> /// <param name='parameters'> /// Optional. The parameters supplied to the list job stream's stream /// items operation. /// </param> /// <returns> /// The response model for the list job stream operation. /// </returns> public static Task<JobStreamListResponse> ListTestJobStreamsAsync(this IJobStreamOperations operations, string resourceGroupName, string automationAccount, string runbookName, JobStreamListParameters parameters) { return operations.ListTestJobStreamsAsync(resourceGroupName, automationAccount, runbookName, parameters, CancellationToken.None); } } }
// *********************************************************************** // Copyright (c) 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 NUnit.Framework; using NUnit.Framework.Internal; namespace NUnit.Gui.Tests { namespace Assemblies { /// <summary> /// Constant definitions for the mock-assembly dll. /// </summary> public class MockAssembly { public const int Classes = 9; public const int NamespaceSuites = 6; // assembly, NUnit, Tests, Assemblies, Singletons, TestAssembly public const int Tests = MockTestFixture.Tests + Singletons.OneTestCase.Tests + TestAssembly.MockTestFixture.Tests + IgnoredFixture.Tests + ExplicitFixture.Tests + BadFixture.Tests + FixtureWithTestCases.Tests + ParameterizedFixture.Tests + GenericFixtureConstants.Tests; public const int Suites = MockTestFixture.Suites + Singletons.OneTestCase.Suites + TestAssembly.MockTestFixture.Suites + IgnoredFixture.Suites + ExplicitFixture.Suites + BadFixture.Suites + FixtureWithTestCases.Suites + ParameterizedFixture.Suites + GenericFixtureConstants.Suites + NamespaceSuites; public const int Nodes = Tests + Suites; public const int ExplicitFixtures = 1; public const int SuitesRun = Suites - ExplicitFixtures; public const int Passed = MockTestFixture.Passed + Singletons.OneTestCase.Tests + TestAssembly.MockTestFixture.Tests + FixtureWithTestCases.Tests + ParameterizedFixture.Tests + GenericFixtureConstants.Tests; public const int Skipped_Ignored = MockTestFixture.Skipped_Ignored + IgnoredFixture.Tests; public const int Skipped_Explicit = MockTestFixture.Skipped_Explicit + ExplicitFixture.Tests; public const int Skipped = Skipped_Ignored + Skipped_Explicit; public const int Failed_Errors = MockTestFixture.Failed_Errors; public const int Failed_Failures = MockTestFixture.Failed_Failures; public const int Failed_NotRunnable = MockTestFixture.Failed_NotRunnable + BadFixture.Tests; public const int Failed = Failed_Errors + Failed_Failures + Failed_NotRunnable; public const int Warnings = MockTestFixture.Warnings; public const int Inconclusive = MockTestFixture.Inconclusive; public const int Categories = MockTestFixture.Categories; } [TestFixture(Description="Fake Test Fixture")] [Category("FixtureCategory")] public class MockTestFixture { public const int Tests = 11; public const int Suites = 1; public const int Passed = 1; public const int Skipped_Ignored = 1; public const int Skipped_Explicit = 1; public const int Failed_Failures = 1; public const int Failed_Errors = 1; public const int Failed_NotRunnable = 2; public const int Failed = Failed_Errors + Failed_Failures + Failed_NotRunnable; public const int Warnings = 1; public const int Inconclusive = 1; public const int Categories = 5; public const int MockCategoryTests = 2; [Test(Description="Mock Test #1")] public void MockTest1() {} [Test] [Category("MockCategory")] [Property("Severity","Critical")] [Description("This is a really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really long description")] public void MockTest2() {} [Test] [Category("MockCategory")] [Category("AnotherCategory")] public void MockTest3() { Assert.Pass("Succeeded!"); } [Test] protected static void MockTest5() {} [Test] public void FailingTest() { Assert.Fail("Intentional failure"); } [Test] public void WarningTest() { Assert.Warn("Warning Message"); } [Test, Property("TargetMethod", "SomeClassName"), Property("Size", 5), /*Property("TargetType", typeof( System.Threading.Thread ))*/] public void TestWithManyProperties() {} [Test] [Ignore("ignoring this test method for now")] [Category("Foo")] public void MockTest4() {} [Test, Explicit] [Category( "Special" )] public void ExplicitlyRunTest() {} [Test] public void NotRunnableTest( int a, int b) { } [Test] public void InconclusiveTest() { Assert.Inconclusive("No valid data"); } [Test] public void TestWithException() { MethodThrowsException(); } private void MethodThrowsException() { throw new Exception("Intentional Exception"); } } } namespace Singletons { [TestFixture] public class OneTestCase { public const int Tests = 1; public const int Suites = 1; [Test] public virtual void TestCase() {} } } namespace TestAssembly { [TestFixture] public class MockTestFixture { public const int Tests = 1; public const int Suites = 1; [Test] public void MyTest() { } } } [TestFixture, Ignore("BECAUSE")] public class IgnoredFixture { public const int Tests = 3; public const int Suites = 1; [Test] public void Test1() { } [Test] public void Test2() { } [Test] public void Test3() { } } [TestFixture,Explicit] public class ExplicitFixture { public const int Tests = 2; public const int Suites = 1; public const int Nodes = Tests + Suites; [Test] public void Test1() { } [Test] public void Test2() { } } [TestFixture] public class BadFixture { public const int Tests = 1; public const int Suites = 1; public BadFixture(int val) { } [Test] public void SomeTest() { } } [TestFixture] public class FixtureWithTestCases { public const int Tests = 4; public const int Suites = 3; [TestCase(2, 2, ExpectedResult=4)] [TestCase(9, 11, ExpectedResult=20)] public int MethodWithParameters(int x, int y) { return x+y; } [TestCase(2, 4)] [TestCase(9.2, 11.7)] public void GenericMethod<T>(T x, T y) { } } [TestFixture(5)] [TestFixture(42)] public class ParameterizedFixture { public const int Tests = 4; public const int Suites = 3; public ParameterizedFixture(int num) { } [Test] public void Test1() { } [Test] public void Test2() { } } public class GenericFixtureConstants { public const int Tests = 4; public const int Suites = 3; } [TestFixture(5)] [TestFixture(11.5)] public class GenericFixture<T> { public GenericFixture(T num){ } [Test] public void Test1() { } [Test] public void Test2() { } } }
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion // .NET Compact Framework 1.0 has no support for reading assembly attributes #if !NETCF using System; using System.Collections; using System.Reflection; using System.IO; using log4net.Util; using log4net.Repository; using log4net.Repository.Hierarchy; namespace log4net.Config { /// <summary> /// Assembly level attribute to configure the <see cref="XmlConfigurator"/>. /// </summary> /// <remarks> /// <para> /// This attribute may only be used at the assembly scope and can only /// be used once per assembly. /// </para> /// <para> /// Use this attribute to configure the <see cref="XmlConfigurator"/> /// without calling one of the <see cref="M:XmlConfigurator.Configure()"/> /// methods. /// </para> /// <para> /// If neither of the <see cref="ConfigFile"/> or <see cref="ConfigFileExtension"/> /// properties are set the configuration is loaded from the application's .config file. /// If set the <see cref="ConfigFile"/> property takes priority over the /// <see cref="ConfigFileExtension"/> property. The <see cref="ConfigFile"/> property /// specifies a path to a file to load the config from. The path is relative to the /// application's base directory; <see cref="AppDomain.BaseDirectory"/>. /// The <see cref="ConfigFileExtension"/> property is used as a postfix to the assembly file name. /// The config file must be located in the application's base directory; <see cref="AppDomain.BaseDirectory"/>. /// For example in a console application setting the <see cref="ConfigFileExtension"/> to /// <c>config</c> has the same effect as not specifying the <see cref="ConfigFile"/> or /// <see cref="ConfigFileExtension"/> properties. /// </para> /// <para> /// The <see cref="Watch"/> property can be set to cause the <see cref="XmlConfigurator"/> /// to watch the configuration file for changes. /// </para> /// <note> /// <para> /// Log4net will only look for assembly level configuration attributes once. /// When using the log4net assembly level attributes to control the configuration /// of log4net you must ensure that the first call to any of the /// <see cref="log4net.Core.LoggerManager"/> methods is made from the assembly with the configuration /// attributes. /// </para> /// <para> /// If you cannot guarantee the order in which log4net calls will be made from /// different assemblies you must use programmatic configuration instead, i.e. /// call the <see cref="M:XmlConfigurator.Configure()"/> method directly. /// </para> /// </note> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> [AttributeUsage(AttributeTargets.Assembly)] [Serializable] public /*sealed*/ class XmlConfiguratorAttribute : ConfiguratorAttribute { // // Class is not sealed because DOMConfiguratorAttribute extends it while it is obsoleted // /// <summary> /// Default constructor /// </summary> /// <remarks> /// <para> /// Default constructor /// </para> /// </remarks> public XmlConfiguratorAttribute() : base(0) /* configurator priority 0 */ { } #region Public Instance Properties /// <summary> /// Gets or sets the filename of the configuration file. /// </summary> /// <value> /// The filename of the configuration file. /// </value> /// <remarks> /// <para> /// If specified, this is the name of the configuration file to use with /// the <see cref="XmlConfigurator"/>. This file path is relative to the /// <b>application base</b> directory (<see cref="AppDomain.BaseDirectory"/>). /// </para> /// <para> /// The <see cref="ConfigFile"/> takes priority over the <see cref="ConfigFileExtension"/>. /// </para> /// </remarks> public string ConfigFile { get { return m_configFile; } set { m_configFile = value; } } /// <summary> /// Gets or sets the extension of the configuration file. /// </summary> /// <value> /// The extension of the configuration file. /// </value> /// <remarks> /// <para> /// If specified this is the extension for the configuration file. /// The path to the config file is built by using the <b>application /// base</b> directory (<see cref="AppDomain.BaseDirectory"/>), /// the <b>assembly file name</b> and the config file extension. /// </para> /// <para> /// If the <see cref="ConfigFileExtension"/> is set to <c>MyExt</c> then /// possible config file names would be: <c>MyConsoleApp.exe.MyExt</c> or /// <c>MyClassLibrary.dll.MyExt</c>. /// </para> /// <para> /// The <see cref="ConfigFile"/> takes priority over the <see cref="ConfigFileExtension"/>. /// </para> /// </remarks> public string ConfigFileExtension { get { return m_configFileExtension; } set { m_configFileExtension = value; } } /// <summary> /// Gets or sets a value indicating whether to watch the configuration file. /// </summary> /// <value> /// <c>true</c> if the configuration should be watched, <c>false</c> otherwise. /// </value> /// <remarks> /// <para> /// If this flag is specified and set to <c>true</c> then the framework /// will watch the configuration file and will reload the config each time /// the file is modified. /// </para> /// <para> /// The config file can only be watched if it is loaded from local disk. /// In a No-Touch (Smart Client) deployment where the application is downloaded /// from a web server the config file may not reside on the local disk /// and therefore it may not be able to watch it. /// </para> /// </remarks> public bool Watch { get { return m_configureAndWatch; } set { m_configureAndWatch = value; } } #endregion Public Instance Properties #region Override ConfiguratorAttribute /// <summary> /// Configures the <see cref="ILoggerRepository"/> for the specified assembly. /// </summary> /// <param name="sourceAssembly">The assembly that this attribute was defined on.</param> /// <param name="targetRepository">The repository to configure.</param> /// <remarks> /// <para> /// Configure the repository using the <see cref="XmlConfigurator"/>. /// The <paramref name="targetRepository"/> specified must extend the <see cref="Hierarchy"/> /// class otherwise the <see cref="XmlConfigurator"/> will not be able to /// configure it. /// </para> /// </remarks> /// <exception cref="ArgumentOutOfRangeException">The <paramref name="targetRepository" /> does not extend <see cref="Hierarchy"/>.</exception> override public void Configure(Assembly sourceAssembly, ILoggerRepository targetRepository) { IList configurationMessages = new ArrayList(); using (new LogLog.LogReceivedAdapter(configurationMessages)) { string applicationBaseDirectory = null; try { applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory; } catch { // Ignore this exception because it is only thrown when ApplicationBaseDirectory is a file // and the application does not have PathDiscovery permission } if (applicationBaseDirectory == null || (new Uri(applicationBaseDirectory)).IsFile) { ConfigureFromFile(sourceAssembly, targetRepository); } else { ConfigureFromUri(sourceAssembly, targetRepository); } } targetRepository.ConfigurationMessages = configurationMessages; } #endregion /// <summary> /// Attempt to load configuration from the local file system /// </summary> /// <param name="sourceAssembly">The assembly that this attribute was defined on.</param> /// <param name="targetRepository">The repository to configure.</param> private void ConfigureFromFile(Assembly sourceAssembly, ILoggerRepository targetRepository) { // Work out the full path to the config file string fullPath2ConfigFile = null; // Select the config file if (m_configFile == null || m_configFile.Length == 0) { if (m_configFileExtension == null || m_configFileExtension.Length == 0) { // Use the default .config file for the AppDomain try { fullPath2ConfigFile = SystemInfo.ConfigurationFileLocation; } catch(Exception ex) { LogLog.Error(declaringType, "XmlConfiguratorAttribute: Exception getting ConfigurationFileLocation. Must be able to resolve ConfigurationFileLocation when ConfigFile and ConfigFileExtension properties are not set.", ex); } } else { // Force the extension to start with a '.' if (m_configFileExtension[0] != '.') { m_configFileExtension = "." + m_configFileExtension; } string applicationBaseDirectory = null; try { applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory; } catch(Exception ex) { LogLog.Error(declaringType, "Exception getting ApplicationBaseDirectory. Must be able to resolve ApplicationBaseDirectory and AssemblyFileName when ConfigFileExtension property is set.", ex); } if (applicationBaseDirectory != null) { fullPath2ConfigFile = Path.Combine(applicationBaseDirectory, SystemInfo.AssemblyFileName(sourceAssembly) + m_configFileExtension); } } } else { string applicationBaseDirectory = null; try { applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory; } catch(Exception ex) { LogLog.Warn(declaringType, "Exception getting ApplicationBaseDirectory. ConfigFile property path ["+m_configFile+"] will be treated as an absolute path.", ex); } if (applicationBaseDirectory != null) { // Just the base dir + the config file fullPath2ConfigFile = Path.Combine(applicationBaseDirectory, m_configFile); } else { fullPath2ConfigFile = m_configFile; } } if (fullPath2ConfigFile != null) { ConfigureFromFile(targetRepository, new FileInfo(fullPath2ConfigFile)); } } /// <summary> /// Configure the specified repository using a <see cref="FileInfo"/> /// </summary> /// <param name="targetRepository">The repository to configure.</param> /// <param name="configFile">the FileInfo pointing to the config file</param> private void ConfigureFromFile(ILoggerRepository targetRepository, FileInfo configFile) { // Do we configure just once or do we configure and then watch? if (m_configureAndWatch) { XmlConfigurator.ConfigureAndWatch(targetRepository, configFile); } else { XmlConfigurator.Configure(targetRepository, configFile); } } /// <summary> /// Attempt to load configuration from a URI /// </summary> /// <param name="sourceAssembly">The assembly that this attribute was defined on.</param> /// <param name="targetRepository">The repository to configure.</param> private void ConfigureFromUri(Assembly sourceAssembly, ILoggerRepository targetRepository) { // Work out the full path to the config file Uri fullPath2ConfigFile = null; // Select the config file if (m_configFile == null || m_configFile.Length == 0) { if (m_configFileExtension == null || m_configFileExtension.Length == 0) { string systemConfigFilePath = null; try { systemConfigFilePath = SystemInfo.ConfigurationFileLocation; } catch(Exception ex) { LogLog.Error(declaringType, "XmlConfiguratorAttribute: Exception getting ConfigurationFileLocation. Must be able to resolve ConfigurationFileLocation when ConfigFile and ConfigFileExtension properties are not set.", ex); } if (systemConfigFilePath != null) { Uri systemConfigFileUri = new Uri(systemConfigFilePath); // Use the default .config file for the AppDomain fullPath2ConfigFile = systemConfigFileUri; } } else { // Force the extension to start with a '.' if (m_configFileExtension[0] != '.') { m_configFileExtension = "." + m_configFileExtension; } string systemConfigFilePath = null; try { systemConfigFilePath = SystemInfo.ConfigurationFileLocation; } catch(Exception ex) { LogLog.Error(declaringType, "XmlConfiguratorAttribute: Exception getting ConfigurationFileLocation. Must be able to resolve ConfigurationFileLocation when the ConfigFile property are not set.", ex); } if (systemConfigFilePath != null) { UriBuilder builder = new UriBuilder(new Uri(systemConfigFilePath)); // Remove the current extension from the systemConfigFileUri path string path = builder.Path; int startOfExtension = path.LastIndexOf("."); if (startOfExtension >= 0) { path = path.Substring(0, startOfExtension); } path += m_configFileExtension; builder.Path = path; fullPath2ConfigFile = builder.Uri; } } } else { string applicationBaseDirectory = null; try { applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory; } catch(Exception ex) { LogLog.Warn(declaringType, "Exception getting ApplicationBaseDirectory. ConfigFile property path ["+m_configFile+"] will be treated as an absolute URI.", ex); } if (applicationBaseDirectory != null) { // Just the base dir + the config file fullPath2ConfigFile = new Uri(new Uri(applicationBaseDirectory), m_configFile); } else { fullPath2ConfigFile = new Uri(m_configFile); } } if (fullPath2ConfigFile != null) { if (fullPath2ConfigFile.IsFile) { // The m_configFile could be an absolute local path, therefore we have to be // prepared to switch back to using FileInfos here ConfigureFromFile(targetRepository, new FileInfo(fullPath2ConfigFile.LocalPath)); } else { if (m_configureAndWatch) { LogLog.Warn(declaringType, "XmlConfiguratorAttribute: Unable to watch config file loaded from a URI"); } XmlConfigurator.Configure(targetRepository, fullPath2ConfigFile); } } } #region Private Instance Fields private string m_configFile = null; private string m_configFileExtension = null; private bool m_configureAndWatch = false; #endregion Private Instance Fields #region Private Static Fields /// <summary> /// The fully qualified type of the XmlConfiguratorAttribute class. /// </summary> /// <remarks> /// Used by the internal logger to record the Type of the /// log message. /// </remarks> private readonly static Type declaringType = typeof(XmlConfiguratorAttribute); #endregion Private Static Fields } } #endif // !NETCF
// // SqliteModelCache.cs // // Authors: // Gabriel Burt <gburt@novell.com> // Scott Peterson <lunchtimemama@gmail.com> // // Copyright (C) 2007-2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.Text; using Hyena.Query; namespace Hyena.Data.Sqlite { public class SqliteModelCache<T> : DictionaryModelCache<T> where T : ICacheableItem, new () { private HyenaSqliteConnection connection; private ICacheableDatabaseModel model; private SqliteModelProvider<T> provider; private HyenaSqliteCommand select_range_command; private HyenaSqliteCommand select_single_command; private HyenaSqliteCommand select_first_command; private HyenaSqliteCommand count_command; private HyenaSqliteCommand delete_selection_command; private HyenaSqliteCommand save_selection_command; private HyenaSqliteCommand get_selection_command; private HyenaSqliteCommand indexof_command; private string select_str; private string reload_sql; private string last_indexof_where_fragment; private long uid; private long selection_uid; private long rows; // private bool warm; private long first_order_id; public event Action<IDataReader> AggregatesUpdated; public SqliteModelCache (HyenaSqliteConnection connection, string uuid, ICacheableDatabaseModel model, SqliteModelProvider<T> provider) : base (model) { this.connection = connection; this.model = model; this.provider = provider; CheckCacheTable (); if (model.SelectAggregates != null) { if (model.CachesJoinTableEntries) { count_command = new HyenaSqliteCommand (String.Format (@" SELECT count(*), {0} FROM {1}{2} j WHERE j.{4} IN (SELECT ItemID FROM {3} WHERE ModelID = ?) AND {5} = j.{6}", model.SelectAggregates, // eg sum(FileSize), sum(Duration) provider.TableName, // eg CoreTracks model.JoinFragment, // eg , CorePlaylistEntries CacheTableName, // eg CoreCache model.JoinPrimaryKey, // eg EntryID provider.PrimaryKey, // eg CoreTracks.TrackID model.JoinColumn // eg TrackID )); } else { count_command = new HyenaSqliteCommand (String.Format ( "SELECT count(*), {0} FROM {1} WHERE {2} IN (SELECT ItemID FROM {3} WHERE ModelID = ?)", model.SelectAggregates, provider.TableName, provider.PrimaryKey, CacheTableName )); } } else { count_command = new HyenaSqliteCommand (String.Format ( "SELECT COUNT(*) FROM {0} WHERE ModelID = ?", CacheTableName )); } uid = FindOrCreateCacheModelId (String.Format ("{0}-{1}", uuid, typeof(T).Name)); if (model.Selection != null) { selection_uid = FindOrCreateCacheModelId (String.Format ("{0}-{1}-Selection", uuid, typeof(T).Name)); } if (model.CachesJoinTableEntries) { select_str = String.Format ( @"SELECT {0} {10}, OrderID, {5}.ItemID FROM {1} INNER JOIN {2} ON {3} = {2}.{4} INNER JOIN {5} ON {2}.{6} = {5}.ItemID {11} WHERE {5}.ModelID = {7} {8} {9}", provider.Select, provider.From, model.JoinTable, provider.PrimaryKey, model.JoinColumn, CacheTableName, model.JoinPrimaryKey, uid, String.IsNullOrEmpty (provider.Where) ? null : "AND", provider.Where, "{0}", "{1}" ); reload_sql = String.Format (@" DELETE FROM {0} WHERE ModelID = {1}; INSERT INTO {0} (ModelID, ItemID) SELECT {1}, {2} ", CacheTableName, uid, model.JoinPrimaryKey ); } else if (model.CachesValues) { // The duplication of OrderID/ItemID in the select below is intentional! // The first is used construct the QueryFilterInfo value, the last internally // to this class select_str = String.Format ( @"SELECT OrderID, ItemID {2}, OrderID, ItemID FROM {0} {3} WHERE {0}.ModelID = {1}", CacheTableName, uid, "{0}", "{1}" ); reload_sql = String.Format (@" DELETE FROM {0} WHERE ModelID = {1}; INSERT INTO {0} (ModelID, ItemID) SELECT DISTINCT {1}, {2} ", CacheTableName, uid, provider.Select ); } else { select_str = String.Format ( @"SELECT {0} {7}, OrderID, {2}.ItemID FROM {1} INNER JOIN {2} ON {3} = {2}.ItemID {8} WHERE {2}.ModelID = {4} {5} {6}", provider.Select, provider.From, CacheTableName, provider.PrimaryKey, uid, String.IsNullOrEmpty (provider.Where) ? String.Empty : "AND", provider.Where, "{0}", "{1}" ); reload_sql = String.Format (@" DELETE FROM {0} WHERE ModelID = {1}; INSERT INTO {0} (ModelID, ItemID) SELECT {1}, {2} ", CacheTableName, uid, provider.PrimaryKey ); } select_single_command = new HyenaSqliteCommand ( String.Format (@" SELECT OrderID FROM {0} WHERE ModelID = {1} AND ItemID = ?", CacheTableName, uid ) ); select_range_command = new HyenaSqliteCommand ( String.Format (String.Format ("{0} {1}", select_str, "LIMIT ?, ?"), null, null) ); select_first_command = new HyenaSqliteCommand ( String.Format ( "SELECT OrderID FROM {0} WHERE ModelID = {1} LIMIT 1", CacheTableName, uid ) ); if (model.Selection != null) { delete_selection_command = new HyenaSqliteCommand (String.Format ( "DELETE FROM {0} WHERE ModelID = {1}", CacheTableName, selection_uid )); save_selection_command = new HyenaSqliteCommand (String.Format ( "INSERT INTO {0} (ModelID, ItemID) SELECT {1}, ItemID FROM {0} WHERE ModelID = {2} LIMIT ?, ?", CacheTableName, selection_uid, uid )); get_selection_command = new HyenaSqliteCommand (String.Format ( "SELECT OrderID FROM {0} WHERE ModelID = {1} AND ItemID IN (SELECT ItemID FROM {0} WHERE ModelID = {2})", CacheTableName, uid, selection_uid )); } } private bool has_select_all_item = false; public bool HasSelectAllItem { get { return has_select_all_item; } set { has_select_all_item = value; } } // The idea behind this was we could preserve the CoreCache table across restarts of Banshee, // and indicate whether the cache was already primed via this property. It's not used, and may never be. public bool Warm { //get { return warm; } get { return false; } } public long Count { get { return rows; } } public long CacheId { get { return uid; } } protected virtual string CacheModelsTableName { get { return "HyenaCacheModels"; } } protected virtual string CacheTableName { get { return "HyenaCache"; } } private long FirstOrderId { get { lock (this) { if (first_order_id == -1) { first_order_id = connection.Query<long> (select_first_command); } return first_order_id; } } } public long IndexOf (string where_fragment, long offset) { if (String.IsNullOrEmpty (where_fragment)) { return -1; } if (!where_fragment.Equals (last_indexof_where_fragment)) { last_indexof_where_fragment = where_fragment; if (!where_fragment.Trim ().ToLower ().StartsWith ("and ")) { where_fragment = " AND " + where_fragment; } string sql = String.Format ("{0} {1} LIMIT ?, 1", select_str, where_fragment); indexof_command = new HyenaSqliteCommand (String.Format (sql, null, null)); } lock (this) { using (IDataReader reader = connection.Query (indexof_command, offset)) { if (reader.Read ()) { long target_id = (long) reader[reader.FieldCount - 2]; if (target_id == 0) { return -1; } return target_id - FirstOrderId; } } return -1; } } public long IndexOf (ICacheableItem item) { if (item == null || item.CacheModelId != CacheId) { return -1; } return IndexOf (item.CacheEntryId); } public long IndexOf (object item_id) { lock (this) { if (rows == 0) { return -1; } long target_id = connection.Query<long> (select_single_command, item_id); if (target_id == 0) { return -1; } return target_id - FirstOrderId; } } public T GetSingleWhere (string conditionOrderFragment, params object [] args) { return GetSingle (null, null, conditionOrderFragment, args); } private HyenaSqliteCommand get_single_command; private string last_get_single_select_fragment, last_get_single_condition_fragment, last_get_single_from_fragment; public T GetSingle (string selectFragment, string fromFragment, string conditionOrderFragment, params object [] args) { if (selectFragment != last_get_single_select_fragment || conditionOrderFragment != last_get_single_condition_fragment ||fromFragment != last_get_single_from_fragment || get_single_command == null) { last_get_single_select_fragment = selectFragment; last_get_single_condition_fragment = conditionOrderFragment; last_get_single_from_fragment = fromFragment; get_single_command = new HyenaSqliteCommand (String.Format (String.Format ( "{0} {1} {2}", select_str, conditionOrderFragment, "LIMIT 1"), selectFragment, fromFragment )); } using (IDataReader reader = connection.Query (get_single_command, args)) { if (reader.Read ()) { T item = provider.Load (reader); item.CacheEntryId = reader[reader.FieldCount - 1]; item.CacheModelId = uid; return item; } } return default; } private HyenaSqliteCommand last_reload_command; private string last_reload_fragment; public override void Reload () { lock (this) { if (last_reload_fragment != model.ReloadFragment || last_reload_command == null) { last_reload_fragment = model.ReloadFragment; last_reload_command = new HyenaSqliteCommand (String.Format ("{0}{1}", reload_sql, last_reload_fragment)); } Clear (); //Log.DebugFormat ("Reloading {0} with {1}", model, last_reload_command.Text); connection.Execute (last_reload_command); } } public override void Clear () { lock (this) { base.Clear (); first_order_id = -1; } } private bool saved_selection = false; private ICacheableItem saved_focus_item = null; public void SaveSelection () { if (model.Selection != null && model.Selection.Count > 0 && !(has_select_all_item && model.Selection.AllSelected)) { connection.Execute (delete_selection_command); saved_selection = true; if (!has_select_all_item && model.Selection.FocusedIndex != -1) { T item = GetValue (model.Selection.FocusedIndex); if (item != null) { saved_focus_item = GetValue (model.Selection.FocusedIndex); } } long start, end; foreach (Hyena.Collections.RangeCollection.Range range in model.Selection.Ranges) { start = range.Start; end = range.End; // Compensate for the first, fake 'All *' item if (has_select_all_item) { start -= 1; end -= 1; } connection.Execute (save_selection_command, start, end - start + 1); } } else { saved_selection = false; } } public void RestoreSelection () { if (saved_selection) { long selected_id = -1; long first_id = FirstOrderId; // Compensate for the first, fake 'All *' item if (has_select_all_item) { first_id -= 1; } model.Selection.Clear (false); foreach (long order_id in connection.QueryEnumerable<long> (get_selection_command)) { selected_id = order_id - first_id; model.Selection.QuietSelect ((int)selected_id); } if (has_select_all_item && model.Selection.Count == 0) { model.Selection.QuietSelect (0); } if (saved_focus_item != null) { long i = IndexOf (saved_focus_item); if (i != -1) { // TODO get rid of int cast model.Selection.FocusedIndex = (int)i; } } saved_selection = false; saved_focus_item = null; } } protected override void FetchSet (long offset, long limit) { lock (this) { using (IDataReader reader = connection.Query (select_range_command, offset, limit)) { T item; while (reader.Read ()) { if (!ContainsKey (offset)) { item = provider.Load (reader); item.CacheEntryId = reader[reader.FieldCount - 1]; item.CacheModelId = uid; Add (offset, item); } offset++; } } } } public void UpdateAggregates () { rows = UpdateAggregates (AggregatesUpdated, uid); } public void UpdateSelectionAggregates (Action<IDataReader> handler) { SaveSelection (); UpdateAggregates (handler, selection_uid); } private long UpdateAggregates (Action<IDataReader> handler, long model_id) { long aggregate_rows = 0; using (IDataReader reader = connection.Query (count_command, model_id)) { if (reader.Read ()) { aggregate_rows = Convert.ToInt64 (reader[0]); if (handler != null) { handler (reader); } } } return aggregate_rows; } private long FindOrCreateCacheModelId (string id) { long model_id = connection.Query<long> (String.Format ( "SELECT CacheID FROM {0} WHERE ModelID = '{1}'", CacheModelsTableName, id )); if (model_id == 0) { //Console.WriteLine ("Didn't find existing cache for {0}, creating", id); model_id = connection.Execute (new HyenaSqliteCommand (String.Format ( "INSERT INTO {0} (ModelID) VALUES (?)", CacheModelsTableName ), id )); } else { //Console.WriteLine ("Found existing cache for {0}: {1}", id, uid); //warm = true; //Clear (); //UpdateAggregates (); } return model_id; } private static string checked_cache_table; private void CheckCacheTable () { if (CacheTableName == checked_cache_table) { return; } if (!connection.TableExists (CacheTableName)) { connection.Execute (String.Format (@" CREATE TEMP TABLE {0} ( OrderID INTEGER PRIMARY KEY, ModelID INTEGER, ItemID TEXT)", CacheTableName )); } if (!connection.TableExists (CacheModelsTableName)) { connection.Execute (String.Format ( "CREATE TABLE {0} (CacheID INTEGER PRIMARY KEY, ModelID TEXT UNIQUE)", CacheModelsTableName )); } checked_cache_table = CacheTableName; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Analyzer.Utilities; using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.NetCore.Analyzers.Runtime { /// <summary> /// CA2243: Attribute string literals should parse correctly /// Unlike FxCop, this rule does not fire diagnostics for ill-formed versions /// Reason: There is wide usage of semantic versioning which does not follow traditional versioning grammar. /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class AttributeStringLiteralsShouldParseCorrectlyAnalyzer : DiagnosticAnalyzer { internal const string RuleId = "CA2243"; private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(SystemRuntimeAnalyzersResources.AttributeStringLiteralsShouldParseCorrectlyTitle), SystemRuntimeAnalyzersResources.ResourceManager, typeof(SystemRuntimeAnalyzersResources)); private static readonly LocalizableString s_localizableMessageDefault = new LocalizableResourceString(nameof(SystemRuntimeAnalyzersResources.AttributeStringLiteralsShouldParseCorrectlyMessageDefault), SystemRuntimeAnalyzersResources.ResourceManager, typeof(SystemRuntimeAnalyzersResources)); private static readonly LocalizableString s_localizableMessageEmpty = new LocalizableResourceString(nameof(SystemRuntimeAnalyzersResources.AttributeStringLiteralsShouldParseCorrectlyMessageEmpty), SystemRuntimeAnalyzersResources.ResourceManager, typeof(SystemRuntimeAnalyzersResources)); private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(SystemRuntimeAnalyzersResources.AttributeStringLiteralsShouldParseCorrectlyDescription), SystemRuntimeAnalyzersResources.ResourceManager, typeof(SystemRuntimeAnalyzersResources)); internal static DiagnosticDescriptor DefaultRule = new DiagnosticDescriptor(RuleId, s_localizableTitle, s_localizableMessageDefault, DiagnosticCategory.Usage, DiagnosticHelpers.DefaultDiagnosticSeverity, isEnabledByDefault: DiagnosticHelpers.EnabledByDefaultIfNotBuildingVSIX, description: s_localizableDescription, helpLinkUri: "https://msdn.microsoft.com/en-us/library/bb264490.aspx", customTags: WellKnownDiagnosticTags.Telemetry); internal static DiagnosticDescriptor EmptyRule = new DiagnosticDescriptor(RuleId, s_localizableTitle, s_localizableMessageEmpty, DiagnosticCategory.Usage, DiagnosticHelpers.DefaultDiagnosticSeverity, isEnabledByDefault: DiagnosticHelpers.EnabledByDefaultIfNotBuildingVSIX, description: s_localizableDescription, helpLinkUri: "https://msdn.microsoft.com/en-us/library/bb264490.aspx", customTags: WellKnownDiagnosticTags.Telemetry); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(DefaultRule, EmptyRule); private static List<ValueValidator> s_tokensToValueValidator = new List<ValueValidator>( new[] { new ValueValidator(new[] { "guid" }, "Guid", GuidValueValidator), new ValueValidator(new[] { "url", "uri", "urn" }, "Uri", UrlValueValidator, "UriTemplate")}); private static bool GuidValueValidator(string value) { try { var unused = new Guid(value); return true; } catch (OverflowException) { } catch (FormatException) { } return false; } private static bool UrlValueValidator(string value) { return Uri.IsWellFormedUriString(value, System.UriKind.RelativeOrAbsolute); } public override void Initialize(AnalysisContext analysisContext) { analysisContext.EnableConcurrentExecution(); analysisContext.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); analysisContext.RegisterSymbolAction(saContext => { var symbol = saContext.Symbol; AnalyzeSymbol(saContext.ReportDiagnostic, symbol); switch (symbol.Kind) { case SymbolKind.NamedType: { var namedType = symbol as INamedTypeSymbol; AnalyzeSymbols(saContext.ReportDiagnostic, namedType.TypeParameters); if (namedType.TypeKind == TypeKind.Delegate && namedType.DelegateInvokeMethod != null) { AnalyzeSymbols(saContext.ReportDiagnostic, namedType.DelegateInvokeMethod.Parameters); } return; } case SymbolKind.Method: { var methodSymbol = symbol as IMethodSymbol; if (!methodSymbol.IsAccessorMethod()) { AnalyzeSymbols(saContext.ReportDiagnostic, methodSymbol.Parameters); AnalyzeSymbols(saContext.ReportDiagnostic, methodSymbol.TypeParameters); } return; } case SymbolKind.Property: { var propertySymbol = symbol as IPropertySymbol; AnalyzeSymbols(saContext.ReportDiagnostic, propertySymbol.Parameters); return; } } }, SymbolKind.NamedType, SymbolKind.Method, SymbolKind.Property, SymbolKind.Field, SymbolKind.Event); analysisContext.RegisterCompilationAction(caContext => { var compilation = caContext.Compilation; AnalyzeSymbol(caContext.ReportDiagnostic, compilation.Assembly); }); } private static void AnalyzeSymbols(Action<Diagnostic> reportDiagnostic, IEnumerable<ISymbol> symbols) { foreach (var symbol in symbols) { AnalyzeSymbol(reportDiagnostic, symbol); } } private static void AnalyzeSymbol(Action<Diagnostic> reportDiagnostic, ISymbol symbol) { var attributes = symbol.GetAttributes(); foreach (var attribute in attributes) { Analyze(reportDiagnostic, attribute); } } private static void Analyze(Action<Diagnostic> reportDiagnostic, AttributeData attributeData) { var attributeConstructor = attributeData.AttributeConstructor; var constructorArguments = attributeData.ConstructorArguments; if (attributeConstructor == null || attributeConstructor.Parameters.Count() != constructorArguments.Count()) { return; } var syntax = attributeData.ApplicationSyntaxReference.GetSyntax(); for (int i = 0; i < attributeConstructor.Parameters.Count(); i++) { var parameter = attributeConstructor.Parameters[i]; if (parameter.Type.SpecialType != SpecialType.System_String) { continue; } // If the name of the parameter is not something which requires the value-passed // to the parameter to be validated then we don't have to do anything var valueValidator = GetValueValidator(parameter.Name); if (valueValidator != null && !valueValidator.IsIgnoredName(parameter.Name)) { if (constructorArguments[i].Value != null) { var value = (string)constructorArguments[i].Value; string classDisplayString = attributeData.AttributeClass.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat); if (value.Equals(string.Empty, StringComparison.Ordinal)) { reportDiagnostic(syntax.CreateDiagnostic(EmptyRule, classDisplayString, parameter.Name, valueValidator.TypeName)); } else if (!valueValidator.IsValidValue(value)) { reportDiagnostic(syntax.CreateDiagnostic(DefaultRule, classDisplayString, parameter.Name, value, valueValidator.TypeName)); } } } } foreach (var namedArgument in attributeData.NamedArguments) { if (namedArgument.Value.IsNull || namedArgument.Value.Type.SpecialType != SpecialType.System_String) { return; } var valueValidator = GetValueValidator(namedArgument.Key); if (valueValidator != null && !valueValidator.IsIgnoredName(namedArgument.Key)) { var value = (string)(namedArgument.Value.Value); string classDisplayString = attributeData.AttributeClass.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat); if (value.Equals(string.Empty, StringComparison.Ordinal)) { reportDiagnostic(syntax.CreateDiagnostic(EmptyRule, classDisplayString, $"{classDisplayString}.{namedArgument.Key}", valueValidator.TypeName)); } else if (!valueValidator.IsValidValue(value)) { reportDiagnostic(syntax.CreateDiagnostic(DefaultRule, classDisplayString, $"{classDisplayString}.{namedArgument.Key}", value, valueValidator.TypeName)); } } } } private static ValueValidator GetValueValidator(string name) { foreach (var valueValidator in s_tokensToValueValidator) { if (WordParser.ContainsWord(name, WordParserOptions.SplitCompoundWords, valueValidator.AcceptedTokens)) { return valueValidator; } } return null; } } internal class ValueValidator { private string _ignoredName; public string[] AcceptedTokens { get; } public string TypeName { get; } public Func<string, bool> IsValidValue { get; } public bool IsIgnoredName(string name) { return _ignoredName != null && string.Equals(_ignoredName, name, StringComparison.OrdinalIgnoreCase); } public ValueValidator(string[] acceptedTokens, string typeName, Func<string, bool> isValidValue, string ignoredName = null) { _ignoredName = ignoredName; AcceptedTokens = acceptedTokens; TypeName = typeName; IsValidValue = isValidValue; } } }
// 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 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.CustomerInsights { using Azure; using Management; using Rest; using Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// ProfilesOperations operations. /// </summary> public partial interface IProfilesOperations { /// <summary> /// Creates a profile within a Hub, or updates an existing profile. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='hubName'> /// The name of the hub. /// </param> /// <param name='profileName'> /// The name of the profile. /// </param> /// <param name='parameters'> /// Parameters supplied to the create/delete Profile type operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ProfileResourceFormat>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string hubName, string profileName, ProfileResourceFormat parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets information about the specified profile. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='hubName'> /// The name of the hub. /// </param> /// <param name='profileName'> /// The name of the profile. /// </param> /// <param name='localeCode'> /// Locale of profile to retrieve, default is en-us. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ProfileResourceFormat>> GetWithHttpMessagesAsync(string resourceGroupName, string hubName, string profileName, string localeCode = "en-us", Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a profile within a hub /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='hubName'> /// The name of the hub. /// </param> /// <param name='profileName'> /// The name of the profile. /// </param> /// <param name='localeCode'> /// Locale of profile to retrieve, default is en-us. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string hubName, string profileName, string localeCode = "en-us", Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all profile in the hub. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='hubName'> /// The name of the hub. /// </param> /// <param name='localeCode'> /// Locale of profile to retrieve, default is en-us. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<ProfileResourceFormat>>> ListByHubWithHttpMessagesAsync(string resourceGroupName, string hubName, string localeCode = "en-us", Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates a profile within a Hub, or updates an existing profile. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='hubName'> /// The name of the hub. /// </param> /// <param name='profileName'> /// The name of the profile. /// </param> /// <param name='parameters'> /// Parameters supplied to the create/delete Profile type operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ProfileResourceFormat>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string hubName, string profileName, ProfileResourceFormat parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a profile within a hub /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='hubName'> /// The name of the hub. /// </param> /// <param name='profileName'> /// The name of the profile. /// </param> /// <param name='localeCode'> /// Locale of profile to retrieve, default is en-us. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string hubName, string profileName, string localeCode = "en-us", Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all profile in the hub. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<ProfileResourceFormat>>> ListByHubNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Globalization; using System.Reflection; namespace System.Net { internal enum CookieToken { // State types Nothing, NameValuePair, // X=Y Attribute, // X EndToken, // ';' EndCookie, // ',' End, // EOLN Equals, // Value types Comment, CommentUrl, CookieName, Discard, Domain, Expires, MaxAge, Path, Port, Secure, HttpOnly, Unknown, Version } // CookieTokenizer // // Used to split a single or multi-cookie (header) string into individual // tokens. internal class CookieTokenizer { private bool _eofCookie; private int _index; private int _length; private string _name; private bool _quoted; private int _start; private CookieToken _token; private int _tokenLength; private string _tokenStream; private string _value; private int _cookieStartIndex; private int _cookieLength; internal CookieTokenizer(string tokenStream) { _length = tokenStream.Length; _tokenStream = tokenStream; } internal bool EndOfCookie { get { return _eofCookie; } set { _eofCookie = value; } } internal bool Eof { get { return _index >= _length; } } internal string Name { get { return _name; } set { _name = value; } } internal bool Quoted { get { return _quoted; } set { _quoted = value; } } internal CookieToken Token { get { return _token; } set { _token = value; } } internal string Value { get { return _value; } set { _value = value; } } // GetCookieString // // Gets the full string of the cookie internal string GetCookieString() { return _tokenStream.SubstringTrim(_cookieStartIndex, _cookieLength); } // Extract // // Extracts the current token internal string Extract() { string tokenString = string.Empty; if (_tokenLength != 0) { tokenString = Quoted ? _tokenStream.Substring(_start, _tokenLength) : _tokenStream.SubstringTrim(_start, _tokenLength); } return tokenString; } // FindNext // // Find the start and length of the next token. The token is terminated // by one of: // - end-of-line // - end-of-cookie: unquoted comma separates multiple cookies // - end-of-token: unquoted semi-colon // - end-of-name: unquoted equals // // Inputs: // <argument> ignoreComma // true if parsing doesn't stop at a comma. This is only true when // we know we're parsing an original cookie that has an expires= // attribute, because the format of the time/date used in expires // is: // Wdy, dd-mmm-yyyy HH:MM:SS GMT // // <argument> ignoreEquals // true if parsing doesn't stop at an equals sign. The LHS of the // first equals sign is an attribute name. The next token may // include one or more equals signs. For example: // SESSIONID=ID=MSNx45&q=33 // // Outputs: // <member> _index // incremented to the last position in _tokenStream contained by // the current token // // <member> _start // incremented to the start of the current token // // <member> _tokenLength // set to the length of the current token // // Assumes: Nothing // // Returns: // type of CookieToken found: // // End - end of the cookie string // EndCookie - end of current cookie in (potentially) a // multi-cookie string // EndToken - end of name=value pair, or end of an attribute // Equals - end of name= // // Throws: Nothing internal CookieToken FindNext(bool ignoreComma, bool ignoreEquals) { _tokenLength = 0; _start = _index; while ((_index < _length) && Char.IsWhiteSpace(_tokenStream[_index])) { ++_index; ++_start; } CookieToken token = CookieToken.End; int increment = 1; if (!Eof) { if (_tokenStream[_index] == '"') { Quoted = true; ++_index; bool quoteOn = false; while (_index < _length) { char currChar = _tokenStream[_index]; if (!quoteOn && currChar == '"') { break; } if (quoteOn) { quoteOn = false; } else if (currChar == '\\') { quoteOn = true; } ++_index; } if (_index < _length) { ++_index; } _tokenLength = _index - _start; increment = 0; // If we are here, reset ignoreComma. // In effect, we ignore everything after quoted string until the next delimiter. ignoreComma = false; } while ((_index < _length) && (_tokenStream[_index] != ';') && (ignoreEquals || (_tokenStream[_index] != '=')) && (ignoreComma || (_tokenStream[_index] != ','))) { // Fixing 2 things: // 1) ignore day of week in cookie string // 2) revert ignoreComma once meet it, so won't miss the next cookie) if (_tokenStream[_index] == ',') { _start = _index + 1; _tokenLength = -1; ignoreComma = false; } ++_index; _tokenLength += increment; } if (!Eof) { switch (_tokenStream[_index]) { case ';': token = CookieToken.EndToken; break; case '=': token = CookieToken.Equals; break; default: _cookieLength = _index - _cookieStartIndex; token = CookieToken.EndCookie; break; } ++_index; } else { _cookieLength = _index - _cookieStartIndex; } } return token; } // Next // // Get the next cookie name/value or attribute // // Cookies come in the following formats: // // 1. Version0 // Set-Cookie: [<name>][=][<value>] // [; expires=<date>] // [; path=<path>] // [; domain=<domain>] // [; secure] // Cookie: <name>=<value> // // Notes: <name> and/or <value> may be blank // <date> is the RFC 822/1123 date format that // incorporates commas, e.g. // "Wednesday, 09-Nov-99 23:12:40 GMT" // // 2. RFC 2109 // Set-Cookie: 1#{ // <name>=<value> // [; comment=<comment>] // [; domain=<domain>] // [; max-age=<seconds>] // [; path=<path>] // [; secure] // ; Version=<version> // } // Cookie: $Version=<version> // 1#{ // ; <name>=<value> // [; path=<path>] // [; domain=<domain>] // } // // 3. RFC 2965 // Set-Cookie2: 1#{ // <name>=<value> // [; comment=<comment>] // [; commentURL=<comment>] // [; discard] // [; domain=<domain>] // [; max-age=<seconds>] // [; path=<path>] // [; ports=<portlist>] // [; secure] // ; Version=<version> // } // Cookie: $Version=<version> // 1#{ // ; <name>=<value> // [; path=<path>] // [; domain=<domain>] // [; port="<port>"] // } // [Cookie2: $Version=<version>] // // Inputs: // <argument> first // true if this is the first name/attribute that we have looked for // in the cookie stream // // Outputs: // // Assumes: // Nothing // // Returns: // type of CookieToken found: // // - Attribute // - token was single-value. May be empty. Caller should check // Eof or EndCookie to determine if any more action needs to // be taken // // - NameValuePair // - Name and Value are meaningful. Either may be empty // // Throws: // Nothing internal CookieToken Next(bool first, bool parseResponseCookies) { Reset(); if (first) { _cookieStartIndex = _index; _cookieLength = 0; } CookieToken terminator = FindNext(false, false); if (terminator == CookieToken.EndCookie) { EndOfCookie = true; } if ((terminator == CookieToken.End) || (terminator == CookieToken.EndCookie)) { if ((Name = Extract()).Length != 0) { Token = TokenFromName(parseResponseCookies); return CookieToken.Attribute; } return terminator; } Name = Extract(); if (first) { Token = CookieToken.CookieName; } else { Token = TokenFromName(parseResponseCookies); } if (terminator == CookieToken.Equals) { terminator = FindNext(!first && (Token == CookieToken.Expires), true); if (terminator == CookieToken.EndCookie) { EndOfCookie = true; } Value = Extract(); return CookieToken.NameValuePair; } else { return CookieToken.Attribute; } } // Reset // // Sets this tokenizer up for finding the next name/value pair, // attribute, or end-of-{token,cookie,line}. internal void Reset() { _eofCookie = false; _name = string.Empty; _quoted = false; _start = _index; _token = CookieToken.Nothing; _tokenLength = 0; _value = string.Empty; } private struct RecognizedAttribute { private string _name; private CookieToken _token; internal RecognizedAttribute(string name, CookieToken token) { _name = name; _token = token; } internal CookieToken Token { get { return _token; } } internal bool IsEqualTo(string value) { return string.Equals(_name, value, StringComparison.OrdinalIgnoreCase); } } // Recognized attributes in order of expected frequency. private static readonly RecognizedAttribute[] s_recognizedAttributes = { new RecognizedAttribute(CookieFields.PathAttributeName, CookieToken.Path), new RecognizedAttribute(CookieFields.MaxAgeAttributeName, CookieToken.MaxAge), new RecognizedAttribute(CookieFields.ExpiresAttributeName, CookieToken.Expires), new RecognizedAttribute(CookieFields.VersionAttributeName, CookieToken.Version), new RecognizedAttribute(CookieFields.DomainAttributeName, CookieToken.Domain), new RecognizedAttribute(CookieFields.SecureAttributeName, CookieToken.Secure), new RecognizedAttribute(CookieFields.DiscardAttributeName, CookieToken.Discard), new RecognizedAttribute(CookieFields.PortAttributeName, CookieToken.Port), new RecognizedAttribute(CookieFields.CommentAttributeName, CookieToken.Comment), new RecognizedAttribute(CookieFields.CommentUrlAttributeName, CookieToken.CommentUrl), new RecognizedAttribute(CookieFields.HttpOnlyAttributeName, CookieToken.HttpOnly), }; private static readonly RecognizedAttribute[] s_recognizedServerAttributes = { new RecognizedAttribute('$' + CookieFields.PathAttributeName, CookieToken.Path), new RecognizedAttribute('$' + CookieFields.VersionAttributeName, CookieToken.Version), new RecognizedAttribute('$' + CookieFields.DomainAttributeName, CookieToken.Domain), new RecognizedAttribute('$' + CookieFields.PortAttributeName, CookieToken.Port), new RecognizedAttribute('$' + CookieFields.HttpOnlyAttributeName, CookieToken.HttpOnly), }; internal CookieToken TokenFromName(bool parseResponseCookies) { if (!parseResponseCookies) { for (int i = 0; i < s_recognizedServerAttributes.Length; ++i) { if (s_recognizedServerAttributes[i].IsEqualTo(Name)) { return s_recognizedServerAttributes[i].Token; } } } else { for (int i = 0; i < s_recognizedAttributes.Length; ++i) { if (s_recognizedAttributes[i].IsEqualTo(Name)) { return s_recognizedAttributes[i].Token; } } } return CookieToken.Unknown; } } // CookieParser // // Takes a cookie header, makes cookies. internal class CookieParser { private CookieTokenizer _tokenizer; private Cookie _savedCookie; internal CookieParser(string cookieString) { _tokenizer = new CookieTokenizer(cookieString); } // GetString // // Gets the next cookie string internal string GetString() { bool first = true; if (_tokenizer.Eof) { return null; } do { _tokenizer.Next(first, true); first = false; } while (!_tokenizer.Eof && !_tokenizer.EndOfCookie); return _tokenizer.GetCookieString(); } #if SYSTEM_NET_PRIMITIVES_DLL private static bool InternalSetNameMethod(Cookie cookie, string value) { return cookie.InternalSetName(value); } #else private static Func<Cookie, string, bool> s_internalSetNameMethod; private static Func<Cookie, string, bool> InternalSetNameMethod { get { if (s_internalSetNameMethod == null) { // We need to use Cookie.InternalSetName instead of the Cookie.set_Name wrapped in a try catch block, as // Cookie.set_Name keeps the original name if the string is empty or null. // Unfortunately this API is internal so we use reflection to access it. The method is cached for performance reasons. BindingFlags flags = BindingFlags.Instance; #if uap flags |= BindingFlags.Public; #else flags |= BindingFlags.NonPublic; #endif MethodInfo method = typeof(Cookie).GetMethod("InternalSetName", flags); Debug.Assert(method != null, "We need to use an internal method named InternalSetName that is declared on Cookie."); s_internalSetNameMethod = (Func<Cookie, string, bool>)Delegate.CreateDelegate(typeof(Func<Cookie, string, bool>), method); } return s_internalSetNameMethod; } } #endif private static FieldInfo s_isQuotedDomainField = null; private static FieldInfo IsQuotedDomainField { get { if (s_isQuotedDomainField == null) { FieldInfo field = typeof(Cookie).GetField("IsQuotedDomain", BindingFlags.NonPublic | BindingFlags.Instance); Debug.Assert(field != null, "We need to use an internal field named IsQuotedDomain that is declared on Cookie."); s_isQuotedDomainField = field; } return s_isQuotedDomainField; } } private static FieldInfo s_isQuotedVersionField = null; private static FieldInfo IsQuotedVersionField { get { if (s_isQuotedVersionField == null) { FieldInfo field = typeof(Cookie).GetField("IsQuotedVersion", BindingFlags.NonPublic | BindingFlags.Instance); Debug.Assert(field != null, "We need to use an internal field named IsQuotedVersion that is declared on Cookie."); s_isQuotedVersionField = field; } return s_isQuotedVersionField; } } // Get // // Gets the next cookie or null if there are no more cookies. internal Cookie Get() { Cookie cookie = null; // Only the first occurrence of an attribute value must be counted. bool commentSet = false; bool commentUriSet = false; bool domainSet = false; bool expiresSet = false; bool pathSet = false; bool portSet = false; // Special case: may have no value in header. bool versionSet = false; bool secureSet = false; bool discardSet = false; do { CookieToken token = _tokenizer.Next(cookie == null, true); if (cookie == null && (token == CookieToken.NameValuePair || token == CookieToken.Attribute)) { cookie = new Cookie(); InternalSetNameMethod(cookie, _tokenizer.Name); cookie.Value = _tokenizer.Value; } else { switch (token) { case CookieToken.NameValuePair: switch (_tokenizer.Token) { case CookieToken.Comment: if (!commentSet) { commentSet = true; cookie.Comment = _tokenizer.Value; } break; case CookieToken.CommentUrl: if (!commentUriSet) { commentUriSet = true; if (Uri.TryCreate(CheckQuoted(_tokenizer.Value), UriKind.Absolute, out Uri parsed)) { cookie.CommentUri = parsed; } } break; case CookieToken.Domain: if (!domainSet) { domainSet = true; cookie.Domain = CheckQuoted(_tokenizer.Value); IsQuotedDomainField.SetValue(cookie, _tokenizer.Quoted); } break; case CookieToken.Expires: if (!expiresSet) { expiresSet = true; if (DateTime.TryParse(CheckQuoted(_tokenizer.Value), CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out DateTime expires)) { cookie.Expires = expires; } else { // This cookie will be rejected InternalSetNameMethod(cookie, string.Empty); } } break; case CookieToken.MaxAge: if (!expiresSet) { expiresSet = true; if (int.TryParse(CheckQuoted(_tokenizer.Value), out int parsed)) { cookie.Expires = DateTime.Now.AddSeconds(parsed); } else { // This cookie will be rejected InternalSetNameMethod(cookie, string.Empty); } } break; case CookieToken.Path: if (!pathSet) { pathSet = true; cookie.Path = _tokenizer.Value; } break; case CookieToken.Port: if (!portSet) { portSet = true; try { cookie.Port = _tokenizer.Value; } catch { // This cookie will be rejected InternalSetNameMethod(cookie, string.Empty); } } break; case CookieToken.Version: if (!versionSet) { versionSet = true; int parsed; if (int.TryParse(CheckQuoted(_tokenizer.Value), out parsed)) { cookie.Version = parsed; IsQuotedVersionField.SetValue(cookie, _tokenizer.Quoted); } else { // This cookie will be rejected InternalSetNameMethod(cookie, string.Empty); } } break; } break; case CookieToken.Attribute: switch (_tokenizer.Token) { case CookieToken.Discard: if (!discardSet) { discardSet = true; cookie.Discard = true; } break; case CookieToken.Secure: if (!secureSet) { secureSet = true; cookie.Secure = true; } break; case CookieToken.HttpOnly: cookie.HttpOnly = true; break; case CookieToken.Port: if (!portSet) { portSet = true; cookie.Port = string.Empty; } break; } break; } } } while (!_tokenizer.Eof && !_tokenizer.EndOfCookie); return cookie; } internal Cookie GetServer() { Cookie cookie = _savedCookie; _savedCookie = null; // Only the first occurrence of an attribute value must be counted. bool domainSet = false; bool pathSet = false; bool portSet = false; // Special case: may have no value in header. do { bool first = cookie == null || string.IsNullOrEmpty(cookie.Name); CookieToken token = _tokenizer.Next(first, false); if (first && (token == CookieToken.NameValuePair || token == CookieToken.Attribute)) { if (cookie == null) { cookie = new Cookie(); } InternalSetNameMethod(cookie, _tokenizer.Name); cookie.Value = _tokenizer.Value; } else { switch (token) { case CookieToken.NameValuePair: switch (_tokenizer.Token) { case CookieToken.Domain: if (!domainSet) { domainSet = true; cookie.Domain = CheckQuoted(_tokenizer.Value); IsQuotedDomainField.SetValue(cookie, _tokenizer.Quoted); } break; case CookieToken.Path: if (!pathSet) { pathSet = true; cookie.Path = _tokenizer.Value; } break; case CookieToken.Port: if (!portSet) { portSet = true; try { cookie.Port = _tokenizer.Value; } catch (CookieException) { // This cookie will be rejected InternalSetNameMethod(cookie, string.Empty); } } break; case CookieToken.Version: // this is a new cookie, this token is for the next cookie. _savedCookie = new Cookie(); if (int.TryParse(_tokenizer.Value, out int parsed)) { _savedCookie.Version = parsed; } return cookie; case CookieToken.Unknown: // this is a new cookie, the token is for the next cookie. _savedCookie = new Cookie(); InternalSetNameMethod(_savedCookie, _tokenizer.Name); _savedCookie.Value = _tokenizer.Value; return cookie; } break; case CookieToken.Attribute: if (_tokenizer.Token == CookieToken.Port && !portSet) { portSet = true; cookie.Port = string.Empty; } break; } } } while (!_tokenizer.Eof && !_tokenizer.EndOfCookie); return cookie; } internal static string CheckQuoted(string value) { if (value.Length < 2 || value[0] != '\"' || value[value.Length - 1] != '\"') return value; return value.Length == 2 ? string.Empty : value.Substring(1, value.Length - 2); } } }
using UnityEngine; using System.Collections.Generic; using /*<com>*/Finegamedesign.Utils/*<Model>*/; namespace /*<com>*/Finegamedesign.Anagram.TestSyntax { public class TestSyntaxModel { private static void Shuffle(List<string> cards) { for (int i = DataUtil.Length(cards) - 1; 1 <= i; i--) { int r = (int)(Mathf.Floor((Random.value % 1.0f) * (i + 1))); string swap = cards[r]; cards[r] = cards[i]; cards[i] = swap; } } internal string helpState; internal int letterMax = 10; internal List<string> inputs = new List<string>(); /** * From letter graphic. */ internal float letterWidth = 42.0f; internal delegate /*<var>*/void ActionDelegate(); internal /*<Function>*/ActionDelegate onComplete; internal delegate bool IsJustPressed(string letter); internal string help; internal List<string> outputs = new List<string>(); internal List<string> completes = new List<string>(); internal string text; internal List<string> word; internal float wordPosition = 0.0f; internal float wordPositionScaled = 0.0f; internal int points = 0; internal int score = 0; internal string state; internal TestSyntaxLevels levels = new TestSyntaxLevels(); private List<string> available; private Dictionary<string, dynamic> repeat = new Dictionary<string, dynamic>(){ } ; private List<string> selects; private Dictionary<string, dynamic> wordHash; private bool isVerbose = false; public TestSyntaxModel() { wordHash = new Dictionary<string, dynamic>(){ { "aa", true} } ; Trial(levels.GetParams()); } internal void Trial(Dictionary<string, dynamic> parameters) { wordPosition = 0.0f; help = ""; wordWidthPerSecond = -0.01f; if (parameters.ContainsKey("text")) { text = (string)(parameters["text"]); } if (parameters.ContainsKey("help")) { help = (string)(parameters["help"]); } if (parameters.ContainsKey("wordWidthPerSecond")) { wordWidthPerSecond = (float)(parameters["wordWidthPerSecond"]); } if (parameters.ContainsKey("wordPosition")) { wordPosition = (float)(parameters["wordPosition"]); } available = DataUtil.Split(text, ""); word = DataUtil.CloneList(available); if ("" == help) { Shuffle(word); wordWidthPerSecond = // -0.05; // -0.02; // -0.01; // -0.005; -0.002f; // -0.001; float power = // 1.5; // 1.75; 2.0f; int baseRate = Mathf.Max(1, letterMax - DataUtil.Length(text)); wordWidthPerSecond *= Mathf.Pow(baseRate, power); } selects = DataUtil.CloneList(word); repeat = new Dictionary<string, dynamic>(){ } ; if (isVerbose) Debug.Log("Model.trial: word[0]: <" + word[0] + ">"); } private int previous = 0; private int now = 0; internal void UpdateNow(int cumulativeMilliseconds) { float deltaSeconds = (now - previous) / 1000.0f; Update(deltaSeconds); previous = now; } internal void Update(float deltaSeconds) { UpdatePosition(deltaSeconds); } internal float width = 720; internal float scale = 1.0f; private float wordWidthPerSecond; internal void ScaleToScreen(float screenWidth) { scale = screenWidth / width; } /** * Test case: 2015-03 Use Mac. Rosa Zedek expects to read key to change level. */ private void ClampWordPosition() { float wordWidth = 160; float min = wordWidth - width; if (wordPosition <= min) { help = "GAME OVER! TO SKIP ANY WORD, PRESS THE PAGEUP KEY (MAC: FN+UP). TO GO BACK A WORD, PRESS THE PAGEDOWN KEY (MAC: FN+DOWN)."; helpState = "gameOver"; } wordPosition = Mathf.Max(min, Mathf.Min(0, wordPosition)); } private void UpdatePosition(float seconds) { wordPosition += (seconds * width * wordWidthPerSecond); ClampWordPosition(); wordPositionScaled = wordPosition * scale; if (isVerbose) Debug.Log("Model.updatePosition: " + wordPosition); } private float outputKnockback = 0.0f; internal bool MayKnockback() { return 0 < outputKnockback && 1 <= DataUtil.Length(outputs); } /** * Clamp word to appear on screen. Test case: 2015-04-18 Complete word. See next word slide in. */ private void PrepareKnockback(int length, bool complete) { float perLength = 0.03f; // 0.05; // 0.1; outputKnockback = perLength * width * length; if (complete) { outputKnockback *= 3; } ClampWordPosition(); } internal bool OnOutputHitsWord() { bool enabled = MayKnockback(); if (enabled) { wordPosition += outputKnockback; Shuffle(word); selects = DataUtil.CloneList(word); for (int i = 0; i < DataUtil.Length(inputs); i++) { string letter = inputs[i]; int selected = selects.IndexOf(letter); if (0 <= selected) { selects[selected] = letter.ToLower(); } } outputKnockback = 0; } return enabled; } /** * @param justPressed Filter signature justPressed(letter):Boolean. */ internal List<string> GetPresses(/*<Function>*/IsJustPressed justPressed) { List<string> presses = new List<string>(); Dictionary<string, dynamic> letters = new Dictionary<string, dynamic>(){ } ; for (int i = 0; i < DataUtil.Length(available); i++) { string letter = available[i]; if (letters.ContainsKey(letter)) { continue; } else { letters[letter] = true; } if (justPressed(letter)) { presses.Add(letter); } } return presses; } /** * If letter not available, disable typing it. * @return Vector of word indexes. */ internal List<int> Press(List<string> presses) { Dictionary<string, dynamic> letters = new Dictionary<string, dynamic>(){ } ; List<int> selectsNow = new List<int>(); for (int i = 0; i < DataUtil.Length(presses); i++) { string letter = presses[i]; if (letters.ContainsKey(letter)) { continue; } else { letters[letter] = true; } int index = available.IndexOf(letter); if (0 <= index) { available.RemoveRange(index, 1); inputs.Add(letter); int selected = selects.IndexOf(letter); if (0 <= selected) { selectsNow.Add(selected); selects[selected] = letter.ToLower(); } } } return selectsNow; } internal List<int> Backspace() { List<int> selectsNow = new List<int>(); if (1 <= DataUtil.Length(inputs)) { string letter = DataUtil.Pop(inputs); available.Add(letter); int selected = selects.LastIndexOf(letter.ToLower()); if (0 <= selected) { selectsNow.Add(selected); selects[selected] = letter; } } return selectsNow; } /** * @return animation state. * "submit" or "complete": Word shoots. Test case: 2015-04-18 Anders sees word is a weapon. * "submit": Shuffle letters. Test case: 2015-04-18 Jennifer wants to shuffle. Irregular arrangement of letters. Jennifer feels uncomfortable. * Test case: 2015-04-19 Backspace. Deselect. Submit. Type. Select. */ internal string Submit() { string submission = DataUtil.Join(inputs, ""); bool accepted = false; state = "wrong"; if (1 <= DataUtil.Length(submission)) { if (wordHash.ContainsKey(submission)) { if (repeat.ContainsKey(submission)) { state = "repeat"; if (levels.index <= 50 && "" == help) { help = "YOU CAN ONLY ENTER EACH SHORTER WORD ONCE."; helpState = "repeat"; } } else { if ("repeat" == helpState) { helpState = ""; help = ""; } repeat[submission] = true; accepted = true; ScoreUp(submission); bool complete = DataUtil.Length(text) == DataUtil.Length(submission); PrepareKnockback(DataUtil.Length(submission), complete); if (complete) { completes = DataUtil.CloneList(word); Trial(levels.Up()); state = "complete"; if (null != onComplete) { onComplete(); } } else { state = "submit"; } } } outputs = DataUtil.CloneList(inputs); } if (isVerbose) Debug.Log("Model.submit: " + submission + ". Accepted " + accepted); DataUtil.Clear(inputs); available = DataUtil.CloneList(word); selects = DataUtil.CloneList(word); return state; } private void ScoreUp(string submission) { points = DataUtil.Length(submission); score += points; } internal void CheatLevelUp(int add) { score = 0; Trial(levels.Up(add)); wordPosition = 0.0f; } } }
// This file was created automatically, do not modify the contents of this file. // ReSharper disable InvalidXmlDocComment // ReSharper disable InconsistentNaming // ReSharper disable CheckNamespace // ReSharper disable MemberCanBePrivate.Global using System; using System.Runtime.InteropServices; // Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\GameFramework\SpectatorPawnMovement.h:15 namespace UnrealEngine { [ManageType("ManageSpectatorPawnMovement")] public partial class ManageSpectatorPawnMovement : USpectatorPawnMovement, IManageWrapper { public ManageSpectatorPawnMovement(IntPtr adress) : base(adress) { } #region DLLInmport [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_ApplyControlInputToVelocity(IntPtr self, float deltaTime); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_StopActiveMovement(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_OnTeleported(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_SetPlaneConstraintEnabled(IntPtr self, bool bEnabled); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_SnapUpdatedComponentToPlane(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_StopMovementImmediately(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_UpdateComponentVelocity(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_UpdateTickRegistration(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_Activate(IntPtr self, bool bReset); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_BeginPlay(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_CreateRenderState_Concurrent(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_Deactivate(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_DestroyComponent(IntPtr self, bool bPromoteChildren); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_DestroyRenderState_Concurrent(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_InitializeComponent(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_InvalidateLightingCacheDetailed(IntPtr self, bool bInvalidateBuildEnqueuedLighting, bool bTranslationOnly); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_OnActorEnableCollisionChanged(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_OnComponentCreated(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_OnComponentDestroyed(IntPtr self, bool bDestroyingHierarchy); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_OnCreatePhysicsState(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_OnDestroyPhysicsState(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_OnRegister(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_OnRep_IsActive(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_OnUnregister(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_RegisterComponentTickFunctions(IntPtr self, bool bRegister); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_SendRenderDynamicData_Concurrent(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_SendRenderTransform_Concurrent(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_SetActive(IntPtr self, bool bNewActive, bool bReset); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_SetAutoActivate(IntPtr self, bool bNewAutoActivate); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_SetComponentTickEnabled(IntPtr self, bool bEnabled); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_SetComponentTickEnabledAsync(IntPtr self, bool bEnabled); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_ToggleActive(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_UninitializeComponent(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_BeginDestroy(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_FinishDestroy(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_MarkAsEditorOnlySubobject(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_PostCDOContruct(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_PostEditImport(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_PostInitProperties(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_PostLoad(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_PostNetReceive(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_PostRepNotifies(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_PostSaveRoot(IntPtr self, bool bCleanupIsRequired); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_PreDestroyFromReplication(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_PreNetReceive(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_ShutdownAfterError(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_CreateCluster(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__USpectatorPawnMovement_OnClusterMarkedAsPendingKill(IntPtr self); #endregion #region Methods /// <summary> /// Update Velocity based on input. Also applies gravity. /// </summary> protected override void ApplyControlInputToVelocity(float deltaTime) => E__Supper__USpectatorPawnMovement_ApplyControlInputToVelocity(this, deltaTime); /// <summary> /// Stops applying further movement (usually zeros acceleration). /// </summary> public override void StopActiveMovement() => E__Supper__USpectatorPawnMovement_StopActiveMovement(this); /// <summary> /// Called by owning Actor upon successful teleport from AActor::TeleportTo(). /// </summary> public override void OnTeleported() => E__Supper__USpectatorPawnMovement_OnTeleported(this); /// <summary> /// Sets whether or not the plane constraint is enabled. /// </summary> public override void SetPlaneConstraintEnabled(bool bEnabled) => E__Supper__USpectatorPawnMovement_SetPlaneConstraintEnabled(this, bEnabled); /// <summary> /// Snap the updated component to the plane constraint, if enabled. /// </summary> public override void SnapUpdatedComponentToPlane() => E__Supper__USpectatorPawnMovement_SnapUpdatedComponentToPlane(this); /// <summary> /// Stops movement immediately (zeroes velocity, usually zeros acceleration for components with acceleration). /// </summary> public override void StopMovementImmediately() => E__Supper__USpectatorPawnMovement_StopMovementImmediately(this); /// <summary> /// Update ComponentVelocity of UpdatedComponent. This needs to be called by derived classes at the end of an update whenever Velocity has changed. /// </summary> public override void UpdateComponentVelocity() => E__Supper__USpectatorPawnMovement_UpdateComponentVelocity(this); /// <summary> /// Update tick registration state, determined by bAutoUpdateTickRegistration. Called by SetUpdatedComponent. /// </summary> public override void UpdateTickRegistration() => E__Supper__USpectatorPawnMovement_UpdateTickRegistration(this); /// <summary> /// Activates the SceneComponent, should be overridden by native child classes. /// </summary> /// <param name="bReset">Whether the activation should happen even if ShouldActivate returns false.</param> public override void Activate(bool bReset) => E__Supper__USpectatorPawnMovement_Activate(this, bReset); /// <summary> /// BeginsPlay for the component. Occurs at level startup or actor spawn. This is before BeginPlay (Actor or Component). /// <para>All Components (that want initialization) in the level will be Initialized on load before any </para> /// Actor/Component gets BeginPlay. /// <para>Requires component to be registered and initialized. </para> /// </summary> public override void BeginPlay() => E__Supper__USpectatorPawnMovement_BeginPlay(this); /// <summary> /// Used to create any rendering thread information for this component /// <para>@warning This is called concurrently on multiple threads (but never the same component concurrently) </para> /// </summary> protected override void CreateRenderState_Concurrent() => E__Supper__USpectatorPawnMovement_CreateRenderState_Concurrent(this); /// <summary> /// Deactivates the SceneComponent. /// </summary> public override void Deactivate() => E__Supper__USpectatorPawnMovement_Deactivate(this); /// <summary> /// Unregister the component, remove it from its outer Actor's Components array and mark for pending kill. /// </summary> public override void DestroyComponent(bool bPromoteChildren) => E__Supper__USpectatorPawnMovement_DestroyComponent(this, bPromoteChildren); /// <summary> /// Used to shut down any rendering thread structure for this component /// <para>@warning This is called concurrently on multiple threads (but never the same component concurrently) </para> /// </summary> protected override void DestroyRenderState_Concurrent() => E__Supper__USpectatorPawnMovement_DestroyRenderState_Concurrent(this); /// <summary> /// Initializes the component. Occurs at level startup or actor spawn. This is before BeginPlay (Actor or Component). /// <para>All Components in the level will be Initialized on load before any Actor/Component gets BeginPlay </para> /// Requires component to be registered, and bWantsInitializeComponent to be true. /// </summary> public override void InitializeComponent() => E__Supper__USpectatorPawnMovement_InitializeComponent(this); /// <summary> /// Called when this actor component has moved, allowing it to discard statically cached lighting information. /// </summary> public override void InvalidateLightingCacheDetailed(bool bInvalidateBuildEnqueuedLighting, bool bTranslationOnly) => E__Supper__USpectatorPawnMovement_InvalidateLightingCacheDetailed(this, bInvalidateBuildEnqueuedLighting, bTranslationOnly); /// <summary> /// Called on each component when the Actor's bEnableCollisionChanged flag changes /// </summary> public override void OnActorEnableCollisionChanged() => E__Supper__USpectatorPawnMovement_OnActorEnableCollisionChanged(this); /// <summary> /// Called when a component is created (not loaded). This can happen in the editor or during gameplay /// </summary> public override void OnComponentCreated() => E__Supper__USpectatorPawnMovement_OnComponentCreated(this); /// <summary> /// Called when a component is destroyed /// </summary> /// <param name="bDestroyingHierarchy">True if the entire component hierarchy is being torn down, allows avoiding expensive operations</param> public override void OnComponentDestroyed(bool bDestroyingHierarchy) => E__Supper__USpectatorPawnMovement_OnComponentDestroyed(this, bDestroyingHierarchy); /// <summary> /// Used to create any physics engine information for this component /// </summary> protected override void OnCreatePhysicsState() => E__Supper__USpectatorPawnMovement_OnCreatePhysicsState(this); /// <summary> /// Used to shut down and physics engine structure for this component /// </summary> protected override void OnDestroyPhysicsState() => E__Supper__USpectatorPawnMovement_OnDestroyPhysicsState(this); /// <summary> /// Called when a component is registered, after Scene is set, but before CreateRenderState_Concurrent or OnCreatePhysicsState are called. /// </summary> protected override void OnRegister() => E__Supper__USpectatorPawnMovement_OnRegister(this); public override void OnRep_IsActive() => E__Supper__USpectatorPawnMovement_OnRep_IsActive(this); /// <summary> /// Called when a component is unregistered. Called after DestroyRenderState_Concurrent and OnDestroyPhysicsState are called. /// </summary> protected override void OnUnregister() => E__Supper__USpectatorPawnMovement_OnUnregister(this); /// <summary> /// Virtual call chain to register all tick functions /// </summary> /// <param name="bRegister">true to register, false, to unregister</param> protected override void RegisterComponentTickFunctions(bool bRegister) => E__Supper__USpectatorPawnMovement_RegisterComponentTickFunctions(this, bRegister); /// <summary> /// Called to send dynamic data for this component to the rendering thread /// </summary> protected override void SendRenderDynamicData_Concurrent() => E__Supper__USpectatorPawnMovement_SendRenderDynamicData_Concurrent(this); /// <summary> /// Called to send a transform update for this component to the rendering thread /// <para>@warning This is called concurrently on multiple threads (but never the same component concurrently) </para> /// </summary> protected override void SendRenderTransform_Concurrent() => E__Supper__USpectatorPawnMovement_SendRenderTransform_Concurrent(this); /// <summary> /// Sets whether the component is active or not /// </summary> /// <param name="bNewActive">The new active state of the component</param> /// <param name="bReset">Whether the activation should happen even if ShouldActivate returns false.</param> public override void SetActive(bool bNewActive, bool bReset) => E__Supper__USpectatorPawnMovement_SetActive(this, bNewActive, bReset); /// <summary> /// Sets whether the component should be auto activate or not. Only safe during construction scripts. /// </summary> /// <param name="bNewAutoActivate">The new auto activate state of the component</param> public override void SetAutoActivate(bool bNewAutoActivate) => E__Supper__USpectatorPawnMovement_SetAutoActivate(this, bNewAutoActivate); /// <summary> /// Set this component's tick functions to be enabled or disabled. Only has an effect if the function is registered /// </summary> /// <param name="bEnabled">Whether it should be enabled or not</param> public override void SetComponentTickEnabled(bool bEnabled) => E__Supper__USpectatorPawnMovement_SetComponentTickEnabled(this, bEnabled); /// <summary> /// Spawns a task on GameThread that will call SetComponentTickEnabled /// </summary> /// <param name="bEnabled">Whether it should be enabled or not</param> public override void SetComponentTickEnabledAsync(bool bEnabled) => E__Supper__USpectatorPawnMovement_SetComponentTickEnabledAsync(this, bEnabled); /// <summary> /// Toggles the active state of the component /// </summary> public override void ToggleActive() => E__Supper__USpectatorPawnMovement_ToggleActive(this); /// <summary> /// Handle this component being Uninitialized. /// <para>Called from AActor::EndPlay only if bHasBeenInitialized is true </para> /// </summary> public override void UninitializeComponent() => E__Supper__USpectatorPawnMovement_UninitializeComponent(this); /// <summary> /// Called before destroying the object. This is called immediately upon deciding to destroy the object, to allow the object to begin an /// <para>asynchronous cleanup process. </para> /// </summary> public override void BeginDestroy() => E__Supper__USpectatorPawnMovement_BeginDestroy(this); /// <summary> /// Called to finish destroying the object. After UObject::FinishDestroy is called, the object's memory should no longer be accessed. /// <para>@warning Because properties are destroyed here, Super::FinishDestroy() should always be called at the end of your child class's FinishDestroy() method, rather than at the beginning. </para> /// </summary> public override void FinishDestroy() => E__Supper__USpectatorPawnMovement_FinishDestroy(this); /// <summary> /// Called during subobject creation to mark this component as editor only, which causes it to get stripped in packaged builds /// </summary> public override void MarkAsEditorOnlySubobject() => E__Supper__USpectatorPawnMovement_MarkAsEditorOnlySubobject(this); /// <summary> /// Called after the C++ constructor has run on the CDO for a class. This is an obscure routine used to deal with the recursion /// <para>in the construction of the default materials </para> /// </summary> public override void PostCDOContruct() => E__Supper__USpectatorPawnMovement_PostCDOContruct(this); /// <summary> /// Called after importing property values for this object (paste, duplicate or .t3d import) /// <para>Allow the object to perform any cleanup for properties which shouldn't be duplicated or </para> /// are unsupported by the script serialization /// </summary> public override void PostEditImport() => E__Supper__USpectatorPawnMovement_PostEditImport(this); /// <summary> /// Called after the C++ constructor and after the properties have been initialized, including those loaded from config. /// <para>This is called before any serialization or other setup has happened. </para> /// </summary> public override void PostInitProperties() => E__Supper__USpectatorPawnMovement_PostInitProperties(this); /// <summary> /// Do any object-specific cleanup required immediately after loading an object. /// <para>This is not called for newly-created objects, and by default will always execute on the game thread. </para> /// </summary> public override void PostLoad() => E__Supper__USpectatorPawnMovement_PostLoad(this); /// <summary> /// Called right after receiving a bunch /// </summary> public override void PostNetReceive() => E__Supper__USpectatorPawnMovement_PostNetReceive(this); /// <summary> /// Called right after calling all OnRep notifies (called even when there are no notifies) /// </summary> public override void PostRepNotifies() => E__Supper__USpectatorPawnMovement_PostRepNotifies(this); /// <summary> /// Called from within SavePackage on the passed in base/root object. /// <para>This function is called after the package has been saved and can perform cleanup. </para> /// </summary> /// <param name="bCleanupIsRequired">Whether PreSaveRoot dirtied state that needs to be cleaned up</param> public override void PostSaveRoot(bool bCleanupIsRequired) => E__Supper__USpectatorPawnMovement_PostSaveRoot(this, bCleanupIsRequired); /// <summary> /// Called right before being marked for destruction due to network replication /// </summary> public override void PreDestroyFromReplication() => E__Supper__USpectatorPawnMovement_PreDestroyFromReplication(this); /// <summary> /// Called right before receiving a bunch /// </summary> public override void PreNetReceive() => E__Supper__USpectatorPawnMovement_PreNetReceive(this); /// <summary> /// After a critical error, perform any mission-critical cleanup, such as restoring the video mode orreleasing hardware resources. /// </summary> public override void ShutdownAfterError() => E__Supper__USpectatorPawnMovement_ShutdownAfterError(this); /// <summary> /// Called after PostLoad to create UObject cluster /// </summary> public override void CreateCluster() => E__Supper__USpectatorPawnMovement_CreateCluster(this); /// <summary> /// Called during Garbage Collection to perform additional cleanup when the cluster is about to be destroyed due to PendingKill flag being set on it. /// </summary> public override void OnClusterMarkedAsPendingKill() => E__Supper__USpectatorPawnMovement_OnClusterMarkedAsPendingKill(this); #endregion public static implicit operator IntPtr(ManageSpectatorPawnMovement self) { return self?.NativePointer ?? IntPtr.Zero; } public static implicit operator ManageSpectatorPawnMovement(ObjectPointerDescription PtrDesc) { return NativeManager.GetWrapper<ManageSpectatorPawnMovement>(PtrDesc); } } }
using System; using System.Collections.Generic; using System.Linq; #if NETFX_CORE using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using SetUp = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestInitializeAttribute; using TearDown = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestCleanupAttribute; using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute; #else using NUnit.Framework; #endif namespace SQLite.Tests { [TestFixture] public class TransactionTest { private TestDb db; private List<TestObj> testObjects; public class TestObj { [AutoIncrement, PrimaryKey] public int Id { get; set; } public override string ToString() { return string.Format("[TestObj: Id={0}]", Id); } } public class TransactionTestException : Exception { } public class TestDb : SQLiteConnection { public TestDb(String path) : base(path) { CreateTable<TestObj>(); } } [SetUp] public void Setup() { testObjects = Enumerable.Range(1, 20).Select(i => new TestObj()).ToList(); db = new TestDb(TestPath.GetTempFileName()); db.InsertAll(testObjects); } [TearDown] public void TearDown() { if (db != null) { db.Close(); } } [Test] public void SuccessfulSavepointTransaction() { db.RunInTransaction(() => { db.Delete(testObjects[0]); db.Delete(testObjects[1]); db.Insert(new TestObj()); }); Assert.AreEqual(testObjects.Count - 1, db.Table<TestObj>().Count()); } [Test] public void FailSavepointTransaction() { try { db.RunInTransaction(() => { db.Delete(testObjects[0]); throw new TransactionTestException(); }); } catch (TransactionTestException) { // ignore } Assert.AreEqual(testObjects.Count, db.Table<TestObj>().Count()); } [Test] public void SuccessfulNestedSavepointTransaction() { db.RunInTransaction(() => { db.Delete(testObjects[0]); db.RunInTransaction(() => { db.Delete(testObjects[1]); }); }); Assert.AreEqual(testObjects.Count - 2, db.Table<TestObj>().Count()); } [Test] public void FailNestedSavepointTransaction() { try { db.RunInTransaction(() => { db.Delete(testObjects[0]); db.RunInTransaction(() => { db.Delete(testObjects[1]); throw new TransactionTestException(); }); }); } catch (TransactionTestException) { // ignore } Assert.AreEqual(testObjects.Count, db.Table<TestObj>().Count()); } [Test] public void Issue329_AsyncTransactionFailuresShouldRollback () { var adb = new SQLiteAsyncConnection (TestPath.GetTempFileName ()); adb.CreateTableAsync<TestObj> ().Wait (); var initialCount = adb.Table<TestObj> ().CountAsync ().Result; var rollbacks = 0; // // Fail a commit // adb.Trace = true; adb.Tracer = m => { Console.WriteLine (m); if (m == "Executing: rollback") rollbacks++; }; try { adb.RunInTransactionAsync (db => { db.Insert (new TestObj ()); throw new Exception ("User exception"); }).Wait (); Assert.Fail ("Should have thrown"); } catch (AggregateException aex) when (aex.InnerException.Message == "User exception") { // Expected } Assert.AreEqual (1, rollbacks); } [Test] public void Issue604_RunInTransactionAsync () { var adb = new SQLiteAsyncConnection (TestPath.GetTempFileName ()); adb.CreateTableAsync<TestObj> ().Wait (); var initialCount = adb.Table<TestObj> ().CountAsync ().Result; // // Fail a commit // adb.Trace = true; adb.Tracer = m => { //Console.WriteLine (m); if (m.Trim().EndsWith ("commit")) throw SQLiteException.New (SQLite3.Result.Busy, "Make commit fail"); }; try { adb.RunInTransactionAsync (db => { db.Insert (new TestObj ()); }).Wait (); Assert.Fail ("Should have thrown"); } catch (AggregateException aex) when (aex.InnerException is SQLiteException ex && ex.Result == SQLite3.Result.Busy) { // Expected } // // Are we stuck? // adb.Tracer = null; adb.RunInTransactionAsync (db => { db.Insert (new TestObj ()); }).Wait (); Assert.AreEqual (initialCount + 1, adb.Table<TestObj> ().CountAsync ().Result); } [Test] public void Issue604_RecoversFromFailedCommit () { db.Trace = true; var initialCount = db.Table<TestObj> ().Count (); // // Well this is an issue because there is an internal variable called _transactionDepth // that tries to track if we are in an active transaction. // The problem is, _transactionDepth is set to 0 and then commit is executed on the database. // Well, the commit fails and "When COMMIT fails in this way, the transaction remains active and // the COMMIT can be retried later after the reader has had a chance to clear" // var rollbacks = 0; db.Tracer = m => { if (m == "Executing: commit") throw SQLiteException.New (SQLite3.Result.Busy, "Make commit fail"); if (m == "Executing: rollback") rollbacks++; }; db.BeginTransaction (); db.Insert (new TestObj ()); try { db.Commit (); Assert.Fail ("Should have thrown"); } catch (SQLiteException ex) when (ex.Result == SQLite3.Result.Busy) { db.Tracer = null; } Assert.False (db.IsInTransaction); Assert.AreEqual (1, rollbacks); // // The catch statements in the RunInTransaction family of functions catch this and call rollback, // but since _transactionDepth is 0, the transaction isn't actually rolled back. // // So the next time begin transaction is called on the same connection, // sqlite-net attempts to begin a new transaction (because _transactionDepth is 0), // which promptly fails because there is still an active transaction on the connection. // // Well now we are in big trouble because _transactionDepth got set to 1, // and when begin transaction fails in this manner, the transaction isn't rolled back // (which would have set _transactionDepth to 0) // db.BeginTransaction (); db.Insert (new TestObj ()); db.Commit (); Assert.AreEqual (initialCount + 1, db.Table<TestObj> ().Count ()); } [Test] public void Issue604_RecoversFromFailedRelease () { db.Trace = true; var initialCount = db.Table<TestObj> ().Count (); var rollbacks = 0; db.Tracer = m => { //Console.WriteLine (m); if (m.StartsWith ("Executing: release")) throw SQLiteException.New (SQLite3.Result.Busy, "Make release fail"); if (m == "Executing: rollback") rollbacks++; }; var sp0 = db.SaveTransactionPoint (); db.Insert (new TestObj ()); try { db.Release (sp0); Assert.Fail ("Should have thrown"); } catch (SQLiteException ex) when (ex.Result == SQLite3.Result.Busy) { db.Tracer = null; } Assert.False (db.IsInTransaction); Assert.AreEqual (1, rollbacks); db.BeginTransaction (); db.Insert (new TestObj ()); db.Commit (); Assert.AreEqual (initialCount + 1, db.Table<TestObj> ().Count ()); } } }
// 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.Text; using Microsoft.Build.Shared; using Microsoft.Build.Utilities; using Microsoft.Build.UnitTests; using System.IO; using Microsoft.Build.Tasks; using Xunit; namespace Microsoft.Build.UnitTests { sealed public class SdkToolsPathUtility_Tests { private string _defaultSdkToolsPath = NativeMethodsShared.IsWindows ? "C:\\ProgramFiles\\WIndowsSDK\\bin" : "/ProgramFiles/WindowsSDK/bin"; private TaskLoggingHelper _log = null; private string _toolName = "MyTool.exe"; private MockEngine _mockEngine = null; private MockFileExists _mockExists = null; public SdkToolsPathUtility_Tests() { // Create a delegate helper to make the testing of a method which uses a lot of fileExists a bit easier _mockExists = new MockFileExists(_defaultSdkToolsPath); // We need an engine to see any logging messages the method may log _mockEngine = new MockEngine(); // Dummy task to get a TaskLoggingHelper TaskToLogFrom loggingTask = new TaskToLogFrom(); loggingTask.BuildEngine = _mockEngine; _log = loggingTask.Log; _log.TaskResources = AssemblyResources.PrimaryResources; } #region Misc /// <summary> /// Test the case where the sdkToolsPath is null or empty /// </summary> [Fact] public void GeneratePathToToolNullOrEmptySdkToolPath() { string toolPath = SdkToolsPathUtility.GeneratePathToTool(_mockExists.MockFileExistsOnlyInX86, ProcessorArchitecture.X86, null, _toolName, _log, true); Assert.Null(toolPath); string comment = ResourceUtilities.FormatResourceStringStripCodeAndKeyword("General.SdkToolsPathNotSpecifiedOrToolDoesNotExist", _toolName, null); _mockEngine.AssertLogContains(comment); Assert.Equal(0, _mockEngine.Warnings); comment = ResourceUtilities.FormatResourceStringStripCodeAndKeyword("General.SdkToolsPathToolDoesNotExist", _toolName, null, ToolLocationHelper.GetDotNetFrameworkSdkRootRegistryKey(TargetDotNetFrameworkVersion.Latest)); _mockEngine.AssertLogContains(comment); Assert.Equal(1, _mockEngine.Errors); } /// <summary> /// Test the case where the sdkToolsPath is null or empty and we do not want to log errors or warnings /// </summary> [Fact] public void GeneratePathToToolNullOrEmptySdkToolPathNoLogging() { string toolPath = SdkToolsPathUtility.GeneratePathToTool(_mockExists.MockFileExistsOnlyInX86, ProcessorArchitecture.X86, null, _toolName, _log, false); Assert.Null(toolPath); string comment = ResourceUtilities.FormatResourceStringStripCodeAndKeyword("General.SdkToolsPathNotSpecifiedOrToolDoesNotExist", _toolName, null); _mockEngine.AssertLogDoesntContain(comment); Assert.Equal(0, _mockEngine.Warnings); comment = ResourceUtilities.FormatResourceStringStripCodeAndKeyword("General.SdkToolsPathToolDoesNotExist", _toolName, null, ToolLocationHelper.GetDotNetFrameworkSdkRootRegistryKey(TargetDotNetFrameworkVersion.Version45)); _mockEngine.AssertLogDoesntContain(comment); Assert.Equal(0, _mockEngine.Errors); } #endregion #region Test x86 /// <summary> /// Test the case where the processor architecture is x86 and the tool exists in the x86 sdk path /// </summary> [Fact] public void GeneratePathToToolX86ExistsOnx86() { string toolPath = SdkToolsPathUtility.GeneratePathToTool(_mockExists.MockFileExistsOnlyInX86, ProcessorArchitecture.X86, _defaultSdkToolsPath, _toolName, _log, true); // Path we expect to get out of the method string expectedPath = Path.Combine(_defaultSdkToolsPath, _toolName); Assert.Equal(expectedPath, toolPath); Assert.True(String.IsNullOrEmpty(_mockEngine.Log)); } #endregion #region Test x64 /// <summary> /// Test the case where the processor architecture is x64 and the tool exists in the x64 sdk path /// </summary> [Fact] public void GeneratePathToToolX64ExistsOnx64() { string toolPath = SdkToolsPathUtility.GeneratePathToTool(_mockExists.MockFileExistsOnlyInX64, ProcessorArchitecture.AMD64, _defaultSdkToolsPath, _toolName, _log, true); // Path we expect to get out of the method string expectedPath = Path.Combine(_defaultSdkToolsPath, "x64"); expectedPath = Path.Combine(expectedPath, _toolName); Assert.Equal(expectedPath, toolPath); Assert.True(String.IsNullOrEmpty(_mockEngine.Log)); } /// <summary> /// Test the case where the processor architecture is x64 and the tool does not exists in the x64 sdk path but does exist in the x86 path /// </summary> [Fact] public void GeneratePathToToolX64ExistsOnx86() { string toolPath = SdkToolsPathUtility.GeneratePathToTool(_mockExists.MockFileExistsOnlyInX86, ProcessorArchitecture.AMD64, _defaultSdkToolsPath, _toolName, _log, true); // Path we expect to get out of the method string expectedPath = Path.Combine(_defaultSdkToolsPath, _toolName); Assert.Equal(expectedPath, toolPath); Assert.True(String.IsNullOrEmpty(_mockEngine.Log)); } #endregion #region Test Ia64 /// <summary> /// Test the case where the processor architecture is ia64 and the tool exists in the ia64 sdk path /// </summary> [Fact] public void GeneratePathToToolIa64ExistsOnIa64() { string toolPath = SdkToolsPathUtility.GeneratePathToTool(_mockExists.MockFileExistsOnlyInIa64, ProcessorArchitecture.IA64, _defaultSdkToolsPath, _toolName, _log, true); // Path we expect to get out of the method string expectedPath = Path.Combine(_defaultSdkToolsPath, "ia64"); expectedPath = Path.Combine(expectedPath, _toolName); Assert.Equal(expectedPath, toolPath); Assert.True(String.IsNullOrEmpty(_mockEngine.Log)); } /// <summary> /// Test the case where the processor architecture is ia64 and the tool does not exists in the ia64 sdk path but does exist in the x86 path /// </summary> [Fact] public void GeneratePathToToolIa64ExistsOnx86() { string toolPath = SdkToolsPathUtility.GeneratePathToTool(_mockExists.MockFileExistsOnlyInX86, ProcessorArchitecture.IA64, _defaultSdkToolsPath, _toolName, _log, true); // Path we expect to get out of the method string expectedPath = Path.Combine(_defaultSdkToolsPath, _toolName); Assert.Equal(expectedPath, toolPath); Assert.True(String.IsNullOrEmpty(_mockEngine.Log)); } #endregion /// <summary> /// Test the case where the processor architecture is x86 and the tool does not exist in the x86 sdk path (or anywhere for that matter) /// </summary> [Fact] public void GeneratePathToToolX86DoesNotExistAnywhere() { string toolPath = SdkToolsPathUtility.GeneratePathToTool(_mockExists.MockFileDoesNotExist, ProcessorArchitecture.X86, _defaultSdkToolsPath, _toolName, _log, true); Assert.Null(toolPath); string comment = ResourceUtilities.FormatResourceStringStripCodeAndKeyword("General.PlatformSDKFileNotFoundSdkToolsPath", _toolName, _defaultSdkToolsPath, _defaultSdkToolsPath); _mockEngine.AssertLogContains(comment); comment = ResourceUtilities.FormatResourceStringStripCodeAndKeyword("General.SdkToolsPathToolDoesNotExist", _toolName, _defaultSdkToolsPath, ToolLocationHelper.GetDotNetFrameworkSdkRootRegistryKey(TargetDotNetFrameworkVersion.Latest)); _mockEngine.AssertLogContains(comment); Assert.Equal(1, _mockEngine.Errors); } /// <summary> /// Test the case where there are illegal chars in the sdktoolspath and Path.combine has a problem. /// </summary> [Fact] public void VerifyErrorWithIllegalChars() { if (!NativeMethodsShared.IsWindows) { return; // "No invalid path characters under Unix" } string toolPath = SdkToolsPathUtility.GeneratePathToTool(_mockExists.MockFileDoesNotExist, ProcessorArchitecture.X86, "./?><;)(*&^%$#@!", _toolName, _log, true); Assert.Null(toolPath); _mockEngine.AssertLogContains("MSB3666"); Assert.Equal(1, _mockEngine.Errors); } /// <summary> /// Test the case where the processor architecture is x86 and the tool does not exist in the x86 sdk path (or anywhere for that matter)and we do not want to log /// </summary> [Fact] public void GeneratePathToToolX86DoesNotExistAnywhereNoLogging() { string toolPath = SdkToolsPathUtility.GeneratePathToTool(_mockExists.MockFileDoesNotExist, ProcessorArchitecture.X86, _defaultSdkToolsPath, _toolName, _log, false); Assert.Null(toolPath); string comment = ResourceUtilities.FormatResourceStringStripCodeAndKeyword("General.PlatformSDKFileNotFoundSdkToolsPath", _toolName, _defaultSdkToolsPath, _defaultSdkToolsPath); _mockEngine.AssertLogDoesntContain(comment); comment = ResourceUtilities.FormatResourceStringStripCodeAndKeyword("General.SdkToolsPathToolDoesNotExist", _toolName, _defaultSdkToolsPath, ToolLocationHelper.GetDotNetFrameworkSdkRootRegistryKey(TargetDotNetFrameworkVersion.Version45)); _mockEngine.AssertLogDoesntContain(comment); Assert.Equal(0, _mockEngine.Errors); } #region Helper Classes // Task just so we can access to a real taskLogging helper and inspect the log. internal class TaskToLogFrom : Task { /// <summary> /// Empty execute, this task will never be executed /// </summary> /// <returns></returns> public override bool Execute() { throw new NotImplementedException(); } } /// <summary> /// This class is used for testing the ability of the SdkToolsPathUtility class to handle situations when /// the toolname exists or does not exist. /// </summary> internal class MockFileExists { #region Data /// <summary> /// Path to the x86 sdk tools location /// </summary> private string _sdkToolsPath = null; #endregion #region Constructor /// <summary> /// This class gives the ability to create a fileexists delegate which helps in testing the sdktoolspath utility class /// which makes extensive use of fileexists. /// The sdkToolsPath is the expected location of the x86 sdk directory. /// </summary> public MockFileExists(string sdkToolsPath) { _sdkToolsPath = sdkToolsPath; } #endregion #region Properties /// <summary> /// A file exists object that will only return true if path passed in is the sdkToolsPath /// </summary> public FileExists MockFileExistsOnlyInX86 { get { return new FileExists(ExistsOnlyInX86); } } /// <summary> /// A file exists object that will only return true if path passed in is the sdkToolsPath\X64 /// </summary> public FileExists MockFileExistsOnlyInX64 { get { return new FileExists(ExistsOnlyInX64); } } /// <summary> /// A file exists object that will only return true if path passed in is the sdkToolsPath\Ia64 /// </summary> public FileExists MockFileExistsOnlyInIa64 { get { return new FileExists(ExistsOnlyInIa64); } } /// <summary> /// File exists delegate which will always return true /// </summary> public FileExists MockFileExistsInAll { get { return new FileExists(ExistsInAll); } } /// <summary> /// File Exists delegate which will always return false /// </summary> public FileExists MockFileDoesNotExist { get { return new FileExists(DoesNotExist); } } #endregion #region FileExists Methods /// <summary> /// A file exists object that will only return true if path passed in is the sdkToolsPath /// </summary> private bool ExistsOnlyInX86(string filePath) { return string.Equals(Path.GetDirectoryName(filePath), _sdkToolsPath, StringComparison.OrdinalIgnoreCase); } /// <summary> /// A file exists object that will only return true if path passed in is the sdkToolsPath\x64 /// </summary> private bool ExistsOnlyInX64(string filePath) { return string.Equals(Path.GetDirectoryName(filePath), Path.Combine(_sdkToolsPath, "x64"), StringComparison.OrdinalIgnoreCase); } /// <summary> /// A file exists object that will only return true if path passed in is the sdkToolsPath /// </summary> private bool ExistsOnlyInIa64(string filePath) { return string.Equals(Path.GetDirectoryName(filePath), Path.Combine(_sdkToolsPath, "ia64"), StringComparison.OrdinalIgnoreCase); } /// <summary> /// File Exists delegate which will always return true /// </summary> private bool ExistsInAll(string filePath) { return true; } /// <summary> /// File Exists delegate which will always return false /// </summary> private bool DoesNotExist(string filePath) { return false; } #endregion } #endregion } }
using System; using System.Collections; using Server.Misc; using Server.Items; using Server.Mobiles; using Server.Targeting; namespace Server.Mobiles { public class WarriorGuard : BaseGuard { private Timer m_AttackTimer, m_IdleTimer; private Mobile m_Focus; [Constructable] public WarriorGuard() : this( null ) { } public WarriorGuard( Mobile target ) : base( target ) { InitStats( 1000, 1000, 1000 ); SpeechHue = Utility.RandomDyedHue(); Hue = Utility.RandomSkinHue(); if ( Female = Utility.RandomBool() ) { Body = 0x191; Name = NameList.RandomName( "female" ); Title = "la garde"; switch( Utility.Random( 2 ) ) { case 0: AddItem( new LeatherSkirt() ); break; case 1: AddItem( new LeatherShorts() ); break; } switch( Utility.Random( 5 ) ) { case 0: AddItem( new FemaleLeatherChest() ); break; case 1: AddItem( new FemaleStuddedChest() ); break; case 2: AddItem( new LeatherBustierArms() ); break; case 3: AddItem( new StuddedBustierArms() ); break; case 4: AddItem( new FemalePlateChest() ); break; } } else { Body = 0x190; Name = NameList.RandomName( "male" ); Title = "le garde"; AddItem( new PlateChest() ); AddItem( new PlateArms() ); AddItem( new PlateLegs() ); switch( Utility.Random( 3 ) ) { case 0: AddItem( new Doublet( Utility.RandomNondyedHue() ) ); break; case 1: AddItem( new Tunic( Utility.RandomNondyedHue() ) ); break; case 2: AddItem( new BodySash( Utility.RandomNondyedHue() ) ); break; } } Utility.AssignRandomHair( this ); if( Utility.RandomBool() ) Utility.AssignRandomFacialHair( this, HairHue ); Halberd weapon = new Halberd(); weapon.Movable = false; weapon.Crafter = this; weapon.Quality = WeaponQuality.Exceptional; AddItem( weapon ); Container pack = new Backpack(); pack.Movable = false; pack.DropItem( new Gold( 10, 25 ) ); AddItem( pack ); Skills[SkillName.Anatomy].Base = 120.0; Skills[SkillName.Tactics].Base = 120.0; Skills[SkillName.Swords].Base = 120.0; Skills[SkillName.MagicResist].Base = 120.0; Skills[SkillName.DetectHidden].Base = 100.0; this.NextCombatTime = DateTime.Now + TimeSpan.FromSeconds( 0.5 ); this.Focus = target; } public WarriorGuard( Serial serial ) : base( serial ) { } public override bool OnBeforeDeath() { if ( m_Focus != null && m_Focus.Alive ) new AvengeTimer( m_Focus ).Start(); // If a guard dies, three more guards will spawn return base.OnBeforeDeath(); } [CommandProperty( AccessLevel.GameMaster )] public override Mobile Focus { get { return m_Focus; } set { if ( Deleted ) return; Mobile oldFocus = m_Focus; if ( oldFocus != value ) { m_Focus = value; if ( value != null ) this.AggressiveAction( value ); Combatant = value; if ( oldFocus != null && !oldFocus.Alive ) Say( "Thou hast suffered thy punishment, scoundrel." ); if ( value != null ) Say( 500131 ); // Thou wilt regret thine actions, swine! if ( m_AttackTimer != null ) { m_AttackTimer.Stop(); m_AttackTimer = null; } if ( m_IdleTimer != null ) { m_IdleTimer.Stop(); m_IdleTimer = null; } if ( m_Focus != null ) { m_AttackTimer = new AttackTimer( this ); m_AttackTimer.Start(); ((AttackTimer)m_AttackTimer).DoOnTick(); } else { m_IdleTimer = new IdleTimer( this ); m_IdleTimer.Start(); } } else if ( m_Focus == null && m_IdleTimer == null ) { m_IdleTimer = new IdleTimer( this ); m_IdleTimer.Start(); } } } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version writer.Write( m_Focus ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); switch ( version ) { case 0: { m_Focus = reader.ReadMobile(); if ( m_Focus != null ) { m_AttackTimer = new AttackTimer( this ); m_AttackTimer.Start(); } else { m_IdleTimer = new IdleTimer( this ); m_IdleTimer.Start(); } break; } } } public override void OnAfterDelete() { if ( m_AttackTimer != null ) { m_AttackTimer.Stop(); m_AttackTimer = null; } if ( m_IdleTimer != null ) { m_IdleTimer.Stop(); m_IdleTimer = null; } base.OnAfterDelete(); } private class AvengeTimer : Timer { private Mobile m_Focus; public AvengeTimer( Mobile focus ) : base( TimeSpan.FromSeconds( 2.5 ), TimeSpan.FromSeconds( 1.0 ), 3 ) { m_Focus = focus; } protected override void OnTick() { BaseGuard.Spawn( m_Focus, m_Focus, 1, true ); } } private class AttackTimer : Timer { private WarriorGuard m_Owner; public AttackTimer( WarriorGuard owner ) : base( TimeSpan.FromSeconds( 0.25 ), TimeSpan.FromSeconds( 0.1 ) ) { m_Owner = owner; } public void DoOnTick() { OnTick(); } protected override void OnTick() { if ( m_Owner.Deleted ) { Stop(); return; } m_Owner.Criminal = false; m_Owner.Kills = 0; m_Owner.Stam = m_Owner.StamMax; Mobile target = m_Owner.Focus; if ( target != null && (target.Deleted || !target.Alive || !m_Owner.CanBeHarmful( target )) ) { m_Owner.Focus = null; Stop(); return; } else if ( m_Owner.Weapon is Fists ) { m_Owner.Kill(); Stop(); return; } if ( target != null && m_Owner.Combatant != target ) m_Owner.Combatant = target; if ( target == null ) { Stop(); } else {// <instakill> TeleportTo( target ); target.BoltEffect( 0 ); if ( target is BaseCreature ) ((BaseCreature)target).NoKillAwards = true; target.Damage( target.HitsMax, m_Owner ); target.Kill(); // just in case, maybe Damage is overriden on some shard if ( target.Corpse != null && !target.Player ) target.Corpse.Delete(); m_Owner.Focus = null; Stop(); }// </instakill> /*else if ( !m_Owner.InRange( target, 20 ) ) { m_Owner.Focus = null; } else if ( !m_Owner.InRange( target, 10 ) || !m_Owner.InLOS( target ) ) { TeleportTo( target ); } else if ( !m_Owner.InRange( target, 1 ) ) { if ( !m_Owner.Move( m_Owner.GetDirectionTo( target ) | Direction.Running ) ) TeleportTo( target ); } else if ( !m_Owner.CanSee( target ) ) { if ( !m_Owner.UseSkill( SkillName.DetectHidden ) && Utility.Random( 50 ) == 0 ) m_Owner.Say( "Reveal!" ); }*/ } private void TeleportTo( Mobile target ) { Point3D from = m_Owner.Location; Point3D to = target.Location; m_Owner.Location = to; Effects.SendLocationParticles( EffectItem.Create( from, m_Owner.Map, EffectItem.DefaultDuration ), 0x3728, 10, 10, 2023 ); Effects.SendLocationParticles( EffectItem.Create( to, m_Owner.Map, EffectItem.DefaultDuration ), 0x3728, 10, 10, 5023 ); m_Owner.PlaySound( 0x1FE ); } } private class IdleTimer : Timer { private WarriorGuard m_Owner; private int m_Stage; public IdleTimer( WarriorGuard owner ) : base( TimeSpan.FromSeconds( 2.0 ), TimeSpan.FromSeconds( 2.5 ) ) { m_Owner = owner; } protected override void OnTick() { if ( m_Owner.Deleted ) { Stop(); return; } if ( (m_Stage++ % 4) == 0 || !m_Owner.Move( m_Owner.Direction ) ) m_Owner.Direction = (Direction)Utility.Random( 8 ); if ( m_Stage > 16 ) { Effects.SendLocationParticles( EffectItem.Create( m_Owner.Location, m_Owner.Map, EffectItem.DefaultDuration ), 0x3728, 10, 10, 2023 ); m_Owner.PlaySound( 0x1FE ); m_Owner.Delete(); } } } } }
using System; using System.Collections.Generic; using Microsoft.Data.Entity.Migrations; namespace WebApp.Migrations { public partial class PhoneOrderRequired : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles"); migrationBuilder.DropForeignKey(name: "FK_Customer_City_CityId", table: "Customer"); migrationBuilder.DropForeignKey(name: "FK_Customer_Sms_SmsId", table: "Customer"); migrationBuilder.DropForeignKey(name: "FK_Housing_City_CityId", table: "Housing"); migrationBuilder.DropForeignKey(name: "FK_Housing_District_DistrictId", table: "Housing"); migrationBuilder.DropForeignKey(name: "FK_Housing_Street_StreetId", table: "Housing"); migrationBuilder.DropForeignKey(name: "FK_Housing_TypesHousing_TypesHousingId", table: "Housing"); migrationBuilder.AlterColumn<int>( name: "TypesHousingId", table: "Housing", nullable: false); migrationBuilder.AddForeignKey( name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Customer_City_CityId", table: "Customer", column: "CityId", principalTable: "City", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Customer_Sms_SmsId", table: "Customer", column: "SmsId", principalTable: "Sms", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Housing_City_CityId", table: "Housing", column: "CityId", principalTable: "City", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Housing_District_DistrictId", table: "Housing", column: "DistrictId", principalTable: "District", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Housing_Street_StreetId", table: "Housing", column: "StreetId", principalTable: "Street", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Housing_TypesHousing_TypesHousingId", table: "Housing", column: "TypesHousingId", principalTable: "TypesHousing", principalColumn: "Id", onDelete: ReferentialAction.Cascade); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles"); migrationBuilder.DropForeignKey(name: "FK_Customer_City_CityId", table: "Customer"); migrationBuilder.DropForeignKey(name: "FK_Customer_Sms_SmsId", table: "Customer"); migrationBuilder.DropForeignKey(name: "FK_Housing_City_CityId", table: "Housing"); migrationBuilder.DropForeignKey(name: "FK_Housing_District_DistrictId", table: "Housing"); migrationBuilder.DropForeignKey(name: "FK_Housing_Street_StreetId", table: "Housing"); migrationBuilder.DropForeignKey(name: "FK_Housing_TypesHousing_TypesHousingId", table: "Housing"); migrationBuilder.AlterColumn<int>( name: "TypesHousingId", table: "Housing", nullable: true); migrationBuilder.AddForeignKey( name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Customer_City_CityId", table: "Customer", column: "CityId", principalTable: "City", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Customer_Sms_SmsId", table: "Customer", column: "SmsId", principalTable: "Sms", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Housing_City_CityId", table: "Housing", column: "CityId", principalTable: "City", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Housing_District_DistrictId", table: "Housing", column: "DistrictId", principalTable: "District", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Housing_Street_StreetId", table: "Housing", column: "StreetId", principalTable: "Street", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Housing_TypesHousing_TypesHousingId", table: "Housing", column: "TypesHousingId", principalTable: "TypesHousing", principalColumn: "Id", onDelete: ReferentialAction.Restrict); } } }
namespace GuideEnricher { using ArgusTV.DataContracts; using ArgusTV.ServiceProxy; using Config; using GuideEnricher.tvdb; using log4net; using System; using System.Reflection; using System.ServiceModel; using System.Timers; using Timer = System.Timers.Timer; public class Service : IDisposable { private const string MODULE = "GuideEnricher"; private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly IConfiguration config = Config.Config.Instance; private static Timer ftrConnectionTimer; private static Timer enrichTimer; public static bool BusyEnriching; private static object lockThis = new object(); private static int waitTime; private ForTheRecordListener eventListener; public Service() { eventListener = new ForTheRecordListener(new Action(() => Enrich(null, null)), config, log); } public void Start() { try { log.Info("Starting"); eventListener.StartEventListenerTask(); ftrConnectionTimer = new Timer(500) { AutoReset = false }; ftrConnectionTimer.Elapsed += this.SetupFTRConnection; ftrConnectionTimer.Start(); if (!int.TryParse(config.GetProperty("sleepTimeInHours"), out waitTime)) { waitTime = 12; } enrichTimer = new Timer(TimeSpan.FromSeconds(15).TotalMilliseconds) { AutoReset = false }; enrichTimer.Elapsed += Enrich; enrichTimer.Start(); } catch (Exception ex) { log.Fatal("Error on starting service", ex); throw; } } public void Stop() { eventListener.CancelEventListenerTask(); log.Info("Service stopping"); } public void SetupFTRConnection(Object state, ElapsedEventArgs eventArgs) { try { if (Proxies.IsInitialized) { if (Proxies.CoreService.Ping(Constants.RestApiVersion).Result > 0) { log.Debug("Ping"); } return; } log.Debug("Trying to connect to Argus TV"); ArgusTV.ServiceProxy.ServerSettings serverSettings = GetServerSettings(); if (Proxies.Initialize(serverSettings)) { Proxies.LogService.LogMessage(MODULE, LogSeverity.Information, "GuideEnricher successfully connected"); log.Info("Successfully connected to Argus TV"); } else { log.Fatal("Unable to connect to Argus TV, check your settings. Will try again later"); } } catch (ArgusTV.ServiceProxy.ArgusTVNotFoundException notFoundException) { log.Error(notFoundException.Message); } catch (EndpointNotFoundException) { log.Error("Connection to Argus TV lost, make sure the Argus TV service is running"); } catch (ArgusTVException ftrException) { log.Fatal(ftrException.Message); } finally { ftrConnectionTimer.Interval = TimeSpan.FromMinutes(1).TotalMilliseconds; ftrConnectionTimer.Start(); } } public static void Enrich(Object state, ElapsedEventArgs eventArgs) { try { lock (lockThis) { BusyEnriching = true; } int ping = Proxies.CoreService.Ping(Constants.RestApiVersion).Result; if (ping > 0) { log.DebugFormat("Ping {0}", ping); } var matchMethods = EpisodeMatchMethodLoader.GetMatchMethods(); var tvDbApi = new TvDbService(config.CacheFolder, config.ApiKey); var tvdbLibAccess = new TvdbLibAccess(config, matchMethods, tvDbApi); var enricher = new Enricher(config, tvdbLibAccess, matchMethods); enricher.EnrichUpcomingProgramsAsync().Wait(); } catch (Exception exception) { log.Error("Error enriching", exception); } finally { lock (lockThis) { BusyEnriching = false; } if (!enrichTimer.Enabled) { enrichTimer.Interval = TimeSpan.FromHours(waitTime).TotalMilliseconds; enrichTimer.Start(); } } } public static ArgusTV.ServiceProxy.ServerSettings GetServerSettings() { var serverSettings = new ArgusTV.ServiceProxy.ServerSettings(); serverSettings.ServerName = config.GetProperty("ftrUrlHost"); serverSettings.Transport = ArgusTV.ServiceProxy.ServiceTransport.Http; serverSettings.Port = Convert.ToInt32(config.GetProperty("ftrUrlPort")); var password = config.GetProperty("ftrUrlPassword"); var userName = config.GetProperty("ftrUserName"); if (!string.IsNullOrEmpty(userName)) { serverSettings.UserName = userName; } if (!string.IsNullOrEmpty(password)) { serverSettings.Password = password; } return serverSettings; } internal static bool InitializeConnectionToArgusTV() { ArgusTV.ServiceProxy.ServerSettings serverSettings = Service.GetServerSettings(); return Proxies.Initialize(serverSettings, false); } #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { if (this.eventListener != null) eventListener.Dispose(); // TODO: dispose managed state (managed objects). } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. disposedValue = true; } } // This code added to correctly implement the disposable pattern. public void Dispose() { // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose(true); } #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; using Xunit; namespace System.Net.WebHeaderCollectionTests { public partial class WebHeaderCollectionTest { [Fact] public void Ctor_Success() { new WebHeaderCollection(); } [Fact] public void DefaultPropertyValues_ReturnEmptyAfterConstruction_Success() { WebHeaderCollection w = new WebHeaderCollection(); Assert.Equal(0, w.AllKeys.Length); Assert.Equal(0, w.Count); Assert.Equal("\r\n", w.ToString()); Assert.Empty(w); Assert.Empty(w.AllKeys); } [Fact] public void HttpRequestHeader_Add_Success() { WebHeaderCollection w = new WebHeaderCollection(); w[HttpRequestHeader.Connection] = "keep-alive"; Assert.Equal(1, w.Count); Assert.Equal("keep-alive", w[HttpRequestHeader.Connection]); Assert.Equal("Connection", w.AllKeys[0]); } [Theory] [InlineData((HttpRequestHeader)int.MinValue)] [InlineData((HttpRequestHeader)(-1))] [InlineData((HttpRequestHeader)int.MaxValue)] public void HttpRequestHeader_AddInvalid_Throws(HttpRequestHeader header) { WebHeaderCollection w = new WebHeaderCollection(); Assert.Throws<IndexOutOfRangeException>(() => w[header] = "foo"); } [Theory] [InlineData((HttpResponseHeader)int.MinValue)] [InlineData((HttpResponseHeader)(-1))] [InlineData((HttpResponseHeader)int.MaxValue)] public void HttpResponseHeader_AddInvalid_Throws(HttpResponseHeader header) { WebHeaderCollection w = new WebHeaderCollection(); Assert.Throws<IndexOutOfRangeException>(() => w[header] = "foo"); } [Fact] public void CustomHeader_AddQuery_Success() { string customHeader = "Custom-Header"; string customValue = "Custom;.-Value"; WebHeaderCollection w = new WebHeaderCollection(); w[customHeader] = customValue; Assert.Equal(1, w.Count); Assert.Equal(customValue, w[customHeader]); Assert.Equal(customHeader, w.AllKeys[0]); } [Fact] public void HttpResponseHeader_AddQuery_CommonHeader_Success() { string headerValue = "value123"; WebHeaderCollection w = new WebHeaderCollection(); w[HttpResponseHeader.ProxyAuthenticate] = headerValue; w[HttpResponseHeader.WwwAuthenticate] = headerValue; Assert.Equal(headerValue, w[HttpResponseHeader.ProxyAuthenticate]); Assert.Equal(headerValue, w[HttpResponseHeader.WwwAuthenticate]); } [Fact] public void HttpRequest_AddQuery_CommonHeader_Success() { string headerValue = "value123"; WebHeaderCollection w = new WebHeaderCollection(); w[HttpRequestHeader.Accept] = headerValue; Assert.Equal(headerValue, w[HttpRequestHeader.Accept]); } [Fact] public void RequestThenResponseHeaders_Add_Throws() { WebHeaderCollection w = new WebHeaderCollection(); w[HttpRequestHeader.Accept] = "text/json"; Assert.Throws<InvalidOperationException>(() => w[HttpResponseHeader.ContentLength] = "123"); } [Fact] public void ResponseThenRequestHeaders_Add_Throws() { WebHeaderCollection w = new WebHeaderCollection(); w[HttpResponseHeader.ContentLength] = "123"; Assert.Throws<InvalidOperationException>(() => w[HttpRequestHeader.Accept] = "text/json"); } [Fact] public void ResponseHeader_QueryRequest_Throws() { WebHeaderCollection w = new WebHeaderCollection(); w[HttpResponseHeader.ContentLength] = "123"; Assert.Throws<InvalidOperationException>(() => w[HttpRequestHeader.Accept]); } [Fact] public void RequestHeader_QueryResponse_Throws() { WebHeaderCollection w = new WebHeaderCollection(); w[HttpRequestHeader.Accept] = "text/json"; Assert.Throws<InvalidOperationException>(() => w[HttpResponseHeader.ContentLength]); } [Fact] public void Setter_ValidName_Success() { WebHeaderCollection w = new WebHeaderCollection(); w["Accept"] = "text/json"; } [Theory] [InlineData(null)] [InlineData("")] public void Setter_NullOrEmptyName_Throws(string name) { WebHeaderCollection w = new WebHeaderCollection(); Assert.Throws<ArgumentNullException>("name", () => w[name] = "test"); } public static object[][] InvalidNames = { new object[] { "(" }, new object[] { "\u1234" }, new object[] { "\u0019" } }; [Theory, MemberData(nameof(InvalidNames))] public void Setter_InvalidName_Throws(string name) { WebHeaderCollection w = new WebHeaderCollection(); Assert.Throws<ArgumentException>("name", () => w[name] = "test"); } public static object[][] InvalidValues = { new object[] { "value1\rvalue2\r" }, new object[] { "value1\nvalue2\r" }, new object[] { "value1\u007fvalue2" }, new object[] { "value1\r\nvalue2" }, new object[] { "value1\u0019value2" } }; [Theory, MemberData(nameof(InvalidValues))] public void Setter_InvalidValue_Throws(string value) { WebHeaderCollection w = new WebHeaderCollection(); Assert.Throws<ArgumentException>("value", () => w["custom"] = value); } public static object[][] ValidValues = { new object[] { null }, new object[] { "" }, new object[] { "value1\r\n" }, new object[] { "value1\tvalue2" }, new object[] { "value1\r\n\tvalue2" }, new object[] { "value1\r\n value2" } }; [Theory, MemberData(nameof(ValidValues))] public void Setter_ValidValue_Success(string value) { WebHeaderCollection w = new WebHeaderCollection(); w["custom"] = value; } [Theory] [InlineData("name", "name")] [InlineData("name", "NaMe")] [InlineData("nAmE", "name")] public void Setter_SameHeaderTwice_Success(string firstName, string secondName) { WebHeaderCollection w = new WebHeaderCollection(); w[firstName] = "first"; w[secondName] = "second"; Assert.Equal(1, w.Count); Assert.NotEmpty(w); Assert.NotEmpty(w.AllKeys); Assert.Equal(new[] { firstName }, w.AllKeys); Assert.Equal("second", w[firstName]); Assert.Equal("second", w[secondName]); } [Theory] [InlineData(null)] [InlineData("")] public void Remove_NullOrEmptyName_Throws(string name) { WebHeaderCollection w = new WebHeaderCollection(); Assert.Throws<ArgumentNullException>("name", () => w.Remove(name)); } [Fact] public void Remove_IllegalCharacter_Throws() { WebHeaderCollection w = new WebHeaderCollection(); Assert.Throws<ArgumentException>("name", () => w.Remove("{")); } [Fact] public void Remove_EmptyCollection_Success() { WebHeaderCollection w = new WebHeaderCollection(); w.Remove("foo"); Assert.Equal(0, w.Count); Assert.Empty(w); Assert.Empty(w.AllKeys); } [Theory] [InlineData("name", "name")] [InlineData("name", "NaMe")] public void Remove_SetThenRemove_Success(string setName, string removeName) { WebHeaderCollection w = new WebHeaderCollection(); w[setName] = "value"; w.Remove(removeName); Assert.Equal(0, w.Count); Assert.Empty(w); Assert.Empty(w.AllKeys); } [Theory] [InlineData("name", "name")] [InlineData("name", "NaMe")] public void Remove_SetTwoThenRemoveOne_Success(string setName, string removeName) { WebHeaderCollection w = new WebHeaderCollection(); w[setName] = "value"; w["foo"] = "bar"; w.Remove(removeName); Assert.Equal(1, w.Count); Assert.NotEmpty(w); Assert.NotEmpty(w.AllKeys); Assert.Equal(new[] { "foo" }, w.AllKeys); Assert.Equal("bar", w["foo"]); } [Fact] public void Getter_EmptyCollection_Success() { WebHeaderCollection w = new WebHeaderCollection(); Assert.Null(w["name"]); Assert.Equal(0, w.Count); Assert.Empty(w); Assert.Empty(w.AllKeys); } [Fact] public void Getter_NonEmptyCollectionNonExistentHeader_Success() { WebHeaderCollection w = new WebHeaderCollection(); w["name"] = "value"; Assert.Null(w["foo"]); Assert.Equal(1, w.Count); Assert.NotEmpty(w); Assert.NotEmpty(w.AllKeys); Assert.Equal(new[] { "name" }, w.AllKeys); Assert.Equal("value", w["name"]); } [Fact] public void Getter_Success() { string[] keys = { "Accept", "uPgRaDe", "Custom" }; string[] values = { "text/plain, text/html", " HTTP/2.0 , SHTTP/1.3, , RTA/x11 ", "\"xyzzy\", \"r2d2xxxx\", \"c3piozzzz\"" }; WebHeaderCollection w = new WebHeaderCollection(); for (int i = 0; i < keys.Length; ++i) { string key = keys[i]; string value = values[i]; w[key] = value; } for (int i = 0; i < keys.Length; ++i) { string key = keys[i]; string expected = values[i].Trim(); Assert.Equal(expected, w[key]); Assert.Equal(expected, w[key.ToUpperInvariant()]); Assert.Equal(expected, w[key.ToLowerInvariant()]); } } [Fact] public void ToString_Empty_Success() { WebHeaderCollection w = new WebHeaderCollection(); Assert.Equal("\r\n", w.ToString()); } [Theory] [InlineData(null)] [InlineData("")] public void ToString_SingleHeaderWithEmptyValue_Success(string value) { WebHeaderCollection w = new WebHeaderCollection(); w["name"] = value; Assert.Equal("name: \r\n\r\n", w.ToString()); } [Fact] public void ToString_NotEmpty_Success() { WebHeaderCollection w = new WebHeaderCollection(); w["Accept"] = "text/plain"; w["Content-Length"] = "123"; Assert.Equal( "Accept: text/plain\r\nContent-Length: 123\r\n\r\n", w.ToString()); } [Fact] public void IterateCollection_Success() { WebHeaderCollection w = new WebHeaderCollection(); w["Accept"] = "text/plain"; w["Content-Length"] = "123"; string result = ""; foreach (var item in w) { result += item; } Assert.Equal("AcceptContent-Length", result); } [Fact] public void Enumerator_Success() { string item1 = "Accept"; string item2 = "Content-Length"; string item3 = "Name"; WebHeaderCollection w = new WebHeaderCollection(); w[item1] = "text/plain"; w[item2] = "123"; w[item3] = "value"; IEnumerable collection = w; IEnumerator e = collection.GetEnumerator(); for (int i = 0; i < 2; i++) { // Not started Assert.Throws<InvalidOperationException>(() => e.Current); Assert.True(e.MoveNext()); Assert.Same(item1, e.Current); Assert.True(e.MoveNext()); Assert.Same(item2, e.Current); Assert.True(e.MoveNext()); Assert.Same(item3, e.Current); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); // Ended Assert.Throws<InvalidOperationException>(() => e.Current); e.Reset(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace System.IO { /// <summary> /// Wrapper to help with path normalization. /// </summary> unsafe internal class PathHelper { // Can't be over 8.3 and be a short name private const int MaxShortName = 12; private const char LastAnsi = (char)255; private const char Delete = (char)127; // Trim trailing white spaces, tabs etc but don't be aggressive in removing everything that has UnicodeCategory of trailing space. // string.WhitespaceChars will trim more aggressively than what the underlying FS does (for ex, NTFS, FAT). private static readonly char[] s_trimEndChars = { (char)0x9, // Horizontal tab (char)0xA, // Line feed (char)0xB, // Vertical tab (char)0xC, // Form feed (char)0xD, // Carriage return (char)0x20, // Space (char)0x85, // Next line (char)0xA0 // Non breaking space }; [ThreadStatic] private static StringBuffer t_fullPathBuffer; /// <summary> /// Normalize the given path. /// </summary> /// <remarks> /// Normalizes via Win32 GetFullPathName(). It will also trim all "typical" whitespace at the end of the path (see s_trimEndChars). Will also trim initial /// spaces if the path is determined to be rooted. /// /// Note that invalid characters will be checked after the path is normalized, which could remove bad characters. (C:\|\..\a.txt -- C:\a.txt) /// </remarks> /// <param name="path">Path to normalize</param> /// <param name="checkInvalidCharacters">True to check for invalid characters</param> /// <param name="expandShortPaths">Attempt to expand short paths if true</param> /// <exception cref="ArgumentException">Thrown if the path is an illegal UNC (does not contain a full server/share) or contains illegal characters.</exception> /// <exception cref="PathTooLongException">Thrown if the path or a path segment exceeds the filesystem limits.</exception> /// <exception cref="FileNotFoundException">Thrown if Windows returns ERROR_FILE_NOT_FOUND. (See Win32Marshal.GetExceptionForWin32Error)</exception> /// <exception cref="DirectoryNotFoundException">Thrown if Windows returns ERROR_PATH_NOT_FOUND. (See Win32Marshal.GetExceptionForWin32Error)</exception> /// <exception cref="UnauthorizedAccessException">Thrown if Windows returns ERROR_ACCESS_DENIED. (See Win32Marshal.GetExceptionForWin32Error)</exception> /// <exception cref="IOException">Thrown if Windows returns an error that doesn't map to the above. (See Win32Marshal.GetExceptionForWin32Error)</exception> /// <returns>Normalized path</returns> internal static string Normalize(string path, bool checkInvalidCharacters, bool expandShortPaths) { // Get the full path StringBuffer fullPath = t_fullPathBuffer ?? (t_fullPathBuffer = new StringBuffer(PathInternal.MaxShortPath)); try { GetFullPathName(path, fullPath); // Trim whitespace off the end of the string. Win32 normalization trims only U+0020. fullPath.TrimEnd(s_trimEndChars); if (fullPath.Length >= PathInternal.MaxLongPath) { // Fullpath is genuinely too long throw new PathTooLongException(SR.IO_PathTooLong); } // Checking path validity used to happen before getting the full path name. To avoid additional input allocation // (to trim trailing whitespace) we now do it after the Win32 call. This will allow legitimate paths through that // used to get kicked back (notably segments with invalid characters might get removed via ".."). // // There is no way that GetLongPath can invalidate the path so we'll do this (cheaper) check before we attempt to // expand short file names. // Scan the path for: // // - Illegal path characters. // - Invalid UNC paths like \\, \\server, \\server\. // - Segments that are too long (over MaxComponentLength) // As the path could be > 30K, we'll combine the validity scan. None of these checks are performed by the Win32 // GetFullPathName() API. bool possibleShortPath = false; bool foundTilde = false; bool possibleBadUnc = IsUnc(fullPath); ulong index = possibleBadUnc ? (ulong)2 : 0; ulong lastSeparator = possibleBadUnc ? (ulong)1 : 0; ulong segmentLength; char* start = fullPath.CharPointer; char current; while (index < fullPath.Length) { current = start[index]; // Try to skip deeper analysis. '?' and higher are valid/ignorable except for '\', '|', and '~' if (current < '?' || current == '\\' || current == '|' || current == '~') { switch (current) { case '|': case '>': case '<': case '\"': if (checkInvalidCharacters) throw new ArgumentException(SR.Argument_InvalidPathChars, "path"); foundTilde = false; break; case '~': foundTilde = true; break; case '\\': segmentLength = index - lastSeparator - 1; if (segmentLength > (ulong)PathInternal.MaxComponentLength) throw new PathTooLongException(SR.IO_PathTooLong); lastSeparator = index; if (foundTilde) { if (segmentLength <= MaxShortName) { // Possibly a short path. possibleShortPath = true; } foundTilde = false; } if (possibleBadUnc) { // If we're at the end of the path and this is the first separator, we're missing the share. // Otherwise we're good, so ignore UNC tracking from here. if (index == fullPath.Length - 1) throw new ArgumentException(SR.Arg_PathIllegalUNC); else possibleBadUnc = false; } break; default: if (checkInvalidCharacters && current < ' ') throw new ArgumentException(SR.Argument_InvalidPathChars, "path"); break; } } index++; } if (possibleBadUnc) throw new ArgumentException(SR.Arg_PathIllegalUNC); segmentLength = fullPath.Length - lastSeparator - 1; if (segmentLength > (ulong)PathInternal.MaxComponentLength) throw new PathTooLongException(SR.IO_PathTooLong); if (foundTilde && segmentLength <= MaxShortName) possibleShortPath = true; // Check for a short filename path and try and expand it. Technically you don't need to have a tilde for a short name, but // this is how we've always done this. This expansion is costly so we'll continue to let other short paths slide. if (expandShortPaths && possibleShortPath) { return TryExpandShortFileName(fullPath, originalPath: path); } else { if (fullPath.Length == (ulong)path.Length && fullPath.StartsWith(path)) { // If we have the exact same string we were passed in, don't bother to allocate another string from the StringBuilder. return path; } else { return fullPath.ToString(); } } } finally { // Clear the buffer fullPath.Free(); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsUnc(StringBuffer buffer) { return buffer.Length > 1 && buffer[0] == '\\' && buffer[1] == '\\'; } private static void GetFullPathName(string path, StringBuffer fullPath) { // If the string starts with an extended prefix we would need to remove it from the path before we call GetFullPathName as // it doesn't root extended paths correctly. We don't currently resolve extended paths, so we'll just assert here. Debug.Assert(PathInternal.IsRelative(path) || !PathInternal.IsExtended(path)); // Historically we would skip leading spaces *only* if the path started with a drive " C:" or a UNC " \\" int startIndex = PathInternal.PathStartSkip(path); fixed (char* pathStart = path) { uint result = 0; while ((result = Interop.mincore.GetFullPathNameW(pathStart + startIndex, (uint)fullPath.CharCapacity, fullPath.GetHandle(), IntPtr.Zero)) > fullPath.CharCapacity) { // Reported size (which does not include the null) is greater than the buffer size. Increase the capacity. fullPath.EnsureCharCapacity(result); } if (result == 0) { // Failure, get the error and throw int errorCode = Marshal.GetLastWin32Error(); if (errorCode == 0) errorCode = Interop.mincore.Errors.ERROR_BAD_PATHNAME; throw Win32Marshal.GetExceptionForWin32Error(errorCode, path); } fullPath.Length = result; } } private static ulong GetInputBuffer(StringBuffer content, bool isUnc, out StringBuffer buffer) { ulong length = content.Length; length += isUnc ? (ulong)PathInternal.UncExtendedPrefixToInsert.Length : (ulong)PathInternal.ExtendedPathPrefix.Length; buffer = new StringBuffer(length); if (isUnc) { buffer.CopyFrom(bufferIndex: 0, source: PathInternal.UncExtendedPathPrefix); ulong prefixDifference = (ulong)(PathInternal.UncExtendedPathPrefix.Length - PathInternal.UncPathPrefix.Length); content.CopyTo(bufferIndex: prefixDifference, destination: buffer, destinationIndex: (ulong)PathInternal.ExtendedPathPrefix.Length, count: content.Length - prefixDifference); return prefixDifference; } else { ulong prefixSize = (ulong)PathInternal.ExtendedPathPrefix.Length; buffer.CopyFrom(bufferIndex: 0, source: PathInternal.ExtendedPathPrefix); content.CopyTo(bufferIndex: 0, destination: buffer, destinationIndex: prefixSize, count: content.Length); return prefixSize; } } private static string TryExpandShortFileName(StringBuffer outputBuffer, string originalPath) { // We guarantee we'll expand short names for paths that only partially exist. As such, we need to find the part of the path that actually does exist. To // avoid allocating like crazy we'll create only one input array and modify the contents with embedded nulls. Debug.Assert(!PathInternal.IsRelative(outputBuffer), "should have resolved by now"); Debug.Assert(!PathInternal.IsExtended(outputBuffer), "expanding short names expects normal paths"); // Add the extended prefix before expanding to allow growth over MAX_PATH StringBuffer inputBuffer = null; ulong rootLength = PathInternal.GetRootLength(outputBuffer); bool isUnc = IsUnc(outputBuffer); ulong rootDifference = GetInputBuffer(outputBuffer, isUnc, out inputBuffer); rootLength += rootDifference; ulong inputLength = inputBuffer.Length; bool success = false; ulong foundIndex = inputBuffer.Length - 1; while (!success) { uint result = Interop.mincore.GetLongPathNameW(inputBuffer.GetHandle(), outputBuffer.GetHandle(), (uint)outputBuffer.CharCapacity); // Replace any temporary null we added if (inputBuffer[foundIndex] == '\0') inputBuffer[foundIndex] = '\\'; if (result == 0) { // Look to see if we couldn't find the file int error = Marshal.GetLastWin32Error(); if (error != Interop.mincore.Errors.ERROR_FILE_NOT_FOUND && error != Interop.mincore.Errors.ERROR_PATH_NOT_FOUND) { // Some other failure, give up break; } // We couldn't find the path at the given index, start looking further back in the string. foundIndex--; for (; foundIndex > rootLength && inputBuffer[foundIndex] != '\\'; foundIndex--) ; if (foundIndex == rootLength) { // Can't trim the path back any further break; } else { // Temporarily set a null in the string to get Windows to look further up the path inputBuffer[foundIndex] = '\0'; } } else if (result > outputBuffer.CharCapacity) { // Not enough space. The result count for this API does not include the null terminator. outputBuffer.EnsureCharCapacity(result); result = Interop.mincore.GetLongPathNameW(inputBuffer.GetHandle(), outputBuffer.GetHandle(), (uint)outputBuffer.CharCapacity); } else { // Found the path success = true; outputBuffer.Length = result; if (foundIndex < inputLength - 1) { // It was a partial find, put the non-existant part of the path back outputBuffer.Append(inputBuffer, foundIndex, inputBuffer.Length - foundIndex); } } } // Strip out the prefix and return the string StringBuffer bufferToUse = success ? outputBuffer : inputBuffer; string returnValue = null; int newLength = (int)(bufferToUse.Length - rootDifference); if (isUnc) { // Need to go from \\?\UNC\ to \\?\UN\\ bufferToUse[(ulong)PathInternal.UncExtendedPathPrefix.Length - 1] = '\\'; } if (bufferToUse.SubstringEquals(originalPath, rootDifference, newLength)) { // Use the original path to avoid allocating returnValue = originalPath; } else { returnValue = bufferToUse.Substring(rootDifference, newLength); } inputBuffer.Dispose(); return returnValue; } } }
// 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.Data.Common; using System.Threading; using System.Threading.Tasks; namespace System.Data.ProviderBase { internal abstract class DbConnectionFactory { private Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> _connectionPoolGroups; private readonly List<DbConnectionPool> _poolsToRelease; private readonly List<DbConnectionPoolGroup> _poolGroupsToRelease; private readonly Timer _pruningTimer; private const int PruningDueTime = 4 * 60 * 1000; // 4 minutes private const int PruningPeriod = 30 * 1000; // thirty seconds // s_pendingOpenNonPooled is an array of tasks used to throttle creation of non-pooled connections to // a maximum of Environment.ProcessorCount at a time. private static uint s_pendingOpenNonPooledNext = 0; private static Task<DbConnectionInternal>[] s_pendingOpenNonPooled = new Task<DbConnectionInternal>[Environment.ProcessorCount]; private static Task<DbConnectionInternal> s_completedTask; protected DbConnectionFactory() { _connectionPoolGroups = new Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup>(); _poolsToRelease = new List<DbConnectionPool>(); _poolGroupsToRelease = new List<DbConnectionPoolGroup>(); _pruningTimer = CreatePruningTimer(); } public abstract DbProviderFactory ProviderFactory { get; } public void ClearAllPools() { Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> connectionPoolGroups = _connectionPoolGroups; foreach (KeyValuePair<DbConnectionPoolKey, DbConnectionPoolGroup> entry in connectionPoolGroups) { DbConnectionPoolGroup poolGroup = entry.Value; if (null != poolGroup) { poolGroup.Clear(); } } } public void ClearPool(DbConnection connection) { ADP.CheckArgumentNull(connection, nameof(connection)); DbConnectionPoolGroup poolGroup = GetConnectionPoolGroup(connection); if (null != poolGroup) { poolGroup.Clear(); } } public void ClearPool(DbConnectionPoolKey key) { Debug.Assert(key != null, "key cannot be null"); ADP.CheckArgumentNull(key.ConnectionString, nameof(key) + "." + nameof(key.ConnectionString)); DbConnectionPoolGroup poolGroup; Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> connectionPoolGroups = _connectionPoolGroups; if (connectionPoolGroups.TryGetValue(key, out poolGroup)) { poolGroup.Clear(); } } internal virtual DbConnectionPoolProviderInfo CreateConnectionPoolProviderInfo(DbConnectionOptions connectionOptions) { return null; } internal DbConnectionInternal CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions) { Debug.Assert(null != owningConnection, "null owningConnection?"); Debug.Assert(null != poolGroup, "null poolGroup?"); DbConnectionOptions connectionOptions = poolGroup.ConnectionOptions; DbConnectionPoolGroupProviderInfo poolGroupProviderInfo = poolGroup.ProviderInfo; DbConnectionPoolKey poolKey = poolGroup.PoolKey; DbConnectionInternal newConnection = CreateConnection(connectionOptions, poolKey, poolGroupProviderInfo, null, owningConnection, userOptions); if (null != newConnection) { newConnection.MakeNonPooledObject(owningConnection); } return newConnection; } internal DbConnectionInternal CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) { Debug.Assert(null != pool, "null pool?"); DbConnectionPoolGroupProviderInfo poolGroupProviderInfo = pool.PoolGroup.ProviderInfo; DbConnectionInternal newConnection = CreateConnection(options, poolKey, poolGroupProviderInfo, pool, owningObject, userOptions); if (null != newConnection) { newConnection.MakePooledConnection(pool); } return newConnection; } internal virtual DbConnectionPoolGroupProviderInfo CreateConnectionPoolGroupProviderInfo(DbConnectionOptions connectionOptions) { return null; } private Timer CreatePruningTimer() { TimerCallback callback = new TimerCallback(PruneConnectionPoolGroups); return new Timer(callback, null, PruningDueTime, PruningPeriod); } protected DbConnectionOptions FindConnectionOptions(DbConnectionPoolKey key) { Debug.Assert(key != null, "key cannot be null"); if (!string.IsNullOrEmpty(key.ConnectionString)) { DbConnectionPoolGroup connectionPoolGroup; Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> connectionPoolGroups = _connectionPoolGroups; if (connectionPoolGroups.TryGetValue(key, out connectionPoolGroup)) { return connectionPoolGroup.ConnectionOptions; } } return null; } private static Task<DbConnectionInternal> GetCompletedTask() { Debug.Assert(Monitor.IsEntered(s_pendingOpenNonPooled), $"Expected {nameof(s_pendingOpenNonPooled)} lock to be held."); return s_completedTask ?? (s_completedTask = Task.FromResult<DbConnectionInternal>(null)); } internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, out DbConnectionInternal connection) { Debug.Assert(null != owningConnection, "null owningConnection?"); DbConnectionPoolGroup poolGroup; DbConnectionPool connectionPool; connection = null; // Work around race condition with clearing the pool between GetConnectionPool obtaining pool // and GetConnection on the pool checking the pool state. Clearing the pool in this window // will switch the pool into the ShuttingDown state, and GetConnection will return null. // There is probably a better solution involving locking the pool/group, but that entails a major // re-design of the connection pooling synchronization, so is postponed for now. // Use retriesLeft to prevent CPU spikes with incremental sleep // start with one msec, double the time every retry // max time is: 1 + 2 + 4 + ... + 2^(retries-1) == 2^retries -1 == 1023ms (for 10 retries) int retriesLeft = 10; int timeBetweenRetriesMilliseconds = 1; do { poolGroup = GetConnectionPoolGroup(owningConnection); // Doing this on the callers thread is important because it looks up the WindowsIdentity from the thread. connectionPool = GetConnectionPool(owningConnection, poolGroup); if (null == connectionPool) { // If GetConnectionPool returns null, we can be certain that // this connection should not be pooled via DbConnectionPool // or have a disabled pool entry. poolGroup = GetConnectionPoolGroup(owningConnection); // previous entry have been disabled if (retry != null) { Task<DbConnectionInternal> newTask; CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); lock (s_pendingOpenNonPooled) { // look for an available task slot (completed or empty) int idx; for (idx = 0; idx < s_pendingOpenNonPooled.Length; idx++) { Task task = s_pendingOpenNonPooled[idx]; if (task == null) { s_pendingOpenNonPooled[idx] = GetCompletedTask(); break; } else if (task.IsCompleted) { break; } } // if didn't find one, pick the next one in round-robin fashion if (idx == s_pendingOpenNonPooled.Length) { idx = (int)(s_pendingOpenNonPooledNext % s_pendingOpenNonPooled.Length); unchecked { s_pendingOpenNonPooledNext++; } } // now that we have an antecedent task, schedule our work when it is completed. // If it is a new slot or a completed task, this continuation will start right away. newTask = s_pendingOpenNonPooled[idx].ContinueWith((_) => { var newConnection = CreateNonPooledConnection(owningConnection, poolGroup, userOptions); if ((oldConnection != null) && (oldConnection.State == ConnectionState.Open)) { oldConnection.PrepareForReplaceConnection(); oldConnection.Dispose(); } return newConnection; }, cancellationTokenSource.Token, TaskContinuationOptions.LongRunning, TaskScheduler.Default); // Place this new task in the slot so any future work will be queued behind it s_pendingOpenNonPooled[idx] = newTask; } // Set up the timeout (if needed) if (owningConnection.ConnectionTimeout > 0) { int connectionTimeoutMilliseconds = owningConnection.ConnectionTimeout * 1000; cancellationTokenSource.CancelAfter(connectionTimeoutMilliseconds); } // once the task is done, propagate the final results to the original caller newTask.ContinueWith((task) => { cancellationTokenSource.Dispose(); if (task.IsCanceled) { retry.TrySetException(ADP.ExceptionWithStackTrace(ADP.NonPooledOpenTimeout())); } else if (task.IsFaulted) { retry.TrySetException(task.Exception.InnerException); } else { if (!retry.TrySetResult(task.Result)) { // The outer TaskCompletionSource was already completed // Which means that we don't know if someone has messed with the outer connection in the middle of creation // So the best thing to do now is to destroy the newly created connection task.Result.DoomThisConnection(); task.Result.Dispose(); } } }, TaskScheduler.Default); return false; } connection = CreateNonPooledConnection(owningConnection, poolGroup, userOptions); } else { // TODO: move this to src/Common and integrate with SqlClient //if (((SqlClient.SqlConnection)owningConnection).ForceNewConnection) //{ // Debug.Assert(!(oldConnection is DbConnectionClosed), "Force new connection, but there is no old connection"); // connection = connectionPool.ReplaceConnection(owningConnection, userOptions, oldConnection); //} //else //{ if (!connectionPool.TryGetConnection(owningConnection, retry, userOptions, out connection)) { return false; } //} if (connection == null) { // connection creation failed on semaphore waiting or if max pool reached if (connectionPool.IsRunning) { // If GetConnection failed while the pool is running, the pool timeout occurred. throw ADP.PooledOpenTimeout(); } else { // We've hit the race condition, where the pool was shut down after we got it from the group. // Yield time slice to allow shut down activities to complete and a new, running pool to be instantiated // before retrying. Threading.Thread.Sleep(timeBetweenRetriesMilliseconds); timeBetweenRetriesMilliseconds *= 2; // double the wait time for next iteration } } } } while (connection == null && retriesLeft-- > 0); if (connection == null) { // exhausted all retries or timed out - give up throw ADP.PooledOpenTimeout(); } return true; } private DbConnectionPool GetConnectionPool(DbConnection owningObject, DbConnectionPoolGroup connectionPoolGroup) { // if poolgroup is disabled, it will be replaced with a new entry Debug.Assert(null != owningObject, "null owningObject?"); Debug.Assert(null != connectionPoolGroup, "null connectionPoolGroup?"); // It is possible that while the outer connection object has // been sitting around in a closed and unused state in some long // running app, the pruner may have come along and remove this // the pool entry from the master list. If we were to use a // pool entry in this state, we would create "unmanaged" pools, // which would be bad. To avoid this problem, we automagically // re-create the pool entry whenever it's disabled. // however, don't rebuild connectionOptions if no pooling is involved - let new connections do that work if (connectionPoolGroup.IsDisabled && (null != connectionPoolGroup.PoolGroupOptions)) { // reusing existing pool option in case user originally used SetConnectionPoolOptions DbConnectionPoolGroupOptions poolOptions = connectionPoolGroup.PoolGroupOptions; // get the string to hash on again DbConnectionOptions connectionOptions = connectionPoolGroup.ConnectionOptions; Debug.Assert(null != connectionOptions, "prevent expansion of connectionString"); connectionPoolGroup = GetConnectionPoolGroup(connectionPoolGroup.PoolKey, poolOptions, ref connectionOptions); Debug.Assert(null != connectionPoolGroup, "null connectionPoolGroup?"); SetConnectionPoolGroup(owningObject, connectionPoolGroup); } DbConnectionPool connectionPool = connectionPoolGroup.GetConnectionPool(this); return connectionPool; } internal DbConnectionPoolGroup GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, ref DbConnectionOptions userConnectionOptions) { if (string.IsNullOrEmpty(key.ConnectionString)) { return (DbConnectionPoolGroup)null; } DbConnectionPoolGroup connectionPoolGroup; Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> connectionPoolGroups = _connectionPoolGroups; if (!connectionPoolGroups.TryGetValue(key, out connectionPoolGroup) || (connectionPoolGroup.IsDisabled && (null != connectionPoolGroup.PoolGroupOptions))) { // If we can't find an entry for the connection string in // our collection of pool entries, then we need to create a // new pool entry and add it to our collection. DbConnectionOptions connectionOptions = CreateConnectionOptions(key.ConnectionString, userConnectionOptions); if (null == connectionOptions) { throw ADP.InternalConnectionError(ADP.ConnectionError.ConnectionOptionsMissing); } if (null == userConnectionOptions) { // we only allow one expansion on the connection string userConnectionOptions = connectionOptions; } // We don't support connection pooling on Win9x if (null == poolOptions) { if (null != connectionPoolGroup) { // reusing existing pool option in case user originally used SetConnectionPoolOptions poolOptions = connectionPoolGroup.PoolGroupOptions; } else { // Note: may return null for non-pooled connections poolOptions = CreateConnectionPoolGroupOptions(connectionOptions); } } DbConnectionPoolGroup newConnectionPoolGroup = new DbConnectionPoolGroup(connectionOptions, key, poolOptions); newConnectionPoolGroup.ProviderInfo = CreateConnectionPoolGroupProviderInfo(connectionOptions); lock (this) { connectionPoolGroups = _connectionPoolGroups; if (!connectionPoolGroups.TryGetValue(key, out connectionPoolGroup)) { // build new dictionary with space for new connection string Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> newConnectionPoolGroups = new Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup>(1 + connectionPoolGroups.Count); foreach (KeyValuePair<DbConnectionPoolKey, DbConnectionPoolGroup> entry in connectionPoolGroups) { newConnectionPoolGroups.Add(entry.Key, entry.Value); } // lock prevents race condition with PruneConnectionPoolGroups newConnectionPoolGroups.Add(key, newConnectionPoolGroup); connectionPoolGroup = newConnectionPoolGroup; _connectionPoolGroups = newConnectionPoolGroups; } else { Debug.Assert(!connectionPoolGroup.IsDisabled, "Disabled pool entry discovered"); } } Debug.Assert(null != connectionPoolGroup, "how did we not create a pool entry?"); Debug.Assert(null != userConnectionOptions, "how did we not have user connection options?"); } else if (null == userConnectionOptions) { userConnectionOptions = connectionPoolGroup.ConnectionOptions; } return connectionPoolGroup; } private void PruneConnectionPoolGroups(object state) { // First, walk the pool release list and attempt to clear each // pool, when the pool is finally empty, we dispose of it. If the // pool isn't empty, it's because there are active connections or // distributed transactions that need it. lock (_poolsToRelease) { if (0 != _poolsToRelease.Count) { DbConnectionPool[] poolsToRelease = _poolsToRelease.ToArray(); foreach (DbConnectionPool pool in poolsToRelease) { if (null != pool) { pool.Clear(); if (0 == pool.Count) { _poolsToRelease.Remove(pool); } } } } } // Next, walk the pool entry release list and dispose of each // pool entry when it is finally empty. If the pool entry isn't // empty, it's because there are active pools that need it. lock (_poolGroupsToRelease) { if (0 != _poolGroupsToRelease.Count) { DbConnectionPoolGroup[] poolGroupsToRelease = _poolGroupsToRelease.ToArray(); foreach (DbConnectionPoolGroup poolGroup in poolGroupsToRelease) { if (null != poolGroup) { int poolsLeft = poolGroup.Clear(); // may add entries to _poolsToRelease if (0 == poolsLeft) { _poolGroupsToRelease.Remove(poolGroup); } } } } } // Finally, we walk through the collection of connection pool entries // and prune each one. This will cause any empty pools to be put // into the release list. lock (this) { Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> connectionPoolGroups = _connectionPoolGroups; Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> newConnectionPoolGroups = new Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup>(connectionPoolGroups.Count); foreach (KeyValuePair<DbConnectionPoolKey, DbConnectionPoolGroup> entry in connectionPoolGroups) { if (null != entry.Value) { Debug.Assert(!entry.Value.IsDisabled, "Disabled pool entry discovered"); // entries start active and go idle during prune if all pools are gone // move idle entries from last prune pass to a queue for pending release // otherwise process entry which may move it from active to idle if (entry.Value.Prune()) { // may add entries to _poolsToRelease QueuePoolGroupForRelease(entry.Value); } else { newConnectionPoolGroups.Add(entry.Key, entry.Value); } } } _connectionPoolGroups = newConnectionPoolGroups; } } internal void QueuePoolForRelease(DbConnectionPool pool, bool clearing) { // Queue the pool up for release -- we'll clear it out and dispose // of it as the last part of the pruning timer callback so we don't // do it with the pool entry or the pool collection locked. Debug.Assert(null != pool, "null pool?"); // set the pool to the shutdown state to force all active // connections to be automatically disposed when they // are returned to the pool pool.Shutdown(); lock (_poolsToRelease) { if (clearing) { pool.Clear(); } _poolsToRelease.Add(pool); } } internal void QueuePoolGroupForRelease(DbConnectionPoolGroup poolGroup) { Debug.Assert(null != poolGroup, "null poolGroup?"); lock (_poolGroupsToRelease) { _poolGroupsToRelease.Add(poolGroup); } } protected virtual DbConnectionInternal CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) { return CreateConnection(options, poolKey, poolGroupProviderInfo, pool, owningConnection); } protected abstract DbConnectionInternal CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection); protected abstract DbConnectionOptions CreateConnectionOptions(string connectionString, DbConnectionOptions previous); protected abstract DbConnectionPoolGroupOptions CreateConnectionPoolGroupOptions(DbConnectionOptions options); internal abstract DbConnectionPoolGroup GetConnectionPoolGroup(DbConnection connection); internal abstract DbConnectionInternal GetInnerConnection(DbConnection connection); internal abstract void PermissionDemand(DbConnection outerConnection); internal abstract void SetConnectionPoolGroup(DbConnection outerConnection, DbConnectionPoolGroup poolGroup); internal abstract void SetInnerConnectionEvent(DbConnection owningObject, DbConnectionInternal to); internal abstract bool SetInnerConnectionFrom(DbConnection owningObject, DbConnectionInternal to, DbConnectionInternal from); internal abstract void SetInnerConnectionTo(DbConnection owningObject, DbConnectionInternal to); } }
// // Copyright (c) 2008-2013, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.IO; using DiscUtils.Streams; namespace DiscUtils.Vhdx { /// <summary> /// Creates new VHD disks by wrapping existing streams. /// </summary> /// <remarks>Using this method for creating virtual disks avoids consuming /// large amounts of memory, or going via the local file system when the aim /// is simply to present a VHD version of an existing disk.</remarks> public sealed class DiskBuilder : DiskImageBuilder { private long _blockSize = 32 * Sizes.OneMiB; /// <summary> /// The VHDX block size, or <c>0</c> (indicating default). /// </summary> public long BlockSize { get { return _blockSize; } set { if (value % Sizes.OneMiB != 0) { throw new ArgumentException("BlockSize must be a multiple of 1MB", nameof(value)); } _blockSize = value; } } /// <summary> /// Gets or sets the type of VHDX file to build. /// </summary> public DiskType DiskType { get; set; } /// <summary> /// Initiates the build process. /// </summary> /// <param name="baseName">The base name for the VHDX, for example 'foo' to create 'foo.vhdx'.</param> /// <returns>A set of one or more logical files that constitute the virtual disk. The first file is /// the 'primary' file that is normally attached to VMs.</returns> public override DiskImageFileSpecification[] Build(string baseName) { if (string.IsNullOrEmpty(baseName)) { throw new ArgumentException("Invalid base file name", nameof(baseName)); } if (Content == null) { throw new InvalidOperationException("No content stream specified"); } DiskImageFileSpecification fileSpec = new DiskImageFileSpecification(baseName + ".vhdx", new DiskStreamBuilder(Content, DiskType, BlockSize)); return new[] { fileSpec }; } private class DiskStreamBuilder : StreamBuilder { private readonly long _blockSize; private readonly SparseStream _content; private readonly DiskType _diskType; public DiskStreamBuilder(SparseStream content, DiskType diskType, long blockSize) { _content = content; _diskType = diskType; _blockSize = blockSize; } protected override List<BuilderExtent> FixExtents(out long totalLength) { if (_diskType != DiskType.Dynamic) { throw new NotSupportedException("Creation of only dynamic disks currently implemented"); } List<BuilderExtent> extents = new List<BuilderExtent>(); int logicalSectorSize = 512; int physicalSectorSize = 4096; long chunkRatio = 0x800000L * logicalSectorSize / _blockSize; long dataBlocksCount = MathUtilities.Ceil(_content.Length, _blockSize); long sectorBitmapBlocksCount = MathUtilities.Ceil(dataBlocksCount, chunkRatio); long totalBatEntriesDynamic = dataBlocksCount + (dataBlocksCount - 1) / chunkRatio; FileHeader fileHeader = new FileHeader { Creator = ".NET DiscUtils" }; long fileEnd = Sizes.OneMiB; VhdxHeader header1 = new VhdxHeader(); header1.SequenceNumber = 0; header1.FileWriteGuid = Guid.NewGuid(); header1.DataWriteGuid = Guid.NewGuid(); header1.LogGuid = Guid.Empty; header1.LogVersion = 0; header1.Version = 1; header1.LogLength = (uint)Sizes.OneMiB; header1.LogOffset = (ulong)fileEnd; header1.CalcChecksum(); fileEnd += header1.LogLength; VhdxHeader header2 = new VhdxHeader(header1); header2.SequenceNumber = 1; header2.CalcChecksum(); RegionTable regionTable = new RegionTable(); RegionEntry metadataRegion = new RegionEntry(); metadataRegion.Guid = RegionEntry.MetadataRegionGuid; metadataRegion.FileOffset = fileEnd; metadataRegion.Length = (uint)Sizes.OneMiB; metadataRegion.Flags = RegionFlags.Required; regionTable.Regions.Add(metadataRegion.Guid, metadataRegion); fileEnd += metadataRegion.Length; RegionEntry batRegion = new RegionEntry(); batRegion.Guid = RegionEntry.BatGuid; batRegion.FileOffset = fileEnd; batRegion.Length = (uint)MathUtilities.RoundUp(totalBatEntriesDynamic * 8, Sizes.OneMiB); batRegion.Flags = RegionFlags.Required; regionTable.Regions.Add(batRegion.Guid, batRegion); fileEnd += batRegion.Length; extents.Add(ExtentForStruct(fileHeader, 0)); extents.Add(ExtentForStruct(header1, 64 * Sizes.OneKiB)); extents.Add(ExtentForStruct(header2, 128 * Sizes.OneKiB)); extents.Add(ExtentForStruct(regionTable, 192 * Sizes.OneKiB)); extents.Add(ExtentForStruct(regionTable, 256 * Sizes.OneKiB)); // Metadata FileParameters fileParams = new FileParameters { BlockSize = (uint)_blockSize, Flags = FileParametersFlags.None }; ParentLocator parentLocator = new ParentLocator(); byte[] metadataBuffer = new byte[metadataRegion.Length]; MemoryStream metadataStream = new MemoryStream(metadataBuffer); Metadata.Initialize(metadataStream, fileParams, (ulong)_content.Length, (uint)logicalSectorSize, (uint)physicalSectorSize, null); extents.Add(new BuilderBufferExtent(metadataRegion.FileOffset, metadataBuffer)); List<Range<long, long>> presentBlocks = new List<Range<long, long>>(StreamExtent.Blocks(_content.Extents, _blockSize)); // BAT BlockAllocationTableBuilderExtent batExtent = new BlockAllocationTableBuilderExtent( batRegion.FileOffset, batRegion.Length, presentBlocks, fileEnd, _blockSize, chunkRatio); extents.Add(batExtent); // Stream contents foreach (Range<long, long> range in presentBlocks) { long substreamStart = range.Offset * _blockSize; long substreamCount = Math.Min(_content.Length - substreamStart, range.Count * _blockSize); SubStream dataSubStream = new SubStream(_content, substreamStart, substreamCount); BuilderSparseStreamExtent dataExtent = new BuilderSparseStreamExtent(fileEnd, dataSubStream); extents.Add(dataExtent); fileEnd += range.Count * _blockSize; } totalLength = fileEnd; return extents; } private static BuilderExtent ExtentForStruct(IByteArraySerializable structure, long position) { byte[] buffer = new byte[structure.Size]; structure.WriteTo(buffer, 0); return new BuilderBufferExtent(position, buffer); } } private class BlockAllocationTableBuilderExtent : BuilderExtent { private byte[] _batData; private readonly List<Range<long, long>> _blocks; private readonly long _blockSize; private readonly long _chunkRatio; private readonly long _dataStart; public BlockAllocationTableBuilderExtent(long start, long length, List<Range<long, long>> blocks, long dataStart, long blockSize, long chunkRatio) : base(start, length) { _blocks = blocks; _dataStart = dataStart; _blockSize = blockSize; _chunkRatio = chunkRatio; } public override void Dispose() { _batData = null; } public override void PrepareForRead() { _batData = new byte[Length]; long fileOffset = _dataStart; BatEntry entry = new BatEntry(); foreach (Range<long, long> range in _blocks) { for (long block = range.Offset; block < range.Offset + range.Count; ++block) { long chunk = block / _chunkRatio; long chunkOffset = block % _chunkRatio; long batIndex = chunk * (_chunkRatio + 1) + chunkOffset; entry.FileOffsetMB = fileOffset / Sizes.OneMiB; entry.PayloadBlockStatus = PayloadBlockStatus.FullyPresent; entry.WriteTo(_batData, (int)(batIndex * 8)); fileOffset += _blockSize; } } } public override int Read(long diskOffset, byte[] block, int offset, int count) { int start = (int)Math.Min(diskOffset - Start, _batData.Length); int numRead = Math.Min(count, _batData.Length - start); Array.Copy(_batData, start, block, offset, numRead); return numRead; } public override void DisposeReadState() { _batData = null; } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.Diagnostics; using Test.Utilities; using Xunit; namespace Microsoft.CodeQuality.Analyzers.Maintainability.UnitTests { public class AvoidUninstantiatedInternalClassesTests : DiagnosticAnalyzerTestBase { [Fact] public void CA1812_CSharp_Diagnostic_UninstantiatedInternalClass() { VerifyCSharp( @"internal class C { } ", GetCSharpResultAt(1, 16, AvoidUninstantiatedInternalClassesAnalyzer.Rule, "C")); } [Fact] public void CA1812_Basic_Diagnostic_UninstantiatedInternalClass() { VerifyBasic( @"Friend Class C End Class", GetBasicResultAt(1, 14, AvoidUninstantiatedInternalClassesAnalyzer.Rule, "C")); } [Fact] public void CA1812_CSharp_NoDiagnostic_UninstantiatedInternalStruct() { VerifyCSharp( @"internal struct CInternal { }"); } [Fact] public void CA1812_Basic_NoDiagnostic_UninstantiatedInternalStruct() { VerifyBasic( @"Friend Structure CInternal End Structure"); } [Fact] public void CA1812_CSharp_NoDiagnostic_UninstantiatedPublicClass() { VerifyCSharp( @"public class C { }"); } [Fact] public void CA1812_Basic_NoDiagnostic_UninstantiatedPublicClass() { VerifyBasic( @"Public Class C End Class"); } [Fact] public void CA1812_CSharp_NoDiagnostic_InstantiatedInternalClass() { VerifyCSharp( @"internal class C { } public class D { private readonly C _c = new C(); }"); } [Fact] public void CA1812_Basic_NoDiagnostic_InstantiatedInternalClass() { VerifyBasic( @"Friend Class C End Class Public Class D Private _c As New C End Class"); } [Fact] public void CA1812_CSharp_Diagnostic_UninstantiatedInternalClassNestedInPublicClass() { VerifyCSharp( @"public class C { internal class D { } }", GetCSharpResultAt(3, 20, AvoidUninstantiatedInternalClassesAnalyzer.Rule, "C.D")); } [Fact] public void CA1812_Basic_Diagnostic_UninstantiatedInternalClassNestedInPublicClass() { VerifyBasic( @"Public Class C Friend Class D End Class End Class", GetBasicResultAt(2, 18, AvoidUninstantiatedInternalClassesAnalyzer.Rule, "C.D")); } [Fact] public void CA1812_CSharp_NoDiagnostic_InstantiatedInternalClassNestedInPublicClass() { VerifyCSharp( @"public class C { private readonly D _d = new D(); internal class D { } }"); } [Fact] public void CA1812_Basic_NoDiagnostic_InstantiatedInternalClassNestedInPublicClass() { VerifyBasic( @"Public Class C Private ReadOnly _d = New D Friend Class D End Class End Class"); } [Fact] public void CA1812_Basic_NoDiagnostic_InternalModule() { // No static classes in VB. VerifyBasic( @"Friend Module M End Module"); } [Fact] public void CA1812_CSharp_NoDiagnostic_InternalAbstractClass() { VerifyCSharp( @"internal abstract class A { }"); } [Fact] public void CA1812_Basic_NoDiagnostic_InternalAbstractClass() { VerifyBasic( @"Friend MustInherit Class A End Class"); } [Fact] public void CA1812_CSharp_NoDiagnostic_InternalDelegate() { VerifyCSharp(@" namespace N { internal delegate void Del(); }"); } [Fact] public void CA1812_Basic_NoDiagnostic_InternalDelegate() { VerifyBasic(@" Namespace N Friend Delegate Sub Del() End Namespace"); } [Fact] public void CA1812_CSharp_NoDiagnostic_InternalEnum() { VerifyCSharp( @"namespace N { internal enum E {} // C# enums don't care if there are any members. }"); } [Fact] public void CA1812_Basic_NoDiagnostic_InternalEnum() { VerifyBasic( @"Namespace N Friend Enum E None ' VB enums require at least one member. End Enum End Namespace"); } [Fact] public void CA1812_CSharp_NoDiagnostic_AttributeClass() { VerifyCSharp( @"using System; internal class MyAttribute: Attribute {} internal class MyOtherAttribute: MyAttribute {}"); } [Fact] public void CA1812_Basic_NoDiagnostic_AttributeClass() { VerifyBasic( @"Imports System Friend Class MyAttribute Inherits Attribute End Class Friend Class MyOtherAttribute Inherits MyAttribute End Class"); } [Fact(Skip = "https://github.com/dotnet/roslyn-analyzers/issues/881")] public void CA1812_CSharp_NoDiagnostic_TypeContainingAssemblyEntryPointReturningVoid() { VerifyCSharp( @"internal class C { private static void Main() {} }"); } [Fact(Skip = "https://github.com/dotnet/roslyn-analyzers/issues/881")] public void CA1812_Basic_NoDiagnostic_TypeContainingAssemblyEntryPointReturningVoid() { VerifyBasic( @"Friend Class C Private Shared Sub Main() End Sub End Class"); } [Fact(Skip = "https://github.com/dotnet/roslyn-analyzers/issues/881")] public void CA1812_CSharp_NoDiagnostic_TypeContainingAssemblyEntryPointReturningInt() { VerifyCSharp( @"internal class C { private static int Main() { return 1; } }"); } [Fact(Skip = "https://github.com/dotnet/roslyn-analyzers/issues/881")] public void CA1812_Basic_NoDiagnostic_TypeContainingAssemblyEntryPointReturningInt() { VerifyBasic( @"Friend Class C Private Shared Function Main() As Integer Return 1 End Sub End Class"); } [Fact] public void CA1812_CSharp_Diagnostic_MainMethodIsNotStatic() { VerifyCSharp( @"internal class C { private void Main() {} }", GetCSharpResultAt(1, 16, AvoidUninstantiatedInternalClassesAnalyzer.Rule, "C")); } [Fact] public void CA1812_Basic_Diagnostic_MainMethodIsNotStatic() { VerifyBasic( @"Friend Class C Private Sub Main() End Sub End Class", GetBasicResultAt(1, 14, AvoidUninstantiatedInternalClassesAnalyzer.Rule, "C")); } [Fact(Skip = "https://github.com/dotnet/roslyn-analyzers/issues/881")] public void CA1812_Basic_NoDiagnostic_MainMethodIsDifferentlyCased() { VerifyBasic( @"Friend Class C Private Shared Sub mAiN() End Sub End Class"); } // The following tests are just to ensure that the messages are formatted properly // for types within namespaces. [Fact] public void CA1812_CSharp_Diagnostic_UninstantiatedInternalClassInNamespace() { VerifyCSharp( @"namespace N { internal class C { } }", GetCSharpResultAt(3, 20, AvoidUninstantiatedInternalClassesAnalyzer.Rule, "C")); } [Fact] public void CA1812_Basic_Diagnostic_UninstantiatedInternalClassInNamespace() { VerifyBasic( @"Namespace N Friend Class C End Class End Namespace", GetBasicResultAt(2, 18, AvoidUninstantiatedInternalClassesAnalyzer.Rule, "C")); } [Fact] public void CA1812_CSharp_Diagnostic_UninstantiatedInternalClassNestedInPublicClassInNamespace() { VerifyCSharp( @"namespace N { public class C { internal class D { } } }", GetCSharpResultAt(5, 24, AvoidUninstantiatedInternalClassesAnalyzer.Rule, "C.D")); } [Fact] public void CA1812_Basic_Diagnostic_UninstantiatedInternalClassNestedInPublicClassInNamespace() { VerifyBasic( @"Namespace N Public Class C Friend Class D End Class End Class End Namespace", GetBasicResultAt(3, 22, AvoidUninstantiatedInternalClassesAnalyzer.Rule, "C.D")); } [Fact] public void CA1812_CSharp_NoDiagnostic_UninstantiatedInternalMef1ExportedClass() { VerifyCSharp( @"using System; using System.ComponentModel.Composition; namespace System.ComponentModel.Composition { public class ExportAttribute: Attribute { } } [Export] internal class C { }"); } [Fact] public void CA1812_Basic_NoDiagnostic_UninstantiatedInternalMef1ExportedClass() { VerifyBasic( @"Imports System Imports System.ComponentModel.Composition Namespace System.ComponentModel.Composition Public Class ExportAttribute Inherits Attribute End Class End Namespace <Export> Friend Class C End Class"); } [Fact] public void CA1812_CSharp_NoDiagnostic_UninstantiatedInternalMef2ExportedClass() { VerifyCSharp( @"using System; using System.ComponentModel.Composition; namespace System.ComponentModel.Composition { public class ExportAttribute: Attribute { } } [Export] internal class C { }"); } [Fact] public void CA1812_Basic_NoDiagnostic_UninstantiatedInternalMef2ExportedClass() { VerifyBasic( @"Imports System Imports System.ComponentModel.Composition Namespace System.ComponentModel.Composition Public Class ExportAttribute Inherits Attribute End Class End Namespace <Export> Friend Class C End Class"); } [Fact] public void CA1812_CSharp_NoDiagnostic_ImplementsIConfigurationSectionHandler() { VerifyCSharp( @"using System.Configuration; using System.Xml; internal class C : IConfigurationSectionHandler { public object Create(object parent, object configContext, XmlNode section) { return null; } }"); } [Fact] public void CA1812_Basic_NoDiagnostic_ImplementsIConfigurationSectionHandler() { VerifyBasic( @"Imports System.Configuration Imports System.Xml Friend Class C Implements IConfigurationSectionHandler Private Function IConfigurationSectionHandler_Create(parent As Object, configContext As Object, section As XmlNode) As Object Implements IConfigurationSectionHandler.Create Return Nothing End Function End Class"); } [Fact] public void CA1812_CSharp_NoDiagnostic_DerivesFromConfigurationSection() { VerifyCSharp( @"using System.Configuration; namespace System.Configuration { public class ConfigurationSection { } } internal class C : ConfigurationSection { }"); } [Fact] public void CA1812_Basic_NoDiagnostic_DerivesFromConfigurationSection() { VerifyBasic( @"Imports System.Configuration Namespace System.Configuration Public Class ConfigurationSection End Class End Namespace Friend Class C Inherits ConfigurationSection End Class"); } [Fact] public void CA1812_CSharp_NoDiagnostic_DerivesFromSafeHandle() { VerifyCSharp( @"using System; using System.Runtime.InteropServices; internal class MySafeHandle : SafeHandle { protected MySafeHandle(IntPtr invalidHandleValue, bool ownsHandle) : base(invalidHandleValue, ownsHandle) { } public override bool IsInvalid => true; protected override bool ReleaseHandle() { return true; } }"); } [Fact] public void CA1812_Basic_NoDiagnostic_DerivesFromSafeHandle() { VerifyBasic( @"Imports System Imports System.Runtime.InteropServices Friend Class MySafeHandle Inherits SafeHandle Protected Sub New(invalidHandleValue As IntPtr, ownsHandle As Boolean) MyBase.New(invalidHandleValue, ownsHandle) End Sub Public Overrides ReadOnly Property IsInvalid As Boolean Get Return True End Get End Property Protected Overrides Function ReleaseHandle() As Boolean Return True End Function End Class"); } [Fact] public void CA1812_CSharp_NoDiagnostic_DerivesFromTraceListener() { VerifyCSharp( @"using System.Diagnostics; internal class MyTraceListener : TraceListener { public override void Write(string message) { } public override void WriteLine(string message) { } }"); } [Fact] public void CA1812_Basic_NoDiagnostic_DerivesFromTraceListener() { VerifyBasic( @"Imports System.Diagnostics Friend Class MyTraceListener Inherits TraceListener Public Overrides Sub Write(message As String) End Sub Public Overrides Sub WriteLine(message As String) End Sub End Class"); } [Fact] public void CA1812_CSharp_NoDiagnostic_InternalNestedTypeIsInstantiated() { VerifyCSharp( @"internal class C { internal class C2 { } } public class D { private readonly C.C2 _c2 = new C.C2(); } "); } [Fact] public void CA1812_Basic_NoDiagnostic_InternalNestedTypeIsInstantiated() { VerifyBasic( @"Friend Class C Friend Class C2 End Class End Class Public Class D Private _c2 As new C.C2 End Class"); } [Fact] public void CA1812_CSharp_Diagnostic_InternalNestedTypeIsNotInstantiated() { VerifyCSharp( @"internal class C { internal class C2 { } }", GetCSharpResultAt( 3, 20, AvoidUninstantiatedInternalClassesAnalyzer.Rule, "C.C2")); } [Fact] public void CA1812_Basic_Diagnostic_InternalNestedTypeIsNotInstantiated() { VerifyBasic( @"Friend Class C Friend Class C2 End Class End Class", GetBasicResultAt( 2, 18, AvoidUninstantiatedInternalClassesAnalyzer.Rule, "C.C2")); } [Fact] public void CA1812_CSharp_Diagnostic_PrivateNestedTypeIsInstantiated() { VerifyCSharp( @"internal class C { private readonly C2 _c2 = new C2(); private class C2 { } }", GetCSharpResultAt( 1, 16, AvoidUninstantiatedInternalClassesAnalyzer.Rule, "C")); } [Fact] public void CA1812_Basic_Diagnostic_PrivateNestedTypeIsInstantiated() { VerifyBasic( @"Friend Class C Private _c2 As New C2 Private Class C2 End Class End Class", GetBasicResultAt( 1, 14, AvoidUninstantiatedInternalClassesAnalyzer.Rule, "C")); } [Fact] public void CA1812_CSharp_NoDiagnostic_StaticHolderClass() { VerifyCSharp( @"internal static class C { internal static void F() { } }"); } [Fact] public void CA1812_Basic_NoDiagnostic_StaticHolderClass() { VerifyBasic( @"Friend Module C Friend Sub F() End Sub End Module"); } [Fact] public void CA1812_CSharp_Diagnostic_EmptyInternalStaticClass() { // Note that this is not considered a "static holder class" // because it doesn't actually have any static members. VerifyCSharp( @"internal static class S { }", GetCSharpResultAt( 1, 23, AvoidUninstantiatedInternalClassesAnalyzer.Rule, "S")); } [Fact] public void CA1812_CSharp_NoDiagnostic_UninstantiatedInternalClassInFriendlyAssembly() { VerifyCSharp( @"using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo(""TestProject"")] internal class C { }" ); } [Fact] public void CA1812_Basic_NoDiagnostic_UninstantiatedInternalClassInFriendlyAssembly() { VerifyBasic( @"Imports System.Runtime.CompilerServices <Assembly: InternalsVisibleToAttribute(""TestProject"")> Friend Class C End Class" ); } [Fact, WorkItem(1154, "https://github.com/dotnet/roslyn-analyzers/issues/1154")] public void CA1812_CSharp_GenericInternalClass_InstanciatedNoDiagnostic() { VerifyCSharp(@" using System; using System.Collections.Generic; using System.Linq; public static class X { public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> source, Comparison<T> compare) { return source.OrderBy(new ComparisonComparer<T>(compare)); } public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> source, IComparer<T> comparer) { return source.OrderBy(t => t, comparer); } private class ComparisonComparer<T> : Comparer<T> { private readonly Comparison<T> _compare; public ComparisonComparer(Comparison<T> compare) { _compare = compare; } public override int Compare(T x, T y) { return _compare(x, y); } } } "); } [Fact, WorkItem(1154, "https://github.com/dotnet/roslyn-analyzers/issues/1154")] public void CA1812_Basic_GenericInternalClass_InstanciatedNoDiagnostic() { VerifyBasic(@" Imports System Imports System.Collections.Generic Imports System.Linq Imports System.Runtime.CompilerServices Module M <Extension()> Public Function OrderBy(Of T)(ByVal source As IEnumerable(Of T), compare As Comparison(Of T)) As IEnumerable(Of T) Return source.OrderBy(New ComparisonCompare(Of T)(compare)) End Function <Extension()> Public Function OrderBy(Of T)(ByVal source As IEnumerable(Of T), comparer As IComparer(Of T)) As IEnumerable(Of T) Return source.OrderBy(Function(i) i, comparer) End Function Private Class ComparisonCompare(Of T) Inherits Comparer(Of T) Private _compare As Comparison(Of T) Public Sub New(compare As Comparison(Of T)) _compare = compare End Sub Public Overrides Function Compare(x As T, y As T) As Integer Throw New NotImplementedException() End Function End Class End Module "); } [Fact, WorkItem(1158, "https://github.com/dotnet/roslyn-analyzers/issues/1158")] public void CA1812_CSharp_NoDiagnostic_GenericMethodWithNewConstraint() { VerifyCSharp(@" using System; internal class InstantiatedType { } internal static class Factory { internal static T Create<T>() where T : new() { return new T(); } } internal class Program { public static void Main(string[] args) { Console.WriteLine(Factory.Create<InstantiatedType>()); } }"); } [Fact, WorkItem(1158, "https://github.com/dotnet/roslyn-analyzers/issues/1158")] public void CA1812_Basic_NoDiagnostic_GenericMethodWithNewConstraint() { VerifyBasic(@" Imports System Module Module1 Sub Main() Console.WriteLine(Create(Of InstantiatedType)()) End Sub Friend Class InstantiatedType End Class Friend Function Create(Of T As New)() As T Return New T End Function End Module"); } [Fact, WorkItem(1158, "https://github.com/dotnet/roslyn-analyzers/issues/1158")] public void CA1812_CSharp_NoDiagnostic_GenericTypeWithNewConstraint() { VerifyCSharp(@" internal class InstantiatedType { } internal class Factory<T> where T : new() { } internal class Program { public static void Main(string[] args) { var factory = new Factory<InstantiatedType>(); } }"); } [Fact, WorkItem(1158, "https://github.com/dotnet/roslyn-analyzers/issues/1158")] public void CA1812_Basic_NoDiagnostic_GenericTypeWithNewConstraint() { VerifyBasic(@" Imports System Module Module1 Sub Main() Console.WriteLine(New Factory(Of InstantiatedType)) End Sub Friend Class InstantiatedType End Class Friend Class Factory(Of T As New) End Class End Module"); } [Fact, WorkItem(1158, "https://github.com/dotnet/roslyn-analyzers/issues/1158")] public void CA1812_CSharp_Diagnostic_NestedGenericTypeWithNoNewConstraint() { VerifyCSharp(@" using System.Collections.Generic; internal class InstantiatedType { } internal class Factory<T> where T : new() { } internal class Program { public static void Main(string[] args) { var list = new List<Factory<InstantiatedType>>(); } }", GetCSharpResultAt( 4, 16, AvoidUninstantiatedInternalClassesAnalyzer.Rule, "InstantiatedType"), GetCSharpResultAt( 8, 16, AvoidUninstantiatedInternalClassesAnalyzer.Rule, "Factory<T>")); } [Fact, WorkItem(1158, "https://github.com/dotnet/roslyn-analyzers/issues/1158")] public void CA1812_Basic_Diagnostic_NestedGenericTypeWithNoNewConstraint() { VerifyBasic(@" Imports System.Collections.Generic Module Library Friend Class InstantiatedType End Class Friend Class Factory(Of T As New) End Class Sub Main() Dim a = New List(Of Factory(Of InstantiatedType)) End Sub End Module", GetBasicResultAt( 5, 18, AvoidUninstantiatedInternalClassesAnalyzer.Rule, "Library.InstantiatedType"), GetBasicResultAt( 8, 18, AvoidUninstantiatedInternalClassesAnalyzer.Rule, "Library.Factory(Of T)")); } [Fact, WorkItem(1158, "https://github.com/dotnet/roslyn-analyzers/issues/1158")] public void CA1812_CSharp_NoDiagnostic_NestedGenericTypeWithNewConstraint() { VerifyCSharp(@" using System.Collections.Generic; internal class InstantiatedType { } internal class Factory1<T> where T : new() { } internal class Factory2<T> where T : new() { } internal class Program { public static void Main(string[] args) { var factory = new Factory1<Factory2<InstantiatedType>>(); } }"); } [Fact, WorkItem(1158, "https://github.com/dotnet/roslyn-analyzers/issues/1158")] public void CA1812_Basic_NoDiagnostic_NestedGenericTypeWithNewConstraint() { VerifyBasic(@" Imports System.Collections.Generic Module Library Friend Class InstantiatedType End Class Friend Class Factory1(Of T As New) End Class Friend Class Factory2(Of T As New) End Class Sub Main() Dim a = New Factory1(Of Factory2(Of InstantiatedType)) End Sub End Module"); } protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer() { return new AvoidUninstantiatedInternalClassesAnalyzer(); } protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() { return new AvoidUninstantiatedInternalClassesAnalyzer(); } } }
#if SILVERLIGHT using Microsoft.VisualStudio.TestTools.UnitTesting; #elif NETFX_CORE using DevExpress.TestFramework.NUnit; #else using NUnit.Framework; #endif using System; using System.Collections.Generic; using System.IO; namespace DevExpress.Mvvm.Tests { [TestFixture] public class BindableBaseTests { [System.Runtime.Serialization.DataContract] public class SerializableAndBindable : BindableBase { } [Test] public void IsSerializableTest() { SerializableAndBindable s = new SerializableAndBindable(); var serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(SerializableAndBindable)); MemoryStream m = new MemoryStream(); serializer.WriteObject(m, s); } [Test] public void PropertyChangedCallbackAndPropertyChangedEventOrderTest() { BindableBaseTest bb = new BindableBaseTest(); bool propertyChangedCalled = false; bb.PropertyChanged += (s, e) => { propertyChangedCalled = true; Assert.AreEqual("SomeProperty7", e.PropertyName); Assert.AreEqual(0, bb.ChangedCallbackCallCount); }; bb.SomeProperty7 = 777; Assert.IsTrue(propertyChangedCalled); Assert.AreEqual(1, bb.ChangedCallbackCallCount); } [Test] public void OnPropertiesChangedTest() { BindableBaseTest bb = new BindableBaseTest(); int count = 0; List<string> propNames = new List<string>(); bb.PropertyChanged += (o, e) => { count++; propNames.Add(e.PropertyName); }; bb.SomeProperty9 = 150; Assert.AreEqual("SomeProperty", propNames[0]); Assert.AreEqual("SomeProperty9", propNames[1]); Assert.AreEqual(2, count); propNames.Clear(); bb.SomeProperty10 = 150; Assert.AreEqual("SomeProperty2", propNames[0]); Assert.AreEqual("SomeProperty10", propNames[1]); Assert.AreEqual(4, count); propNames.Clear(); bb.SomeProperty11 = 150; Assert.AreEqual("SomeProperty2", propNames[0]); Assert.AreEqual("SomeProperty3", propNames[1]); Assert.AreEqual("SomeProperty10", propNames[2]); Assert.AreEqual(7, count); propNames.Clear(); bb.SomeProperty12 = 150; Assert.AreEqual("SomeProperty2", propNames[0]); Assert.AreEqual("SomeProperty3", propNames[1]); Assert.AreEqual("SomeProperty10", propNames[2]); Assert.AreEqual("SomeProperty11", propNames[3]); Assert.AreEqual(11, count); propNames.Clear(); bb.SomeProperty13 = 150; Assert.AreEqual("SomeProperty2", propNames[0]); Assert.AreEqual("SomeProperty3", propNames[1]); Assert.AreEqual("SomeProperty10", propNames[2]); Assert.AreEqual("SomeProperty11", propNames[3]); Assert.AreEqual("SomeProperty12", propNames[4]); Assert.AreEqual(16, count); } [Test] public void OnPropertyChangedTest() { BindableBaseTest bb = new BindableBaseTest(); int count = 0; string propName = null; bb.SomeProperty = 50; bb.PropertyChanged += (o, e) => { count++; propName = e.PropertyName; }; bb.SomeProperty = 150; Assert.AreEqual("SomeProperty", propName); Assert.AreEqual(1, count); bb.SomeProperty8 = 150; Assert.AreEqual("SomeProperty8", propName); Assert.AreEqual(2, count); } #if !NETFX_CORE [Test] public void RaisePropertyChangedWithNoParametersTest_B251476() { BindableBaseTest bb = new BindableBaseTest(); bb.RaisePropertyChanged(null); bb.RaisePropertyChanged(string.Empty); bb.RaisePropertyChanged(); bb.RaisePropertiesChanged(null); bb.RaisePropertiesChanged(string.Empty); } #endif [Test] public void SetPropertyTest() { BindableBaseTest bb = new BindableBaseTest(); int count = 0; string propName = null; bb.SomeProperty2 = 50; bb.PropertyChanged += (o, e) => { count++; propName = e.PropertyName; }; bb.SomeProperty2 = 150; Assert.AreEqual("SomeProperty2", propName); Assert.AreEqual(1, count); Assert.AreEqual(150, bb.SomeProperty2); bb.SomeProperty2 = 150; Assert.AreEqual(1, count); } [Test] public void SetPropertyWithLambdaTest() { BindableBaseTest bb = new BindableBaseTest(); int count = 0; string propName = null; bb.SomeProperty3 = 50; bb.PropertyChanged += (o, e) => { count++; propName = e.PropertyName; }; bb.SomeProperty3 = 150; Assert.AreEqual("SomeProperty3", propName); Assert.AreEqual(1, count); Assert.AreEqual(150, bb.SomeProperty3); bb.SomeProperty3 = 150; Assert.AreEqual(1, count); } #if !NETFX_CORE [Test, ExpectedException(typeof(ArgumentException))] public void SetPropertyInvalidLambdaTest() { BindableBaseTest bb = new BindableBaseTest(); bb.SomeProperty4 = 150; } [Test, ExpectedException(typeof(ArgumentException))] public void SetPropertyInvalidLambdaTest2() { BindableBaseTest bb = new BindableBaseTest(); bb.SomeProperty5 = 150; } [Test, ExpectedException(typeof(ArgumentException))] public void SetPropertyInvalidLambdaTest3() { BindableBaseTest bb = new BindableBaseTest(); bb.SomeProperty6 = 150; } #endif [Test] public void SetPropertyWithCallbackTest() { BindableBaseTest bb = new BindableBaseTest(); int count = 0; string propName = null; bb.SomeProperty7 = 50; Assert.AreEqual(1, bb.ChangedCallbackCallCount); bb.PropertyChanged += (o, e) => { count++; propName = e.PropertyName; }; bb.SomeProperty7 = 150; Assert.AreEqual(2, bb.ChangedCallbackCallCount); Assert.AreEqual("SomeProperty7", propName); Assert.AreEqual(1, count); Assert.AreEqual(150, bb.SomeProperty7); bb.SomeProperty7 = 150; Assert.AreEqual(1, count); } #region property bag test class PropertyBagViewModel : BindableBase { public bool? IntPropertySetValueResult; public int IntProperty { get { return GetProperty(() => IntProperty); } set { IntPropertySetValueResult = SetProperty(() => IntProperty, value); } } public int StringPropertyChangedCount; public string StringProperty { get { return GetProperty(() => StringProperty); } set { SetProperty(() => StringProperty, value, () => StringPropertyChangedCount ++); } } } [Test] public void GetSetPropertyTest() { var viewModel = new PropertyBagViewModel(); int propertyChangedCount = 0; string propName = null; viewModel.PropertyChanged += (o, e) => { propertyChangedCount++; propName = e.PropertyName; }; Assert.AreEqual(0, viewModel.IntProperty); Assert.IsFalse(viewModel.PropertyManager.propertyBag.ContainsKey("IntProperty")); viewModel.IntProperty = 0; Assert.AreEqual(0, viewModel.IntProperty); Assert.IsFalse(viewModel.PropertyManager.propertyBag.ContainsKey("IntProperty")); Assert.AreEqual(false, viewModel.IntPropertySetValueResult.Value); Assert.AreEqual(0, propertyChangedCount); Assert.AreEqual(null, propName); viewModel.IntProperty = 9; Assert.AreEqual(9, viewModel.IntProperty); Assert.IsTrue(viewModel.PropertyManager.propertyBag.ContainsKey("IntProperty")); Assert.AreEqual(true, viewModel.IntPropertySetValueResult.Value); Assert.AreEqual(1, propertyChangedCount); Assert.AreEqual("IntProperty", propName); viewModel.IntProperty = 0; Assert.AreEqual(0, viewModel.IntProperty); Assert.IsTrue(viewModel.PropertyManager.propertyBag.ContainsKey("IntProperty")); Assert.AreEqual(true, viewModel.IntPropertySetValueResult.Value); Assert.AreEqual(2, propertyChangedCount); Assert.AreEqual("IntProperty", propName); viewModel.StringProperty = null; Assert.AreEqual(null, viewModel.StringProperty); Assert.AreEqual(0, viewModel.StringPropertyChangedCount); Assert.AreEqual(2, propertyChangedCount); viewModel.StringProperty = string.Empty; Assert.AreEqual(string.Empty, viewModel.StringProperty); Assert.AreEqual(1, viewModel.StringPropertyChangedCount); Assert.AreEqual(3, propertyChangedCount); Assert.AreEqual("StringProperty", propName); viewModel.StringProperty = "x"; Assert.AreEqual("x", viewModel.StringProperty); Assert.AreEqual(2, viewModel.StringPropertyChangedCount); viewModel.StringProperty = "x"; Assert.AreEqual("x", viewModel.StringProperty); Assert.AreEqual(2, viewModel.StringPropertyChangedCount); } #endregion } class BindableBaseTest : BindableBase { public int ChangedCallbackCallCount { get; private set; } int someProperty7; public int SomeProperty7 { get { return someProperty7; } set { SetProperty(ref someProperty7, value, () => SomeProperty7, () => { ChangedCallbackCallCount++; }); } } int someProperty6; public int SomeProperty6 { get { return someProperty6; } set { SetProperty(ref someProperty6, value, () => this[0]); } } int this[int index] { get { return 0; }} int someProperty5; public int SomeProperty5 { get { return someProperty5; } set { SetProperty(ref someProperty5, value, () => GetHashCode()); } } int someProperty4; public int SomeProperty4 { get { return someProperty4; } set { SetProperty(ref someProperty4, value, () => 1); } } int someProperty3; public int SomeProperty3 { get { return someProperty3; } set { SetProperty(ref someProperty3, value, () => SomeProperty3); } } int someProperty2; public int SomeProperty2 { get { return someProperty2; } set { SetProperty(ref someProperty2, value, "SomeProperty2"); } } public int SomeProperty { set { RaisePropertyChanged("SomeProperty"); } } public int SomeProperty8 { get { return 0; } set { RaisePropertyChanged(() => SomeProperty8); } } public int SomeProperty9 { set { RaisePropertiesChanged("SomeProperty", "SomeProperty9"); } } public int SomeProperty10 { get { return 0; } set { RaisePropertiesChanged(() => SomeProperty2, () => SomeProperty10); } } public int SomeProperty11 { get { return 0; } set { RaisePropertiesChanged(() => SomeProperty2, () => SomeProperty3, () => SomeProperty10); } } public int SomeProperty12 { get { return 0; } set { RaisePropertiesChanged(() => SomeProperty2, () => SomeProperty3, () => SomeProperty10, () => SomeProperty11); } } public int SomeProperty13 { get { return 0; } set { RaisePropertiesChanged(() => SomeProperty2, () => SomeProperty3, () => SomeProperty10, () => SomeProperty11, () => SomeProperty12); } } public new void RaisePropertyChanged(string propertyName) { base.RaisePropertyChanged(propertyName); } #if !NETFX_CORE public new void RaisePropertyChanged() { base.RaisePropertyChanged(); } #endif public new void RaisePropertiesChanged(params string[] propertyNames) { base.RaisePropertiesChanged(propertyNames); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace VideoStoreRedux.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; namespace Sharp6800.Trainer { public enum Peripheral { PRA, PRB } public enum RegisterSelected { PRA, DDRA, CRA, PRB, DDRB, CRB, } public class PeripheralEventArgs { public Peripheral Peripheral { get; set; } public int Value { get; set; } public PeripheralEventArgs(Peripheral peripheral) { Peripheral = peripheral; Value = 0; } public PeripheralEventArgs(Peripheral peripheral, int value) { Peripheral = peripheral; Value = value; } } public class DebugConsoleAdapter : RS232Adapder { public override void WriteByte(int value) { Debug.Write($"{new string((char)value, 1)}"); } } public abstract class RS232Adapder { private int sendState = 0; private int sendBuffer = 0; private int rcvState = 0; private int rcvBuffer = 0x7F; private Queue<int> inputBuffer = new Queue<int>(); private int tempBuffer; public abstract void WriteByte(int value); public void WriteString(string value) { foreach (var chr in value) { inputBuffer.Enqueue(chr); } } public void WriteCharacter(int value) { inputBuffer.Enqueue(value); } public int Write() { var value = 0x7F; if (rcvState == 0) { if (inputBuffer.Count > 0) { tempBuffer = inputBuffer.Dequeue(); rcvState++; value = 0xFF; } } else if (rcvState == 1) { value = 0xFF; rcvState++; } else if (rcvState == 2) { value = 0x7F; rcvState++; } else if (rcvState == 11) { rcvState = 0; value = 0x7F; } else { //value = 0x7E | (tempBuffer >> rcvState - 1); value = tempBuffer << 7 - (rcvState - 3); value = value & 0x80; value = value | 0b1110; rcvState++; } return value; } public void Read(int value) { //value &= 1; if (sendState == 0) { if (value == 0) { sendBuffer = 0; sendState++; } } else if (sendState == 9) { if (value == 1) { if (sendBuffer > 0) { WriteByte(sendBuffer); } sendState = 0; } } else { sendBuffer |= value << sendState - 1; sendState++; } } } public class MC6820 { /** * RS0/1 = Register Select 0/1 * CRA/B = Control Register A/B * DDRA/B = Data Direction Register A/B * PRA/B = Peripheral Register A/B */ private int CRA = 0; private int CRB = 0; private int DDRA = 0; private int DDRB = 0; private int PRA = 0; private int PRB = 0; private RegisterSelected registerSelected = RegisterSelected.DDRA; public EventHandler<PeripheralEventArgs> OnPeripheralWrite { get; set; } public EventHandler<PeripheralEventArgs> OnPeripheralRead { get; set; } public void Set(int registerSelect, int value) { switch (registerSelect) { // RS1 = 0, RS0 = 0 case 0: switch (CRA & 4) { // CRA-B4 = 1 case 4: PRA = value; OnPeripheralWrite?.Invoke(this, new PeripheralEventArgs(Peripheral.PRA, value)); return; // CRA-B4 = 0 case 0: DDRA = value; return; } break; // RS1 = 0, RS0 = 1 case 1: CRA = value; return; // RS1 = 1, RS0 = 0 case 2: switch (CRB & 4) { // CRB-B4 = 1 case 4: PRB = value; OnPeripheralWrite?.Invoke(this, new PeripheralEventArgs(Peripheral.PRB, value)); return; // CRB-B4 = 0 case 0: DDRB = value; return; } break; // RS1 = 1, RS0 = 1 case 3: CRB = value; return; } throw new Exception("Invalid state"); } public void Set(int value) { switch (registerSelected) { case RegisterSelected.PRA: PRA = value; OnPeripheralWrite?.Invoke(this, new PeripheralEventArgs(Peripheral.PRA, value)); break; case RegisterSelected.DDRA: DDRA = value; break; case RegisterSelected.CRA: CRA = value; break; case RegisterSelected.PRB: PRB = value; OnPeripheralWrite.Invoke(this, new PeripheralEventArgs(Peripheral.PRB, value)); break; case RegisterSelected.DDRB: DDRB = value; break; case RegisterSelected.CRB: CRB = value; break; } //Debug.WriteLine("WRITE: {0:X4}", value); } public int Get(int registerSelect) { switch (registerSelect) { // RS1 = 0, RS0 = 0 case 0: switch (CRA & 4) { // CRA-B4 = 1 case 4: var eventArgs = new PeripheralEventArgs(Peripheral.PRA); OnPeripheralRead.Invoke(this, eventArgs); return eventArgs.Value; // CRA-B4 = 0 case 0: return DDRA; } break; // RS1 = 0, RS0 = 1 case 1: return CRA; // RS1 = 1, RS0 = 0 case 2: switch (CRB & 4) { // CRB-B4 = 1 case 4: var eventArgs = new PeripheralEventArgs(Peripheral.PRB); OnPeripheralRead.Invoke(this, eventArgs); return eventArgs.Value; // CRB-B4 = 0 case 0: return DDRB; } break; // RS1 = 0, RS0 = 1 case 3: return CRB; } throw new Exception("Invalid state"); } public int Get() { var value = 0x7F; switch (registerSelected) { case RegisterSelected.PRA: return PRA; case RegisterSelected.DDRA: return DDRA; case RegisterSelected.CRA: return CRA; case RegisterSelected.PRB: return PRB; case RegisterSelected.DDRB: return DDRB; case RegisterSelected.CRB: return CRB; } return value; } public void RegisterSelect(int value) { switch (value & 3) { case 0: switch (CRA & 4) { case 4: registerSelected = RegisterSelected.PRA; break; case 0: registerSelected = RegisterSelected.DDRA; break; } break; case 1: registerSelected = RegisterSelected.CRA; break; case 2: switch (CRB & 4) { case 4: registerSelected = RegisterSelected.PRB; break; case 0: registerSelected = RegisterSelected.DDRB; break; } break; case 3: registerSelected = RegisterSelected.CRB; break; } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using Azure.Core; namespace Azure.Data.Tables { /// <summary> /// A generic dictionary-like <see cref="ITableEntity"/> type which defines an arbitrary set of properties on an entity as key-value pairs. /// </summary> /// <remarks> /// This type can be used with any of the generic entity interaction methods in <see cref="TableClient"/> where entity model type flexibility is desired. /// For example, if your table contains a jagged schema, or you need to precisely update a subset of properties in a <see cref="TableUpdateMode.Merge"/> mode operation. /// </remarks> public sealed partial class TableEntity : ITableEntity { private readonly IDictionary<string, object> _properties; /// <summary> /// The partition key is a unique identifier for the partition within a given table and forms the first part of an entity's primary key. /// </summary> /// <value>A string containing the partition key for the entity.</value> public string PartitionKey { get { return GetString(TableConstants.PropertyNames.PartitionKey); } set { _properties[TableConstants.PropertyNames.PartitionKey] = value; } } /// <summary> /// The row key is a unique identifier for an entity within a given partition. Together, the <see cref="PartitionKey" /> and RowKey uniquely identify an entity within a table. /// </summary> /// <value>A string containing the row key for the entity.</value> public string RowKey { get { return GetString(TableConstants.PropertyNames.RowKey); } set { _properties[TableConstants.PropertyNames.RowKey] = value; } } /// <summary> /// The Timestamp property is a DateTimeOffset value that is maintained on the server side to record the time an entity was last modified. /// The Table service uses the Timestamp property internally to provide optimistic concurrency. The value of Timestamp is a monotonically increasing value, /// meaning that each time the entity is modified, the value of Timestamp increases for that entity. This property should not be set on insert or update operations (the value will be ignored). /// </summary> /// <value>A <see cref="DateTimeOffset"/> containing the timestamp of the entity.</value> public DateTimeOffset? Timestamp { get { return GetValue<DateTimeOffset?>(TableConstants.PropertyNames.Timestamp); } set { _properties[TableConstants.PropertyNames.Timestamp] = value; } } /// <summary> /// Gets or sets the entity's ETag. /// </summary> /// <value>An <see cref="ETag"/> containing the ETag value for the entity.</value> public ETag ETag { get { return new(GetString(TableConstants.PropertyNames.EtagOdata)); } set { _properties[TableConstants.PropertyNames.EtagOdata] = value.ToString(); } } /// <summary> /// Creates an instance of the <see cref="TableEntity" /> class without any properties initialized. /// </summary> public TableEntity() : this(null) { } /// <summary> /// Initializes a new instance of the <see cref="TableEntity"/> class with the specified partition key and row key. /// </summary> /// <param name="partitionKey">A string containing the partition key of the <see cref="TableEntity"/> to be initialized.</param> /// <param name="rowKey">A string containing the row key of the <see cref="TableEntity"/> to be initialized.</param> public TableEntity(string partitionKey, string rowKey) : this(null) { PartitionKey = partitionKey; RowKey = rowKey; } /// <summary> /// Initializes a new instance of the <see cref="TableEntity"/> class with properties specified in <paramref name="values"/>. /// </summary> /// <param name="values">A <see cref="IDictionary"/> containing the initial values of the entity.</param> public TableEntity(IDictionary<string, object> values) { _properties = values != null ? new Dictionary<string, object>(values) : new Dictionary<string, object>(); } /// <summary> /// Get the value of a <see cref="TableEntity"/>'s /// <see cref="string"/> property called /// <paramref name="key"/>. /// </summary> /// <param name="key">The name of the property.</param> /// <returns>The value of the property.</returns> /// <exception cref="InvalidOperationException">Value associated with given <paramref name="key"/> is not of type <see cref="string" />.</exception> public string GetString(string key) => GetValue<string>(key); /// <summary> /// Get the value of a <see cref="TableEntity"/>'s /// <see cref="BinaryData"/> property called /// <paramref name="key"/>. /// </summary> /// <param name="key">The name of the property.</param> /// <returns>The value of the property.</returns> /// <exception cref="InvalidOperationException">Value associated with given <paramref name="key"/> is not of type byte array.</exception> public BinaryData GetBinaryData(string key) => GetValue<BinaryData>(key); /// <summary> /// Get the value of a <see cref="TableEntity"/>'s /// <see cref="byte"/> property called /// <paramref name="key"/>. /// </summary> /// <param name="key">The name of the property.</param> /// <returns>The value of the property.</returns> /// <exception cref="InvalidOperationException">Value associated with given <paramref name="key"/> is not of type byte array.</exception> public byte[] GetBinary(string key) => GetValue<byte[]>(key); /// <summary> /// Get the value of a <see cref="TableEntity"/>'s /// <see cref="string"/> property called /// <paramref name="key"/>. /// </summary> /// <param name="key">The name of the property.</param> /// <returns>The value of the property.</returns> /// <exception cref="InvalidOperationException">Value associated with given <paramref name="key"/> is not of type <see cref="bool" />.</exception> public bool? GetBoolean(string key) => GetValue<bool?>(key); /// <summary> /// Get the value of a <see cref="TableEntity"/>'s /// <see cref="DateTime"/> property called /// <paramref name="key"/>. /// </summary> /// <param name="key">The name of the property.</param> /// <returns>The value of the property.</returns> /// <exception cref="InvalidOperationException">Value associated with given <paramref name="key"/> is not of type <see cref="DateTime" />.</exception> public DateTime? GetDateTime(string key) => GetValue<DateTime?>(key); /// <summary> /// Get the value of a <see cref="TableEntity"/>'s /// <see cref="DateTimeOffset"/> property called /// <paramref name="key"/>. /// </summary> /// <param name="key">The name of the property.</param> /// <returns>The value of the property.</returns> /// <exception cref="InvalidOperationException">Value associated with given <paramref name="key"/> is not of type <see cref="DateTimeOffset" />.</exception> public DateTimeOffset? GetDateTimeOffset(string key) => GetValue<DateTimeOffset?>(key); /// <summary> /// Get the value of a <see cref="TableEntity"/>'s /// <see cref="double"/> property called /// <paramref name="key"/>. /// </summary> /// <param name="key">The name of the property.</param> /// <returns>The value of the property.</returns> /// <exception cref="InvalidOperationException">Value associated with given <paramref name="key"/> is not of type <see cref="double" />.</exception> public double? GetDouble(string key) => GetValue<double?>(key); /// <summary> /// Get the value of a <see cref="TableEntity"/>'s /// <see cref="Guid"/> property called /// <paramref name="key"/>. /// </summary> /// <param name="key">The name of the property.</param> /// <returns>The value of the property.</returns> /// <exception cref="InvalidOperationException">Value associated with given <paramref name="key"/> is not of type <see cref="Guid" />.</exception> public Guid? GetGuid(string key) => GetValue<Guid?>(key); /// <summary> /// Get the value of a <see cref="TableEntity"/>'s /// <see cref="int"/> property called /// <paramref name="key"/>. /// </summary> /// <param name="key">The name of the property.</param> /// <returns>The value of the property.</returns> /// <exception cref="InvalidOperationException">Value associated with given <paramref name="key"/> is not of type <see cref="int" />.</exception> public int? GetInt32(string key) => GetValue<int?>(key); /// <summary> /// Get the value of a <see cref="TableEntity"/>'s /// <see cref="long"/> property called /// <paramref name="key"/>. /// </summary> /// <param name="key">The name of the property.</param> /// <returns>The value of the property.</returns> /// <exception cref="InvalidOperationException">Value associated with given <paramref name="key"/> is not of type <see cref="long" />.</exception> public long? GetInt64(string key) => GetValue<long?>(key); /// <summary> /// Set a document property. /// </summary> /// <param name="key">The property name.</param> /// <param name="value">The property value.</param> /// <exception cref="InvalidOperationException">The given <paramref name="value"/> does not match the type of the existing value associated with given <paramref name="key"/>.</exception> private void SetValue(string key, object value) { Argument.AssertNotNullOrEmpty(key, nameof(key)); if (value != null && _properties.TryGetValue(key, out object existingValue) && existingValue != null) { value = CoerceType(existingValue, value); } _properties[key] = value; } /// <summary> /// Get an entity property. /// </summary> /// <typeparam name="T">The expected type of the property value.</typeparam> /// <param name="key">The property name.</param> /// <returns>The value of the property.</returns> /// <exception cref="InvalidOperationException">Value associated with given <paramref name="key"/> is not of given type <typeparamref name="T"/>.</exception> private T GetValue<T>(string key) => (T)GetValue(key, typeof(T)); /// <summary> /// Get an entity property. /// </summary> /// <param name="key">The property name.</param> /// <param name="type">The expected type of the property value.</param> /// <returns>The value of the property.</returns> /// <exception cref="InvalidOperationException">Value associated with given <paramref name="key"/> is not of type <paramref name="type"/>.</exception> private object GetValue(string key, Type type = null) { Argument.AssertNotNullOrEmpty(key, nameof(key)); if (!_properties.TryGetValue(key, out object value) || value == null) { return null; } if (type != null) { var valueType = value.GetType(); if (type == typeof(DateTime?) && valueType == typeof(DateTimeOffset)) { return ((DateTimeOffset)value).UtcDateTime; } if (type == typeof(DateTimeOffset?) && valueType == typeof(DateTime)) { return new DateTimeOffset((DateTime)value); } if (type == typeof(BinaryData) && valueType == typeof(byte[])) { return new BinaryData(value); } EnforceType(type, valueType); } return value; } /// <summary> /// Ensures that the given type matches the type of the existing /// property; throws an exception if the types do not match. /// </summary> private static void EnforceType(Type requestedType, Type givenType) { if (!requestedType.IsAssignableFrom(givenType)) { throw new InvalidOperationException(string.Format( CultureInfo.InvariantCulture, $"Cannot return {requestedType} type for a {givenType} typed property.")); } } /// <summary> /// Performs type coercion for numeric types. /// <param name="newValue"/> of type int will be coerced to long or double if <param name="existingValue"/> is typed as long or double. /// All other type assignment changes will be accepted as is. /// </summary> private static object CoerceType(object existingValue, object newValue) { if (!existingValue.GetType().IsAssignableFrom(newValue.GetType())) { return existingValue switch { double _ => newValue switch { // if we already had a double value, preserve it as double even if newValue was an int. // example: entity["someDoubleValue"] = 5; int newIntValue => (double)newIntValue, _ => newValue }, long _ => newValue switch { // if we already had a long value, preserve it as long even if newValue was an int. // example: entity["someLongValue"] = 5; int newIntValue => (long)newIntValue, _ => newValue }, _ => newValue }; } return newValue; } } }
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *********************************************************************/ using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using Axiom.MathLib; using Axiom.Core; using Axiom.Animating; using System.ComponentModel; using System.Xml; using Multiverse.CollisionLib; namespace Multiverse.CollisionLib { public enum PolygonKind { Illegal = 0, CV, Terrain, Bounding } public class PathData { protected static int codeVersion = 1; protected int version; protected const float oneMeter = 1000.0f; protected List<PathObject> pathObjects; public PathData() { version = codeVersion; pathObjects = new List<PathObject>(); } public PathData(XmlReader r) { pathObjects = new List<PathObject>(); FromXml(r); } public void AddModelPathObject(bool logPathGeneration, PathObjectType type, string modelName, Vector3 modelPosition, Matrix4 modelTransform, List<CollisionShape> shapes, float terrainHeight) { PathGenerator pathGenerator = new PathGenerator(logPathGeneration, modelName, type, terrainHeight, modelTransform, shapes); // Perform traversal and creation of polygons, arcs // between polygons, and portals to the terrain pathGenerator.GeneratePolygonsArcsAndPortals(); List<PathPolygon> polygons = new List<PathPolygon>(); List<PathArc> portals = new List<PathArc>(); List<PathArc> arcs = new List<PathArc>(); foreach(GridPolygon r in pathGenerator.CVPolygons) polygons.Add(new PathPolygon(r.Index, PolygonKind.CV, r.CornerLocs)); foreach(GridPolygon r in pathGenerator.TerrainPolygons) polygons.Add(new PathPolygon(r.Index, PolygonKind.Terrain, r.CornerLocs)); foreach(PolygonArc portal in pathGenerator.TerrainPortals) portals.Add(new PathArc(portal.Kind, portal.Poly1Index, portal.Poly2Index, MakePathEdge(portal.Edge))); foreach(PolygonArc arc in pathGenerator.PolygonArcs) arcs.Add(new PathArc(arc.Kind, arc.Poly1Index, arc.Poly2Index, MakePathEdge(arc.Edge))); pathObjects.Add(new PathObject(pathGenerator.ModelName, type.name, pathGenerator.FirstTerrainIndex, new PathPolygon(0, PolygonKind.Bounding, pathGenerator.ModelCorners), polygons, portals, arcs)); } public int CodeVersion { get { return codeVersion; } } public int Version { get { return version; } } public List<PathObject> PathObjects { get { return pathObjects; } } protected void FromXml(XmlReader r) { for (int i = 0; i < r.AttributeCount; i++) { r.MoveToAttribute(i); // set the field in this object based on the element we just read if (r.Name == "version") version = int.Parse(r.Value); } r.MoveToElement(); //Moves the reader back to the element node. while (r.Read()) { if (r.NodeType == XmlNodeType.Whitespace) continue; else if (r.NodeType == XmlNodeType.EndElement) break; else if (r.NodeType == XmlNodeType.Element) { if (r.Name == "PathObject") pathObjects.Add(new PathObject(r)); } } } public void ToXml(XmlWriter w) { if (pathObjects.Count > 0) { w.WriteStartElement("PathData"); w.WriteAttributeString("version", version.ToString()); foreach (PathObject obj in pathObjects) obj.ToXml(w); w.WriteEndElement(); } } protected PathEdge MakePathEdge (GridEdge edge) { return new PathEdge(edge.StartLoc, edge.EndLoc); } } public class PathObjectType { public string name; public float height; public float width; public float maxClimbSlope; public float gridResolution; public float maxDisjointDistance; public int minimumFeatureSize; public PathObjectType(string name, float height, float width, float maxClimbSlope, float gridResolution, float maxDisjointDistance, int minimumFeatureSize) { this.AcceptValues(name, height, width, maxClimbSlope, gridResolution, maxDisjointDistance, minimumFeatureSize); } public PathObjectType(XmlReader r) { FromXml(r); } public PathObjectType() { } public PathObjectType(PathObjectType other) { name = other.name; height = other.height; width = other.width; maxClimbSlope = other.maxClimbSlope; gridResolution = other.gridResolution; maxDisjointDistance = other.maxDisjointDistance; minimumFeatureSize = other.minimumFeatureSize; } public void AcceptValues(string name, float height, float width, float maxClimbSlope, float gridResolution, float maxDisjointDistance, int minimumFeatureSize) { this.name = name; this.height = height; this.width = width; this.maxClimbSlope = maxClimbSlope; this.gridResolution = gridResolution; this.maxDisjointDistance = maxDisjointDistance; this.minimumFeatureSize = minimumFeatureSize; } public void ToXml(XmlWriter w) { w.WriteStartElement("PathObjectType"); w.WriteAttributeString("name", name); w.WriteAttributeString("height", height.ToString()); w.WriteAttributeString("width", width.ToString()); w.WriteAttributeString("maxClimbSlope", maxClimbSlope.ToString()); w.WriteAttributeString("gridResolution", gridResolution.ToString()); w.WriteAttributeString("maxDisjointDistance", maxDisjointDistance.ToString()); w.WriteAttributeString("minimumFeatureSize", minimumFeatureSize.ToString()); w.WriteEndElement(); } public void FromXml(XmlReader r) { // first parse the attributes for (int i = 0; i < r.AttributeCount; i++) { r.MoveToAttribute(i); // set the field in this object based on the element we just read switch (r.Name) { case "name": name = r.Value; break; case "height": height = float.Parse(r.Value); break; case "width": width = float.Parse(r.Value); break; case "maxClimbSlope": maxClimbSlope = float.Parse(r.Value); break; case "gridResolution": gridResolution = float.Parse(r.Value); break; case "maxDisjointDistance": maxDisjointDistance = float.Parse(r.Value); break; case "minimumFeatureSize": minimumFeatureSize = int.Parse(r.Value); break; } } } } public class PathObject { protected string modelName; protected string type; protected int firstTerrainIndex; protected PathPolygon boundingPolygon; protected List<PathPolygon> polygons; protected List<PathArc> portals; protected List<PathArc> arcs; public PathObject(string modelName, string type, int firstTerrainIndex, PathPolygon boundingPolygon, List<PathPolygon> polygons, List<PathArc> portals, List<PathArc> arcs) { this.modelName = modelName; this.type = type; this.firstTerrainIndex = firstTerrainIndex; this.boundingPolygon = boundingPolygon; this.polygons = polygons; this.portals = portals; this.arcs = arcs; } public PathObject(XmlReader r) { FromXml(r); } public void FromXml(XmlReader r) { for (int i = 0; i < r.AttributeCount; i++) { r.MoveToAttribute(i); // set the field in this object based on the element we just read if (r.Name == "modelName") modelName = r.Value; if (r.Name == "type") type = r.Value; if (r.Name == "firstTerrainIndex") firstTerrainIndex = int.Parse(r.Value); } r.MoveToElement(); //Moves the reader back to the element node. while (r.Read()) { if (r.NodeType == XmlNodeType.Whitespace) { continue; } // look for the start of an element if (r.NodeType == XmlNodeType.Element) { // parse that element // save the name of the element string elementName = r.Name; switch (elementName) { case "BoundingPolygon": List<PathPolygon> polys = ReadPolygons(r); Debug.Assert(polys.Count == 1, "In PathObject.FromXml, must have exactly one polygon in BoundingPolygon list!"); boundingPolygon = polys[0]; break; case "PathPolygons": polygons = ReadPolygons(r); break; case "PathPortals": portals = ReadArcs(r); break; case "PathArcs": arcs = ReadArcs(r); break; } } else if (r.NodeType == XmlNodeType.EndElement) { break; } } } private List<PathPolygon> ReadPolygons(XmlReader r) { List<PathPolygon> polygons = new List<PathPolygon>(); while (r.Read()) { if (r.NodeType == XmlNodeType.Whitespace) { continue; } r.MoveToElement(); //Moves the reader back to the element node. // look for the start of an element if (r.NodeType == XmlNodeType.Element) { // parse that element // save the name of the element if (r.Name == "PathPolygon") polygons.Add(new PathPolygon(r)); } else if (r.NodeType == XmlNodeType.EndElement) { break; } } return polygons; } private List<PathArc> ReadArcs(XmlReader r) { List<PathArc> theArcs = new List<PathArc>(); while (r.Read()) { if (r.NodeType == XmlNodeType.Whitespace) { continue; } r.MoveToElement(); //Moves the reader back to the element node. // look for the start of an element if (r.NodeType == XmlNodeType.Element) { // parse that element // save the name of the element if (r.Name == "PathArc") theArcs.Add(new PathArc(r)); } else if (r.NodeType == XmlNodeType.EndElement) { break; } } return theArcs; } public void ToXml(XmlWriter w) { w.WriteStartElement("PathObject"); w.WriteAttributeString("modelName", modelName); w.WriteAttributeString("type", type); w.WriteAttributeString("firstTerrainIndex", firstTerrainIndex.ToString()); w.WriteStartElement("BoundingPolygon"); boundingPolygon.ToXml(w); w.WriteEndElement(); if (polygons.Count > 0) { w.WriteStartElement("PathPolygons"); foreach(PathPolygon rect in polygons) rect.ToXml(w); w.WriteEndElement(); } if (portals.Count > 0) { w.WriteStartElement("PathPortals"); foreach(PathArc portal in portals) portal.ToXml(w); w.WriteEndElement(); } if (arcs.Count > 0) { w.WriteStartElement("PathArcs"); foreach(PathArc arc in arcs) arc.ToXml(w); w.WriteEndElement(); } w.WriteEndElement(); } } public class PathPolygon { protected int index; protected PolygonKind kind; protected Vector3 [] corners; public PathPolygon(int index, PolygonKind kind, Vector3 [] corners) { this.kind = kind; this.index = index; this.corners = corners; } public PathPolygon(XmlReader r) { FromXml(r); } public static String PolygonKindToString(PolygonKind kind) { switch (kind) { case PolygonKind.Illegal: return "Illegal"; case PolygonKind.CV: return "CV"; case PolygonKind.Terrain: return "Terrain"; case PolygonKind.Bounding: return "Bounding"; default: return "Unknown PolygonKind " + (int)kind; } } public static PolygonKind PolygonKindFromString(String s) { switch (s) { case "Illegal": return PolygonKind.Illegal; case "CV": return PolygonKind.CV; case "Terrain": return PolygonKind.Terrain; case "Bounding": return PolygonKind.Bounding; default: return PolygonKind.Illegal; } } public int Index { get { return index; } } public PolygonKind Kind { get { return kind; } } public Vector3 [] Corners { get { return corners; } } public void FromXml(XmlReader r) { corners = new Vector3[4]; int cornerNumber = 0; while (r.Read()) { if (r.NodeType == XmlNodeType.Whitespace) { continue; } for (int i = 0; i < r.AttributeCount; i++) { r.MoveToAttribute(i); // set the field in this object based on the element we just read if (r.Name == "kind") { kind = PolygonKindFromString(r.Value); break; } if (r.Name == "index") { index = int.Parse(r.Value); break; } } r.MoveToElement(); //Moves the reader back to the element node. // look for the start of an element if (r.NodeType == XmlNodeType.Element) { // parse that element // save the name of the element string elementName = r.Name; switch (elementName) { case "Corner": corners[cornerNumber++] = XmlHelperClass.ParseVectorAttributes(r); break; } } else if (r.NodeType == XmlNodeType.EndElement) { break; } } } public void ToXml(XmlWriter w) { w.WriteStartElement("PathPolygon"); w.WriteAttributeString("kind", PathPolygon.PolygonKindToString(kind)); w.WriteAttributeString("index", index.ToString()); foreach(Vector3 corner in corners) XmlHelperClass.WriteVectorElement(w, "Corner", corner); w.WriteEndElement(); } } public class PathEdge { protected Vector3 start, end; public PathEdge(Vector3 start, Vector3 end) { this.start = start; this.end = end; } public PathEdge(XmlReader r) { FromXml(r); } public void FromXml(XmlReader r) { while (r.Read()) { if (r.NodeType == XmlNodeType.Whitespace) { continue; } r.MoveToElement(); //Moves the reader back to the element node. // look for the start of an element if (r.NodeType == XmlNodeType.Element) { // parse that element // save the name of the element string elementName = r.Name; switch (elementName) { case "Start": start = XmlHelperClass.ParseVectorAttributes(r); break; case "End": end = XmlHelperClass.ParseVectorAttributes(r); break; } } else if (r.NodeType == XmlNodeType.EndElement) { break; } } } public void ToXml(XmlWriter w) { w.WriteStartElement("PathEdge"); XmlHelperClass.WriteVectorElement(w, "Start", start); XmlHelperClass.WriteVectorElement(w, "End", end); w.WriteEndElement(); } } public class PathArc { protected ArcKind kind; protected int poly1Index; protected int poly2Index; protected PathEdge edge; public PathArc(ArcKind kind, int poly1Index, int poly2Index, PathEdge edge) { this.kind = kind; this.poly1Index = poly1Index; this.poly2Index = poly2Index; this.edge = edge; } public PathArc(XmlReader r) { FromXml(r); } public static String ArcKindToString(ArcKind kind) { switch (kind) { case ArcKind.Illegal: return "Illegal"; case ArcKind.CVToCV: return "CVToCV"; case ArcKind.TerrainToTerrain: return "TerrainToTerrain"; case ArcKind.CVToTerrain: return "CVToTerrain"; default: return "Unknown ArcKind " + (int)kind; } } public static ArcKind ArcKindFromString(String s) { switch (s) { case "Illegal": return ArcKind.Illegal; case "CVToCV": return ArcKind.CVToCV; case "TerrainToTerrain": return ArcKind.TerrainToTerrain; case "CVToTerrain": return ArcKind.CVToTerrain; default: return ArcKind.Illegal; } } public ArcKind Kind { get { return kind; } } public int Poly1Index { get { return poly1Index; } } public int Poly2Index { get { return poly2Index; } } public PathEdge Edge { get { return edge; } } public void FromXml(XmlReader r) { while (r.Read()) { if (r.NodeType == XmlNodeType.Whitespace) { continue; } for (int i = 0; i < r.AttributeCount; i++) { r.MoveToAttribute(i); // set the field in this object based on the element we just read switch (r.Name) { case "kind": kind = ArcKindFromString(r.Value); break; case "poly1Index": poly1Index = int.Parse(r.Value); break; case "poly2Index": poly2Index = int.Parse(r.Value); break; } } r.MoveToElement(); //Moves the reader back to the element node. // look for the start of an element if (r.NodeType == XmlNodeType.Element) { // parse that element // save the name of the element string elementName = r.Name; switch (elementName) { case "PathEdge": edge = new PathEdge(r); break; } } else if (r.NodeType == XmlNodeType.EndElement) { break; } } } public void ToXml(XmlWriter w) { w.WriteStartElement("PathArc"); w.WriteAttributeString("kind", ArcKindToString(kind)); w.WriteAttributeString("poly1Index", poly1Index.ToString()); w.WriteAttributeString("poly2Index", poly2Index.ToString()); edge.ToXml(w); w.WriteEndElement(); } } class XmlHelperClass { public static Vector3 ParseVectorAttributes(XmlReader r) { float x = 0; float y = 0; float z = 0; for (int i = 0; i < r.AttributeCount; i++) { r.MoveToAttribute(i); // set the field in this object based on the element we just read switch (r.Name) { case "x": x = float.Parse(r.Value); break; case "y": y = float.Parse(r.Value); break; case "z": z = float.Parse(r.Value); break; } } r.MoveToElement(); //Moves the reader back to the element node. return new Vector3(x, y, z); } public static void WriteVectorElement(XmlWriter w, string elementName, Vector3 v) { w.WriteStartElement(elementName); w.WriteAttributeString("x", v.x.ToString()); w.WriteAttributeString("y", v.y.ToString()); w.WriteAttributeString("z", v.z.ToString()); w.WriteEndElement(); } } }
//------------------------------------------------------------------------------ // <copyright file="MetabaseServerConfig.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.Configuration { using System.Configuration; using System.Collections; using System.Globalization; using System.Text; using System.IO; using System.Web.Util; using System.Web.Hosting; using System.Web.Caching; using Microsoft.Win32; class MetabaseServerConfig : IServerConfig, IConfigMapPath, IConfigMapPath2 { private const string DEFAULT_SITEID = "1"; private const string DEFAULT_ROOTAPPID = "/LM/W3SVC/1/ROOT"; private const int MAX_PATH=260; private const int BUFSIZE = MAX_PATH + 1; private const string LMW3SVC_PREFIX = "/LM/W3SVC/"; private const string ROOT_SUFFIX="/ROOT"; static private MetabaseServerConfig s_instance; static private object s_initLock = new Object(); string _defaultSiteName; string _siteIdForCurrentApplication; static internal IServerConfig GetInstance() { if (s_instance == null) { lock (s_initLock) { if (s_instance == null) { s_instance = new MetabaseServerConfig(); } } } return s_instance; } private MetabaseServerConfig() { HttpRuntime.ForceStaticInit(); // force webengine.dll to load // Get the default site information bool found = MBGetSiteNameFromSiteID(DEFAULT_SITEID, out _defaultSiteName); _siteIdForCurrentApplication = HostingEnvironment.SiteID; if (_siteIdForCurrentApplication == null) { _siteIdForCurrentApplication = DEFAULT_SITEID; } } string IServerConfig.GetSiteNameFromSiteID(string siteID) { if (StringUtil.EqualsIgnoreCase(siteID, DEFAULT_SITEID)) return _defaultSiteName; string siteName; bool found = MBGetSiteNameFromSiteID(siteID, out siteName); return siteName; } // if appHost is null, we use the site ID for the current application string IServerConfig.MapPath(IApplicationHost appHost, VirtualPath path) { string siteID = (appHost == null) ? _siteIdForCurrentApplication : appHost.GetSiteID(); return MapPathCaching(siteID, path); } string[] IServerConfig.GetVirtualSubdirs(VirtualPath path, bool inApp) { string aboPath = GetAboPath(_siteIdForCurrentApplication, path.VirtualPathString); return MBGetVirtualSubdirs(aboPath, inApp); } bool IServerConfig.GetUncUser(IApplicationHost appHost, VirtualPath path, out string username, out string password) { string aboPath = GetAboPath(appHost.GetSiteID(), path.VirtualPathString); return MBGetUncUser(aboPath, out username, out password); } long IServerConfig.GetW3WPMemoryLimitInKB() { return (long) MBGetW3WPMemoryLimitInKB(); } string IConfigMapPath.GetMachineConfigFilename() { return HttpConfigurationSystem.MachineConfigurationFilePath; } string IConfigMapPath.GetRootWebConfigFilename() { return HttpConfigurationSystem.RootWebConfigurationFilePath; } private void GetPathConfigFilenameWorker(string siteID, VirtualPath path, out string directory, out string baseName) { directory = MapPathCaching(siteID, path); if (directory != null) { baseName = HttpConfigurationSystem.WebConfigFileName; } else { baseName = null; } } // Based on <siteID, path>, return: // directory - the physical directory of the path (vpath) // baseName - name of the configuration file to look for. // E.g. if siteID="1" and path="/", directory="c:\inetpub\wwwroot" and baseName="web.config" void IConfigMapPath.GetPathConfigFilename( string siteID, string path, out string directory, out string baseName) { GetPathConfigFilenameWorker(siteID, VirtualPath.Create(path), out directory, out baseName); } void IConfigMapPath2.GetPathConfigFilename( string siteID, VirtualPath path, out string directory, out string baseName) { GetPathConfigFilenameWorker(siteID, path, out directory, out baseName); } void IConfigMapPath.GetDefaultSiteNameAndID(out string siteName, out string siteID) { siteName = _defaultSiteName; siteID = DEFAULT_SITEID; } void IConfigMapPath.ResolveSiteArgument(string siteArgument, out string siteName, out string siteID) { if ( String.IsNullOrEmpty(siteArgument) || StringUtil.EqualsIgnoreCase(siteArgument, DEFAULT_SITEID) || StringUtil.EqualsIgnoreCase(siteArgument, _defaultSiteName)) { siteName = _defaultSiteName; siteID = DEFAULT_SITEID; } else { siteName = String.Empty; siteID = String.Empty; bool found = false; if (IISMapPath.IsSiteId(siteArgument)) { found = MBGetSiteNameFromSiteID(siteArgument, out siteName); } if (found) { siteID = siteArgument; } else { found = MBGetSiteIDFromSiteName(siteArgument, out siteID); if (found) { siteName = siteArgument; } else { siteName = siteArgument; siteID = String.Empty; } } } } // Map from <siteID, path> to a physical file path string IConfigMapPath.MapPath(string siteID, string vpath) { return MapPathCaching(siteID, VirtualPath.Create(vpath)); } // IConfigMapPath2 VirtualPath fast path string IConfigMapPath2.MapPath(string siteID, VirtualPath vpath) { return MapPathCaching(siteID, vpath); } VirtualPath GetAppPathForPathWorker(string siteID, VirtualPath vpath) { string aboPath = GetAboPath(siteID, vpath.VirtualPathString); string appAboPath = MBGetAppPath(aboPath); if (appAboPath == null) return VirtualPath.RootVirtualPath; string rootAboPath = GetRootAppIDFromSiteID(siteID); if (StringUtil.EqualsIgnoreCase(rootAboPath, appAboPath)) { return VirtualPath.RootVirtualPath; } string appPath = appAboPath.Substring(rootAboPath.Length); return VirtualPath.CreateAbsolute(appPath); } string IConfigMapPath.GetAppPathForPath(string siteID, string vpath) { VirtualPath resolved = GetAppPathForPathWorker(siteID, VirtualPath.Create(vpath)); return resolved.VirtualPathString; } // IConfigMapPath2 VirtualPath fast path VirtualPath IConfigMapPath2.GetAppPathForPath(string siteID, VirtualPath vpath) { return GetAppPathForPathWorker(siteID, vpath); } private string MatchResult(VirtualPath path, string result) { if (string.IsNullOrEmpty(result)) { return result; } result = result.Replace('/', '\\'); // ensure extra '\\' in the physical path if the virtual path had extra '/' // and the other way -- no extra '\\' in physical if virtual didn't have it. if (path.HasTrailingSlash) { if (!UrlPath.PathEndsWithExtraSlash(result) && !UrlPath.PathIsDriveRoot(result)) { result = result + "\\"; } } else { if (UrlPath.PathEndsWithExtraSlash(result) && !UrlPath.PathIsDriveRoot(result)) { result = result.Substring(0, result.Length - 1); } } return result; } private string MapPathCaching(string siteID, VirtualPath path) { // UrlMetaDataSlidingExpiration config setting controls // the duration of all cached items related to url metadata. bool doNotCache = CachedPathData.DoNotCacheUrlMetadata; TimeSpan slidingExpiration = CachedPathData.UrlMetadataSlidingExpiration; // store a single variation of the path VirtualPath originalPath = path; MapPathCacheInfo cacheInfo; if (doNotCache) { cacheInfo = new MapPathCacheInfo(); } else { // Check if it's in the cache String cacheKey = CacheInternal.PrefixMapPath + siteID + path.VirtualPathString; cacheInfo = (MapPathCacheInfo)HttpRuntime.CacheInternal.Get(cacheKey); // If not in cache, add it to the cache if (cacheInfo == null) { cacheInfo = new MapPathCacheInfo(); // Add to the cache. // No need to have a lock here. UtcAdd will add the entry if it doesn't exist. // If it does exist, the existing value will be returned (Dev10 Bug 755034). object existingEntry = HttpRuntime.CacheInternal.UtcAdd( cacheKey, cacheInfo, null, Cache.NoAbsoluteExpiration, slidingExpiration, CacheItemPriority.Default, null); if (existingEntry != null) { cacheInfo = existingEntry as MapPathCacheInfo; } } } // If not been evaluated, then evaluate it if (!cacheInfo.Evaluated) { lock(cacheInfo) { if (!cacheInfo.Evaluated && HttpRuntime.IsMapPathRelaxed) { ////////////////////////////////////////////////////////////////// // Verify that the parent path is valid. If parent is invalid, then set this to invalid if (path.VirtualPathString.Length > 1) { VirtualPath vParent = path.Parent; if (vParent != null) { string parentPath = vParent.VirtualPathString; if (parentPath.Length > 1 && StringUtil.StringEndsWith(parentPath, '/')) { // Trim the extra trailing / if there is one vParent = VirtualPath.Create(parentPath.Substring(0, parentPath.Length - 1)); } try { string parentMapPathResult = MapPathCaching(siteID, vParent); if (parentMapPathResult == HttpRuntime.GetRelaxedMapPathResult(null)) { // parent is invalid! cacheInfo.MapPathResult = parentMapPathResult; cacheInfo.Evaluated = true; } } catch { cacheInfo.MapPathResult = HttpRuntime.GetRelaxedMapPathResult(null); cacheInfo.Evaluated = true; } } } } if (!cacheInfo.Evaluated) { string physicalPath = null; try { physicalPath = MapPathActual(siteID, path); if (HttpRuntime.IsMapPathRelaxed) { physicalPath = HttpRuntime.GetRelaxedMapPathResult(physicalPath); } // Throw if the resulting physical path is not canonical, to prevent potential // security issues (VSWhidbey 418125) if (FileUtil.IsSuspiciousPhysicalPath(physicalPath)) { if (HttpRuntime.IsMapPathRelaxed) { physicalPath = HttpRuntime.GetRelaxedMapPathResult(null); } else { throw new HttpException(SR.GetString(SR.Cannot_map_path, path)); } } } catch (Exception e) { if (HttpRuntime.IsMapPathRelaxed) { physicalPath = HttpRuntime.GetRelaxedMapPathResult(null); } else { cacheInfo.CachedException = e; cacheInfo.Evaluated=true; throw; } } if ( physicalPath != null ) { // Only cache if we got a good value cacheInfo.MapPathResult = physicalPath; cacheInfo.Evaluated = true; } } } } // Throw an exception if required if (cacheInfo.CachedException != null) { throw cacheInfo.CachedException; } return MatchResult(originalPath, cacheInfo.MapPathResult); } private string MapPathActual(string siteID, VirtualPath path) { string appID = GetRootAppIDFromSiteID(siteID); string physicalPath = MBMapPath(appID, path.VirtualPathString); return physicalPath; } private string GetRootAppIDFromSiteID(string siteId) { return LMW3SVC_PREFIX + siteId + ROOT_SUFFIX; } private string GetAboPath(string siteID, string path) { string rootAppID = GetRootAppIDFromSiteID(siteID); string aboPath = rootAppID + FixupPathSlash(path); return aboPath; } private string FixupPathSlash(string path) { if (path == null) { return null; } int l = path.Length; if (l == 0 || path[l-1] != '/') { return path; } return path.Substring(0, l-1); } // // Metabase access functions // private bool MBGetSiteNameFromSiteID(string siteID, out string siteName) { string appID = GetRootAppIDFromSiteID(siteID); StringBuilder sb = new StringBuilder(BUFSIZE); int r = UnsafeNativeMethods.IsapiAppHostGetSiteName(appID, sb, sb.Capacity); if (r == 1) { siteName = sb.ToString(); return true; } else { siteName = String.Empty; return false; } } private bool MBGetSiteIDFromSiteName(string siteName, out string siteID) { StringBuilder sb = new StringBuilder(BUFSIZE); int r = UnsafeNativeMethods.IsapiAppHostGetSiteId(siteName, sb, sb.Capacity); if (r == 1) { siteID = sb.ToString(); return true; } else { siteID = String.Empty; return false; } } private string MBMapPath(string appID, string path) { // keep growing the buffer to support paths longer than MAX_PATH int bufSize = BUFSIZE; StringBuilder sb; int r; for (;;) { sb = new StringBuilder(bufSize); r = UnsafeNativeMethods.IsapiAppHostMapPath(appID, path, sb, sb.Capacity); Debug.Trace("MapPath", "IsapiAppHostMapPath(" + path + ") returns " + r); if (r == -2) { // insufficient buffer bufSize *= 2; } else { break; } } if (r == -1) { // special case access denied error throw new HostingEnvironmentException( SR.GetString(SR.Cannot_access_mappath_title), SR.GetString(SR.Cannot_access_mappath_details)); } string physicalPath; if (r == 1) { physicalPath = sb.ToString(); } else { physicalPath = null; } return physicalPath; } private string[] MBGetVirtualSubdirs(string aboPath, bool inApp) { StringBuilder sb = new StringBuilder(BUFSIZE); int index = 0; ArrayList list = new ArrayList(); for (;;) { sb.Length = 0; int r = UnsafeNativeMethods.IsapiAppHostGetNextVirtualSubdir(aboPath, inApp, ref index, sb, sb.Capacity); if (r == 0) break; string subdir = sb.ToString(); list.Add(subdir); } string[] subdirs = new string[list.Count]; list.CopyTo(subdirs); return subdirs; } private bool MBGetUncUser(string aboPath, out string username, out string password) { StringBuilder usr = new StringBuilder(BUFSIZE); StringBuilder pwd = new StringBuilder(BUFSIZE); int r = UnsafeNativeMethods.IsapiAppHostGetUncUser(aboPath, usr, usr.Capacity, pwd, pwd.Capacity); if (r == 1) { username = usr.ToString(); password = pwd.ToString(); return true; } else { username = null; password = null; return false; } } private int MBGetW3WPMemoryLimitInKB() { return UnsafeNativeMethods.GetW3WPMemoryLimitInKB(); } private string MBGetAppPath(string aboPath) { StringBuilder buf = new StringBuilder(aboPath.Length + 1); int r = UnsafeNativeMethods.IsapiAppHostGetAppPath(aboPath, buf, buf.Capacity); string appAboPath; if (r == 1) { appAboPath = buf.ToString(); } else { appAboPath = null; } return appAboPath; } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics; #if CCINamespace using Microsoft.Cci.Metadata; #else using System.Compiler.Metadata; #endif using System.Globalization; using System.Text; using System.Diagnostics.Contracts; #if CCINamespace namespace Microsoft.Cci{ #else namespace System.Compiler{ #endif #if !(FxCop || NoWriter) /// <summary> /// High performance replacement for System.IO.BinaryWriter. /// </summary> public sealed class BinaryWriter{ public MemoryStream/*!*/ BaseStream; private bool UTF8 = true; public BinaryWriter(MemoryStream/*!*/ output) { this.BaseStream = output; //^ base(); } public BinaryWriter(MemoryStream output, bool unicode) { this.BaseStream = output; this.UTF8 = !unicode; } public BinaryWriter(MemoryStream/*!*/ output, Encoding/*!*/ encoding) { Debug.Assert(encoding == Encoding.Unicode); this.BaseStream = output; this.UTF8 = false; //^ base(); } public void Align(uint alignment) { MemoryStream m = this.BaseStream; int i = m.Position; while (i % alignment > 0) { m.Buffer[i++] = 0; m.Position = i; } } public void Write(bool value){ MemoryStream m = this.BaseStream; int i = m.Position; m.Position = i+1; m.Buffer[i] = (byte)(value ? 1 : 0); } public void Write(byte value){ MemoryStream m = this.BaseStream; int i = m.Position; m.Position = i+1; m.Buffer[i] = value; } public void Write(sbyte value){ MemoryStream m = this.BaseStream; int i = m.Position; m.Position = i+1; m.Buffer[i] = (byte)value; } public void Write(byte[] buffer){ if (buffer == null) return; this.BaseStream.Write(buffer, 0, buffer.Length); } public void Write(char ch){ MemoryStream m = this.BaseStream; int i = m.Position; if (this.UTF8){ if (ch < 0x80){ m.Position = i+1; m.Buffer[i] = (byte)ch; }else this.Write(new char[]{ch}); }else{ m.Position = i+2; byte[] buffer = m.Buffer; buffer[i++] = (byte)ch; buffer[i] = (byte)(ch >> 8); } } public void Write(char[] chars){ if (chars == null) return; MemoryStream m = this.BaseStream; int n = chars.Length; int i = m.Position; if (this.UTF8){ m.Position = i+n; byte[] buffer = m.Buffer; for (int j = 0; j < n; j++){ char ch = chars[j]; if ((ch & 0x80) != 0) goto writeUTF8; buffer[i++] = (byte)ch; } return; writeUTF8: int ch32 = 0; for (int j = n-(m.Position-i); j < n; j++){ char ch = chars[j]; if (ch < 0x80){ m.Position = i+1; buffer = m.Buffer; buffer[i++] = (byte)ch; }else if (ch < 0x800){ m.Position = i+2; buffer = m.Buffer; buffer[i++] = (byte)(((ch>>6) & 0x1F) | 0xC0); buffer[i] = (byte)((ch & 0x3F) | 0x80); }else if (0xD800 <= ch && ch <= 0xDBFF){ ch32 = (ch & 0x3FF) << 10; }else if (0xDC00 <= ch && ch <= 0xDFFF){ ch32 |= ch & 0x3FF; m.Position = i+4; buffer = m.Buffer; buffer[i++] = (byte)(((ch32>>18) & 0x7) | 0xF0); buffer[i++] = (byte)(((ch32>>12) & 0x3F) | 0x80); buffer[i++] = (byte)(((ch32>>6) & 0x3F) | 0x80); buffer[i] = (byte)((ch32 & 0x3F) | 0x80); }else{ m.Position = i+3; buffer = m.Buffer; buffer[i++] = (byte)(((ch>>12) & 0xF) | 0xE0); buffer[i++] = (byte)(((ch>>6) & 0x3F) | 0x80); buffer[i] = (byte)((ch & 0x3F) | 0x80); } } }else{ m.Position = i+n*2; byte[] buffer = m.Buffer; for (int j = 0; j < n; j++){ char ch = chars[j]; buffer[i++] = (byte)ch; buffer[i++] = (byte)(ch >> 8); } } } public unsafe void Write(double value){ MemoryStream m = this.BaseStream; int i = m.Position; m.Position=i+8; fixed(byte* b = m.Buffer) *((double*)(b+i)) = value; } public void Write(short value){ MemoryStream m = this.BaseStream; int i = m.Position; m.Position=i+2; byte[] buffer = m.Buffer; buffer[i++] = (byte)value; buffer[i] = (byte)(value >> 8); } public unsafe void Write(ushort value){ MemoryStream m = this.BaseStream; int i = m.Position; m.Position=i+2; byte[] buffer = m.Buffer; buffer[i++] = (byte)value; buffer[i] = (byte)(value >> 8); } public void Write(int value){ MemoryStream m = this.BaseStream; int i = m.Position; m.Position=i+4; byte[] buffer = m.Buffer; buffer[i++] = (byte)value; buffer[i++] = (byte)(value >> 8); buffer[i++] = (byte)(value >> 16); buffer[i] = (byte)(value >> 24); } public void Write(uint value){ MemoryStream m = this.BaseStream; int i = m.Position; m.Position=i+4; byte[] buffer = m.Buffer; buffer[i++] = (byte)value; buffer[i++] = (byte)(value >> 8); buffer[i++] = (byte)(value >> 16); buffer[i] = (byte)(value >> 24); } public void Write(long value){ MemoryStream m = this.BaseStream; int i = m.Position; m.Position=i+8; byte[] buffer = m.Buffer; uint lo = (uint)value; uint hi = (uint)(value >> 32); buffer[i++] = (byte)lo; buffer[i++] = (byte)(lo >> 8); buffer[i++] = (byte)(lo >> 16); buffer[i++] = (byte)(lo >> 24); buffer[i++] = (byte)hi; buffer[i++] = (byte)(hi >> 8); buffer[i++] = (byte)(hi >> 16); buffer[i] = (byte)(hi >> 24); } public unsafe void Write(ulong value){ MemoryStream m = this.BaseStream; int i = m.Position; m.Position=i+8; byte[] buffer = m.Buffer; uint lo = (uint)value; uint hi = (uint)(value >> 32); buffer[i++] = (byte)lo; buffer[i++] = (byte)(lo >> 8); buffer[i++] = (byte)(lo >> 16); buffer[i++] = (byte)(lo >> 24); buffer[i++] = (byte)hi; buffer[i++] = (byte)(hi >> 8); buffer[i++] = (byte)(hi >> 16); buffer[i] = (byte)(hi >> 24); } public unsafe void Write(float value){ MemoryStream m = this.BaseStream; int i = m.Position; m.Position=i+4; fixed(byte* b = m.Buffer) *((float*)(b+i)) = value; } public void Write(string str){ this.Write(str, false); } public void Write(string str, bool emitNullTerminator){ if (str == null){ Debug.Assert(!emitNullTerminator); this.Write((byte)0xff); return; } int n = str.Length; if (!emitNullTerminator){ if (this.UTF8) Ir2md.WriteCompressedInt(this, GetUTF8ByteCount(str)); else Ir2md.WriteCompressedInt(this, n*2); } MemoryStream m = this.BaseStream; int i = m.Position; if (this.UTF8){ m.Position = i+n; byte[] buffer = m.Buffer; for (int j = 0; j < n; j++){ char ch = str[j]; if (ch >= 0x80) goto writeUTF8; buffer[i++] = (byte)ch; } if (emitNullTerminator){ m.Position = i+1; buffer = m.Buffer; buffer[i] = 0; } return; writeUTF8: int ch32 = 0; for (int j = n-(m.Position-i); j < n; j++){ char ch = str[j]; if (ch < 0x80){ m.Position = i+1; buffer = m.Buffer; buffer[i++] = (byte)ch; }else if (ch < 0x800){ m.Position = i+2; buffer = m.Buffer; buffer[i++] = (byte)(((ch>>6) & 0x1F) | 0xC0); buffer[i++] = (byte)((ch & 0x3F) | 0x80); }else if (0xD800 <= ch && ch <= 0xDBFF){ ch32 = (ch & 0x3FF) << 10; }else if (0xDC00 <= ch && ch <= 0xDFFF){ ch32 |= ch & 0x3FF; m.Position = i+4; buffer = m.Buffer; buffer[i++] = (byte)(((ch32>>18) & 0x7) | 0xF0); buffer[i++] = (byte)(((ch32>>12) & 0x3F) | 0x80); buffer[i++] = (byte)(((ch32>>6) & 0x3F) | 0x80); buffer[i++] = (byte)((ch32 & 0x3F) | 0x80); }else{ m.Position = i+3; buffer = m.Buffer; buffer[i++] = (byte)(((ch>>12) & 0xF) | 0xE0); buffer[i++] = (byte)(((ch>>6) & 0x3F) | 0x80); buffer[i++] = (byte)((ch & 0x3F) | 0x80); } } if (emitNullTerminator){ m.Position = i+1; buffer = m.Buffer; buffer[i] = 0; } }else{ m.Position = i+n*2; byte[] buffer = m.Buffer; for (int j = 0; j < n; j++){ char ch = str[j]; buffer[i++] = (byte)ch; buffer[i++] = (byte)(ch >> 8); } if (emitNullTerminator){ m.Position = i+2; buffer = m.Buffer; buffer[i++] = 0; buffer[i] = 0; } } } public static int GetUTF8ByteCount(string str){ int count = 0; for (int i = 0, n = str == null ? 0 : str.Length; i < n; i++){ //^ assume str != null; char ch = str[i]; if (ch < 0x80){ count += 1; }else if (ch < 0x800){ count += 2; }else if (0xD800 <= ch && ch <= 0xDBFF){ count += 2; }else if (0xDC00 <= ch && ch <= 0xDFFF){ count += 2; }else{ count += 3; } } return count; } } public sealed class MemoryStream{ public byte[]/* ! */ Buffer; public int Length; public int position; public int Position{ get{return this.position;} set{ byte[] myBuffer = this.Buffer; int n = myBuffer.Length; if (value >= n) this.Grow(myBuffer, n, value); if (value > this.Length) this.Length = value; this.position = value; } } public MemoryStream() : this(64) { } public MemoryStream(int capacity){ this.Buffer = new byte[capacity]; this.Length = 0; this.position = 0; //^ base(); } public MemoryStream(byte[]/*!*/ bytes){ if (bytes == null) { Debug.Fail(""); } this.Buffer = bytes; this.Length = bytes.Length; this.position = 0; //^ base(); } private void Grow(byte[]/*!*/ myBuffer, int n, int m) { if (myBuffer == null) { Debug.Fail(""); return; } int n2 = n*2; while (m >= n2) n2 = n2*2; byte[] newBuffer = this.Buffer = new byte[n2]; for (int i = 0; i < n; i++) newBuffer[i] = myBuffer[i]; //TODO: optimize this } public void Seek(long offset, SeekOrigin loc){ Contract.Assume(loc == SeekOrigin.Begin); Contract.Assume(offset <= int.MaxValue); this.Position = (int)offset; } public byte[]/*!*/ ToArray() { int n = this.Length; byte[] source = this.Buffer; if (source.Length == n) return this.Buffer; //unlikely, but the check is cheap byte[] result = new byte[n]; for (int i = 0; i < n; i++) result[i] = source[i]; //TODO: optimize this return result; } public void Write(byte[]/*!*/ buffer, int index, int count) { int p = this.position; this.Position = p + count; byte[] myBuffer = this.Buffer; for (int i = 0, j = p, k = index; i < count; i++) myBuffer[j++] = buffer[k++]; //TODO: optimize this } public void WriteTo(MemoryStream/*!*/ stream) { stream.Write(this.Buffer, 0, this.Length); } public void WriteTo(System.IO.Stream/*!*/ stream) { stream.Write(this.Buffer, 0, this.Length); } } public enum SeekOrigin{Begin, Current, End} #endif /// <summary> /// A version of System.IO.Path that does not throw exceptions. /// </summary> #if FxCop || NoWriter internal sealed class BetterPath { #else public sealed class BetterPath { #endif public static readonly char AltDirectorySeparatorChar = System.IO.Path.AltDirectorySeparatorChar; public static readonly char DirectorySeparatorChar = System.IO.Path.DirectorySeparatorChar; public static readonly char VolumeSeparatorChar = System.IO.Path.VolumeSeparatorChar; public static string ChangeExtension(string path, string extension) { if (path == null) return null; string text1 = path; int num1 = path.Length; while (--num1 >= 0) { char ch1 = path[num1]; if (ch1 == '.') { text1 = path.Substring(0, num1); break; } if (((ch1 == BetterPath.DirectorySeparatorChar) || (ch1 == BetterPath.AltDirectorySeparatorChar)) || (ch1 == BetterPath.VolumeSeparatorChar)) break; } if (extension == null || path.Length == 0) return text1; if (extension.Length == 0 || extension[0] != '.') text1 = text1 + "."; return text1 + extension; } public static string Combine(string path1, string path2) { if (path1 == null || path1.Length == 0) return path2; if (path2 == null || path2.Length == 0) return path1; char ch = path2[0]; if (ch == BetterPath.DirectorySeparatorChar || ch == BetterPath.AltDirectorySeparatorChar || (path2.Length >= 2 && path2[1] == BetterPath.VolumeSeparatorChar)) return path2; ch = path1[path1.Length - 1]; if (ch != BetterPath.DirectorySeparatorChar && ch != BetterPath.AltDirectorySeparatorChar && ch != BetterPath.VolumeSeparatorChar) return (path1 + BetterPath.DirectorySeparatorChar + path2); return path1 + path2; } public static string GetExtension(string path) { if (path == null) return null; int length = path.Length; for (int i = length; --i >= 0; ) { char ch = path[i]; if (ch == '.') { if (i != length - 1) return path.Substring(i, length - i); else return String.Empty; } if (ch == BetterPath.DirectorySeparatorChar || ch == BetterPath.AltDirectorySeparatorChar || ch == BetterPath.VolumeSeparatorChar) break; } return string.Empty; } public static String GetFileName(string path) { if (path == null) return null; int length = path.Length; for (int i = length; --i >= 0; ) { char ch = path[i]; if (ch == BetterPath.DirectorySeparatorChar || ch == BetterPath.AltDirectorySeparatorChar || ch == BetterPath.VolumeSeparatorChar) return path.Substring(i+1); } return path; } public static string GetFileNameWithoutExtension(string path) { int num1; path = BetterPath.GetFileName(path); if (path == null) return null; if ((num1 = path.LastIndexOf('.')) == -1) return path; return path.Substring(0, num1); } public static String GetDirectoryName(string path) { if (path == null) return null; int length = path.Length; for (int i = length; --i >= 0; ) { char ch = path[i]; if (ch == BetterPath.DirectorySeparatorChar || ch == BetterPath.AltDirectorySeparatorChar || ch == BetterPath.VolumeSeparatorChar) return path.Substring(0, i); } return path; } public static char[] GetInvalidFileNameChars() { #if WHIDBEY return System.IO.Path.GetInvalidFileNameChars(); #else return System.IO.Path.InvalidPathChars; #endif } public static char[] GetInvalidPathChars() { #if WHIDBEY return System.IO.Path.GetInvalidPathChars(); #else return System.IO.Path.InvalidPathChars; #endif } public static string GetTempFileName() { return System.IO.Path.GetTempFileName(); } public static bool HasExtension(string path) { if (path != null) { int num1 = path.Length; while (--num1 >= 0) { char ch1 = path[num1]; if (ch1 == '.') { if (num1 != (path.Length - 1)) { return true; } return false; } if (((ch1 == BetterPath.DirectorySeparatorChar) || (ch1 == BetterPath.AltDirectorySeparatorChar)) || (ch1 == BetterPath.VolumeSeparatorChar)) { break; } } } return false; } } }
namespace PICkit2V2 { partial class DialogPK2Go { /// <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 Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(DialogPK2Go)); this.panelIntro = new System.Windows.Forms.Panel(); this.label8 = new System.Windows.Forms.Label(); this.label15 = new System.Windows.Forms.Label(); this.label16 = new System.Windows.Forms.Label(); this.buttonBack = new System.Windows.Forms.Button(); this.buttonNext = new System.Windows.Forms.Button(); this.buttonCancel = new System.Windows.Forms.Button(); this.buttonHelp = new System.Windows.Forms.Button(); this.panelSettings = new System.Windows.Forms.Panel(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.label14 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.labelVerify = new System.Windows.Forms.Label(); this.labelMemRegions = new System.Windows.Forms.Label(); this.label11 = new System.Windows.Forms.Label(); this.labelDataProtect = new System.Windows.Forms.Label(); this.label9 = new System.Windows.Forms.Label(); this.labelCodeProtect = new System.Windows.Forms.Label(); this.label10 = new System.Windows.Forms.Label(); this.labelOSCCAL_BandGap = new System.Windows.Forms.Label(); this.labelDataSource = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.labelPartNumber = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.label2 = new System.Windows.Forms.Label(); this.labelRowErase = new System.Windows.Forms.Label(); this.checkBoxRowErase = new System.Windows.Forms.CheckBox(); this.radioButtonPK2Power = new System.Windows.Forms.RadioButton(); this.radioButtonSelfPower = new System.Windows.Forms.RadioButton(); this.label1 = new System.Windows.Forms.Label(); this.panelDownload = new System.Windows.Forms.Panel(); this.label7 = new System.Windows.Forms.Label(); this.groupBox3 = new System.Windows.Forms.GroupBox(); this.labelSourceSmmry = new System.Windows.Forms.Label(); this.labelTargetPowerSmmry = new System.Windows.Forms.Label(); this.label12 = new System.Windows.Forms.Label(); this.labelVDDMin = new System.Windows.Forms.Label(); this.labelPNsmmry = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.labelMemRegionsSmmry = new System.Windows.Forms.Label(); this.labelVPP1stSmmry = new System.Windows.Forms.Label(); this.labelVerifySmmry = new System.Windows.Forms.Label(); this.labelFastProgSmmry = new System.Windows.Forms.Label(); this.labelMCLRHoldSmmry = new System.Windows.Forms.Label(); this.panelDownloading = new System.Windows.Forms.Panel(); this.labelDOWNLOADING = new System.Windows.Forms.Label(); this.panelDownloadDone = new System.Windows.Forms.Panel(); this.label13 = new System.Windows.Forms.Label(); this.label17 = new System.Windows.Forms.Label(); this.timerBlink = new System.Windows.Forms.Timer(this.components); this.pictureBoxTarget = new System.Windows.Forms.PictureBox(); this.label18 = new System.Windows.Forms.Label(); this.label19 = new System.Windows.Forms.Label(); this.label20 = new System.Windows.Forms.Label(); this.panelErrors = new System.Windows.Forms.Panel(); this.label21 = new System.Windows.Forms.Label(); this.label22 = new System.Windows.Forms.Label(); this.pictureBoxBusy = new System.Windows.Forms.PictureBox(); this.label23 = new System.Windows.Forms.Label(); this.label24 = new System.Windows.Forms.Label(); this.radioButtonVErr = new System.Windows.Forms.RadioButton(); this.radioButton2Blinks = new System.Windows.Forms.RadioButton(); this.radioButton3Blinks = new System.Windows.Forms.RadioButton(); this.radioButton4Blinks = new System.Windows.Forms.RadioButton(); this.label25 = new System.Windows.Forms.Label(); this.label26 = new System.Windows.Forms.Label(); this.label27 = new System.Windows.Forms.Label(); this.label28 = new System.Windows.Forms.Label(); this.label29 = new System.Windows.Forms.Label(); this.label256K = new System.Windows.Forms.Label(); this.panelIntro.SuspendLayout(); this.panelSettings.SuspendLayout(); this.groupBox2.SuspendLayout(); this.groupBox1.SuspendLayout(); this.panelDownload.SuspendLayout(); this.groupBox3.SuspendLayout(); this.panelDownloading.SuspendLayout(); this.panelDownloadDone.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxTarget)).BeginInit(); this.panelErrors.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxBusy)).BeginInit(); this.SuspendLayout(); // // panelIntro // this.panelIntro.Controls.Add(this.label256K); this.panelIntro.Controls.Add(this.label8); this.panelIntro.Controls.Add(this.label15); this.panelIntro.Controls.Add(this.label16); this.panelIntro.Location = new System.Drawing.Point(12, 12); this.panelIntro.Name = "panelIntro"; this.panelIntro.Size = new System.Drawing.Size(351, 331); this.panelIntro.TabIndex = 0; // // label8 // this.label8.AutoSize = true; this.label8.Font = new System.Drawing.Font("Arial", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label8.Location = new System.Drawing.Point(69, 31); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(213, 19); this.label8.TabIndex = 5; this.label8.Text = "Programmer-To-Go Wizard"; // // label15 // this.label15.AutoSize = true; this.label15.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label15.Location = new System.Drawing.Point(29, 90); this.label15.Name = "label15"; this.label15.Size = new System.Drawing.Size(290, 195); this.label15.TabIndex = 4; this.label15.Text = resources.GetString("label15.Text"); // // label16 // this.label16.AutoSize = true; this.label16.Font = new System.Drawing.Font("Arial", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label16.Location = new System.Drawing.Point(81, 12); this.label16.Name = "label16"; this.label16.Size = new System.Drawing.Size(188, 19); this.label16.TabIndex = 2; this.label16.Text = "Welcome to the PICkit 2"; // // buttonBack // this.buttonBack.Enabled = false; this.buttonBack.Location = new System.Drawing.Point(102, 350); this.buttonBack.Name = "buttonBack"; this.buttonBack.Size = new System.Drawing.Size(82, 22); this.buttonBack.TabIndex = 7; this.buttonBack.Text = "< Back"; this.buttonBack.UseVisualStyleBackColor = true; this.buttonBack.Click += new System.EventHandler(this.buttonBack_Click); // // buttonNext // this.buttonNext.Location = new System.Drawing.Point(192, 350); this.buttonNext.Name = "buttonNext"; this.buttonNext.Size = new System.Drawing.Size(82, 22); this.buttonNext.TabIndex = 6; this.buttonNext.Text = "Next >"; this.buttonNext.UseVisualStyleBackColor = true; this.buttonNext.Click += new System.EventHandler(this.buttonNext_Click); // // buttonCancel // this.buttonCancel.Location = new System.Drawing.Point(282, 350); this.buttonCancel.Name = "buttonCancel"; this.buttonCancel.Size = new System.Drawing.Size(82, 22); this.buttonCancel.TabIndex = 5; this.buttonCancel.Text = "Cancel"; this.buttonCancel.UseVisualStyleBackColor = true; this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click); // // buttonHelp // this.buttonHelp.Location = new System.Drawing.Point(12, 350); this.buttonHelp.Name = "buttonHelp"; this.buttonHelp.Size = new System.Drawing.Size(82, 22); this.buttonHelp.TabIndex = 6; this.buttonHelp.Text = "Help"; this.buttonHelp.UseVisualStyleBackColor = true; this.buttonHelp.Click += new System.EventHandler(this.buttonHelp_Click); // // panelSettings // this.panelSettings.Controls.Add(this.groupBox2); this.panelSettings.Controls.Add(this.groupBox1); this.panelSettings.Controls.Add(this.label1); this.panelSettings.Location = new System.Drawing.Point(12, 12); this.panelSettings.Name = "panelSettings"; this.panelSettings.Size = new System.Drawing.Size(351, 331); this.panelSettings.TabIndex = 8; this.panelSettings.Visible = false; // // groupBox2 // this.groupBox2.Controls.Add(this.label14); this.groupBox2.Controls.Add(this.label4); this.groupBox2.Controls.Add(this.labelVerify); this.groupBox2.Controls.Add(this.labelMemRegions); this.groupBox2.Controls.Add(this.label11); this.groupBox2.Controls.Add(this.labelDataProtect); this.groupBox2.Controls.Add(this.label9); this.groupBox2.Controls.Add(this.labelCodeProtect); this.groupBox2.Controls.Add(this.label10); this.groupBox2.Controls.Add(this.labelOSCCAL_BandGap); this.groupBox2.Controls.Add(this.labelDataSource); this.groupBox2.Controls.Add(this.label5); this.groupBox2.Controls.Add(this.labelPartNumber); this.groupBox2.Controls.Add(this.label3); this.groupBox2.Font = new System.Drawing.Font("Arial", 9.75F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.groupBox2.Location = new System.Drawing.Point(12, 34); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(325, 154); this.groupBox2.TabIndex = 6; this.groupBox2.TabStop = false; this.groupBox2.Text = "Buffer Settings"; // // label14 // this.label14.AutoSize = true; this.label14.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label14.Location = new System.Drawing.Point(6, 109); this.label14.Name = "label14"; this.label14.Size = new System.Drawing.Size(79, 15); this.label14.TabIndex = 18; this.label14.Text = "Verify Device:"; // // label4 // this.label4.AutoSize = true; this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label4.Location = new System.Drawing.Point(59, 135); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(198, 13); this.label4.TabIndex = 9; this.label4.Text = "Click CANCEL to change buffer settings.\r\n"; // // labelVerify // this.labelVerify.AutoSize = true; this.labelVerify.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labelVerify.Location = new System.Drawing.Point(90, 109); this.labelVerify.Name = "labelVerify"; this.labelVerify.Size = new System.Drawing.Size(30, 15); this.labelVerify.TabIndex = 17; this.labelVerify.Text = "Yes"; // // labelMemRegions // this.labelMemRegions.AutoSize = true; this.labelMemRegions.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labelMemRegions.Location = new System.Drawing.Point(115, 94); this.labelMemRegions.Name = "labelMemRegions"; this.labelMemRegions.Size = new System.Drawing.Size(151, 15); this.labelMemRegions.TabIndex = 12; this.labelMemRegions.Text = "Program Entire Device"; // // label11 // this.label11.AutoSize = true; this.label11.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label11.Location = new System.Drawing.Point(5, 94); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(104, 15); this.label11.TabIndex = 15; this.label11.Text = "Memory Regions:"; // // labelDataProtect // this.labelDataProtect.AutoSize = true; this.labelDataProtect.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labelDataProtect.Location = new System.Drawing.Point(251, 79); this.labelDataProtect.Name = "labelDataProtect"; this.labelDataProtect.Size = new System.Drawing.Size(25, 15); this.labelDataProtect.TabIndex = 14; this.labelDataProtect.Text = "NA"; // // label9 // this.label9.AutoSize = true; this.label9.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label9.Location = new System.Drawing.Point(168, 79); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(77, 15); this.label9.TabIndex = 12; this.label9.Text = "Data Protect:"; // // labelCodeProtect // this.labelCodeProtect.AutoSize = true; this.labelCodeProtect.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labelCodeProtect.Location = new System.Drawing.Point(91, 79); this.labelCodeProtect.Name = "labelCodeProtect"; this.labelCodeProtect.Size = new System.Drawing.Size(27, 15); this.labelCodeProtect.TabIndex = 13; this.labelCodeProtect.Text = "ON"; // // label10 // this.label10.AutoSize = true; this.label10.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label10.Location = new System.Drawing.Point(5, 79); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(80, 15); this.label10.TabIndex = 11; this.label10.Text = "Code Protect:"; // // labelOSCCAL_BandGap // this.labelOSCCAL_BandGap.AutoSize = true; this.labelOSCCAL_BandGap.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labelOSCCAL_BandGap.Location = new System.Drawing.Point(59, 33); this.labelOSCCAL_BandGap.Name = "labelOSCCAL_BandGap"; this.labelOSCCAL_BandGap.Size = new System.Drawing.Size(177, 15); this.labelOSCCAL_BandGap.TabIndex = 10; this.labelOSCCAL_BandGap.Text = "OSCCAL will be preserved."; this.labelOSCCAL_BandGap.Visible = false; // // labelDataSource // this.labelDataSource.AutoSize = true; this.labelDataSource.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labelDataSource.Location = new System.Drawing.Point(32, 63); this.labelDataSource.Name = "labelDataSource"; this.labelDataSource.Size = new System.Drawing.Size(88, 13); this.labelDataSource.TabIndex = 8; this.labelDataSource.Text = "<DataSource>"; // // label5 // this.label5.AutoSize = true; this.label5.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label5.Location = new System.Drawing.Point(6, 48); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(109, 15); this.label5.TabIndex = 7; this.label5.Text = "Buffer data source:"; // // labelPartNumber // this.labelPartNumber.AutoSize = true; this.labelPartNumber.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labelPartNumber.Location = new System.Drawing.Point(59, 18); this.labelPartNumber.Name = "labelPartNumber"; this.labelPartNumber.Size = new System.Drawing.Size(100, 15); this.labelPartNumber.TabIndex = 6; this.labelPartNumber.Text = "<PartNumber>"; // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label3.Location = new System.Drawing.Point(6, 18); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(47, 15); this.label3.TabIndex = 5; this.label3.Text = "Device:"; // // groupBox1 // this.groupBox1.Controls.Add(this.labelVDDMin); this.groupBox1.Controls.Add(this.label2); this.groupBox1.Controls.Add(this.labelRowErase); this.groupBox1.Controls.Add(this.checkBoxRowErase); this.groupBox1.Controls.Add(this.radioButtonPK2Power); this.groupBox1.Controls.Add(this.radioButtonSelfPower); this.groupBox1.Font = new System.Drawing.Font("Arial", 9.75F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.groupBox1.Location = new System.Drawing.Point(12, 194); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(325, 137); this.groupBox1.TabIndex = 5; this.groupBox1.TabStop = false; this.groupBox1.Text = "Power Settings"; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.Location = new System.Drawing.Point(66, 107); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(191, 26); this.label2.TabIndex = 5; this.label2.Text = "To change PICkit 2 VDD voltage, click\r\n CANCEL and adjust the VDD box.\r\n"; // // labelRowErase // this.labelRowErase.AutoSize = true; this.labelRowErase.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labelRowErase.ForeColor = System.Drawing.Color.OrangeRed; this.labelRowErase.Location = new System.Drawing.Point(13, 89); this.labelRowErase.Name = "labelRowErase"; this.labelRowErase.Size = new System.Drawing.Size(281, 13); this.labelRowErase.TabIndex = 11; this.labelRowErase.Text = "Row Erase used: Will NOT program Code Protected parts!"; this.labelRowErase.Visible = false; // // checkBoxRowErase // this.checkBoxRowErase.AutoSize = true; this.checkBoxRowErase.Enabled = false; this.checkBoxRowErase.Font = new System.Drawing.Font("Arial", 9.75F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.checkBoxRowErase.Location = new System.Drawing.Point(48, 44); this.checkBoxRowErase.Name = "checkBoxRowErase"; this.checkBoxRowErase.Size = new System.Drawing.Size(176, 20); this.checkBoxRowErase.TabIndex = 2; this.checkBoxRowErase.Text = "Use low voltage row erase"; this.checkBoxRowErase.UseVisualStyleBackColor = true; this.checkBoxRowErase.CheckedChanged += new System.EventHandler(this.checkBoxRowErase_CheckedChanged); // // radioButtonPK2Power // this.radioButtonPK2Power.AutoSize = true; this.radioButtonPK2Power.Font = new System.Drawing.Font("Arial", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.radioButtonPK2Power.Location = new System.Drawing.Point(16, 66); this.radioButtonPK2Power.Name = "radioButtonPK2Power"; this.radioButtonPK2Power.Size = new System.Drawing.Size(249, 20); this.radioButtonPK2Power.TabIndex = 1; this.radioButtonPK2Power.TabStop = true; this.radioButtonPK2Power.Text = "Power target from PICkit 2 at 0.0 Volts"; this.radioButtonPK2Power.UseVisualStyleBackColor = true; this.radioButtonPK2Power.Click += new System.EventHandler(this.radioButtonPK2Power_Click); // // radioButtonSelfPower // this.radioButtonSelfPower.AutoSize = true; this.radioButtonSelfPower.Font = new System.Drawing.Font("Arial", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.radioButtonSelfPower.Location = new System.Drawing.Point(16, 21); this.radioButtonSelfPower.Name = "radioButtonSelfPower"; this.radioButtonSelfPower.Size = new System.Drawing.Size(216, 20); this.radioButtonSelfPower.TabIndex = 0; this.radioButtonSelfPower.TabStop = true; this.radioButtonSelfPower.Text = "Target has its own power supply."; this.radioButtonSelfPower.UseVisualStyleBackColor = true; this.radioButtonSelfPower.Click += new System.EventHandler(this.radioButtonSelfPower_Click); // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Arial", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(90, 12); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(171, 19); this.label1.TabIndex = 3; this.label1.Text = "Programmer Settings"; // // panelDownload // this.panelDownload.Controls.Add(this.label7); this.panelDownload.Controls.Add(this.groupBox3); this.panelDownload.Controls.Add(this.label12); this.panelDownload.Location = new System.Drawing.Point(12, 12); this.panelDownload.Name = "panelDownload"; this.panelDownload.Size = new System.Drawing.Size(351, 331); this.panelDownload.TabIndex = 9; this.panelDownload.Visible = false; // // label7 // this.label7.AutoSize = true; this.label7.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label7.Location = new System.Drawing.Point(70, 239); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(212, 45); this.label7.TabIndex = 7; this.label7.Text = "Click the DOWNLOAD button below to\r\nset up PICkit 2 for Programmer-To-Go\r\noperati" + "on.\r\n"; // // groupBox3 // this.groupBox3.Controls.Add(this.labelMCLRHoldSmmry); this.groupBox3.Controls.Add(this.labelFastProgSmmry); this.groupBox3.Controls.Add(this.labelVerifySmmry); this.groupBox3.Controls.Add(this.labelVPP1stSmmry); this.groupBox3.Controls.Add(this.labelMemRegionsSmmry); this.groupBox3.Controls.Add(this.label6); this.groupBox3.Controls.Add(this.labelPNsmmry); this.groupBox3.Controls.Add(this.labelSourceSmmry); this.groupBox3.Controls.Add(this.labelTargetPowerSmmry); this.groupBox3.Font = new System.Drawing.Font("Arial", 9.75F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.groupBox3.Location = new System.Drawing.Point(12, 34); this.groupBox3.Name = "groupBox3"; this.groupBox3.Size = new System.Drawing.Size(327, 171); this.groupBox3.TabIndex = 6; this.groupBox3.TabStop = false; this.groupBox3.Text = "Download Summary"; // // labelSourceSmmry // this.labelSourceSmmry.AutoSize = true; this.labelSourceSmmry.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labelSourceSmmry.Location = new System.Drawing.Point(6, 58); this.labelSourceSmmry.Name = "labelSourceSmmry"; this.labelSourceSmmry.Size = new System.Drawing.Size(88, 13); this.labelSourceSmmry.TabIndex = 10; this.labelSourceSmmry.Text = "<DataSource>"; // // labelTargetPowerSmmry // this.labelTargetPowerSmmry.AutoSize = true; this.labelTargetPowerSmmry.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labelTargetPowerSmmry.Location = new System.Drawing.Point(6, 75); this.labelTargetPowerSmmry.Name = "labelTargetPowerSmmry"; this.labelTargetPowerSmmry.Size = new System.Drawing.Size(108, 15); this.labelTargetPowerSmmry.TabIndex = 7; this.labelTargetPowerSmmry.Text = "<Target Power>"; // // label12 // this.label12.AutoSize = true; this.label12.Font = new System.Drawing.Font("Arial", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label12.Location = new System.Drawing.Point(81, 12); this.label12.Name = "label12"; this.label12.Size = new System.Drawing.Size(168, 19); this.label12.TabIndex = 3; this.label12.Text = "Download to PICkit 2"; // // labelVDDMin // this.labelVDDMin.AutoSize = true; this.labelVDDMin.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labelVDDMin.ForeColor = System.Drawing.Color.OrangeRed; this.labelVDDMin.Location = new System.Drawing.Point(45, 47); this.labelVDDMin.Name = "labelVDDMin"; this.labelVDDMin.Size = new System.Drawing.Size(132, 13); this.labelVDDMin.TabIndex = 12; this.labelVDDMin.Text = "VDD must be >= 0.0 Volts."; this.labelVDDMin.Visible = false; // // labelPNsmmry // this.labelPNsmmry.AutoSize = true; this.labelPNsmmry.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labelPNsmmry.Location = new System.Drawing.Point(6, 21); this.labelPNsmmry.Name = "labelPNsmmry"; this.labelPNsmmry.Size = new System.Drawing.Size(100, 15); this.labelPNsmmry.TabIndex = 11; this.labelPNsmmry.Text = "<PartNumber>"; // // label6 // this.label6.AutoSize = true; this.label6.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label6.Location = new System.Drawing.Point(6, 41); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(76, 15); this.label6.TabIndex = 12; this.label6.Text = "Data source:"; // // labelMemRegionsSmmry // this.labelMemRegionsSmmry.AutoSize = true; this.labelMemRegionsSmmry.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labelMemRegionsSmmry.Location = new System.Drawing.Point(6, 94); this.labelMemRegionsSmmry.Name = "labelMemRegionsSmmry"; this.labelMemRegionsSmmry.Size = new System.Drawing.Size(134, 13); this.labelMemRegionsSmmry.TabIndex = 13; this.labelMemRegionsSmmry.Text = "<MemRegions CP-DP>"; // // labelVPP1stSmmry // this.labelVPP1stSmmry.AutoSize = true; this.labelVPP1stSmmry.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labelVPP1stSmmry.Location = new System.Drawing.Point(6, 107); this.labelVPP1stSmmry.Name = "labelVPP1stSmmry"; this.labelVPP1stSmmry.Size = new System.Drawing.Size(62, 13); this.labelVPP1stSmmry.TabIndex = 14; this.labelVPP1stSmmry.Text = "<VPP1st>"; // // labelVerifySmmry // this.labelVerifySmmry.AutoSize = true; this.labelVerifySmmry.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labelVerifySmmry.Location = new System.Drawing.Point(6, 120); this.labelVerifySmmry.Name = "labelVerifySmmry"; this.labelVerifySmmry.Size = new System.Drawing.Size(53, 13); this.labelVerifySmmry.TabIndex = 15; this.labelVerifySmmry.Text = "<Verify>"; // // labelFastProgSmmry // this.labelFastProgSmmry.AutoSize = true; this.labelFastProgSmmry.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labelFastProgSmmry.Location = new System.Drawing.Point(6, 133); this.labelFastProgSmmry.Name = "labelFastProgSmmry"; this.labelFastProgSmmry.Size = new System.Drawing.Size(117, 13); this.labelFastProgSmmry.TabIndex = 16; this.labelFastProgSmmry.Text = "<FastProgramming>"; // // labelMCLRHoldSmmry // this.labelMCLRHoldSmmry.AutoSize = true; this.labelMCLRHoldSmmry.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labelMCLRHoldSmmry.Location = new System.Drawing.Point(6, 146); this.labelMCLRHoldSmmry.Name = "labelMCLRHoldSmmry"; this.labelMCLRHoldSmmry.Size = new System.Drawing.Size(81, 13); this.labelMCLRHoldSmmry.TabIndex = 17; this.labelMCLRHoldSmmry.Text = "<MCLRHold>"; // // panelDownloading // this.panelDownloading.Controls.Add(this.labelDOWNLOADING); this.panelDownloading.Location = new System.Drawing.Point(12, 12); this.panelDownloading.Name = "panelDownloading"; this.panelDownloading.Size = new System.Drawing.Size(351, 331); this.panelDownloading.TabIndex = 6; this.panelDownloading.Visible = false; // // labelDOWNLOADING // this.labelDOWNLOADING.AutoSize = true; this.labelDOWNLOADING.Font = new System.Drawing.Font("Arial", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labelDOWNLOADING.Location = new System.Drawing.Point(72, 153); this.labelDOWNLOADING.Name = "labelDOWNLOADING"; this.labelDOWNLOADING.Size = new System.Drawing.Size(206, 24); this.labelDOWNLOADING.TabIndex = 2; this.labelDOWNLOADING.Text = "Downloading Now..."; // // panelDownloadDone // this.panelDownloadDone.Controls.Add(this.label20); this.panelDownloadDone.Controls.Add(this.label19); this.panelDownloadDone.Controls.Add(this.label18); this.panelDownloadDone.Controls.Add(this.pictureBoxTarget); this.panelDownloadDone.Controls.Add(this.label17); this.panelDownloadDone.Controls.Add(this.label13); this.panelDownloadDone.Location = new System.Drawing.Point(12, 12); this.panelDownloadDone.Name = "panelDownloadDone"; this.panelDownloadDone.Size = new System.Drawing.Size(351, 331); this.panelDownloadDone.TabIndex = 10; this.panelDownloadDone.Visible = false; // // label13 // this.label13.AutoSize = true; this.label13.Font = new System.Drawing.Font("Arial", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label13.Location = new System.Drawing.Point(75, 15); this.label13.Name = "label13"; this.label13.Size = new System.Drawing.Size(201, 22); this.label13.TabIndex = 2; this.label13.Text = "Download Complete!"; // // label17 // this.label17.AutoSize = true; this.label17.Font = new System.Drawing.Font("Arial", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label17.Location = new System.Drawing.Point(17, 62); this.label17.Name = "label17"; this.label17.Size = new System.Drawing.Size(323, 48); this.label17.TabIndex = 3; this.label17.Text = "The PICkit 2 unit will indicate it\'s in Programmer-To-Go\r\nmode and ready to progr" + "am by blinking the \"Target\" \r\nLED twice in succession:"; // // timerBlink // this.timerBlink.Interval = 250; this.timerBlink.Tick += new System.EventHandler(this.timerBlink_Tick); // // pictureBoxTarget // this.pictureBoxTarget.BackColor = System.Drawing.SystemColors.ControlText; this.pictureBoxTarget.Location = new System.Drawing.Point(73, 125); this.pictureBoxTarget.Name = "pictureBoxTarget"; this.pictureBoxTarget.Size = new System.Drawing.Size(15, 15); this.pictureBoxTarget.TabIndex = 4; this.pictureBoxTarget.TabStop = false; // // label18 // this.label18.AutoSize = true; this.label18.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label18.Location = new System.Drawing.Point(101, 125); this.label18.Name = "label18"; this.label18.Size = new System.Drawing.Size(48, 15); this.label18.TabIndex = 6; this.label18.Text = "Target"; // // label19 // this.label19.AutoSize = true; this.label19.Font = new System.Drawing.Font("Arial", 9.75F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label19.Location = new System.Drawing.Point(16, 159); this.label19.Name = "label19"; this.label19.Size = new System.Drawing.Size(230, 16); this.label19.TabIndex = 7; this.label19.Text = "Remove the PICkit 2 from USB now."; // // label20 // this.label20.AutoSize = true; this.label20.Font = new System.Drawing.Font("Arial", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label20.Location = new System.Drawing.Point(16, 175); this.label20.Name = "label20"; this.label20.Size = new System.Drawing.Size(332, 144); this.label20.TabIndex = 8; this.label20.Text = resources.GetString("label20.Text"); // // panelErrors // this.panelErrors.Controls.Add(this.label29); this.panelErrors.Controls.Add(this.label28); this.panelErrors.Controls.Add(this.label27); this.panelErrors.Controls.Add(this.label26); this.panelErrors.Controls.Add(this.label25); this.panelErrors.Controls.Add(this.radioButton4Blinks); this.panelErrors.Controls.Add(this.radioButton3Blinks); this.panelErrors.Controls.Add(this.radioButton2Blinks); this.panelErrors.Controls.Add(this.radioButtonVErr); this.panelErrors.Controls.Add(this.label24); this.panelErrors.Controls.Add(this.label23); this.panelErrors.Controls.Add(this.pictureBoxBusy); this.panelErrors.Controls.Add(this.label22); this.panelErrors.Controls.Add(this.label21); this.panelErrors.Location = new System.Drawing.Point(12, 12); this.panelErrors.Name = "panelErrors"; this.panelErrors.Size = new System.Drawing.Size(351, 331); this.panelErrors.TabIndex = 11; this.panelErrors.Visible = false; // // label21 // this.label21.AutoSize = true; this.label21.Font = new System.Drawing.Font("Arial", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label21.Location = new System.Drawing.Point(69, 12); this.label21.Name = "label21"; this.label21.Size = new System.Drawing.Size(226, 19); this.label21.TabIndex = 4; this.label21.Text = "Programming && Error Codes"; // // label22 // this.label22.AutoSize = true; this.label22.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label22.Location = new System.Drawing.Point(25, 33); this.label22.Name = "label22"; this.label22.Size = new System.Drawing.Size(287, 150); this.label22.TabIndex = 8; this.label22.Text = resources.GetString("label22.Text"); // // pictureBoxBusy // this.pictureBoxBusy.BackColor = System.Drawing.SystemColors.ControlText; this.pictureBoxBusy.Location = new System.Drawing.Point(107, 194); this.pictureBoxBusy.Name = "pictureBoxBusy"; this.pictureBoxBusy.Size = new System.Drawing.Size(15, 15); this.pictureBoxBusy.TabIndex = 9; this.pictureBoxBusy.TabStop = false; // // label23 // this.label23.AutoSize = true; this.label23.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label23.Location = new System.Drawing.Point(138, 194); this.label23.Name = "label23"; this.label23.Size = new System.Drawing.Size(37, 15); this.label23.TabIndex = 10; this.label23.Text = "Busy"; // // label24 // this.label24.AutoSize = true; this.label24.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label24.Location = new System.Drawing.Point(25, 212); this.label24.Name = "label24"; this.label24.Size = new System.Drawing.Size(188, 15); this.label24.TabIndex = 11; this.label24.Text = "Error Codes (Select for example):"; // // radioButtonVErr // this.radioButtonVErr.AutoSize = true; this.radioButtonVErr.Checked = true; this.radioButtonVErr.Location = new System.Drawing.Point(28, 230); this.radioButtonVErr.Name = "radioButtonVErr"; this.radioButtonVErr.Size = new System.Drawing.Size(85, 17); this.radioButtonVErr.TabIndex = 12; this.radioButtonVErr.TabStop = true; this.radioButtonVErr.Text = "Fast Blinking"; this.radioButtonVErr.UseVisualStyleBackColor = true; this.radioButtonVErr.Click += new System.EventHandler(this.radioButtonVErr_Click); // // radioButton2Blinks // this.radioButton2Blinks.AutoSize = true; this.radioButton2Blinks.Location = new System.Drawing.Point(28, 264); this.radioButton2Blinks.Name = "radioButton2Blinks"; this.radioButton2Blinks.Size = new System.Drawing.Size(62, 17); this.radioButton2Blinks.TabIndex = 13; this.radioButton2Blinks.Text = "2 Blinks"; this.radioButton2Blinks.UseVisualStyleBackColor = true; this.radioButton2Blinks.Click += new System.EventHandler(this.radioButtonVErr_Click); // // radioButton3Blinks // this.radioButton3Blinks.AutoSize = true; this.radioButton3Blinks.Location = new System.Drawing.Point(186, 230); this.radioButton3Blinks.Name = "radioButton3Blinks"; this.radioButton3Blinks.Size = new System.Drawing.Size(62, 17); this.radioButton3Blinks.TabIndex = 14; this.radioButton3Blinks.Text = "3 Blinks"; this.radioButton3Blinks.UseVisualStyleBackColor = true; this.radioButton3Blinks.Click += new System.EventHandler(this.radioButtonVErr_Click); // // radioButton4Blinks // this.radioButton4Blinks.AutoSize = true; this.radioButton4Blinks.Location = new System.Drawing.Point(186, 264); this.radioButton4Blinks.Name = "radioButton4Blinks"; this.radioButton4Blinks.Size = new System.Drawing.Size(62, 17); this.radioButton4Blinks.TabIndex = 15; this.radioButton4Blinks.Text = "4 Blinks"; this.radioButton4Blinks.UseVisualStyleBackColor = true; this.radioButton4Blinks.Click += new System.EventHandler(this.radioButtonVErr_Click); // // label25 // this.label25.AutoSize = true; this.label25.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label25.Location = new System.Drawing.Point(48, 246); this.label25.Name = "label25"; this.label25.Size = new System.Drawing.Size(88, 15); this.label25.TabIndex = 16; this.label25.Text = "VDD/VPP Error"; // // label26 // this.label26.AutoSize = true; this.label26.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label26.Location = new System.Drawing.Point(47, 280); this.label26.Name = "label26"; this.label26.Size = new System.Drawing.Size(89, 15); this.label26.TabIndex = 17; this.label26.Text = "Device ID Error"; // // label27 // this.label27.AutoSize = true; this.label27.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label27.Location = new System.Drawing.Point(206, 246); this.label27.Name = "label27"; this.label27.Size = new System.Drawing.Size(73, 15); this.label27.TabIndex = 18; this.label27.Text = "Verify Failed"; // // label28 // this.label28.AutoSize = true; this.label28.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label28.Location = new System.Drawing.Point(206, 280); this.label28.Name = "label28"; this.label28.Size = new System.Drawing.Size(78, 15); this.label28.TabIndex = 19; this.label28.Text = "Internal Error"; // // label29 // this.label29.AutoSize = true; this.label29.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label29.Location = new System.Drawing.Point(28, 312); this.label29.Name = "label29"; this.label29.Size = new System.Drawing.Size(294, 13); this.label29.TabIndex = 19; this.label29.Text = "Click EXIT to close Wizard. Click HELP for more information.\r\n"; // // label256K // this.label256K.AutoSize = true; this.label256K.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label256K.Location = new System.Drawing.Point(156, 306); this.label256K.Name = "label256K"; this.label256K.Size = new System.Drawing.Size(196, 13); this.label256K.TabIndex = 6; this.label256K.Text = "256K PICkit 2 upgrade support enabled.\r\n"; this.label256K.Visible = false; // // DialogPK2Go // this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.ClientSize = new System.Drawing.Size(374, 380); this.Controls.Add(this.panelErrors); this.Controls.Add(this.panelDownloadDone); this.Controls.Add(this.panelDownloading); this.Controls.Add(this.panelDownload); this.Controls.Add(this.panelSettings); this.Controls.Add(this.buttonHelp); this.Controls.Add(this.buttonBack); this.Controls.Add(this.panelIntro); this.Controls.Add(this.buttonNext); this.Controls.Add(this.buttonCancel); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "DialogPK2Go"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Programmer-To-Go Wizard"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.DialogPK2Go_FormClosing); this.panelIntro.ResumeLayout(false); this.panelIntro.PerformLayout(); this.panelSettings.ResumeLayout(false); this.panelSettings.PerformLayout(); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.panelDownload.ResumeLayout(false); this.panelDownload.PerformLayout(); this.groupBox3.ResumeLayout(false); this.groupBox3.PerformLayout(); this.panelDownloading.ResumeLayout(false); this.panelDownloading.PerformLayout(); this.panelDownloadDone.ResumeLayout(false); this.panelDownloadDone.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxTarget)).EndInit(); this.panelErrors.ResumeLayout(false); this.panelErrors.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxBusy)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Panel panelIntro; private System.Windows.Forms.Button buttonBack; private System.Windows.Forms.Button buttonNext; private System.Windows.Forms.Button buttonCancel; private System.Windows.Forms.Button buttonHelp; private System.Windows.Forms.Panel panelSettings; private System.Windows.Forms.Label label16; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label15; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.Label label2; private System.Windows.Forms.RadioButton radioButtonPK2Power; private System.Windows.Forms.RadioButton radioButtonSelfPower; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label labelPartNumber; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label labelDataSource; private System.Windows.Forms.Label label4; private System.Windows.Forms.Panel panelDownload; private System.Windows.Forms.GroupBox groupBox3; private System.Windows.Forms.Label labelTargetPowerSmmry; private System.Windows.Forms.Label label12; private System.Windows.Forms.Label label7; private System.Windows.Forms.Label labelSourceSmmry; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label labelOSCCAL_BandGap; private System.Windows.Forms.Label label10; private System.Windows.Forms.Label labelMemRegions; private System.Windows.Forms.Label labelCodeProtect; private System.Windows.Forms.Label label14; private System.Windows.Forms.Label labelVerify; private System.Windows.Forms.Label label11; private System.Windows.Forms.Label labelDataProtect; private System.Windows.Forms.Label label9; private System.Windows.Forms.Label labelRowErase; private System.Windows.Forms.CheckBox checkBoxRowErase; private System.Windows.Forms.Label labelVDDMin; private System.Windows.Forms.Label labelPNsmmry; private System.Windows.Forms.Label labelMemRegionsSmmry; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label labelMCLRHoldSmmry; private System.Windows.Forms.Label labelFastProgSmmry; private System.Windows.Forms.Label labelVerifySmmry; private System.Windows.Forms.Label labelVPP1stSmmry; private System.Windows.Forms.Panel panelDownloading; private System.Windows.Forms.Label labelDOWNLOADING; private System.Windows.Forms.Panel panelDownloadDone; private System.Windows.Forms.Label label13; private System.Windows.Forms.Label label17; private System.Windows.Forms.Timer timerBlink; private System.Windows.Forms.Label label20; private System.Windows.Forms.Label label19; private System.Windows.Forms.Label label18; private System.Windows.Forms.PictureBox pictureBoxTarget; private System.Windows.Forms.Panel panelErrors; private System.Windows.Forms.Label label21; private System.Windows.Forms.Label label22; private System.Windows.Forms.Label label23; private System.Windows.Forms.PictureBox pictureBoxBusy; private System.Windows.Forms.Label label26; private System.Windows.Forms.Label label25; private System.Windows.Forms.RadioButton radioButton4Blinks; private System.Windows.Forms.RadioButton radioButton3Blinks; private System.Windows.Forms.RadioButton radioButton2Blinks; private System.Windows.Forms.RadioButton radioButtonVErr; private System.Windows.Forms.Label label24; private System.Windows.Forms.Label label27; private System.Windows.Forms.Label label28; private System.Windows.Forms.Label label29; private System.Windows.Forms.Label label256K; } }
/* * 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; using System.Collections.Generic; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.IO.Compression; using System.Net; using System.Net.Security; using System.Reflection; using System.Text; using System.Web; using System.Xml; using System.Xml.Serialization; using System.Xml.Linq; using log4net; using Nwc.XmlRpc; using OpenMetaverse.StructuredData; using XMLResponseHelper = OpenSim.Framework.SynchronousRestObjectRequester.XMLResponseHelper; using OpenSim.Framework.ServiceAuth; namespace OpenSim.Framework { /// <summary> /// Miscellaneous static methods and extension methods related to the web /// </summary> public static class WebUtil { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Control the printing of certain debug messages. /// </summary> /// <remarks> /// If DebugLevel >= 3 then short notices about outgoing HTTP requests are logged. /// </remarks> public static int DebugLevel { get; set; } /// <summary> /// Request number for diagnostic purposes. /// </summary> public static int RequestNumber { get; set; } /// <summary> /// Control where OSD requests should be serialized per endpoint. /// </summary> public static bool SerializeOSDRequestsPerEndpoint { get; set; } /// <summary> /// this is the header field used to communicate the local request id /// used for performance and debugging /// </summary> public const string OSHeaderRequestID = "opensim-request-id"; /// <summary> /// Number of milliseconds a call can take before it is considered /// a "long" call for warning & debugging purposes /// </summary> public const int LongCallTime = 3000; /// <summary> /// The maximum length of any data logged because of a long request time. /// </summary> /// <remarks> /// This is to truncate any really large post data, such as an asset. In theory, the first section should /// give us useful information about the call (which agent it relates to if applicable, etc.). /// This is also used to truncate messages when using DebugLevel 5. /// </remarks> public const int MaxRequestDiagLength = 200; /// <summary> /// Dictionary of end points /// </summary> private static Dictionary<string,object> m_endpointSerializer = new Dictionary<string,object>(); private static object EndPointLock(string url) { System.Uri uri = new System.Uri(url); string endpoint = string.Format("{0}:{1}",uri.Host,uri.Port); lock (m_endpointSerializer) { object eplock = null; if (! m_endpointSerializer.TryGetValue(endpoint,out eplock)) { eplock = new object(); m_endpointSerializer.Add(endpoint,eplock); // m_log.WarnFormat("[WEB UTIL] add a new host to end point serializer {0}",endpoint); } return eplock; } } #region JSONRequest /// <summary> /// PUT JSON-encoded data to a web service that returns LLSD or /// JSON data /// </summary> public static OSDMap PutToServiceCompressed(string url, OSDMap data, int timeout) { return ServiceOSDRequest(url,data, "PUT", timeout, true, false); } public static OSDMap PutToService(string url, OSDMap data, int timeout) { return ServiceOSDRequest(url,data, "PUT", timeout, false, false); } public static OSDMap PostToService(string url, OSDMap data, int timeout, bool rpc) { return ServiceOSDRequest(url, data, "POST", timeout, false, rpc); } public static OSDMap PostToServiceCompressed(string url, OSDMap data, int timeout) { return ServiceOSDRequest(url, data, "POST", timeout, true, false); } public static OSDMap GetFromService(string url, int timeout) { return ServiceOSDRequest(url, null, "GET", timeout, false, false); } public static OSDMap ServiceOSDRequest(string url, OSDMap data, string method, int timeout, bool compressed, bool rpc) { if (SerializeOSDRequestsPerEndpoint) { lock (EndPointLock(url)) { return ServiceOSDRequestWorker(url, data, method, timeout, compressed, rpc); } } else { return ServiceOSDRequestWorker(url, data, method, timeout, compressed, rpc); } } public static void LogOutgoingDetail(Stream outputStream) { LogOutgoingDetail("", outputStream); } public static void LogOutgoingDetail(string context, Stream outputStream) { using (Stream stream = Util.Copy(outputStream)) using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { string output; if (DebugLevel == 5) { char[] chars = new char[WebUtil.MaxRequestDiagLength + 1]; // +1 so we know to add "..." only if needed int len = reader.Read(chars, 0, WebUtil.MaxRequestDiagLength + 1); output = new string(chars, 0, len); } else { output = reader.ReadToEnd(); } LogOutgoingDetail(context, output); } } public static void LogOutgoingDetail(string type, int reqnum, string output) { LogOutgoingDetail(string.Format("{0} {1}: ", type, reqnum), output); } public static void LogOutgoingDetail(string context, string output) { if (DebugLevel == 5) { if (output.Length > MaxRequestDiagLength) output = output.Substring(0, MaxRequestDiagLength) + "..."; } m_log.DebugFormat("[LOGHTTP]: {0}{1}", context, Util.BinaryToASCII(output)); } public static void LogResponseDetail(int reqnum, Stream inputStream) { LogOutgoingDetail(string.Format("RESPONSE {0}: ", reqnum), inputStream); } public static void LogResponseDetail(int reqnum, string input) { LogOutgoingDetail(string.Format("RESPONSE {0}: ", reqnum), input); } private static OSDMap ServiceOSDRequestWorker(string url, OSDMap data, string method, int timeout, bool compressed, bool rpc) { int reqnum = RequestNumber++; if (DebugLevel >= 3) m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} JSON-RPC {1} to {2}", reqnum, method, url); string errorMessage = "unknown error"; int tickstart = Util.EnvironmentTickCount(); int tickdata = 0; int tickcompressdata = 0; int tickJsondata = 0; int compsize = 0; string strBuffer = null; try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = method; request.Timeout = timeout; request.KeepAlive = false; request.MaximumAutomaticRedirections = 10; request.ReadWriteTimeout = timeout / 4; request.Headers[OSHeaderRequestID] = reqnum.ToString(); // If there is some input, write it into the request if (data != null) { strBuffer = OSDParser.SerializeJsonString(data); tickJsondata = Util.EnvironmentTickCountSubtract(tickstart); if (DebugLevel >= 5) LogOutgoingDetail("SEND", reqnum, strBuffer); byte[] buffer = System.Text.Encoding.UTF8.GetBytes(strBuffer); request.ContentType = rpc ? "application/json-rpc" : "application/json"; if (compressed) { request.Headers["X-Content-Encoding"] = "gzip"; // can't set "Content-Encoding" because old OpenSims fail if they get an unrecognized Content-Encoding using (MemoryStream ms = new MemoryStream()) { using (GZipStream comp = new GZipStream(ms, CompressionMode.Compress, true)) { comp.Write(buffer, 0, buffer.Length); // We need to close the gzip stream before we write it anywhere // because apparently something important related to gzip compression // gets written on the stream upon Dispose() } byte[] buf = ms.ToArray(); tickcompressdata = Util.EnvironmentTickCountSubtract(tickstart); request.ContentLength = buf.Length; //Count bytes to send compsize = buf.Length; using (Stream requestStream = request.GetRequestStream()) requestStream.Write(buf, 0, (int)buf.Length); } } else { tickcompressdata = tickJsondata; compsize = buffer.Length; request.ContentLength = buffer.Length; //Count bytes to send using (Stream requestStream = request.GetRequestStream()) requestStream.Write(buffer, 0, buffer.Length); //Send it } } // capture how much time was spent writing, this may seem silly // but with the number concurrent requests, this often blocks tickdata = Util.EnvironmentTickCountSubtract(tickstart); using (WebResponse response = request.GetResponse()) { using (Stream responseStream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(responseStream)) { string responseStr = reader.ReadToEnd(); if (WebUtil.DebugLevel >= 5) WebUtil.LogResponseDetail(reqnum, responseStr); return CanonicalizeResults(responseStr); } } } } catch (WebException we) { errorMessage = we.Message; if (we.Status == WebExceptionStatus.ProtocolError) { using (HttpWebResponse webResponse = (HttpWebResponse)we.Response) errorMessage = String.Format("[{0}] {1}", webResponse.StatusCode, webResponse.StatusDescription); } } catch (Exception ex) { errorMessage = ex.Message; m_log.Debug("[WEB UTIL]: Exception making request: " + ex.ToString()); } finally { int tickdiff = Util.EnvironmentTickCountSubtract(tickstart); if (tickdiff > LongCallTime) { m_log.InfoFormat( "[WEB UTIL]: Slow ServiceOSD request {0} {1} {2} took {3}ms, {4}ms writing({5} at Json; {6} at comp), {7} bytes ({8} uncomp): {9}", reqnum, method, url, tickdiff, tickdata, tickJsondata, tickcompressdata, compsize, strBuffer != null ? strBuffer.Length : 0, strBuffer != null ? (strBuffer.Length > MaxRequestDiagLength ? strBuffer.Remove(MaxRequestDiagLength) : strBuffer) : ""); } else if (DebugLevel >= 4) { m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} took {1}ms, {2}ms writing", reqnum, tickdiff, tickdata); } } m_log.DebugFormat( "[LOGHTTP]: JSON-RPC request {0} {1} to {2} FAILED: {3}", reqnum, method, url, errorMessage); return ErrorResponseMap(errorMessage); } /// <summary> /// Since there are no consistencies in the way web requests are /// formed, we need to do a little guessing about the result format. /// Keys: /// Success|success == the success fail of the request /// _RawResult == the raw string that came back /// _Result == the OSD unpacked string /// </summary> private static OSDMap CanonicalizeResults(string response) { OSDMap result = new OSDMap(); // Default values result["Success"] = OSD.FromBoolean(true); result["success"] = OSD.FromBoolean(true); result["_RawResult"] = OSD.FromString(response); result["_Result"] = new OSDMap(); if (response.Equals("true",System.StringComparison.OrdinalIgnoreCase)) return result; if (response.Equals("false",System.StringComparison.OrdinalIgnoreCase)) { result["Success"] = OSD.FromBoolean(false); result["success"] = OSD.FromBoolean(false); return result; } try { OSD responseOSD = OSDParser.Deserialize(response); if (responseOSD.Type == OSDType.Map) { result["_Result"] = (OSDMap)responseOSD; return result; } } catch { // don't need to treat this as an error... we're just guessing anyway // m_log.DebugFormat("[WEB UTIL] couldn't decode <{0}>: {1}",response,e.Message); } return result; } #endregion JSONRequest #region FormRequest /// <summary> /// POST URL-encoded form data to a web service that returns LLSD or /// JSON data /// </summary> public static OSDMap PostToService(string url, NameValueCollection data) { return ServiceFormRequest(url,data, 30000); } public static OSDMap ServiceFormRequest(string url, NameValueCollection data, int timeout) { lock (EndPointLock(url)) { return ServiceFormRequestWorker(url,data,timeout); } } private static OSDMap ServiceFormRequestWorker(string url, NameValueCollection data, int timeout) { int reqnum = RequestNumber++; string method = (data != null && data["RequestMethod"] != null) ? data["RequestMethod"] : "unknown"; if (DebugLevel >= 3) m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} ServiceForm '{1}' to {2}", reqnum, method, url); string errorMessage = "unknown error"; int tickstart = Util.EnvironmentTickCount(); int tickdata = 0; string queryString = null; try { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); request.Method = "POST"; request.Timeout = timeout; request.KeepAlive = false; request.MaximumAutomaticRedirections = 10; request.ReadWriteTimeout = timeout / 4; request.Headers[OSHeaderRequestID] = reqnum.ToString(); if (data != null) { queryString = BuildQueryString(data); if (DebugLevel >= 5) LogOutgoingDetail("SEND", reqnum, queryString); byte[] buffer = System.Text.Encoding.UTF8.GetBytes(queryString); request.ContentLength = buffer.Length; request.ContentType = "application/x-www-form-urlencoded"; using (Stream requestStream = request.GetRequestStream()) requestStream.Write(buffer, 0, buffer.Length); } // capture how much time was spent writing, this may seem silly // but with the number concurrent requests, this often blocks tickdata = Util.EnvironmentTickCountSubtract(tickstart); using (WebResponse response = request.GetResponse()) { using (Stream responseStream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(responseStream)) { string responseStr = reader.ReadToEnd(); if (WebUtil.DebugLevel >= 5) WebUtil.LogResponseDetail(reqnum, responseStr); OSD responseOSD = OSDParser.Deserialize(responseStr); if (responseOSD.Type == OSDType.Map) return (OSDMap)responseOSD; } } } } catch (WebException we) { errorMessage = we.Message; if (we.Status == WebExceptionStatus.ProtocolError) { using (HttpWebResponse webResponse = (HttpWebResponse)we.Response) errorMessage = String.Format("[{0}] {1}",webResponse.StatusCode,webResponse.StatusDescription); } } catch (Exception ex) { errorMessage = ex.Message; } finally { int tickdiff = Util.EnvironmentTickCountSubtract(tickstart); if (tickdiff > LongCallTime) { m_log.InfoFormat( "[LOGHTTP]: Slow ServiceForm request {0} '{1}' to {2} took {3}ms, {4}ms writing, {5}", reqnum, method, url, tickdiff, tickdata, queryString != null ? (queryString.Length > MaxRequestDiagLength) ? queryString.Remove(MaxRequestDiagLength) : queryString : ""); } else if (DebugLevel >= 4) { m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} took {1}ms, {2}ms writing", reqnum, tickdiff, tickdata); } } m_log.WarnFormat("[LOGHTTP]: ServiceForm request {0} '{1}' to {2} failed: {3}", reqnum, method, url, errorMessage); return ErrorResponseMap(errorMessage); } /// <summary> /// Create a response map for an error, trying to keep /// the result formats consistent /// </summary> private static OSDMap ErrorResponseMap(string msg) { OSDMap result = new OSDMap(); result["Success"] = "False"; result["Message"] = OSD.FromString("Service request failed: " + msg); return result; } #endregion FormRequest #region Uri /// <summary> /// Combines a Uri that can contain both a base Uri and relative path /// with a second relative path fragment /// </summary> /// <param name="uri">Starting (base) Uri</param> /// <param name="fragment">Relative path fragment to append to the end /// of the Uri</param> /// <returns>The combined Uri</returns> /// <remarks>This is similar to the Uri constructor that takes a base /// Uri and the relative path, except this method can append a relative /// path fragment on to an existing relative path</remarks> public static Uri Combine(this Uri uri, string fragment) { string fragment1 = uri.Fragment; string fragment2 = fragment; if (!fragment1.EndsWith("/")) fragment1 = fragment1 + '/'; if (fragment2.StartsWith("/")) fragment2 = fragment2.Substring(1); return new Uri(uri, fragment1 + fragment2); } /// <summary> /// Combines a Uri that can contain both a base Uri and relative path /// with a second relative path fragment. If the fragment is absolute, /// it will be returned without modification /// </summary> /// <param name="uri">Starting (base) Uri</param> /// <param name="fragment">Relative path fragment to append to the end /// of the Uri, or an absolute Uri to return unmodified</param> /// <returns>The combined Uri</returns> public static Uri Combine(this Uri uri, Uri fragment) { if (fragment.IsAbsoluteUri) return fragment; string fragment1 = uri.Fragment; string fragment2 = fragment.ToString(); if (!fragment1.EndsWith("/")) fragment1 = fragment1 + '/'; if (fragment2.StartsWith("/")) fragment2 = fragment2.Substring(1); return new Uri(uri, fragment1 + fragment2); } /// <summary> /// Appends a query string to a Uri that may or may not have existing /// query parameters /// </summary> /// <param name="uri">Uri to append the query to</param> /// <param name="query">Query string to append. Can either start with ? /// or just containg key/value pairs</param> /// <returns>String representation of the Uri with the query string /// appended</returns> public static string AppendQuery(this Uri uri, string query) { if (String.IsNullOrEmpty(query)) return uri.ToString(); if (query[0] == '?' || query[0] == '&') query = query.Substring(1); string uriStr = uri.ToString(); if (uriStr.Contains("?")) return uriStr + '&' + query; else return uriStr + '?' + query; } #endregion Uri #region NameValueCollection /// <summary> /// Convert a NameValueCollection into a query string. This is the /// inverse of HttpUtility.ParseQueryString() /// </summary> /// <param name="parameters">Collection of key/value pairs to convert</param> /// <returns>A query string with URL-escaped values</returns> public static string BuildQueryString(NameValueCollection parameters) { List<string> items = new List<string>(parameters.Count); foreach (string key in parameters.Keys) { string[] values = parameters.GetValues(key); if (values != null) { foreach (string value in values) items.Add(String.Concat(key, "=", HttpUtility.UrlEncode(value ?? String.Empty))); } } return String.Join("&", items.ToArray()); } /// <summary> /// /// </summary> /// <param name="collection"></param> /// <param name="key"></param> /// <returns></returns> public static string GetOne(this NameValueCollection collection, string key) { string[] values = collection.GetValues(key); if (values != null && values.Length > 0) return values[0]; return null; } #endregion NameValueCollection #region Stream /// <summary> /// Copies the contents of one stream to another, starting at the /// current position of each stream /// </summary> /// <param name="copyFrom">The stream to copy from, at the position /// where copying should begin</param> /// <param name="copyTo">The stream to copy to, at the position where /// bytes should be written</param> /// <param name="maximumBytesToCopy">The maximum bytes to copy</param> /// <returns>The total number of bytes copied</returns> /// <remarks> /// Copying begins at the streams' current positions. The positions are /// NOT reset after copying is complete. /// NOTE!! .NET 4.0 adds the method 'Stream.CopyTo(stream, bufferSize)'. /// This function could be replaced with that method once we move /// totally to .NET 4.0. For versions before, this routine exists. /// This routine used to be named 'CopyTo' but the int parameter has /// a different meaning so this method was renamed to avoid any confusion. /// </remarks> public static int CopyStream(this Stream copyFrom, Stream copyTo, int maximumBytesToCopy) { byte[] buffer = new byte[4096]; int readBytes; int totalCopiedBytes = 0; while ((readBytes = copyFrom.Read(buffer, 0, Math.Min(4096, maximumBytesToCopy))) > 0) { int writeBytes = Math.Min(maximumBytesToCopy, readBytes); copyTo.Write(buffer, 0, writeBytes); totalCopiedBytes += writeBytes; maximumBytesToCopy -= writeBytes; } return totalCopiedBytes; } #endregion Stream public class QBasedComparer : IComparer { public int Compare(Object x, Object y) { float qx = GetQ(x); float qy = GetQ(y); return qy.CompareTo(qx); // descending order } private float GetQ(Object o) { // Example: image/png;q=0.9 float qvalue = 1F; if (o is String) { string mime = (string)o; string[] parts = mime.Split(';'); if (parts.Length > 1) { string[] kvp = parts[1].Split('='); if (kvp.Length == 2 && kvp[0] == "q") float.TryParse(kvp[1], NumberStyles.Number, CultureInfo.InvariantCulture, out qvalue); } } return qvalue; } } /// <summary> /// Takes the value of an Accept header and returns the preferred types /// ordered by q value (if it exists). /// Example input: image/jpg;q=0.7, image/png;q=0.8, image/jp2 /// Exmaple output: ["jp2", "png", "jpg"] /// NOTE: This doesn't handle the semantics of *'s... /// </summary> /// <param name="accept"></param> /// <returns></returns> public static string[] GetPreferredImageTypes(string accept) { if (string.IsNullOrEmpty(accept)) return new string[0]; string[] types = accept.Split(new char[] { ',' }); if (types.Length > 0) { List<string> list = new List<string>(types); list.RemoveAll(delegate(string s) { return !s.ToLower().StartsWith("image"); }); ArrayList tlist = new ArrayList(list); tlist.Sort(new QBasedComparer()); string[] result = new string[tlist.Count]; for (int i = 0; i < tlist.Count; i++) { string mime = (string)tlist[i]; string[] parts = mime.Split(new char[] { ';' }); string[] pair = parts[0].Split(new char[] { '/' }); if (pair.Length == 2) result[i] = pair[1].ToLower(); else // oops, we don't know what this is... result[i] = pair[0]; } return result; } return new string[0]; } } public static class AsynchronousRestObjectRequester { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Perform an asynchronous REST request. /// </summary> /// <param name="verb">GET or POST</param> /// <param name="requestUrl"></param> /// <param name="obj"></param> /// <param name="action"></param> /// <returns></returns> /// /// <exception cref="System.Net.WebException">Thrown if we encounter a /// network issue while posting the request. You'll want to make /// sure you deal with this as they're not uncommon</exception> // public static void MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj, Action<TResponse> action) { MakeRequest<TRequest, TResponse>(verb, requestUrl, obj, action, 0); } public static void MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj, Action<TResponse> action, int maxConnections) { MakeRequest<TRequest, TResponse>(verb, requestUrl, obj, action, maxConnections, null); } /// <summary> /// Perform a synchronous REST request. /// </summary> /// <param name="verb"></param> /// <param name="requestUrl"></param> /// <param name="obj"></param> /// <param name="pTimeout"> /// Request timeout in seconds. Timeout.Infinite indicates no timeout. If 0 is passed then the default HttpWebRequest timeout is used (100 seconds) /// </param> /// <param name="maxConnections"></param> /// <returns> /// The response. If there was an internal exception or the request timed out, /// then the default(TResponse) is returned. /// </returns> public static void MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj, Action<TResponse> action, int maxConnections, IServiceAuth auth) { int reqnum = WebUtil.RequestNumber++; if (WebUtil.DebugLevel >= 3) m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} AsynchronousRequestObject {1} to {2}", reqnum, verb, requestUrl); int tickstart = Util.EnvironmentTickCount(); int tickdata = 0; int tickdiff = 0; Type type = typeof(TRequest); WebRequest request = WebRequest.Create(requestUrl); HttpWebRequest ht = (HttpWebRequest)request; if (auth != null) auth.AddAuthorization(ht.Headers); if (maxConnections > 0 && ht.ServicePoint.ConnectionLimit < maxConnections) ht.ServicePoint.ConnectionLimit = maxConnections; TResponse deserial = default(TResponse); request.Method = verb; MemoryStream buffer = null; try { if (verb == "POST") { request.ContentType = "text/xml"; buffer = new MemoryStream(); XmlWriterSettings settings = new XmlWriterSettings(); settings.Encoding = Encoding.UTF8; using (XmlWriter writer = XmlWriter.Create(buffer, settings)) { XmlSerializer serializer = new XmlSerializer(type); serializer.Serialize(writer, obj); writer.Flush(); } int length = (int)buffer.Length; request.ContentLength = length; byte[] data = buffer.ToArray(); if (WebUtil.DebugLevel >= 5) WebUtil.LogOutgoingDetail("SEND", reqnum, System.Text.Encoding.UTF8.GetString(data)); request.BeginGetRequestStream(delegate(IAsyncResult res) { using (Stream requestStream = request.EndGetRequestStream(res)) requestStream.Write(data, 0, length); // capture how much time was spent writing tickdata = Util.EnvironmentTickCountSubtract(tickstart); request.BeginGetResponse(delegate(IAsyncResult ar) { using (WebResponse response = request.EndGetResponse(ar)) { try { using (Stream respStream = response.GetResponseStream()) { deserial = XMLResponseHelper.LogAndDeserialize<TRequest, TResponse>( reqnum, respStream, response.ContentLength); } } catch (System.InvalidOperationException) { } } action(deserial); }, null); }, null); } else { request.BeginGetResponse(delegate(IAsyncResult res2) { try { // If the server returns a 404, this appears to trigger a System.Net.WebException even though that isn't // documented in MSDN using (WebResponse response = request.EndGetResponse(res2)) { try { using (Stream respStream = response.GetResponseStream()) { deserial = XMLResponseHelper.LogAndDeserialize<TRequest, TResponse>( reqnum, respStream, response.ContentLength); } } catch (System.InvalidOperationException) { } } } catch (WebException e) { if (e.Status == WebExceptionStatus.ProtocolError) { if (e.Response is HttpWebResponse) { using (HttpWebResponse httpResponse = (HttpWebResponse)e.Response) { if (httpResponse.StatusCode != HttpStatusCode.NotFound) { // We don't appear to be handling any other status codes, so log these feailures to that // people don't spend unnecessary hours hunting phantom bugs. m_log.DebugFormat( "[ASYNC REQUEST]: Request {0} {1} failed with unexpected status code {2}", verb, requestUrl, httpResponse.StatusCode); } } } } else { m_log.ErrorFormat( "[ASYNC REQUEST]: Request {0} {1} failed with status {2} and message {3}", verb, requestUrl, e.Status, e.Message); } } catch (Exception e) { m_log.ErrorFormat( "[ASYNC REQUEST]: Request {0} {1} failed with exception {2}{3}", verb, requestUrl, e.Message, e.StackTrace); } // m_log.DebugFormat("[ASYNC REQUEST]: Received {0}", deserial.ToString()); try { action(deserial); } catch (Exception e) { m_log.ErrorFormat( "[ASYNC REQUEST]: Request {0} {1} callback failed with exception {2}{3}", verb, requestUrl, e.Message, e.StackTrace); } }, null); } tickdiff = Util.EnvironmentTickCountSubtract(tickstart); if (tickdiff > WebUtil.LongCallTime) { string originalRequest = null; if (buffer != null) { originalRequest = Encoding.UTF8.GetString(buffer.ToArray()); if (originalRequest.Length > WebUtil.MaxRequestDiagLength) originalRequest = originalRequest.Remove(WebUtil.MaxRequestDiagLength); } m_log.InfoFormat( "[LOGHTTP]: Slow AsynchronousRequestObject request {0} {1} to {2} took {3}ms, {4}ms writing, {5}", reqnum, verb, requestUrl, tickdiff, tickdata, originalRequest); } else if (WebUtil.DebugLevel >= 4) { m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} took {1}ms, {2}ms writing", reqnum, tickdiff, tickdata); } } finally { if (buffer != null) buffer.Dispose(); } } } public static class SynchronousRestFormsRequester { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Perform a synchronous REST request. /// </summary> /// <param name="verb"></param> /// <param name="requestUrl"></param> /// <param name="obj"> </param> /// <param name="timeoutsecs"> </param> /// <returns></returns> /// /// <exception cref="System.Net.WebException">Thrown if we encounter a network issue while posting /// the request. You'll want to make sure you deal with this as they're not uncommon</exception> public static string MakeRequest(string verb, string requestUrl, string obj, int timeoutsecs, IServiceAuth auth) { int reqnum = WebUtil.RequestNumber++; if (WebUtil.DebugLevel >= 3) m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} SynchronousRestForms {1} to {2}", reqnum, verb, requestUrl); int tickstart = Util.EnvironmentTickCount(); int tickdata = 0; WebRequest request = WebRequest.Create(requestUrl); request.Method = verb; if (timeoutsecs > 0) request.Timeout = timeoutsecs * 1000; if (auth != null) auth.AddAuthorization(request.Headers); string respstring = String.Empty; int tickset = Util.EnvironmentTickCountSubtract(tickstart); using (MemoryStream buffer = new MemoryStream()) { if ((verb == "POST") || (verb == "PUT")) { request.ContentType = "application/x-www-form-urlencoded"; int length = 0; using (StreamWriter writer = new StreamWriter(buffer)) { writer.Write(obj); writer.Flush(); } length = (int)obj.Length; request.ContentLength = length; byte[] data = buffer.ToArray(); if (WebUtil.DebugLevel >= 5) WebUtil.LogOutgoingDetail("SEND", reqnum, System.Text.Encoding.UTF8.GetString(data)); Stream requestStream = null; try { requestStream = request.GetRequestStream(); requestStream.Write(data, 0, length); } catch (Exception e) { m_log.InfoFormat("[FORMS]: Error sending request to {0}: {1}. Request: {2}", requestUrl, e.Message, obj.Length > WebUtil.MaxRequestDiagLength ? obj.Remove(WebUtil.MaxRequestDiagLength) : obj); throw e; } finally { if (requestStream != null) requestStream.Dispose(); // capture how much time was spent writing tickdata = Util.EnvironmentTickCountSubtract(tickstart); } } try { using (WebResponse resp = request.GetResponse()) { if (resp.ContentLength != 0) { using (Stream respStream = resp.GetResponseStream()) using (StreamReader reader = new StreamReader(respStream)) respstring = reader.ReadToEnd(); } } } catch (Exception e) { m_log.InfoFormat("[FORMS]: Error receiving response from {0}: {1}. Request: {2}", requestUrl, e.Message, obj.Length > WebUtil.MaxRequestDiagLength ? obj.Remove(WebUtil.MaxRequestDiagLength) : obj); throw e; } } int tickdiff = Util.EnvironmentTickCountSubtract(tickstart); if (tickdiff > WebUtil.LongCallTime) { m_log.InfoFormat( "[FORMS]: Slow request {0} {1} {2} took {3}ms, {4}ms writing, {5}", reqnum, verb, requestUrl, tickdiff, tickset, tickdata, obj.Length > WebUtil.MaxRequestDiagLength ? obj.Remove(WebUtil.MaxRequestDiagLength) : obj); } else if (WebUtil.DebugLevel >= 4) { m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} took {1}ms, {2}ms writing", reqnum, tickdiff, tickdata); } if (WebUtil.DebugLevel >= 5) WebUtil.LogResponseDetail(reqnum, respstring); return respstring; } public static string MakeRequest(string verb, string requestUrl, string obj, int timeoutsecs) { return MakeRequest(verb, requestUrl, obj, timeoutsecs, null); } public static string MakeRequest(string verb, string requestUrl, string obj) { return MakeRequest(verb, requestUrl, obj, -1); } public static string MakeRequest(string verb, string requestUrl, string obj, IServiceAuth auth) { return MakeRequest(verb, requestUrl, obj, -1, auth); } } public class SynchronousRestObjectRequester { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Perform a synchronous REST request. /// </summary> /// <param name="verb"></param> /// <param name="requestUrl"></param> /// <param name="obj"></param> /// <returns> /// The response. If there was an internal exception, then the default(TResponse) is returned. /// </returns> public static TResponse MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj) { return MakeRequest<TRequest, TResponse>(verb, requestUrl, obj, 0); } public static TResponse MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj, IServiceAuth auth) { return MakeRequest<TRequest, TResponse>(verb, requestUrl, obj, 0, auth); } /// <summary> /// Perform a synchronous REST request. /// </summary> /// <param name="verb"></param> /// <param name="requestUrl"></param> /// <param name="obj"></param> /// <param name="pTimeout"> /// Request timeout in milliseconds. Timeout.Infinite indicates no timeout. If 0 is passed then the default HttpWebRequest timeout is used (100 seconds) /// </param> /// <returns> /// The response. If there was an internal exception or the request timed out, /// then the default(TResponse) is returned. /// </returns> public static TResponse MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj, int pTimeout) { return MakeRequest<TRequest, TResponse>(verb, requestUrl, obj, pTimeout, 0); } public static TResponse MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj, int pTimeout, IServiceAuth auth) { return MakeRequest<TRequest, TResponse>(verb, requestUrl, obj, pTimeout, 0, auth); } /// Perform a synchronous REST request. /// </summary> /// <param name="verb"></param> /// <param name="requestUrl"></param> /// <param name="obj"></param> /// <param name="pTimeout"> /// Request timeout in milliseconds. Timeout.Infinite indicates no timeout. If 0 is passed then the default HttpWebRequest timeout is used (100 seconds) /// </param> /// <param name="maxConnections"></param> /// <returns> /// The response. If there was an internal exception or the request timed out, /// then the default(TResponse) is returned. /// </returns> public static TResponse MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj, int pTimeout, int maxConnections) { return MakeRequest<TRequest, TResponse>(verb, requestUrl, obj, pTimeout, maxConnections, null); } /// <summary> /// Perform a synchronous REST request. /// </summary> /// <param name="verb"></param> /// <param name="requestUrl"></param> /// <param name="obj"></param> /// <param name="pTimeout"> /// Request timeout in milliseconds. Timeout.Infinite indicates no timeout. If 0 is passed then the default HttpWebRequest timeout is used (100 seconds) /// </param> /// <param name="maxConnections"></param> /// <returns> /// The response. If there was an internal exception or the request timed out, /// then the default(TResponse) is returned. /// </returns> public static TResponse MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj, int pTimeout, int maxConnections, IServiceAuth auth) { int reqnum = WebUtil.RequestNumber++; if (WebUtil.DebugLevel >= 3) m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} SynchronousRestObject {1} to {2}", reqnum, verb, requestUrl); int tickstart = Util.EnvironmentTickCount(); int tickdata = 0; Type type = typeof(TRequest); TResponse deserial = default(TResponse); WebRequest request = WebRequest.Create(requestUrl); HttpWebRequest ht = (HttpWebRequest)request; if (auth != null) auth.AddAuthorization(ht.Headers); if (pTimeout != 0) request.Timeout = pTimeout; if (maxConnections > 0 && ht.ServicePoint.ConnectionLimit < maxConnections) ht.ServicePoint.ConnectionLimit = maxConnections; request.Method = verb; MemoryStream buffer = null; try { if ((verb == "POST") || (verb == "PUT")) { request.ContentType = "text/xml"; buffer = new MemoryStream(); XmlWriterSettings settings = new XmlWriterSettings(); settings.Encoding = Encoding.UTF8; using (XmlWriter writer = XmlWriter.Create(buffer, settings)) { XmlSerializer serializer = new XmlSerializer(type); serializer.Serialize(writer, obj); writer.Flush(); } int length = (int)buffer.Length; request.ContentLength = length; byte[] data = buffer.ToArray(); if (WebUtil.DebugLevel >= 5) WebUtil.LogOutgoingDetail("SEND", reqnum, System.Text.Encoding.UTF8.GetString(data)); try { using (Stream requestStream = request.GetRequestStream()) requestStream.Write(data, 0, length); } catch (Exception e) { m_log.DebugFormat( "[SynchronousRestObjectRequester]: Exception in making request {0} {1}: {2}{3}", verb, requestUrl, e.Message, e.StackTrace); return deserial; } finally { // capture how much time was spent writing tickdata = Util.EnvironmentTickCountSubtract(tickstart); } } try { using (HttpWebResponse resp = (HttpWebResponse)request.GetResponse()) { if (resp.ContentLength != 0) { using (Stream respStream = resp.GetResponseStream()) { deserial = XMLResponseHelper.LogAndDeserialize<TRequest, TResponse>( reqnum, respStream, resp.ContentLength); } } else { m_log.DebugFormat( "[SynchronousRestObjectRequester]: Oops! no content found in response stream from {0} {1}", verb, requestUrl); } } } catch (WebException e) { using (HttpWebResponse hwr = (HttpWebResponse)e.Response) { if (hwr != null) { if (hwr.StatusCode == HttpStatusCode.NotFound) return deserial; if (hwr.StatusCode == HttpStatusCode.Unauthorized) { m_log.Error(string.Format( "[SynchronousRestObjectRequester]: Web request {0} requires authentication ", requestUrl)); return deserial; } } else m_log.Error(string.Format( "[SynchronousRestObjectRequester]: WebException for {0} {1} {2} ", verb, requestUrl, typeof(TResponse).ToString()), e); } } catch (System.InvalidOperationException) { // This is what happens when there is invalid XML m_log.DebugFormat( "[SynchronousRestObjectRequester]: Invalid XML from {0} {1} {2}", verb, requestUrl, typeof(TResponse).ToString()); } catch (Exception e) { m_log.Debug(string.Format( "[SynchronousRestObjectRequester]: Exception on response from {0} {1} ", verb, requestUrl), e); } int tickdiff = Util.EnvironmentTickCountSubtract(tickstart); if (tickdiff > WebUtil.LongCallTime) { string originalRequest = null; if (buffer != null) { originalRequest = Encoding.UTF8.GetString(buffer.ToArray()); if (originalRequest.Length > WebUtil.MaxRequestDiagLength) originalRequest = originalRequest.Remove(WebUtil.MaxRequestDiagLength); } m_log.InfoFormat( "[LOGHTTP]: Slow SynchronousRestObject request {0} {1} to {2} took {3}ms, {4}ms writing, {5}", reqnum, verb, requestUrl, tickdiff, tickdata, originalRequest); } else if (WebUtil.DebugLevel >= 4) { m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} took {1}ms, {2}ms writing", reqnum, tickdiff, tickdata); } } finally { if (buffer != null) buffer.Dispose(); } return deserial; } public static class XMLResponseHelper { public static TResponse LogAndDeserialize<TRequest, TResponse>(int reqnum, Stream respStream, long contentLength) { XmlSerializer deserializer = new XmlSerializer(typeof(TResponse)); if (WebUtil.DebugLevel >= 5) { byte[] data = new byte[contentLength]; Util.ReadStream(respStream, data); WebUtil.LogResponseDetail(reqnum, System.Text.Encoding.UTF8.GetString(data)); using (MemoryStream temp = new MemoryStream(data)) return (TResponse)deserializer.Deserialize(temp); } else { return (TResponse)deserializer.Deserialize(respStream); } } } } public static class XMLRPCRequester { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public static Hashtable SendRequest(Hashtable ReqParams, string method, string url) { int reqnum = WebUtil.RequestNumber++; if (WebUtil.DebugLevel >= 3) m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} XML-RPC '{1}' to {2}", reqnum, method, url); int tickstart = Util.EnvironmentTickCount(); string responseStr = null; try { ArrayList SendParams = new ArrayList(); SendParams.Add(ReqParams); XmlRpcRequest Req = new XmlRpcRequest(method, SendParams); if (WebUtil.DebugLevel >= 5) { string str = Req.ToString(); str = XElement.Parse(str).ToString(SaveOptions.DisableFormatting); WebUtil.LogOutgoingDetail("SEND", reqnum, str); } XmlRpcResponse Resp = Req.Send(url, 30000); try { responseStr = Resp.ToString(); responseStr = XElement.Parse(responseStr).ToString(SaveOptions.DisableFormatting); if (WebUtil.DebugLevel >= 5) WebUtil.LogResponseDetail(reqnum, responseStr); } catch (Exception e) { m_log.Error("Error parsing XML-RPC response", e); } if (Resp.IsFault) { m_log.DebugFormat( "[LOGHTTP]: XML-RPC request {0} '{1}' to {2} FAILED: FaultCode={3}, FaultMessage={4}", reqnum, method, url, Resp.FaultCode, Resp.FaultString); return null; } Hashtable RespData = (Hashtable)Resp.Value; return RespData; } finally { int tickdiff = Util.EnvironmentTickCountSubtract(tickstart); if (tickdiff > WebUtil.LongCallTime) { m_log.InfoFormat( "[LOGHTTP]: Slow XML-RPC request {0} '{1}' to {2} took {3}ms, {4}", reqnum, method, url, tickdiff, responseStr != null ? (responseStr.Length > WebUtil.MaxRequestDiagLength ? responseStr.Remove(WebUtil.MaxRequestDiagLength) : responseStr) : ""); } else if (WebUtil.DebugLevel >= 4) { m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} took {1}ms", reqnum, tickdiff); } } } } }
// Copyright (c) 1995-2009 held by the author(s). 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. // * Neither the names of the Naval Postgraduate School (NPS) // Modeling Virtual Environments and Simulation (MOVES) Institute // (http://www.nps.edu and http://www.MovesInstitute.org) // nor the names of its contributors may be used to endorse or // promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All // rights reserved. This work is licensed under the BSD open source license, // available at https://www.movesinstitute.org/licenses/bsd.html // // Author: DMcG // Modified for use with C#: // - Peter Smith (Naval Air Warfare Center - Training Systems Division) // - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si) using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; using System.Xml.Serialization; using OpenDis.Core; namespace OpenDis.Dis1998 { /// <summary> /// Section 5.2.8. Time measurements that exceed one hour. Hours is the number of hours since January 1, 1970, UTC /// </summary> [Serializable] [XmlRoot] public partial class ClockTime { /// <summary> /// Hours in UTC /// </summary> private int _hour; /// <summary> /// Time past the hour /// </summary> private uint _timePastHour; /// <summary> /// Initializes a new instance of the <see cref="ClockTime"/> class. /// </summary> public ClockTime() { } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if operands are not equal; otherwise, <c>false</c>. /// </returns> public static bool operator !=(ClockTime left, ClockTime right) { return !(left == right); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public static bool operator ==(ClockTime left, ClockTime right) { if (object.ReferenceEquals(left, right)) { return true; } if (((object)left == null) || ((object)right == null)) { return false; } return left.Equals(right); } public virtual int GetMarshalledSize() { int marshalSize = 0; marshalSize += 4; // this._hour marshalSize += 4; // this._timePastHour return marshalSize; } /// <summary> /// Gets or sets the Hours in UTC /// </summary> [XmlElement(Type = typeof(int), ElementName = "hour")] public int Hour { get { return this._hour; } set { this._hour = value; } } /// <summary> /// Gets or sets the Time past the hour /// </summary> [XmlElement(Type = typeof(uint), ElementName = "timePastHour")] public uint TimePastHour { get { return this._timePastHour; } set { this._timePastHour = value; } } /// <summary> /// Occurs when exception when processing PDU is caught. /// </summary> public event EventHandler<PduExceptionEventArgs> ExceptionOccured; /// <summary> /// Called when exception occurs (raises the <see cref="Exception"/> event). /// </summary> /// <param name="e">The exception.</param> protected void RaiseExceptionOccured(Exception e) { if (Pdu.FireExceptionEvents && this.ExceptionOccured != null) { this.ExceptionOccured(this, new PduExceptionEventArgs(e)); } } /// <summary> /// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method /// </summary> /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public virtual void Marshal(DataOutputStream dos) { if (dos != null) { try { dos.WriteInt((int)this._hour); dos.WriteUnsignedInt((uint)this._timePastHour); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public virtual void Unmarshal(DataInputStream dis) { if (dis != null) { try { this._hour = dis.ReadInt(); this._timePastHour = dis.ReadUnsignedInt(); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } /// <summary> /// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging. /// This will be modified in the future to provide a better display. Usage: /// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb }); /// where pdu is an object representing a single pdu and sb is a StringBuilder. /// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality /// </summary> /// <param name="sb">The StringBuilder instance to which the PDU is written to.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public virtual void Reflection(StringBuilder sb) { sb.AppendLine("<ClockTime>"); try { sb.AppendLine("<hour type=\"int\">" + this._hour.ToString(CultureInfo.InvariantCulture) + "</hour>"); sb.AppendLine("<timePastHour type=\"uint\">" + this._timePastHour.ToString(CultureInfo.InvariantCulture) + "</timePastHour>"); sb.AppendLine("</ClockTime>"); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { return this == obj as ClockTime; } /// <summary> /// Compares for reference AND value equality. /// </summary> /// <param name="obj">The object to compare with this instance.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public bool Equals(ClockTime obj) { bool ivarsEqual = true; if (obj.GetType() != this.GetType()) { return false; } if (this._hour != obj._hour) { ivarsEqual = false; } if (this._timePastHour != obj._timePastHour) { ivarsEqual = false; } return ivarsEqual; } /// <summary> /// HashCode Helper /// </summary> /// <param name="hash">The hash value.</param> /// <returns>The new hash value.</returns> private static int GenerateHash(int hash) { hash = hash << (5 + hash); return hash; } /// <summary> /// Gets the hash code. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { int result = 0; result = GenerateHash(result) ^ this._hour.GetHashCode(); result = GenerateHash(result) ^ this._timePastHour.GetHashCode(); return result; } } }
// =========================================================== // Copyright (c) 2014-2015, Enrico Da Ros/kendar.org // 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 SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // =========================================================== using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace UserManager.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
using Microsoft.IdentityModel; using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.S2S.Tokens; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.EventReceivers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Script.Serialization; using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction; using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException; using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration; using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials; namespace IOER { public static class TokenHelper { #region public methods /// <summary> /// Configures .Net to trust all certificates when making network calls. This is used so that calls /// to an https SharePoint server without a valid certificate are not rejected. This should only be used during /// testing, and should never be used in a production app. /// </summary> public static void TrustAllCertificates() { //Trust all certificates ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true); } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequest request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) return request.Form[paramName]; if (!string.IsNullOrEmpty(request.QueryString[paramName])) return request.QueryString[paramName]; } return null; } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequestBase request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) return request.Form[paramName]; if (!string.IsNullOrEmpty(request.QueryString[paramName])) return request.QueryString[paramName]; } return null; } /// <summary> /// Validate that a specified context token string is intended for this application based on the parameters /// specified in web.config. Parameters used from web.config used for validation include ClientId, /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present, /// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents /// and a JsonWebSecurityToken based on the context token is returned. /// </summary> /// <param name="contextTokenString">The context token to validate</param> /// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation. /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used /// for validation instead of <paramref name="appHostName"/> .</param> /// <returns>A JsonWebSecurityToken based on the context token.</returns> public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null) { JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler(); SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString); JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken; SharePointContextToken token = SharePointContextToken.Create(jsonToken); string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority; int firstDot = stsAuthority.IndexOf('.'); GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot); AcsHostUrl = stsAuthority.Substring(firstDot + 1); tokenHandler.ValidateToken(jsonToken); string[] acceptableAudiences; if (!String.IsNullOrEmpty(HostedAppHostNameOverride)) { acceptableAudiences = HostedAppHostNameOverride.Split(';'); } else if (appHostName == null) { acceptableAudiences = new[] { HostedAppHostName }; } else { acceptableAudiences = new[] { appHostName }; } bool validationSuccessful = false; string realm = Realm ?? token.Realm; foreach (var audience in acceptableAudiences) { string principal = GetFormattedPrincipal(ClientId, audience, realm); if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal)) { validationSuccessful = true; break; } } if (!validationSuccessful) { throw new AudienceUriValidationFailedException( String.Format(CultureInfo.CurrentCulture, "\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience)); } return token; } /// <summary> /// Retrieves an access token from ACS to call the source of the specified context token at the specified /// targetHost. The targetHost must be registered for the principal that sent the context token. /// </summary> /// <param name="contextToken">Context token issued by the intended access token audience</param> /// <param name="targetHost">Url authority of the target principal</param> /// <returns>An access token with an audience matching the context token's source</returns> public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost) { string targetPrincipalName = contextToken.TargetPrincipalName; // Extract the refreshToken from the context token string refreshToken = contextToken.RefreshToken; if (String.IsNullOrEmpty(refreshToken)) { return null; } string targetRealm = Realm ?? contextToken.Realm; return GetAccessToken(refreshToken, targetPrincipalName, targetHost, targetRealm); } /// <summary> /// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="authorizationCode">Authorization code to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string authorizationCode, string targetPrincipalName, string targetHost, string targetRealm, Uri redirectUri) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); // Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode( clientId, ClientSecret, authorizationCode, redirectUri, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="refreshToken">Refresh token to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string refreshToken, string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Retrieves an app-only access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAppOnlyAccessToken( string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource); oauth2Request.Resource = resource; // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Creates a client context based on the properties of a remote event receiver /// </summary> /// <param name="properties">Properties of a remote event receiver</param> /// <returns>A ClientContext ready to call the web where the event originated</returns> public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties) { Uri sharepointUrl; if (properties.ListEventProperties != null) { sharepointUrl = new Uri(properties.ListEventProperties.WebUrl); } else if (properties.ItemEventProperties != null) { sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl); } else if (properties.WebEventProperties != null) { sharepointUrl = new Uri(properties.WebEventProperties.FullUrl); } else { return null; } if (ClientCertificate != null) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Creates a client context based on the properties of an app event /// </summary> /// <param name="properties">Properties of an app event</param> /// <param name="useAppWeb">True to target the app web, false to target the host web</param> /// <returns>A ClientContext ready to call the app web or the parent web</returns> public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb) { if (properties.AppEventProperties == null) { return null; } Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl; if (ClientCertificate != null) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string authorizationCode, Uri redirectUri) { return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="targetPrincipalName">Name of the target SharePoint principal</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string targetPrincipalName, string authorizationCode, string targetRealm, Uri redirectUri) { Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Uses the specified access token to create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="accessToken">Access token to be used when calling the specified targetUrl</param> /// <returns>A ClientContext ready to call targetUrl with the specified access token</returns> public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken) { ClientContext clientContext = new ClientContext(targetUrl); clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous; clientContext.FormDigestHandlingEnabled = false; clientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs) { webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken; }; return clientContext; } /// <summary> /// Retrieves an access token from ACS using the specified context token, and uses that access token to create /// a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="contextTokenString">Context token received from the target SharePoint site</param> /// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName /// of web.config will be used instead</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithContextToken( string targetUrl, string contextTokenString, string appHostUrl) { SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl); Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is /// granted</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope, redirectUri); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request a new context token. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param> /// <returns>Url of the SharePoint site's context token redirect page</returns> public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri) { return string.Format( "{0}{1}?client_id={2}&redirect_uri={3}", EnsureTrailingSlash(contextUrl), RedirectPage, ClientId, redirectUri); } /// <summary> /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>An access token with an audience of the target principal</returns> public static string GetS2SAccessTokenWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); } /// <summary> /// Retrieves an S2S client context with an access token signed by the application's private certificate on /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the /// targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>A ClientContext using an access token with an audience of the target application</returns> public static ClientContext GetS2SClientContextWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken); } /// <summary> /// Get authentication realm from SharePoint /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <returns>String representation of the realm GUID</returns> public static string GetRealmFromTargetUrl(Uri targetApplicationUri) { WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc"); request.Headers.Add("Authorization: Bearer "); try { using (request.GetResponse()) { } } catch (WebException e) { string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"]; const string bearer = "Bearer realm=\""; int realmIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal) + bearer.Length; if (bearerResponseHeader.Length > realmIndex) { string targetRealm = bearerResponseHeader.Substring(realmIndex, 36); Guid realmGuid; if (Guid.TryParse(targetRealm, out realmGuid)) { return targetRealm; } } } return null; } #endregion #region private fields // // Configuration Constants // private const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"; private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx"; private const string RedirectPage = "_layouts/15/AppRedirect.aspx"; private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000"; private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1"; private const string S2SProtocol = "OAuth2"; private const string DelegationIssuance = "DelegationIssuance1.0"; private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier; private const string TrustedForImpersonationClaimType = "trustedfordelegation"; private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken; private const int TokenLifetimeMinutes = 1000000; // // Environment Constants // private static string GlobalEndPointPrefix = "accounts"; private static string AcsHostUrl = "accesscontrol.windows.net"; // // Hosted app configuration // private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId"); private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId"); private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride"); private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName"); private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret"); private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret"); private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath"); private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword"); private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword); private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); #endregion #region private methods private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl) { string contextTokenString = properties.ContextToken; if (String.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host); string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken; return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken); } private static string GetAcsMetadataEndpointUrl() { return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl); } private static string GetFormattedPrincipal(string principalName, string hostName, string realm) { if (!String.IsNullOrEmpty(hostName)) { return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm); } return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm); } private static string GetAcsPrincipalName(string realm) { return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm); } private static string GetAcsGlobalEndpointUrl() { return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl); } private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler() { JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never); handler.Configuration.CertificateValidator = X509CertificateValidator.None; List<byte[]> securityKeys = new List<byte[]>(); securityKeys.Add(Convert.FromBase64String(ClientSecret)); if (!string.IsNullOrEmpty(SecondaryClientSecret)) { securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret)); } List<SecurityToken> securityTokens = new List<SecurityToken>(); securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys)); handler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection<SecurityToken>(securityTokens), false); SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry(); foreach (byte[] securitykey in securityKeys) { issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace)); } handler.Configuration.IssuerNameRegistry = issuerNameRegistry; return handler; } private static string GetS2SAccessTokenWithClaims( string targetApplicationHostName, string targetRealm, IEnumerable<JsonWebTokenClaim> claims) { return IssueToken( ClientId, IssuerId, targetRealm, SharePointPrincipal, targetRealm, targetApplicationHostName, true, claims, claims == null); } private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity) { JsonWebTokenClaim[] claims = new JsonWebTokenClaim[] { new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()), new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory") }; return claims; } private static string IssueToken( string sourceApplication, string issuerApplication, string sourceRealm, string targetApplication, string targetRealm, string targetApplicationHostName, bool trustedForDelegation, IEnumerable<JsonWebTokenClaim> claims, bool appOnly = false) { if (null == SigningCredentials) { throw new InvalidOperationException("SigningCredentials was not initialized"); } #region Actor token string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm); string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm); string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm); List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>(); actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid)); if (trustedForDelegation && !appOnly) { actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true")); } // Create token JsonWebSecurityToken actorToken = new JsonWebSecurityToken( issuer: issuer, audience: audience, validFrom: DateTime.UtcNow, validTo: DateTime.UtcNow.AddMinutes(TokenLifetimeMinutes), signingCredentials: SigningCredentials, claims: actorClaims); string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken); if (appOnly) { // App-only token is the same as actor token for delegated case return actorTokenString; } #endregion Actor token #region Outer token List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims); outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString)); JsonWebSecurityToken jsonToken = new JsonWebSecurityToken( nameid, // outer token issuer should match actor token nameid audience, DateTime.UtcNow, DateTime.UtcNow.AddMinutes(10), outerClaims); string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken); #endregion Outer token return accessToken; } private static string EnsureTrailingSlash(string url) { if (!String.IsNullOrEmpty(url) && url[url.Length - 1] != '/') { return url + "/"; } return url; } #endregion #region AcsMetadataParser // This class is used to get MetaData document from the global STS endpoint. It contains // methods to parse the MetaData document and get endpoints and STS certificate. public static class AcsMetadataParser { public static X509Certificate2 GetAcsSigningCert(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); if (null != document.keys && document.keys.Count > 0) { JsonKey signingKey = document.keys[0]; if (null != signingKey && null != signingKey.keyValue) { return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value)); } } throw new Exception("Metadata document does not contain ACS signing certificate."); } public static string GetDelegationServiceUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance); if (null != delegationEndpoint) { return delegationEndpoint.location; } throw new Exception("Metadata document does not contain Delegation Service endpoint Url"); } private static JsonMetadataDocument GetMetadataDocument(string realm) { string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}", GetAcsMetadataEndpointUrl(), realm); byte[] acsMetadata; using (WebClient webClient = new WebClient()) { acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm); } string jsonResponseString = Encoding.UTF8.GetString(acsMetadata); JavaScriptSerializer serializer = new JavaScriptSerializer(); JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString); if (null == document) { throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm); } return document; } public static string GetStsUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol); if (null != s2sEndpoint) { return s2sEndpoint.location; } throw new Exception("Metadata document does not contain STS endpoint url"); } private class JsonMetadataDocument { public string serviceName { get; set; } public List<JsonEndpoint> endpoints { get; set; } public List<JsonKey> keys { get; set; } } private class JsonEndpoint { public string location { get; set; } public string protocol { get; set; } public string usage { get; set; } } private class JsonKeyValue { public string type { get; set; } public string value { get; set; } } private class JsonKey { public string usage { get; set; } public JsonKeyValue keyValue { get; set; } } } #endregion } /// <summary> /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token /// </summary> public class SharePointContextToken : JsonWebSecurityToken { public static SharePointContextToken Create(JsonWebSecurityToken contextToken) { return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims); } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims) : base(issuer, audience, validFrom, validTo, claims) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken) : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials) : base(issuer, audience, validFrom, validTo, claims, signingCredentials) { } public string NameId { get { return GetClaimValue(this, "nameid"); } } /// <summary> /// The principal name portion of the context token's "appctxsender" claim /// </summary> public string TargetPrincipalName { get { string appctxsender = GetClaimValue(this, "appctxsender"); if (appctxsender == null) { return null; } return appctxsender.Split('@')[0]; } } /// <summary> /// The context token's "refreshtoken" claim /// </summary> public string RefreshToken { get { return GetClaimValue(this, "refreshtoken"); } } /// <summary> /// The context token's "CacheKey" claim /// </summary> public string CacheKey { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string cacheKey = (string)dict["CacheKey"]; return cacheKey; } } /// <summary> /// The context token's "SecurityTokenServiceUri" claim /// </summary> public string SecurityTokenServiceUri { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"]; return securityTokenServiceUri; } } /// <summary> /// The realm portion of the context token's "audience" claim /// </summary> public string Realm { get { string aud = Audience; if (aud == null) { return null; } string tokenRealm = aud.Substring(aud.IndexOf('@') + 1); return tokenRealm; } } private static string GetClaimValue(JsonWebSecurityToken token, string claimType) { if (token == null) { throw new ArgumentNullException("token"); } foreach (JsonWebTokenClaim claim in token.Claims) { if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType)) { return claim.Value; } } return null; } } public class OAuthTokenPair { public string AccessToken; public string RefreshToken; } /// <summary> /// Represents a security token which contains multiple security keys that are generated using symmetric algorithms. /// </summary> public class MultipleSymmetricKeySecurityToken : SecurityToken { /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys) : this(UniqueId.CreateUniqueId(), keys) { } /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="tokenId">The unique identifier of the security token.</param> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys) { if (keys == null) { throw new ArgumentNullException("keys"); } if (String.IsNullOrEmpty(tokenId)) { throw new ArgumentException("Value cannot be a null or empty string.", "tokenId"); } foreach (byte[] key in keys) { if (key.Length <= 0) { throw new ArgumentException("The key length must be greater then zero.", "keys"); } } id = tokenId; effectiveTime = DateTime.UtcNow; securityKeys = CreateSymmetricSecurityKeys(keys); } /// <summary> /// Gets the unique identifier of the security token. /// </summary> public override string Id { get { return id; } } /// <summary> /// Gets the cryptographic keys associated with the security token. /// </summary> public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { return securityKeys.AsReadOnly(); } } /// <summary> /// Gets the first instant in time at which this security token is valid. /// </summary> public override DateTime ValidFrom { get { return effectiveTime; } } /// <summary> /// Gets the last instant in time at which this security token is valid. /// </summary> public override DateTime ValidTo { get { // Never expire return DateTime.MaxValue; } } /// <summary> /// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier. /// </summary> /// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param> /// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns> public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw new ArgumentNullException("keyIdentifierClause"); } // Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the // presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later // when the key is matched to the issuer. if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause) { return true; } return base.MatchesKeyIdentifierClause(keyIdentifierClause); } #region private members private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys) { List<SecurityKey> symmetricKeys = new List<SecurityKey>(); foreach (byte[] key in keys) { symmetricKeys.Add(new InMemorySymmetricSecurityKey(key)); } return symmetricKeys; } private string id; private DateTime effectiveTime; private List<SecurityKey> securityKeys; #endregion } }
#region License /* ********************************************************************************** * Copyright (c) Roman Ivantsov * This source code is subject to terms and conditions of the MIT License * for Irony. A copy of the license can be found in the License.txt file * at the root of this distribution. * By using this source code in any fashion, you are agreeing to be bound by the terms of the * MIT License. * You must not remove this notice from this software. * **********************************************************************************/ #endregion using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using System.Diagnostics; using System.Globalization; namespace Irony.Parsing { [Flags] public enum ParseOptions { GrammarDebugging = 0x01, TraceParser = 0x02, AnalyzeCode = 0x10, //run code analysis; effective only in Module mode } public enum ParseMode { File, //default, continuous input file VsLineScan, // line-by-line scanning in VS integration for syntax highlighting CommandLine, //line-by-line from console } public enum ParserStatus { Init, //initial state Parsing, Previewing, //previewing tokens Recovering, //recovering from error Accepted, AcceptedPartial, Error, } // The purpose of this class is to provide a container for information shared // between parser, scanner and token filters. public class ParsingContext { public readonly Parser Parser; public readonly LanguageData Language; //Parser settings public ParseOptions Options; public ParseMode Mode = ParseMode.File; public int MaxErrors = 20; //maximum error count to report public CultureInfo Culture; //defaults to Grammar.DefaultCulture, might be changed by app code #region properties and fields //Parser fields public ParserState CurrentParserState { get; internal set; } public ParseTreeNode CurrentParserInput { get; internal set; } internal readonly ParserStack ParserStack = new ParserStack(); internal readonly ParserStack ParserInputStack = new ParserStack(); public ParseTree CurrentParseTree { get; internal set; } public readonly TokenStack OpenBraces = new TokenStack(); public ParserTrace ParserTrace = new ParserTrace(); public ISourceStream Source { get { return SourceStream; } } //list for terminals - for current parser state and current input char public TerminalList CurrentTerminals = new TerminalList(); public Token CurrentToken; //The token just scanned by Scanner public Token PreviousToken; public SourceLocation PreviousLineStart; //Location of last line start //Internal fields internal SourceStream SourceStream; internal TokenFilterList TokenFilters = new TokenFilterList(); internal TokenStack BufferedTokens = new TokenStack(); internal IEnumerator<Token> FilteredTokens; //stream of tokens after filter internal TokenStack PreviewTokens = new TokenStack(); internal ParsingEventArgs SharedParsingEventArgs; public VsScannerStateMap VsLineScanState; //State variable used in line scanning mode for VS integration public ParserStatus Status {get; internal set;} public bool HasErrors; //error flag, once set remains set //values dictionary to use by custom language implementations to save some temporary values in parse process public readonly Dictionary<string, object> Values = new Dictionary<string, object>(); public int TabWidth { get { return _tabWidth; } set { _tabWidth = value; if (SourceStream != null) SourceStream.TabWidth = value; } } int _tabWidth = 8; #endregion #region constructors public ParsingContext(Parser parser) { this.Parser = parser; Language = Parser.Language; Culture = Language.Grammar.DefaultCulture; //This might be a problem for multi-threading - if we have several contexts on parallel threads with different culture. //Resources.Culture is static property (this is not Irony's fault, this is auto-generated file). Resources.Culture = Culture; //We assume that if Irony is compiled in Debug mode, then developer is debugging his grammar/language implementation #if DEBUG Options |= ParseOptions.GrammarDebugging; #endif SharedParsingEventArgs = new ParsingEventArgs(this); } #endregion #region Events: TokenCreated public event EventHandler<ParsingEventArgs> TokenCreated; internal void OnTokenCreated() { if (TokenCreated != null) TokenCreated(this, SharedParsingEventArgs); } #endregion #region Options helper methods public bool OptionIsSet(ParseOptions option) { return (Options & option) != 0; } public void SetOption(ParseOptions option, bool value) { if (value) Options |= option; else Options &= ~option; } #endregion #region Error handling and tracing public void AddParserError(string message, params object[] args) { var location = CurrentParserInput == null? Source.Location : CurrentParserInput.Span.Location; HasErrors = true; AddParserMessage(ParserErrorLevel.Error, location, message, args); } public void AddParserMessage(ParserErrorLevel level, SourceLocation location, string message, params object[] args) { if (CurrentParseTree == null) return; if (CurrentParseTree.ParserMessages.Count >= MaxErrors) return; if (args != null && args.Length > 0) message = string.Format(message, args); CurrentParseTree.ParserMessages.Add(new ParserMessage(level, location, message, CurrentParserState)); if (OptionIsSet(ParseOptions.TraceParser)) ParserTrace.Add( new ParserTraceEntry(CurrentParserState, ParserStack.Top, CurrentParserInput, message, true)); } public void AddTrace(string message, params object[] args) { if (!OptionIsSet(ParseOptions.TraceParser)) return; if (args != null && args.Length > 0) message = string.Format(message, args); ParserTrace.Add(new ParserTraceEntry(CurrentParserState, ParserStack.Top, CurrentParserInput, message, false)); } #endregion internal void Reset() { CurrentParserState = Parser.InitialState; CurrentParserInput = null; ParserStack.Clear(); HasErrors = false; ParserStack.Push(new ParseTreeNode(CurrentParserState)); ParserInputStack.Clear(); CurrentParseTree = null; OpenBraces.Clear(); ParserTrace.Clear(); CurrentTerminals.Clear(); CurrentToken = null; PreviousToken = null; PreviousLineStart = new SourceLocation(0, -1, 0); BufferedTokens.Clear(); PreviewTokens.Clear(); Values.Clear(); foreach (var filter in TokenFilters) filter.Reset(); } public void SetSourceLocation(SourceLocation location) { foreach (var filter in TokenFilters) filter.OnSetSourceLocation(location); SourceStream.Location = location; } #region Expected term set computations public StringSet GetExpectedTermSet() { if (CurrentParserState == null) return new StringSet(); //See note about multi-threading issues in ComputeReportedExpectedSet comments. if (CurrentParserState.ReportedExpectedSet == null) CurrentParserState.ReportedExpectedSet = CoreParser.ComputeGroupedExpectedSetForState(Language.Grammar, CurrentParserState); //Filter out closing braces which are not expected based on previous input. // While the closing parenthesis ")" might be expected term in a state in general, // if there was no opening parenthesis in preceding input then we would not // expect a closing one. var expectedSet = FilterBracesInExpectedSet(CurrentParserState.ReportedExpectedSet); return expectedSet; } private StringSet FilterBracesInExpectedSet(StringSet stateExpectedSet) { var result = new StringSet(); result.UnionWith(stateExpectedSet); //Find what brace we expect var nextClosingBrace = string.Empty; if (OpenBraces.Count > 0) { var lastOpenBraceTerm = OpenBraces.Peek().KeyTerm; var nextClosingBraceTerm = lastOpenBraceTerm.IsPairFor as KeyTerm; if (nextClosingBraceTerm != null) nextClosingBrace = nextClosingBraceTerm.Text; } //Now check all closing braces in result set, and leave only nextClosingBrace foreach(var closingBrace in Language.GrammarData.ClosingBraces) { if (result.Contains(closingBrace) && closingBrace != nextClosingBrace) result.Remove(closingBrace); } return result; } #endregion }//class // A struct used for packing/unpacking ScannerState int value; used for VS integration. // When Terminal produces incomplete token, it sets // this state to non-zero value; this value identifies this terminal as the one who will continue scanning when // it resumes, and the terminal's internal state when there may be several types of multi-line tokens for one terminal. // For ex., there maybe several types of string literal like in Python. [StructLayout(LayoutKind.Explicit)] public struct VsScannerStateMap { [FieldOffset(0)] public int Value; [FieldOffset(0)] public byte TerminalIndex; //1-based index of active multiline term in MultilineTerminals [FieldOffset(1)] public byte TokenSubType; //terminal subtype (used in StringLiteral to identify string kind) [FieldOffset(2)] public short TerminalFlags; //Terminal flags }//struct }
// // ConsoleCrayon.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2008 Novell, Inc. // // 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; namespace Hyena { public static class ConsoleCrayon { #region Public API private static ConsoleColor foreground_color; public static ConsoleColor ForegroundColor { get { return foreground_color; } set { foreground_color = value; SetColor (foreground_color, true); } } private static ConsoleColor background_color; public static ConsoleColor BackgroundColor { get { return background_color; } set { background_color = value; SetColor (background_color, false); } } public static void ResetColor () { if (XtermColors) { Console.Write (GetAnsiResetControlCode ()); } else if (Environment.OSVersion.Platform != PlatformID.Unix && !RuntimeIsMono) { Console.ResetColor (); } } private static void SetColor (ConsoleColor color, bool isForeground) { if (color < ConsoleColor.Black || color > ConsoleColor.White) { throw new ArgumentOutOfRangeException ("color", "Not a ConsoleColor value."); } if (XtermColors) { Console.Write (GetAnsiColorControlCode (color, isForeground)); } else if (Environment.OSVersion.Platform != PlatformID.Unix && !RuntimeIsMono) { if (isForeground) { Console.ForegroundColor = color; } else { Console.BackgroundColor = color; } } } #endregion #region Ansi/VT Code Calculation // Modified from Mono's System.TermInfoDriver // License: MIT/X11 // Authors: Gonzalo Paniagua Javier <gonzalo@ximian.com> // (C) 2005-2006 Novell, Inc <http://www.novell.com> private static int TranslateColor (ConsoleColor desired, out bool light) { light = false; switch (desired) { // Dark colors case ConsoleColor.Black: return 0; case ConsoleColor.DarkRed: return 1; case ConsoleColor.DarkGreen: return 2; case ConsoleColor.DarkYellow: return 3; case ConsoleColor.DarkBlue: return 4; case ConsoleColor.DarkMagenta: return 5; case ConsoleColor.DarkCyan: return 6; case ConsoleColor.Gray: return 7; // Light colors case ConsoleColor.DarkGray: light = true; return 0; case ConsoleColor.Red: light = true; return 1; case ConsoleColor.Green: light = true; return 2; case ConsoleColor.Yellow: light = true; return 3; case ConsoleColor.Blue: light = true; return 4; case ConsoleColor.Magenta: light = true; return 5; case ConsoleColor.Cyan: light = true; return 6; case ConsoleColor.White: default: light = true; return 7; } } private static string GetAnsiColorControlCode (ConsoleColor color, bool isForeground) { // lighter fg colours are 90 -> 97 rather than 30 -> 37 // lighter bg colours are 100 -> 107 rather than 40 -> 47 bool light; int code = TranslateColor (color, out light) + (isForeground ? 30 : 40) + (light ? 60 : 0); return String.Format ("\x001b[{0}m", code); } private static string GetAnsiResetControlCode () { return "\x001b[0m"; } #endregion #region xterm Detection private static bool? xterm_colors = null; public static bool XtermColors { get { if (xterm_colors == null) { DetectXtermColors (); } return xterm_colors.Value; } } [System.Runtime.InteropServices.DllImport ("libc", EntryPoint="isatty")] private extern static int _isatty (int fd); private static bool isatty (int fd) { try { return _isatty (fd) == 1; } catch { return false; } } private static void DetectXtermColors () { bool _xterm_colors = false; switch (Environment.GetEnvironmentVariable ("TERM")) { case "xterm": case "rxvt": case "rxvt-unicode": if (Environment.GetEnvironmentVariable ("COLORTERM") != null) { _xterm_colors = true; } break; case "xterm-color": _xterm_colors = true; break; } xterm_colors = _xterm_colors && isatty (1) && isatty (2); } #endregion #region Runtime Detection private static bool? runtime_is_mono; public static bool RuntimeIsMono { get { if (runtime_is_mono == null) { runtime_is_mono = Type.GetType ("System.MonoType") != null; } return runtime_is_mono.Value; } } #endregion #region Tests public static void Test () { TestSelf (); Console.WriteLine (); TestAnsi (); Console.WriteLine (); TestRuntime (); } private static void TestSelf () { Console.WriteLine ("==SELF TEST=="); foreach (ConsoleColor color in Enum.GetValues (typeof (ConsoleColor))) { ForegroundColor = color; Console.Write (color); ResetColor (); Console.Write (" :: "); BackgroundColor = color; Console.Write (color); ResetColor (); Console.WriteLine (); } } private static void TestAnsi () { Console.WriteLine ("==ANSI TEST=="); foreach (ConsoleColor color in Enum.GetValues (typeof (ConsoleColor))) { string color_code_fg = GetAnsiColorControlCode (color, true); string color_code_bg = GetAnsiColorControlCode (color, false); Console.Write ("{0}{1}: {2}{3} :: {4}{1}: {5}{3}", color_code_fg, color, color_code_fg.Substring (2), GetAnsiResetControlCode (), color_code_bg, color_code_bg.Substring (2)); Console.WriteLine (); } } private static void TestRuntime () { Console.WriteLine ("==RUNTIME TEST=="); foreach (ConsoleColor color in Enum.GetValues (typeof (ConsoleColor))) { Console.ForegroundColor = color; Console.Write (color); Console.ResetColor (); Console.Write (" :: "); Console.BackgroundColor = color; Console.Write (color); Console.ResetColor (); Console.WriteLine (); } } #endregion } }
/*=============================================================================================== Record to disk example Copyright (c), Firelight Technologies Pty, Ltd 2004-2011. This example shows how to do a streaming record to disk. ===============================================================================================*/ using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Text; using System.Runtime.InteropServices; using System.IO; namespace recordtodisk { public class recordtodisk : System.Windows.Forms.Form { private FMOD.System system = null; private FMOD.Sound sound = null; private bool recording = false; private FileStream fs = null; private uint soundlength = 0; private uint lastrecordpos = 0; private int datalength = 0; private int selected = 0; private System.Windows.Forms.Label label; private System.Windows.Forms.ComboBox comboBoxRecord; private System.Windows.Forms.Timer timer; private System.Windows.Forms.Button exit_button; private System.Windows.Forms.StatusBar statusBar; private System.Windows.Forms.Button start; private System.Windows.Forms.ComboBox comboBoxOutput; private System.Windows.Forms.Button stop; private System.ComponentModel.IContainer components; public recordtodisk() { InitializeComponent(); } protected override void Dispose( bool disposing ) { /* Write back the wav header now that we know its length. */ if (recording) { recording = false; WriteWavHeader(datalength); } if( disposing ) { FMOD.RESULT result; /* Shut down */ if (sound != null) { result = sound.release(); ERRCHECK(result); } if (system != null) { result = system.close(); ERRCHECK(result); result = system.release(); ERRCHECK(result); } if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.label = new System.Windows.Forms.Label(); this.comboBoxRecord = new System.Windows.Forms.ComboBox(); this.timer = new System.Windows.Forms.Timer(this.components); this.exit_button = new System.Windows.Forms.Button(); this.statusBar = new System.Windows.Forms.StatusBar(); this.start = new System.Windows.Forms.Button(); this.comboBoxOutput = new System.Windows.Forms.ComboBox(); this.stop = new System.Windows.Forms.Button(); this.SuspendLayout(); // // label // this.label.Location = new System.Drawing.Point(8, 8); this.label.Name = "label"; this.label.Size = new System.Drawing.Size(264, 32); this.label.TabIndex = 7; this.label.Text = "Copyright (c) Firelight Technologies 2004-2011"; this.label.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // comboBoxRecord // this.comboBoxRecord.Location = new System.Drawing.Point(16, 72); this.comboBoxRecord.Name = "comboBoxRecord"; this.comboBoxRecord.Size = new System.Drawing.Size(248, 21); this.comboBoxRecord.TabIndex = 10; this.comboBoxRecord.Text = "Select RECORD driver"; this.comboBoxRecord.SelectedIndexChanged += new System.EventHandler(this.comboBoxRecord_SelectedIndexChanged); // // timer // this.timer.Enabled = true; this.timer.Interval = 10; this.timer.Tick += new System.EventHandler(this.timer_Tick); // // exit_button // this.exit_button.Location = new System.Drawing.Point(96, 144); this.exit_button.Name = "exit_button"; this.exit_button.Size = new System.Drawing.Size(72, 24); this.exit_button.TabIndex = 16; this.exit_button.Text = "Exit"; this.exit_button.Click += new System.EventHandler(this.exit_button_Click); // // statusBar // this.statusBar.Location = new System.Drawing.Point(0, 171); this.statusBar.Name = "statusBar"; this.statusBar.Size = new System.Drawing.Size(272, 24); this.statusBar.TabIndex = 17; // // start // this.start.Location = new System.Drawing.Point(16, 104); this.start.Name = "start"; this.start.Size = new System.Drawing.Size(128, 32); this.start.TabIndex = 18; this.start.Text = "Start recording to record.wav"; this.start.Click += new System.EventHandler(this.start_Click); // // comboBoxOutput // this.comboBoxOutput.Location = new System.Drawing.Point(16, 40); this.comboBoxOutput.Name = "comboBoxOutput"; this.comboBoxOutput.Size = new System.Drawing.Size(248, 21); this.comboBoxOutput.TabIndex = 19; this.comboBoxOutput.Text = "Select OUTPUT type"; this.comboBoxOutput.SelectedIndexChanged += new System.EventHandler(this.comboBoxOutput_SelectedIndexChanged); // // stop // this.stop.Location = new System.Drawing.Point(152, 104); this.stop.Name = "stop"; this.stop.Size = new System.Drawing.Size(104, 32); this.stop.TabIndex = 20; this.stop.Text = "Stop"; this.stop.Click += new System.EventHandler(this.stop_Click); // // recordtodisk // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(272, 195); this.Controls.Add(this.stop); this.Controls.Add(this.comboBoxOutput); this.Controls.Add(this.start); this.Controls.Add(this.statusBar); this.Controls.Add(this.exit_button); this.Controls.Add(this.comboBoxRecord); this.Controls.Add(this.label); this.Name = "recordtodisk"; this.Text = "Record To Disk Example"; this.Load += new System.EventHandler(this.recordtodisk_Load); this.ResumeLayout(false); } #endregion [STAThread] static void Main() { Application.Run(new recordtodisk()); } private void recordtodisk_Load(object sender, System.EventArgs e) { uint version = 0; FMOD.RESULT result; comboBoxOutput.Enabled = true; comboBoxRecord.Enabled = false; start.Enabled = false; /* Create a System object and initialize. */ result = FMOD.Factory.System_Create(ref system); ERRCHECK(result); result = system.getVersion(ref version); ERRCHECK(result); if (version < FMOD.VERSION.number) { MessageBox.Show("Error! You are using an old version of FMOD " + version.ToString("X") + ". This program requires " + FMOD.VERSION.number.ToString("X") + "."); Application.Exit(); } /* Get output modes */ comboBoxOutput.Items.Add("DirectSound"); comboBoxOutput.Items.Add("Windows Multimedia WaveOut"); comboBoxOutput.Items.Add("ASIO"); } private void comboBoxOutput_SelectedIndexChanged(object sender, System.EventArgs e) { FMOD.RESULT result = FMOD.RESULT.OK; StringBuilder drivername = new StringBuilder(256); int numdrivers = 0; FMOD.GUID guid = new FMOD.GUID(); switch (comboBoxOutput.SelectedIndex) { case 0: result = system.setOutput(FMOD.OUTPUTTYPE.DSOUND); break; case 1: result = system.setOutput(FMOD.OUTPUTTYPE.WINMM); break; case 2: result = system.setOutput(FMOD.OUTPUTTYPE.ASIO); break; default: return; } ERRCHECK(result); /* Get Record drivers */ result = system.getRecordNumDrivers(ref numdrivers); ERRCHECK(result); for (int count = 0; count < numdrivers; count++) { result = system.getRecordDriverInfo(count, drivername, drivername.Capacity, ref guid); ERRCHECK(result); comboBoxRecord.Items.Add(drivername.ToString()); } comboBoxOutput.Enabled = false; comboBoxRecord.Enabled = true; } private void comboBoxRecord_SelectedIndexChanged(object sender, System.EventArgs e) { FMOD.CREATESOUNDEXINFO exinfo = new FMOD.CREATESOUNDEXINFO(); FMOD.RESULT result; selected = comboBoxRecord.SelectedIndex; comboBoxOutput.Enabled = false; comboBoxRecord.Enabled = false; /* Initialise */ result = system.init(32, FMOD.INITFLAGS.NORMAL, (IntPtr)null); ERRCHECK(result); exinfo.cbsize = Marshal.SizeOf(exinfo); exinfo.numchannels = 2; exinfo.format = FMOD.SOUND_FORMAT.PCM16; exinfo.defaultfrequency = 44100; exinfo.length = (uint)(exinfo.defaultfrequency * 2 * exinfo.numchannels * 2); result = system.createSound((string)null, (FMOD.MODE._2D | FMOD.MODE.SOFTWARE | FMOD.MODE.OPENUSER), ref exinfo, ref sound); ERRCHECK(result); start.Enabled = true; } private void start_Click(object sender, System.EventArgs e) { FMOD.RESULT result; result = system.recordStart(selected, sound, true); ERRCHECK(result); soundlength = 0; lastrecordpos = 0; datalength = 0; fs = new FileStream("record.wav", FileMode.Create, FileAccess.Write); /* Write out the wav header. As we don't know the length yet it will be 0. */ WriteWavHeader(0); recording = true; result = sound.getLength(ref soundlength, FMOD.TIMEUNIT.PCM); ERRCHECK(result); start.Enabled = false; } private void stop_Click(object sender, System.EventArgs e) { /* Write back the wav header now that we know its length. */ if (recording) { recording = false; WriteWavHeader(datalength); fs.Close(); start.Enabled = true; } } private void timer_Tick(object sender, System.EventArgs e) { FMOD.RESULT result; if (recording) { uint recordpos = 0; result = system.getRecordPosition(selected, ref recordpos); ERRCHECK(result); if (recordpos != lastrecordpos) { IntPtr ptr1 = IntPtr.Zero, ptr2 = IntPtr.Zero; int blocklength; uint len1 = 0, len2 = 0; blocklength = (int)recordpos - (int)lastrecordpos; if (blocklength < 0) { blocklength += (int)soundlength; } /* Lock the sound to get access to the raw data. */ sound.@lock(lastrecordpos * 4, (uint)blocklength * 4, ref ptr1, ref ptr2, ref len1, ref len2); /* *4 = stereo 16bit. 1 sample = 4 bytes. */ /* Write it to disk. */ if (ptr1 != IntPtr.Zero && len1 > 0) { byte[] buf = new byte[len1]; Marshal.Copy(ptr1, buf, 0, (int)len1); datalength += (int)len1; fs.Write(buf, 0, (int)len1); } if (ptr2 != IntPtr.Zero && len2 > 0) { byte[] buf = new byte[len2]; Marshal.Copy(ptr2, buf, 0, (int)len2); datalength += (int)len2; fs.Write(buf, 0, (int)len2); } /* Unlock the sound to allow FMOD to use it again. */ sound.unlock(ptr1, ptr1, len1, len2); } lastrecordpos = recordpos; statusBar.Text = "Record buffer pos = " + recordpos + " Record time = " + datalength / 44100 / 4 / 60 + ":" + (datalength / 44100 / 4) % 60; } if (system != null) { system.update(); } } private void exit_button_Click(object sender, System.EventArgs e) { Application.Exit(); } /* WAV Structures */ [StructLayout(LayoutKind.Sequential, Pack = 1)] struct RiffChunk { [MarshalAs(UnmanagedType.ByValArray,SizeConst=4)] public char[] id; public int size; } [StructLayout(LayoutKind.Sequential, Pack = 1)] struct FmtChunk { public RiffChunk chunk; public ushort wFormatTag; /* format type */ public ushort nChannels; /* number of channels (i.e. mono, stereo...) */ public uint nSamplesPerSec; /* sample rate */ public uint nAvgBytesPerSec; /* for buffer estimation */ public ushort nBlockAlign; /* block size of data */ public ushort wBitsPerSample; /* number of bits per sample of mono data */ } [StructLayout(LayoutKind.Sequential, Pack = 1)] struct DataChunk { public RiffChunk chunk; } [StructLayout(LayoutKind.Sequential, Pack = 1)] struct WavHeader { public RiffChunk chunk; [MarshalAs(UnmanagedType.ByValArray,SizeConst=4)] public char[] rifftype; } private void WriteWavHeader(int length) { FMOD.SOUND_TYPE type = FMOD.SOUND_TYPE.UNKNOWN; FMOD.SOUND_FORMAT format = FMOD.SOUND_FORMAT.NONE; int channels = 0, bits = 0, temp1 = 0; float rate = 0.0f; float temp = 0.0f; if (sound == null) { return; } sound.getFormat(ref type, ref format, ref channels, ref bits); sound.getDefaults(ref rate, ref temp, ref temp, ref temp1); fs.Seek(0, SeekOrigin.Begin); FmtChunk fmtChunk = new FmtChunk(); DataChunk dataChunk = new DataChunk(); WavHeader wavHeader = new WavHeader(); RiffChunk riffChunk = new RiffChunk(); fmtChunk.chunk = new RiffChunk(); fmtChunk.chunk.id = new char[4]; fmtChunk.chunk.id[0] = 'f'; fmtChunk.chunk.id[1] = 'm'; fmtChunk.chunk.id[2] = 't'; fmtChunk.chunk.id[3] = ' '; fmtChunk.chunk.size = Marshal.SizeOf(fmtChunk) - Marshal.SizeOf(riffChunk); fmtChunk.wFormatTag = 1; fmtChunk.nChannels = (ushort)channels; fmtChunk.nSamplesPerSec = (uint)rate; fmtChunk.nAvgBytesPerSec = (uint)(rate * channels * bits / 8); fmtChunk.nBlockAlign = (ushort)(1 * channels * bits / 8); fmtChunk.wBitsPerSample = (ushort)bits; dataChunk.chunk = new RiffChunk(); dataChunk.chunk.id = new char[4]; dataChunk.chunk.id[0] = 'd'; dataChunk.chunk.id[1] = 'a'; dataChunk.chunk.id[2] = 't'; dataChunk.chunk.id[3] = 'a'; dataChunk.chunk.size = (int)length; wavHeader.chunk = new RiffChunk(); wavHeader.chunk.id = new char[4]; wavHeader.chunk.id[0] = 'R'; wavHeader.chunk.id[1] = 'I'; wavHeader.chunk.id[2] = 'F'; wavHeader.chunk.id[3] = 'F'; wavHeader.chunk.size = (int)(Marshal.SizeOf(fmtChunk) + Marshal.SizeOf(riffChunk) + length); wavHeader.rifftype = new char[4]; wavHeader.rifftype[0] = 'W'; wavHeader.rifftype[1] = 'A'; wavHeader.rifftype[2] = 'V'; wavHeader.rifftype[3] = 'E'; /* Write out the WAV header. */ IntPtr wavHeaderPtr = Marshal.AllocHGlobal(Marshal.SizeOf(wavHeader)); IntPtr fmtChunkPtr = Marshal.AllocHGlobal(Marshal.SizeOf(fmtChunk)); IntPtr dataChunkPtr = Marshal.AllocHGlobal(Marshal.SizeOf(dataChunk)); byte []wavHeaderBytes = new byte[Marshal.SizeOf(wavHeader)]; byte []fmtChunkBytes = new byte[Marshal.SizeOf(fmtChunk)]; byte []dataChunkBytes = new byte[Marshal.SizeOf(dataChunk)]; Marshal.StructureToPtr(wavHeader, wavHeaderPtr, false); Marshal.Copy(wavHeaderPtr, wavHeaderBytes, 0, Marshal.SizeOf(wavHeader)); Marshal.StructureToPtr(fmtChunk, fmtChunkPtr, false); Marshal.Copy(fmtChunkPtr, fmtChunkBytes, 0, Marshal.SizeOf(fmtChunk)); Marshal.StructureToPtr(dataChunk, dataChunkPtr, false); Marshal.Copy(dataChunkPtr, dataChunkBytes, 0, Marshal.SizeOf(dataChunk)); fs.Write(wavHeaderBytes, 0, Marshal.SizeOf(wavHeader)); fs.Write(fmtChunkBytes, 0, Marshal.SizeOf(fmtChunk)); fs.Write(dataChunkBytes, 0, Marshal.SizeOf(dataChunk)); } private void ERRCHECK(FMOD.RESULT result) { if (result != FMOD.RESULT.OK) { timer.Stop(); MessageBox.Show("FMOD error! " + result + " - " + FMOD.Error.String(result)); Environment.Exit(-1); } } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IO; using System.Management.Automation; using System.Management.Automation.Internal; using System.Security; using System.Text; using System.Xml; using Dbg = System.Management.Automation.Diagnostics; namespace Microsoft.PowerShell.Commands { /// <summary> /// Implementation for the Export-Clixml command. /// </summary> [Cmdlet(VerbsData.Export, "Clixml", SupportsShouldProcess = true, DefaultParameterSetName = "ByPath", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096926")] public sealed class ExportClixmlCommand : PSCmdlet, IDisposable { #region Command Line Parameters // If a Passthru parameter is added, the SupportsShouldProcess // implementation will need to be modified. /// <summary> /// Depth of serialization. /// </summary> [Parameter] [ValidateRange(1, int.MaxValue)] public int Depth { get; set; } /// <summary> /// Mandatory file name to write to. /// </summary> [Parameter(Mandatory = true, Position = 0, ParameterSetName = "ByPath")] public string Path { get; set; } /// <summary> /// Mandatory file name to write to. /// </summary> [Parameter(Mandatory = true, ParameterSetName = "ByLiteralPath")] [Alias("PSPath", "LP")] public string LiteralPath { get { return Path; } set { Path = value; _isLiteralPath = true; } } private bool _isLiteralPath = false; /// <summary> /// Input object to be exported. /// </summary> [Parameter(ValueFromPipeline = true, Mandatory = true)] [AllowNull] public PSObject InputObject { get; set; } /// <summary> /// Property that sets force parameter. /// </summary> [Parameter] public SwitchParameter Force { get { return _force; } set { _force = value; } } private bool _force; /// <summary> /// Property that prevents file overwrite. /// </summary> [Parameter] [Alias("NoOverwrite")] public SwitchParameter NoClobber { get { return _noclobber; } set { _noclobber = value; } } private bool _noclobber; /// <summary> /// Encoding optional flag. /// </summary> [Parameter] [ArgumentToEncodingTransformationAttribute()] [ArgumentEncodingCompletionsAttribute] [ValidateNotNullOrEmpty] public Encoding Encoding { get { return _encoding; } set { EncodingConversion.WarnIfObsolete(this, value); _encoding = value; } } private Encoding _encoding = ClrFacade.GetDefaultEncoding(); #endregion Command Line Parameters #region Overrides /// <summary> /// BeginProcessing override. /// </summary> protected override void BeginProcessing() { CreateFileStream(); } /// <summary> /// </summary> protected override void ProcessRecord() { if (_serializer != null) { _serializer.Serialize(InputObject); _xw.Flush(); } } /// <summary> /// </summary> protected override void EndProcessing() { if (_serializer != null) { _serializer.Done(); _serializer = null; } CleanUp(); } /// <summary> /// </summary> protected override void StopProcessing() { base.StopProcessing(); _serializer.Stop(); } #endregion Overrides #region file /// <summary> /// Handle to file stream. /// </summary> private FileStream _fs; /// <summary> /// Stream writer used to write to file. /// </summary> private XmlWriter _xw; /// <summary> /// Serializer used for serialization. /// </summary> private Serializer _serializer; /// <summary> /// FileInfo of file to clear read-only flag when operation is complete. /// </summary> private FileInfo _readOnlyFileInfo = null; private void CreateFileStream() { Dbg.Assert(Path != null, "FileName is mandatory parameter"); if (!ShouldProcess(Path)) return; StreamWriter sw; PathUtils.MasterStreamOpen( this, this.Path, this.Encoding, false, // default encoding false, // append this.Force, this.NoClobber, out _fs, out sw, out _readOnlyFileInfo, _isLiteralPath ); // create xml writer XmlWriterSettings xmlSettings = new(); xmlSettings.CloseOutput = true; xmlSettings.Encoding = sw.Encoding; xmlSettings.Indent = true; xmlSettings.OmitXmlDeclaration = true; _xw = XmlWriter.Create(sw, xmlSettings); if (Depth == 0) { _serializer = new Serializer(_xw); } else { _serializer = new Serializer(_xw, Depth, true); } } private void CleanUp() { if (_fs != null) { if (_xw != null) { _xw.Dispose(); _xw = null; } _fs.Dispose(); _fs = null; } } #endregion file #region IDisposable Members /// <summary> /// Set to true when object is disposed. /// </summary> private bool _disposed; /// <summary> /// Public dispose method. /// </summary> public void Dispose() { if (!_disposed) { CleanUp(); } _disposed = true; } #endregion IDisposable Members } /// <summary> /// Implements Import-Clixml command. /// </summary> [Cmdlet(VerbsData.Import, "Clixml", SupportsPaging = true, DefaultParameterSetName = "ByPath", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096618")] public sealed class ImportClixmlCommand : PSCmdlet, IDisposable { #region Command Line Parameters /// <summary> /// Mandatory file name to read from. /// </summary> [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByPath")] public string[] Path { get; set; } /// <summary> /// Mandatory file name to read from. /// </summary> [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByLiteralPath")] [Alias("PSPath", "LP")] public string[] LiteralPath { get { return Path; } set { Path = value; _isLiteralPath = true; } } private bool _isLiteralPath = false; #endregion Command Line Parameters #region IDisposable Members private bool _disposed = false; /// <summary> /// Public dispose method. /// </summary> public void Dispose() { if (!_disposed) { GC.SuppressFinalize(this); if (_helper != null) { _helper.Dispose(); _helper = null; } _disposed = true; } } #endregion private ImportXmlHelper _helper; /// <summary> /// ProcessRecord overload. /// </summary> protected override void ProcessRecord() { if (Path != null) { foreach (string path in Path) { _helper = new ImportXmlHelper(path, this, _isLiteralPath); _helper.Import(); } } } /// <summary> /// </summary> protected override void StopProcessing() { base.StopProcessing(); _helper.Stop(); } } /// <summary> /// Implementation for the convertto-xml command. /// </summary> [Cmdlet(VerbsData.ConvertTo, "Xml", SupportsShouldProcess = false, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096603", RemotingCapability = RemotingCapability.None)] [OutputType(typeof(XmlDocument), typeof(string))] public sealed class ConvertToXmlCommand : PSCmdlet, IDisposable { #region Command Line Parameters /// <summary> /// Depth of serialization. /// </summary> [Parameter(HelpMessage = "Specifies how many levels of contained objects should be included in the XML representation")] [ValidateRange(1, int.MaxValue)] public int Depth { get; set; } /// <summary> /// Input Object which is written to XML format. /// </summary> [Parameter(Position = 0, ValueFromPipeline = true, Mandatory = true)] [AllowNull] public PSObject InputObject { get; set; } /// <summary> /// Property that sets NoTypeInformation parameter. /// </summary> [Parameter(HelpMessage = "Specifies not to include the Type information in the XML representation")] public SwitchParameter NoTypeInformation { get { return _notypeinformation; } set { _notypeinformation = value; } } private bool _notypeinformation; /// <summary> /// Property that sets As parameter. /// </summary> [Parameter] [ValidateNotNullOrEmpty] [ValidateSet("Stream", "String", "Document")] public string As { get; set; } = "Document"; #endregion Command Line Parameters #region Overrides /// <summary> /// BeginProcessing override. /// </summary> protected override void BeginProcessing() { if (!As.Equals("Stream", StringComparison.OrdinalIgnoreCase)) { CreateMemoryStream(); } else { WriteObject(string.Format(CultureInfo.InvariantCulture, "<?xml version=\"1.0\" encoding=\"{0}\"?>", Encoding.UTF8.WebName)); WriteObject("<Objects>"); } } /// <summary> /// Override ProcessRecord. /// </summary> protected override void ProcessRecord() { if (As.Equals("Stream", StringComparison.OrdinalIgnoreCase)) { CreateMemoryStream(); if (_serializer != null) _serializer.SerializeAsStream(InputObject); if (_serializer != null) { _serializer.DoneAsStream(); _serializer = null; } // Loading to the XML Document _ms.Position = 0; StreamReader read = new(_ms); string data = read.ReadToEnd(); WriteObject(data); // Cleanup CleanUp(); } else { if (_serializer != null) _serializer.Serialize(InputObject); } } /// <summary> /// </summary> protected override void EndProcessing() { if (_serializer != null) { _serializer.Done(); _serializer = null; } if (As.Equals("Stream", StringComparison.OrdinalIgnoreCase)) { WriteObject("</Objects>"); } else { // Loading to the XML Document _ms.Position = 0; if (As.Equals("Document", StringComparison.OrdinalIgnoreCase)) { // this is a trusted xml doc - the cmdlet generated the doc into a private memory stream XmlDocument xmldoc = new(); xmldoc.Load(_ms); WriteObject(xmldoc); } else if (As.Equals("String", StringComparison.OrdinalIgnoreCase)) { StreamReader read = new(_ms); string data = read.ReadToEnd(); WriteObject(data); } } // Cleaning up CleanUp(); } /// <summary> /// StopProcessing. /// </summary> protected override void StopProcessing() { _serializer.Stop(); } #endregion Overrides #region memory /// <summary> /// XmlText writer. /// </summary> private XmlWriter _xw; /// <summary> /// Serializer used for serialization. /// </summary> private CustomSerialization _serializer; /// <summary> /// Memory Stream used for serialization. /// </summary> private MemoryStream _ms; private void CreateMemoryStream() { // Memory Stream _ms = new MemoryStream(); // We use XmlTextWriter originally: // _xw = new XmlTextWriter(_ms, null); // _xw.Formatting = Formatting.Indented; // This implies the following settings: // - Encoding is null -> use the default encoding 'UTF-8' when creating the writer from the stream; // - XmlTextWriter closes the underlying stream / writer when 'Close/Dispose' is called on it; // - Use the default indentation setting -- two space characters. // // We configure the same settings in XmlWriterSettings when refactoring this code to use XmlWriter: // - The default encoding used by XmlWriterSettings is 'UTF-8', but we call it out explicitly anyway; // - Set CloseOutput to true; // - Set Indent to true, and by default, IndentChars is two space characters. // // We use XmlWriterSettings.OmitXmlDeclaration instead of XmlWriter.WriteStartDocument because the // xml writer created by calling XmlWriter.Create(Stream, XmlWriterSettings) will write out the xml // declaration even without calling WriteStartDocument(). var xmlSettings = new XmlWriterSettings(); xmlSettings.Encoding = Encoding.UTF8; xmlSettings.CloseOutput = true; xmlSettings.Indent = true; if (As.Equals("Stream", StringComparison.OrdinalIgnoreCase)) { // Omit xml declaration in this case because we will write out the declaration string in BeginProcess. xmlSettings.OmitXmlDeclaration = true; } _xw = XmlWriter.Create(_ms, xmlSettings); if (Depth == 0) { _serializer = new CustomSerialization(_xw, NoTypeInformation); } else { _serializer = new CustomSerialization(_xw, NoTypeInformation, Depth); } } /// <summary> ///Cleaning up the MemoryStream. /// </summary> private void CleanUp() { if (_ms != null) { if (_xw != null) { _xw.Dispose(); _xw = null; } _ms.Dispose(); _ms = null; } } #endregion memory #region IDisposable Members /// <summary> /// Set to true when object is disposed. /// </summary> private bool _disposed; /// <summary> /// Public dispose method. /// </summary> public void Dispose() { if (!_disposed) { CleanUp(); } _disposed = true; } #endregion IDisposable Members } /// <summary> /// Helper class to import single XML file. /// </summary> internal class ImportXmlHelper : IDisposable { #region constructor /// <summary> /// XML file to import. /// </summary> private readonly string _path; /// <summary> /// Reference to cmdlet which is using this helper class. /// </summary> private readonly PSCmdlet _cmdlet; private readonly bool _isLiteralPath; internal ImportXmlHelper(string fileName, PSCmdlet cmdlet, bool isLiteralPath) { Dbg.Assert(fileName != null, "filename is mandatory"); Dbg.Assert(cmdlet != null, "cmdlet is mandatory"); _path = fileName; _cmdlet = cmdlet; _isLiteralPath = isLiteralPath; } #endregion constructor #region file /// <summary> /// Handle to file stream. /// </summary> internal FileStream _fs; /// <summary> /// XmlReader used to read file. /// </summary> internal XmlReader _xr; private static XmlReader CreateXmlReader(Stream stream) { TextReader textReader = new StreamReader(stream); // skip #< CLIXML directive const string cliXmlDirective = "#< CLIXML"; if (textReader.Peek() == (int)cliXmlDirective[0]) { string line = textReader.ReadLine(); if (!line.Equals(cliXmlDirective, StringComparison.Ordinal)) { stream.Seek(0, SeekOrigin.Begin); } } return XmlReader.Create(textReader, InternalDeserializer.XmlReaderSettingsForCliXml); } internal void CreateFileStream() { _fs = PathUtils.OpenFileStream(_path, _cmdlet, _isLiteralPath); _xr = CreateXmlReader(_fs); } private void CleanUp() { if (_fs != null) { _fs.Dispose(); _fs = null; } } #endregion file #region IDisposable Members /// <summary> /// Set to true when object is disposed. /// </summary> private bool _disposed; /// <summary> /// Public dispose method. /// </summary> public void Dispose() { if (!_disposed) { CleanUp(); } _disposed = true; GC.SuppressFinalize(this); } #endregion IDisposable Members private Deserializer _deserializer; internal void Import() { CreateFileStream(); _deserializer = new Deserializer(_xr); // If total count has been requested, return a dummy object with zero confidence if (_cmdlet.PagingParameters.IncludeTotalCount) { PSObject totalCount = _cmdlet.PagingParameters.NewTotalCount(0, 0); _cmdlet.WriteObject(totalCount); } ulong skip = _cmdlet.PagingParameters.Skip; ulong first = _cmdlet.PagingParameters.First; // if paging is not specified then keep the old V2 behavior if (skip == 0 && first == ulong.MaxValue) { while (!_deserializer.Done()) { object result = _deserializer.Deserialize(); _cmdlet.WriteObject(result); } } // else try to flatten the output if possible else { ulong skipped = 0; ulong count = 0; while (!_deserializer.Done() && count < first) { object result = _deserializer.Deserialize(); PSObject psObject = result as PSObject; if (psObject != null) { ICollection c = psObject.BaseObject as ICollection; if (c != null) { foreach (object o in c) { if (count >= first) break; if (skipped++ >= skip) { count++; _cmdlet.WriteObject(o); } } } else { if (skipped++ >= skip) { count++; _cmdlet.WriteObject(result); } } } else if (skipped++ >= skip) { count++; _cmdlet.WriteObject(result); continue; } } } } internal void Stop() { if (_deserializer != null) { _deserializer.Stop(); } } } #region Select-Xml ///<summary> ///This cmdlet is used to search an xml document based on the XPath Query. ///</summary> [Cmdlet(VerbsCommon.Select, "Xml", DefaultParameterSetName = "Xml", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097031")] [OutputType(typeof(SelectXmlInfo))] public class SelectXmlCommand : PSCmdlet { #region parameters /// <summary> /// Specifies the path which contains the xml files. The default is the current user directory. /// </summary> [Parameter(Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "Path")] [ValidateNotNullOrEmpty] public string[] Path { get; set; } /// <summary> /// Specifies the literal path which contains the xml files. The default is the current user directory. /// </summary> [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "LiteralPath")] [ValidateNotNullOrEmpty] [Alias("PSPath", "LP")] public string[] LiteralPath { get { return Path; } set { Path = value; _isLiteralPath = true; } } private bool _isLiteralPath = false; /// <summary> /// The following is the definition of the input parameter "XML". /// Specifies the xml Node. /// </summary> [Parameter(Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, ParameterSetName = "Xml")] [ValidateNotNullOrEmpty] [Alias("Node")] public System.Xml.XmlNode[] Xml { get; set; } /// <summary> /// The following is the definition of the input parameter in string format. /// Specifies the string format of a fully qualified xml. /// </summary> [Parameter(Mandatory = true, ValueFromPipeline = true, ParameterSetName = "Content")] [ValidateNotNullOrEmpty] public string[] Content { get; set; } /// <summary> /// The following is the definition of the input parameter "Xpath". /// Specifies the String in XPath language syntax. The xml documents will be /// searched for the nodes/values represented by this parameter. /// </summary> [Parameter(Mandatory = true, Position = 0)] [ValidateNotNullOrEmpty] public string XPath { get; set; } /// <summary> /// The following definition used to specify the NameSpace of xml. /// </summary> [Parameter] [ValidateNotNullOrEmpty] public Hashtable Namespace { get; set; } #endregion parameters #region private private void WriteResults(XmlNodeList foundXmlNodes, string filePath) { Dbg.Assert(foundXmlNodes != null, "Caller should verify foundNodes != null"); foreach (XmlNode foundXmlNode in foundXmlNodes) { SelectXmlInfo selectXmlInfo = new(); selectXmlInfo.Node = foundXmlNode; selectXmlInfo.Pattern = XPath; selectXmlInfo.Path = filePath; this.WriteObject(selectXmlInfo); } } private void ProcessXmlNode(XmlNode xmlNode, string filePath) { Dbg.Assert(xmlNode != null, "Caller should verify xmlNode != null"); XmlNodeList xList; if (Namespace != null) { XmlNamespaceManager xmlns = AddNameSpaceTable(this.ParameterSetName, xmlNode as XmlDocument, Namespace); xList = xmlNode.SelectNodes(XPath, xmlns); } else { xList = xmlNode.SelectNodes(XPath); } this.WriteResults(xList, filePath); } private void ProcessXmlFile(string filePath) { // Cannot use ImportXMLHelper because it will throw terminating error which will // not be inline with Select-String // So doing self processing of the file. try { XmlDocument xmlDocument = InternalDeserializer.LoadUnsafeXmlDocument( new FileInfo(filePath), true, /* preserve whitespace, comments, etc. */ null); /* default maxCharactersInDocument */ this.ProcessXmlNode(xmlDocument, filePath); } catch (NotSupportedException notSupportedException) { this.WriteFileReadError(filePath, notSupportedException); } catch (IOException ioException) { this.WriteFileReadError(filePath, ioException); } catch (SecurityException securityException) { this.WriteFileReadError(filePath, securityException); } catch (UnauthorizedAccessException unauthorizedAccessException) { this.WriteFileReadError(filePath, unauthorizedAccessException); } catch (XmlException xmlException) { this.WriteFileReadError(filePath, xmlException); } catch (InvalidOperationException invalidOperationException) { this.WriteFileReadError(filePath, invalidOperationException); } } private void WriteFileReadError(string filePath, Exception exception) { string errorMessage = string.Format( CultureInfo.InvariantCulture, // filePath is culture invariant, exception message is to be copied verbatim UtilityCommonStrings.FileReadError, filePath, exception.Message); ArgumentException argumentException = new(errorMessage, exception); ErrorRecord errorRecord = new(argumentException, "ProcessingFile", ErrorCategory.InvalidArgument, filePath); this.WriteError(errorRecord); } private XmlNamespaceManager AddNameSpaceTable(string parametersetname, XmlDocument xDoc, Hashtable namespacetable) { XmlNamespaceManager xmlns; if (parametersetname.Equals("Xml")) { XmlNameTable xmlnt = new NameTable(); xmlns = new XmlNamespaceManager(xmlnt); } else { xmlns = new XmlNamespaceManager(xDoc.NameTable); } foreach (DictionaryEntry row in namespacetable) { try { xmlns.AddNamespace(row.Key.ToString(), row.Value.ToString()); } catch (NullReferenceException) { string message = StringUtil.Format(UtilityCommonStrings.SearchXMLPrefixNullError); InvalidOperationException e = new(message); ErrorRecord er = new(e, "PrefixError", ErrorCategory.InvalidOperation, namespacetable); WriteError(er); } catch (ArgumentNullException) { string message = StringUtil.Format(UtilityCommonStrings.SearchXMLPrefixNullError); InvalidOperationException e = new(message); ErrorRecord er = new(e, "PrefixError", ErrorCategory.InvalidOperation, namespacetable); WriteError(er); } } return xmlns; } #endregion private #region override /// <summary> /// ProcessRecord method. /// </summary> protected override void ProcessRecord() { if (ParameterSetName.Equals("Xml", StringComparison.OrdinalIgnoreCase)) { foreach (XmlNode xmlNode in this.Xml) { ProcessXmlNode(xmlNode, string.Empty); } } else if ( (ParameterSetName.Equals("Path", StringComparison.OrdinalIgnoreCase) || (ParameterSetName.Equals("LiteralPath", StringComparison.OrdinalIgnoreCase)))) { // If any file not resolved, execution stops. this is to make consistent with select-string. List<string> fullresolvedPaths = new(); foreach (string fpath in Path) { if (_isLiteralPath) { string resolvedPath = GetUnresolvedProviderPathFromPSPath(fpath); fullresolvedPaths.Add(resolvedPath); } else { ProviderInfo provider; Collection<string> resolvedPaths = GetResolvedProviderPathFromPSPath(fpath, out provider); if (!provider.NameEquals(this.Context.ProviderNames.FileSystem)) { // Cannot open File error string message = StringUtil.Format(UtilityCommonStrings.FileOpenError, provider.FullName); InvalidOperationException e = new(message); ErrorRecord er = new(e, "ProcessingFile", ErrorCategory.InvalidOperation, fpath); WriteError(er); continue; } fullresolvedPaths.AddRange(resolvedPaths); } } foreach (string file in fullresolvedPaths) { ProcessXmlFile(file); } } else if (ParameterSetName.Equals("Content", StringComparison.OrdinalIgnoreCase)) { foreach (string xmlstring in Content) { XmlDocument xmlDocument; try { xmlDocument = (XmlDocument)LanguagePrimitives.ConvertTo(xmlstring, typeof(XmlDocument), CultureInfo.InvariantCulture); } catch (PSInvalidCastException invalidCastException) { this.WriteError(invalidCastException.ErrorRecord); continue; } this.ProcessXmlNode(xmlDocument, string.Empty); } } else { Dbg.Assert(false, "Unrecognized parameterset"); } } #endregion overrides } /// <summary> /// The object returned by Select-Xml representing the result of a match. /// </summary> public sealed class SelectXmlInfo { /// <summary> /// If the object is InputObject, Input Stream is used. /// </summary> private const string inputStream = "InputStream"; private const string MatchFormat = "{0}:{1}"; private const string SimpleFormat = "{0}"; /// <summary> /// The XmlNode that matches search. /// </summary> public XmlNode Node { get; set; } /// <summary> /// The FileName from which the match is found. /// </summary> public string Path { get { return _path; } set { if (string.IsNullOrEmpty(value)) { _path = inputStream; } else { _path = value; } } } private string _path; /// <summary> /// The pattern used to search. /// </summary> public string Pattern { get; set; } /// <summary> /// Returns the string representation of this object. The format /// depends on whether a path has been set for this object or not. /// </summary> /// <returns></returns> public override string ToString() { return ToString(null); } /// <summary> /// Return String representation of the object. /// </summary> /// <param name="directory"></param> /// <returns></returns> private string ToString(string directory) { string displayPath = (directory != null) ? RelativePath(directory) : _path; return FormatLine(GetNodeText(), displayPath); } /// <summary> /// Returns the XmlNode Value or InnerXml. /// </summary> /// <returns></returns> internal string GetNodeText() { string nodeText = string.Empty; if (Node != null) { if (Node.Value != null) { nodeText = Node.Value.Trim(); } else { nodeText = Node.InnerXml.Trim(); } } return nodeText; } /// <summary> /// Returns the path of the matching file truncated relative to the <paramref name="directory"/> parameter. /// <remarks> /// For example, if the matching path was c:\foo\bar\baz.c and the directory argument was c:\foo /// the routine would return bar\baz.c /// </remarks> /// </summary> /// <param name="directory">The directory base the truncation on.</param> /// <returns>The relative path that was produced.</returns> private string RelativePath(string directory) { string relPath = _path; if (!relPath.Equals(inputStream)) { if (relPath.StartsWith(directory, StringComparison.OrdinalIgnoreCase)) { int offset = directory.Length; if (offset < relPath.Length) { if (directory[offset - 1] == '\\' || directory[offset - 1] == '/') relPath = relPath.Substring(offset); else if (relPath[offset] == '\\' || relPath[offset] == '/') relPath = relPath.Substring(offset + 1); } } } return relPath; } /// <summary> /// Formats a line for use in ToString. /// </summary> /// <param name="text"></param> /// <param name="displaypath"></param> /// <returns></returns> private string FormatLine(string text, string displaypath) { if (_path.Equals(inputStream)) { return StringUtil.Format(SimpleFormat, text); } else { return StringUtil.Format(MatchFormat, text, displaypath); } } } #endregion Select-Xml }
// Copyright (C) 2015 EventDay, Inc using System; using System.Collections.Generic; using System.Linq; using Antlr4.Runtime.Tree; using EventDayDsl.EventDay.Entities; using EventDayDsl.EventDay.Language; namespace EventDayDsl.EventDay { internal class Dsl : GrammarBaseVisitor<string> { private string _commandType; private string _currentMessageName; private string _eventType; public Dsl(string name) { Name = name; File = new File(name); } public string Name { get; set; } public File File { get; } public override string VisitStateDefinition(GrammarParser.StateDefinitionContext context) { var stateName = VisitTerminal(context.state_name().ID()); var definition = new StateDefinition(File.Namespace) { Name = stateName }; var interfaceContext = context.stateDefinitionInterface(); if (interfaceContext != null) definition.Interface = VisitTerminal(interfaceContext.ID()); File.StateDefinitions.Add(definition); return context.GetText(); } public override string VisitEnumDefinition(GrammarParser.EnumDefinitionContext context) { var name = VisitTerminal(context.type().ID()); var @enum = new Enumeration(name); foreach (var member in context.enumMemberList().enumMember()) { var valueContext = member.enumMemberValue(); var memberValue = int.Parse(VisitTerminal(valueContext.INTEGER())); var memberName = VisitTerminal(member.name().ID()); @enum.Values.Add(new EnumerationValue(memberName, memberValue)); } File.Enums.Add(@enum); return context.ToString(); } public override string VisitStateApplicationList(GrammarParser.StateApplicationListContext context) { foreach (var applicationContext in context.stateApplication()) { VisitStateApplication(applicationContext); } return context.GetText(); } public override string VisitStateApplication(GrammarParser.StateApplicationContext context) { var stateName = VisitTerminal(context.ID()); File.StateDefintionReceive(stateName, _currentMessageName); return context.GetText(); } public override string VisitImportAssingment(GrammarParser.ImportAssingmentContext context) { var ns = string.Join(".", context.@namespace().ID().Select(VisitTerminal)); File.Usings.Add(ns); return context.GetText(); } public override string VisitNamespaceAssignment(GrammarParser.NamespaceAssignmentContext context) { var ns = string.Join(".", context.@namespace().ID().Select(VisitTerminal)); File.Namespace = ns; return context.GetText(); } public override string VisitConstant(GrammarParser.ConstantContext context) { var name = VisitTerminal(context.name().ID()); var type = VisitTerminal(context.type().ID()); var typeArguments = context.type().typeArguments(); if (typeArguments != null) { type += typeArguments.GetText(); } var modifier = context.type().typeModifier(); var isOptional = modifier?.OPTIONAL() != null; var optionalName = context.optionalName(); if (optionalName == null) File.AddPropertyDefinition(name, type, isOptional); else File.AddPropertyDefinition(name, VisitTerminal(optionalName.ID()), type, isOptional); return context.GetText(); } public override string VisitCommandAssignment(GrammarParser.CommandAssignmentContext context) { _commandType = string.Join(", ", context.type().Select(t => { var type = VisitTerminal(t.ID()); if (t.typeArguments() != null) { type += t.typeArguments().GetText(); } return type; })); return context.GetText(); } public override string VisitEventAssignment(GrammarParser.EventAssignmentContext context) { _eventType = string.Join(", ", context.type().Select(t => { var type = VisitTerminal(t.ID()); if (t.typeArguments() != null) { type += t.typeArguments().GetText(); } return type; })); return context.GetText(); } public override string VisitMarkerDefinition(GrammarParser.MarkerDefinitionContext context) { var name = VisitTerminal(context.ID()); var item = new MarkerInterface(name); var argumentList = context.argumentList(); if (argumentList != null) { foreach (var argument in argumentList.argument()) { var tuple = ReadProperty(argument); item.AddProperty(tuple.Item1, tuple.Item2, tuple.Item3); } } File.MarkerInterfaces.Add(item); return context.GetText(); } public override string VisitEntityDefinition(GrammarParser.EntityDefinitionContext context) { var interfaces = new HashSet<MarkerInterface>(MarkerInterface.NameComparer); var markerList = context.markerList(); if (markerList != null) { foreach (var iface in markerList.marker()) { var iname = VisitTerminal(iface.ID()); var definedInterface = File.MarkerInterfaces.First(x => x.Name == iname); if (definedInterface != null) interfaces.Add(definedInterface); } } var name = VisitTerminal(context.type().ID()); var entity = new Entity(name, interfaces); foreach (var argument in context.argumentList().argument()) { if (argument == null) continue; var tuple = ReadProperty(argument); entity.AddProperty(tuple.Item1, tuple.Item2, tuple.Item3); } var stringContext = context.toString(); if (stringContext != null) { entity.StringFormat = VisitTerminal(stringContext.TO_STRING()); } File.Entities.Add(entity); return context.GetText(); } public override string VisitMessageDefinition(GrammarParser.MessageDefinitionContext context) { var type = ""; var isEvent = context.EVENT() != null; if (isEvent) { type = _eventType; } if (context.CMD() != null) { type = _commandType; } var interfaces = new HashSet<MarkerInterface>(MarkerInterface.NameComparer) {new MarkerInterface(type)}; var markerList = context.markerList(); if (markerList != null) { foreach (var iface in markerList.marker()) { var iname = VisitTerminal(iface.ID()); var definedInterface = File.MarkerInterfaces.First(x => x.Name == iname); if (definedInterface != null) interfaces.Add(definedInterface); } } var name = VisitTerminal(context.type().ID()); _currentMessageName = name; var message = new Message(name, interfaces); File.Messages.Add(message); foreach (var argument in context.argumentList().argument()) { if (argument == null) continue; var tuple = ReadProperty(argument); message.AddProperty(tuple.Item1, tuple.Item2, tuple.Item3); } if (isEvent) message.AddProperty(Globals.EventGenerationDateProperty, "DateTime"); var stringContext = context.toString(); if (stringContext != null) { message.StringFormat = VisitTerminal(stringContext.TO_STRING()); } foreach (var stateApplicationListContext in context.stateApplicationList()) { VisitStateApplicationList(stateApplicationListContext); } return context.GetText(); } private Tuple<string, string, bool> ReadProperty(GrammarParser.ArgumentContext argument) { var type = VisitTerminal(argument.type().ID()); var typeArguments = argument.type().typeArguments(); if (typeArguments != null) { type += typeArguments.GetText(); } string name; var modifier = argument.type().typeModifier(); var isOptional = modifier?.OPTIONAL() != null; if (argument.name() == null) { name = VisitTerminal(argument.type().ID()); var definition = File.FindPropertyDefinition(name); if (string.IsNullOrEmpty(definition?.Item1)) throw new Exception($"Tried to use an undefined property '{name}'"); type = definition.Item2; name = definition.Item1; isOptional = definition.Item3 || isOptional; } else { name = VisitTerminal(argument.name().ID()); } return Tuple.Create(name, type, isOptional); } public override string VisitTerminal(ITerminalNode node) { return node.GetText(); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure.Management.Authorization; using Microsoft.Azure.Management.Authorization.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Authorization { /// <summary> /// Get classic administrator details (see http://TBD for more information) /// </summary> internal partial class ClassicAdministratorOperations : IServiceOperations<AuthorizationManagementClient>, IClassicAdministratorOperations { /// <summary> /// Initializes a new instance of the ClassicAdministratorOperations /// class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal ClassicAdministratorOperations(AuthorizationManagementClient client) { this._client = client; } private AuthorizationManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Authorization.AuthorizationManagementClient. /// </summary> public AuthorizationManagementClient Client { get { return this._client; } } /// <summary> /// Gets a list of classic administrators for the subscription. /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// ClassicAdministrator list result information. /// </returns> public async Task<ClassicAdministratorListResult> ListAsync(CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/providers/Microsoft.Authorization/classicAdministrators"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-06-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ClassicAdministratorListResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ClassicAdministratorListResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { ClassicAdministrator classicAdministratorInstance = new ClassicAdministrator(); result.ClassicAdministrators.Add(classicAdministratorInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); classicAdministratorInstance.Id = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); classicAdministratorInstance.Name = nameInstance; } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); classicAdministratorInstance.Type = typeInstance; } JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { ClassicAdministratorProperties propertiesInstance = new ClassicAdministratorProperties(); classicAdministratorInstance.Properties = propertiesInstance; JToken emailAddressValue = propertiesValue["emailAddress"]; if (emailAddressValue != null && emailAddressValue.Type != JTokenType.Null) { string emailAddressInstance = ((string)emailAddressValue); propertiesInstance.EmailAddress = emailAddressInstance; } JToken roleValue = propertiesValue["role"]; if (roleValue != null && roleValue.Type != JTokenType.Null) { string roleInstance = ((string)roleValue); propertiesInstance.Role = roleInstance; } } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// // System.Security.Cryptography.SHA1CryptoServiceProvider.cs // // Authors: // Matthew S. Ford (Matthew.S.Ford@Rose-Hulman.Edu) // Sebastien Pouliot (sebastien@ximian.com) // // Copyright 2001 by Matthew S. Ford. // Copyright (C) 2004, 2005, 2008 Novell, Inc (http://www.novell.com) // // 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. // // Note: // The MS Framework includes two (almost) identical class for SHA1. // SHA1Managed is a 100% managed implementation. // SHA1CryptoServiceProvider (this file) is a wrapper on CryptoAPI. // Mono must provide those two class for binary compatibility. // In our case both class are wrappers around a managed internal class SHA1Internal. using System; using System.Runtime.InteropServices; using System.Security.Cryptography; namespace Mono.Security.Cryptography { internal class SHA1Internal { private const int BLOCK_SIZE_BYTES = 64; private uint[] _H; // these are my chaining variables private ulong count; private byte[] _ProcessingBuffer; // Used to start data when passed less than a block worth. private int _ProcessingBufferCount; // Counts how much data we have stored that still needs processed. private uint[] buff; public SHA1Internal() { _H = new uint[5]; _ProcessingBuffer = new byte[BLOCK_SIZE_BYTES]; buff = new uint[80]; Initialize(); } public void HashCore(byte[] rgb, int ibStart, int cbSize) { int i; if (_ProcessingBufferCount != 0) { if (cbSize < (BLOCK_SIZE_BYTES - _ProcessingBufferCount)) { System.Buffer.BlockCopy(rgb, ibStart, _ProcessingBuffer, _ProcessingBufferCount, cbSize); _ProcessingBufferCount += cbSize; return; } else { i = (BLOCK_SIZE_BYTES - _ProcessingBufferCount); System.Buffer.BlockCopy(rgb, ibStart, _ProcessingBuffer, _ProcessingBufferCount, i); ProcessBlock(_ProcessingBuffer, 0); _ProcessingBufferCount = 0; ibStart += i; cbSize -= i; } } for (i = 0; i < cbSize - cbSize % BLOCK_SIZE_BYTES; i += BLOCK_SIZE_BYTES) { ProcessBlock(rgb, (uint)(ibStart + i)); } if (cbSize % BLOCK_SIZE_BYTES != 0) { System.Buffer.BlockCopy(rgb, cbSize - cbSize % BLOCK_SIZE_BYTES + ibStart, _ProcessingBuffer, 0, cbSize % BLOCK_SIZE_BYTES); _ProcessingBufferCount = cbSize % BLOCK_SIZE_BYTES; } } public byte[] HashFinal() { byte[] hash = new byte[20]; ProcessFinalBlock(_ProcessingBuffer, 0, _ProcessingBufferCount); for (int i = 0; i < 5; i++) { for (int j = 0; j < 4; j++) { hash[i * 4 + j] = (byte)(_H[i] >> (8 * (3 - j))); } } return hash; } public void Initialize() { count = 0; _ProcessingBufferCount = 0; _H[0] = 0x67452301; _H[1] = 0xefcdab89; _H[2] = 0x98badcfe; _H[3] = 0x10325476; _H[4] = 0xC3D2E1F0; } private void ProcessBlock(byte[] inputBuffer, uint inputOffset) { uint a, b, c, d, e; count += BLOCK_SIZE_BYTES; // abc removal would not work on the fields uint[] _H = this._H; uint[] buff = this.buff; InitialiseBuff(buff, inputBuffer, inputOffset); FillBuff(buff); a = _H[0]; b = _H[1]; c = _H[2]; d = _H[3]; e = _H[4]; // This function was unrolled because it seems to be doubling our performance with current compiler/VM. // Possibly roll up if this changes. // ---- Round 1 -------- int i = 0; while (i < 20) { e += ((a << 5) | (a >> 27)) + (((c ^ d) & b) ^ d) + 0x5A827999 + buff[i]; b = (b << 30) | (b >> 2); d += ((e << 5) | (e >> 27)) + (((b ^ c) & a) ^ c) + 0x5A827999 + buff[i + 1]; a = (a << 30) | (a >> 2); c += ((d << 5) | (d >> 27)) + (((a ^ b) & e) ^ b) + 0x5A827999 + buff[i + 2]; e = (e << 30) | (e >> 2); b += ((c << 5) | (c >> 27)) + (((e ^ a) & d) ^ a) + 0x5A827999 + buff[i + 3]; d = (d << 30) | (d >> 2); a += ((b << 5) | (b >> 27)) + (((d ^ e) & c) ^ e) + 0x5A827999 + buff[i + 4]; c = (c << 30) | (c >> 2); i += 5; } // ---- Round 2 -------- while (i < 40) { e += ((a << 5) | (a >> 27)) + (b ^ c ^ d) + 0x6ED9EBA1 + buff[i]; b = (b << 30) | (b >> 2); d += ((e << 5) | (e >> 27)) + (a ^ b ^ c) + 0x6ED9EBA1 + buff[i + 1]; a = (a << 30) | (a >> 2); c += ((d << 5) | (d >> 27)) + (e ^ a ^ b) + 0x6ED9EBA1 + buff[i + 2]; e = (e << 30) | (e >> 2); b += ((c << 5) | (c >> 27)) + (d ^ e ^ a) + 0x6ED9EBA1 + buff[i + 3]; d = (d << 30) | (d >> 2); a += ((b << 5) | (b >> 27)) + (c ^ d ^ e) + 0x6ED9EBA1 + buff[i + 4]; c = (c << 30) | (c >> 2); i += 5; } // ---- Round 3 -------- while (i < 60) { e += ((a << 5) | (a >> 27)) + ((b & c) | (b & d) | (c & d)) + 0x8F1BBCDC + buff[i]; b = (b << 30) | (b >> 2); d += ((e << 5) | (e >> 27)) + ((a & b) | (a & c) | (b & c)) + 0x8F1BBCDC + buff[i + 1]; a = (a << 30) | (a >> 2); c += ((d << 5) | (d >> 27)) + ((e & a) | (e & b) | (a & b)) + 0x8F1BBCDC + buff[i + 2]; e = (e << 30) | (e >> 2); b += ((c << 5) | (c >> 27)) + ((d & e) | (d & a) | (e & a)) + 0x8F1BBCDC + buff[i + 3]; d = (d << 30) | (d >> 2); a += ((b << 5) | (b >> 27)) + ((c & d) | (c & e) | (d & e)) + 0x8F1BBCDC + buff[i + 4]; c = (c << 30) | (c >> 2); i += 5; } // ---- Round 4 -------- while (i < 80) { e += ((a << 5) | (a >> 27)) + (b ^ c ^ d) + 0xCA62C1D6 + buff[i]; b = (b << 30) | (b >> 2); d += ((e << 5) | (e >> 27)) + (a ^ b ^ c) + 0xCA62C1D6 + buff[i + 1]; a = (a << 30) | (a >> 2); c += ((d << 5) | (d >> 27)) + (e ^ a ^ b) + 0xCA62C1D6 + buff[i + 2]; e = (e << 30) | (e >> 2); b += ((c << 5) | (c >> 27)) + (d ^ e ^ a) + 0xCA62C1D6 + buff[i + 3]; d = (d << 30) | (d >> 2); a += ((b << 5) | (b >> 27)) + (c ^ d ^ e) + 0xCA62C1D6 + buff[i + 4]; c = (c << 30) | (c >> 2); i += 5; } _H[0] += a; _H[1] += b; _H[2] += c; _H[3] += d; _H[4] += e; } private static void InitialiseBuff(uint[] buff, byte[] input, uint inputOffset) { buff[0] = (uint)((input[inputOffset + 0] << 24) | (input[inputOffset + 1] << 16) | (input[inputOffset + 2] << 8) | (input[inputOffset + 3])); buff[1] = (uint)((input[inputOffset + 4] << 24) | (input[inputOffset + 5] << 16) | (input[inputOffset + 6] << 8) | (input[inputOffset + 7])); buff[2] = (uint)((input[inputOffset + 8] << 24) | (input[inputOffset + 9] << 16) | (input[inputOffset + 10] << 8) | (input[inputOffset + 11])); buff[3] = (uint)((input[inputOffset + 12] << 24) | (input[inputOffset + 13] << 16) | (input[inputOffset + 14] << 8) | (input[inputOffset + 15])); buff[4] = (uint)((input[inputOffset + 16] << 24) | (input[inputOffset + 17] << 16) | (input[inputOffset + 18] << 8) | (input[inputOffset + 19])); buff[5] = (uint)((input[inputOffset + 20] << 24) | (input[inputOffset + 21] << 16) | (input[inputOffset + 22] << 8) | (input[inputOffset + 23])); buff[6] = (uint)((input[inputOffset + 24] << 24) | (input[inputOffset + 25] << 16) | (input[inputOffset + 26] << 8) | (input[inputOffset + 27])); buff[7] = (uint)((input[inputOffset + 28] << 24) | (input[inputOffset + 29] << 16) | (input[inputOffset + 30] << 8) | (input[inputOffset + 31])); buff[8] = (uint)((input[inputOffset + 32] << 24) | (input[inputOffset + 33] << 16) | (input[inputOffset + 34] << 8) | (input[inputOffset + 35])); buff[9] = (uint)((input[inputOffset + 36] << 24) | (input[inputOffset + 37] << 16) | (input[inputOffset + 38] << 8) | (input[inputOffset + 39])); buff[10] = (uint)((input[inputOffset + 40] << 24) | (input[inputOffset + 41] << 16) | (input[inputOffset + 42] << 8) | (input[inputOffset + 43])); buff[11] = (uint)((input[inputOffset + 44] << 24) | (input[inputOffset + 45] << 16) | (input[inputOffset + 46] << 8) | (input[inputOffset + 47])); buff[12] = (uint)((input[inputOffset + 48] << 24) | (input[inputOffset + 49] << 16) | (input[inputOffset + 50] << 8) | (input[inputOffset + 51])); buff[13] = (uint)((input[inputOffset + 52] << 24) | (input[inputOffset + 53] << 16) | (input[inputOffset + 54] << 8) | (input[inputOffset + 55])); buff[14] = (uint)((input[inputOffset + 56] << 24) | (input[inputOffset + 57] << 16) | (input[inputOffset + 58] << 8) | (input[inputOffset + 59])); buff[15] = (uint)((input[inputOffset + 60] << 24) | (input[inputOffset + 61] << 16) | (input[inputOffset + 62] << 8) | (input[inputOffset + 63])); } private static void FillBuff(uint[] buff) { uint val; for (int i = 16; i < 80; i += 8) { val = buff[i - 3] ^ buff[i - 8] ^ buff[i - 14] ^ buff[i - 16]; buff[i] = (val << 1) | (val >> 31); val = buff[i - 2] ^ buff[i - 7] ^ buff[i - 13] ^ buff[i - 15]; buff[i + 1] = (val << 1) | (val >> 31); val = buff[i - 1] ^ buff[i - 6] ^ buff[i - 12] ^ buff[i - 14]; buff[i + 2] = (val << 1) | (val >> 31); val = buff[i + 0] ^ buff[i - 5] ^ buff[i - 11] ^ buff[i - 13]; buff[i + 3] = (val << 1) | (val >> 31); val = buff[i + 1] ^ buff[i - 4] ^ buff[i - 10] ^ buff[i - 12]; buff[i + 4] = (val << 1) | (val >> 31); val = buff[i + 2] ^ buff[i - 3] ^ buff[i - 9] ^ buff[i - 11]; buff[i + 5] = (val << 1) | (val >> 31); val = buff[i + 3] ^ buff[i - 2] ^ buff[i - 8] ^ buff[i - 10]; buff[i + 6] = (val << 1) | (val >> 31); val = buff[i + 4] ^ buff[i - 1] ^ buff[i - 7] ^ buff[i - 9]; buff[i + 7] = (val << 1) | (val >> 31); } } private void ProcessFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) { ulong total = count + (ulong)inputCount; int paddingSize = (56 - (int)(total % BLOCK_SIZE_BYTES)); if (paddingSize < 1) paddingSize += BLOCK_SIZE_BYTES; int length = inputCount + paddingSize + 8; byte[] fooBuffer = (length == 64) ? _ProcessingBuffer : new byte[length]; for (int i = 0; i < inputCount; i++) { fooBuffer[i] = inputBuffer[i + inputOffset]; } fooBuffer[inputCount] = 0x80; for (int i = inputCount + 1; i < inputCount + paddingSize; i++) { fooBuffer[i] = 0x00; } // I deal in bytes. The algorithm deals in bits. ulong size = total << 3; AddLength(size, fooBuffer, inputCount + paddingSize); ProcessBlock(fooBuffer, 0); if (length == 128) ProcessBlock(fooBuffer, 64); } internal void AddLength(ulong length, byte[] buffer, int position) { buffer[position++] = (byte)(length >> 56); buffer[position++] = (byte)(length >> 48); buffer[position++] = (byte)(length >> 40); buffer[position++] = (byte)(length >> 32); buffer[position++] = (byte)(length >> 24); buffer[position++] = (byte)(length >> 16); buffer[position++] = (byte)(length >> 8); buffer[position] = (byte)(length); } public SHA1Internal Clone() { return new SHA1Internal { _H = (uint[])_H.Clone(), count = count, _ProcessingBuffer = (byte[])_ProcessingBuffer.Clone(), _ProcessingBufferCount = _ProcessingBufferCount, buff = (uint[])buff.Clone() }; } } [ComVisible(true)] internal sealed class SHA1CryptoServiceProvider : SHA1, ICloneable { private SHA1Internal sha; public SHA1CryptoServiceProvider() { sha = new SHA1Internal(); } ~SHA1CryptoServiceProvider() { Dispose(false); } protected override void Dispose(bool disposing) { // nothing new to do (managed implementation) base.Dispose(disposing); } protected override void HashCore(byte[] rgb, int ibStart, int cbSize) { State = 1; sha.HashCore(rgb, ibStart, cbSize); } protected override byte[] HashFinal() { State = 0; return sha.HashFinal(); } public override void Initialize() { sha.Initialize(); } object ICloneable.Clone() { return new SHA1CryptoServiceProvider() { sha = sha.Clone() }; } } }
/* * Copyright 2006-2015 TIBIC SOLUTIONS * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Xml; using System.Xml.Serialization; using LWAS.Extensible.Exceptions; using LWAS.Extensible.Interfaces.Configuration; namespace LWAS.Infrastructure.Configuration { [Serializable] public class ConfigurationElement : ConfigurationType, IConfigurationElement, IConfigurationType, IXmlSerializable { private IConfigurationElementAttributesCollection _attributes; private IConfigurationElementsCollection _elements; public IConfigurationElementAttributesCollection Attributes { get { this.EnsureAttributes(); return this._attributes; } set { this._attributes = new ConfigurationElementAttributesCollection(this, value); } } public IConfigurationElementsCollection Elements { get { this.EnsureElements(); return this._elements; } set { this._elements = new ConfigurationElementsCollection(this, value); } } public ConfigurationElement(string key) : base(key) { } protected virtual void EnsureAttributes() { if (null == this._attributes) { this._attributes = new ConfigurationElementAttributesCollection(this); } } protected virtual void EnsureElements() { if (null == this._elements) { this._elements = new ConfigurationElementsCollection(this); } } public IConfigurationElement Clone() { ConfigurationElement clone = new ConfigurationElement(this.ConfigKey); clone.ConfigKey = this.ConfigKey; clone.Attributes = this.Attributes.Clone(clone); clone.Elements = this.Elements.Clone(clone); return clone; } public IConfigurationElementAttribute AddAttribute(string key) { if (string.IsNullOrEmpty(key)) { throw new ArgumentNullException("key"); } this.Attributes.Add(key, new ConfigurationElementAttribute(key)); return this.Attributes[key]; } public IConfigurationElement AddElement(string key) { if (string.IsNullOrEmpty(key)) { throw new ArgumentNullException("key"); } this.Elements.Add(key, new ConfigurationElement(key)); return this.Elements[key]; } public IConfigurationElementAttribute GetAttributeReference(string attribute) { if (string.IsNullOrEmpty(attribute)) { throw new ArgumentNullException("attribute"); } if (!this.Attributes.ContainsKey(attribute)) { throw new MissingConfigurationException(attribute); } return this.Attributes[attribute]; } public IConfigurationElement GetElementReference(string element) { if (string.IsNullOrEmpty(element)) { throw new ArgumentNullException("element"); } if (!this.Elements.ContainsKey(element)) { throw new MissingConfigurationException(element); } return this.Elements[element]; } public override void ReadXml(XmlReader reader) { if (null == reader) { throw new ArgumentNullException("reader"); } if (reader.EOF) { throw new ArgumentException("reader is at EOF"); } reader.MoveToElement(); base.ReadXml(reader); reader.MoveToContent(); int elementDepth = reader.Depth; if (reader.ReadToDescendant("attributes")) { this.EnsureAttributes(); if (reader.ReadToDescendant("attribute")) { int depth = reader.Depth; do { ConfigurationElementAttribute attribute = new ConfigurationElementAttribute(string.Empty); attribute.ReadXml(reader); this._attributes.Add(attribute.ConfigKey, attribute); reader.MoveToElement(); while (depth < reader.Depth && reader.Read()) { } } while (reader.ReadToNextSibling("attribute")); } } while (elementDepth < reader.Depth - 1 && reader.Read()) { } if (reader.ReadToNextSibling("elements")) { this.EnsureElements(); if (reader.ReadToDescendant("element")) { int depth = reader.Depth; do { ConfigurationElement element = new ConfigurationElement(string.Empty); element.ReadXml(reader); this._elements.Add(element.ConfigKey, element); reader.MoveToElement(); while (depth < reader.Depth && reader.Read()) { } } while (reader.ReadToNextSibling("element")); } } } public override void WriteXml(XmlWriter writer) { if (null == writer) { throw new ArgumentNullException("writer"); } writer.WriteStartElement("element"); base.WriteXml(writer); this.EnsureAttributes(); writer.WriteStartElement("attributes"); foreach (IConfigurationElementAttribute attribute in this._attributes.Values) { attribute.WriteXml(writer); } writer.WriteEndElement(); this.EnsureElements(); writer.WriteStartElement("elements"); foreach (IConfigurationElement element in this._elements.Values) { element.WriteXml(writer); } writer.WriteEndElement(); writer.WriteEndElement(); } } }
/* ==================================================================== 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.HWPF.Model.Types { using System; using NPOI.Util; using NPOI.HWPF.UserModel; using System.Text; /** * Section Properties. * NOTE: This source Is automatically generated please do not modify this file. Either subclass or * remove the record in src/records/definitions. * @author S. Ryan Ackley */ public abstract class SEPAbstractType : BaseObject { protected byte field_1_bkc; protected bool field_2_fTitlePage; protected bool field_3_fAutoPgn; protected byte field_4_nfcPgn; /** Arabic */ /**/public const byte NFCPGN_ARABIC = 0; /** Roman (upper case) */ /**/public const byte NFCPGN_ROMAN_UPPER_CASE = 1; /** Roman (lower case) */ /**/public const byte NFCPGN_ROMAN_LOWER_CASE = 2; /** Letter (upper case) */ /**/public const byte NFCPGN_LETTER_UPPER_CASE = 3; /** Letter (lower case) */ /**/public const byte NFCPGN_LETTER_LOWER_CASE = 4; protected bool field_5_fUnlocked; protected byte field_6_cnsPgn; protected bool field_7_fPgnRestart; protected bool field_8_fEndNote; protected byte field_9_lnc; protected byte field_10_grpfIhdt; protected int field_11_nLnnMod; protected int field_12_dxaLnn; protected int field_13_dxaPgn; protected int field_14_dyaPgn; protected bool field_15_fLBetween; protected byte field_16_vjc; protected int field_17_dmBinFirst; protected int field_18_dmBinOther; protected int field_19_dmPaperReq; protected BorderCode field_20_brcTop; protected BorderCode field_21_brcLeft; protected BorderCode field_22_brcBottom; protected BorderCode field_23_brcRight; protected bool field_24_fPropMark; protected int field_25_ibstPropRMark; protected DateAndTime field_26_dttmPropRMark; protected int field_27_dxtCharSpace; protected int field_28_dyaLinePitch; protected int field_29_clm; protected int field_30_unused2; protected bool field_31_dmOrientPage; public const bool DMORIENTPAGE_LANDSCAPE = false; public const bool DMORIENTPAGE_PORTRAIT = true; protected byte field_32_iHeadingPgn; protected int field_33_pgnStart; protected int field_34_lnnMin; protected int field_35_wTextFlow; protected short field_36_unused3; protected int field_37_pgbProp; protected short field_38_unused4; protected int field_39_xaPage; protected int field_40_yaPage; protected int field_41_xaPageNUp; protected int field_42_yaPageNUp; protected int field_43_dxaLeft; protected int field_44_dxaRight; protected int field_45_dyaTop; protected int field_46_dyaBottom; protected int field_47_dzaGutter; protected int field_48_dyaHdrTop; protected int field_49_dyaHdrBottom; protected int field_50_ccolM1; protected bool field_51_fEvenlySpaced; protected byte field_52_unused5; protected int field_53_dxaColumns; protected int[] field_54_rgdxaColumn; protected int field_55_dxaColumnWidth; protected byte field_56_dmOrientFirst; protected byte field_57_fLayout; protected short field_58_unused6; protected byte[] field_59_olstAnm; public SEPAbstractType() { this.field_1_bkc = 2; this.field_8_fEndNote = true; this.field_13_dxaPgn = 720; this.field_14_dyaPgn = 720; this.field_31_dmOrientPage = true; this.field_33_pgnStart = 1; this.field_39_xaPage = 12240; this.field_40_yaPage = 15840; this.field_41_xaPageNUp = 12240; this.field_42_yaPageNUp = 15840; this.field_43_dxaLeft = 1800; this.field_44_dxaRight = 1800; this.field_45_dyaTop = 1440; this.field_46_dyaBottom = 1440; this.field_48_dyaHdrTop = 720; this.field_49_dyaHdrBottom = 720; this.field_51_fEvenlySpaced = true; this.field_53_dxaColumns = 720; } /** * Get the bkc field for the SEP record. */ public byte GetBkc() { return field_1_bkc; } /** * Set the bkc field for the SEP record. */ public void SetBkc(byte field_1_bkc) { this.field_1_bkc = field_1_bkc; } /** * Get the fTitlePage field for the SEP record. */ public bool GetFTitlePage() { return field_2_fTitlePage; } /** * Set the fTitlePage field for the SEP record. */ public void SetFTitlePage(bool field_2_fTitlePage) { this.field_2_fTitlePage = field_2_fTitlePage; } /** * Get the fAutoPgn field for the SEP record. */ public bool GetFAutoPgn() { return field_3_fAutoPgn; } /** * Set the fAutoPgn field for the SEP record. */ public void SetFAutoPgn(bool field_3_fAutoPgn) { this.field_3_fAutoPgn = field_3_fAutoPgn; } /** * Get the nfcPgn field for the SEP record. */ public byte GetNfcPgn() { return field_4_nfcPgn; } /** * Set the nfcPgn field for the SEP record. */ public void SetNfcPgn(byte field_4_nfcPgn) { this.field_4_nfcPgn = field_4_nfcPgn; } /** * Get the fUnlocked field for the SEP record. */ public bool GetFUnlocked() { return field_5_fUnlocked; } /** * Set the fUnlocked field for the SEP record. */ public void SetFUnlocked(bool field_5_fUnlocked) { this.field_5_fUnlocked = field_5_fUnlocked; } /** * Get the cnsPgn field for the SEP record. */ public byte GetCnsPgn() { return field_6_cnsPgn; } /** * Set the cnsPgn field for the SEP record. */ public void SetCnsPgn(byte field_6_cnsPgn) { this.field_6_cnsPgn = field_6_cnsPgn; } /** * Get the fPgnRestart field for the SEP record. */ public bool GetFPgnRestart() { return field_7_fPgnRestart; } /** * Set the fPgnRestart field for the SEP record. */ public void SetFPgnRestart(bool field_7_fPgnRestart) { this.field_7_fPgnRestart = field_7_fPgnRestart; } /** * Get the fEndNote field for the SEP record. */ public bool GetFEndNote() { return field_8_fEndNote; } /** * Set the fEndNote field for the SEP record. */ public void SetFEndNote(bool field_8_fEndNote) { this.field_8_fEndNote = field_8_fEndNote; } /** * Get the lnc field for the SEP record. */ public byte GetLnc() { return field_9_lnc; } /** * Set the lnc field for the SEP record. */ public void SetLnc(byte field_9_lnc) { this.field_9_lnc = field_9_lnc; } /** * Get the grpfIhdt field for the SEP record. */ public byte GetGrpfIhdt() { return field_10_grpfIhdt; } /** * Set the grpfIhdt field for the SEP record. */ public void SetGrpfIhdt(byte field_10_grpfIhdt) { this.field_10_grpfIhdt = field_10_grpfIhdt; } /** * Get the nLnnMod field for the SEP record. */ public int GetNLnnMod() { return field_11_nLnnMod; } /** * Set the nLnnMod field for the SEP record. */ public void SetNLnnMod(int field_11_nLnnMod) { this.field_11_nLnnMod = field_11_nLnnMod; } /** * Get the dxaLnn field for the SEP record. */ public int GetDxaLnn() { return field_12_dxaLnn; } /** * Set the dxaLnn field for the SEP record. */ public void SetDxaLnn(int field_12_dxaLnn) { this.field_12_dxaLnn = field_12_dxaLnn; } /** * Get the dxaPgn field for the SEP record. */ public int GetDxaPgn() { return field_13_dxaPgn; } /** * Set the dxaPgn field for the SEP record. */ public void SetDxaPgn(int field_13_dxaPgn) { this.field_13_dxaPgn = field_13_dxaPgn; } /** * Get the dyaPgn field for the SEP record. */ public int GetDyaPgn() { return field_14_dyaPgn; } /** * Set the dyaPgn field for the SEP record. */ public void SetDyaPgn(int field_14_dyaPgn) { this.field_14_dyaPgn = field_14_dyaPgn; } /** * Get the fLBetween field for the SEP record. */ public bool GetFLBetween() { return field_15_fLBetween; } /** * Set the fLBetween field for the SEP record. */ public void SetFLBetween(bool field_15_fLBetween) { this.field_15_fLBetween = field_15_fLBetween; } /** * Get the vjc field for the SEP record. */ public byte GetVjc() { return field_16_vjc; } /** * Set the vjc field for the SEP record. */ public void SetVjc(byte field_16_vjc) { this.field_16_vjc = field_16_vjc; } /** * Get the dmBinFirst field for the SEP record. */ public int GetDmBinFirst() { return field_17_dmBinFirst; } /** * Set the dmBinFirst field for the SEP record. */ public void SetDmBinFirst(int field_17_dmBinFirst) { this.field_17_dmBinFirst = field_17_dmBinFirst; } /** * Get the dmBinOther field for the SEP record. */ public int GetDmBinOther() { return field_18_dmBinOther; } /** * Set the dmBinOther field for the SEP record. */ public void SetDmBinOther(int field_18_dmBinOther) { this.field_18_dmBinOther = field_18_dmBinOther; } /** * Get the dmPaperReq field for the SEP record. */ public int GetDmPaperReq() { return field_19_dmPaperReq; } /** * Set the dmPaperReq field for the SEP record. */ public void SetDmPaperReq(int field_19_dmPaperReq) { this.field_19_dmPaperReq = field_19_dmPaperReq; } /** * Get the brcTop field for the SEP record. */ public BorderCode GetBrcTop() { return field_20_brcTop; } /** * Set the brcTop field for the SEP record. */ public void SetBrcTop(BorderCode field_20_brcTop) { this.field_20_brcTop = field_20_brcTop; } /** * Get the brcLeft field for the SEP record. */ public BorderCode GetBrcLeft() { return field_21_brcLeft; } /** * Set the brcLeft field for the SEP record. */ public void SetBrcLeft(BorderCode field_21_brcLeft) { this.field_21_brcLeft = field_21_brcLeft; } /** * Get the brcBottom field for the SEP record. */ public BorderCode GetBrcBottom() { return field_22_brcBottom; } /** * Set the brcBottom field for the SEP record. */ public void SetBrcBottom(BorderCode field_22_brcBottom) { this.field_22_brcBottom = field_22_brcBottom; } /** * Get the brcRight field for the SEP record. */ public BorderCode GetBrcRight() { return field_23_brcRight; } /** * Set the brcRight field for the SEP record. */ public void SetBrcRight(BorderCode field_23_brcRight) { this.field_23_brcRight = field_23_brcRight; } /** * Get the fPropMark field for the SEP record. */ public bool GetFPropMark() { return field_24_fPropMark; } /** * Set the fPropMark field for the SEP record. */ public void SetFPropMark(bool field_24_fPropMark) { this.field_24_fPropMark = field_24_fPropMark; } /** * Get the ibstPropRMark field for the SEP record. */ public int GetIbstPropRMark() { return field_25_ibstPropRMark; } /** * Set the ibstPropRMark field for the SEP record. */ public void SetIbstPropRMark(int field_25_ibstPropRMark) { this.field_25_ibstPropRMark = field_25_ibstPropRMark; } /** * Get the dttmPropRMark field for the SEP record. */ public DateAndTime GetDttmPropRMark() { return field_26_dttmPropRMark; } /** * Set the dttmPropRMark field for the SEP record. */ public void SetDttmPropRMark(DateAndTime field_26_dttmPropRMark) { this.field_26_dttmPropRMark = field_26_dttmPropRMark; } /** * Get the dxtCharSpace field for the SEP record. */ public int GetDxtCharSpace() { return field_27_dxtCharSpace; } /** * Set the dxtCharSpace field for the SEP record. */ public void SetDxtCharSpace(int field_27_dxtCharSpace) { this.field_27_dxtCharSpace = field_27_dxtCharSpace; } /** * Get the dyaLinePitch field for the SEP record. */ public int GetDyaLinePitch() { return field_28_dyaLinePitch; } /** * Set the dyaLinePitch field for the SEP record. */ public void SetDyaLinePitch(int field_28_dyaLinePitch) { this.field_28_dyaLinePitch = field_28_dyaLinePitch; } /** * Get the clm field for the SEP record. */ public int GetClm() { return field_29_clm; } /** * Set the clm field for the SEP record. */ public void SetClm(int field_29_clm) { this.field_29_clm = field_29_clm; } /** * Get the unused2 field for the SEP record. */ public int GetUnused2() { return field_30_unused2; } /** * Set the unused2 field for the SEP record. */ public void SetUnused2(int field_30_unused2) { this.field_30_unused2 = field_30_unused2; } /** * Get the dmOrientPage field for the SEP record. */ public bool GetDmOrientPage() { return field_31_dmOrientPage; } /** * Set the dmOrientPage field for the SEP record. */ public void SetDmOrientPage(bool field_31_dmOrientPage) { this.field_31_dmOrientPage = field_31_dmOrientPage; } /** * Get the iHeadingPgn field for the SEP record. */ public byte GetIHeadingPgn() { return field_32_iHeadingPgn; } /** * Set the iHeadingPgn field for the SEP record. */ public void SetIHeadingPgn(byte field_32_iHeadingPgn) { this.field_32_iHeadingPgn = field_32_iHeadingPgn; } /** * Get the pgnStart field for the SEP record. */ public int GetPgnStart() { return field_33_pgnStart; } /** * Set the pgnStart field for the SEP record. */ public void SetPgnStart(int field_33_pgnStart) { this.field_33_pgnStart = field_33_pgnStart; } /** * Get the lnnMin field for the SEP record. */ public int GetLnnMin() { return field_34_lnnMin; } /** * Set the lnnMin field for the SEP record. */ public void SetLnnMin(int field_34_lnnMin) { this.field_34_lnnMin = field_34_lnnMin; } /** * Get the wTextFlow field for the SEP record. */ public int GetWTextFlow() { return field_35_wTextFlow; } /** * Set the wTextFlow field for the SEP record. */ public void SetWTextFlow(int field_35_wTextFlow) { this.field_35_wTextFlow = field_35_wTextFlow; } /** * Get the unused3 field for the SEP record. */ public short GetUnused3() { return field_36_unused3; } /** * Set the unused3 field for the SEP record. */ public void SetUnused3(short field_36_unused3) { this.field_36_unused3 = field_36_unused3; } /** * Get the pgbProp field for the SEP record. */ public int GetPgbProp() { return field_37_pgbProp; } /** * Set the pgbProp field for the SEP record. */ public void SetPgbProp(int field_37_pgbProp) { this.field_37_pgbProp = field_37_pgbProp; } /** * Get the unused4 field for the SEP record. */ public short GetUnused4() { return field_38_unused4; } /** * Set the unused4 field for the SEP record. */ public void SetUnused4(short field_38_unused4) { this.field_38_unused4 = field_38_unused4; } /** * Get the xaPage field for the SEP record. */ public int GetXaPage() { return field_39_xaPage; } /** * Set the xaPage field for the SEP record. */ public void SetXaPage(int field_39_xaPage) { this.field_39_xaPage = field_39_xaPage; } /** * Get the yaPage field for the SEP record. */ public int GetYaPage() { return field_40_yaPage; } /** * Set the yaPage field for the SEP record. */ public void SetYaPage(int field_40_yaPage) { this.field_40_yaPage = field_40_yaPage; } /** * Get the xaPageNUp field for the SEP record. */ public int GetXaPageNUp() { return field_41_xaPageNUp; } /** * Set the xaPageNUp field for the SEP record. */ public void SetXaPageNUp(int field_41_xaPageNUp) { this.field_41_xaPageNUp = field_41_xaPageNUp; } /** * Get the yaPageNUp field for the SEP record. */ public int GetYaPageNUp() { return field_42_yaPageNUp; } /** * Set the yaPageNUp field for the SEP record. */ public void SetYaPageNUp(int field_42_yaPageNUp) { this.field_42_yaPageNUp = field_42_yaPageNUp; } /** * Get the dxaLeft field for the SEP record. */ public int GetDxaLeft() { return field_43_dxaLeft; } /** * Set the dxaLeft field for the SEP record. */ public void SetDxaLeft(int field_43_dxaLeft) { this.field_43_dxaLeft = field_43_dxaLeft; } /** * Get the dxaRight field for the SEP record. */ public int GetDxaRight() { return field_44_dxaRight; } /** * Set the dxaRight field for the SEP record. */ public void SetDxaRight(int field_44_dxaRight) { this.field_44_dxaRight = field_44_dxaRight; } /** * Get the dyaTop field for the SEP record. */ public int GetDyaTop() { return field_45_dyaTop; } /** * Set the dyaTop field for the SEP record. */ public void SetDyaTop(int field_45_dyaTop) { this.field_45_dyaTop = field_45_dyaTop; } /** * Get the dyaBottom field for the SEP record. */ public int GetDyaBottom() { return field_46_dyaBottom; } /** * Set the dyaBottom field for the SEP record. */ public void SetDyaBottom(int field_46_dyaBottom) { this.field_46_dyaBottom = field_46_dyaBottom; } /** * Get the dzaGutter field for the SEP record. */ public int GetDzaGutter() { return field_47_dzaGutter; } /** * Set the dzaGutter field for the SEP record. */ public void SetDzaGutter(int field_47_dzaGutter) { this.field_47_dzaGutter = field_47_dzaGutter; } /** * Get the dyaHdrTop field for the SEP record. */ public int GetDyaHdrTop() { return field_48_dyaHdrTop; } /** * Set the dyaHdrTop field for the SEP record. */ public void SetDyaHdrTop(int field_48_dyaHdrTop) { this.field_48_dyaHdrTop = field_48_dyaHdrTop; } /** * Get the dyaHdrBottom field for the SEP record. */ public int GetDyaHdrBottom() { return field_49_dyaHdrBottom; } /** * Set the dyaHdrBottom field for the SEP record. */ public void SetDyaHdrBottom(int field_49_dyaHdrBottom) { this.field_49_dyaHdrBottom = field_49_dyaHdrBottom; } /** * Get the ccolM1 field for the SEP record. */ public int GetCcolM1() { return field_50_ccolM1; } /** * Set the ccolM1 field for the SEP record. */ public void SetCcolM1(int field_50_ccolM1) { this.field_50_ccolM1 = field_50_ccolM1; } /** * Get the fEvenlySpaced field for the SEP record. */ public bool GetFEvenlySpaced() { return field_51_fEvenlySpaced; } /** * Set the fEvenlySpaced field for the SEP record. */ public void SetFEvenlySpaced(bool field_51_fEvenlySpaced) { this.field_51_fEvenlySpaced = field_51_fEvenlySpaced; } /** * Get the unused5 field for the SEP record. */ public byte GetUnused5() { return field_52_unused5; } /** * Set the unused5 field for the SEP record. */ public void SetUnused5(byte field_52_unused5) { this.field_52_unused5 = field_52_unused5; } /** * Get the dxaColumns field for the SEP record. */ public int GetDxaColumns() { return field_53_dxaColumns; } /** * Set the dxaColumns field for the SEP record. */ public void SetDxaColumns(int field_53_dxaColumns) { this.field_53_dxaColumns = field_53_dxaColumns; } /** * Get the rgdxaColumn field for the SEP record. */ public int[] GetRgdxaColumn() { return field_54_rgdxaColumn; } /** * Set the rgdxaColumn field for the SEP record. */ public void SetRgdxaColumn(int[] field_54_rgdxaColumn) { this.field_54_rgdxaColumn = field_54_rgdxaColumn; } /** * Get the dxaColumnWidth field for the SEP record. */ public int GetDxaColumnWidth() { return field_55_dxaColumnWidth; } /** * Set the dxaColumnWidth field for the SEP record. */ public void SetDxaColumnWidth(int field_55_dxaColumnWidth) { this.field_55_dxaColumnWidth = field_55_dxaColumnWidth; } /** * Get the dmOrientFirst field for the SEP record. */ public byte GetDmOrientFirst() { return field_56_dmOrientFirst; } /** * Set the dmOrientFirst field for the SEP record. */ public void SetDmOrientFirst(byte field_56_dmOrientFirst) { this.field_56_dmOrientFirst = field_56_dmOrientFirst; } /** * Get the fLayout field for the SEP record. */ public byte GetFLayout() { return field_57_fLayout; } /** * Set the fLayout field for the SEP record. */ public void SetFLayout(byte field_57_fLayout) { this.field_57_fLayout = field_57_fLayout; } /** * Get the unused6 field for the SEP record. */ public short GetUnused6() { return field_58_unused6; } /** * Set the unused6 field for the SEP record. */ public void SetUnused6(short field_58_unused6) { this.field_58_unused6 = field_58_unused6; } /** * Get the olstAnm field for the SEP record. */ public byte[] GetOlstAnm() { return field_59_olstAnm; } /** * Set the olstAnm field for the SEP record. */ public void SetOlstAnm(byte[] field_59_olstAnm) { this.field_59_olstAnm = field_59_olstAnm; } } }
namespace InControl { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using UnityEngine; public class InputDevice { public static readonly InputDevice Null = new InputDevice( "None" ); public string Name { get; protected set; } public string Meta { get; protected set; } public int SortOrder { get; protected set; } public InputDeviceClass DeviceClass { get; protected set; } public InputDeviceStyle DeviceStyle { get; protected set; } public Guid GUID { get; private set; } public ulong LastChangeTick { get; private set; } public bool IsAttached { get; private set; } protected bool RawSticks { get; private set; } List<InputControl> controls; public ReadOnlyCollection<InputControl> Controls { get; protected set; } protected InputControl[] ControlsByTarget { get; private set; } public TwoAxisInputControl LeftStick { get; private set; } public TwoAxisInputControl RightStick { get; private set; } public TwoAxisInputControl DPad { get; private set; } /// <summary> /// When a device is passive, it will never be considered an active device. /// This may be useful if you want a device to be accessible, but not /// show up in places where active devices are used. /// Defaults to <code>false</code>. /// </summary> public bool Passive; protected struct AnalogSnapshotEntry { public float value; public float maxValue; public float minValue; public void TrackMinMaxValue( float currentValue ) { maxValue = Mathf.Max( maxValue, currentValue ); minValue = Mathf.Min( minValue, currentValue ); } } protected AnalogSnapshotEntry[] AnalogSnapshot { get; set; } public InputDevice() : this( "" ) { } public InputDevice( string name ) : this( name, false ) { } public InputDevice( string name, bool rawSticks ) { Name = name; RawSticks = rawSticks; Meta = ""; GUID = Guid.NewGuid(); LastChangeTick = 0; SortOrder = int.MaxValue; DeviceClass = InputDeviceClass.Unknown; DeviceStyle = InputDeviceStyle.Unknown; Passive = false; const int numInputControlTypes = (int) InputControlType.Count + 1; ControlsByTarget = new InputControl[numInputControlTypes]; controls = new List<InputControl>( 32 ); Controls = new ReadOnlyCollection<InputControl>( controls ); RemoveAliasControls(); } internal void OnAttached() { IsAttached = true; AddAliasControls(); } internal void OnDetached() { IsAttached = false; StopVibration(); RemoveAliasControls(); } void AddAliasControls() { RemoveAliasControls(); if (IsKnown) { LeftStick = new TwoAxisInputControl(); RightStick = new TwoAxisInputControl(); DPad = new TwoAxisInputControl(); AddControl( InputControlType.LeftStickX, "Left Stick X" ); AddControl( InputControlType.LeftStickY, "Left Stick Y" ); AddControl( InputControlType.RightStickX, "Right Stick X" ); AddControl( InputControlType.RightStickY, "Right Stick Y" ); AddControl( InputControlType.DPadX, "DPad X" ); AddControl( InputControlType.DPadY, "DPad Y" ); #if UNITY_PS4 AddControl( InputControlType.Command, "OPTIONS button" ); #else AddControl( InputControlType.Command, "Command" ); #endif ExpireControlCache(); } } void RemoveAliasControls() { LeftStick = TwoAxisInputControl.Null; RightStick = TwoAxisInputControl.Null; DPad = TwoAxisInputControl.Null; RemoveControl( InputControlType.LeftStickX ); RemoveControl( InputControlType.LeftStickY ); RemoveControl( InputControlType.RightStickX ); RemoveControl( InputControlType.RightStickY ); RemoveControl( InputControlType.DPadX ); RemoveControl( InputControlType.DPadY ); RemoveControl( InputControlType.Command ); ExpireControlCache(); } protected void ClearControls() { Array.Clear( ControlsByTarget, 0, ControlsByTarget.Length ); controls.Clear(); ExpireControlCache(); } public bool HasControl( InputControlType controlType ) { return ControlsByTarget[(int) controlType] != null; } /// <summary> /// Gets the control with the specified control type. If the control does not exist, <c>InputControl.Null</c> is returned. /// </summary> /// <param name="controlType">The control type of the control to get.</param> public InputControl GetControl( InputControlType controlType ) { var inputControl = ControlsByTarget[(int) controlType]; return inputControl ?? InputControl.Null; } /// <summary> /// Gets the control with the specified control type. If the control does not exist, <c>InputControl.Null</c> is returned. /// </summary> /// <param name="controlType">The control type of the control to get.</param> public InputControl this[InputControlType controlType] { get { return GetControl( controlType ); } } // Warning: this is super inefficient. Don't use it unless you have to, m'kay? public static InputControlType GetInputControlTypeByName( string inputControlName ) { return (InputControlType) Enum.Parse( typeof( InputControlType ), inputControlName ); } // Warning: this is super inefficient. Don't use it unless you have to, m'kay? public InputControl GetControlByName( string controlName ) { var inputControlType = GetInputControlTypeByName( controlName ); return GetControl( inputControlType ); } public InputControl AddControl( InputControlType controlType, string handle ) { var inputControl = ControlsByTarget[(int) controlType]; if (inputControl == null) { inputControl = new InputControl( handle, controlType ); ControlsByTarget[(int) controlType] = inputControl; controls.Add( inputControl ); ExpireControlCache(); } return inputControl; } public InputControl AddControl( InputControlType controlType, string handle, float lowerDeadZone, float upperDeadZone ) { var inputControl = AddControl( controlType, handle ); inputControl.LowerDeadZone = lowerDeadZone; inputControl.UpperDeadZone = upperDeadZone; return inputControl; } void RemoveControl( InputControlType controlType ) { var inputControl = ControlsByTarget[(int) controlType]; if (inputControl != null) { ControlsByTarget[(int) controlType] = null; controls.Remove( inputControl ); ExpireControlCache(); } } public void ClearInputState() { LeftStick.ClearInputState(); RightStick.ClearInputState(); DPad.ClearInputState(); var controlsCount = Controls.Count; for (var i = 0; i < controlsCount; i++) { var control = Controls[i]; if (control != null) { control.ClearInputState(); } } } protected void UpdateWithState( InputControlType controlType, bool state, ulong updateTick, float deltaTime ) { GetControl( controlType ).UpdateWithState( state, updateTick, deltaTime ); } protected void UpdateWithValue( InputControlType controlType, float value, ulong updateTick, float deltaTime ) { GetControl( controlType ).UpdateWithValue( value, updateTick, deltaTime ); } internal void UpdateLeftStickWithValue( Vector2 value, ulong updateTick, float deltaTime ) { LeftStickLeft.UpdateWithValue( Mathf.Max( 0.0f, -value.x ), updateTick, deltaTime ); LeftStickRight.UpdateWithValue( Mathf.Max( 0.0f, value.x ), updateTick, deltaTime ); if (InputManager.InvertYAxis) { LeftStickUp.UpdateWithValue( Mathf.Max( 0.0f, -value.y ), updateTick, deltaTime ); LeftStickDown.UpdateWithValue( Mathf.Max( 0.0f, value.y ), updateTick, deltaTime ); } else { LeftStickUp.UpdateWithValue( Mathf.Max( 0.0f, value.y ), updateTick, deltaTime ); LeftStickDown.UpdateWithValue( Mathf.Max( 0.0f, -value.y ), updateTick, deltaTime ); } } internal void UpdateLeftStickWithRawValue( Vector2 value, ulong updateTick, float deltaTime ) { LeftStickLeft.UpdateWithRawValue( Mathf.Max( 0.0f, -value.x ), updateTick, deltaTime ); LeftStickRight.UpdateWithRawValue( Mathf.Max( 0.0f, value.x ), updateTick, deltaTime ); if (InputManager.InvertYAxis) { LeftStickUp.UpdateWithRawValue( Mathf.Max( 0.0f, -value.y ), updateTick, deltaTime ); LeftStickDown.UpdateWithRawValue( Mathf.Max( 0.0f, value.y ), updateTick, deltaTime ); } else { LeftStickUp.UpdateWithRawValue( Mathf.Max( 0.0f, value.y ), updateTick, deltaTime ); LeftStickDown.UpdateWithRawValue( Mathf.Max( 0.0f, -value.y ), updateTick, deltaTime ); } } internal void CommitLeftStick() { LeftStickUp.Commit(); LeftStickDown.Commit(); LeftStickLeft.Commit(); LeftStickRight.Commit(); } internal void UpdateRightStickWithValue( Vector2 value, ulong updateTick, float deltaTime ) { RightStickLeft.UpdateWithValue( Mathf.Max( 0.0f, -value.x ), updateTick, deltaTime ); RightStickRight.UpdateWithValue( Mathf.Max( 0.0f, value.x ), updateTick, deltaTime ); if (InputManager.InvertYAxis) { RightStickUp.UpdateWithValue( Mathf.Max( 0.0f, -value.y ), updateTick, deltaTime ); RightStickDown.UpdateWithValue( Mathf.Max( 0.0f, value.y ), updateTick, deltaTime ); } else { RightStickUp.UpdateWithValue( Mathf.Max( 0.0f, value.y ), updateTick, deltaTime ); RightStickDown.UpdateWithValue( Mathf.Max( 0.0f, -value.y ), updateTick, deltaTime ); } } internal void UpdateRightStickWithRawValue( Vector2 value, ulong updateTick, float deltaTime ) { RightStickLeft.UpdateWithRawValue( Mathf.Max( 0.0f, -value.x ), updateTick, deltaTime ); RightStickRight.UpdateWithRawValue( Mathf.Max( 0.0f, value.x ), updateTick, deltaTime ); if (InputManager.InvertYAxis) { RightStickUp.UpdateWithRawValue( Mathf.Max( 0.0f, -value.y ), updateTick, deltaTime ); RightStickDown.UpdateWithRawValue( Mathf.Max( 0.0f, value.y ), updateTick, deltaTime ); } else { RightStickUp.UpdateWithRawValue( Mathf.Max( 0.0f, value.y ), updateTick, deltaTime ); RightStickDown.UpdateWithRawValue( Mathf.Max( 0.0f, -value.y ), updateTick, deltaTime ); } } internal void CommitRightStick() { RightStickUp.Commit(); RightStickDown.Commit(); RightStickLeft.Commit(); RightStickRight.Commit(); } public virtual void Update( ulong updateTick, float deltaTime ) { // Implemented by subclasses, but does nothing by default. } bool AnyCommandControlIsPressed() { for (var i = (int) InputControlType.Back; i <= (int) InputControlType.Minus; i++) { var control = ControlsByTarget[i]; if (control != null && control.IsPressed) { return true; } } return false; } void ProcessLeftStick( ulong updateTick, float deltaTime ) { var x = Utility.ValueFromSides( LeftStickLeft.NextRawValue, LeftStickRight.NextRawValue ); var y = Utility.ValueFromSides( LeftStickDown.NextRawValue, LeftStickUp.NextRawValue, InputManager.InvertYAxis ); Vector2 v; if (RawSticks || LeftStickLeft.Raw || LeftStickRight.Raw || LeftStickUp.Raw || LeftStickDown.Raw) { v = new Vector2( x, y ); } else { var lowerDeadZone = Utility.Max( LeftStickLeft.LowerDeadZone, LeftStickRight.LowerDeadZone, LeftStickUp.LowerDeadZone, LeftStickDown.LowerDeadZone ); var upperDeadZone = Utility.Min( LeftStickLeft.UpperDeadZone, LeftStickRight.UpperDeadZone, LeftStickUp.UpperDeadZone, LeftStickDown.UpperDeadZone ); v = Utility.ApplyCircularDeadZone( x, y, lowerDeadZone, upperDeadZone ); } LeftStick.Raw = true; LeftStick.UpdateWithAxes( v.x, v.y, updateTick, deltaTime ); LeftStickX.Raw = true; LeftStickX.CommitWithValue( v.x, updateTick, deltaTime ); LeftStickY.Raw = true; LeftStickY.CommitWithValue( v.y, updateTick, deltaTime ); LeftStickLeft.SetValue( LeftStick.Left.Value, updateTick ); LeftStickRight.SetValue( LeftStick.Right.Value, updateTick ); LeftStickUp.SetValue( LeftStick.Up.Value, updateTick ); LeftStickDown.SetValue( LeftStick.Down.Value, updateTick ); } void ProcessRightStick( ulong updateTick, float deltaTime ) { var x = Utility.ValueFromSides( RightStickLeft.NextRawValue, RightStickRight.NextRawValue ); var y = Utility.ValueFromSides( RightStickDown.NextRawValue, RightStickUp.NextRawValue, InputManager.InvertYAxis ); Vector2 v; if (RawSticks || RightStickLeft.Raw || RightStickRight.Raw || RightStickUp.Raw || RightStickDown.Raw) { v = new Vector2( x, y ); } else { var lowerDeadZone = Utility.Max( RightStickLeft.LowerDeadZone, RightStickRight.LowerDeadZone, RightStickUp.LowerDeadZone, RightStickDown.LowerDeadZone ); var upperDeadZone = Utility.Min( RightStickLeft.UpperDeadZone, RightStickRight.UpperDeadZone, RightStickUp.UpperDeadZone, RightStickDown.UpperDeadZone ); v = Utility.ApplyCircularDeadZone( x, y, lowerDeadZone, upperDeadZone ); } RightStick.Raw = true; RightStick.UpdateWithAxes( v.x, v.y, updateTick, deltaTime ); RightStickX.Raw = true; RightStickX.CommitWithValue( v.x, updateTick, deltaTime ); RightStickY.Raw = true; RightStickY.CommitWithValue( v.y, updateTick, deltaTime ); RightStickLeft.SetValue( RightStick.Left.Value, updateTick ); RightStickRight.SetValue( RightStick.Right.Value, updateTick ); RightStickUp.SetValue( RightStick.Up.Value, updateTick ); RightStickDown.SetValue( RightStick.Down.Value, updateTick ); } void ProcessDPad( ulong updateTick, float deltaTime ) { var x = Utility.ValueFromSides( DPadLeft.NextRawValue, DPadRight.NextRawValue ); var y = Utility.ValueFromSides( DPadDown.NextRawValue, DPadUp.NextRawValue, InputManager.InvertYAxis ); Vector2 v; if (RawSticks || DPadLeft.Raw || DPadRight.Raw || DPadUp.Raw || DPadDown.Raw) { v = new Vector2( x, y ); } else { var lowerDeadZone = Utility.Max( DPadLeft.LowerDeadZone, DPadRight.LowerDeadZone, DPadUp.LowerDeadZone, DPadDown.LowerDeadZone ); var upperDeadZone = Utility.Min( DPadLeft.UpperDeadZone, DPadRight.UpperDeadZone, DPadUp.UpperDeadZone, DPadDown.UpperDeadZone ); v = Utility.ApplySeparateDeadZone( x, y, lowerDeadZone, upperDeadZone ); } DPad.Raw = true; DPad.UpdateWithAxes( v.x, v.y, updateTick, deltaTime ); DPadX.Raw = true; DPadX.CommitWithValue( v.x, updateTick, deltaTime ); DPadY.Raw = true; DPadY.CommitWithValue( v.y, updateTick, deltaTime ); DPadLeft.SetValue( DPad.Left.Value, updateTick ); DPadRight.SetValue( DPad.Right.Value, updateTick ); DPadUp.SetValue( DPad.Up.Value, updateTick ); DPadDown.SetValue( DPad.Down.Value, updateTick ); } public void Commit( ulong updateTick, float deltaTime ) { // We need to do some processing for known controllers to ensure all // the various control aliases holding directional values are calculated // optimally with circular deadzones and then set properly everywhere. if (IsKnown) { ProcessLeftStick( updateTick, deltaTime ); ProcessRightStick( updateTick, deltaTime ); ProcessDPad( updateTick, deltaTime ); } // Next, commit all control values. var controlsCount = Controls.Count; for (var i = 0; i < controlsCount; i++) { var control = Controls[i]; if (control != null) { control.Commit(); if (control.HasChanged && !control.Passive) { LastChangeTick = updateTick; } } } // Calculate the Command control alias for known controllers and commit it. if (IsKnown) { Command.CommitWithState( AnyCommandControlIsPressed(), updateTick, deltaTime ); } } public bool LastChangedAfter( InputDevice device ) { return device == null || LastChangeTick > device.LastChangeTick; } internal void RequestActivation() { LastChangeTick = InputManager.CurrentTick; } public virtual void Vibrate( float leftMotor, float rightMotor ) { } public void Vibrate( float intensity ) { Vibrate( intensity, intensity ); } public void StopVibration() { Vibrate( 0.0f ); } public virtual void SetLightColor( float red, float green, float blue ) { } public void SetLightColor( Color color ) { SetLightColor( color.r * color.a, color.g * color.a, color.b * color.a ); } public virtual void SetLightFlash( float flashOnDuration, float flashOffDuration ) { } public void StopLightFlash() { SetLightFlash( 1.0f, 0.0f ); } public virtual bool IsSupportedOnThisPlatform { get { return true; } } public virtual bool IsKnown { get { return true; } } public bool IsUnknown { get { return !IsKnown; } } [Obsolete( "Use InputDevice.CommandIsPressed instead.", false )] public bool MenuIsPressed { get { return IsKnown && Command.IsPressed; } } [Obsolete( "Use InputDevice.CommandWasPressed instead.", false )] public bool MenuWasPressed { get { return IsKnown && Command.WasPressed; } } [Obsolete( "Use InputDevice.CommandWasReleased instead.", false )] public bool MenuWasReleased { get { return IsKnown && Command.WasReleased; } } public bool CommandIsPressed { get { return IsKnown && Command.IsPressed; } } public bool CommandWasPressed { get { return IsKnown && Command.WasPressed; } } public bool CommandWasReleased { get { return IsKnown && Command.WasReleased; } } public InputControl AnyButton { get { var controlsCount = Controls.Count; for (var i = 0; i < controlsCount; i++) { var control = Controls[i]; if (control != null && control.IsButton && control.IsPressed) { return control; } } return InputControl.Null; } } public bool AnyButtonIsPressed { get { var controlCount = Controls.Count; for (var i = 0; i < controlCount; i++) { var control = Controls[i]; if (control != null && control.IsButton && control.IsPressed) { return true; } } return false; } } public bool AnyButtonWasPressed { get { var controlCount = Controls.Count; for (var i = 0; i < controlCount; i++) { var control = Controls[i]; if (control != null && control.IsButton && control.WasPressed) { return true; } } return false; } } public bool AnyButtonWasReleased { get { var controlCount = Controls.Count; for (var i = 0; i < controlCount; i++) { var control = Controls[i]; if (control != null && control.IsButton && control.WasReleased) { return true; } } return false; } } public TwoAxisInputControl Direction { get { return DPad.UpdateTick > LeftStick.UpdateTick ? DPad : LeftStick; } } #region Cached Control Properties InputControl cachedLeftStickUp; InputControl cachedLeftStickDown; InputControl cachedLeftStickLeft; InputControl cachedLeftStickRight; InputControl cachedRightStickUp; InputControl cachedRightStickDown; InputControl cachedRightStickLeft; InputControl cachedRightStickRight; InputControl cachedDPadUp; InputControl cachedDPadDown; InputControl cachedDPadLeft; InputControl cachedDPadRight; InputControl cachedAction1; InputControl cachedAction2; InputControl cachedAction3; InputControl cachedAction4; InputControl cachedLeftTrigger; InputControl cachedRightTrigger; InputControl cachedLeftBumper; InputControl cachedRightBumper; InputControl cachedLeftStickButton; InputControl cachedRightStickButton; InputControl cachedLeftStickX; InputControl cachedLeftStickY; InputControl cachedRightStickX; InputControl cachedRightStickY; InputControl cachedDPadX; InputControl cachedDPadY; InputControl cachedCommand; public InputControl LeftStickUp { get { return cachedLeftStickUp ?? (cachedLeftStickUp = GetControl( InputControlType.LeftStickUp )); } } public InputControl LeftStickDown { get { return cachedLeftStickDown ?? (cachedLeftStickDown = GetControl( InputControlType.LeftStickDown )); } } public InputControl LeftStickLeft { get { return cachedLeftStickLeft ?? (cachedLeftStickLeft = GetControl( InputControlType.LeftStickLeft )); } } public InputControl LeftStickRight { get { return cachedLeftStickRight ?? (cachedLeftStickRight = GetControl( InputControlType.LeftStickRight )); } } public InputControl RightStickUp { get { return cachedRightStickUp ?? (cachedRightStickUp = GetControl( InputControlType.RightStickUp )); } } public InputControl RightStickDown { get { return cachedRightStickDown ?? (cachedRightStickDown = GetControl( InputControlType.RightStickDown )); } } public InputControl RightStickLeft { get { return cachedRightStickLeft ?? (cachedRightStickLeft = GetControl( InputControlType.RightStickLeft )); } } public InputControl RightStickRight { get { return cachedRightStickRight ?? (cachedRightStickRight = GetControl( InputControlType.RightStickRight )); } } public InputControl DPadUp { get { return cachedDPadUp ?? (cachedDPadUp = GetControl( InputControlType.DPadUp )); } } public InputControl DPadDown { get { return cachedDPadDown ?? (cachedDPadDown = GetControl( InputControlType.DPadDown )); } } public InputControl DPadLeft { get { return cachedDPadLeft ?? (cachedDPadLeft = GetControl( InputControlType.DPadLeft )); } } public InputControl DPadRight { get { return cachedDPadRight ?? (cachedDPadRight = GetControl( InputControlType.DPadRight )); } } public InputControl Action1 { get { return cachedAction1 ?? (cachedAction1 = GetControl( InputControlType.Action1 )); } } public InputControl Action2 { get { return cachedAction2 ?? (cachedAction2 = GetControl( InputControlType.Action2 )); } } public InputControl Action3 { get { return cachedAction3 ?? (cachedAction3 = GetControl( InputControlType.Action3 )); } } public InputControl Action4 { get { return cachedAction4 ?? (cachedAction4 = GetControl( InputControlType.Action4 )); } } public InputControl LeftTrigger { get { return cachedLeftTrigger ?? (cachedLeftTrigger = GetControl( InputControlType.LeftTrigger )); } } public InputControl RightTrigger { get { return cachedRightTrigger ?? (cachedRightTrigger = GetControl( InputControlType.RightTrigger )); } } public InputControl LeftBumper { get { return cachedLeftBumper ?? (cachedLeftBumper = GetControl( InputControlType.LeftBumper )); } } public InputControl RightBumper { get { return cachedRightBumper ?? (cachedRightBumper = GetControl( InputControlType.RightBumper )); } } public InputControl LeftStickButton { get { return cachedLeftStickButton ?? (cachedLeftStickButton = GetControl( InputControlType.LeftStickButton )); } } public InputControl RightStickButton { get { return cachedRightStickButton ?? (cachedRightStickButton = GetControl( InputControlType.RightStickButton )); } } public InputControl LeftStickX { get { return cachedLeftStickX ?? (cachedLeftStickX = GetControl( InputControlType.LeftStickX )); } } public InputControl LeftStickY { get { return cachedLeftStickY ?? (cachedLeftStickY = GetControl( InputControlType.LeftStickY )); } } public InputControl RightStickX { get { return cachedRightStickX ?? (cachedRightStickX = GetControl( InputControlType.RightStickX )); } } public InputControl RightStickY { get { return cachedRightStickY ?? (cachedRightStickY = GetControl( InputControlType.RightStickY )); } } public InputControl DPadX { get { return cachedDPadX ?? (cachedDPadX = GetControl( InputControlType.DPadX )); } } public InputControl DPadY { get { return cachedDPadY ?? (cachedDPadY = GetControl( InputControlType.DPadY )); } } public InputControl Command { get { return cachedCommand ?? (cachedCommand = GetControl( InputControlType.Command )); } } void ExpireControlCache() { cachedLeftStickUp = null; cachedLeftStickDown = null; cachedLeftStickLeft = null; cachedLeftStickRight = null; cachedRightStickUp = null; cachedRightStickDown = null; cachedRightStickLeft = null; cachedRightStickRight = null; cachedDPadUp = null; cachedDPadDown = null; cachedDPadLeft = null; cachedDPadRight = null; cachedAction1 = null; cachedAction2 = null; cachedAction3 = null; cachedAction4 = null; cachedLeftTrigger = null; cachedRightTrigger = null; cachedLeftBumper = null; cachedRightBumper = null; cachedLeftStickButton = null; cachedRightStickButton = null; cachedLeftStickX = null; cachedLeftStickY = null; cachedRightStickX = null; cachedRightStickY = null; cachedDPadX = null; cachedDPadY = null; cachedCommand = null; } #endregion #region Snapshots for Unknown Devices internal virtual int NumUnknownAnalogs { get { return 0; } } internal virtual int NumUnknownButtons { get { return 0; } } internal virtual bool ReadRawButtonState( int index ) { return false; } internal virtual float ReadRawAnalogValue( int index ) { return 0.0f; } internal void TakeSnapshot() { if (AnalogSnapshot == null) { AnalogSnapshot = new AnalogSnapshotEntry[NumUnknownAnalogs]; } for (var i = 0; i < NumUnknownAnalogs; i++) { var analogValue = Utility.ApplySnapping( ReadRawAnalogValue( i ), 0.5f ); AnalogSnapshot[i].value = analogValue; } } internal UnknownDeviceControl GetFirstPressedAnalog() { if (AnalogSnapshot != null) { for (var index = 0; index < NumUnknownAnalogs; index++) { var control = InputControlType.Analog0 + index; var analogValue = Utility.ApplySnapping( ReadRawAnalogValue( index ), 0.5f ); var analogDelta = analogValue - AnalogSnapshot[index].value; AnalogSnapshot[index].TrackMinMaxValue( analogValue ); if (analogDelta > +0.1f) { analogDelta = AnalogSnapshot[index].maxValue - AnalogSnapshot[index].value; } if (analogDelta < -0.1f) { analogDelta = AnalogSnapshot[index].minValue - AnalogSnapshot[index].value; } if (analogDelta > +1.9f) { return new UnknownDeviceControl( control, InputRangeType.MinusOneToOne ); } if (analogDelta < -0.9f) { return new UnknownDeviceControl( control, InputRangeType.ZeroToMinusOne ); } if (analogDelta > +0.9f) { return new UnknownDeviceControl( control, InputRangeType.ZeroToOne ); } } } return UnknownDeviceControl.None; } internal UnknownDeviceControl GetFirstPressedButton() { for (var index = 0; index < NumUnknownButtons; index++) { if (ReadRawButtonState( index )) { return new UnknownDeviceControl( InputControlType.Button0 + index, InputRangeType.ZeroToOne ); } } return UnknownDeviceControl.None; } #endregion } }
/* Josip Medved <jmedved@jmedved.com> * www.medo64.com * MIT License */ //2021-11-07: Changing delegate signature //2021-10-07: Refactored for .NET 5 //2014-12-20: Added support for .text files //2012-11-24: Suppressing bogus CA5122 warning (http://connect.microsoft.com/VisualStudio/feedback/details/729254/bogus-ca5122-warning-about-p-invoke-declarations-should-not-be-safe-critical) //2012-03-05: Added padding to buttons //2011-09-01: Added DEBUG sufix for DEBUG builds //2010-11-03: Informational version is used for program name // Content background is now in Window system color //2009-10-25: Adjusted disposing of buttons //2008-12-20: Adjusted for high DPI mode //2008-11-05: Refactoring (Microsoft.Maintainability : 'AboutBox.ShowDialog(IWin32Window, Uri, string)' has a cyclomatic complexity of 27, Microsoft.Maintainability : 'AboutBox.ShowDialog(IWin32Window, Uri, string)' is coupled with 38 different types from 10 different namespaces.) //2008-04-11: Cleaned code to match FxCop 1.36 beta 2 (NormalizeStringsToUppercase, SpecifyMarshalingForPInvokeStringArguments) //2008-01-25: Added product title parameter //2008-01-22: Changed caption to "About" instead of "About..." //2008-01-05: Top line now contains product name //2008-01-02: New version namespace Medo.Windows.Forms; using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Text; using System.Windows.Forms; using System.Windows.Forms.VisualStyles; /// <summary> /// Simple about form. /// </summary> [SupportedOSPlatform("windows")] public static class AboutBox { /// <summary> /// Shows modal dialog. /// </summary> public static DialogResult ShowDialog() { lock (SyncRoot) { return ShowDialog(null, null, null); } } /// <summary> /// Shows modal dialog. /// </summary> /// <param name="owner">Any object that implements IWin32Window that represents the top-level window that will own the modal dialog box.</param> public static DialogResult ShowDialog(IWin32Window? owner) { lock (SyncRoot) { return ShowDialog(owner, null, null); } } /// <summary> /// Shows modal dialog. /// </summary> /// <param name="owner">Any object that implements IWin32Window that represents the top-level window that will own the modal dialog box.</param> /// <param name="webpage">URI of program's web page.</param> public static DialogResult ShowDialog(IWin32Window? owner, Uri? webpage) { lock (SyncRoot) { return ShowDialog(owner, webpage, null); } } /// <summary> /// Shows modal dialog. /// </summary> /// <param name="owner">Any object that implements IWin32Window that represents the top-level window that will own the modal dialog box.</param> /// <param name="webpage">URI of program's web page.</param> /// <param name="productName">Title to use. If null, title will be provided from assembly info.</param> public static DialogResult ShowDialog(IWin32Window? owner, Uri? webpage, string? productName) { lock (SyncRoot) { ShowForm(owner, webpage, productName); return DialogResult.OK; } } private static readonly object SyncRoot = new(); private static void ShowForm(IWin32Window? owner, Uri? webpage, string? productName) { var info = new AssemblyInformation(); var defaultFont = SystemFonts.MessageBoxFont ?? SystemFonts.DefaultFont; List<PaintItem> paintItems = new(); using var form = new Form(); form.FormBorderStyle = FormBorderStyle.FixedDialog; form.ShowIcon = false; form.ShowInTaskbar = false; form.MinimizeBox = false; form.MaximizeBox = false; form.AutoSize = false; form.AutoScaleMode = AutoScaleMode.None; form.Text = "About"; var imageHeight = 32; using (var graphics = form.CreateGraphics()) { // icon var bitmap = NativeMethods.GetIconBitmap(info.ExecutablePath); PaintBitmapItem? bitmapItem = null; if (bitmap != null) { bitmapItem = new PaintBitmapItem(bitmap, new Point(7, 7)); paintItems.Add(bitmapItem); } // title var imageRight = 7; if (bitmapItem != null) { imageRight = bitmapItem.Rectangle.Right + 7; imageHeight = bitmapItem.Rectangle.Height; } var productFont = new Font(defaultFont.Name, imageHeight, defaultFont.Style, GraphicsUnit.Pixel, defaultFont.GdiCharSet); var productItem = new PaintTextItem( productName ?? info.ProductName + " " + info.ProductVersion, productFont, imageRight, 7, imageHeight, VerticalAlignment.Center, graphics); paintItems.Add(productItem); // extra stuff var fullNameItem = new PaintTextItem(info.AssemblyNameAndVersion, defaultFont, 7, 7 + imageHeight + 7 + 2 + 7, 0, VerticalAlignment.Top, graphics); paintItems.Add(fullNameItem); var frameworkItem = new PaintTextItem(".NET framework " + Environment.Version.ToString(), defaultFont, 7, fullNameItem.Rectangle.Bottom, 0, VerticalAlignment.Top, graphics); paintItems.Add(frameworkItem); var osItem = new PaintTextItem(Environment.OSVersion.VersionString, defaultFont, 7, frameworkItem.Rectangle.Bottom, 0, VerticalAlignment.Top, graphics); paintItems.Add(osItem); if (info.ProductCopyright != null) { var copyrightItem = new PaintTextItem(info.ProductCopyright, defaultFont, 7, osItem.Rectangle.Bottom + 7, 0, VerticalAlignment.Top, graphics); paintItems.Add(copyrightItem); } } int maxRight = 320; foreach (var item in paintItems) { maxRight = Math.Max(maxRight, item.Rectangle.Right); } int maxBottom = 80; foreach (var item in paintItems) { maxBottom = Math.Max(maxBottom, item.Rectangle.Bottom); } // Close button var closeButton = new Button() { Anchor = AnchorStyles.Right | AnchorStyles.Bottom, AutoSize = true, DialogResult = DialogResult.OK, Padding = new Padding(3, 1, 3, 1), Text = "Close" }; form.Controls.Add(closeButton); closeButton.Location = new Point(form.ClientRectangle.Right - closeButton.Width - 7, form.ClientRectangle.Bottom - closeButton.Height - 7); var buttonLeft = form.ClientRectangle.Left + 7; // Readme button if (info.ReadMePath != null) { var readmeButton = new Button() { Anchor = AnchorStyles.Left | AnchorStyles.Bottom, AutoSize = true, Padding = new Padding(3, 1, 3, 1), Text = "Read Me" }; readmeButton.Click += delegate { try { var path = info.ReadMePath; string? applicationExe = null; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { applicationExe = NativeMethods.AssocQueryString(".txt"); } if (applicationExe != null) { Process.Start(applicationExe, path); } else { Process.Start(path); } } catch (Win32Exception) { } }; form.Controls.Add(readmeButton); readmeButton.Location = new Point(buttonLeft, closeButton.Top); buttonLeft += readmeButton.Width + 7; } // WebPage button if (webpage != null) { var webPageButton = new Button() { Anchor = AnchorStyles.Left | AnchorStyles.Bottom, AutoSize = true, Padding = new Padding(3, 1, 3, 1), Text = "Web page" }; webPageButton.Click += delegate { try { var url = webpage.ToString(); var startInfo = new ProcessStartInfo(url) { UseShellExecute = true }; Process.Start(startInfo); } catch (Win32Exception ex) { Trace.TraceError("[Medo AboutBox] Exception: " + ex.Message); } }; form.Controls.Add(webPageButton); webPageButton.Location = new Point(buttonLeft, closeButton.Top); } var borderX = (form.Width - form.ClientRectangle.Width); var borderY = (form.Height - form.ClientRectangle.Height); form.Width = borderX + maxRight + 7; form.Height = borderY + maxBottom + 11 + 11 + closeButton.Size.Height + 7; if (owner == null) { form.StartPosition = FormStartPosition.CenterScreen; } else { form.StartPosition = FormStartPosition.CenterParent; } form.AcceptButton = closeButton; form.CancelButton = closeButton; form.Paint += delegate (object? sender, PaintEventArgs e) { if (paintItems != null) { e.Graphics.FillRectangle(SystemBrushes.Window, e.ClipRectangle.Left, e.ClipRectangle.Top, e.ClipRectangle.Width, paintItems[^1].Rectangle.Bottom + 11); } if (paintItems != null) { for (var i = 0; i < paintItems.Count; ++i) { paintItems[i].Paint(e.Graphics); } } }; if (owner != null) { if ((owner is Form formOwner) && formOwner.TopMost) { form.TopMost = false; // workaround for some earlier versions form.TopMost = true; } form.ShowDialog(owner); } else { form.ShowDialog(); } } private class AssemblyInformation { public AssemblyInformation() { ProductName = Application.ProductName; ProductVersion = Application.ProductVersion; ExecutablePath = Application.ExecutablePath; foreach (var fileName in new string[] { "README.txt", "readme.txt", "ReadMe.txt" }) { var path = Path.Combine(Application.StartupPath, fileName); if (File.Exists(path)) { ReadMePath = path; break; } } var assembly = Assembly.GetEntryAssembly(); if (assembly != null) { var assemblyName = assembly.GetName(); AssemblyName = assemblyName.Name?.ToString(); AssemblyVersion = assemblyName.Version?.ToString(); var copyrightAttributes = assembly.GetCustomAttributes(typeof(AssemblyCopyrightAttribute), true); if ((copyrightAttributes != null) && (copyrightAttributes.Length >= 1)) { ProductCopyright = ((AssemblyCopyrightAttribute)copyrightAttributes[^1]).Copyright; } } } public string ExecutablePath { get; init; } public string? ReadMePath { get; init; } public string ProductName { get; init; } public string ProductVersion { get; init; } public string? ProductCopyright { get; init; } public string? AssemblyName { get; init; } public string? AssemblyVersion { get; init; } public string AssemblyNameAndVersion { get { string text = AssemblyName ?? ""; if (AssemblyVersion != null) { if (!string.IsNullOrEmpty(text)) { text += " "; } text += AssemblyVersion; } #if DEBUG if (!string.IsNullOrEmpty(text)) { text += " "; } text += "DEBUG"; #endif return text; } } } #region Paint items private abstract class PaintItem { public Point Location { get; init; } public Rectangle Rectangle { get; init; } public abstract void Paint(Graphics graphics); } private sealed class PaintBitmapItem : PaintItem { public PaintBitmapItem(Bitmap image, Point location) { Image = image; Location = location; Rectangle = new Rectangle(location, image.Size); } public override void Paint(Graphics graphics) { graphics.DrawImage(Image, Rectangle); } public Bitmap Image { get; init; } } private sealed class PaintTextItem : PaintItem { public PaintTextItem(string title, Font font, int x, int y, int height, VerticalAlignment align, Graphics measurementGraphics) { Text = title; Font = font; var size = measurementGraphics.MeasureString(title, font, 600).ToSize(); switch (align) { case VerticalAlignment.Top: Location = new Point(x, y); break; case VerticalAlignment.Center: Location = new Point(x, y + (height - size.Height) / 2); break; case VerticalAlignment.Bottom: Location = new Point(x, y + height - size.Height); break; } Rectangle = new Rectangle(Location, size); } public string Text { get; init; } public Font Font { get; private set; } public override void Paint(Graphics graphics) { graphics.DrawString(Text, Font, SystemBrushes.ControlText, Location); } } #endregion Paint items private static class NativeMethods { #region API private const Int32 S_OK = 0; private const Int32 ASSOCF_NONE = 0; private const Int32 ASSOCSTR_EXECUTABLE = 2; [DllImport("user32.dll", CharSet = CharSet.Unicode)] private static extern IntPtr LoadIcon(IntPtr hInstance, String lpIconName); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] private static extern IntPtr LoadLibrary(String lpFileName); [DllImport("Shlwapi.dll", SetLastError = true, CharSet = CharSet.Unicode)] private static extern Int32 AssocQueryString(Int32 flags, Int32 str, String pszAssoc, String? pszExtra, StringBuilder pszOutDWORD, ref Int32 pcchOut); #endregion API internal static Bitmap? GetIconBitmap(string executablePath) { var hLibrary = LoadLibrary(executablePath); if (!hLibrary.Equals(IntPtr.Zero)) { var hIcon = LoadIcon(hLibrary, "#32512"); if (!hIcon.Equals(IntPtr.Zero)) { var bitmap = Icon.FromHandle(hIcon).ToBitmap(); if (bitmap != null) { return bitmap; } } } return null; } internal static string? AssocQueryString(string extension) { var sbExe = new StringBuilder(1024); var len = sbExe.Capacity; if (AssocQueryString(ASSOCF_NONE, ASSOCSTR_EXECUTABLE, extension, null, sbExe, ref len) == NativeMethods.S_OK) { return sbExe.ToString(); } return null; } } }
using Lucene.Net.Support; using System.Diagnostics; namespace Lucene.Net.Codecs.Lucene41 { /* * 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 IndexInput = Lucene.Net.Store.IndexInput; /// <summary> /// Implements the skip list reader for block postings format /// that stores positions and payloads. /// <para/> /// Although this skipper uses MultiLevelSkipListReader as an interface, /// its definition of skip position will be a little different. /// <para/> /// For example, when skipInterval = blockSize = 3, df = 2*skipInterval = 6, /// <para/> /// 0 1 2 3 4 5 /// d d d d d d (posting list) /// ^ ^ (skip point in MultiLeveSkipWriter) /// ^ (skip point in Lucene41SkipWriter) /// <para/> /// In this case, MultiLevelSkipListReader will use the last document as a skip point, /// while Lucene41SkipReader should assume no skip point will comes. /// <para/> /// If we use the interface directly in Lucene41SkipReader, it may silly try to read /// another skip data after the only skip point is loaded. /// <para/> /// To illustrate this, we can call skipTo(d[5]), since skip point d[3] has smaller docId, /// and numSkipped+blockSize== df, the MultiLevelSkipListReader will assume the skip list /// isn't exhausted yet, and try to load a non-existed skip point /// <para/> /// Therefore, we'll trim df before passing it to the interface. see <see cref="Trim(int)"/>. /// </summary> internal sealed class Lucene41SkipReader : MultiLevelSkipListReader { // private boolean DEBUG = Lucene41PostingsReader.DEBUG; private readonly int blockSize; private long[] docPointer; private long[] posPointer; private long[] payPointer; private int[] posBufferUpto; private int[] payloadByteUpto; private long lastPosPointer; private long lastPayPointer; private int lastPayloadByteUpto; private long lastDocPointer; private int lastPosBufferUpto; public Lucene41SkipReader(IndexInput skipStream, int maxSkipLevels, int blockSize, bool hasPos, bool hasOffsets, bool hasPayloads) : base(skipStream, maxSkipLevels, blockSize, 8) { this.blockSize = blockSize; docPointer = new long[maxSkipLevels]; if (hasPos) { posPointer = new long[maxSkipLevels]; posBufferUpto = new int[maxSkipLevels]; if (hasPayloads) { payloadByteUpto = new int[maxSkipLevels]; } else { payloadByteUpto = null; } if (hasOffsets || hasPayloads) { payPointer = new long[maxSkipLevels]; } else { payPointer = null; } } else { posPointer = null; } } /// <summary> /// Trim original docFreq to tell skipReader read proper number of skip points. /// <para/> /// Since our definition in Lucene41Skip* is a little different from MultiLevelSkip* /// this trimmed docFreq will prevent skipReader from: /// 1. silly reading a non-existed skip point after the last block boundary /// 2. moving into the vInt block /// </summary> internal int Trim(int df) { return df % blockSize == 0 ? df - 1 : df; } public void Init(long skipPointer, long docBasePointer, long posBasePointer, long payBasePointer, int df) { base.Init(skipPointer, Trim(df)); lastDocPointer = docBasePointer; lastPosPointer = posBasePointer; lastPayPointer = payBasePointer; Arrays.Fill(docPointer, docBasePointer); if (posPointer != null) { Arrays.Fill(posPointer, posBasePointer); if (payPointer != null) { Arrays.Fill(payPointer, payBasePointer); } } else { Debug.Assert(posBasePointer == 0); } } /// <summary> /// Returns the doc pointer of the doc to which the last call of /// <seealso cref="MultiLevelSkipListReader.SkipTo(int)"/> has skipped. /// </summary> public long DocPointer { get { return lastDocPointer; } } public long PosPointer { get { return lastPosPointer; } } public int PosBufferUpto { get { return lastPosBufferUpto; } } public long PayPointer { get { return lastPayPointer; } } public int PayloadByteUpto { get { return lastPayloadByteUpto; } } public int NextSkipDoc { get { return m_skipDoc[0]; } } protected override void SeekChild(int level) { base.SeekChild(level); // if (DEBUG) { // System.out.println("seekChild level=" + level); // } docPointer[level] = lastDocPointer; if (posPointer != null) { posPointer[level] = lastPosPointer; posBufferUpto[level] = lastPosBufferUpto; if (payloadByteUpto != null) { payloadByteUpto[level] = lastPayloadByteUpto; } if (payPointer != null) { payPointer[level] = lastPayPointer; } } } protected override void SetLastSkipData(int level) { base.SetLastSkipData(level); lastDocPointer = docPointer[level]; // if (DEBUG) { // System.out.println("setLastSkipData level=" + value); // System.out.println(" lastDocPointer=" + lastDocPointer); // } if (posPointer != null) { lastPosPointer = posPointer[level]; lastPosBufferUpto = posBufferUpto[level]; // if (DEBUG) { // System.out.println(" lastPosPointer=" + lastPosPointer + " lastPosBUfferUpto=" + lastPosBufferUpto); // } if (payPointer != null) { lastPayPointer = payPointer[level]; } if (payloadByteUpto != null) { lastPayloadByteUpto = payloadByteUpto[level]; } } } protected override int ReadSkipData(int level, IndexInput skipStream) { // if (DEBUG) { // System.out.println("readSkipData level=" + level); // } int delta = skipStream.ReadVInt32(); // if (DEBUG) { // System.out.println(" delta=" + delta); // } docPointer[level] += skipStream.ReadVInt32(); // if (DEBUG) { // System.out.println(" docFP=" + docPointer[level]); // } if (posPointer != null) { posPointer[level] += skipStream.ReadVInt32(); // if (DEBUG) { // System.out.println(" posFP=" + posPointer[level]); // } posBufferUpto[level] = skipStream.ReadVInt32(); // if (DEBUG) { // System.out.println(" posBufferUpto=" + posBufferUpto[level]); // } if (payloadByteUpto != null) { payloadByteUpto[level] = skipStream.ReadVInt32(); } if (payPointer != null) { payPointer[level] += skipStream.ReadVInt32(); } } return delta; } } }
/* * 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 Nini.Config; using log4net; using System; using System.Reflection; using System.IO; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Xml; using System.Xml.Serialization; using System.Collections.Generic; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using OpenSim.Framework; using OpenSim.Framework.ServiceAuth; using OpenSim.Framework.Servers.HttpServer; using OpenMetaverse; namespace OpenSim.Server.Handlers.GridUser { public class MuteListServerPostHandler : BaseStreamHandler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private IMuteListService m_service; public MuteListServerPostHandler(IMuteListService service, IServiceAuth auth) : base("POST", "/mutelist", auth) { m_service = service; } protected override byte[] ProcessRequest(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { string body; using(StreamReader sr = new StreamReader(requestData)) body = sr.ReadToEnd(); body = body.Trim(); //m_log.DebugFormat("[XXX]: query String: {0}", body); string method = string.Empty; try { Dictionary<string, object> request = ServerUtils.ParseQueryString(body); if (!request.ContainsKey("METHOD")) return FailureResult(); method = request["METHOD"].ToString(); switch (method) { case "get": return getmutes(request); case "update": return updatemute(request); case "delete": return deletemute(request); } m_log.DebugFormat("[MUTELIST HANDLER]: unknown method request: {0}", method); } catch (Exception e) { m_log.DebugFormat("[MUTELIST HANDLER]: Exception in method {0}: {1}", method, e); } return FailureResult(); } byte[] getmutes(Dictionary<string, object> request) { if(!request.ContainsKey("agentid") || !request.ContainsKey("mutecrc")) return FailureResult(); UUID agentID; if(!UUID.TryParse(request["agentid"].ToString(), out agentID)) return FailureResult(); uint mutecrc; if(!UInt32.TryParse(request["mutecrc"].ToString(), out mutecrc)) return FailureResult(); byte[] data = m_service.MuteListRequest(agentID, mutecrc); Dictionary<string, object> result = new Dictionary<string, object>(); result["result"] = Convert.ToBase64String(data); string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID USER HANDLER]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] updatemute(Dictionary<string, object> request) { if(!request.ContainsKey("agentid") || !request.ContainsKey("muteid")) return FailureResult(); MuteData mute = new MuteData(); if( !UUID.TryParse(request["agentid"].ToString(), out mute.AgentID)) return FailureResult(); if(!UUID.TryParse(request["muteid"].ToString(), out mute.MuteID)) return FailureResult(); if(request.ContainsKey("mutename")) { mute.MuteName = request["mutename"].ToString(); } else mute.MuteName = String.Empty; if(request.ContainsKey("mutetype")) { if(!Int32.TryParse(request["mutetype"].ToString(), out mute.MuteType)) return FailureResult(); } else mute.MuteType = 0; if(request.ContainsKey("muteflags")) { if(!Int32.TryParse(request["muteflags"].ToString(), out mute.MuteFlags)) return FailureResult(); } else mute.MuteFlags = 0; if(request.ContainsKey("mutestamp")) { if(!Int32.TryParse(request["mutestamp"].ToString(), out mute.Stamp)) return FailureResult(); } else mute.Stamp = Util.UnixTimeSinceEpoch(); return m_service.UpdateMute(mute) ? SuccessResult() : FailureResult(); } byte[] deletemute(Dictionary<string, object> request) { if(!request.ContainsKey("agentid") || !request.ContainsKey("muteid")) return FailureResult(); UUID agentID; if( !UUID.TryParse(request["agentid"].ToString(), out agentID)) return FailureResult(); UUID muteID; if(!UUID.TryParse(request["muteid"].ToString(), out muteID)) return FailureResult(); string muteName; if(request.ContainsKey("mutename")) { muteName = request["mutename"].ToString(); } else muteName = String.Empty; return m_service.RemoveMute(agentID, muteID, muteName) ? SuccessResult() : FailureResult(); } private byte[] SuccessResult() { XmlDocument doc = new XmlDocument(); XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); doc.AppendChild(xmlnode); XmlElement rootElement = doc.CreateElement("", "ServerResponse", ""); doc.AppendChild(rootElement); XmlElement result = doc.CreateElement("", "result", ""); result.AppendChild(doc.CreateTextNode("Success")); rootElement.AppendChild(result); return Util.DocToBytes(doc); } private byte[] FailureResult() { XmlDocument doc = new XmlDocument(); XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); doc.AppendChild(xmlnode); XmlElement rootElement = doc.CreateElement("", "ServerResponse", ""); doc.AppendChild(rootElement); XmlElement result = doc.CreateElement("", "result", ""); result.AppendChild(doc.CreateTextNode("Failure")); rootElement.AppendChild(result); return Util.DocToBytes(doc); } } }
// 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.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text; using Microsoft.Protocols.TestTools.StackSdk.Messages; using Microsoft.Protocols.TestTools.StackSdk.Security.Nlmp; using Microsoft.Protocols.TestTools.StackSdk.Security.Sspi; namespace Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Cifs { /// <summary> /// this class provide static utilities /// </summary> [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] public static class CifsMessageUtils { #region constants //default constants internal const string DIALECT_PCLAN = "PCLAN1.0"; internal const string DIALECT_PCNETWORK_PROGRAM = "PC NETWORK PROGRAM 1.0"; internal const string DIALECT_NTLANMAN = "NT LM 0.12"; internal const string NATIVE_OS = "Windows Vista (TM) Enterprise 6001 Service Pack 1"; internal const string NATIVE_LANMAN = "Windows Vista (TM) Enterprise 6.0"; internal const string NATIVE_FS = "NTFS"; internal const string IPC_CONNECT_STRING = "IPC$"; internal const string TREE_CONNECT_SERVICE = "?????"; internal const uint SMB_PROTOCOL_IDENTIFIER = 0x424D53FF; // 0xFF, 'S', 'M', 'B' internal const uint SMB_PROTOCOL_IDENTIFIER_ASYNC = 0x424D5300; // 0x00, 'S', 'M', 'B' internal const ushort INVALID_MID = 0xFFFF; //SDK use 0FF to indicate current packet is a andx packet. very useful when updating context. //since andx packet does not has a header,they share the first leading packet. internal const uint SMB_PROTOCOL_ANDXPACKET = 0xFF; /// <summary> /// Minimal smb packet length /// </summary> public const int PACKET_MINIMUM_LENGTH = 35; #endregion #region encode & decode /// <summary> /// To convert a struct to byte array. /// </summary> /// <typeparam name="T">The struct type.</typeparam> /// <param name="t">The struct to be converted.</param> /// <returns> /// Return the byte array converted from a struct. /// </returns> /// <exception cref="System.ArgumentException"> /// The sum of offset and count is greater than the buffer length.</exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// offset or count is negative.</exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// offset or count is negative.</exception> /// <exception cref="System.InvalidOperationException"> /// fail in GetSize of MessageUtils.</exception> public static byte[] ToBytes<T>(T t) { using (MessageUtils utils = new MessageUtils(null)) { int size = utils.GetSize(t); byte[] rawBytes = new byte[size]; using (MemoryStream memoryStream = new MemoryStream(rawBytes)) { using (Channel channel = new Channel(null, memoryStream)) { channel.BeginWriteGroup(); channel.Write<T>(t); channel.EndWriteGroup(); int actualSize = (int)channel.Stream.Position; byte[] actualBytes = new byte[actualSize]; Array.Copy(rawBytes, actualBytes, actualSize); return actualBytes; } } } } /// <summary> /// To convert a byte array to a struct. /// </summary> /// <typeparam name="T">The struct type.</typeparam> /// <param name="data">The byte array to be converted.</param> /// <returns> /// The struct converted from byte array. /// </returns> /// <exception cref="System.ArgumentException"> /// The sum of offset and count is greater than the buffer length.</exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// offset or count is negative.</exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// offset or count is negative.</exception> [SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")] public static T ToStuct<T>(byte[] data) { using (MemoryStream memoryStream = new MemoryStream(data)) { using (Channel channel = new Channel(null, memoryStream)) { return channel.Read<T>(); } } } /// <summary> /// To get the size in bytes of a structure. /// </summary> /// <typeparam name="T">The struct type.</typeparam> /// <param name="t">The structure to be sized.</param> /// <returns> /// Return the size in bytes of the structure. /// </returns> /// <exception cref="System.InvalidOperationException"> /// fail in GetSize of MessageUtils.</exception> public static int GetSize<T>(T t) where T : struct { return TypeMarshal.GetBlockMemorySize(t); } #endregion #region convert array /// <summary> /// convert a primitive type array to a byte array. /// </summary> /// <param name="source">a primitive type array</param> /// <returns>a byte array</returns> public static byte[] ToBytesArray<T>(T[] source) { byte[] dest = null; if (source != null) { if (source.Length == 0) { dest = new byte[0]; } else { dest = new byte[Marshal.SizeOf(typeof(T)) * source.Length]; Buffer.BlockCopy(source, 0, dest, 0, dest.Length); } } return dest; } /// <summary> /// convert a byte array to a primitive type array. /// </summary> /// <param name="source">a byte array</param> /// <returns>a primitive type array</returns> [SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")] public static T[] ToTypeArray<T>(byte[] source) { T[] dest = null; if (source == null || source.Length == 0) { dest = new T[0]; } else { int size = Marshal.SizeOf(typeof(T)); dest = new T[(int)Math.Ceiling((double)source.Length / size)]; Buffer.BlockCopy(source, 0, dest, 0, source.Length); } return dest; } /// <summary> /// To convert a string to the bytes of SMB_String. /// </summary> /// <param name="smbString">the string without null-terminator to be converted.</param> /// <param name="isUnicode">the encoding type. Unicode if true, otherwise ASCII.</param> /// <returns>the bytes in Unicode/ASCII formate with a NULL-terminated.</returns> public static byte[] ToSmbStringBytes(string smbString, bool isUnicode) { if (smbString == null) { throw new ArgumentNullException("smbString"); } if (isUnicode) { return Encoding.Unicode.GetBytes(smbString + "\0"); } else { return Encoding.ASCII.GetBytes(smbString + "\0"); } } /// <summary> /// Get String from a buffer. /// </summary> /// <param name="bytes">a byte array</param> /// <param name="smbFlags2">The smbFlags2 of the SmbHeader to which this bytes belong to</param> /// <returns>the string</returns> public static string ToString(byte[] bytes, SmbFlags2 smbFlags2) { if (bytes == null) { return string.Empty; } if ((smbFlags2 & SmbFlags2.SMB_FLAGS2_UNICODE) == SmbFlags2.SMB_FLAGS2_UNICODE) { return Encoding.Unicode.GetString(bytes, 0, bytes.Length - 2); } else { return Encoding.ASCII.GetString(bytes, 0, bytes.Length - 1); } } /// <summary> /// To convert the bytes in ASCII formate with a NUL-terminated to SMB_String. /// </summary> /// <param name="bytes">the bytes in ASCII formate with a NUL-terminated.</param> /// <param name="startIndex">the start index of the .</param> /// <param name="withFormat">there is 1 byte BufferFormat in the bytes or not.</param> /// <returns>the string to be converted.</returns> public static string ToSmbString(byte[] bytes, int startIndex, bool withFormat) { if (bytes == null) { throw new ArgumentNullException("bytes"); } int formatLen = 0; if (withFormat) { formatLen = 1; } int endIndex = Array.IndexOf<byte>(bytes, 0, startIndex); if (endIndex >= 0) { if (bytes.Length >= (startIndex + formatLen + 1)) { return Encoding.ASCII.GetString(bytes, startIndex + formatLen, endIndex - (startIndex + formatLen)); } else { throw new ArgumentOutOfRangeException("startIndex", "The startIndex should be inside the length of bytes."); } } else { throw new ArgumentException("The bytes of SmbString should include a null-terminator.", "bytes"); } } #endregion #region get size /// <summary> /// Get the total size of a SmbEa array /// </summary> /// <param name="extendedAttributeList">a SmbEa array</param> /// <returns>the size</returns> internal static uint GetSmbEAListSize(SMB_FEA[] extendedAttributeList) { uint sizeOfListInBytes = 0; if (extendedAttributeList != null) { foreach (SMB_FEA smbEa in extendedAttributeList) { sizeOfListInBytes += (uint)EA.SMB_EA_FIXED_SIZE; if (smbEa.AttributeName != null) { sizeOfListInBytes += (uint)smbEa.AttributeName.Length; } if (smbEa.ValueName != null) { sizeOfListInBytes += (uint)smbEa.ValueName.Length; } } } return sizeOfListInBytes; } /// <summary> /// Get the total size of a SmbQueryEa array /// </summary> /// <param name="extendedAttributeList">a SmbQueryEa array</param> /// <returns>the size</returns> internal static uint GetSmbQueryEAListSize(SMB_GEA[] extendedAttributeList) { uint sizeOfListInBytes = 0; if (extendedAttributeList != null) { foreach (SMB_GEA smbQueryEa in extendedAttributeList) { sizeOfListInBytes += (uint)EA.SMB_QUERY_EA_FIXED_SIZE; if (smbQueryEa.AttributeName != null) { sizeOfListInBytes += (uint)smbQueryEa.AttributeName.Length; } } } return sizeOfListInBytes; } #endregion #region Read a null terminated string from channel /// <summary> /// Read a null terminated UNICODE or ASCII string from channel. /// </summary> /// <param name="channel">the channel from which the string will be read.</param> /// <param name="isUnicode">if true, the string formate is UNICODE, otherwise ASCII.</param> /// <returns>the binary string with null terminator.</returns> internal static byte[] ReadNullTerminatedString(Channel channel, bool isUnicode) { int byteCount = 0; while (true) { if (isUnicode) { byte data0 = channel.Peek<byte>(byteCount++); byte data1 = channel.Peek<byte>(byteCount++); if (data0 == 0 && data1 == 0) { break; } } else { byte data = channel.Peek<byte>(byteCount++); if (data == 0) { break; } } } return channel.ReadBytes(byteCount); } #endregion #region create packet header /// <summary> /// a full smb header create function /// </summary> /// <param name="command">The operation code that this SMB is requesting or responding to.</param> /// <param name="pid">Caller's process ID</param> /// <param name="mid">This field SHOULD be the multiplex ID that is used to associate a /// response with a request.</param> /// <param name="uid">This field SHOULD identify the authenticated instance of the user.</param> /// <param name="tid">This field identifies the subdirectory (or tree) on the server that the /// client is accessing.</param> /// <param name="flags">The Flags field contains individual flags.</param> /// <param name="flags2"> /// The Flags2 field contains individual bit flags /// that, depending on the negotiated SMB dialect, indicate /// various client and server capabilities. /// </param> /// <returns>smb header</returns> public static SmbHeader CreateSmbHeader( SmbCommand command, uint pid, ushort mid, ushort uid, ushort tid, SmbFlags flags, SmbFlags2 flags2) { SmbHeader header = new SmbHeader(); // (0xFF, 'S', 'M', 'B') header.Protocol = SMB_PROTOCOL_IDENTIFIER; header.Status = 0; header.PidHigh = (ushort)((pid >> 16) & 0xffff); header.Reserved = 0x0; header.Command = command; header.Flags = flags; header.Flags2 = flags2; header.SecurityFeatures = 0; header.Tid = tid; header.PidLow = (ushort)(pid & 0xffff); header.Uid = uid; header.Mid = mid; return header; } /// <summary> /// a full smb header create function /// </summary> /// <param name="command">The operation code that this SMB is requesting or responding to.</param> /// <param name="mid">This field SHOULD be the multiplex ID that is used to associate a /// response with a request.</param> /// <param name="uid">This field SHOULD identify the authenticated instance of the user.</param> /// <param name="tid">This field identifies the subdirectory (or tree) on the server that the /// client is accessing.</param> /// <param name="flags">it describes various features in effect for the message.</param> /// <param name="flags2">it represents various features in effect for the message.</param> /// <returns>smb header</returns> public static SmbHeader CreateSmbHeader( SmbCommand command, ushort mid, ushort uid, ushort tid, SmbFlags flags, SmbFlags2 flags2) { return CreateSmbHeader(command, 0, mid, uid, tid, flags, flags2); } /// <summary> /// a full smb header create function /// </summary> /// <param name="connection">the connection to which the packet belongs</param> /// <param name="request">the request packet</param> /// <returns>smb header</returns> /// <exception cref="KeyNotFoundException">The request is not pending in this connection.</exception> public static SmbHeader CreateSmbHeader( CifsServerPerConnection connection, SmbPacket request) { if (request == null) { throw new ArgumentNullException("request"); } if (request.SmbHeader.Protocol == SMB_PROTOCOL_IDENTIFIER // 0xFF, 'S', 'M', 'B' && !connection.PendingRequestTable.Contains(request)) { throw new KeyNotFoundException("The request is not pending in this connection."); } SmbHeader smbHeader = smbHeader = request.SmbHeader; smbHeader.Status = 0; smbHeader.SecurityFeatures = 0; smbHeader.Flags |= SmbFlags.SMB_FLAGS_REPLY; return smbHeader; } #endregion #region create response packet /// <summary> /// to new a Smb response packet in type of the Command in SmbHeader. /// </summary> /// <param name="request">the request of the response.</param> /// <param name="smbHeader">the SMB header of the packet.</param> /// <param name="channel">the channel started with SmbParameters.</param> /// <returns> /// the new response packet. /// the null means that the utility don't know how to create the response. /// </returns> [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] [SuppressMessage("Microsoft.Maintainability", "CA1505:AvoidUnmantainableCode")] [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] internal static SmbPacket CreateSmbResponsePacket( SmbPacket request, SmbHeader smbHeader, Channel channel) { SmbPacket smbPacket = null; switch (smbHeader.Command) { case SmbCommand.SMB_COM_CREATE_DIRECTORY: // 0x00, smbPacket = new SmbCreateDirectoryResponsePacket(); break; case SmbCommand.SMB_COM_DELETE_DIRECTORY: // 0x01, smbPacket = new SmbDeleteDirectoryResponsePacket(); break; case SmbCommand.SMB_COM_OPEN: // 0x02, smbPacket = new SmbOpenResponsePacket(); break; case SmbCommand.SMB_COM_CREATE: // 0x03, smbPacket = new SmbCreateResponsePacket(); break; case SmbCommand.SMB_COM_CLOSE: // 0x04, smbPacket = new SmbCloseResponsePacket(); break; case SmbCommand.SMB_COM_FLUSH: // 0x05, smbPacket = new SmbFlushResponsePacket(); break; case SmbCommand.SMB_COM_DELETE: // 0x06, smbPacket = new SmbDeleteResponsePacket(); break; case SmbCommand.SMB_COM_RENAME: // 0x07, smbPacket = new SmbRenameResponsePacket(); break; case SmbCommand.SMB_COM_QUERY_INFORMATION: // 0x08, smbPacket = new SmbQueryInformationResponsePacket(); break; case SmbCommand.SMB_COM_SET_INFORMATION: // 0x09, smbPacket = new SmbSetInformationResponsePacket(); break; case SmbCommand.SMB_COM_READ: // 0x0A, smbPacket = new SmbReadResponsePacket(); break; case SmbCommand.SMB_COM_WRITE: // 0x0B, smbPacket = new SmbWriteResponsePacket(); break; case SmbCommand.SMB_COM_LOCK_byte_RANGE: // 0x0C, smbPacket = new SmbLockByteRangeResponsePacket(); break; case SmbCommand.SMB_COM_UNLOCK_byte_RANGE: // 0x0D, smbPacket = new SmbUnlockByteRangeResponsePacket(); break; case SmbCommand.SMB_COM_CREATE_TEMPORARY: // 0x0E, smbPacket = new SmbCreateTemporaryResponsePacket(); break; case SmbCommand.SMB_COM_CREATE_NEW: // 0x0F, smbPacket = new SmbCreateNewResponsePacket(); break; case SmbCommand.SMB_COM_CHECK_DIRECTORY: // 0x10, smbPacket = new SmbCheckDirectoryResponsePacket(); break; case SmbCommand.SMB_COM_PROCESS_EXIT: // 0x11, smbPacket = new SmbProcessExitResponsePacket(); break; case SmbCommand.SMB_COM_SEEK: // 0x12, smbPacket = new SmbSeekResponsePacket(); break; case SmbCommand.SMB_COM_LOCK_AND_READ: // 0x13, smbPacket = new SmbLockAndReadResponsePacket(); break; case SmbCommand.SMB_COM_WRITE_AND_UNLOCK: // 0x14, smbPacket = new SmbWriteAndUnlockResponsePacket(); break; case SmbCommand.SMB_COM_READ_RAW: // 0x1A, smbPacket = new SmbReadRawResponsePacket(); break; case SmbCommand.SMB_COM_READ_MPX: // 0x1B, smbPacket = new SmbReadMpxResponsePacket(); break; case SmbCommand.SMB_COM_READ_MPX_SECONDARY: // 0x1C, smbPacket = new SmbReadMpxSecondaryResponsePacket(); break; case SmbCommand.SMB_COM_WRITE_RAW: // 0x1D, smbPacket = new SmbWriteRawInterimResponsePacket(); break; case SmbCommand.SMB_COM_WRITE_MPX: // 0x1E, smbPacket = new SmbWriteMpxResponsePacket(); break; case SmbCommand.SMB_COM_WRITE_MPX_SECONDARY: // 0x1F, smbPacket = new SmbWriteMpxSecondaryResponsePacket(); break; case SmbCommand.SMB_COM_WRITE_COMPLETE: // 0x20, // This command was introduced in LAN Manager 1.0 dialect. This command is deprecated. // This commandis sent by the server in the final response of an SMB_COM_WRITE_RAW command. // See SMB_COM_WRITE_RAW for details. smbPacket = new SmbWriteRawFinalResponsePacket(); break; case SmbCommand.SMB_COM_QUERY_SERVER: // 0x21, smbPacket = new SmbQueryServerResponsePacket(); break; case SmbCommand.SMB_COM_SET_INFORMATION2: // 0x22, smbPacket = new SmbSetInformation2ResponsePacket(); break; case SmbCommand.SMB_COM_QUERY_INFORMATION2: // 0x23, smbPacket = new SmbQueryInformation2ResponsePacket(); break; case SmbCommand.SMB_COM_LOCKING_ANDX: // 0x24, if (request != null) { smbPacket = new SmbLockingAndxResponsePacket(); } else { //OpLock Break Notification sent by server smbPacket = new SmbLockingAndxRequestPacket(); } break; case SmbCommand.SMB_COM_TRANSACTION: // 0x25, // The format of the SMB_COM_TRANSACTION Interim Server Response message MUST be an SMB header // with an empty Parameter and Data section and the WordCount and ByteCount fields MUST be zero. if (smbHeader.Status == 0 && channel.Peek<byte>(0) == 0 && channel.Peek<ushort>(1) == 0) { smbPacket = new SmbTransactionInterimResponsePacket(); } else { SmbTransactionRequestPacket transactionRequest = request as SmbTransactionRequestPacket; if (transactionRequest != null) { smbPacket = CreateSmbTransResponsePacket( (TransSubCommand)transactionRequest.SmbParameters.Setup[0]); } } break; case SmbCommand.SMB_COM_IOCTL: // 0x27, smbPacket = new SmbIoctlResponsePacket(); break; case SmbCommand.SMB_COM_IOCTL_SECONDARY: // 0x28, smbPacket = new SmbIoctlSecondaryResponsePacket(); break; case SmbCommand.SMB_COM_COPY: // 0x29, smbPacket = new SmbCopyResponsePacket(); break; case SmbCommand.SMB_COM_MOVE: // 0x2A, smbPacket = new SmbMoveResponsePacket(); break; case SmbCommand.SMB_COM_ECHO: // 0x2B, smbPacket = new SmbEchoResponsePacket(); break; case SmbCommand.SMB_COM_WRITE_AND_CLOSE: // 0x2C, smbPacket = new SmbWriteAndCloseResponsePacket(); break; case SmbCommand.SMB_COM_OPEN_ANDX: // 0x2D, smbPacket = new SmbOpenAndxResponsePacket(); break; case SmbCommand.SMB_COM_READ_ANDX: // 0x2E, smbPacket = new SmbReadAndxResponsePacket(); break; case SmbCommand.SMB_COM_WRITE_ANDX: // 0x2F, smbPacket = new SmbWriteAndxResponsePacket(); break; case SmbCommand.SMB_COM_NEW_FILE_SIZE: // 0x30, smbPacket = new SmbNewFileSizeResponsePacket(); break; case SmbCommand.SMB_COM_CLOSE_AND_TREE_DISC: // 0x31, smbPacket = new SmbCloseAndTreeDiscResponsePacket(); break; case SmbCommand.SMB_COM_TRANSACTION2: // 0x32, // The format of the SMB_COM_TRANSACTION2 Interim Server Response message MUST be an SMB header // with an empty Parameter and Data section and the WordCount and ByteCount fields MUST be zero. if (smbHeader.Status == 0 && channel.Peek<byte>(0) == 0 && channel.Peek<ushort>(1) == 0) { smbPacket = new SmbTransaction2InterimResponsePacket(); } else { SmbTransaction2RequestPacket transaction2Request = request as SmbTransaction2RequestPacket; if (transaction2Request != null) { smbPacket = CreateSmbTrans2ResponsePacket(transaction2Request); } } break; case SmbCommand.SMB_COM_FIND_CLOSE2: // 0x34, smbPacket = new SmbFindClose2ResponsePacket(); break; case SmbCommand.SMB_COM_FIND_NOTIFY_CLOSE: // 0x35, smbPacket = new SmbFindNotifyCloseResponsePacket(); break; case SmbCommand.SMB_COM_TREE_CONNECT: // 0x70, smbPacket = new SmbTreeConnectResponsePacket(); break; case SmbCommand.SMB_COM_TREE_DISCONNECT: // 0x71, smbPacket = new SmbTreeDisconnectResponsePacket(); break; case SmbCommand.SMB_COM_NEGOTIATE: // 0x72, smbPacket = new SmbNegotiateResponsePacket(); break; case SmbCommand.SMB_COM_SESSION_SETUP_ANDX: // 0x73, smbPacket = new SmbSessionSetupAndxResponsePacket(); break; case SmbCommand.SMB_COM_LOGOFF_ANDX: // 0x74, smbPacket = new SmbLogoffAndxResponsePacket(); break; case SmbCommand.SMB_COM_TREE_CONNECT_ANDX: // 0x75, smbPacket = new SmbTreeConnectAndxResponsePacket(); break; case SmbCommand.SMB_COM_SECURITY_PACKAGE_ANDX: // 0x7E, smbPacket = new SmbSecurityPackageAndxResponsePacket(); break; case SmbCommand.SMB_COM_QUERY_INFORMATION_DISK: // 0x80, smbPacket = new SmbQueryInformationDiskResponsePacket(); break; case SmbCommand.SMB_COM_SEARCH: // 0x81, smbPacket = new SmbSearchResponsePacket(); break; case SmbCommand.SMB_COM_FIND: // 0x82, smbPacket = new SmbFindResponsePacket(); break; case SmbCommand.SMB_COM_FIND_UNIQUE: // 0x83, smbPacket = new SmbFindUniqueResponsePacket(); break; case SmbCommand.SMB_COM_FIND_CLOSE: // 0x84, smbPacket = new SmbFindCloseResponsePacket(); break; case SmbCommand.SMB_COM_NT_TRANSACT: // 0xA0, // The format of the SMB_COM_NT_TRANSACTION Interim Server Response message MUST be an SMB header // with an empty Parameter and Data section and the WordCount and ByteCount fields MUST be zero. if (smbHeader.Status == 0 && channel.Peek<byte>(0) == 0 && channel.Peek<ushort>(1) == 0) { smbPacket = new SmbNtTransactInterimResponsePacket(); } else { SmbNtTransactRequestPacket ntTransactRequest = request as SmbNtTransactRequestPacket; if (ntTransactRequest != null) { smbPacket = CreateSmbNtTransResponsePacket( (NtTransSubCommand)ntTransactRequest.SmbParameters.Function); } } break; case SmbCommand.SMB_COM_NT_CREATE_ANDX: // 0xA2, smbPacket = new SmbNtCreateAndxResponsePacket(); break; case SmbCommand.SMB_COM_NT_RENAME: // 0xA5, smbPacket = new SmbNtRenameResponsePacket(); break; case SmbCommand.SMB_COM_OPEN_PRINT_FILE: // 0xC0, smbPacket = new SmbOpenPrintFileResponsePacket(); break; case SmbCommand.SMB_COM_WRITE_PRINT_FILE: // 0xC1, smbPacket = new SmbWritePrintFileResponsePacket(); break; case SmbCommand.SMB_COM_CLOSE_PRINT_FILE: // 0xC2, smbPacket = new SmbClosePrintFileResponsePacket(); break; case SmbCommand.SMB_COM_GET_PRINT_QUEUE: // 0xC3, smbPacket = new SmbGetPrintQueueResponsePacket(); break; case SmbCommand.SMB_COM_READ_BULK: // 0xD8, smbPacket = new SmbReadBulkResponsePacket(); break; case SmbCommand.SMB_COM_WRITE_BULK: // 0xD9, smbPacket = new SmbWriteBulkResponsePacket(); break; case SmbCommand.SMB_COM_WRITE_BULK_DATA: // 0xDA, smbPacket = new SmbWriteBulkDataResponsePacket(); break; case SmbCommand.SMB_COM_INVALID: // 0xFE, smbPacket = new SmbInvalidResponsePacket(); break; case SmbCommand.SMB_COM_NO_ANDX_COMMAND: // 0xFF, smbPacket = new SmbNoAndxCommandResponsePacket(); break; } if (smbPacket != null) { smbPacket.SmbHeader = smbHeader; } return smbPacket; } #endregion #region create request packet /// <summary> /// create request packet in type of the command of smbheader. /// </summary> /// <param name="smbHeader">the header of smb packet</param> /// <param name="channel">the channel to access bytes</param> /// <returns>the target packet</returns> [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] internal static SmbPacket CreateSmbRequestPacket(SmbHeader smbHeader, Channel channel) { SmbPacket smbPacket = null; switch (smbHeader.Command) { #region Smb Com command case SmbCommand.SMB_COM_CREATE_DIRECTORY: // 0x00, smbPacket = new SmbCreateDirectoryRequestPacket(); break; case SmbCommand.SMB_COM_DELETE_DIRECTORY: // 0x01, smbPacket = new SmbDeleteDirectoryRequestPacket(); break; case SmbCommand.SMB_COM_OPEN: // 0x02, smbPacket = new SmbOpenRequestPacket(); break; case SmbCommand.SMB_COM_CREATE: // 0x03, smbPacket = new SmbCreateRequestPacket(); break; case SmbCommand.SMB_COM_CLOSE: // 0x04, smbPacket = new SmbCloseRequestPacket(); break; case SmbCommand.SMB_COM_FLUSH: // 0x05, smbPacket = new SmbFlushRequestPacket(); break; case SmbCommand.SMB_COM_DELETE: // 0x06, smbPacket = new SmbDeleteRequestPacket(); break; case SmbCommand.SMB_COM_RENAME: // 0x07, smbPacket = new SmbRenameRequestPacket(); break; case SmbCommand.SMB_COM_QUERY_INFORMATION: // 0x08, smbPacket = new SmbQueryInformationRequestPacket(); break; case SmbCommand.SMB_COM_SET_INFORMATION: // 0x09, smbPacket = new SmbSetInformationRequestPacket(); break; case SmbCommand.SMB_COM_READ: // 0x0A, smbPacket = new SmbReadRequestPacket(); break; case SmbCommand.SMB_COM_WRITE: // 0x0B, smbPacket = new SmbWriteRequestPacket(); break; case SmbCommand.SMB_COM_LOCK_byte_RANGE: // 0x0C, smbPacket = new SmbLockByteRangeRequestPacket(); break; case SmbCommand.SMB_COM_UNLOCK_byte_RANGE: // 0x0D, smbPacket = new SmbUnlockByteRangeRequestPacket(); break; case SmbCommand.SMB_COM_CREATE_TEMPORARY: // 0x0E, smbPacket = new SmbCreateTemporaryRequestPacket(); break; case SmbCommand.SMB_COM_CREATE_NEW: // 0x0F, smbPacket = new SmbCreateNewRequestPacket(); break; case SmbCommand.SMB_COM_CHECK_DIRECTORY: // 0x10, smbPacket = new SmbCheckDirectoryRequestPacket(); break; case SmbCommand.SMB_COM_PROCESS_EXIT: // 0x11, smbPacket = new SmbProcessExitRequestPacket(); break; case SmbCommand.SMB_COM_SEEK: // 0x12, smbPacket = new SmbSeekRequestPacket(); break; case SmbCommand.SMB_COM_LOCK_AND_READ: // 0x13, smbPacket = new SmbLockAndReadRequestPacket(); break; case SmbCommand.SMB_COM_WRITE_AND_UNLOCK: // 0x14, smbPacket = new SmbWriteAndUnlockRequestPacket(); break; case SmbCommand.SMB_COM_READ_RAW: // 0x1A, smbPacket = new SmbReadRawRequestPacket(); break; case SmbCommand.SMB_COM_READ_MPX: // 0x1B, smbPacket = new SmbReadMpxRequestPacket(); break; case SmbCommand.SMB_COM_READ_MPX_SECONDARY: // 0x1C, smbPacket = new SmbReadMpxSecondaryRequestPacket(); break; case SmbCommand.SMB_COM_WRITE_RAW: // 0x1D, smbPacket = new SmbWriteRawRequestPacket(); break; case SmbCommand.SMB_COM_WRITE_MPX: // 0x1E, smbPacket = new SmbWriteMpxRequestPacket(); break; case SmbCommand.SMB_COM_WRITE_MPX_SECONDARY: // 0x1F, smbPacket = new SmbWriteMpxSecondaryRequestPacket(); break; case SmbCommand.SMB_COM_QUERY_SERVER: // 0x21, smbPacket = new SmbQueryServerRequestPacket(); break; case SmbCommand.SMB_COM_SET_INFORMATION2: // 0x22, smbPacket = new SmbSetInformation2RequestPacket(); break; case SmbCommand.SMB_COM_QUERY_INFORMATION2: // 0x23, smbPacket = new SmbQueryInformation2RequestPacket(); break; case SmbCommand.SMB_COM_LOCKING_ANDX: // 0x24, smbPacket = new SmbLockingAndxRequestPacket(); break; case SmbCommand.SMB_COM_IOCTL: // 0x27, smbPacket = new SmbIoctlRequestPacket(); break; case SmbCommand.SMB_COM_IOCTL_SECONDARY: // 0x28, smbPacket = new SmbIoctlSecondaryRequestPacket(); break; case SmbCommand.SMB_COM_COPY: // 0x29, smbPacket = new SmbCopyRequestPacket(); break; case SmbCommand.SMB_COM_MOVE: // 0x2A, smbPacket = new SmbMoveRequestPacket(); break; case SmbCommand.SMB_COM_ECHO: // 0x2B, smbPacket = new SmbEchoRequestPacket(); break; case SmbCommand.SMB_COM_WRITE_AND_CLOSE: // 0x2C, smbPacket = new SmbWriteAndCloseRequestPacket(); break; case SmbCommand.SMB_COM_OPEN_ANDX: // 0x2D, smbPacket = new SmbOpenAndxRequestPacket(); break; case SmbCommand.SMB_COM_READ_ANDX: // 0x2E, smbPacket = new SmbReadAndxRequestPacket(); break; case SmbCommand.SMB_COM_WRITE_ANDX: // 0x2F, smbPacket = new SmbWriteAndxRequestPacket(); break; case SmbCommand.SMB_COM_NEW_FILE_SIZE: // 0x30, smbPacket = new SmbNewFileSizeRequestPacket(); break; case SmbCommand.SMB_COM_CLOSE_AND_TREE_DISC: // 0x31, smbPacket = new SmbCloseAndTreeDiscRequestPacket(); break; case SmbCommand.SMB_COM_FIND_CLOSE2: // 0x34, smbPacket = new SmbFindClose2RequestPacket(); break; case SmbCommand.SMB_COM_FIND_NOTIFY_CLOSE: // 0x35, smbPacket = new SmbFindNotifyCloseRequestPacket(); break; case SmbCommand.SMB_COM_TREE_CONNECT: // 0x70, smbPacket = new SmbTreeConnectRequestPacket(); break; case SmbCommand.SMB_COM_TREE_DISCONNECT: // 0x71, smbPacket = new SmbTreeDisconnectRequestPacket(); break; case SmbCommand.SMB_COM_NEGOTIATE: // 0x72, smbPacket = new SmbNegotiateRequestPacket(); break; case SmbCommand.SMB_COM_SESSION_SETUP_ANDX: // 0x73, smbPacket = new SmbSessionSetupAndxRequestPacket(); break; case SmbCommand.SMB_COM_LOGOFF_ANDX: // 0x74, smbPacket = new SmbLogoffAndxRequestPacket(); break; case SmbCommand.SMB_COM_TREE_CONNECT_ANDX: // 0x75, smbPacket = new SmbTreeConnectAndxRequestPacket(); break; case SmbCommand.SMB_COM_SECURITY_PACKAGE_ANDX: // 0x7E, smbPacket = new SmbSecurityPackageAndxRequestPacket(); break; case SmbCommand.SMB_COM_QUERY_INFORMATION_DISK: // 0x80, smbPacket = new SmbQueryInformationDiskRequestPacket(); break; case SmbCommand.SMB_COM_SEARCH: // 0x81, smbPacket = new SmbSearchRequestPacket(); break; case SmbCommand.SMB_COM_FIND: // 0x82, smbPacket = new SmbFindRequestPacket(); break; case SmbCommand.SMB_COM_FIND_UNIQUE: // 0x83, smbPacket = new SmbFindUniqueRequestPacket(); break; case SmbCommand.SMB_COM_FIND_CLOSE: // 0x84, smbPacket = new SmbFindCloseRequestPacket(); break; case SmbCommand.SMB_COM_NT_CREATE_ANDX: // 0xA2, smbPacket = new SmbNtCreateAndxRequestPacket(); break; case SmbCommand.SMB_COM_NT_RENAME: // 0xA5, smbPacket = new SmbNtRenameRequestPacket(); break; case SmbCommand.SMB_COM_OPEN_PRINT_FILE: // 0xC0, smbPacket = new SmbOpenPrintFileRequestPacket(); break; case SmbCommand.SMB_COM_WRITE_PRINT_FILE: // 0xC1, smbPacket = new SmbWritePrintFileRequestPacket(); break; case SmbCommand.SMB_COM_CLOSE_PRINT_FILE: // 0xC2, smbPacket = new SmbClosePrintFileRequestPacket(); break; case SmbCommand.SMB_COM_GET_PRINT_QUEUE: // 0xC3, smbPacket = new SmbGetPrintQueueRequestPacket(); break; case SmbCommand.SMB_COM_READ_BULK: // 0xD8, smbPacket = new SmbReadBulkRequestPacket(); break; case SmbCommand.SMB_COM_WRITE_BULK: // 0xD9, smbPacket = new SmbWriteBulkRequestPacket(); break; case SmbCommand.SMB_COM_WRITE_BULK_DATA: // 0xDA, smbPacket = new SmbWriteBulkDataRequestPacket(); break; case SmbCommand.SMB_COM_INVALID: // 0xFE, smbPacket = new SmbInvalidRequestPacket(); break; case SmbCommand.SMB_COM_NO_ANDX_COMMAND: // 0xFF, smbPacket = new SmbNoAndxCommandRequestPacket(); break; #endregion #region Trans NtTrans Tran2 case SmbCommand.SMB_COM_TRANSACTION: SMB_COM_TRANSACTION_Request_SMB_Parameters transaction = channel.Peek<SMB_COM_TRANSACTION_Request_SMB_Parameters>(0); if (transaction.SetupCount == 0) { smbPacket = new SmbTransRapRequestPacket(); } else { smbPacket = CreateTransactionPacket( transaction.SetupCount, (TransSubCommand)transaction.Setup[0]); } break; case SmbCommand.SMB_COM_TRANSACTION2: SMB_COM_TRANSACTION2_Request_SMB_Parameters transaction2 = channel.Peek<SMB_COM_TRANSACTION2_Request_SMB_Parameters>(0); smbPacket = CreateTrans2Packet((Trans2SubCommand)transaction2.Setup[0]); break; case SmbCommand.SMB_COM_NT_TRANSACT: SMB_COM_NT_TRANSACT_Request_SMB_Parameters ntTransactoin = channel.Peek<SMB_COM_NT_TRANSACT_Request_SMB_Parameters>(0); smbPacket = CreateNtTransPacket(ntTransactoin.Function); break; #endregion } return smbPacket; } /// <summary> /// create the nt transaction packets /// </summary> /// <param name="command">the command of nt transaction</param> /// <returns>the target nt transaction packet</returns> internal static SmbPacket CreateNtTransPacket(NtTransSubCommand command) { SmbPacket smbPacket = null; switch (command) { case NtTransSubCommand.NT_TRANSACT_CREATE: smbPacket = new SmbNtTransactCreateRequestPacket(); break; case NtTransSubCommand.NT_TRANSACT_RENAME: smbPacket = new SmbNtTransactRenameRequestPacket(); break; case NtTransSubCommand.NT_TRANSACT_IOCTL: smbPacket = new SmbNtTransactIoctlRequestPacket(); break; case NtTransSubCommand.NT_TRANSACT_NOTIFY_CHANGE: smbPacket = new SmbNtTransactNotifyChangeRequestPacket(); break; case NtTransSubCommand.NT_TRANSACT_QUERY_SECURITY_DESC: smbPacket = new SmbNtTransactQuerySecurityDescRequestPacket(); break; case NtTransSubCommand.NT_TRANSACT_SET_SECURITY_DESC: smbPacket = new SmbNtTransactSetSecurityDescRequestPacket(); break; } return smbPacket; } /// <summary> /// create the transaction2 packet. /// </summary> /// <param name="command">the command of transaction2 packet.</param> /// <returns>the target transaction2 packet</returns> internal static SmbPacket CreateTrans2Packet(Trans2SubCommand command) { SmbPacket smbPacket = null; switch ((Trans2SubCommand)command) { case Trans2SubCommand.TRANS2_OPEN2: smbPacket = new SmbTrans2Open2RequestPacket(); break; case Trans2SubCommand.TRANS2_FIND_FIRST2: smbPacket = new SmbTrans2FindFirst2RequestPacket(); break; case Trans2SubCommand.TRANS2_FIND_NEXT2: smbPacket = new SmbTrans2FindNext2RequestPacket(); break; case Trans2SubCommand.TRANS2_QUERY_FS_INFORMATION: smbPacket = new SmbTrans2QueryFsInformationRequestPacket(); break; case Trans2SubCommand.TRANS2_SET_FS_INFORMATION: smbPacket = new SmbTrans2SetFsInformationRequestPacket(); break; case Trans2SubCommand.TRANS2_QUERY_PATH_INFORMATION: smbPacket = new SmbTrans2QueryPathInformationRequestPacket(); break; case Trans2SubCommand.TRANS2_SET_PATH_INFORMATION: smbPacket = new SmbTrans2SetPathInformationRequestPacket(); break; case Trans2SubCommand.TRANS2_QUERY_FILE_INFORMATION: smbPacket = new SmbTrans2QueryFileInformationRequestPacket(); break; case Trans2SubCommand.TRANS2_SET_FILE_INFORMATION: smbPacket = new SmbTrans2SetFileInformationRequestPacket(); break; case Trans2SubCommand.TRANS2_FSCTL: smbPacket = new SmbTrans2FsctlRequestPacket(); break; case Trans2SubCommand.TRANS2_IOCTL2: smbPacket = new SmbTrans2Ioctl2RequestPacket(); break; case Trans2SubCommand.TRANS2_FIND_NOTIFY_FIRST: smbPacket = new SmbTrans2FindNotifyFirstRequestPacket(); break; case Trans2SubCommand.TRANS2_FIND_NOTIFY_NEXT: smbPacket = new SmbTrans2FindNotifyNextRequestPacket(); break; case Trans2SubCommand.TRANS2_CREATE_DIRECTORY: smbPacket = new SmbTrans2CreateDirectoryRequestPacket(); break; case Trans2SubCommand.TRANS2_SESSION_SETUP: smbPacket = new SmbTrans2SessionSetupRequestPacket(); break; case Trans2SubCommand.TRANS2_GET_DFS_REFERRAL: smbPacket = new SmbTrans2GetDfsReferalRequestPacket(); break; case Trans2SubCommand.TRANS2_REPORT_DFS_INCONSISTENCY: smbPacket = new SmbTrans2ReportDfsInconsistencyRequestPacket(); break; } return smbPacket; } /// <summary> /// create the transaction packet. /// </summary> /// <param name="setupCount">the count of setup</param> /// <param name="command">the command of transaction packet</param> /// <returns>the target transaction packet</returns> internal static SmbPacket CreateTransactionPacket(byte setupCount, TransSubCommand command) { if (setupCount == 0) { return new SmbTransRapRequestPacket(); } SmbPacket smbPacket = null; switch ((TransSubCommand)command) { case TransSubCommand.TRANS_SET_NMPIPE_STATE: smbPacket = new SmbTransSetNmpipeStateRequestPacket(); break; case TransSubCommand.TRANS_RAW_READ_NMPIPE: smbPacket = new SmbTransRawReadNmpipeRequestPacket(); break; case TransSubCommand.TRANS_QUERY_NMPIPE_STATE: smbPacket = new SmbTransQueryNmpipeStateRequestPacket(); break; case TransSubCommand.TRANS_QUERY_NMPIPE_INFO: smbPacket = new SmbTransQueryNmpipeInfoRequestPacket(); break; case TransSubCommand.TRANS_PEEK_NMPIPE: smbPacket = new SmbTransPeekNmpipeRequestPacket(); break; case TransSubCommand.TRANS_TRANSACT_NMPIPE: smbPacket = new SmbTransTransactNmpipeRequestPacket(); break; case TransSubCommand.TRANS_RAW_WRITE_NMPIPE: smbPacket = new SmbTransRawWriteNmpipeRequestPacket(); break; case TransSubCommand.TRANS_READ_NMPIPE: smbPacket = new SmbTransReadNmpipeRequestPacket(); break; case TransSubCommand.TRANS_WRITE_NMPIPE: smbPacket = new SmbTransWriteNmpipeRequestPacket(); break; case TransSubCommand.TRANS_WAIT_NMPIPE: smbPacket = new SmbTransWaitNmpipeRequestPacket(); break; case TransSubCommand.TRANS_CALL_NMPIPE: smbPacket = new SmbTransCallNmpipeRequestPacket(); break; } return smbPacket; } /// <summary> /// to new a Smb sub trans response packet in type of the SubCommand in SmbParameters. /// </summary> /// <param name="subCommand">the TransSubCommand of the Trans response packet.</param> /// <returns> /// the new response packet. /// the null means that the utility don't know how to create the response. /// </returns> private static SmbTransactionSuccessResponsePacket CreateSmbTransResponsePacket( TransSubCommand subCommand) { SmbTransactionSuccessResponsePacket response = null; switch (subCommand) { case TransSubCommand.TRANS_SET_NMPIPE_STATE: // 0x0001, response = new SmbTransSetNmpipeStateSuccessResponsePacket(); break; case TransSubCommand.TRANS_RAW_READ_NMPIPE: // 0x0011, response = new SmbTransRawReadNmpipeSuccessResponsePacket(); break; case TransSubCommand.TRANS_QUERY_NMPIPE_STATE: // 0x0021, response = new SmbTransQueryNmpipeStateSuccessResponsePacket(); break; case TransSubCommand.TRANS_QUERY_NMPIPE_INFO: // 0x0022, response = new SmbTransQueryNmpipeInfoSuccessResponsePacket(); break; case TransSubCommand.TRANS_PEEK_NMPIPE: // 0x0023, response = new SmbTransPeekNmpipeSuccessResponsePacket(); break; case TransSubCommand.TRANS_TRANSACT_NMPIPE: // 0x0026, response = new SmbTransTransactNmpipeSuccessResponsePacket(); break; case TransSubCommand.TRANS_RAW_WRITE_NMPIPE: // 0x0031, response = new SmbTransRawWriteNmpipeSuccessResponsePacket(); break; case TransSubCommand.TRANS_READ_NMPIPE: // 0x0036, response = new SmbTransReadNmpipeSuccessResponsePacket(); break; case TransSubCommand.TRANS_WRITE_NMPIPE: // 0x0037, response = new SmbTransWriteNmpipeSuccessResponsePacket(); break; case TransSubCommand.TRANS_WAIT_NMPIPE: // 0x0053, response = new SmbTransWaitNmpipeSuccessResponsePacket(); break; case TransSubCommand.TRANS_CALL_NMPIPE: // 0x0054, response = new SmbTransCallNmpipeSuccessResponsePacket(); break; default: break; } return response; } /// <summary> /// to new a Smb sub transs response packet in type of the SubCommand in SmbParameters. /// </summary> /// <param name="smbTransaction2Request">the request of the Trans2 response packet.</param> /// <returns> /// the new response packet. /// the null means that the utility don't know how to create the response. /// </returns> [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] [SuppressMessage("Microsoft.Maintainability", "CA1505:AvoidUnmantainableCode")] [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] private static SmbTransaction2FinalResponsePacket CreateSmbTrans2ResponsePacket( SmbTransaction2RequestPacket smbTransaction2Request) { SmbTransaction2FinalResponsePacket response = null; switch ((Trans2SubCommand)smbTransaction2Request.SmbParameters.Setup[0]) { case Trans2SubCommand.TRANS2_OPEN2: // 0x00, response = new SmbTrans2Open2FinalResponsePacket(); break; case Trans2SubCommand.TRANS2_FIND_FIRST2: // 0x0001, SmbTrans2FindFirst2RequestPacket first2Request = smbTransaction2Request as SmbTrans2FindFirst2RequestPacket; if (first2Request != null) { response = new SmbTrans2FindFirst2FinalResponsePacket(first2Request.Trans2Parameters.InformationLevel, (first2Request.Trans2Parameters.Flags & Trans2FindFlags.SMB_FIND_RETURN_RESUME_KEYS) == Trans2FindFlags.SMB_FIND_RETURN_RESUME_KEYS); } break; case Trans2SubCommand.TRANS2_FIND_NEXT2: // 0x0002, SmbTrans2FindNext2RequestPacket next2Request = smbTransaction2Request as SmbTrans2FindNext2RequestPacket; if (next2Request != null) { response = new SmbTrans2FindNext2FinalResponsePacket(next2Request.Trans2Parameters.InformationLevel, (next2Request.Trans2Parameters.Flags & Trans2FindFlags.SMB_FIND_RETURN_RESUME_KEYS) == Trans2FindFlags.SMB_FIND_RETURN_RESUME_KEYS); } break; case Trans2SubCommand.TRANS2_QUERY_FS_INFORMATION: // 0x0003, SmbTrans2QueryFsInformationRequestPacket queryFsRequest = smbTransaction2Request as SmbTrans2QueryFsInformationRequestPacket; if (queryFsRequest != null) { response = new SmbTrans2QueryFsInformationFinalResponsePacket( queryFsRequest.Trans2Parameters.InformationLevel); } break; case Trans2SubCommand.TRANS2_SET_FS_INFORMATION: // 0x0004, response = new SmbTrans2SetFsInformationFinalResponsePacket(); break; case Trans2SubCommand.TRANS2_QUERY_PATH_INFORMATION: // 0x0005, SmbTrans2QueryPathInformationRequestPacket queryPathRequest = smbTransaction2Request as SmbTrans2QueryPathInformationRequestPacket; if (queryPathRequest != null) { response = new SmbTrans2QueryPathInformationFinalResponsePacket( queryPathRequest.Trans2Parameters.InformationLevel); } break; case Trans2SubCommand.TRANS2_SET_PATH_INFORMATION: // 0x0006, response = new SmbTrans2SetPathInformationFinalResponsePacket(); break; case Trans2SubCommand.TRANS2_QUERY_FILE_INFORMATION: // 0x0007, SmbTrans2QueryFileInformationRequestPacket queryFileRequest = smbTransaction2Request as SmbTrans2QueryFileInformationRequestPacket; if (queryFileRequest != null) { response = new SmbTrans2QueryFileInformationFinalResponsePacket( queryFileRequest.Trans2Parameters.InformationLevel); } break; case Trans2SubCommand.TRANS2_SET_FILE_INFORMATION: // 0x0008, response = new SmbTrans2SetFileInformationFinalResponsePacket(); break; case Trans2SubCommand.TRANS2_FSCTL: // 0x0009, response = new SmbTrans2FsctlFinalResponsePacket(); break; case Trans2SubCommand.TRANS2_IOCTL2: // 0x000a, response = new SmbTrans2Ioctl2FinalResponsePacket(); break; case Trans2SubCommand.TRANS2_FIND_NOTIFY_FIRST: // 0x000b, response = new SmbTrans2FindNotifyFirstFinalResponsePacket(); break; case Trans2SubCommand.TRANS2_FIND_NOTIFY_NEXT: // 0x000c, response = new SmbTrans2FindNotifyNextFinalResponsePacket(); break; case Trans2SubCommand.TRANS2_CREATE_DIRECTORY: // 0x000d, response = new SmbTrans2CreateDirectoryFinalResponsePacket(); break; case Trans2SubCommand.TRANS2_SESSION_SETUP: // 0x000e, response = new SmbTrans2SessionSetupFinalResponsePacket(); break; case Trans2SubCommand.TRANS2_GET_DFS_REFERRAL: // 0x0010, response = new SmbTrans2GetDfsReferalFinalResponsePacket(); break; case Trans2SubCommand.TRANS2_REPORT_DFS_INCONSISTENCY: // 0x0011, response = new SmbTrans2ReportDfsInconsistencyFinalResponsePacket(); break; default: break; } return response; } /// <summary> /// to new a Smb sub transs response packet in type of the SubCommand in SmbParameters. /// </summary> /// <param name="subCommand">the NtTransSubCommand of the NtTrans response packet.</param> /// <returns> /// the new response packet. /// the null means that the utility don't know how to create the response. /// </returns> private static SmbNtTransactSuccessResponsePacket CreateSmbNtTransResponsePacket( NtTransSubCommand subCommand) { SmbNtTransactSuccessResponsePacket response = null; switch (subCommand) { case NtTransSubCommand.NT_TRANSACT_CREATE: // 0x0001, response = new SmbNtTransactCreateResponsePacket(); break; case NtTransSubCommand.NT_TRANSACT_IOCTL: // 0x0002, response = new SmbNtTransactIoctlResponsePacket(); break; case NtTransSubCommand.NT_TRANSACT_SET_SECURITY_DESC: // 0x0003, response = new SmbNtTransactSetSecurityDescResponsePacket(); break; case NtTransSubCommand.NT_TRANSACT_NOTIFY_CHANGE: // 0x0004, response = new SmbNtTransactNotifyChangeResponsePacket(); break; case NtTransSubCommand.NT_TRANSACT_RENAME: // 0x0005, response = new SmbNtTransactRenameResponsePacket(); break; case NtTransSubCommand.NT_TRANSACT_QUERY_SECURITY_DESC: // 0x0006, response = new SmbNtTransactQuerySecurityDescResponsePacket(); break; default: break; } return response; } #endregion #region utilities /// <summary> /// it is used to compute a signature for a message block against a key. /// </summary> /// <param name="message">the raw packet bytes.</param> /// <param name="sessionKey">the session key.</param> /// <returns>the signature.</returns> /// <exception cref="System.ArgumentNullException">the message or sessionKey is null.</exception> public static byte[] CreateSignature(byte[] message, byte[] sessionKey) { return CreateSignature(message, sessionKey, new byte[0]); } /// <summary> /// it is used to compute a signature for a message block against a key. /// </summary> /// <param name="message">the raw packet bytes.</param> /// <param name="sessionKey">the session key.</param> /// <param name="challengeResponse">the challenge response.</param> /// <returns>the signature.</returns> /// <exception cref="System.ArgumentNullException">the message or sessionKey or challengeResponse is null. /// </exception> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security.Cryptography", "CA5350:MD5CannotBeUsed")] public static byte[] CreateSignature(byte[] message, byte[] sessionKey, byte[] challengeResponse) { if (message == null) { throw new ArgumentNullException("message"); } if (sessionKey == null) { throw new ArgumentNullException("sessionKey"); } if (challengeResponse == null) { throw new ArgumentNullException("sessionKey"); } byte[] data = new byte[message.Length + sessionKey.Length + challengeResponse.Length]; Array.Copy(sessionKey, data, sessionKey.Length); Array.Copy(challengeResponse, 0, data, sessionKey.Length, challengeResponse.Length); Array.Copy(message, 0, data, sessionKey.Length + challengeResponse.Length, message.Length); MD5 md5 = MD5.Create(); byte[] result = md5.ComputeHash(data); return result; } /// <summary> /// PlainTextAuthenticate Method /// </summary> /// <param name="request">the SessionSetup request.</param> /// <param name="accountCredentials">All the available users</param> /// <returns>the account name</returns> public static string PlainTextAuthenticate( SmbSessionSetupAndxRequestPacket request, Collection<AccountCredential> accountCredentials) { string account = string.Empty; if (request != null && accountCredentials != null) { foreach (AccountCredential accountCredential in accountCredentials) { string actualAccount = ToString(request.SmbData.AccountName, request.SmbHeader.Flags2); if (actualAccount != accountCredential.AccountName) { continue; } string actualPassword = string.Empty; if (request.SmbParameters.UnicodePasswordLen != 0) { actualPassword = Encoding.Unicode.GetString(request.SmbData.UnicodePassword); } if (request.SmbParameters.OEMPasswordLen != 0) { actualPassword = Encoding.ASCII.GetString(request.SmbData.UnicodePassword); } if (actualPassword == accountCredential.Password) { account = accountCredential.AccountName; break; } } } return account; } /// <summary> /// NTLMAuthenticate Method /// </summary> /// <param name="request">the SessionSetup request.</param> /// <param name="nlmpServerSecurityContexts">all the users' security contexts.</param> /// <param name="systemTime">The server system time.</param> /// <returns>return the user's security context if passed, return null if failed.</returns> public static NlmpServerSecurityContext NTLMAuthenticate( SmbSessionSetupAndxRequestPacket request, Collection<NlmpServerSecurityContext> nlmpServerSecurityContexts, ulong systemTime) { NlmpServerSecurityContext nlmpServerSecurityContext = null; if (request != null && request.SmbParameters.OEMPasswordLen != 0 && request.SmbParameters.UnicodePasswordLen != 0) { foreach (NlmpServerSecurityContext securityContext in nlmpServerSecurityContexts) { string accountOfRequest = CifsMessageUtils.ToString(request.SmbData.AccountName, request.SmbHeader.Flags2); string domainOfRequest = CifsMessageUtils.ToString(request.SmbData.PrimaryDomain, request.SmbHeader.Flags2); if (securityContext.VerifySecurityToken( accountOfRequest, domainOfRequest, systemTime, request.SmbData.OEMPassword, request.SmbData.UnicodePassword)) { nlmpServerSecurityContext = securityContext; break; } } } return nlmpServerSecurityContext; } /// <summary> /// Verify the receiving request/response if message sign is active. /// </summary> /// <param name="packet">the request or response received.</param> /// <param name="sessionKey">the session key</param> /// <param name="sequenceNumber">the sequence number</param> /// <returns>return true if passed, return false if failed.</returns> public static bool VerifySignature(SmbPacket packet, byte[] sessionKey, uint sequenceNumber) { return VerifySignature(packet, sessionKey, sequenceNumber, new byte[0]); } /// <summary> /// Verify the receiving request/response if message sign is active. /// </summary> /// <param name="packet">the request or response received.</param> /// <param name="sessionKey">the session key</param> /// <param name="sequenceNumber">the sequence number</param> /// <param name="challengeResponse">the challenge response.</param> /// <returns>return true if passed, return false if failed.</returns> public static bool VerifySignature(SmbPacket packet, byte[] sessionKey, uint sequenceNumber, byte[] challengeResponse) { SmbPacket clonePacket = packet.Clone() as SmbPacket; clonePacket.Sign(sequenceNumber, sessionKey, challengeResponse); return packet.SmbHeader.SecurityFeatures == clonePacket.SmbHeader.SecurityFeatures; } /// <summary> /// get the pad length. /// </summary> /// <param name="packetLength">the length to calculate pad for</param> /// <param name="lengthPadingTo">the length to padding, e.g. 4 bytes align, 8 bytes align.</param> /// <returns>the pad length</returns> public static int CalculatePadLength(int packetLength, int lengthPadingTo) { if(packetLength < 0) { throw new InvalidOperationException("the packet length mustnot be negative."); } if (packetLength == 0) { return 0; } int len = lengthPadingTo - packetLength % lengthPadingTo; return len; } #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. /* * Ordered String/String[] collection of name/value pairs with support for null key * Wraps NameObject collection * */ using System.Text; namespace System.Collections.Specialized { /// <devdoc> /// <para>Represents a sorted collection of associated <see cref='System.String' qualify='true'/> keys and <see cref='System.String' qualify='true'/> values that /// can be accessed either with the hash code of the key or with the index.</para> /// </devdoc> public class NameValueCollection : NameObjectCollectionBase { private String[] _all; private String[] _allKeys; // // Constructors // /// <devdoc> /// <para>Creates an empty <see cref='System.Collections.Specialized.NameValueCollection'/> with the default initial capacity /// and using the default case-insensitive hash code provider and the default /// case-insensitive comparer.</para> /// </devdoc> public NameValueCollection() : base() { } /// <devdoc> /// <para>Copies the entries from the specified <see cref='System.Collections.Specialized.NameValueCollection'/> to a new <see cref='System.Collections.Specialized.NameValueCollection'/> with the same initial capacity as /// the number of entries copied and using the default case-insensitive hash code /// provider and the default case-insensitive comparer.</para> /// </devdoc> public NameValueCollection(NameValueCollection col) : base(col != null ? col.Comparer : null) { Add(col); } /// <devdoc> /// <para>Creates an empty <see cref='System.Collections.Specialized.NameValueCollection'/> with /// the specified initial capacity and using the default case-insensitive hash code /// provider and the default case-insensitive comparer.</para> /// </devdoc> public NameValueCollection(int capacity) : base(capacity) { } public NameValueCollection(IEqualityComparer equalityComparer) : base(equalityComparer) { } public NameValueCollection(Int32 capacity, IEqualityComparer equalityComparer) : base(capacity, equalityComparer) { } /// <devdoc> /// <para>Copies the entries from the specified <see cref='System.Collections.Specialized.NameValueCollection'/> to a new <see cref='System.Collections.Specialized.NameValueCollection'/> with the specified initial capacity or the /// same initial capacity as the number of entries copied, whichever is greater, and /// using the default case-insensitive hash code provider and the default /// case-insensitive comparer.</para> /// </devdoc> public NameValueCollection(int capacity, NameValueCollection col) : base(capacity, (col != null ? col.Comparer : null)) { if (col == null) { throw new ArgumentNullException("col"); } this.Comparer = col.Comparer; Add(col); } // // Helper methods // /// <devdoc> /// <para> Resets the cached arrays of the collection to <see langword='null'/>.</para> /// </devdoc> protected void InvalidateCachedArrays() { _all = null; _allKeys = null; } private static String GetAsOneString(ArrayList list) { int n = (list != null) ? list.Count : 0; if (n == 1) { return (String)list[0]; } else if (n > 1) { StringBuilder s = new StringBuilder((String)list[0]); for (int i = 1; i < n; i++) { s.Append(','); s.Append((String)list[i]); } return s.ToString(); } else { return null; } } private static String[] GetAsStringArray(ArrayList list) { int n = (list != null) ? list.Count : 0; if (n == 0) return null; String[] array = new String[n]; list.CopyTo(0, array, 0, n); return array; } // // Misc public APIs // /// <devdoc> /// <para>Copies the entries in the specified <see cref='System.Collections.Specialized.NameValueCollection'/> to the current <see cref='System.Collections.Specialized.NameValueCollection'/>.</para> /// </devdoc> public void Add(NameValueCollection c) { if (c == null) { throw new ArgumentNullException("c"); } InvalidateCachedArrays(); int n = c.Count; for (int i = 0; i < n; i++) { String key = c.GetKey(i); String[] values = c.GetValues(i); if (values != null) { for (int j = 0; j < values.Length; j++) Add(key, values[j]); } else { Add(key, null); } } } /// <devdoc> /// <para>Invalidates the cached arrays and removes all entries /// from the <see cref='System.Collections.Specialized.NameValueCollection'/>.</para> /// </devdoc> public virtual void Clear() { if (IsReadOnly) throw new NotSupportedException(SR.CollectionReadOnly); InvalidateCachedArrays(); BaseClear(); } public void CopyTo(Array dest, int index) { if (dest == null) { throw new ArgumentNullException("dest"); } if (dest.Rank != 1) { throw new ArgumentException(SR.Arg_MultiRank, "dest"); } if (index < 0) { throw new ArgumentOutOfRangeException("index", index, SR.ArgumentOutOfRange_NeedNonNegNum); } if (dest.Length - index < Count) { throw new ArgumentException(SR.Arg_InsufficientSpace); } int n = Count; if (_all == null) { String[] all = new String[n]; for (int i = 0; i < n; i++) { all[i] = Get(i); dest.SetValue(all[i], i + index); } _all = all; // wait until end of loop to set _all reference in case Get throws } else { for (int i = 0; i < n; i++) { dest.SetValue(_all[i], i + index); } } } /// <devdoc> /// <para>Gets a value indicating whether the <see cref='System.Collections.Specialized.NameValueCollection'/> contains entries whose keys are not <see langword='null'/>.</para> /// </devdoc> public bool HasKeys() { return InternalHasKeys(); } /// <devdoc> /// <para>Allows derived classes to alter HasKeys().</para> /// </devdoc> internal virtual bool InternalHasKeys() { return BaseHasKeys(); } // // Access by name // /// <devdoc> /// <para>Adds an entry with the specified name and value into the /// <see cref='System.Collections.Specialized.NameValueCollection'/>.</para> /// </devdoc> public virtual void Add(String name, String value) { if (IsReadOnly) throw new NotSupportedException(SR.CollectionReadOnly); InvalidateCachedArrays(); ArrayList values = (ArrayList)BaseGet(name); if (values == null) { // new key - add new key with single value values = new ArrayList(1); if (value != null) values.Add(value); BaseAdd(name, values); } else { // old key -- append value to the list of values if (value != null) values.Add(value); } } /// <devdoc> /// <para> Gets the values associated with the specified key from the <see cref='System.Collections.Specialized.NameValueCollection'/> combined into one comma-separated list.</para> /// </devdoc> public virtual String Get(String name) { ArrayList values = (ArrayList)BaseGet(name); return GetAsOneString(values); } /// <devdoc> /// <para>Gets the values associated with the specified key from the <see cref='System.Collections.Specialized.NameValueCollection'/>.</para> /// </devdoc> public virtual String[] GetValues(String name) { ArrayList values = (ArrayList)BaseGet(name); return GetAsStringArray(values); } /// <devdoc> /// <para>Adds a value to an entry in the <see cref='System.Collections.Specialized.NameValueCollection'/>.</para> /// </devdoc> public virtual void Set(String name, String value) { if (IsReadOnly) throw new NotSupportedException(SR.CollectionReadOnly); InvalidateCachedArrays(); ArrayList values = new ArrayList(1); values.Add(value); BaseSet(name, values); } /// <devdoc> /// <para>Removes the entries with the specified key from the <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance.</para> /// </devdoc> public virtual void Remove(String name) { InvalidateCachedArrays(); BaseRemove(name); } /// <devdoc> /// <para> Represents the entry with the specified key in the /// <see cref='System.Collections.Specialized.NameValueCollection'/>.</para> /// </devdoc> public String this[String name] { get { return Get(name); } set { Set(name, value); } } // // Indexed access // /// <devdoc> /// <para> /// Gets the values at the specified index of the <see cref='System.Collections.Specialized.NameValueCollection'/> combined into one /// comma-separated list.</para> /// </devdoc> public virtual String Get(int index) { ArrayList values = (ArrayList)BaseGet(index); return GetAsOneString(values); } /// <devdoc> /// <para> Gets the values at the specified index of the <see cref='System.Collections.Specialized.NameValueCollection'/>.</para> /// </devdoc> public virtual String[] GetValues(int index) { ArrayList values = (ArrayList)BaseGet(index); return GetAsStringArray(values); } /// <devdoc> /// <para>Gets the key at the specified index of the <see cref='System.Collections.Specialized.NameValueCollection'/>.</para> /// </devdoc> public virtual String GetKey(int index) { return BaseGetKey(index); } /// <devdoc> /// <para>Represents the entry at the specified index of the <see cref='System.Collections.Specialized.NameValueCollection'/>.</para> /// </devdoc> public String this[int index] { get { return Get(index); } } // // Access to keys and values as arrays // /// <devdoc> /// <para>Gets all the keys in the <see cref='System.Collections.Specialized.NameValueCollection'/>. </para> /// </devdoc> public virtual String[] AllKeys { get { if (_allKeys == null) _allKeys = BaseGetAllKeys(); return _allKeys; } } } }
using CodeForDevices.WindowsUniversal.Hardware.Buses; using CodeForDotNet; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading.Tasks; using Windows.Devices.I2c; namespace Emlid.WindowsIot.Hardware.Components.Pca9685 { /// <summary> /// PCA9685 PWM LED driver (hardware device), connected via I2C. /// </summary> /// <remarks> /// The PCA9685 is a 16 channel, 12-bit PWM LED controller with I2C bus connection. /// <para> /// This class enables direct control of the device intended for internal use. /// If exposed to other users, it should wrapped by a thread safe class which /// coordinates access and deals with object lifetime (dispose). /// See http://www.nxp.com/documents/data_sheet/PCA9685.pdf for more information. /// </para> /// </remarks> public sealed class Pca9685Device : DisposableObject { #region Constants /// <summary> /// 7-bit I2C address of the first PCA9685 on the bus. /// </summary> public const byte I2cAddress = 0x80 >> 1; /// <summary> /// 7-bit I2C address of the PCA9685 "all call" address. /// </summary> public const byte I2cAllCallAddress = 0x70 >> 1; /// <summary> /// Maximum number of devices (chip number) for this model. /// </summary> public const int MaximumDevices = 62; /// <summary> /// Offset of the first channel register, <see cref="Pca9685Register.Channel0OnLow"/>. /// </summary> public const byte ChannelStartAddress = 0x06; /// <summary> /// Size of the channel register groups, added to <see cref="ChannelStartAddress"/> to calculate the address of specific channels. /// </summary> public const byte ChannelSize = sizeof(ushort) * 2; /// <summary> /// Total number of channels. /// </summary> public const int ChannelCount = 16; /// <summary> /// Internal clock speed in Hz. /// </summary> public const int InternalClockSpeed = 25000000; /// <summary> /// Maximum clock speed in Hz. /// </summary> public const int ClockSpeedMaximum = 50000000; /// <summary> /// Minimum value of the <see cref="Pca9685Register.Prescale"/> register. /// </summary> public const byte PrescaleMinimum = 0x03; /// <summary> /// Maximum value of the <see cref="Pca9685Register.Prescale"/> register. /// </summary> public const byte PrescaleMaximum = 0xff; /// <summary> /// Default value of the <see cref="Pca9685Register.Prescale"/> register. /// </summary> public const byte PrescaleDefault = 0x30; /// <summary> /// Time to wait in milliseconds after switching modes, stopping or starting the oscillator. /// </summary> public const int ModeSwitchDelay = 1; #endregion Constants #region Lifetime /// <summary> /// Creates an instance using the specified I2C device. /// </summary> /// <param name="busNumber">I2C bus controller number (zero based).</param> /// <param name="chipNumber">Chip number.</param> /// <param name="clockSpeed"> /// Optional external clock speed in Hz. Otherwise the <see cref="InternalClockSpeed"/> is used. /// This is a physical property, not a software option. /// </param> /// <param name="speed">Bus speed.</param> /// <param name="sharingMode">Sharing mode.</param> [CLSCompliant(false)] public Pca9685Device(uint busNumber, byte chipNumber, int? clockSpeed, I2cBusSpeed speed = I2cBusSpeed.FastMode, I2cSharingMode sharingMode = I2cSharingMode.Exclusive) { // Validate if (clockSpeed.HasValue && (clockSpeed == 0 || clockSpeed.Value > ClockSpeedMaximum)) throw new ArgumentOutOfRangeException(nameof(clockSpeed)); // Get address var address = GetI2cAddress(chipNumber); // Connect to hardware _hardware = I2cExtensions.Connect(busNumber, address, speed, sharingMode); // Initialize configuration ClockIsExternal = clockSpeed.HasValue; ClockSpeed = clockSpeed ?? InternalClockSpeed; FrequencyDefault = CalculateFrequency(PrescaleDefault, ClockSpeed); FrequencyMinimum = CalculateFrequency(PrescaleMaximum, ClockSpeed); // Inverse relationship (max = min) FrequencyMaximum = CalculateFrequency(PrescaleMinimum, ClockSpeed); // Inverse relationship (min = max) // Build channels _channels = new Collection<Pca9685ChannelValue>(); Channels = new ReadOnlyCollection<Pca9685ChannelValue>(_channels); for (var index = 0; index < ChannelCount; index++) _channels.Add(new Pca9685ChannelValue(index)); // Set "all call" address I2cExtensions.WriteJoinByte(_hardware, (byte)Pca9685Register.AllCall, I2cAllCallAddress); // Enable auto-increment and "all call" I2cExtensions.WriteReadWriteBit(_hardware, (byte)Pca9685Register.Mode1, (byte)(Pca9685Mode1Bits.AutoIncrement | Pca9685Mode1Bits.AllCall), true); // Read current values and update properties ReadAll(); } #region IDisposable /// <summary> /// Frees resources owned by this instance. /// </summary> /// <param name="disposing"> /// True when called via <see cref="IDisposable.Dispose"/>, false when called via finalizer. /// </param> protected override void Dispose(bool disposing) { // Only managed resources to dispose if (!disposing) return; // Close device _hardware?.Dispose(); } #endregion IDisposable #endregion Lifetime #region Private Fields /// <summary> /// I2C device. /// </summary> private I2cDevice _hardware; #endregion Private Fields #region Public Properties /// <summary> /// Channels and their values (also settable). /// </summary> public ReadOnlyCollection<Pca9685ChannelValue> Channels { get; private set; } private readonly Collection<Pca9685ChannelValue> _channels; /// <summary> /// Indicates the PWM clock is controlled externally. /// </summary> public bool ClockIsExternal { get; private set; } /// <summary> /// PWM clock speed in Hz, either internal or external. /// </summary> public int ClockSpeed { get; private set; } /// <summary> /// Frequency in Hz. /// </summary> public int Frequency { get; private set; } /// <summary> /// Frequency when the hardware <see cref="PrescaleDefault"/> is set. /// </summary> public int FrequencyDefault { get; private set; } /// <summary> /// Minimum frequency based on <see cref="ClockSpeed"/> and <see cref="PrescaleMaximum"/> (inverse relation). /// </summary> public int FrequencyMinimum { get; private set; } /// <summary> /// Maximum frequency based on <see cref="ClockSpeed"/> and <see cref="PrescaleMinimum"/> (inverse relation). /// </summary> public int FrequencyMaximum { get; private set; } /// <summary> /// Last known mode 1 register bits. /// </summary> public Pca9685Mode1Bits Mode1Register { get; private set; } /// <summary> /// Last known mode 2 register bits. /// </summary> public Pca9685Mode2Bits Mode2Register { get; private set; } /// <summary> /// Minimum PWM length in milliseconds, based on the current frequency. /// </summary> public decimal PwmMsMinimum { get; private set; } /// <summary> /// Maximum PWM length in milliseconds, based on the current frequency. /// </summary> public decimal PwmMsMaximum { get; private set; } #endregion Public Properties #region Public Methods #region General /// <summary> /// Gets the I2C address for communication with the specified chip number. /// </summary> /// <param name="chipNumber"> /// Device (chip) number, from zero to the <see cref="MaximumDevices"/> supported. /// </param> /// <returns>7-bit I2C address.</returns> public static byte GetI2cAddress(byte chipNumber) { // Validate if (chipNumber < 0 || chipNumber > MaximumDevices) throw new ArgumentOutOfRangeException(nameof(chipNumber)); // Calculate and return address return (byte)(I2cAddress + chipNumber); } /// <summary> /// Reads all values from the device and updates properties. /// </summary> public void ReadAll() { ReadMode1(); ReadMode2(); ReadFrequency(); ReadAllChannels(); } #endregion General #region Mode /// <summary> /// Reads the current value of the <see cref="Pca9685Register.Mode1"/> register. /// </summary> /// <returns>Bit flags corresponding to the actual mode byte.</returns> public Pca9685Mode1Bits ReadMode1() { // Read register var value = (Pca9685Mode1Bits)I2cExtensions.WriteReadByte(_hardware, (byte)Pca9685Register.Mode1); // Update property Mode1Register = value; // Return result return value; } /// <summary> /// Reads the current value of the <see cref="Pca9685Register.Mode2"/> register. /// </summary> /// <returns>Bit flags corresponding to the actual mode byte.</returns> public Pca9685Mode2Bits ReadMode2() { // Read register var value = (Pca9685Mode2Bits)I2cExtensions.WriteReadByte(_hardware, (byte)Pca9685Register.Mode2); // Update property Mode2Register = value; // Return result return value; } #endregion Mode #region Sleep /// <summary> /// Enters sleep mode. /// </summary> /// <remarks> /// Sets the <see cref="Pca9685Register.Mode1"/> register <see cref="Pca9685Mode1Bits.Sleep"/> bit /// then waits for <see cref="ModeSwitchDelay"/> to allow the oscillator to stop. /// </remarks> /// <returns> /// True when mode was changed, false when already set. /// </returns> public bool Sleep() { // Read sleep bit (do nothing when already sleeping) var sleeping = I2cExtensions.WriteReadBit(_hardware, (byte)Pca9685Register.Mode1, (byte)Pca9685Mode1Bits.Sleep); if (sleeping) return false; // Set sleep bit I2cExtensions.WriteReadWriteBit(_hardware, (byte)Pca9685Register.Mode1, (byte)Pca9685Mode1Bits.Sleep, true); // Wait for completion Task.Delay(ModeSwitchDelay).Wait(); // Update related properties ReadMode1(); // Return changed return true; } /// <summary> /// Leaves sleep mode. /// </summary> /// <remarks> /// Clears the <see cref="Pca9685Register.Mode1"/> register <see cref="Pca9685Mode1Bits.Sleep"/> bit /// then waits for <see cref="ModeSwitchDelay"/> to allow the oscillator to start. /// </remarks> /// <returns> /// True when mode was changed, false when not sleeping. /// </returns> public bool Wake() { // Read sleep bit (do nothing when already sleeping) var sleeping = I2cExtensions.WriteReadBit(_hardware, (byte)Pca9685Register.Mode1, (byte)Pca9685Mode1Bits.Sleep); if (!sleeping) return false; // Clear sleep bit I2cExtensions.WriteReadWriteBit(_hardware, (byte)Pca9685Register.Mode1, (byte)Pca9685Mode1Bits.Sleep, false); // Wait for completion Task.Delay(ModeSwitchDelay).Wait(); // Update related properties ReadMode1(); // Return changed return true; } #endregion Sleep #region Restart /// <summary> /// Restarts the device with default options, then updates all properties. /// </summary> public void Restart() { // Call overloaded method Restart(Pca9685Mode1Bits.None); } /// <summary> /// Restarts the device with additional options specified, then updates all properties. /// </summary> /// <param name="options"> /// Optional mode 1 parameters to add to the final restart sequence. A logical OR is applied to this value and /// the standard <see cref="Pca9685Mode1Bits.Restart"/>, <see cref="Pca9685Mode1Bits.ExternalClock"/> and /// <see cref="Pca9685Mode1Bits.AutoIncrement"/> bits. /// </param> public void Restart(Pca9685Mode1Bits options) { // Configure according to external clock presence var externalClock = ClockIsExternal; var delay = TimeSpan.FromTicks(Convert.ToInt64(Math.Round(TimeSpan.TicksPerMillisecond * 0.5))); // Send I2C restart sequence... // Write first sleep var sleep = (byte)Pca9685Mode1Bits.Sleep; I2cExtensions.WriteJoinByte(_hardware, (byte)Pca9685Register.Mode1, sleep); // Write sleep again with external clock option (when present) if (externalClock) { sleep |= (byte)(Pca9685Mode1Bits.ExternalClock); I2cExtensions.WriteJoinByte(_hardware, (byte)Pca9685Register.Mode1, sleep); } else { // At least 500 nanoseconds sleep required using internal clock Task.Delay(delay).Wait(); } // Write reset with external clock option and any additional options var restart = (byte)(Pca9685Mode1Bits.Restart | Pca9685Mode1Bits.AutoIncrement); if (externalClock) restart |= (byte)Pca9685Mode1Bits.ExternalClock; restart |= (byte)options; I2cExtensions.WriteJoinByte(_hardware, (byte)Pca9685Register.Mode1, restart); // At least 500 nanoseconds delay to allow oscillator to start Task.Delay(delay).Wait(); // Update all properties ReadAll(); } #endregion Restart #region Frequency /// <summary> /// Calculates the effective frequency from a <see cref="Pca9685Register.Prescale"/> value and clock speed. /// </summary> /// <param name="prescale">Prescale value from which to calculate frequency.</param> /// <param name="clockSpeed">Clock speed with which to calculate the frequency.</param> /// <returns>Calculated frequency in Hz.</returns> public static int CalculateFrequency(byte prescale, int clockSpeed) { // Validate if (prescale < PrescaleMinimum || prescale > PrescaleMaximum) throw new ArgumentOutOfRangeException(nameof(prescale)); if (clockSpeed <= 0 || clockSpeed > ClockSpeedMaximum) throw new ArgumentOutOfRangeException(nameof(clockSpeed)); // Calculate and return result return Convert.ToInt32(Math.Round(clockSpeed / 4096f / (prescale + 1f))); } /// <summary> /// Calculates the <see cref="Pca9685Register.Prescale"/> value from a desired frequency and clock speed. /// </summary> /// <remarks> /// Due to scaling only certain frequencies are possible. To get the resulting frequency from the desired /// frequency it is necessary to re-calculate the effective frequency back from the prescale, /// i.e. call <see cref="CalculateFrequency"/>. /// </remarks> /// <param name="frequency"> /// Desired frequency in Hz. /// Must be between <see cref="FrequencyMinimum"/> and <see cref="FrequencyMaximum"/> to get a valid result. /// </param> /// <param name="clockSpeed"></param> /// <returns>Calculated prescale value.</returns> /// <exception cref="ArgumentOutOfRangeException"> /// Thrown when an invalid parameter is passed. /// </exception> /// <exception cref="OverflowException"> /// Thrown when parameters are passed which causes the resulting prescale to be higher than /// <see cref="PrescaleMaximum"/> or lower than <see cref="PrescaleMinimum"/>. /// </exception> public static byte CalculatePrescale(int frequency, int clockSpeed) { // Validate if (frequency <= 0) throw new ArgumentOutOfRangeException(nameof(frequency)); if (clockSpeed <= 0 || clockSpeed > ClockSpeedMaximum) throw new ArgumentOutOfRangeException(nameof(clockSpeed)); // Calculate and prescale return Convert.ToByte(Math.Round(clockSpeed / (4096f * frequency)) - 1); } /// <summary> /// Reads the prescale register and calculates the <see cref="Frequency"/> (and related properties) /// based on <see cref="ClockSpeed"/>. /// </summary> /// <returns> /// Frequency in Hz. Related properties are also updated. /// </returns> public int ReadFrequency() { // Read prescale register var prescale = I2cExtensions.WriteReadByte(_hardware, (byte)Pca9685Register.Prescale); // Calculate frequency var frequency = CalculateFrequency(prescale, ClockSpeed); // Update related properties Frequency = frequency; PwmMsMinimum = Pca9685ChannelValue.CalculateWidthMs(frequency, 0); PwmMsMaximum = Pca9685ChannelValue.CalculateWidthMs(frequency, Pca9685ChannelValue.Maximum); // Return result return frequency; } /// <summary> /// Calculates the prescale value from the frequency (according to <see cref="ClockSpeed"/>) /// then writes that register, then calls <see cref="ReadFrequency"/> to update properties. /// Note the actual frequency may differ to the requested frequency due to clock scale (rounding). /// </summary> /// <remarks> /// The prescale can only be set during sleep mode. This method enters <see cref="Sleep"/> if necessary, /// then only if the device was awake before, calls <see cref="Wake"/> afterwards. It's important not to /// start output unexpectedly to avoid damage, i.e. if the device was sleeping before, the frequency is /// changed without starting the oscillator. /// </remarks> /// <param name="frequency">Desired frequency to set in Hz.</param> /// <returns> /// Effective frequency in Hz, read-back and recalculated after setting the desired frequency. /// Frequency in Hz. Related properties are also updated. /// </returns> /// <exception cref="ArgumentOutOfRangeException"> /// Thrown when <paramref name="frequency"/> is less than <see cref="FrequencyMinimum"/> or greater than /// <see cref="FrequencyMaximum"/>. /// </exception> public int WriteFrequency(int frequency) { // Validate if (frequency < FrequencyMinimum || frequency > FrequencyMaximum) throw new ArgumentOutOfRangeException(nameof(frequency)); // Calculate prescale var prescale = CalculatePrescale(frequency, ClockSpeed); // Enter sleep mode and record wake status var wasAwake = Sleep(); // Write prescale I2cExtensions.WriteJoinByte(_hardware, (byte)Pca9685Register.Prescale, prescale); // Read result var actual = ReadFrequency(); // Wake-up if previously running if (wasAwake) Wake(); // Update related properties PwmMsMinimum = Pca9685ChannelValue.CalculateWidthMs(frequency, 0); PwmMsMaximum = Pca9685ChannelValue.CalculateWidthMs(frequency, Pca9685ChannelValue.Maximum); // Return actual frequency return actual; } #endregion Frequency #region Channels /// <summary> /// Gets the register address of a channel by index. /// </summary> /// <param name="index">Zero based channel number (0-15) or 16 for the "all call" channel.</param> /// <returns>Channel address.</returns> public static byte GetChannelAddress(int index) { // Validate if (index < 0 || index > ChannelCount) throw new ArgumentOutOfRangeException(nameof(index)); // Calculate and return address return (byte)(ChannelStartAddress + (ChannelSize * index)); } /// <summary> /// Clears all channels cleanly, then updates all <see cref="Channels"/>. /// </summary> /// <remarks> /// To "cleanly" clear the channels, it is necessary to first ensure they are not disabled, /// set them to zero, then disable them. Otherwise the ON value and the low OFF value /// remain because writes are ignored when the OFF channel bit 12 is already set. /// </remarks> public void Clear() { // Enable all channels I2cExtensions.WriteJoinByte(_hardware, (byte)Pca9685Register.AllChannelsOffHigh, 0x00); // Zero all channels I2cExtensions.WriteJoinBytes(_hardware, (byte)Pca9685Register.AllChannelsOnLow, new byte[] { 0x00, 0x00, 0x00, 0x00 }); // Disable all channels I2cExtensions.WriteJoinByte(_hardware, (byte)Pca9685Register.AllChannelsOffHigh, 0x10); // Update channels ReadAllChannels(); } /// <summary> /// Reads a whole channel value (on and off), and updates it in <see cref="Channels"/>. /// </summary> /// <param name="index">Zero based channel number (0-15).</param> /// <returns>Channel value</returns> public Pca9685ChannelValue ReadChannel(int index) { // Validate if (index < 0 | index >= ChannelCount) throw new ArgumentOutOfRangeException(nameof(index)); // Calculate register address var register = GetChannelAddress(index); // Read value var bytes = I2cExtensions.WriteReadBytes(_hardware, register, sizeof(ushort) * 2); // Update channel property and return result var value = Pca9685ChannelValue.FromByteArray(bytes); return _channels[index] = value; } /// <summary> /// Reads multiple channel values (both on and off for each), and updates it in <see cref="Channels"/>. /// </summary> /// <param name="index">Zero based channel number (0-15).</param> /// <param name="count">Number of channels to read.</param> /// <returns>Channel values</returns> public Collection<Pca9685ChannelValue> ReadChannels(int index, int count) { // Validate if (index < 0 | index >= ChannelCount) throw new ArgumentOutOfRangeException(nameof(index)); if (count < 1 || index + count > ChannelCount) throw new ArgumentOutOfRangeException(nameof(count)); // Calculate register address var register = GetChannelAddress(index); // Send I2C command to read channels in one operation var data = I2cExtensions.WriteReadBytes(_hardware, register, ChannelSize * count); // Update channel properties and add to results var results = new Collection<Pca9685ChannelValue>(); for (int channelIndex = index, offset = 0; count > 0; count--, channelIndex++, offset += ChannelSize) { // Calculate value var value = Pca9685ChannelValue.FromByteArray(data, offset); // Update property _channels[channelIndex] = value; // Add to results results.Add(value); } // Return results return results; } /// <summary> /// Reads the PWM "on" (rising) value of a channel, and updates it in <see cref="Channels"/>. /// </summary> /// <param name="index">Zero based channel number (0-15).</param> /// <returns>Channel value.</returns> public int ReadChannelOn(int index) { // Validate if (index < 0 | index >= ChannelCount) throw new ArgumentOutOfRangeException(nameof(index)); // Calculate register address var register = GetChannelAddress(index); // Read and convert value var bytes = I2cExtensions.WriteReadBytes(_hardware, register, sizeof(ushort)); var value = BitConverter.ToUInt16(bytes, 0); // Update channel when changed var oldValue = _channels[index]; if (oldValue.On != value) _channels[index] = new Pca9685ChannelValue(value, oldValue.Off); // Return result return value; } /// <summary> /// Reads the PWM "off" (falling) value of a channel, and updates it in <see cref="Channels"/>. /// </summary> /// <param name="index">Zero based channel number (0-15).</param> /// <returns>Channel value.</returns> public int ReadChannelOff(int index) { // Validate if (index < 0 | index >= ChannelCount) throw new ArgumentOutOfRangeException(nameof(index)); // Calculate register address of second word value var register = (byte)(GetChannelAddress(index) + sizeof(ushort)); // Read and convert value var bytes = I2cExtensions.WriteReadBytes(_hardware, register, sizeof(ushort)); var value = BitConverter.ToUInt16(bytes, 0); // Update channel when changed var oldValue = _channels[index]; if (oldValue.Off != value) _channels[index] = new Pca9685ChannelValue(oldValue.On, value); // Return result return value; } /// <summary> /// Calculates the "on" and "off" values of a channel from length (and optional delay), /// then writes them together, and updates it in <see cref="Channels"/>. /// </summary> /// <param name="index">Zero based channel number (0-15) or 16 for the "all call" channel.</param> /// <param name="width">Pulse width in clock ticks.</param> /// <param name="delay">Optional delay in clock ticks.</param> /// <returns> /// Updated channel value or null when all channels were updated. /// </returns> public Pca9685ChannelValue? WriteChannelLength(int index, int width, int delay = 0) { // Call overloaded method return WriteChannel(index, Pca9685ChannelValue.FromWidth(width, delay)); } /// <summary> /// Calculates the "on" and "off" values of a channel from milliseconds (and optional delay), /// then writes them together, and updates it in <see cref="Channels"/>. /// </summary> /// <param name="index">Zero based channel number (0-15) or 16 for the "all call" channel.</param> /// <param name="width"> /// Pulse width in milliseconds. Cannot be greater than one clock interval (1000 / frequency). /// </param> /// <param name="delay">Optional delay in milliseconds. Cannot be greater than one clock interval (1000 / frequency).</param> /// <returns> /// Updated channel value or null when all channels were updated. /// </returns> public Pca9685ChannelValue? WriteChannelMs(int index, decimal width, int delay = 0) { // Call overloaded method return WriteChannel(index, Pca9685ChannelValue.FromWidthMs(width, Frequency, delay)); } /// <summary> /// Writes the "on" and "off" values of a channel together, and updates it in <see cref="Channels"/>. /// </summary> /// <param name="index">Zero based channel number (0-15) or 16 for the "all call" channel.</param> /// <param name="value"><see cref="Pca9685ChannelValue"/> to write.</param> /// <returns> /// Updated channel value or null when all channels were updated. /// </returns> public Pca9685ChannelValue? WriteChannel(int index, Pca9685ChannelValue value) { // Validate if (index < 0 | index > ChannelCount) throw new ArgumentOutOfRangeException(nameof(index)); if (value == null) throw new ArgumentNullException(nameof(value)); // Calculate register address var register = GetChannelAddress(index); // Convert and write value var bytes = value.ToByteArray(); I2cExtensions.WriteJoinBytes(_hardware, register, bytes); // Read and return result when single channel if (index < ChannelCount) return ReadChannel(index); // Read all channels when "all call". ReadAllChannels(); return null; } /// <summary> /// Writes multiple channels together (both "on" and "off" values), and updates it in <see cref="Channels"/>. /// </summary> /// <param name="index">Zero based channel number (0-15) or 16 for the "all call" channel.</param> /// <param name="values">Collection of <see cref="Pca9685ChannelValue"/>s to write.</param> public void WriteChannels(int index, IList<Pca9685ChannelValue> values) { // Validate if (index < 0 | index > ChannelCount) throw new ArgumentOutOfRangeException(nameof(index)); if (values == null || values.Count == 0) throw new ArgumentNullException(nameof(values)); var count = values.Count; if (index + count > ChannelCount) throw new ArgumentOutOfRangeException(nameof(values)); // Build I2C packet var data = new byte[1 + ChannelSize * count]; // Calculate first register address var register = GetChannelAddress(index); data[0] = register; // Write channels and update properties for (int dataIndex = 0, dataOffset = 1; dataIndex < count; dataIndex++, dataOffset += ChannelSize) { // Get channel data var channelData = values[dataIndex].ToByteArray(); // Copy to buffer Array.ConstrainedCopy(channelData, 0, data, dataOffset, ChannelSize); // Update property _channels[index + dataIndex] = Pca9685ChannelValue.FromByteArray(channelData); } // Send packet I2cExtensions.WriteBytes(_hardware, data); } /// <summary> /// Writes the PWM "on" (rising) value of a channel. /// </summary> /// <param name="index">Zero based channel number (0-15) or 16 for the "all call" channel.</param> /// <param name="value">12-bit channel value in the range 0-<see cref="Pca9685ChannelValue.Maximum"/>.</param> /// <exception cref="ArgumentOutOfRangeException">Thrown when the <paramref name="value"/> is greater than <see cref="Pca9685ChannelValue.Maximum"/>.</exception> public void WriteChannelOn(int index, int value) { // Validate if (value > Pca9685ChannelValue.Maximum) throw new ArgumentOutOfRangeException(nameof(value)); // Calculate register address var register = GetChannelAddress(index); // Convert and write value var data = BitConverter.GetBytes(value); I2cExtensions.WriteJoinBytes(_hardware, register, data); } /// <summary> /// Writes the PWM "off" (falling) value of a channel. /// </summary> /// <param name="index">Zero based channel number (0-15) or 16 for the "all call" channel.</param> /// <param name="value">12-bit channel value in the range 0-<see cref="Pca9685ChannelValue.Maximum"/>.</param> /// <exception cref="ArgumentOutOfRangeException">Thrown when the <paramref name="value"/> is greater then <see cref="Pca9685ChannelValue.Maximum"/>.</exception> public void WriteChannelOff(int index, int value) { // Validate if (value > Pca9685ChannelValue.Maximum) throw new ArgumentOutOfRangeException(nameof(value)); // Calculate register address of second word value var register = (byte)(GetChannelAddress(index) + sizeof(ushort)); // Convert and write value var bytes = BitConverter.GetBytes(value); I2cExtensions.WriteJoinBytes(_hardware, register, bytes); } /// <summary> /// Reads all channels and updates <see cref="Channels"/>. /// </summary> public void ReadAllChannels() { // Read all channels as one block of data var data = I2cExtensions.WriteReadBytes(_hardware, ChannelStartAddress, ChannelSize * ChannelCount); // Update properties for (var index = 0; index < ChannelCount; index++) _channels[index] = Pca9685ChannelValue.FromByteArray(data, ChannelSize * index); } #endregion Channels #endregion Public Methods } }
// 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.Globalization; using System.Threading; using Xunit; namespace System.Numerics.Tests { public partial class parseTest : RemoteExecutorTestBase { private readonly static int s_samples = 10; private readonly static Random s_random = new Random(100); // Invariant culture is commonly used for (de-)serialization and similar to en-US // Ukrainian (Ukraine) added to catch regressions (issue #1642) // Current cultue to get additional value out of glob/loc test runs public static IEnumerable<object[]> Cultures { get { yield return new object[] { CultureInfo.InvariantCulture }; yield return new object[] { new CultureInfo("uk-UA") }; if (CultureInfo.CurrentCulture.ToString() != "uk-UA") yield return new object[] { CultureInfo.CurrentCulture }; } } [Theory] [MemberData(nameof(Cultures))] [OuterLoop] public static void RunParseToStringTests(CultureInfo culture) { RemoteInvoke((cultureName) => { byte[] tempByteArray1 = new byte[0]; Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(cultureName); //default style VerifyDefaultParse(s_random); //single NumberStyles VerifyNumberStyles(NumberStyles.None, s_random); VerifyNumberStyles(NumberStyles.AllowLeadingWhite, s_random); VerifyNumberStyles(NumberStyles.AllowTrailingWhite, s_random); VerifyNumberStyles(NumberStyles.AllowLeadingSign, s_random); VerifyNumberStyles(NumberStyles.AllowTrailingSign, s_random); VerifyNumberStyles(NumberStyles.AllowParentheses, s_random); VerifyNumberStyles(NumberStyles.AllowDecimalPoint, s_random); VerifyNumberStyles(NumberStyles.AllowThousands, s_random); VerifyNumberStyles(NumberStyles.AllowExponent, s_random); VerifyNumberStyles(NumberStyles.AllowCurrencySymbol, s_random); VerifyNumberStyles(NumberStyles.AllowHexSpecifier, s_random); //composite NumberStyles VerifyNumberStyles(NumberStyles.Integer, s_random); VerifyNumberStyles(NumberStyles.HexNumber, s_random); VerifyNumberStyles(NumberStyles.Number, s_random); VerifyNumberStyles(NumberStyles.Float, s_random); VerifyNumberStyles(NumberStyles.Currency, s_random); VerifyNumberStyles(NumberStyles.Any, s_random); //invalid number style // ******InvalidNumberStyles NumberStyles invalid = (NumberStyles)0x7c00; AssertExtensions.Throws<ArgumentException>(null, () => { BigInteger.Parse("1", invalid).ToString("d"); }); AssertExtensions.Throws<ArgumentException>(null, () => { BigInteger junk; BigInteger.TryParse("1", invalid, null, out junk); Assert.Equal(junk.ToString("d"), "1"); }); //FormatProvider tests RunFormatProviderParseStrings(); }, culture.ToString()).Dispose(); } private static void RunFormatProviderParseStrings() { NumberFormatInfo nfi = new NumberFormatInfo(); nfi = MarkUp(nfi); //Currencies // *************************** // *** FormatProvider - Currencies // *************************** VerifyFormatParse("@ 12#34#56!", NumberStyles.Any, nfi, new BigInteger(123456)); VerifyFormatParse("(12#34#56!@)", NumberStyles.Any, nfi, new BigInteger(-123456)); //Numbers // *************************** // *** FormatProvider - Numbers // *************************** VerifySimpleFormatParse(">1234567", nfi, new BigInteger(1234567)); VerifySimpleFormatParse("<1234567", nfi, new BigInteger(-1234567)); VerifyFormatParse("123&4567^", NumberStyles.Any, nfi, new BigInteger(1234567)); VerifyFormatParse("123&4567^ <", NumberStyles.Any, nfi, new BigInteger(-1234567)); } public static void VerifyDefaultParse(Random random) { // BasicTests VerifyFailParseToString(null, typeof(ArgumentNullException)); VerifyFailParseToString(string.Empty, typeof(FormatException)); VerifyParseToString("0"); VerifyParseToString("000"); VerifyParseToString("1"); VerifyParseToString("001"); // SimpleNumbers - Small for (int i = 0; i < s_samples; i++) { VerifyParseToString(GetDigitSequence(1, 10, random)); } // SimpleNumbers - Large for (int i = 0; i < s_samples; i++) { VerifyParseToString(GetDigitSequence(100, 1000, random)); } // Leading White for (int i = 0; i < s_samples; i++) { VerifyParseToString("\u0009\u0009\u0009" + GetDigitSequence(1, 100, random)); VerifyParseToString("\u000A\u000A\u000A" + GetDigitSequence(1, 100, random)); VerifyParseToString("\u000B\u000B\u000B" + GetDigitSequence(1, 100, random)); VerifyParseToString("\u000C\u000C\u000C" + GetDigitSequence(1, 100, random)); VerifyParseToString("\u000D\u000D\u000D" + GetDigitSequence(1, 100, random)); VerifyParseToString("\u0020\u0020\u0020" + GetDigitSequence(1, 100, random)); } // Trailing White for (int i = 0; i < s_samples; i++) { VerifyParseToString(GetDigitSequence(1, 100, random) + "\u0009\u0009\u0009"); VerifyParseToString(GetDigitSequence(1, 100, random) + "\u000A\u000A\u000A"); VerifyParseToString(GetDigitSequence(1, 100, random) + "\u000B\u000B\u000B"); VerifyParseToString(GetDigitSequence(1, 100, random) + "\u000C\u000C\u000C"); VerifyParseToString(GetDigitSequence(1, 100, random) + "\u000D\u000D\u000D"); VerifyParseToString(GetDigitSequence(1, 100, random) + "\u0020\u0020\u0020"); } // Leading Sign for (int i = 0; i < s_samples; i++) { VerifyParseToString(CultureInfo.CurrentCulture.NumberFormat.NegativeSign + GetDigitSequence(1, 100, random)); VerifyParseToString(CultureInfo.CurrentCulture.NumberFormat.PositiveSign + GetDigitSequence(1, 100, random)); } // Trailing Sign for (int i = 0; i < s_samples; i++) { VerifyFailParseToString(GetDigitSequence(1, 100, random) + CultureInfo.CurrentCulture.NumberFormat.NegativeSign, typeof(FormatException)); VerifyFailParseToString(GetDigitSequence(1, 100, random) + CultureInfo.CurrentCulture.NumberFormat.PositiveSign, typeof(FormatException)); } // Parentheses for (int i = 0; i < s_samples; i++) { VerifyFailParseToString("(" + GetDigitSequence(1, 100, random) + ")", typeof(FormatException)); } // Decimal Point - end for (int i = 0; i < s_samples; i++) { VerifyFailParseToString(GetDigitSequence(1, 100, random) + CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator, typeof(FormatException)); } // Decimal Point - middle for (int i = 0; i < s_samples; i++) { VerifyFailParseToString(GetDigitSequence(1, 100, random) + CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator + "000", typeof(FormatException)); } // Decimal Point - non-zero decimal for (int i = 0; i < s_samples; i++) { VerifyFailParseToString(GetDigitSequence(1, 100, random) + CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator + GetDigitSequence(20, 25, random), typeof(FormatException)); } // Thousands for (int i = 0; i < s_samples; i++) { int[] sizes = null; string seperator = null; string digits = null; sizes = CultureInfo.CurrentCulture.NumberFormat.NumberGroupSizes; seperator = CultureInfo.CurrentCulture.NumberFormat.NumberGroupSeparator; digits = GenerateGroups(sizes, seperator, random); VerifyFailParseToString(digits, typeof(FormatException)); } // Exponent for (int i = 0; i < s_samples; i++) { VerifyFailParseToString(GetDigitSequence(1, 100, random) + "e" + CultureInfo.CurrentCulture.NumberFormat.PositiveSign + GetDigitSequence(1, 3, random), typeof(FormatException)); VerifyFailParseToString(GetDigitSequence(1, 100, random) + "e" + CultureInfo.CurrentCulture.NumberFormat.NegativeSign + GetDigitSequence(1, 3, random), typeof(FormatException)); } // Currency Symbol for (int i = 0; i < s_samples; i++) { VerifyFailParseToString(CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol + GetDigitSequence(1, 100, random), typeof(FormatException)); } // Hex Specifier for (int i = 0; i < s_samples; i++) { VerifyFailParseToString(GetHexDigitSequence(1, 100, random), typeof(FormatException)); } // Invalid Chars for (int i = 0; i < s_samples; i++) { VerifyFailParseToString(GetDigitSequence(1, 50, random) + GetRandomInvalidChar(random) + GetDigitSequence(1, 50, random), typeof(FormatException)); } } public static void VerifyNumberStyles(NumberStyles ns, Random random) { VerifyParseToString(null, ns, false, null); VerifyParseToString(string.Empty, ns, false); VerifyParseToString("0", ns, true); VerifyParseToString("000", ns, true); VerifyParseToString("1", ns, true); VerifyParseToString("001", ns, true); // SimpleNumbers - Small for (int i = 0; i < s_samples; i++) { VerifyParseToString(GetDigitSequence(1, 10, random), ns, true); } // SimpleNumbers - Large for (int i = 0; i < s_samples; i++) { VerifyParseToString(GetDigitSequence(100, 1000, random), ns, true); } // Leading White for (int i = 0; i < s_samples; i++) { VerifyParseToString("\u0009\u0009\u0009" + GetDigitSequence(1, 100, random), ns, ((ns & NumberStyles.AllowLeadingWhite) != 0)); VerifyParseToString("\u000A\u000A\u000A" + GetDigitSequence(1, 100, random), ns, ((ns & NumberStyles.AllowLeadingWhite) != 0)); VerifyParseToString("\u000B\u000B\u000B" + GetDigitSequence(1, 100, random), ns, ((ns & NumberStyles.AllowLeadingWhite) != 0)); VerifyParseToString("\u000C\u000C\u000C" + GetDigitSequence(1, 100, random), ns, ((ns & NumberStyles.AllowLeadingWhite) != 0)); VerifyParseToString("\u000D\u000D\u000D" + GetDigitSequence(1, 100, random), ns, ((ns & NumberStyles.AllowLeadingWhite) != 0)); VerifyParseToString("\u0020\u0020\u0020" + GetDigitSequence(1, 100, random), ns, ((ns & NumberStyles.AllowLeadingWhite) != 0)); } // Trailing White for (int i = 0; i < s_samples; i++) { VerifyParseToString(GetDigitSequence(1, 100, random) + "\u0009\u0009\u0009", ns, FailureNotExpectedForTrailingWhite(ns, false)); VerifyParseToString(GetDigitSequence(1, 100, random) + "\u000A\u000A\u000A", ns, FailureNotExpectedForTrailingWhite(ns, false)); VerifyParseToString(GetDigitSequence(1, 100, random) + "\u000B\u000B\u000B", ns, FailureNotExpectedForTrailingWhite(ns, false)); VerifyParseToString(GetDigitSequence(1, 100, random) + "\u000C\u000C\u000C", ns, FailureNotExpectedForTrailingWhite(ns, false)); VerifyParseToString(GetDigitSequence(1, 100, random) + "\u000D\u000D\u000D", ns, FailureNotExpectedForTrailingWhite(ns, false)); VerifyParseToString(GetDigitSequence(1, 100, random) + "\u0020\u0020\u0020", ns, FailureNotExpectedForTrailingWhite(ns, true)); } // Leading Sign for (int i = 0; i < s_samples; i++) { VerifyParseToString(CultureInfo.CurrentCulture.NumberFormat.NegativeSign + GetDigitSequence(1, 100, random), ns, ((ns & NumberStyles.AllowLeadingSign) != 0)); VerifyParseToString(CultureInfo.CurrentCulture.NumberFormat.PositiveSign + GetDigitSequence(1, 100, random), ns, ((ns & NumberStyles.AllowLeadingSign) != 0)); } // Trailing Sign for (int i = 0; i < s_samples; i++) { VerifyParseToString(GetDigitSequence(1, 100, random) + CultureInfo.CurrentCulture.NumberFormat.NegativeSign, ns, ((ns & NumberStyles.AllowTrailingSign) != 0)); VerifyParseToString(GetDigitSequence(1, 100, random) + CultureInfo.CurrentCulture.NumberFormat.PositiveSign, ns, ((ns & NumberStyles.AllowTrailingSign) != 0)); } // Parentheses for (int i = 0; i < s_samples; i++) { VerifyParseToString("(" + GetDigitSequence(1, 100, random) + ")", ns, ((ns & NumberStyles.AllowParentheses) != 0)); } // Decimal Point - end for (int i = 0; i < s_samples; i++) { VerifyParseToString(GetDigitSequence(1, 100, random) + CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator, ns, ((ns & NumberStyles.AllowDecimalPoint) != 0)); } // Decimal Point - middle for (int i = 0; i < s_samples; i++) { string digits = GetDigitSequence(1, 100, random); VerifyParseToString(digits + CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator + "000", ns, ((ns & NumberStyles.AllowDecimalPoint) != 0), digits); } // Decimal Point - non-zero decimal for (int i = 0; i < s_samples; i++) { string digits = GetDigitSequence(1, 100, random); VerifyParseToString(digits + CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator + GetDigitSequence(20, 25, random), ns, false, digits); } // Thousands for (int i = 0; i < s_samples; i++) { int[] sizes = null; string seperator = null; string digits = null; sizes = CultureInfo.CurrentCulture.NumberFormat.NumberGroupSizes; seperator = CultureInfo.CurrentCulture.NumberFormat.NumberGroupSeparator; digits = GenerateGroups(sizes, seperator, random); VerifyParseToString(digits, ns, ((ns & NumberStyles.AllowThousands) != 0)); } // Exponent for (int i = 0; i < s_samples; i++) { string digits = GetDigitSequence(1, 100, random); string exp = GetDigitSequence(1, 3, random); int expValue = int.Parse(exp); string zeros = new string('0', expValue); //Positive Exponents VerifyParseToString(digits + "e" + CultureInfo.CurrentCulture.NumberFormat.PositiveSign + exp, ns, ((ns & NumberStyles.AllowExponent) != 0), digits + zeros); //Negative Exponents bool valid = ((ns & NumberStyles.AllowExponent) != 0); for (int j = digits.Length; (valid && (j > 0) && (j > digits.Length - expValue)); j--) { if (digits[j - 1] != '0') { valid = false; } } if (digits.Length - int.Parse(exp) > 0) { VerifyParseToString(digits + "e" + CultureInfo.CurrentCulture.NumberFormat.NegativeSign + exp, ns, valid, digits.Substring(0, digits.Length - int.Parse(exp))); } else { VerifyParseToString(digits + "e" + CultureInfo.CurrentCulture.NumberFormat.NegativeSign + exp, ns, valid, "0"); } } // Currency Symbol for (int i = 0; i < s_samples; i++) { VerifyParseToString(CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol + GetDigitSequence(1, 100, random), ns, ((ns & NumberStyles.AllowCurrencySymbol) != 0)); } // Hex Specifier for (int i = 0; i < s_samples; i++) { VerifyParseToString(GetHexDigitSequence(1, 15, random) + "A", ns, ((ns & NumberStyles.AllowHexSpecifier) != 0)); } // Invalid Chars for (int i = 0; i < s_samples; i++) { VerifyParseToString(GetDigitSequence(1, 100, random) + GetRandomInvalidChar(random) + GetDigitSequence(1, 10, random), ns, false); } } private static void VerifyParseToString(string num1) { BigInteger test; Eval(BigInteger.Parse(num1), Fix(num1.Trim())); Assert.True(BigInteger.TryParse(num1, out test)); Eval(test, Fix(num1.Trim())); } private static void VerifyFailParseToString(string num1, Type expectedExceptionType) { BigInteger test; Assert.False(BigInteger.TryParse(num1, out test), string.Format("Expected TryParse to fail on {0}", num1)); if (num1 == null) { Assert.Throws<ArgumentNullException>(() => { BigInteger.Parse(num1).ToString("d"); }); } else { Assert.Throws<FormatException>(() => { BigInteger.Parse(num1).ToString("d"); }); } } private static void VerifyParseToString(string num1, NumberStyles ns, bool failureNotExpected) { VerifyParseToString(num1, ns, failureNotExpected, Fix(num1.Trim(), ((ns & NumberStyles.AllowHexSpecifier) != 0), failureNotExpected)); } static partial void VerifyParseSpanToString(string num1, NumberStyles ns, bool failureNotExpected, string expected); private static void VerifyParseToString(string num1, NumberStyles ns, bool failureNotExpected, string expected) { BigInteger test; if (failureNotExpected) { Eval(BigInteger.Parse(num1, ns), expected); Assert.True(BigInteger.TryParse(num1, ns, null, out test)); Eval(test, expected); } else { if (num1 == null) { Assert.Throws<ArgumentNullException>(() => { BigInteger.Parse(num1, ns); }); } else { Assert.Throws<FormatException>(() => { BigInteger.Parse(num1, ns); }); } Assert.False(BigInteger.TryParse(num1, ns, null, out test), string.Format("Expected TryParse to fail on {0}", num1)); } if (num1 != null) { VerifyParseSpanToString(num1, ns, failureNotExpected, expected); } } static partial void VerifySimpleFormatParseSpan(string num1, NumberFormatInfo nfi, BigInteger expected, bool failureExpected); private static void VerifySimpleFormatParse(string num1, NumberFormatInfo nfi, BigInteger expected, bool failureExpected = false) { BigInteger test; if (!failureExpected) { Assert.Equal(expected, BigInteger.Parse(num1, nfi)); Assert.True(BigInteger.TryParse(num1, NumberStyles.Any, nfi, out test)); Assert.Equal(expected, test); } else { Assert.Throws<FormatException>(() => { BigInteger.Parse(num1, nfi); }); Assert.False(BigInteger.TryParse(num1, NumberStyles.Any, nfi, out test), string.Format("Expected TryParse to fail on {0}", num1)); } if (num1 != null) { VerifySimpleFormatParseSpan(num1, nfi, expected, failureExpected); } } static partial void VerifyFormatParseSpan(string s, NumberStyles ns, NumberFormatInfo nfi, BigInteger expected, bool failureExpected); private static void VerifyFormatParse(string num1, NumberStyles ns, NumberFormatInfo nfi, BigInteger expected, bool failureExpected = false) { BigInteger test; if (!failureExpected) { Assert.Equal(expected, BigInteger.Parse(num1, ns, nfi)); Assert.True(BigInteger.TryParse(num1, NumberStyles.Any, nfi, out test)); Assert.Equal(expected, test); } else { Assert.Throws<FormatException>(() => { BigInteger.Parse(num1, ns, nfi); }); Assert.False(BigInteger.TryParse(num1, ns, nfi, out test), string.Format("Expected TryParse to fail on {0}", num1)); } if (num1 != null) { VerifyFormatParseSpan(num1, ns, nfi, expected, failureExpected); } } private static string GetDigitSequence(int min, int max, Random random) { string result = string.Empty; string[] digits = new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }; int size = random.Next(min, max); for (int i = 0; i < size; i++) { result += digits[random.Next(0, digits.Length)]; if (i == 0) { while (result == "0") { result = digits[random.Next(0, digits.Length)]; } } } return result; } private static string GetHexDigitSequence(int min, int max, Random random) { string result = string.Empty; string[] digits = new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" }; int size = random.Next(min, max); bool hasHexCharacter = false; while (!hasHexCharacter) { for (int i = 0; i < size; i++) { int j = random.Next(0, digits.Length); result += digits[j]; if (j > 9) { hasHexCharacter = true; } } } return result; } private static string GetRandomInvalidChar(Random random) { char[] digits = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F' }; char result = '5'; while (result == '5') { result = unchecked((char)random.Next()); for (int i = 0; i < digits.Length; i++) { if (result == (char)digits[i]) { result = '5'; } } // Remove the comma: 'AllowThousands' NumberStyle does not enforce the GroupSizes. if (result == ',') { result = '5'; } } string res = new string(result, 1); return res; } private static string Fix(string input) { return Fix(input, false); } private static string Fix(string input, bool isHex) { return Fix(input, isHex, true); } private static string Fix(string input, bool isHex, bool failureNotExpected) { string output = input; if (failureNotExpected) { if (isHex) { output = ConvertHexToDecimal(output); } while (output.StartsWith("0") & (output.Length > 1)) { output = output.Substring(1); } List<char> out2 = new List<char>(); for (int i = 0; i < output.Length; i++) { if ((output[i] >= '0') & (output[i] <= '9')) { out2.Add(output[i]); } } output = new string(out2.ToArray()); } return output; } private static string ConvertHexToDecimal(string input) { char[] inArr = input.ToCharArray(); bool isNeg = false; if (inArr.Length > 0) { if (int.Parse("0" + inArr[0], NumberStyles.AllowHexSpecifier) > 7) { isNeg = true; for (int i = 0; i < inArr.Length; i++) { int digit = int.Parse("0" + inArr[i], NumberStyles.AllowHexSpecifier); digit = 15 - digit; inArr[i] = digit.ToString("x")[0]; } } } BigInteger x = 0; BigInteger baseNum = 1; for (int i = inArr.Length - 1; i >= 0; i--) { try { BigInteger x2 = (int.Parse(new string(new char[] { inArr[i] }), NumberStyles.AllowHexSpecifier) * baseNum); x = x + x2; } catch (FormatException) { // left blank char is not a hex character; } baseNum = baseNum * 16; } if (isNeg) { x = x + 1; } List<char> number = new List<char>(); if (x == 0) { number.Add('0'); } else { while (x > 0) { number.Add((x % 10).ToString().ToCharArray()[0]); x = x / 10; } number.Reverse(); } string y2 = new string(number.ToArray()); if (isNeg) { y2 = CultureInfo.CurrentCulture.NumberFormat.NegativeSign.ToCharArray() + y2; } return y2; } private static string GenerateGroups(int[] sizes, string seperator, Random random) { List<int> total_sizes = new List<int>(); int total; int num_digits = random.Next(10, 100); string digits = string.Empty; total = 0; total_sizes.Add(0); for (int j = 0; ((j < (sizes.Length - 1)) && (total < 101)); j++) { total += sizes[j]; total_sizes.Add(total); } if (total < 101) { if (sizes[sizes.Length - 1] == 0) { total_sizes.Add(101); } else { while (total < 101) { total += sizes[sizes.Length - 1]; total_sizes.Add(total); } } } bool first = true; for (int j = total_sizes.Count - 1; j > 0; j--) { if ((first) && (total_sizes[j] >= num_digits)) { continue; } int group_size = num_digits - total_sizes[j - 1]; if (first) { digits += GetDigitSequence(group_size, group_size, random); first = false; } else { //Generate an extra character since the first character of GetDigitSequence is non-zero. digits += GetDigitSequence(group_size + 1, group_size + 1, random).Substring(1); } num_digits -= group_size; if (num_digits > 0) { digits += seperator; } } return digits; } private static NumberFormatInfo MarkUp(NumberFormatInfo nfi) { nfi.CurrencyDecimalDigits = 0; nfi.CurrencyDecimalSeparator = "!"; nfi.CurrencyGroupSeparator = "#"; nfi.CurrencyGroupSizes = new int[] { 2 }; nfi.CurrencyNegativePattern = 4; nfi.CurrencyPositivePattern = 2; nfi.CurrencySymbol = "@"; nfi.NumberDecimalDigits = 0; nfi.NumberDecimalSeparator = "^"; nfi.NumberGroupSeparator = "&"; nfi.NumberGroupSizes = new int[] { 4 }; nfi.NumberNegativePattern = 4; nfi.PercentDecimalDigits = 0; nfi.PercentDecimalSeparator = "*"; nfi.PercentGroupSeparator = "+"; nfi.PercentGroupSizes = new int[] { 5 }; nfi.PercentNegativePattern = 2; nfi.PercentPositivePattern = 2; nfi.PercentSymbol = "?"; nfi.PerMilleSymbol = "~"; nfi.NegativeSign = "<"; nfi.PositiveSign = ">"; return nfi; } // We need to account for cultures like fr-FR and uk-UA that use the no-break space (NBSP, 0xA0) // character as the group separator. Because NBSP cannot be (easily) entered by the end user we // accept regular spaces (SP, 0x20) as group separators for those cultures which means that // trailing SP characters will be interpreted as group separators rather than whitespace. // // See also System.Globalization.FormatProvider+Number.MatchChars(char*, char*) private static bool FailureNotExpectedForTrailingWhite(NumberStyles ns, bool spaceOnlyTrail) { if (spaceOnlyTrail && (ns & NumberStyles.AllowThousands) != 0) { if ((ns & NumberStyles.AllowCurrencySymbol) != 0) { if (CultureInfo.CurrentCulture.NumberFormat.CurrencyGroupSeparator == "\u00A0") return true; } else { if (CultureInfo.CurrentCulture.NumberFormat.NumberGroupSeparator == "\u00A0") return true; } } return (ns & NumberStyles.AllowTrailingWhite) != 0; } public static void Eval(BigInteger x, string expected) { bool IsPos = (x >= 0); if (!IsPos) { x = -x; } if (x == 0) { Assert.Equal(expected, "0"); } else { List<char> number = new List<char>(); while (x > 0) { number.Add((x % 10).ToString().ToCharArray()[0]); x = x / 10; } number.Reverse(); string actual = new string(number.ToArray()); Assert.Equal(expected, actual); } } } }
// 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. /*============================================================ ** ** ** ** ** ** Purpose: Exposes routines for enumerating through a ** directory. ** ** April 11,2000 ** ===========================================================*/ using System; using System.Collections; using System.Collections.Generic; using System.Security; #if FEATURE_MACL using System.Security.AccessControl; #endif using System.Security.Permissions; using Microsoft.Win32; using System.Text; using System.Runtime.InteropServices; using System.Globalization; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Diagnostics.Contracts; namespace System.IO { [Serializable] [ComVisible(true)] public sealed class DirectoryInfo : FileSystemInfo { private String[] demandDir; #if FEATURE_CORECLR // Migrating InheritanceDemands requires this default ctor, so we can annotate it. #if FEATURE_CORESYSTEM [System.Security.SecurityCritical] #else [System.Security.SecuritySafeCritical] #endif //FEATURE_CORESYSTEM private DirectoryInfo(){} [System.Security.SecurityCritical] public static DirectoryInfo UnsafeCreateDirectoryInfo(String path) { if (path == null) throw new ArgumentNullException(nameof(path)); Contract.EndContractBlock(); DirectoryInfo di = new DirectoryInfo(); di.Init(path, false); return di; } #endif [System.Security.SecuritySafeCritical] public DirectoryInfo(String path) { if (path==null) throw new ArgumentNullException(nameof(path)); Contract.EndContractBlock(); Init(path, true); } [System.Security.SecurityCritical] private void Init(String path, bool checkHost) { // Special case "<DriveLetter>:" to point to "<CurrentDirectory>" instead if ((path.Length == 2) && (path[1] == ':')) { OriginalPath = "."; } else { OriginalPath = path; } // Must fully qualify the path for the security check String fullPath = Path.GetFullPathInternal(path); demandDir = new String[] {Directory.GetDemandDir(fullPath, true)}; #if FEATURE_CORECLR if (checkHost) { FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, OriginalPath, fullPath); state.EnsureState(); } #else new FileIOPermission(FileIOPermissionAccess.Read, demandDir, false, false ).Demand(); #endif FullPath = fullPath; DisplayPath = GetDisplayName(OriginalPath, FullPath); } #if FEATURE_CORESYSTEM [System.Security.SecuritySafeCritical] #endif //FEATURE_CORESYSTEM internal DirectoryInfo(String fullPath, bool junk) { Contract.Assert(Path.GetRootLength(fullPath) > 0, "fullPath must be fully qualified!"); // Fast path when we know a DirectoryInfo exists. OriginalPath = Path.GetFileName(fullPath); FullPath = fullPath; DisplayPath = GetDisplayName(OriginalPath, FullPath); demandDir = new String[] {Directory.GetDemandDir(fullPath, true)}; } [System.Security.SecurityCritical] // auto-generated private DirectoryInfo(SerializationInfo info, StreamingContext context) : base(info, context) { #if !FEATURE_CORECLR demandDir = new String[] {Directory.GetDemandDir(FullPath, true)}; new FileIOPermission(FileIOPermissionAccess.Read, demandDir, false, false ).Demand(); #endif DisplayPath = GetDisplayName(OriginalPath, FullPath); } public override String Name { get { #if FEATURE_CORECLR // DisplayPath is dir name for coreclr return DisplayPath; #else // Return just dir name return GetDirName(FullPath); #endif } } public DirectoryInfo Parent { [System.Security.SecuritySafeCritical] get { String parentName; // FullPath might be either "c:\bar" or "c:\bar\". Handle // those cases, as well as avoiding mangling "c:\". String s = FullPath; if (s.Length > 3 && s.EndsWith(Path.DirectorySeparatorChar)) s = FullPath.Substring(0, FullPath.Length - 1); parentName = Path.GetDirectoryName(s); if (parentName==null) return null; DirectoryInfo dir = new DirectoryInfo(parentName,false); #if FEATURE_CORECLR FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.PathDiscovery | FileSecurityStateAccess.Read, String.Empty, dir.demandDir[0]); state.EnsureState(); #else new FileIOPermission(FileIOPermissionAccess.PathDiscovery | FileIOPermissionAccess.Read, dir.demandDir, false, false).Demand(); #endif return dir; } } #if FEATURE_CORECLR [System.Security.SecuritySafeCritical] #endif public DirectoryInfo CreateSubdirectory(String path) { if (path == null) throw new ArgumentNullException(nameof(path)); Contract.EndContractBlock(); return CreateSubdirectory(path, null); } #if FEATURE_MACL [System.Security.SecuritySafeCritical] // auto-generated public DirectoryInfo CreateSubdirectory(String path, DirectorySecurity directorySecurity) { return CreateSubdirectoryHelper(path, directorySecurity); } #else // FEATURE_MACL #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif public DirectoryInfo CreateSubdirectory(String path, Object directorySecurity) { if (path == null) throw new ArgumentNullException(nameof(path)); Contract.EndContractBlock(); return CreateSubdirectoryHelper(path, directorySecurity); } #endif // FEATURE_MACL [System.Security.SecurityCritical] // auto-generated private DirectoryInfo CreateSubdirectoryHelper(String path, Object directorySecurity) { Contract.Requires(path != null); String newDirs = Path.InternalCombine(FullPath, path); String fullPath = Path.GetFullPathInternal(newDirs); if (0!=String.Compare(FullPath,0,fullPath,0, FullPath.Length,StringComparison.OrdinalIgnoreCase)) { String displayPath = __Error.GetDisplayablePath(DisplayPath, false); throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSubPath", path, displayPath)); } // Ensure we have permission to create this subdirectory. String demandDirForCreation = Directory.GetDemandDir(fullPath, true); #if FEATURE_CORECLR FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Write, OriginalPath, demandDirForCreation); state.EnsureState(); #else new FileIOPermission(FileIOPermissionAccess.Write, new String[] { demandDirForCreation }, false, false).Demand(); #endif Directory.InternalCreateDirectory(fullPath, path, directorySecurity); // Check for read permission to directory we hand back by calling this constructor. return new DirectoryInfo(fullPath); } public void Create() { Directory.InternalCreateDirectory(FullPath, OriginalPath, null, true); } #if FEATURE_MACL public void Create(DirectorySecurity directorySecurity) { Directory.InternalCreateDirectory(FullPath, OriginalPath, directorySecurity, true); } #endif // Tests if the given path refers to an existing DirectoryInfo on disk. // // Your application must have Read permission to the directory's // contents. // public override bool Exists { [System.Security.SecuritySafeCritical] // auto-generated get { try { if (_dataInitialised == -1) Refresh(); if (_dataInitialised != 0) // Refresh was unable to initialise the data return false; return _data.fileAttributes != -1 && (_data.fileAttributes & Win32Native.FILE_ATTRIBUTE_DIRECTORY) != 0; } catch { return false; } } } #if FEATURE_MACL public DirectorySecurity GetAccessControl() { return Directory.GetAccessControl(FullPath, AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group); } public DirectorySecurity GetAccessControl(AccessControlSections includeSections) { return Directory.GetAccessControl(FullPath, includeSections); } public void SetAccessControl(DirectorySecurity directorySecurity) { Directory.SetAccessControl(FullPath, directorySecurity); } #endif // Returns an array of Files in the current DirectoryInfo matching the // given search criteria (ie, "*.txt"). public FileInfo[] GetFiles(String searchPattern) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); Contract.EndContractBlock(); return InternalGetFiles(searchPattern, SearchOption.TopDirectoryOnly); } // Returns an array of Files in the current DirectoryInfo matching the // given search criteria (ie, "*.txt"). public FileInfo[] GetFiles(String searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException(nameof(searchOption), Environment.GetResourceString("ArgumentOutOfRange_Enum")); Contract.EndContractBlock(); return InternalGetFiles(searchPattern, searchOption); } // Returns an array of Files in the current DirectoryInfo matching the // given search criteria (ie, "*.txt"). private FileInfo[] InternalGetFiles(String searchPattern, SearchOption searchOption) { Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); IEnumerable<FileInfo> enble = FileSystemEnumerableFactory.CreateFileInfoIterator(FullPath, OriginalPath, searchPattern, searchOption); List<FileInfo> fileList = new List<FileInfo>(enble); return fileList.ToArray(); } // Returns an array of Files in the DirectoryInfo specified by path public FileInfo[] GetFiles() { return InternalGetFiles("*", SearchOption.TopDirectoryOnly); } // Returns an array of Directories in the current directory. public DirectoryInfo[] GetDirectories() { return InternalGetDirectories("*", SearchOption.TopDirectoryOnly); } // Returns an array of strongly typed FileSystemInfo entries in the path with the // given search criteria (ie, "*.txt"). public FileSystemInfo[] GetFileSystemInfos(String searchPattern) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); Contract.EndContractBlock(); return InternalGetFileSystemInfos(searchPattern, SearchOption.TopDirectoryOnly); } // Returns an array of strongly typed FileSystemInfo entries in the path with the // given search criteria (ie, "*.txt"). public FileSystemInfo[] GetFileSystemInfos(String searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException(nameof(searchOption), Environment.GetResourceString("ArgumentOutOfRange_Enum")); Contract.EndContractBlock(); return InternalGetFileSystemInfos(searchPattern, searchOption); } // Returns an array of strongly typed FileSystemInfo entries in the path with the // given search criteria (ie, "*.txt"). private FileSystemInfo[] InternalGetFileSystemInfos(String searchPattern, SearchOption searchOption) { Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); IEnumerable<FileSystemInfo> enble = FileSystemEnumerableFactory.CreateFileSystemInfoIterator(FullPath, OriginalPath, searchPattern, searchOption); List<FileSystemInfo> fileList = new List<FileSystemInfo>(enble); return fileList.ToArray(); } // Returns an array of strongly typed FileSystemInfo entries which will contain a listing // of all the files and directories. public FileSystemInfo[] GetFileSystemInfos() { return InternalGetFileSystemInfos("*", SearchOption.TopDirectoryOnly); } // Returns an array of Directories in the current DirectoryInfo matching the // given search criteria (ie, "System*" could match the System & System32 // directories). public DirectoryInfo[] GetDirectories(String searchPattern) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); Contract.EndContractBlock(); return InternalGetDirectories(searchPattern, SearchOption.TopDirectoryOnly); } // Returns an array of Directories in the current DirectoryInfo matching the // given search criteria (ie, "System*" could match the System & System32 // directories). public DirectoryInfo[] GetDirectories(String searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException(nameof(searchOption), Environment.GetResourceString("ArgumentOutOfRange_Enum")); Contract.EndContractBlock(); return InternalGetDirectories(searchPattern, searchOption); } // Returns an array of Directories in the current DirectoryInfo matching the // given search criteria (ie, "System*" could match the System & System32 // directories). private DirectoryInfo[] InternalGetDirectories(String searchPattern, SearchOption searchOption) { Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); IEnumerable<DirectoryInfo> enble = FileSystemEnumerableFactory.CreateDirectoryInfoIterator(FullPath, OriginalPath, searchPattern, searchOption); List<DirectoryInfo> fileList = new List<DirectoryInfo>(enble); return fileList.ToArray(); } public IEnumerable<DirectoryInfo> EnumerateDirectories() { return InternalEnumerateDirectories("*", SearchOption.TopDirectoryOnly); } public IEnumerable<DirectoryInfo> EnumerateDirectories(String searchPattern) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); Contract.EndContractBlock(); return InternalEnumerateDirectories(searchPattern, SearchOption.TopDirectoryOnly); } public IEnumerable<DirectoryInfo> EnumerateDirectories(String searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException(nameof(searchOption), Environment.GetResourceString("ArgumentOutOfRange_Enum")); Contract.EndContractBlock(); return InternalEnumerateDirectories(searchPattern, searchOption); } private IEnumerable<DirectoryInfo> InternalEnumerateDirectories(String searchPattern, SearchOption searchOption) { Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); return FileSystemEnumerableFactory.CreateDirectoryInfoIterator(FullPath, OriginalPath, searchPattern, searchOption); } public IEnumerable<FileInfo> EnumerateFiles() { return InternalEnumerateFiles("*", SearchOption.TopDirectoryOnly); } public IEnumerable<FileInfo> EnumerateFiles(String searchPattern) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); Contract.EndContractBlock(); return InternalEnumerateFiles(searchPattern, SearchOption.TopDirectoryOnly); } public IEnumerable<FileInfo> EnumerateFiles(String searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException(nameof(searchOption), Environment.GetResourceString("ArgumentOutOfRange_Enum")); Contract.EndContractBlock(); return InternalEnumerateFiles(searchPattern, searchOption); } private IEnumerable<FileInfo> InternalEnumerateFiles(String searchPattern, SearchOption searchOption) { Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); return FileSystemEnumerableFactory.CreateFileInfoIterator(FullPath, OriginalPath, searchPattern, searchOption); } public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos() { return InternalEnumerateFileSystemInfos("*", SearchOption.TopDirectoryOnly); } public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(String searchPattern) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); Contract.EndContractBlock(); return InternalEnumerateFileSystemInfos(searchPattern, SearchOption.TopDirectoryOnly); } public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(String searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException(nameof(searchOption), Environment.GetResourceString("ArgumentOutOfRange_Enum")); Contract.EndContractBlock(); return InternalEnumerateFileSystemInfos(searchPattern, searchOption); } private IEnumerable<FileSystemInfo> InternalEnumerateFileSystemInfos(String searchPattern, SearchOption searchOption) { Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); return FileSystemEnumerableFactory.CreateFileSystemInfoIterator(FullPath, OriginalPath, searchPattern, searchOption); } // Returns the root portion of the given path. The resulting string // consists of those rightmost characters of the path that constitute the // root of the path. Possible patterns for the resulting string are: An // empty string (a relative path on the current drive), "\" (an absolute // path on the current drive), "X:" (a relative path on a given drive, // where X is the drive letter), "X:\" (an absolute path on a given drive), // and "\\server\share" (a UNC path for a given server and share name). // The resulting string is null if path is null. // public DirectoryInfo Root { [System.Security.SecuritySafeCritical] get { String demandPath; int rootLength = Path.GetRootLength(FullPath); String rootPath = FullPath.Substring(0, rootLength); demandPath = Directory.GetDemandDir(rootPath, true); #if FEATURE_CORECLR FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, String.Empty, demandPath); sourceState.EnsureState(); #else new FileIOPermission(FileIOPermissionAccess.PathDiscovery, new String[] { demandPath }, false, false).Demand(); #endif return new DirectoryInfo(rootPath); } } [System.Security.SecuritySafeCritical] public void MoveTo(String destDirName) { if (destDirName==null) throw new ArgumentNullException(nameof(destDirName)); if (destDirName.Length==0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), nameof(destDirName)); Contract.EndContractBlock(); #if FEATURE_CORECLR FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Write | FileSecurityStateAccess.Read, DisplayPath, Directory.GetDemandDir(FullPath, true)); sourceState.EnsureState(); #else new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, demandDir, false, false).Demand(); #endif String fullDestDirName = Path.GetFullPathInternal(destDirName); String demandPath; if (!fullDestDirName.EndsWith(Path.DirectorySeparatorChar)) fullDestDirName = fullDestDirName + Path.DirectorySeparatorChar; demandPath = fullDestDirName + '.'; // Demand read & write permission to destination. The reason is // we hand back a DirectoryInfo to the destination that would allow // you to read a directory listing from that directory. Sure, you // had the ability to read the file contents in the old location, // but you technically also need read permissions to the new // location as well, and write is not a true superset of read. #if FEATURE_CORECLR FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Write, destDirName, demandPath); destState.EnsureState(); #else new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, demandPath).Demand(); #endif String fullSourcePath; if (FullPath.EndsWith(Path.DirectorySeparatorChar)) fullSourcePath = FullPath; else fullSourcePath = FullPath + Path.DirectorySeparatorChar; if (String.Compare(fullSourcePath, fullDestDirName, StringComparison.OrdinalIgnoreCase) == 0) throw new IOException(Environment.GetResourceString("IO.IO_SourceDestMustBeDifferent")); String sourceRoot = Path.GetPathRoot(fullSourcePath); String destinationRoot = Path.GetPathRoot(fullDestDirName); if (String.Compare(sourceRoot, destinationRoot, StringComparison.OrdinalIgnoreCase) != 0) throw new IOException(Environment.GetResourceString("IO.IO_SourceDestMustHaveSameRoot")); if (!Win32Native.MoveFile(FullPath, destDirName)) { int hr = Marshal.GetLastWin32Error(); if (hr == Win32Native.ERROR_FILE_NOT_FOUND) // A dubious error code { hr = Win32Native.ERROR_PATH_NOT_FOUND; __Error.WinIOError(hr, DisplayPath); } if (hr == Win32Native.ERROR_ACCESS_DENIED) // We did this for Win9x. We can't change it for backcomp. throw new IOException(Environment.GetResourceString("UnauthorizedAccess_IODenied_Path", DisplayPath)); __Error.WinIOError(hr,String.Empty); } FullPath = fullDestDirName; OriginalPath = destDirName; DisplayPath = GetDisplayName(OriginalPath, FullPath); demandDir = new String[] { Directory.GetDemandDir(FullPath, true) }; // Flush any cached information about the directory. _dataInitialised = -1; } [System.Security.SecuritySafeCritical] public override void Delete() { Directory.Delete(FullPath, OriginalPath, false, true); } [System.Security.SecuritySafeCritical] public void Delete(bool recursive) { Directory.Delete(FullPath, OriginalPath, recursive, true); } // Returns the fully qualified path public override String ToString() { return DisplayPath; } private static String GetDisplayName(String originalPath, String fullPath) { Contract.Assert(originalPath != null); Contract.Assert(fullPath != null); String displayName = ""; // Special case "<DriveLetter>:" to point to "<CurrentDirectory>" instead if ((originalPath.Length == 2) && (originalPath[1] == ':')) { displayName = "."; } else { #if FEATURE_CORECLR displayName = GetDirName(fullPath); #else displayName = originalPath; #endif } return displayName; } private static String GetDirName(String fullPath) { Contract.Assert(fullPath != null); String dirName = null; if (fullPath.Length > 3) { String s = fullPath; if (fullPath.EndsWith(Path.DirectorySeparatorChar)) { s = fullPath.Substring(0, fullPath.Length - 1); } dirName = Path.GetFileName(s); } else { dirName = fullPath; // For rooted paths, like "c:\" } return dirName; } } }
#region Copyright // // This framework is based on log4j see http://jakarta.apache.org/log4j // Copyright (C) The Apache Software Foundation. All rights reserved. // // This software is published under the terms of the Apache Software // License version 1.1, a copy of which has been included with this // distribution in the LICENSE.txt file. // #endregion using System; using System.Collections; namespace log4net.spi { /// <summary> /// Defines the set of levels recognised by the system. /// </summary> /// <remarks> /// <para>Defines the set of levels recognised by the system.</para> /// /// <para>The predefined set of levels recognised by the system are /// <see cref="OFF"/>, <see cref="FATAL"/>, <see cref="ERROR"/>, /// <see cref="WARN"/>, <see cref="INFO"/>, <see cref="DEBUG"/> and /// <see cref="ALL"/>.</para> /// /// <para>The Level class is sealed. You cannot extend this class.</para> /// </remarks> #if !NETCF [Serializable] #endif sealed public class Level { #region Static Member Variables /// <summary> /// The <c>OFF</c> level designates a higher level than all the rest. /// </summary> public readonly static Level OFF = new Level(int.MaxValue, "OFF"); /// <summary> /// The <c>EMERGENCY</c> level designates very severe error events. System unusable, emergencies. /// </summary> public readonly static Level EMERGENCY = new Level(120000, "EMERGENCY"); /// <summary> /// The <c>FATAL</c> level designates very severe error events that will presumably lead the application to abort. /// </summary> public readonly static Level FATAL = new Level(110000, "FATAL"); /// <summary> /// The <c>ALERT</c> level designates very severe error events. Take immediate action, alerts. /// </summary> public readonly static Level ALERT = new Level(100000, "ALERT"); /// <summary> /// The <c>CRITICAL</c> level designates very severe error events. Critical condition, critical. /// </summary> public readonly static Level CRITICAL = new Level(90000, "CRITICAL"); /// <summary> /// The <c>SEVERE</c> level designates very severe error events. Critical condition, critical. /// </summary> public readonly static Level SEVERE = new Level(80000, "SEVERE"); /// <summary> /// The <c>ERROR</c> level designates error events that might still allow the application to continue running. /// </summary> public readonly static Level ERROR = new Level(70000, "ERROR"); /// <summary> /// The <c>WARN</c> level designates potentially harmful situations. /// </summary> public readonly static Level WARN = new Level(60000, "WARN"); /// <summary> /// The <c>NOTICE</c> level designates informational messages that highlight the progress of the application at the highest level. /// </summary> public readonly static Level NOTICE = new Level(50000, "NOTICE"); /// <summary> /// The <c>INFO</c> level designates informational messages that highlight the progress of the application at coarse-grained level. /// </summary> public readonly static Level INFO = new Level(40000, "INFO"); /// <summary> /// The <c>DEBUG</c> level designates fine-grained informational events that are most useful to debug an application. /// </summary> public readonly static Level DEBUG = new Level(30000, "DEBUG"); /// <summary> /// The <c>FINE</c> level designates fine-grained informational events that are most useful to debug an application. /// </summary> public readonly static Level FINE = new Level(30000, "FINE"); /// <summary> /// The <c>TRACE</c> level designates fine-grained informational events that are most useful to debug an application. /// </summary> public readonly static Level TRACE = new Level(20000, "TRACE"); /// <summary> /// The <c>FINER</c> level designates fine-grained informational events that are most useful to debug an application. /// </summary> public readonly static Level FINER = new Level(20000, "FINER"); /// <summary> /// The <c>VERBOSE</c> level designates fine-grained informational events that are most useful to debug an application. /// </summary> public readonly static Level VERBOSE = new Level(10000, "VERBOSE"); /// <summary> /// The <c>FINEST</c> level designates fine-grained informational events that are most useful to debug an application. /// </summary> public readonly static Level FINEST = new Level(10000, "FINEST"); /// <summary> /// The <c>ALL</c> level designates the lowest level possible. /// </summary> public readonly static Level ALL = new Level(int.MinValue, "ALL"); #endregion #region Member Variables private int m_level; private string m_levelStr; #endregion #region Constructors /// <summary> /// Instantiate a level object. /// </summary> /// <param name="level">integer value for this level, higher values represent more severe levels</param> /// <param name="levelName">the string name of this level</param> public Level(int level, string levelName) { m_level = level; m_levelStr = string.Intern(levelName); } #endregion #region Override implementation of Object /// <summary> /// Returns the string representation of this level. /// </summary> /// <returns></returns> override public string ToString() { return m_levelStr; } /// <summary> /// Override Equals to compare the levels of /// Level objects. Defers to base class if /// the target object is not a Level. /// </summary> /// <param name="o">The object to compare against</param> /// <returns>true if the objects are equal</returns> override public bool Equals(object o) { if (o != null && o is Level) { return m_level == ((Level)o).m_level; } else { return base.Equals(o); } } /// <summary> /// Returns a hash code that is suitable for use in a hashtree etc /// </summary> /// <returns>the hash of this object</returns> override public int GetHashCode() { return m_level; } #endregion #region Operators /// <summary> /// Operator greater than that compares Levels /// </summary> /// <param name="l">left hand side</param> /// <param name="r">right hand side</param> /// <returns>true if left hand side is greater than the right hand side</returns> public static bool operator > (Level l, Level r) { return l.m_level > r.m_level; } /// <summary> /// Operator less than that compares Levels /// </summary> /// <param name="l">left hand side</param> /// <param name="r">right hand side</param> /// <returns>true if left hand side is less than the right hand side</returns> public static bool operator < (Level l, Level r) { return l.m_level < r.m_level; } /// <summary> /// Operator greater than or equal that compares Levels /// </summary> /// <param name="l">left hand side</param> /// <param name="r">right hand side</param> /// <returns>true if left hand side is greater than or equal to the right hand side</returns> public static bool operator >= (Level l, Level r) { return l.m_level >= r.m_level; } /// <summary> /// Operator less than or equal that compares Levels /// </summary> /// <param name="l">left hand side</param> /// <param name="r">right hand side</param> /// <returns>true if left hand side is less than or equal to the right hand side</returns> public static bool operator <= (Level l, Level r) { return l.m_level <= r.m_level; } /// <summary> /// Operator equals that compares Levels /// </summary> /// <param name="l">left hand side</param> /// <param name="r">right hand side</param> /// <returns>true if left hand side is equal to the right hand side</returns> public static bool operator == (Level l, Level r) { if (((object)l) != null && ((object)r) != null) { return l.m_level == r.m_level; } else { return ((object)l) == ((object)r); } } /// <summary> /// Operator not equals that compares Levels /// </summary> /// <param name="l">left hand side</param> /// <param name="r">right hand side</param> /// <returns>true if left hand side is not equal to the right hand side</returns> public static bool operator != (Level l, Level r) { return !(l==r); } #endregion /// <summary> /// The name of this level /// </summary> /// <value> /// The name of this level /// </value> /// <remarks> /// The name of this level. Readonly. /// </remarks> public string Name { get { return m_levelStr; } } /// <summary> /// The Value of this level /// </summary> /// <value> /// The Value of this level /// </value> /// <remarks> /// The Value of this level. Readonly. /// </remarks> public int Value { get { return m_level; } } /// <summary> /// Compares two specified <see cref="Level"/> values. /// </summary> /// <param name="l">A <see cref="Level"/></param> /// <param name="r">A <see cref="Level"/></param> /// <returns>A signed number indicating the relative values of <c>l</c> and <c>r</c>.</returns> /// <remarks> /// Less than zero: <c>l</c> is less than <c>r</c>. /// Zero: <c>l</c> and <c>r</c> are equal. /// Greater than zero: <c>l</c> is greater than <c>r</c>. /// </remarks> public static int Compare(Level l, Level r) { if (l == null && r == null) { return 0; } if (l == null) { return -1; } if (r == null) { return 1; } return l.m_level - r.m_level; } /// <summary> /// Compares this instance to a specified <see cref="Object"/> /// </summary> /// <param name="r">An <see cref="Object"/> or a null reference</param> /// <returns>A signed number indicating the relative values of this instance and <c>r</c>.</returns> /// <remarks> /// Less than zero: this instance is less than <c>r</c>. /// Zero: this instance and <c>r</c> are equal. /// Greater than zero: this instance is greater than <c>r</c>. /// Any instance of <see cref="Level"/>, regardless of its value, /// is considered greater than a null reference. /// </remarks> public int CompareTo(object r) { if (r is Level) { return Compare(this, (Level)r); } throw new ArgumentOutOfRangeException("Parameter: r, Value: ["+r+"] out of range. Expected instance of Level"); } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // // ExtensionsTest.cs - NUnit Test Cases for Extensions.cs class under // System.Xml.Schema namespace found in System.Xml.Linq assembly // (System.Xml.Linq.dll) // // Author: // Stefan Prutianu (stefanprutianu@yahoo.com) // // (C) Stefan Prutianu // using System; using System.Xml; using System.IO; using Network = System.Net; using System.Xml.Linq; using System.Xml.Schema; using System.Collections.Generic; using ExtensionsClass = System.Xml.Schema.Extensions; using Xunit; namespace CoreXml.Test.XLinq { public class SchemaExtensionsTests { public static string xsdString; public static XmlSchemaSet schemaSet; public static string xmlString; public static XDocument xmlDocument; public static bool validationSucceded; // initialize values for tests public SchemaExtensionsTests() { xsdString = @"<?xml version='1.0'?> <xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:element name='note'> <xs:complexType> <xs:sequence> <xs:element name='to' type='xs:string'/> <xs:element name='from' type='xs:string'/> <xs:element name='heading' type='xs:string'/> <xs:element name='ps' type='xs:string' maxOccurs='1' minOccurs = '0' default='Bye!'/> <xs:element name='body'> <xs:simpleType> <xs:restriction base='xs:string'> <xs:minLength value='5'/> <xs:maxLength value='30'/> </xs:restriction> </xs:simpleType> </xs:element> </xs:sequence> <xs:attribute name='subject' type='xs:string' default='mono'/> <xs:attribute name='date' type='xs:date' use='required'/> </xs:complexType> </xs:element> </xs:schema>"; schemaSet = new XmlSchemaSet(); schemaSet.Add("", XmlReader.Create(new StringReader(xsdString))); xmlString = @"<?xml version='1.0'?> <note date ='2010-05-26'> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget to call me!</body> </note>"; xmlDocument = XDocument.Load(new StringReader(xmlString)); validationSucceded = false; /* * Use this method to load the above data from disk * Comment the above code when using this method. * Also the arguments for the folowing tests: XAttributeSuccessValidate * XAttributeFailValidate, XAttributeThrowExceptionValidate, XElementSuccessValidate * XElementFailValidate,XElementThrowExceptionValidate, XAttributeGetSchemaInfo * XElementGetSchemaInfo may need to be changed. */ //LoadOutsideDocuments ("c:\\note.xsd", "c:\\note.xml"); } // this gets called when a validation error occurs private void TestValidationHandler(object sender, ValidationEventArgs e) { validationSucceded = false; } // test succesfull validation [Fact] public void XDocumentSuccessValidate() { validationSucceded = true; ExtensionsClass.Validate (xmlDocument, schemaSet, new ValidationEventHandler(TestValidationHandler)); Assert.Equal(true, validationSucceded); } // test failed validation [Fact] public void XDocumentFailValidate() { string elementName = "AlteringElementName"; object elementValue = "AlteringElementValue"; // alter XML document to invalidate XElement newElement = new XElement(elementName, elementValue); xmlDocument.Root.Add(newElement); validationSucceded = true; ExtensionsClass.Validate (xmlDocument, schemaSet, new ValidationEventHandler(TestValidationHandler)); Assert.Equal(false, validationSucceded); } /* * test if exception is thrown when xml document does not * conform to the xml schema */ [Fact] public void XDocumentThrowExceptionValidate() { string elementName = "AlteringElementName"; object elementValue = "AlteringElementValue"; // alter XML document to invalidate XElement newElement = new XElement(elementName, elementValue); xmlDocument.Root.Add(newElement); Assert.Throws<XmlSchemaValidationException>(() => ExtensionsClass.Validate (xmlDocument, schemaSet, null)); } /* * test xml validation populating the XML tree with * the post-schema-validation infoset(PSVI) */ [Fact] public void XDocumentAddSchemaInfoValidate() { // no. of elements before validation IEnumerable<XElement> elements = xmlDocument.Elements (); IEnumerator<XElement> elementsEnumerator = elements.GetEnumerator (); int beforeNoOfElements = 0; int beforeNoOfAttributes = 0; while (elementsEnumerator.MoveNext ()) { beforeNoOfElements++; if (!elementsEnumerator.Current.HasAttributes) continue; else { IEnumerable<XAttribute> attributes = elementsEnumerator.Current.Attributes (); IEnumerator<XAttribute> attributesEnumerator = attributes.GetEnumerator (); while (attributesEnumerator.MoveNext ()) beforeNoOfAttributes++; } } // populate XML with PSVI validationSucceded = true; ExtensionsClass.Validate (xmlDocument, schemaSet, new ValidationEventHandler(TestValidationHandler), true); Assert.Equal(true, validationSucceded); // no. of elements after validation elements = xmlDocument.Elements (); elementsEnumerator = elements.GetEnumerator (); int afterNoOfElements = 0; int afterNoOfAttributes = 0; while (elementsEnumerator.MoveNext ()) { afterNoOfElements++; if (!elementsEnumerator.Current.HasAttributes) continue; else { IEnumerable<XAttribute> attributes = elementsEnumerator.Current.Attributes (); IEnumerator<XAttribute> attributesEnumerator = attributes.GetEnumerator (); while (attributesEnumerator.MoveNext ()) afterNoOfAttributes++; } } Assert.True(afterNoOfAttributes >= beforeNoOfAttributes, "XDocumentAddSchemaInfoValidate, wrong newAttributes value."); Assert.True(afterNoOfElements >= beforeNoOfElements, "XDocumentAddSchemaInfoValidate, wrong newElements value."); } /* * test xml validation without populating the XML tree with * the post-schema-validation infoset(PSVI). */ [Fact] public void XDocumentNoSchemaInfoValidate () { // no. of elements before validation IEnumerable<XElement> elements = xmlDocument.Elements (); IEnumerator<XElement> elementsEnumerator = elements.GetEnumerator (); int beforeNoOfElements = 0; int beforeNoOfAttributes = 0; while (elementsEnumerator.MoveNext ()) { beforeNoOfElements++; if (!elementsEnumerator.Current.HasAttributes) continue; else { IEnumerable<XAttribute> attributes = elementsEnumerator.Current.Attributes (); IEnumerator<XAttribute> attributesEnumerator = attributes.GetEnumerator (); while (attributesEnumerator.MoveNext ()) beforeNoOfAttributes++; } } // don't populate XML with PSVI validationSucceded = true; ExtensionsClass.Validate (xmlDocument, schemaSet, new ValidationEventHandler(TestValidationHandler), false); Assert.Equal(true, validationSucceded); // no. of elements after validation elements = xmlDocument.Elements (); elementsEnumerator = elements.GetEnumerator (); int afterNoOfElements = 0; int afterNoOfAttributes = 0; while (elementsEnumerator.MoveNext ()) { afterNoOfElements++; if (!elementsEnumerator.Current.HasAttributes) continue; else { IEnumerable<XAttribute> attributes = elementsEnumerator.Current.Attributes (); IEnumerator<XAttribute> attributesEnumerator = attributes.GetEnumerator (); while (attributesEnumerator.MoveNext ()) afterNoOfAttributes++; } } Assert.Equal(afterNoOfAttributes, beforeNoOfAttributes); Assert.Equal(afterNoOfElements, beforeNoOfElements); } // attribute validation succeeds after change [Fact] public void XAttributeSuccessValidate () { string elementName = "note"; string attributeName = "date"; object attributeValue = "2010-05-27"; // validate the entire document validationSucceded = true; ExtensionsClass.Validate (xmlDocument, schemaSet, new ValidationEventHandler(TestValidationHandler), true); Assert.Equal(true, validationSucceded); // change and re-validate attribute value XAttribute date = xmlDocument.Element(elementName).Attribute (attributeName); date.SetValue (attributeValue); ExtensionsClass.Validate (date, date.GetSchemaInfo ().SchemaAttribute,schemaSet, new ValidationEventHandler(TestValidationHandler)); Assert.Equal(true, validationSucceded); } // attribute validation fails after change [Fact] public void XAttributeFailValidate() { string elementName = "note"; string attributeName = "date"; object attributeValue = "2010-12-32"; // validate the entire document validationSucceded = true; ExtensionsClass.Validate(xmlDocument, schemaSet, new ValidationEventHandler(TestValidationHandler),true); Assert.Equal(true, validationSucceded); // change and re-validate attribute value XAttribute date = xmlDocument.Element(elementName).Attribute(attributeName); date.SetValue(attributeValue); ExtensionsClass.Validate(date, date.GetSchemaInfo ().SchemaAttribute, schemaSet, new ValidationEventHandler(TestValidationHandler)); Assert.Equal(false, validationSucceded); } /* * test if exception is thrown when xml document does not * conform to the xml schema after attribute value change */ [Fact] public void XAttributeThrowExceptionValidate() { string elementName = "note"; string attributeName = "date"; object attributeValue = "2010-12-32"; // validate the entire document validationSucceded = true; ExtensionsClass.Validate(xmlDocument, schemaSet, new ValidationEventHandler(TestValidationHandler),true); Assert.Equal(true, validationSucceded); // change and re-validate attribute value XAttribute date = xmlDocument.Element(elementName).Attribute(attributeName); date.SetValue(attributeValue); Assert.Throws<XmlSchemaValidationException>(() => ExtensionsClass.Validate(date, date.GetSchemaInfo().SchemaAttribute, schemaSet, null)); } // element validation succeeds after change [Fact] public void XElementSuccessValidate() { string parentElementName = "note"; string childElementName = "body"; object childElementValue = "Please call me!"; // validate the entire document validationSucceded = true; ExtensionsClass.Validate(xmlDocument, schemaSet, new ValidationEventHandler(TestValidationHandler), true); Assert.Equal(true, validationSucceded); // alter element XElement root = xmlDocument.Element(parentElementName); root.SetElementValue(childElementName, childElementValue); ExtensionsClass.Validate(root, root.GetSchemaInfo().SchemaElement, schemaSet, new ValidationEventHandler(TestValidationHandler)); Assert.Equal(true, validationSucceded); } // element validation fails after change [Fact] public void XElementFailValidate() { string parentElementName = "note"; string childElementName = "body"; object childElementValue = "Don't forget to call me! Please!"; // validate the entire document validationSucceded = true; ExtensionsClass.Validate(xmlDocument, schemaSet, new ValidationEventHandler(TestValidationHandler), true); Assert.Equal(true, validationSucceded); // alter element XElement root = xmlDocument.Element(parentElementName); root.SetElementValue(childElementName, childElementValue); ExtensionsClass.Validate(root, root.GetSchemaInfo().SchemaElement, schemaSet, new ValidationEventHandler(TestValidationHandler)); Assert.Equal(false, validationSucceded); } /* * test if exception is thrown when xml document does not * conform to the xml schema after element value change */ [Fact] public void XElementThrowExceptionValidate() { string parentElementName = "note" ; string childElementName = "body"; object childElementValue = "Don't forget to call me! Please!"; // validate the entire document validationSucceded = true; ExtensionsClass.Validate(xmlDocument, schemaSet, new ValidationEventHandler(TestValidationHandler), true); Assert.Equal(true, validationSucceded); // alter element XElement root = xmlDocument.Element(parentElementName); root.SetElementValue(childElementName, childElementValue); Assert.Throws<XmlSchemaValidationException>(() => ExtensionsClass.Validate(root, root.GetSchemaInfo().SchemaElement, schemaSet, null)); } // test attribute schema info [Fact] public void XAttributeGetSchemaInfo () { string elementName = "note"; string attributeName = "date"; // validate the entire document validationSucceded = true; ExtensionsClass.Validate(xmlDocument, schemaSet, new ValidationEventHandler(TestValidationHandler), true); Assert.Equal(true, validationSucceded); // validate attribute XAttribute date = xmlDocument.Element(elementName).Attribute(attributeName); ExtensionsClass.Validate (date, date.GetSchemaInfo().SchemaAttribute, schemaSet, new ValidationEventHandler(TestValidationHandler)); Assert.Equal(true, validationSucceded); IXmlSchemaInfo schemaInfo = ExtensionsClass.GetSchemaInfo(date); Assert.NotNull(schemaInfo); } // test element schema info [Fact] public void XElementGetSchemaInfo() { string elementName = "body"; // validate the entire document validationSucceded = true; ExtensionsClass.Validate(xmlDocument, schemaSet, new ValidationEventHandler(TestValidationHandler), true); Assert.Equal(true, validationSucceded); // validate element XElement body = xmlDocument.Root.Element(elementName); ExtensionsClass.Validate(body, body.GetSchemaInfo ().SchemaElement, schemaSet, new ValidationEventHandler(TestValidationHandler)); Assert.Equal(true, validationSucceded); IXmlSchemaInfo schemaInfo = ExtensionsClass.GetSchemaInfo(body); Assert.NotNull(schemaInfo); } } }
/* * AbstractEmitter.cs * SnowplowTracker.Emitters * * Copyright (c) 2015 Snowplow Analytics Ltd. All rights reserved. * * This program is licensed to you under the Apache License Version 2.0, * and you may not use this file except in compliance with the Apache License Version 2.0. * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the Apache License Version 2.0 is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. * * Authors: Joshua Beemster, Paul Boocock * Copyright: Copyright (c) 2015-2019 Snowplow Analytics Ltd * License: Apache License Version 2.0 */ using System; using System.Collections.Generic; using SnowplowTracker.Payloads; using SnowplowTracker.Enums; using SnowplowTracker.Storage; using SnowplowTracker.Collections; using SnowplowTracker.Requests; using System.Net.Http; using System.Text; namespace SnowplowTracker.Emitters { public abstract class AbstractEmitter : IEmitter { protected int POST_WRAPPER_BYTES = 88; // "schema":"iglu:com.snowplowanalytics.snowplow/payload_data/jsonschema/1-0-3","data":[] protected int POST_STM_BYTES = 22; // "stm":"1443452851000", protected int FAIL_INTERVAL = 10000; // If all events failed to send protected string endpoint; protected Uri collectorUri; protected HttpProtocol httpProtocol; protected Enums.HttpMethod httpMethod; protected int sendLimit; protected long byteLimitGet; protected long byteLimitPost; protected IStore eventStore; /// <summary> /// Adds an event payload to the database. /// </summary> /// <param name="payload">Payload.</param> public abstract void Add(TrackerPayload payload); /// <summary> /// Starts the Emitter and the Event Consumer. /// - EmitLoop will send all events in the database and then /// wait for the event consumer to signal that there is work. /// - The event consumer waits for its queue to be signalled and /// will then add an event to the database; after which it /// signals the emitloop of work to be done. /// </summary> public abstract void Start(); /// <summary> /// Stops the Emitter and the Event Consumer. /// </summary> public abstract void Stop(); /// <summary> /// Gets whether the emitter is currently sending. /// </summary> /// <returns><c>true</c>, if emitter is sending, <c>false</c> otherwise.</returns> public abstract bool IsSending(); // --- Event Senders /// <summary> /// From a range of event rows will construct a list of RequestResult objects /// </summary> /// <returns>The results of sending all requests</returns> /// <param name="eventRows">Event rows from the database</param> protected List<RequestResult> SendRequests(List<EventRow> eventRows) { ConcurrentQueue<RequestResult> resultQueue = new ConcurrentQueue<RequestResult>(); int count; if (httpMethod == Enums.HttpMethod.GET) { count = HttpGet(eventRows, resultQueue); } else { count = HttpPost(eventRows, resultQueue); } // Wait for the results of each request List<RequestResult> results = new List<RequestResult>(); while (count != 0) { results.Add(resultQueue.Dequeue()); count--; } return results; } /// <summary> /// Sends all events as GET requests on background threads /// </summary> /// <returns>The get.</returns> /// <param name="eventRows">Event rows.</param> protected int HttpGet(List<EventRow> eventRows, ConcurrentQueue<RequestResult> resultQueue) { int count = eventRows.Count; try { // Send each row as an individual GET Request foreach (EventRow eRow in eventRows) { TrackerPayload payload = eRow.GetPayload(); long byteSize = payload.GetByteSize() + POST_STM_BYTES; bool oversize = byteSize > byteLimitGet; Log.Debug("Emitter: Sending GET with byte-size: " + byteSize); new ReadyRequest( new HttpRequest(Enums.HttpMethod.GET, GetGETRequest(payload.GetDictionary())), new List<Guid> { eRow.GetRowId() }, oversize, resultQueue ).Send(); } } catch (Exception e) { Log.Debug("Emitter: caught exception in HTTPGet request: " + e.Message); Log.Debug("Emitter: HTTPGet exception trace: " + e.StackTrace); } return count; } /// <summary> /// Send all event rows as POST requests on background threads /// </summary> /// <returns>The results of all the requests</returns> /// <param name="eventRows">Event rows.</param> protected int HttpPost(List<EventRow> eventRows, ConcurrentQueue<RequestResult> resultQueue) { int count = 0; List<Guid> rowIds = new List<Guid>(); List<Dictionary<string, object>> payloadDicts = new List<Dictionary<string, object>>(); long totalByteSize = 0; try { for (int i = 0; i < eventRows.Count; i++) { TrackerPayload payload = eventRows[i].GetPayload(); long payloadByteSize = payload.GetByteSize() + POST_STM_BYTES; if ((payloadByteSize + POST_WRAPPER_BYTES) > byteLimitPost) { // A single Payload has exceeded the Byte Limit Log.Debug("Emitter: Single event exceeds byte limit: " + (payloadByteSize + POST_WRAPPER_BYTES) + " is > " + byteLimitPost); Log.Debug("Sending POST with byte-size: " + (payloadByteSize + POST_WRAPPER_BYTES)); List<Dictionary<string, object>> singlePayloadPost = new List<Dictionary<string, object>> { payload.GetDictionary() }; List<Guid> singlePayloadId = new List<Guid> { eventRows[i].GetRowId() }; new ReadyRequest(new HttpRequest(Enums.HttpMethod.POST, collectorUri, GetPOSTRequest(singlePayloadPost)), singlePayloadId, true, resultQueue).Send(); count++; } else if ((totalByteSize + payloadByteSize + POST_WRAPPER_BYTES + (payloadDicts.Count - 1)) > byteLimitPost) { Log.Debug("Emitter: Byte limit reached: " + (totalByteSize + payloadByteSize + POST_WRAPPER_BYTES + (payloadDicts.Count - 1)) + " is > " + byteLimitPost); Log.Debug("Emitter: Sending POST with byte-size: " + (totalByteSize + POST_WRAPPER_BYTES + (payloadDicts.Count - 1))); new ReadyRequest(new HttpRequest(Enums.HttpMethod.POST, collectorUri, GetPOSTRequest(payloadDicts)), rowIds, false, resultQueue).Send(); count++; // Reset collections payloadDicts = new List<Dictionary<string, object>> { payload.GetDictionary() }; rowIds = new List<Guid> { eventRows[i].GetRowId() }; totalByteSize = payloadByteSize; } else { payloadDicts.Add(payload.GetDictionary()); rowIds.Add(eventRows[i].GetRowId()); totalByteSize += payloadByteSize; } } if (payloadDicts.Count > 0) { Log.Debug("Emitter: Sending POST with byte-size: " + (totalByteSize + POST_WRAPPER_BYTES + (payloadDicts.Count - 1))); new ReadyRequest(new HttpRequest(Enums.HttpMethod.POST, collectorUri, GetPOSTRequest(payloadDicts)), rowIds, false, resultQueue).Send(); count++; } } catch (Exception e) { Log.Debug("Emitter: caught exception in HTTPPost request: " + e.Message); Log.Debug("Emitter: HTTPPost exception trace: " + e.StackTrace); } return count; } // --- Helpers /// <summary> /// Gets a ready request containing a POST /// </summary> /// <returns>The POST request that is already being sent</returns> /// <param name="events">Events to send in the post</param> protected HttpContent GetPOSTRequest(List<Dictionary<string, object>> events) { // Add STM to event AddSentTimeToEvents(events); // Build the event SelfDescribingJson sdj = new SelfDescribingJson(Constants.SCHEMA_PAYLOAD_DATA, events); // Build the HTTP Content Body HttpContent httpContent = new StringContent(sdj.ToString(), Encoding.UTF8, Constants.POST_CONTENT_TYPE); return httpContent; } /// <summary> /// Gets a ready request containing a GET /// </summary> /// <returns>The GET request that is already being sent</returns> /// <param name="eventDict">The event to be converted into a URI</param> protected Uri GetGETRequest(Dictionary<string, object> eventDict) { // Add STM to event eventDict.Add(Constants.SENT_TIMESTAMP, Utils.GetTimestamp().ToString()); // Build the event return new Uri(collectorUri + Utils.ToQueryString(eventDict)); } /// <summary> /// Gets the collector URI. /// </summary> /// <returns>The collector URI.</returns> /// <param name="endpoint">Endpoint.</param> /// <param name="protocol">Protocol.</param> /// <param name="method">Method.</param> protected Uri MakeCollectorUri(string endpoint, HttpProtocol protocol, Enums.HttpMethod method) { string path = (method == Enums.HttpMethod.GET) ? Constants.GET_URI_SUFFIX : Constants.POST_URI_SUFFIX; string requestProtocol = (protocol == HttpProtocol.HTTP) ? "http" : "https"; return new Uri($"{requestProtocol}://{endpoint}{path}"); } /// <summary> /// Adds the sent time to a list of event payloads /// </summary> /// <param name="events">The event list to add the stm to</param> protected void AddSentTimeToEvents(List<Dictionary<string, object>> events) { string stm = Utils.GetTimestamp().ToString(); foreach (Dictionary<string, object> eventDict in events) { eventDict.Add(Constants.SENT_TIMESTAMP, stm); } } // --- Setters /// <summary> /// Sets the collector URI. /// </summary> /// <param name="endpoint">Endpoint.</param> public void SetCollectorUri(string endpoint) { this.endpoint = endpoint; collectorUri = MakeCollectorUri(this.endpoint, this.httpProtocol, this.httpMethod); } /// <summary> /// Sets the http protocol. /// </summary> /// <param name="httpProtocol">Http protocol.</param> public void SetHttpProtocol(HttpProtocol httpProtocol) { this.httpProtocol = httpProtocol; collectorUri = MakeCollectorUri(this.endpoint, this.httpProtocol, this.httpMethod); } /// <summary> /// Sets the http method. /// </summary> /// <param name="httpMethod">Http method.</param> public void SetHttpMethod(Enums.HttpMethod httpMethod) { this.httpMethod = httpMethod; collectorUri = MakeCollectorUri(this.endpoint, this.httpProtocol, this.httpMethod); } /// <summary> /// Sets the send limit; this controls how many events are grabbed out of the database at anytime. /// </summary> /// <param name="sendLimit">Send limit.</param> public void SetSendLimit(int sendLimit) { this.sendLimit = sendLimit; } /// <summary> /// Sets the byte limit for get requests. /// </summary> /// <param name="byteLimitGet">Byte limit get.</param> public void SetByteLimitGet(long byteLimitGet) { this.byteLimitGet = byteLimitGet; } /// <summary> /// Sets the byte limit for post requests. /// </summary> /// <param name="byteLimitPost">Byte limit post.</param> public void SetByteLimitPost(long byteLimitPost) { this.byteLimitPost = byteLimitPost; } // --- Getters /// <summary> /// Gets the collector URI. /// </summary> /// <returns>The collector URI.</returns> public Uri GetCollectorUri() { return collectorUri; } /// <summary> /// Gets the http protocol. /// </summary> /// <returns>The http protocol.</returns> public HttpProtocol GetHttpProtocol() { return httpProtocol; } /// <summary> /// Gets the http method. /// </summary> /// <returns>The http method.</returns> public Enums.HttpMethod GetHttpMethod() { return httpMethod; } /// <summary> /// Gets the send limit. /// </summary> /// <returns>The send limit.</returns> public int GetSendLimit() { return sendLimit; } /// <summary> /// Gets the byte limit for get requests. /// </summary> /// <returns>The byte limit get.</returns> public long GetByteLimitGet() { return byteLimitGet; } /// <summary> /// Gets the byte limit for post requests. /// </summary> /// <returns>The byte limit post.</returns> public long GetByteLimitPost() { return byteLimitPost; } /// <summary> /// Gets the event store. /// </summary> /// <returns>The event store.</returns> public IStore GetEventStore() { return eventStore; } } }
/******************************************************************************* * Copyright 2008-2013 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file 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. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET * API Version: 2006-03-01 * */ using System; using System.Xml.Serialization; using System.Collections.Specialized; using Amazon.Util; namespace Amazon.S3.Model { /// <summary> /// The parameters to add or update an object in a bucket. /// </summary> public class PutObjectRequest : S3PutWithACLRequest { #region Private Members private string bucketName; private string key; private string filePath; private S3CannedACL cannedACL; private string md5Digest; private bool fGenerateMD5Digest; private string contentType; private string contentBody; internal NameValueCollection metaData; private S3StorageClass storageClass; private bool autoCloseStream = true; private ServerSideEncryptionMethod encryption; private string websiteRedirectLocation; #endregion #region Progress Event /// <summary> /// The event for Put Object progress notifications. All /// subscribers will be notified when a new progress /// event is raised. /// </summary> /// <remarks> /// Subscribe to this event if you want to receive /// put object progress notifications. Here is how:<br /> /// 1. Define a method with a signature similar to this one: /// <code> /// private void displayProgress(object sender, PutObjectProgressArgs args) /// { /// Console.WriteLine(args); /// } /// </code> /// 2. Add this method to the Put Object Progress Event delegate's invocation list /// <code> /// PutObjectRequest request = new PutObjectRequest(); /// request.PutObjectProgressEvent += displayProgress; /// </code> /// </remarks> public event EventHandler<PutObjectProgressArgs> PutObjectProgressEvent; /// <summary> /// The "handler" will be notified every time a put /// object progress event is raised. /// </summary> /// <param name="handler">A method that consumes the put object progress notification</param> /// <returns>this instance of the PutObjectRequest</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public PutObjectRequest WithSubscriber(EventHandler<PutObjectProgressArgs> handler) { this.PutObjectProgressEvent += handler; return this; } #endregion #region BucketName /// <summary> /// The name of the bucket to contain the object. /// </summary> [XmlElementAttribute(ElementName = "BucketName")] public string BucketName { get { return this.bucketName; } set { this.bucketName = value; } } /// <summary> /// Sets the name of the bucket to contain the object. /// </summary> /// <param name="bucketName">The bucket name</param> /// <returns>the request with the BucketName set</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public PutObjectRequest WithBucketName(string bucketName) { this.bucketName = bucketName; return this; } /// <summary> /// Checks if BucketName property is set. /// </summary> /// <returns>true if BucketName property is set.</returns> internal bool IsSetBucketName() { return !System.String.IsNullOrEmpty(this.bucketName); } #endregion #region Key /// <summary> /// The key of the object to be created (or updated). /// </summary> [XmlElementAttribute(ElementName = "Key")] public string Key { get { return this.key; } set { this.key = value; } } /// <summary> /// Sets key of the object to be created (or updated). /// </summary> /// <param name="key">The object key</param> /// <returns>the request with the Key set</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public PutObjectRequest WithKey(string key) { this.key = key; return this; } /// <summary> /// Checks if Key property is set. /// </summary> /// <returns>true if Key property is set.</returns> internal bool IsSetKey() { return !System.String.IsNullOrEmpty(this.key); } #endregion #region FilePath /// <summary> /// The full path and name to a file to be uploaded. /// If this is set the request will upload the specified file to S3. /// </summary> [XmlElementAttribute(ElementName = "FilePath")] public string FilePath { get { return this.filePath; } set { this.filePath = value; } } /// <summary> /// Sets the full path and name to a file to be uploaded. /// If this is set the request will upload the specified file to S3. /// </summary> /// <param name="filePath">Full path and name of a file</param> /// <returns>the request with the FilePath set</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public PutObjectRequest WithFilePath(string filePath) { this.filePath = filePath; return this; } /// <summary> /// Checks if FilePath property is set. /// </summary> /// <returns>true if FilePath property is set.</returns> internal bool IsSetFilePath() { return !System.String.IsNullOrEmpty(this.filePath); } #endregion #region CannedACL /// <summary> /// A canned access control list (CACL) to apply to the object. /// Please refer to <see cref="T:Amazon.S3.Model.S3CannedACL"/> for /// information on S3 Canned ACLs. /// </summary> public S3CannedACL CannedACL { get { return this.cannedACL; } set { this.cannedACL = value; } } /// <summary> /// A canned access control list (CACL) to apply to the object. /// Please refer to <see cref="T:Amazon.S3.Model.S3CannedACL"/> for /// information on S3 Canned ACLs. /// </summary> /// <param name="acl">The Canned ACL to be set on the object</param> /// <returns>The request with the CannedACL set</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public PutObjectRequest WithCannedACL(S3CannedACL acl) { this.cannedACL = acl; return this; } /// <summary> /// Checks if the CannedACL property is set. /// </summary> /// <returns>true if there is the CannedACL property is set.</returns> internal bool IsSetCannedACL() { return (cannedACL != S3CannedACL.NoACL); } /// <summary> /// Resets any previous CannedACL set in this object. /// </summary> public void RemoveCannedACL() { this.cannedACL = S3CannedACL.NoACL; } #endregion #region MD5Digest /// <summary> /// An MD5 digest for the content. /// </summary> /// <remarks> /// <para> /// The base64 encoded 128-bit MD5 digest of the message /// (without the headers) according to RFC 1864. This header /// can be used as a message integrity check to verify that /// the data is the same data that was originally sent. /// </para> /// <para> /// If supplied, after the file has been uploaded to S3, /// S3 checks to ensure that the MD5 hash of the uploaded file /// matches the hash supplied. /// </para> /// <para> /// Although it is optional, we recommend using the /// Content-MD5 mechanism as an end-to-end integrity check. /// </para> /// </remarks> [XmlElementAttribute(ElementName = "MD5Digest")] public string MD5Digest { get { return this.md5Digest; } set { this.md5Digest = value; } } /// <summary> /// Sets an MD5 digest for the content. /// </summary> /// <remarks> /// <para> /// The base64 encoded 128-bit MD5 digest of the message /// (without the headers) according to RFC 1864. This header /// can be used as a message integrity check to verify that /// the data is the same data that was originally sent. /// </para> /// <para> /// If supplied, after the file has been uploaded to S3, /// S3 checks to ensure that the MD5 hash of the uploaded file /// matches the hash supplied. /// </para> /// <para> /// Although it is optional, we recommend using the /// Content-MD5 mechanism as an end-to-end integrity check. /// </para> /// </remarks> /// <param name="digest">Computed MD5 digest value</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public PutObjectRequest WithMD5Digest(string digest) { this.md5Digest = digest; return this; } /// <summary> /// Checks if MD5Digest property is set. /// </summary> /// <returns>true if MD5Digest property is set.</returns> internal bool IsSetMD5Digest() { return !System.String.IsNullOrEmpty(this.md5Digest); } #endregion #region GenerateMD5Digest /// <summary> /// If set, an MD5 digest is automatically computed for the content being uploaded. /// </summary> /// <remarks> /// This is a computationally expensive operation, and will add to the total time it will take to upload /// data to S3. Please use this option judicially. /// </remarks> [XmlElementAttribute(ElementName = "GenerateMD5Digest")] public bool GenerateMD5Digest { get { return this.fGenerateMD5Digest; } set { this.fGenerateMD5Digest = value; } } /// <summary> /// If set, an MD5 digest is automatically computed for the content being uploaded. /// </summary> /// <param name="fGenerateMD5Digest">True to auto-generate a digest</param> /// <returns>this instance</returns> /// <remarks> /// This is a computationally expensive operation, and will add to the total time it will take to upload /// data to S3. Please use this option judicially. /// </remarks> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public PutObjectRequest WithGenerateChecksum(bool fGenerateMD5Digest) { this.fGenerateMD5Digest = fGenerateMD5Digest; return this; } #endregion #region ContentType /// <summary> /// A standard MIME type describing the format of the object data. /// </summary> /// <remarks> /// The content type for the content being uploaded. This property defaults to "binary/octet-stream". /// For more information, refer to: <see href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17"/> /// </remarks> [XmlElementAttribute(ElementName = "ContentType")] public string ContentType { get { return this.contentType; } set { this.contentType = value; } } /// <summary> /// Sets a standard MIME type describing the format of the object data. /// </summary> /// <remarks> /// The content type for the content being uploaded. This property defaults to "binary/octet-stream". /// For more information, refer to: <see href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17"/> /// </remarks> /// <param name="contentType">The content type</param> /// <returns>The request with the ContentType set</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public PutObjectRequest WithContentType(string contentType) { this.contentType = contentType; return this; } /// <summary> /// Checks if ContentType property is set. /// </summary> /// <returns>true if ContentType property is set.</returns> internal bool IsSetContentType() { return !System.String.IsNullOrEmpty(this.contentType); } #endregion #region ContentBody /// <summary> /// Text content to be uploaded. Use this property if you want to upload plaintext to S3. /// The content type will be set to 'text/plain'. /// </summary> [XmlElementAttribute(ElementName = "ContentBody")] public string ContentBody { get { return this.contentBody; } set { this.contentBody = value; if (value != null) { this.contentType = "text/plain"; } } } /// <summary> /// Text content to be uploaded. Use this property if you want to upload plaintext to S3. /// The content type will be set to 'text/plain'. /// </summary> /// <param name="contentBody">The content to upload</param> /// <returns>The request with the ContentBody set</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public PutObjectRequest WithContentBody(string contentBody) { this.contentBody = contentBody; this.contentType = "text/plain"; return this; } /// <summary> /// Checks if ContentBody property is set. /// </summary> /// <returns>true if ContentBody property is set.</returns> internal bool IsSetContentBody() { return this.contentBody != null; } #endregion #region Metadata /// <summary> /// Adds a key/value metadata pair to the object when uploaded. /// </summary> /// <param name="key">The key to associate with the object</param> /// <param name="value">The value for the key</param> /// <returns>The response with Metadata set.</returns> public PutObjectRequest WithMetaData(string key, string value) { if (key == null || value == null) { return this; } if (metaData == null) { metaData = new NameValueCollection(5); } metaData.Add(key, value); return this; } /// <summary> /// Adds a set of key-value metadata pairs to the object when uploaded. /// </summary> /// <param name="metaInfo">The set of key-value pairs that will eventually be /// associated with the S3 Object</param> /// <returns></returns> public PutObjectRequest WithMetaData(NameValueCollection metaInfo) { if (metaInfo == null || metaInfo.Count == 0) { return this; } if (metaData == null) { metaData = new NameValueCollection(metaInfo.Count); } metaData.Add(metaInfo); return this; } /// <summary> /// Checks if Metadata property is set. /// </summary> /// <returns>true if Metadata property is set.</returns> internal bool IsSetMetaData() { return (metaData != null && metaData.Count > 0); } /// <summary> /// Removes a key from the Metadata list if it was /// added previously to this object. /// </summary> /// <param name="key">The key to remove</param> public void RemoveMetaData(string key) { if (metaData == null || metaData.Count == 0) { return; } metaData.Remove(key); } #endregion #region Timeout /// <summary> /// Sets a custom Timeout property (in milliseconds). /// </summary> /// <remarks> /// <para> /// The value of this property is assigned to the /// Timeout property of the HTTPWebRequest object used /// for S3 PUT Object requests. /// </para> /// <para> /// Please set the timeout only if you are certain that /// the file will not be transferred within the default intervals /// for an HttpWebRequest. /// </para> /// <para> /// A value less than or equal to 0 will be silently ignored /// </para> /// </remarks> /// <param name="timeout">Timeout value</param> /// <returns>this instance</returns> /// <seealso cref="P:System.Net.HttpWebRequest.ReadWriteTimeout"/> /// <seealso cref="P:System.Net.HttpWebRequest.Timeout"/> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] new public PutObjectRequest WithTimeout(int timeout) { Timeout = timeout; return this; } #endregion #region ReadWriteTimeout /// <summary> /// Sets a custom ReadWriteTimeout property (in milliseconds). /// </summary> /// <remarks> /// <para> /// The value of this property is assigned to the /// ReadWriteTimeout property of the HTTPWebRequest object /// used for S3 PUT Object requests. /// </para> /// <para> /// A value less than or equal to 0 will be silently ignored /// </para> /// </remarks> /// <param name="readWriteTimeout">ReadWriteTimeout value</param> /// <returns>this instance</returns> /// <seealso cref="P:System.Net.HttpWebRequest.ReadWriteTimeout"/> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] new public PutObjectRequest WithReadWriteTimeout(int readWriteTimeout) { ReadWriteTimeout = readWriteTimeout; return this; } #endregion #region StorageClass /// <summary> /// StorageClass value to apply to the S3 object. /// Default: S3StorageClass.Standard. /// </summary> /// <remarks> /// Set this property only if you want reduced redundancy for this object. /// Please refer to <see cref="T:Amazon.S3.Model.S3StorageClass"/> for /// information on S3 Storage Classes. /// </remarks> public S3StorageClass StorageClass { get { return this.storageClass; } set { this.storageClass = value; } } /// <summary> /// Sets a StorageClass for the S3 object. /// Default: S3StorageClass.Standard. /// </summary> /// <remarks> /// Set this property only if you want reduced redundancy for this object. /// Please refer to <see cref="T:Amazon.S3.Model.S3StorageClass"/> for /// information on S3 Storage Classes. /// </remarks> /// <param name="sClass">The Storage Class to be set on the object</param> /// <returns>The request with the StorageClass set</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public PutObjectRequest WithStorageClass(S3StorageClass sClass) { this.storageClass = sClass; return this; } #endregion #region Grants /// <summary> /// Adds custom access control lists (ACLs) to the object. /// Please refer to <see cref="T:Amazon.S3.Model.S3Grant"/> for information on /// S3 Grants. /// </summary> /// <param name="grants">One or more S3 Grants.</param> /// <returns>The request with the Grants set.</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public PutObjectRequest WithGrants(params S3Grant[] grants) { this.Grants.AddRange(grants); return this; } #endregion #region ServerSideEncryption /// <summary> /// Specifies the encryption used on the server to store the content. /// </summary> public ServerSideEncryptionMethod ServerSideEncryptionMethod { get { return this.encryption; } set { this.encryption = value; } } /// <summary> /// Specifies the encryption used on the server to store the content. /// </summary> /// <param name="encryption">Encryption method to use</param> /// <returns>The response with the ServerSideEncryptionMethod set.</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public PutObjectRequest WithServerSideEncryptionMethod(ServerSideEncryptionMethod encryption) { this.ServerSideEncryptionMethod = encryption; return this; } #endregion #region Website Redirect Location /// <summary> /// If this is set then when a GET request is made from the S3 website endpoint a 301 HTTP status code /// will be returned indicating a redirect with this value as the redirect location. /// </summary> public string WebsiteRedirectLocation { get { return this.websiteRedirectLocation; } set { this.websiteRedirectLocation = value; } } /// <summary> /// If this is set then when a GET request is made from the S3 website endpoint a 301 HTTP status code /// will be returned indicating a redirect with this value as the redirect location. /// </summary> /// <param name="websiteRedirectLocation">The redirect location to be returned on a GET request to this object</param> /// <returns>the request with the WebsiteRedirectLocation set</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public PutObjectRequest WithWebsiteRedirectLocation(string websiteRedirectLocation) { this.websiteRedirectLocation = websiteRedirectLocation; return this; } /// <summary> /// Checks if WebsiteRedirectLocation property is set. /// </summary> /// <returns>true if WebsiteRedirectLocation property is set.</returns> internal bool IsSetWebsiteRedirectLocation() { return !System.String.IsNullOrEmpty(this.websiteRedirectLocation); } #endregion /// <summary> /// This method is called by a producer of put object progress /// notifications. When called, all the subscribers in the /// invocation list will be called sequentially. /// </summary> /// <param name="incrementTransferred">The number of bytes transferred since last event</param> /// <param name="transferred">The number of bytes transferred</param> /// <param name="total">The total number of bytes to be transferred</param> internal override void OnRaiseProgressEvent(long incrementTransferred, long transferred, long total) { AWSSDKUtils.InvokeInBackground(PutObjectProgressEvent, new PutObjectProgressArgs(incrementTransferred, transferred, total), this); } #region AutoCloseStream /// <summary> /// If this value is set to true then the stream used with this request will be closed when all the content /// is read from the stream. /// Default: true. /// </summary> public bool AutoCloseStream { get { return this.autoCloseStream; } set { this.autoCloseStream = value; } } /// <summary> /// If this value is set to true then the stream used with this request will be closed when all the content /// is read from the stream. /// Default: true. /// </summary> /// <param name="autoCloseStream">the value the AutoCloseStream to be set to</param> /// <returns>The request with the AutoCloseStream set</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public PutObjectRequest WithAutoCloseStream(bool autoCloseStream) { this.autoCloseStream = autoCloseStream; return this; } #endregion internal override bool Expect100Continue { get { return true; } } } /// <summary> /// Encapsulates the information needed to provide /// transfer progress to subscribers of the Put Object /// Event. /// </summary> public class PutObjectProgressArgs : TransferProgressArgs { /// <summary> /// The constructor takes the number of /// currently transferred bytes and the /// total number of bytes to be transferred /// </summary> /// <param name="incrementTransferred">The number of bytes transferred since last event</param> /// <param name="transferred">The number of bytes transferred</param> /// <param name="total">The total number of bytes to be transferred</param> public PutObjectProgressArgs(long incrementTransferred, long transferred, long total) : base(incrementTransferred, transferred, total) { } } }
//------------------------------------------------------------------------------ // <copyright file="HttpResponseBase.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web { using System; using System.Collections; using System.Collections.Specialized; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Web.Caching; using System.Web.Routing; [TypeForwardedFrom("System.Web.Abstractions, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=31bf3856ad364e35")] public abstract class HttpResponseBase { public virtual bool Buffer { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public virtual bool BufferOutput { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public virtual HttpCachePolicyBase Cache { get { throw new NotImplementedException(); } } public virtual string CacheControl { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Matches HttpResponse class")] public virtual String Charset { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public virtual CancellationToken ClientDisconnectedToken { get { throw new NotImplementedException(); } } public virtual Encoding ContentEncoding { set { throw new NotImplementedException(); } get { throw new NotImplementedException(); } } public virtual string ContentType { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public virtual HttpCookieCollection Cookies { get { throw new NotImplementedException(); } } public virtual int Expires { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public virtual DateTime ExpiresAbsolute { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public virtual Stream Filter { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public virtual NameValueCollection Headers { get { throw new NotImplementedException(); } } public virtual bool HeadersWritten { get { throw new NotImplementedException(); } } public virtual Encoding HeaderEncoding { set { throw new NotImplementedException(); } get { throw new NotImplementedException(); } } public virtual bool IsClientConnected { get { throw new NotImplementedException(); } } public virtual bool IsRequestBeingRedirected { get { throw new NotImplementedException(); } } public virtual TextWriter Output { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public virtual Stream OutputStream { get { throw new NotImplementedException(); } } public virtual String RedirectLocation { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public virtual string Status { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public virtual int StatusCode { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public virtual String StatusDescription { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public virtual int SubStatusCode { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public virtual bool SupportsAsyncFlush { get { throw new NotImplementedException(); } } public virtual bool SuppressContent { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public virtual bool SuppressDefaultCacheControlHeader { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public virtual bool SuppressFormsAuthenticationRedirect { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public virtual bool TrySkipIisCustomErrors { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public virtual void AddCacheItemDependency(string cacheKey) { throw new NotImplementedException(); } public virtual void AddCacheItemDependencies(ArrayList cacheKeys) { throw new NotImplementedException(); } public virtual void AddCacheItemDependencies(string[] cacheKeys) { throw new NotImplementedException(); } public virtual void AddCacheDependency(params CacheDependency[] dependencies) { throw new NotImplementedException(); } [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Matches HttpResponse class")] public virtual void AddFileDependency(String filename) { throw new NotImplementedException(); } [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Matches HttpResponse class")] public virtual void AddFileDependencies(ArrayList filenames) { throw new NotImplementedException(); } [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Matches HttpResponse class")] public virtual void AddFileDependencies(string[] filenames) { throw new NotImplementedException(); } public virtual void AddHeader(String name, String value) { throw new NotImplementedException(); } [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate", Justification = @"The normal event pattern doesn't work between HttpResponse and HttpResponseBase since the signatures differ.")] public virtual ISubscriptionToken AddOnSendingHeaders(Action<HttpContextBase> callback) { throw new NotImplementedException(); } public virtual void AppendCookie(HttpCookie cookie) { throw new NotImplementedException(); } public virtual void AppendHeader(String name, String value) { throw new NotImplementedException(); } [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Matches HttpResponse class")] public virtual void AppendToLog(String param) { throw new NotImplementedException(); } public virtual string ApplyAppPathModifier(string virtualPath) { throw new NotImplementedException(); } public virtual IAsyncResult BeginFlush(AsyncCallback callback, Object state) { throw new NotImplementedException(); } public virtual void BinaryWrite(byte[] buffer) { throw new NotImplementedException(); } public virtual void Clear() { throw new NotImplementedException(); } public virtual void ClearContent() { throw new NotImplementedException(); } public virtual void ClearHeaders() { throw new NotImplementedException(); } public virtual void Close() { throw new NotImplementedException(); } public virtual void DisableKernelCache() { throw new NotImplementedException(); } public virtual void DisableUserCache() { throw new NotImplementedException(); } [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "End", Justification = "Matches HttpResponse class")] public virtual void End() { throw new NotImplementedException(); } public virtual void EndFlush(IAsyncResult asyncResult) { throw new NotImplementedException(); } public virtual void Flush() { throw new NotImplementedException(); } [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Matches HttpResponse class")] public virtual void Pics(String value) { throw new NotImplementedException(); } [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", Justification = "Matches HttpResponse class")] public virtual void Redirect(String url) { throw new NotImplementedException(); } [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", Justification = "Matches HttpResponse class")] public virtual void Redirect(String url, bool endResponse) { throw new NotImplementedException(); } public virtual void RedirectToRoute(object routeValues) { throw new NotImplementedException(); } public virtual void RedirectToRoute(string routeName) { throw new NotImplementedException(); } public virtual void RedirectToRoute(RouteValueDictionary routeValues) { throw new NotImplementedException(); } public virtual void RedirectToRoute(string routeName, object routeValues) { throw new NotImplementedException(); } public virtual void RedirectToRoute(string routeName, RouteValueDictionary routeValues) { throw new NotImplementedException(); } public virtual void RedirectToRoutePermanent(object routeValues) { throw new NotImplementedException(); } public virtual void RedirectToRoutePermanent(string routeName) { throw new NotImplementedException(); } public virtual void RedirectToRoutePermanent(RouteValueDictionary routeValues) { throw new NotImplementedException(); } public virtual void RedirectToRoutePermanent(string routeName, object routeValues) { throw new NotImplementedException(); } public virtual void RedirectToRoutePermanent(string routeName, RouteValueDictionary routeValues) { throw new NotImplementedException(); } [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", Justification = "Matches HttpResponse class")] public virtual void RedirectPermanent(String url) { throw new NotImplementedException(); } [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", Justification = "Matches HttpResponse class")] public virtual void RedirectPermanent(String url, bool endResponse) { throw new NotImplementedException(); } public virtual void RemoveOutputCacheItem(string path) { throw new NotImplementedException(); } public virtual void RemoveOutputCacheItem(string path, string providerName) { throw new NotImplementedException(); } public virtual void SetCookie(HttpCookie cookie) { throw new NotImplementedException(); } [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Matches HttpResponse class")] public virtual void TransmitFile(string filename) { throw new NotImplementedException(); } [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Matches HttpResponse class")] public virtual void TransmitFile(string filename, long offset, long length) { throw new NotImplementedException(); } [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Matches HttpResponse class")] public virtual void Write(char ch) { throw new NotImplementedException(); } public virtual void Write(char[] buffer, int index, int count) { throw new NotImplementedException(); } [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "obj", Justification = "Matches HttpResponse class")] public virtual void Write(Object obj) { throw new NotImplementedException(); } [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Matches HttpResponse class")] public virtual void Write(string s) { throw new NotImplementedException(); } [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Matches HttpResponse class")] public virtual void WriteFile(String filename) { throw new NotImplementedException(); } [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Matches HttpResponse class")] public virtual void WriteFile(String filename, bool readIntoMemory) { throw new NotImplementedException(); } [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Matches HttpResponse class")] public virtual void WriteFile(String filename, long offset, long size) { throw new NotImplementedException(); } [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Matches HttpResponse class")] public virtual void WriteFile(IntPtr fileHandle, long offset, long size) { throw new NotImplementedException(); } public virtual void WriteSubstitution(HttpResponseSubstitutionCallback callback) { throw new NotImplementedException(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using BTDB.Buffer; using BTDB.FieldHandler; using BTDB.IL; using BTDB.KVDBLayer; using BTDB.StreamLayer; namespace BTDB.ODBLayer { public class ODBDictionary<TKey, TValue> : IOrderedDictionary<TKey, TValue>, IQuerySizeDictionary<TKey> { readonly IInternalObjectDBTransaction _tr; readonly IFieldHandler _keyHandler; readonly IFieldHandler _valueHandler; readonly Func<AbstractBufferedReader, IReaderCtx, TKey> _keyReader; readonly Action<TKey, AbstractBufferedWriter, IWriterCtx> _keyWriter; readonly Func<AbstractBufferedReader, IReaderCtx, TValue> _valueReader; readonly Action<TValue, AbstractBufferedWriter, IWriterCtx> _valueWriter; readonly IKeyValueDBTransaction _keyValueTr; readonly KeyValueDBTransactionProtector _keyValueTrProtector; readonly ulong _id; readonly byte[] _prefix; int _count; int _modificationCounter; KeysCollection? _keysCollection; ValuesCollection? _valuesCollection; public ODBDictionary(IInternalObjectDBTransaction tr, ODBDictionaryConfiguration config, ulong id) { _tr = tr; _keyHandler = config.KeyHandler; _valueHandler = config.ValueHandler; _id = id; var o = ObjectDB.AllDictionariesPrefix.Length; _prefix = new byte[o + PackUnpack.LengthVUInt(_id)]; Array.Copy(ObjectDB.AllDictionariesPrefix, _prefix, o); PackUnpack.PackVUInt(_prefix, ref o, _id); _keyReader = ((Func<AbstractBufferedReader, IReaderCtx, TKey>) config.KeyReader)!; _keyWriter = ((Action<TKey, AbstractBufferedWriter, IWriterCtx>) config.KeyWriter)!; _valueReader = ((Func<AbstractBufferedReader, IReaderCtx, TValue>) config.ValueReader)!; _valueWriter = ((Action<TValue, AbstractBufferedWriter, IWriterCtx>) config.ValueWriter)!; _keyValueTr = _tr.KeyValueDBTransaction; _keyValueTrProtector = _tr.TransactionProtector; _count = -1; } // ReSharper disable once UnusedMember.Global public ODBDictionary(IInternalObjectDBTransaction tr, ODBDictionaryConfiguration config) : this(tr, config, tr.AllocateDictionaryId()) { } static void ThrowModifiedDuringEnum() { throw new InvalidOperationException("DB modified during iteration"); } public static void DoSave(IWriterCtx ctx, IDictionary<TKey, TValue>? dictionary, int cfgId) { var writerCtx = (IDBWriterCtx) ctx; if (!(dictionary is ODBDictionary<TKey, TValue> goodDict)) { var tr = writerCtx.GetTransaction(); var id = tr.AllocateDictionaryId(); goodDict = new ODBDictionary<TKey, TValue>(tr, ODBDictionaryConfiguration.Get(cfgId), id); if (dictionary != null) foreach (var pair in dictionary) goodDict.Add(pair.Key, pair.Value); } ctx.Writer().WriteVUInt64(goodDict._id); } public static void DoFreeContent(IReaderCtx ctx, ulong id, int cfgId) { var readerCtx = (DBReaderCtx) ctx; var tr = readerCtx.GetTransaction(); var dict = new ODBDictionary<TKey, TValue>(tr, ODBDictionaryConfiguration.Get(cfgId), id); dict.FreeContent(ctx, cfgId); } void FreeContent(IReaderCtx readerCtx, int cfgId) { var config = ODBDictionaryConfiguration.Get(cfgId); var ctx = (DBReaderWithFreeInfoCtx) readerCtx; if (config.FreeContent == null) { var method = ILBuilder.Instance .NewMethod<Action<IInternalObjectDBTransaction, AbstractBufferedReader, IList<ulong>>>( $"IDictFinder_Cfg_{cfgId}"); var ilGenerator = method.Generator; var readerLoc = ilGenerator.DeclareLocal(typeof(IReaderCtx)); ilGenerator .Ldarg(0) .Ldarg(1) .Ldarg(2) // ReSharper disable once ObjectCreationAsStatement .Newobj(() => new DBReaderWithFreeInfoCtx(null, null, null)) .Stloc(readerLoc); Action<IILGen> readerOrCtx; if (_valueHandler.NeedsCtx()) readerOrCtx = il => il.Ldloc(readerLoc); else readerOrCtx = il => il.Ldarg(1); _valueHandler.FreeContent(ilGenerator, readerOrCtx); ilGenerator.Ret(); config.FreeContent = method.Create(); } var findIDictAction = (Action<IInternalObjectDBTransaction, AbstractBufferedReader, IList<ulong>>) config.FreeContent; long prevProtectionCounter = 0; long pos = 0; while (true) { _keyValueTrProtector.Start(); if (pos == 0) { _keyValueTr.SetKeyPrefix(_prefix); if (!_keyValueTr.FindFirstKey()) break; } else { if (_keyValueTrProtector.WasInterupted(prevProtectionCounter)) { _keyValueTr.SetKeyPrefix(_prefix); if (!_keyValueTr.SetKeyIndex(pos)) break; } else { if (!_keyValueTr.FindNextKey()) break; } } prevProtectionCounter = _keyValueTrProtector.ProtectionCounter; var valueBytes = _keyValueTr.GetValueAsByteArray(); var valueReader = new ByteArrayReader(valueBytes); findIDictAction(ctx.GetTransaction(), valueReader, ctx.DictIds); pos++; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Add(KeyValuePair<TKey, TValue> item) { Add(item.Key, item.Value); } public void Clear() { _keyValueTrProtector.Start(); _modificationCounter++; _keyValueTr.SetKeyPrefix(_prefix); _keyValueTr.EraseAll(); _count = 0; } public bool Contains(KeyValuePair<TKey, TValue> item) { if (!TryGetValue(item.Key, out var value)) return false; return EqualityComparer<TValue>.Default.Equals(value, item.Value); } public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { if (array == null) throw new ArgumentNullException(nameof(array)); if ((arrayIndex < 0) || (arrayIndex > array.Length)) { throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, "Needs to be nonnegative "); } if ((array.Length - arrayIndex) < Count) { throw new ArgumentException("Array too small"); } foreach (var item in this) { array[arrayIndex++] = item; } } public bool Remove(KeyValuePair<TKey, TValue> item) { if (Contains(item)) { Remove(item.Key); return true; } return false; } public int Count { get { if (_count == -1) { _keyValueTrProtector.Start(); _keyValueTr.SetKeyPrefix(_prefix); _count = (int) Math.Min(_keyValueTr.GetKeyValueCount(), int.MaxValue); } return _count; } } public bool IsReadOnly => false; ByteBuffer KeyToByteArray(TKey key) { var writer = new ByteBufferWriter(); IWriterCtx ctx = null; if (_keyHandler.NeedsCtx()) ctx = new DBWriterCtx(_tr, writer); _keyWriter(key, writer, ctx); return writer.Data; } ByteBuffer ValueToByteArray(TValue value) { var writer = new ByteBufferWriter(); IWriterCtx ctx = null; if (_valueHandler.NeedsCtx()) ctx = new DBWriterCtx(_tr, writer); _valueWriter(value, writer, ctx); return writer.Data; } TKey ByteArrayToKey(ByteBuffer data) { var reader = new ByteBufferReader(data); IReaderCtx ctx = null; if (_keyHandler.NeedsCtx()) ctx = new DBReaderCtx(_tr, reader); return _keyReader(reader, ctx); } TValue ByteArrayToValue(ByteBuffer data) { var reader = new ByteBufferReader(data); IReaderCtx ctx = null; if (_valueHandler.NeedsCtx()) ctx = new DBReaderCtx(_tr, reader); return _valueReader(reader, ctx); } public bool ContainsKey(TKey key) { var keyBytes = KeyToByteArray(key); _keyValueTrProtector.Start(); _keyValueTr.SetKeyPrefix(_prefix); return _keyValueTr.Find(keyBytes) == FindResult.Exact; } public void Add(TKey key, TValue value) { var keyBytes = KeyToByteArray(key); var valueBytes = ValueToByteArray(value); _keyValueTrProtector.Start(); _modificationCounter++; _keyValueTr.SetKeyPrefix(_prefix); if (_keyValueTr.Find(keyBytes) == FindResult.Exact) { throw new ArgumentException("Cannot Add duplicate key to Dictionary"); } _keyValueTr.CreateOrUpdateKeyValue(keyBytes, valueBytes); NotifyAdded(); } public bool Remove(TKey key) { var keyBytes = KeyToByteArray(key); _keyValueTrProtector.Start(); _modificationCounter++; _keyValueTr.SetKeyPrefix(_prefix); var found = _keyValueTr.Find(keyBytes) == FindResult.Exact; if (found) { _keyValueTr.EraseCurrent(); NotifyRemoved(); } return found; } public bool TryGetValue(TKey key, out TValue value) { var keyBytes = KeyToByteArray(key); _keyValueTrProtector.Start(); _keyValueTr.SetKeyPrefix(_prefix); var found = _keyValueTr.Find(keyBytes) == FindResult.Exact; if (!found) { value = default; return false; } var valueBytes = _keyValueTr.GetValue(); value = ByteArrayToValue(valueBytes); return true; } public TValue this[TKey key] { get { var keyBytes = KeyToByteArray(key); _keyValueTrProtector.Start(); _keyValueTr.SetKeyPrefix(_prefix); var found = _keyValueTr.Find(keyBytes) == FindResult.Exact; if (!found) { throw new ArgumentException("Key not found in Dictionary"); } var valueBytes = _keyValueTr.GetValue(); return ByteArrayToValue(valueBytes); } set { var keyBytes = KeyToByteArray(key); var valueBytes = ValueToByteArray(value); _keyValueTrProtector.Start(); _keyValueTr.SetKeyPrefix(_prefix); if (_keyValueTr.CreateOrUpdateKeyValue(keyBytes, valueBytes)) { _modificationCounter++; NotifyAdded(); } } } void NotifyAdded() { if (_count != -1) { if (_count != int.MaxValue) _count++; } } void NotifyRemoved() { if (_count != -1) { if (_count == int.MaxValue) { _count = (int) Math.Min(_keyValueTr.GetKeyValueCount(), int.MaxValue); } else { _count--; } } } class KeysCollection : ICollection<TKey> { readonly ODBDictionary<TKey, TValue> _parent; public KeysCollection(ODBDictionary<TKey, TValue> parent) { _parent = parent; } public IEnumerator<TKey> GetEnumerator() { long prevProtectionCounter = 0; var prevModificationCounter = 0; long pos = 0; while (true) { _parent._keyValueTrProtector.Start(); if (pos == 0) { prevModificationCounter = _parent._modificationCounter; _parent._keyValueTr.SetKeyPrefix(_parent._prefix); if (!_parent._keyValueTr.FindFirstKey()) break; } else { if (_parent._keyValueTrProtector.WasInterupted(prevProtectionCounter)) { if (prevModificationCounter != _parent._modificationCounter) ThrowModifiedDuringEnum(); _parent._keyValueTr.SetKeyPrefix(_parent._prefix); if (!_parent._keyValueTr.SetKeyIndex(pos)) break; } else { if (!_parent._keyValueTr.FindNextKey()) break; } } prevProtectionCounter = _parent._keyValueTrProtector.ProtectionCounter; var keyBytes = _parent._keyValueTr.GetKey(); var key = _parent.ByteArrayToKey(keyBytes); yield return key; pos++; } } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); public void Add(TKey item) { _parent.Add(item!, default); } public void Clear() { _parent.Clear(); } public bool Contains(TKey item) => _parent.ContainsKey(item!); public void CopyTo(TKey[] array, int arrayIndex) { if (array == null) throw new ArgumentNullException(nameof(array)); if ((arrayIndex < 0) || (arrayIndex > array.Length)) { throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, "Needs to be nonnegative "); } if ((array.Length - arrayIndex) < Count) { throw new ArgumentException("Array too small"); } foreach (var item in this) { array[arrayIndex++] = item; } } public bool Remove(TKey item) => _parent.Remove(item!); public int Count => _parent.Count; public bool IsReadOnly => false; } public ICollection<TKey> Keys => _keysCollection ??= new KeysCollection(this); class ValuesCollection : ICollection<TValue> { readonly ODBDictionary<TKey, TValue> _parent; public ValuesCollection(ODBDictionary<TKey, TValue> parent) { _parent = parent; } public IEnumerator<TValue> GetEnumerator() { long prevProtectionCounter = 0; var prevModificationCounter = 0; long pos = 0; while (true) { _parent._keyValueTrProtector.Start(); if (pos == 0) { prevModificationCounter = _parent._modificationCounter; _parent._keyValueTr.SetKeyPrefix(_parent._prefix); if (!_parent._keyValueTr.FindFirstKey()) break; } else { if (_parent._keyValueTrProtector.WasInterupted(prevProtectionCounter)) { if (prevModificationCounter != _parent._modificationCounter) ThrowModifiedDuringEnum(); _parent._keyValueTr.SetKeyPrefix(_parent._prefix); if (!_parent._keyValueTr.SetKeyIndex(pos)) break; } else { if (!_parent._keyValueTr.FindNextKey()) break; } } prevProtectionCounter = _parent._keyValueTrProtector.ProtectionCounter; var valueBytes = _parent._keyValueTr.GetValue(); var value = _parent.ByteArrayToValue(valueBytes); yield return value; pos++; } } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); public void Add(TValue item) { throw new NotSupportedException(); } public void Clear() { _parent.Clear(); } public bool Contains(TValue item) { return this.Any(i => EqualityComparer<TValue>.Default.Equals(i, item)); } public void CopyTo(TValue[] array, int arrayIndex) { if (array == null) throw new ArgumentNullException(nameof(array)); if ((arrayIndex < 0) || (arrayIndex > array.Length)) { throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, "Needs to be nonnegative "); } if ((array.Length - arrayIndex) < Count) { throw new ArgumentException("Array too small"); } foreach (var item in this) { array[arrayIndex++] = item; } } public bool Remove(TValue item) { throw new NotSupportedException(); } public int Count => _parent.Count; public bool IsReadOnly => true; } public ICollection<TValue> Values => _valuesCollection ??= new ValuesCollection(this); public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { long prevProtectionCounter = 0; var prevModificationCounter = 0; long pos = 0; while (true) { _keyValueTrProtector.Start(); if (pos == 0) { prevModificationCounter = _modificationCounter; _keyValueTr.SetKeyPrefix(_prefix); if (!_keyValueTr.FindFirstKey()) break; } else { if (_keyValueTrProtector.WasInterupted(prevProtectionCounter)) { if (prevModificationCounter != _modificationCounter) ThrowModifiedDuringEnum(); _keyValueTr.SetKeyPrefix(_prefix); if (!_keyValueTr.SetKeyIndex(pos)) break; } else { if (!_keyValueTr.FindNextKey()) break; } } prevProtectionCounter = _keyValueTrProtector.ProtectionCounter; var keyBytes = _keyValueTr.GetKey(); var valueBytes = _keyValueTr.GetValue(); var key = ByteArrayToKey(keyBytes); var value = ByteArrayToValue(valueBytes); yield return new KeyValuePair<TKey, TValue>(key, value); pos++; } } public IEnumerable<KeyValuePair<TKey, TValue>> GetReverseEnumerator() { long prevProtectionCounter = 0; var prevModificationCounter = 0; var pos = long.MaxValue; while (true) { _keyValueTrProtector.Start(); if (pos == long.MaxValue) { prevModificationCounter = _modificationCounter; _keyValueTr.SetKeyPrefix(_prefix); if (!_keyValueTr.FindLastKey()) break; pos = _keyValueTr.GetKeyIndex(); } else { if (_keyValueTrProtector.WasInterupted(prevProtectionCounter)) { if (prevModificationCounter != _modificationCounter) ThrowModifiedDuringEnum(); _keyValueTr.SetKeyPrefix(_prefix); if (!_keyValueTr.SetKeyIndex(pos)) break; } else { if (!_keyValueTr.FindPreviousKey()) break; } } prevProtectionCounter = _keyValueTrProtector.ProtectionCounter; var keyBytes = _keyValueTr.GetKey(); var valueBytes = _keyValueTr.GetValue(); var key = ByteArrayToKey(keyBytes); var value = ByteArrayToValue(valueBytes); yield return new KeyValuePair<TKey, TValue>(key, value); pos--; } } public IEnumerable<KeyValuePair<TKey, TValue>> GetIncreasingEnumerator(TKey start) { var startKeyBytes = KeyToByteArray(start); long prevProtectionCounter = 0; var prevModificationCounter = 0; long pos = 0; while (true) { _keyValueTrProtector.Start(); if (pos == 0) { prevModificationCounter = _modificationCounter; _keyValueTr.SetKeyPrefix(_prefix); bool startOk; switch (_keyValueTr.Find(startKeyBytes)) { case FindResult.Exact: case FindResult.Next: startOk = true; break; case FindResult.Previous: startOk = _keyValueTr.FindNextKey(); break; case FindResult.NotFound: startOk = false; break; default: throw new ArgumentOutOfRangeException(); } if (!startOk) break; pos = _keyValueTr.GetKeyIndex(); } else { if (_keyValueTrProtector.WasInterupted(prevProtectionCounter)) { if (prevModificationCounter != _modificationCounter) ThrowModifiedDuringEnum(); _keyValueTr.SetKeyPrefix(_prefix); if (!_keyValueTr.SetKeyIndex(pos)) break; } else { if (!_keyValueTr.FindNextKey()) break; } } prevProtectionCounter = _keyValueTrProtector.ProtectionCounter; var keyBytes = _keyValueTr.GetKey(); var valueBytes = _keyValueTr.GetValue(); var key = ByteArrayToKey(keyBytes); var value = ByteArrayToValue(valueBytes); yield return new KeyValuePair<TKey, TValue>(key, value); pos++; } } public IEnumerable<KeyValuePair<TKey, TValue>> GetDecreasingEnumerator(TKey start) { var startKeyBytes = KeyToByteArray(start); long prevProtectionCounter = 0; var prevModificationCounter = 0; var pos = long.MaxValue; while (true) { _keyValueTrProtector.Start(); if (pos == long.MaxValue) { prevModificationCounter = _modificationCounter; _keyValueTr.SetKeyPrefix(_prefix); bool startOk; switch (_keyValueTr.Find(startKeyBytes)) { case FindResult.Exact: case FindResult.Previous: startOk = true; break; case FindResult.Next: startOk = _keyValueTr.FindPreviousKey(); break; case FindResult.NotFound: startOk = false; break; default: throw new ArgumentOutOfRangeException(); } if (!startOk) break; pos = _keyValueTr.GetKeyIndex(); } else { if (_keyValueTrProtector.WasInterupted(prevProtectionCounter)) { if (prevModificationCounter != _modificationCounter) ThrowModifiedDuringEnum(); _keyValueTr.SetKeyPrefix(_prefix); if (!_keyValueTr.SetKeyIndex(pos)) break; } else { if (!_keyValueTr.FindPreviousKey()) break; } } prevProtectionCounter = _keyValueTrProtector.ProtectionCounter; var keyBytes = _keyValueTr.GetKey(); var valueBytes = _keyValueTr.GetValue(); var key = ByteArrayToKey(keyBytes); var value = ByteArrayToValue(valueBytes); yield return new KeyValuePair<TKey, TValue>(key, value); pos--; } } public long RemoveRange(TKey start, bool includeStart, TKey end, bool includeEnd) { var startKeyBytes = KeyToByteArray(start); var endKeyBytes = KeyToByteArray(end); _keyValueTrProtector.Start(); _modificationCounter++; _keyValueTr.SetKeyPrefix(_prefix); var result = _keyValueTr.Find(startKeyBytes); if (result == FindResult.NotFound) return 0; var startIndex = _keyValueTr.GetKeyIndex(); if (result == FindResult.Exact) { if (!includeStart) startIndex++; } else if (result == FindResult.Previous) { startIndex++; } result = _keyValueTr.Find(endKeyBytes); var endIndex = _keyValueTr.GetKeyIndex(); if (result == FindResult.Exact) { if (!includeEnd) endIndex--; } else if (result == FindResult.Next) { endIndex--; } _keyValueTr.EraseRange(startIndex, endIndex); _count = -1; return Math.Max(0, endIndex - startIndex + 1); } public IEnumerable<KeyValuePair<uint, uint>> QuerySizeEnumerator() { long prevProtectionCounter = 0; var prevModificationCounter = 0; long pos = 0; while (true) { _keyValueTrProtector.Start(); if (pos == 0) { prevModificationCounter = _modificationCounter; _keyValueTr.SetKeyPrefix(_prefix); if (!_keyValueTr.FindFirstKey()) break; } else { if (_keyValueTrProtector.WasInterupted(prevProtectionCounter)) { if (prevModificationCounter != _modificationCounter) ThrowModifiedDuringEnum(); _keyValueTr.SetKeyPrefix(_prefix); if (!_keyValueTr.SetKeyIndex(pos)) break; } else { if (!_keyValueTr.FindNextKey()) break; } } prevProtectionCounter = _keyValueTrProtector.ProtectionCounter; var size = _keyValueTr.GetStorageSizeOfCurrentKey(); yield return size; pos++; } } public KeyValuePair<uint, uint> QuerySizeByKey(TKey key) { var keyBytes = KeyToByteArray(key); _keyValueTrProtector.Start(); _keyValueTr.SetKeyPrefix(_prefix); var found = _keyValueTr.Find(keyBytes) == FindResult.Exact; if (!found) { throw new ArgumentException("Key not found in Dictionary"); } var size = _keyValueTr.GetStorageSizeOfCurrentKey(); return size; } #pragma warning disable 693 // generic parameters named same class AdvancedEnumerator<TKey, TValue> : IOrderedDictionaryEnumerator<TKey, TValue> #pragma warning restore 693 { readonly ODBDictionary<TKey, TValue> _owner; readonly KeyValueDBTransactionProtector _keyValueTrProtector; readonly IKeyValueDBTransaction _keyValueTr; long _prevProtectionCounter; readonly int _prevModificationCounter; readonly uint _startPos; readonly uint _count; uint _pos; SeekState _seekState; readonly bool _ascending; public AdvancedEnumerator(ODBDictionary<TKey, TValue> owner, AdvancedEnumeratorParam<TKey> param) { _owner = owner; _keyValueTrProtector = _owner._keyValueTrProtector; _keyValueTr = _owner._keyValueTr; _ascending = param.Order == EnumerationOrder.Ascending; _keyValueTrProtector.Start(); _prevModificationCounter = _owner._modificationCounter; _prevProtectionCounter = _keyValueTrProtector.ProtectionCounter; _keyValueTr.SetKeyPrefix(_owner._prefix); long startIndex; long endIndex; if (param.EndProposition == KeyProposition.Ignored) { endIndex = _keyValueTr.GetKeyValueCount() - 1; } else { var keyBytes = _owner.KeyToByteArray(param.End); switch (_keyValueTr.Find(keyBytes)) { case FindResult.Exact: endIndex = _keyValueTr.GetKeyIndex(); if (param.EndProposition == KeyProposition.Excluded) { endIndex--; } break; case FindResult.Previous: endIndex = _keyValueTr.GetKeyIndex(); break; case FindResult.Next: endIndex = _keyValueTr.GetKeyIndex() - 1; break; case FindResult.NotFound: endIndex = -1; break; default: throw new ArgumentOutOfRangeException(); } } if (param.StartProposition == KeyProposition.Ignored) { startIndex = 0; } else { var keyBytes = _owner.KeyToByteArray(param.Start); switch (_keyValueTr.Find(keyBytes)) { case FindResult.Exact: startIndex = _keyValueTr.GetKeyIndex(); if (param.StartProposition == KeyProposition.Excluded) { startIndex++; } break; case FindResult.Previous: startIndex = _keyValueTr.GetKeyIndex() + 1; break; case FindResult.Next: startIndex = _keyValueTr.GetKeyIndex(); break; case FindResult.NotFound: startIndex = 0; break; default: throw new ArgumentOutOfRangeException(); } } _count = (uint) Math.Max(0, endIndex - startIndex + 1); _startPos = (uint) (_ascending ? startIndex : endIndex); _pos = 0; _seekState = SeekState.Undefined; } public uint Count => _count; public TValue CurrentValue { get { if (_pos >= _count) throw new IndexOutOfRangeException(); if (_seekState == SeekState.Undefined) throw new BTDBException("Invalid access to uninitialized CurrentValue."); _keyValueTrProtector.Start(); if (_keyValueTrProtector.WasInterupted(_prevProtectionCounter)) { if (_prevModificationCounter != _owner._modificationCounter) ThrowModifiedDuringEnum(); _keyValueTr.SetKeyPrefix(_owner._prefix); Seek(); } else if (_seekState != SeekState.Ready) { Seek(); } _prevProtectionCounter = _keyValueTrProtector.ProtectionCounter; var valueBytes = _keyValueTr.GetValue(); return _owner.ByteArrayToValue(valueBytes); } set { if (_pos >= _count) throw new IndexOutOfRangeException(); if (_seekState == SeekState.Undefined) throw new BTDBException("Invalid access to uninitialized CurrentValue."); _keyValueTrProtector.Start(); if (_keyValueTrProtector.WasInterupted(_prevProtectionCounter)) { if (_prevModificationCounter != _owner._modificationCounter) ThrowModifiedDuringEnum(); _keyValueTr.SetKeyPrefix(_owner._prefix); Seek(); } else if (_seekState != SeekState.Ready) { Seek(); } _prevProtectionCounter = _keyValueTrProtector.ProtectionCounter; var valueBytes = _owner.ValueToByteArray(value); _keyValueTr.SetValue(valueBytes); } } void Seek() { if (_ascending) _keyValueTr.SetKeyIndex(_startPos + _pos); else _keyValueTr.SetKeyIndex(_startPos - _pos); _seekState = SeekState.Ready; } public uint Position { get => _pos; set { _pos = value > _count ? _count : value; _seekState = SeekState.SeekNeeded; } } public bool NextKey(out TKey key) { if (_seekState == SeekState.Ready) _pos++; if (_pos >= _count) { key = default; return false; } _keyValueTrProtector.Start(); if (_keyValueTrProtector.WasInterupted(_prevProtectionCounter)) { if (_prevModificationCounter != _owner._modificationCounter) ThrowModifiedDuringEnum(); _keyValueTr.SetKeyPrefix(_owner._prefix); Seek(); } else if (_seekState != SeekState.Ready) { Seek(); } else { if (_ascending) { _keyValueTr.FindNextKey(); } else { _keyValueTr.FindPreviousKey(); } } _prevProtectionCounter = _keyValueTrProtector.ProtectionCounter; key = _owner.ByteArrayToKey(_keyValueTr.GetKey()); return true; } } public IOrderedDictionaryEnumerator<TKey, TValue> GetAdvancedEnumerator(AdvancedEnumeratorParam<TKey> param) { return new AdvancedEnumerator<TKey, TValue>(this, param); } } }
// Copyright 2018 Google LLC // // 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 // // https://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. // Generated code. DO NOT EDIT! namespace Google.Cloud.BigQuery.DataTransfer.V1.Tests { using Google.Api.Gax; using Google.Api.Gax.Grpc; using Google.Api.Gax.ResourceNames; using apis = Google.Cloud.BigQuery.DataTransfer.V1; using Google.Protobuf.WellKnownTypes; using Grpc.Core; using Moq; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading; using System.Threading.Tasks; using Xunit; /// <summary>Generated unit tests</summary> public class GeneratedDataTransferServiceClientTest { [Fact] public void GetDataSource() { Mock<DataTransferService.DataTransferServiceClient> mockGrpcClient = new Mock<DataTransferService.DataTransferServiceClient>(MockBehavior.Strict); GetDataSourceRequest expectedRequest = new GetDataSourceRequest { DataSourceNameOneof = DataSourceNameOneof.From(new ProjectDataSourceName("[PROJECT]", "[DATA_SOURCE]")), }; DataSource expectedResponse = new DataSource { DataSourceNameOneof = DataSourceNameOneof.From(new ProjectDataSourceName("[PROJECT]", "[DATA_SOURCE]")), DataSourceId = "dataSourceId-1015796374", DisplayName = "displayName1615086568", Description = "description-1724546052", ClientId = "clientId-1904089585", SupportsMultipleTransfers = true, UpdateDeadlineSeconds = 991471694, DefaultSchedule = "defaultSchedule-800168235", SupportsCustomSchedule = true, HelpUrl = "helpUrl-789431439", DefaultDataRefreshWindowDays = 1804935157, ManualRunsDisabled = true, }; mockGrpcClient.Setup(x => x.GetDataSource(expectedRequest, It.IsAny<CallOptions>())) .Returns(expectedResponse); DataTransferServiceClient client = new DataTransferServiceClientImpl(mockGrpcClient.Object, null); DataSourceNameOneof name = DataSourceNameOneof.From(new ProjectDataSourceName("[PROJECT]", "[DATA_SOURCE]")); DataSource response = client.GetDataSource(name); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task GetDataSourceAsync() { Mock<DataTransferService.DataTransferServiceClient> mockGrpcClient = new Mock<DataTransferService.DataTransferServiceClient>(MockBehavior.Strict); GetDataSourceRequest expectedRequest = new GetDataSourceRequest { DataSourceNameOneof = DataSourceNameOneof.From(new ProjectDataSourceName("[PROJECT]", "[DATA_SOURCE]")), }; DataSource expectedResponse = new DataSource { DataSourceNameOneof = DataSourceNameOneof.From(new ProjectDataSourceName("[PROJECT]", "[DATA_SOURCE]")), DataSourceId = "dataSourceId-1015796374", DisplayName = "displayName1615086568", Description = "description-1724546052", ClientId = "clientId-1904089585", SupportsMultipleTransfers = true, UpdateDeadlineSeconds = 991471694, DefaultSchedule = "defaultSchedule-800168235", SupportsCustomSchedule = true, HelpUrl = "helpUrl-789431439", DefaultDataRefreshWindowDays = 1804935157, ManualRunsDisabled = true, }; mockGrpcClient.Setup(x => x.GetDataSourceAsync(expectedRequest, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<DataSource>(Task.FromResult(expectedResponse), null, null, null, null)); DataTransferServiceClient client = new DataTransferServiceClientImpl(mockGrpcClient.Object, null); DataSourceNameOneof name = DataSourceNameOneof.From(new ProjectDataSourceName("[PROJECT]", "[DATA_SOURCE]")); DataSource response = await client.GetDataSourceAsync(name); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public void GetDataSource2() { Mock<DataTransferService.DataTransferServiceClient> mockGrpcClient = new Mock<DataTransferService.DataTransferServiceClient>(MockBehavior.Strict); GetDataSourceRequest request = new GetDataSourceRequest { DataSourceNameOneof = DataSourceNameOneof.From(new ProjectDataSourceName("[PROJECT]", "[DATA_SOURCE]")), }; DataSource expectedResponse = new DataSource { DataSourceNameOneof = DataSourceNameOneof.From(new ProjectDataSourceName("[PROJECT]", "[DATA_SOURCE]")), DataSourceId = "dataSourceId-1015796374", DisplayName = "displayName1615086568", Description = "description-1724546052", ClientId = "clientId-1904089585", SupportsMultipleTransfers = true, UpdateDeadlineSeconds = 991471694, DefaultSchedule = "defaultSchedule-800168235", SupportsCustomSchedule = true, HelpUrl = "helpUrl-789431439", DefaultDataRefreshWindowDays = 1804935157, ManualRunsDisabled = true, }; mockGrpcClient.Setup(x => x.GetDataSource(request, It.IsAny<CallOptions>())) .Returns(expectedResponse); DataTransferServiceClient client = new DataTransferServiceClientImpl(mockGrpcClient.Object, null); DataSource response = client.GetDataSource(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task GetDataSourceAsync2() { Mock<DataTransferService.DataTransferServiceClient> mockGrpcClient = new Mock<DataTransferService.DataTransferServiceClient>(MockBehavior.Strict); GetDataSourceRequest request = new GetDataSourceRequest { DataSourceNameOneof = DataSourceNameOneof.From(new ProjectDataSourceName("[PROJECT]", "[DATA_SOURCE]")), }; DataSource expectedResponse = new DataSource { DataSourceNameOneof = DataSourceNameOneof.From(new ProjectDataSourceName("[PROJECT]", "[DATA_SOURCE]")), DataSourceId = "dataSourceId-1015796374", DisplayName = "displayName1615086568", Description = "description-1724546052", ClientId = "clientId-1904089585", SupportsMultipleTransfers = true, UpdateDeadlineSeconds = 991471694, DefaultSchedule = "defaultSchedule-800168235", SupportsCustomSchedule = true, HelpUrl = "helpUrl-789431439", DefaultDataRefreshWindowDays = 1804935157, ManualRunsDisabled = true, }; mockGrpcClient.Setup(x => x.GetDataSourceAsync(request, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<DataSource>(Task.FromResult(expectedResponse), null, null, null, null)); DataTransferServiceClient client = new DataTransferServiceClientImpl(mockGrpcClient.Object, null); DataSource response = await client.GetDataSourceAsync(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public void CreateTransferConfig() { Mock<DataTransferService.DataTransferServiceClient> mockGrpcClient = new Mock<DataTransferService.DataTransferServiceClient>(MockBehavior.Strict); CreateTransferConfigRequest expectedRequest = new CreateTransferConfigRequest { ParentAsParentNameOneof = ParentNameOneof.From(new ProjectName("[PROJECT]")), TransferConfig = new TransferConfig(), }; TransferConfig expectedResponse = new TransferConfig { TransferConfigNameOneof = TransferConfigNameOneof.From(new ProjectTransferConfigName("[PROJECT]", "[TRANSFER_CONFIG]")), DestinationDatasetId = "destinationDatasetId1541564179", DisplayName = "displayName1615086568", DataSourceId = "dataSourceId-1015796374", Schedule = "schedule-697920873", DataRefreshWindowDays = 327632845, Disabled = true, UserId = 147132913L, DatasetRegion = "datasetRegion959248539", }; mockGrpcClient.Setup(x => x.CreateTransferConfig(expectedRequest, It.IsAny<CallOptions>())) .Returns(expectedResponse); DataTransferServiceClient client = new DataTransferServiceClientImpl(mockGrpcClient.Object, null); ParentNameOneof parent = ParentNameOneof.From(new ProjectName("[PROJECT]")); TransferConfig transferConfig = new TransferConfig(); TransferConfig response = client.CreateTransferConfig(parent, transferConfig); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task CreateTransferConfigAsync() { Mock<DataTransferService.DataTransferServiceClient> mockGrpcClient = new Mock<DataTransferService.DataTransferServiceClient>(MockBehavior.Strict); CreateTransferConfigRequest expectedRequest = new CreateTransferConfigRequest { ParentAsParentNameOneof = ParentNameOneof.From(new ProjectName("[PROJECT]")), TransferConfig = new TransferConfig(), }; TransferConfig expectedResponse = new TransferConfig { TransferConfigNameOneof = TransferConfigNameOneof.From(new ProjectTransferConfigName("[PROJECT]", "[TRANSFER_CONFIG]")), DestinationDatasetId = "destinationDatasetId1541564179", DisplayName = "displayName1615086568", DataSourceId = "dataSourceId-1015796374", Schedule = "schedule-697920873", DataRefreshWindowDays = 327632845, Disabled = true, UserId = 147132913L, DatasetRegion = "datasetRegion959248539", }; mockGrpcClient.Setup(x => x.CreateTransferConfigAsync(expectedRequest, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<TransferConfig>(Task.FromResult(expectedResponse), null, null, null, null)); DataTransferServiceClient client = new DataTransferServiceClientImpl(mockGrpcClient.Object, null); ParentNameOneof parent = ParentNameOneof.From(new ProjectName("[PROJECT]")); TransferConfig transferConfig = new TransferConfig(); TransferConfig response = await client.CreateTransferConfigAsync(parent, transferConfig); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public void CreateTransferConfig2() { Mock<DataTransferService.DataTransferServiceClient> mockGrpcClient = new Mock<DataTransferService.DataTransferServiceClient>(MockBehavior.Strict); CreateTransferConfigRequest request = new CreateTransferConfigRequest { ParentAsParentNameOneof = ParentNameOneof.From(new ProjectName("[PROJECT]")), TransferConfig = new TransferConfig(), }; TransferConfig expectedResponse = new TransferConfig { TransferConfigNameOneof = TransferConfigNameOneof.From(new ProjectTransferConfigName("[PROJECT]", "[TRANSFER_CONFIG]")), DestinationDatasetId = "destinationDatasetId1541564179", DisplayName = "displayName1615086568", DataSourceId = "dataSourceId-1015796374", Schedule = "schedule-697920873", DataRefreshWindowDays = 327632845, Disabled = true, UserId = 147132913L, DatasetRegion = "datasetRegion959248539", }; mockGrpcClient.Setup(x => x.CreateTransferConfig(request, It.IsAny<CallOptions>())) .Returns(expectedResponse); DataTransferServiceClient client = new DataTransferServiceClientImpl(mockGrpcClient.Object, null); TransferConfig response = client.CreateTransferConfig(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task CreateTransferConfigAsync2() { Mock<DataTransferService.DataTransferServiceClient> mockGrpcClient = new Mock<DataTransferService.DataTransferServiceClient>(MockBehavior.Strict); CreateTransferConfigRequest request = new CreateTransferConfigRequest { ParentAsParentNameOneof = ParentNameOneof.From(new ProjectName("[PROJECT]")), TransferConfig = new TransferConfig(), }; TransferConfig expectedResponse = new TransferConfig { TransferConfigNameOneof = TransferConfigNameOneof.From(new ProjectTransferConfigName("[PROJECT]", "[TRANSFER_CONFIG]")), DestinationDatasetId = "destinationDatasetId1541564179", DisplayName = "displayName1615086568", DataSourceId = "dataSourceId-1015796374", Schedule = "schedule-697920873", DataRefreshWindowDays = 327632845, Disabled = true, UserId = 147132913L, DatasetRegion = "datasetRegion959248539", }; mockGrpcClient.Setup(x => x.CreateTransferConfigAsync(request, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<TransferConfig>(Task.FromResult(expectedResponse), null, null, null, null)); DataTransferServiceClient client = new DataTransferServiceClientImpl(mockGrpcClient.Object, null); TransferConfig response = await client.CreateTransferConfigAsync(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public void UpdateTransferConfig() { Mock<DataTransferService.DataTransferServiceClient> mockGrpcClient = new Mock<DataTransferService.DataTransferServiceClient>(MockBehavior.Strict); UpdateTransferConfigRequest expectedRequest = new UpdateTransferConfigRequest { TransferConfig = new TransferConfig(), UpdateMask = new FieldMask(), }; TransferConfig expectedResponse = new TransferConfig { TransferConfigNameOneof = TransferConfigNameOneof.From(new ProjectTransferConfigName("[PROJECT]", "[TRANSFER_CONFIG]")), DestinationDatasetId = "destinationDatasetId1541564179", DisplayName = "displayName1615086568", DataSourceId = "dataSourceId-1015796374", Schedule = "schedule-697920873", DataRefreshWindowDays = 327632845, Disabled = true, UserId = 147132913L, DatasetRegion = "datasetRegion959248539", }; mockGrpcClient.Setup(x => x.UpdateTransferConfig(expectedRequest, It.IsAny<CallOptions>())) .Returns(expectedResponse); DataTransferServiceClient client = new DataTransferServiceClientImpl(mockGrpcClient.Object, null); TransferConfig transferConfig = new TransferConfig(); FieldMask updateMask = new FieldMask(); TransferConfig response = client.UpdateTransferConfig(transferConfig, updateMask); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task UpdateTransferConfigAsync() { Mock<DataTransferService.DataTransferServiceClient> mockGrpcClient = new Mock<DataTransferService.DataTransferServiceClient>(MockBehavior.Strict); UpdateTransferConfigRequest expectedRequest = new UpdateTransferConfigRequest { TransferConfig = new TransferConfig(), UpdateMask = new FieldMask(), }; TransferConfig expectedResponse = new TransferConfig { TransferConfigNameOneof = TransferConfigNameOneof.From(new ProjectTransferConfigName("[PROJECT]", "[TRANSFER_CONFIG]")), DestinationDatasetId = "destinationDatasetId1541564179", DisplayName = "displayName1615086568", DataSourceId = "dataSourceId-1015796374", Schedule = "schedule-697920873", DataRefreshWindowDays = 327632845, Disabled = true, UserId = 147132913L, DatasetRegion = "datasetRegion959248539", }; mockGrpcClient.Setup(x => x.UpdateTransferConfigAsync(expectedRequest, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<TransferConfig>(Task.FromResult(expectedResponse), null, null, null, null)); DataTransferServiceClient client = new DataTransferServiceClientImpl(mockGrpcClient.Object, null); TransferConfig transferConfig = new TransferConfig(); FieldMask updateMask = new FieldMask(); TransferConfig response = await client.UpdateTransferConfigAsync(transferConfig, updateMask); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public void UpdateTransferConfig2() { Mock<DataTransferService.DataTransferServiceClient> mockGrpcClient = new Mock<DataTransferService.DataTransferServiceClient>(MockBehavior.Strict); UpdateTransferConfigRequest request = new UpdateTransferConfigRequest { TransferConfig = new TransferConfig(), UpdateMask = new FieldMask(), }; TransferConfig expectedResponse = new TransferConfig { TransferConfigNameOneof = TransferConfigNameOneof.From(new ProjectTransferConfigName("[PROJECT]", "[TRANSFER_CONFIG]")), DestinationDatasetId = "destinationDatasetId1541564179", DisplayName = "displayName1615086568", DataSourceId = "dataSourceId-1015796374", Schedule = "schedule-697920873", DataRefreshWindowDays = 327632845, Disabled = true, UserId = 147132913L, DatasetRegion = "datasetRegion959248539", }; mockGrpcClient.Setup(x => x.UpdateTransferConfig(request, It.IsAny<CallOptions>())) .Returns(expectedResponse); DataTransferServiceClient client = new DataTransferServiceClientImpl(mockGrpcClient.Object, null); TransferConfig response = client.UpdateTransferConfig(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task UpdateTransferConfigAsync2() { Mock<DataTransferService.DataTransferServiceClient> mockGrpcClient = new Mock<DataTransferService.DataTransferServiceClient>(MockBehavior.Strict); UpdateTransferConfigRequest request = new UpdateTransferConfigRequest { TransferConfig = new TransferConfig(), UpdateMask = new FieldMask(), }; TransferConfig expectedResponse = new TransferConfig { TransferConfigNameOneof = TransferConfigNameOneof.From(new ProjectTransferConfigName("[PROJECT]", "[TRANSFER_CONFIG]")), DestinationDatasetId = "destinationDatasetId1541564179", DisplayName = "displayName1615086568", DataSourceId = "dataSourceId-1015796374", Schedule = "schedule-697920873", DataRefreshWindowDays = 327632845, Disabled = true, UserId = 147132913L, DatasetRegion = "datasetRegion959248539", }; mockGrpcClient.Setup(x => x.UpdateTransferConfigAsync(request, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<TransferConfig>(Task.FromResult(expectedResponse), null, null, null, null)); DataTransferServiceClient client = new DataTransferServiceClientImpl(mockGrpcClient.Object, null); TransferConfig response = await client.UpdateTransferConfigAsync(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public void DeleteTransferConfig() { Mock<DataTransferService.DataTransferServiceClient> mockGrpcClient = new Mock<DataTransferService.DataTransferServiceClient>(MockBehavior.Strict); DeleteTransferConfigRequest expectedRequest = new DeleteTransferConfigRequest { TransferConfigNameOneof = TransferConfigNameOneof.From(new ProjectTransferConfigName("[PROJECT]", "[TRANSFER_CONFIG]")), }; Empty expectedResponse = new Empty(); mockGrpcClient.Setup(x => x.DeleteTransferConfig(expectedRequest, It.IsAny<CallOptions>())) .Returns(expectedResponse); DataTransferServiceClient client = new DataTransferServiceClientImpl(mockGrpcClient.Object, null); TransferConfigNameOneof name = TransferConfigNameOneof.From(new ProjectTransferConfigName("[PROJECT]", "[TRANSFER_CONFIG]")); client.DeleteTransferConfig(name); mockGrpcClient.VerifyAll(); } [Fact] public async Task DeleteTransferConfigAsync() { Mock<DataTransferService.DataTransferServiceClient> mockGrpcClient = new Mock<DataTransferService.DataTransferServiceClient>(MockBehavior.Strict); DeleteTransferConfigRequest expectedRequest = new DeleteTransferConfigRequest { TransferConfigNameOneof = TransferConfigNameOneof.From(new ProjectTransferConfigName("[PROJECT]", "[TRANSFER_CONFIG]")), }; Empty expectedResponse = new Empty(); mockGrpcClient.Setup(x => x.DeleteTransferConfigAsync(expectedRequest, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<Empty>(Task.FromResult(expectedResponse), null, null, null, null)); DataTransferServiceClient client = new DataTransferServiceClientImpl(mockGrpcClient.Object, null); TransferConfigNameOneof name = TransferConfigNameOneof.From(new ProjectTransferConfigName("[PROJECT]", "[TRANSFER_CONFIG]")); await client.DeleteTransferConfigAsync(name); mockGrpcClient.VerifyAll(); } [Fact] public void DeleteTransferConfig2() { Mock<DataTransferService.DataTransferServiceClient> mockGrpcClient = new Mock<DataTransferService.DataTransferServiceClient>(MockBehavior.Strict); DeleteTransferConfigRequest request = new DeleteTransferConfigRequest { TransferConfigNameOneof = TransferConfigNameOneof.From(new ProjectTransferConfigName("[PROJECT]", "[TRANSFER_CONFIG]")), }; Empty expectedResponse = new Empty(); mockGrpcClient.Setup(x => x.DeleteTransferConfig(request, It.IsAny<CallOptions>())) .Returns(expectedResponse); DataTransferServiceClient client = new DataTransferServiceClientImpl(mockGrpcClient.Object, null); client.DeleteTransferConfig(request); mockGrpcClient.VerifyAll(); } [Fact] public async Task DeleteTransferConfigAsync2() { Mock<DataTransferService.DataTransferServiceClient> mockGrpcClient = new Mock<DataTransferService.DataTransferServiceClient>(MockBehavior.Strict); DeleteTransferConfigRequest request = new DeleteTransferConfigRequest { TransferConfigNameOneof = TransferConfigNameOneof.From(new ProjectTransferConfigName("[PROJECT]", "[TRANSFER_CONFIG]")), }; Empty expectedResponse = new Empty(); mockGrpcClient.Setup(x => x.DeleteTransferConfigAsync(request, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<Empty>(Task.FromResult(expectedResponse), null, null, null, null)); DataTransferServiceClient client = new DataTransferServiceClientImpl(mockGrpcClient.Object, null); await client.DeleteTransferConfigAsync(request); mockGrpcClient.VerifyAll(); } [Fact] public void GetTransferConfig() { Mock<DataTransferService.DataTransferServiceClient> mockGrpcClient = new Mock<DataTransferService.DataTransferServiceClient>(MockBehavior.Strict); GetTransferConfigRequest expectedRequest = new GetTransferConfigRequest { TransferConfigNameOneof = TransferConfigNameOneof.From(new ProjectTransferConfigName("[PROJECT]", "[TRANSFER_CONFIG]")), }; TransferConfig expectedResponse = new TransferConfig { TransferConfigNameOneof = TransferConfigNameOneof.From(new ProjectTransferConfigName("[PROJECT]", "[TRANSFER_CONFIG]")), DestinationDatasetId = "destinationDatasetId1541564179", DisplayName = "displayName1615086568", DataSourceId = "dataSourceId-1015796374", Schedule = "schedule-697920873", DataRefreshWindowDays = 327632845, Disabled = true, UserId = 147132913L, DatasetRegion = "datasetRegion959248539", }; mockGrpcClient.Setup(x => x.GetTransferConfig(expectedRequest, It.IsAny<CallOptions>())) .Returns(expectedResponse); DataTransferServiceClient client = new DataTransferServiceClientImpl(mockGrpcClient.Object, null); TransferConfigNameOneof name = TransferConfigNameOneof.From(new ProjectTransferConfigName("[PROJECT]", "[TRANSFER_CONFIG]")); TransferConfig response = client.GetTransferConfig(name); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task GetTransferConfigAsync() { Mock<DataTransferService.DataTransferServiceClient> mockGrpcClient = new Mock<DataTransferService.DataTransferServiceClient>(MockBehavior.Strict); GetTransferConfigRequest expectedRequest = new GetTransferConfigRequest { TransferConfigNameOneof = TransferConfigNameOneof.From(new ProjectTransferConfigName("[PROJECT]", "[TRANSFER_CONFIG]")), }; TransferConfig expectedResponse = new TransferConfig { TransferConfigNameOneof = TransferConfigNameOneof.From(new ProjectTransferConfigName("[PROJECT]", "[TRANSFER_CONFIG]")), DestinationDatasetId = "destinationDatasetId1541564179", DisplayName = "displayName1615086568", DataSourceId = "dataSourceId-1015796374", Schedule = "schedule-697920873", DataRefreshWindowDays = 327632845, Disabled = true, UserId = 147132913L, DatasetRegion = "datasetRegion959248539", }; mockGrpcClient.Setup(x => x.GetTransferConfigAsync(expectedRequest, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<TransferConfig>(Task.FromResult(expectedResponse), null, null, null, null)); DataTransferServiceClient client = new DataTransferServiceClientImpl(mockGrpcClient.Object, null); TransferConfigNameOneof name = TransferConfigNameOneof.From(new ProjectTransferConfigName("[PROJECT]", "[TRANSFER_CONFIG]")); TransferConfig response = await client.GetTransferConfigAsync(name); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public void GetTransferConfig2() { Mock<DataTransferService.DataTransferServiceClient> mockGrpcClient = new Mock<DataTransferService.DataTransferServiceClient>(MockBehavior.Strict); GetTransferConfigRequest request = new GetTransferConfigRequest { TransferConfigNameOneof = TransferConfigNameOneof.From(new ProjectTransferConfigName("[PROJECT]", "[TRANSFER_CONFIG]")), }; TransferConfig expectedResponse = new TransferConfig { TransferConfigNameOneof = TransferConfigNameOneof.From(new ProjectTransferConfigName("[PROJECT]", "[TRANSFER_CONFIG]")), DestinationDatasetId = "destinationDatasetId1541564179", DisplayName = "displayName1615086568", DataSourceId = "dataSourceId-1015796374", Schedule = "schedule-697920873", DataRefreshWindowDays = 327632845, Disabled = true, UserId = 147132913L, DatasetRegion = "datasetRegion959248539", }; mockGrpcClient.Setup(x => x.GetTransferConfig(request, It.IsAny<CallOptions>())) .Returns(expectedResponse); DataTransferServiceClient client = new DataTransferServiceClientImpl(mockGrpcClient.Object, null); TransferConfig response = client.GetTransferConfig(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task GetTransferConfigAsync2() { Mock<DataTransferService.DataTransferServiceClient> mockGrpcClient = new Mock<DataTransferService.DataTransferServiceClient>(MockBehavior.Strict); GetTransferConfigRequest request = new GetTransferConfigRequest { TransferConfigNameOneof = TransferConfigNameOneof.From(new ProjectTransferConfigName("[PROJECT]", "[TRANSFER_CONFIG]")), }; TransferConfig expectedResponse = new TransferConfig { TransferConfigNameOneof = TransferConfigNameOneof.From(new ProjectTransferConfigName("[PROJECT]", "[TRANSFER_CONFIG]")), DestinationDatasetId = "destinationDatasetId1541564179", DisplayName = "displayName1615086568", DataSourceId = "dataSourceId-1015796374", Schedule = "schedule-697920873", DataRefreshWindowDays = 327632845, Disabled = true, UserId = 147132913L, DatasetRegion = "datasetRegion959248539", }; mockGrpcClient.Setup(x => x.GetTransferConfigAsync(request, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<TransferConfig>(Task.FromResult(expectedResponse), null, null, null, null)); DataTransferServiceClient client = new DataTransferServiceClientImpl(mockGrpcClient.Object, null); TransferConfig response = await client.GetTransferConfigAsync(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public void ScheduleTransferRuns() { Mock<DataTransferService.DataTransferServiceClient> mockGrpcClient = new Mock<DataTransferService.DataTransferServiceClient>(MockBehavior.Strict); ScheduleTransferRunsRequest expectedRequest = new ScheduleTransferRunsRequest { ParentAsTransferConfigNameOneof = TransferConfigNameOneof.From(new ProjectTransferConfigName("[PROJECT]", "[TRANSFER_CONFIG]")), StartTime = new Timestamp(), EndTime = new Timestamp(), }; ScheduleTransferRunsResponse expectedResponse = new ScheduleTransferRunsResponse(); mockGrpcClient.Setup(x => x.ScheduleTransferRuns(expectedRequest, It.IsAny<CallOptions>())) .Returns(expectedResponse); DataTransferServiceClient client = new DataTransferServiceClientImpl(mockGrpcClient.Object, null); TransferConfigNameOneof parent = TransferConfigNameOneof.From(new ProjectTransferConfigName("[PROJECT]", "[TRANSFER_CONFIG]")); Timestamp startTime = new Timestamp(); Timestamp endTime = new Timestamp(); ScheduleTransferRunsResponse response = client.ScheduleTransferRuns(parent, startTime, endTime); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task ScheduleTransferRunsAsync() { Mock<DataTransferService.DataTransferServiceClient> mockGrpcClient = new Mock<DataTransferService.DataTransferServiceClient>(MockBehavior.Strict); ScheduleTransferRunsRequest expectedRequest = new ScheduleTransferRunsRequest { ParentAsTransferConfigNameOneof = TransferConfigNameOneof.From(new ProjectTransferConfigName("[PROJECT]", "[TRANSFER_CONFIG]")), StartTime = new Timestamp(), EndTime = new Timestamp(), }; ScheduleTransferRunsResponse expectedResponse = new ScheduleTransferRunsResponse(); mockGrpcClient.Setup(x => x.ScheduleTransferRunsAsync(expectedRequest, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<ScheduleTransferRunsResponse>(Task.FromResult(expectedResponse), null, null, null, null)); DataTransferServiceClient client = new DataTransferServiceClientImpl(mockGrpcClient.Object, null); TransferConfigNameOneof parent = TransferConfigNameOneof.From(new ProjectTransferConfigName("[PROJECT]", "[TRANSFER_CONFIG]")); Timestamp startTime = new Timestamp(); Timestamp endTime = new Timestamp(); ScheduleTransferRunsResponse response = await client.ScheduleTransferRunsAsync(parent, startTime, endTime); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public void ScheduleTransferRuns2() { Mock<DataTransferService.DataTransferServiceClient> mockGrpcClient = new Mock<DataTransferService.DataTransferServiceClient>(MockBehavior.Strict); ScheduleTransferRunsRequest request = new ScheduleTransferRunsRequest { ParentAsTransferConfigNameOneof = TransferConfigNameOneof.From(new ProjectTransferConfigName("[PROJECT]", "[TRANSFER_CONFIG]")), StartTime = new Timestamp(), EndTime = new Timestamp(), }; ScheduleTransferRunsResponse expectedResponse = new ScheduleTransferRunsResponse(); mockGrpcClient.Setup(x => x.ScheduleTransferRuns(request, It.IsAny<CallOptions>())) .Returns(expectedResponse); DataTransferServiceClient client = new DataTransferServiceClientImpl(mockGrpcClient.Object, null); ScheduleTransferRunsResponse response = client.ScheduleTransferRuns(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task ScheduleTransferRunsAsync2() { Mock<DataTransferService.DataTransferServiceClient> mockGrpcClient = new Mock<DataTransferService.DataTransferServiceClient>(MockBehavior.Strict); ScheduleTransferRunsRequest request = new ScheduleTransferRunsRequest { ParentAsTransferConfigNameOneof = TransferConfigNameOneof.From(new ProjectTransferConfigName("[PROJECT]", "[TRANSFER_CONFIG]")), StartTime = new Timestamp(), EndTime = new Timestamp(), }; ScheduleTransferRunsResponse expectedResponse = new ScheduleTransferRunsResponse(); mockGrpcClient.Setup(x => x.ScheduleTransferRunsAsync(request, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<ScheduleTransferRunsResponse>(Task.FromResult(expectedResponse), null, null, null, null)); DataTransferServiceClient client = new DataTransferServiceClientImpl(mockGrpcClient.Object, null); ScheduleTransferRunsResponse response = await client.ScheduleTransferRunsAsync(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public void GetTransferRun() { Mock<DataTransferService.DataTransferServiceClient> mockGrpcClient = new Mock<DataTransferService.DataTransferServiceClient>(MockBehavior.Strict); GetTransferRunRequest expectedRequest = new GetTransferRunRequest { RunNameOneof = RunNameOneof.From(new ProjectRunName("[PROJECT]", "[TRANSFER_CONFIG]", "[RUN]")), }; TransferRun expectedResponse = new TransferRun { RunNameOneof = RunNameOneof.From(new ProjectRunName("[PROJECT]", "[TRANSFER_CONFIG]", "[RUN]")), DestinationDatasetId = "destinationDatasetId1541564179", DataSourceId = "dataSourceId-1015796374", UserId = 147132913L, Schedule = "schedule-697920873", }; mockGrpcClient.Setup(x => x.GetTransferRun(expectedRequest, It.IsAny<CallOptions>())) .Returns(expectedResponse); DataTransferServiceClient client = new DataTransferServiceClientImpl(mockGrpcClient.Object, null); RunNameOneof name = RunNameOneof.From(new ProjectRunName("[PROJECT]", "[TRANSFER_CONFIG]", "[RUN]")); TransferRun response = client.GetTransferRun(name); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task GetTransferRunAsync() { Mock<DataTransferService.DataTransferServiceClient> mockGrpcClient = new Mock<DataTransferService.DataTransferServiceClient>(MockBehavior.Strict); GetTransferRunRequest expectedRequest = new GetTransferRunRequest { RunNameOneof = RunNameOneof.From(new ProjectRunName("[PROJECT]", "[TRANSFER_CONFIG]", "[RUN]")), }; TransferRun expectedResponse = new TransferRun { RunNameOneof = RunNameOneof.From(new ProjectRunName("[PROJECT]", "[TRANSFER_CONFIG]", "[RUN]")), DestinationDatasetId = "destinationDatasetId1541564179", DataSourceId = "dataSourceId-1015796374", UserId = 147132913L, Schedule = "schedule-697920873", }; mockGrpcClient.Setup(x => x.GetTransferRunAsync(expectedRequest, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<TransferRun>(Task.FromResult(expectedResponse), null, null, null, null)); DataTransferServiceClient client = new DataTransferServiceClientImpl(mockGrpcClient.Object, null); RunNameOneof name = RunNameOneof.From(new ProjectRunName("[PROJECT]", "[TRANSFER_CONFIG]", "[RUN]")); TransferRun response = await client.GetTransferRunAsync(name); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public void GetTransferRun2() { Mock<DataTransferService.DataTransferServiceClient> mockGrpcClient = new Mock<DataTransferService.DataTransferServiceClient>(MockBehavior.Strict); GetTransferRunRequest request = new GetTransferRunRequest { RunNameOneof = RunNameOneof.From(new ProjectRunName("[PROJECT]", "[TRANSFER_CONFIG]", "[RUN]")), }; TransferRun expectedResponse = new TransferRun { RunNameOneof = RunNameOneof.From(new ProjectRunName("[PROJECT]", "[TRANSFER_CONFIG]", "[RUN]")), DestinationDatasetId = "destinationDatasetId1541564179", DataSourceId = "dataSourceId-1015796374", UserId = 147132913L, Schedule = "schedule-697920873", }; mockGrpcClient.Setup(x => x.GetTransferRun(request, It.IsAny<CallOptions>())) .Returns(expectedResponse); DataTransferServiceClient client = new DataTransferServiceClientImpl(mockGrpcClient.Object, null); TransferRun response = client.GetTransferRun(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task GetTransferRunAsync2() { Mock<DataTransferService.DataTransferServiceClient> mockGrpcClient = new Mock<DataTransferService.DataTransferServiceClient>(MockBehavior.Strict); GetTransferRunRequest request = new GetTransferRunRequest { RunNameOneof = RunNameOneof.From(new ProjectRunName("[PROJECT]", "[TRANSFER_CONFIG]", "[RUN]")), }; TransferRun expectedResponse = new TransferRun { RunNameOneof = RunNameOneof.From(new ProjectRunName("[PROJECT]", "[TRANSFER_CONFIG]", "[RUN]")), DestinationDatasetId = "destinationDatasetId1541564179", DataSourceId = "dataSourceId-1015796374", UserId = 147132913L, Schedule = "schedule-697920873", }; mockGrpcClient.Setup(x => x.GetTransferRunAsync(request, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<TransferRun>(Task.FromResult(expectedResponse), null, null, null, null)); DataTransferServiceClient client = new DataTransferServiceClientImpl(mockGrpcClient.Object, null); TransferRun response = await client.GetTransferRunAsync(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public void DeleteTransferRun() { Mock<DataTransferService.DataTransferServiceClient> mockGrpcClient = new Mock<DataTransferService.DataTransferServiceClient>(MockBehavior.Strict); DeleteTransferRunRequest expectedRequest = new DeleteTransferRunRequest { RunNameOneof = RunNameOneof.From(new ProjectRunName("[PROJECT]", "[TRANSFER_CONFIG]", "[RUN]")), }; Empty expectedResponse = new Empty(); mockGrpcClient.Setup(x => x.DeleteTransferRun(expectedRequest, It.IsAny<CallOptions>())) .Returns(expectedResponse); DataTransferServiceClient client = new DataTransferServiceClientImpl(mockGrpcClient.Object, null); RunNameOneof name = RunNameOneof.From(new ProjectRunName("[PROJECT]", "[TRANSFER_CONFIG]", "[RUN]")); client.DeleteTransferRun(name); mockGrpcClient.VerifyAll(); } [Fact] public async Task DeleteTransferRunAsync() { Mock<DataTransferService.DataTransferServiceClient> mockGrpcClient = new Mock<DataTransferService.DataTransferServiceClient>(MockBehavior.Strict); DeleteTransferRunRequest expectedRequest = new DeleteTransferRunRequest { RunNameOneof = RunNameOneof.From(new ProjectRunName("[PROJECT]", "[TRANSFER_CONFIG]", "[RUN]")), }; Empty expectedResponse = new Empty(); mockGrpcClient.Setup(x => x.DeleteTransferRunAsync(expectedRequest, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<Empty>(Task.FromResult(expectedResponse), null, null, null, null)); DataTransferServiceClient client = new DataTransferServiceClientImpl(mockGrpcClient.Object, null); RunNameOneof name = RunNameOneof.From(new ProjectRunName("[PROJECT]", "[TRANSFER_CONFIG]", "[RUN]")); await client.DeleteTransferRunAsync(name); mockGrpcClient.VerifyAll(); } [Fact] public void DeleteTransferRun2() { Mock<DataTransferService.DataTransferServiceClient> mockGrpcClient = new Mock<DataTransferService.DataTransferServiceClient>(MockBehavior.Strict); DeleteTransferRunRequest request = new DeleteTransferRunRequest { RunNameOneof = RunNameOneof.From(new ProjectRunName("[PROJECT]", "[TRANSFER_CONFIG]", "[RUN]")), }; Empty expectedResponse = new Empty(); mockGrpcClient.Setup(x => x.DeleteTransferRun(request, It.IsAny<CallOptions>())) .Returns(expectedResponse); DataTransferServiceClient client = new DataTransferServiceClientImpl(mockGrpcClient.Object, null); client.DeleteTransferRun(request); mockGrpcClient.VerifyAll(); } [Fact] public async Task DeleteTransferRunAsync2() { Mock<DataTransferService.DataTransferServiceClient> mockGrpcClient = new Mock<DataTransferService.DataTransferServiceClient>(MockBehavior.Strict); DeleteTransferRunRequest request = new DeleteTransferRunRequest { RunNameOneof = RunNameOneof.From(new ProjectRunName("[PROJECT]", "[TRANSFER_CONFIG]", "[RUN]")), }; Empty expectedResponse = new Empty(); mockGrpcClient.Setup(x => x.DeleteTransferRunAsync(request, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<Empty>(Task.FromResult(expectedResponse), null, null, null, null)); DataTransferServiceClient client = new DataTransferServiceClientImpl(mockGrpcClient.Object, null); await client.DeleteTransferRunAsync(request); mockGrpcClient.VerifyAll(); } [Fact] public void CheckValidCreds() { Mock<DataTransferService.DataTransferServiceClient> mockGrpcClient = new Mock<DataTransferService.DataTransferServiceClient>(MockBehavior.Strict); CheckValidCredsRequest expectedRequest = new CheckValidCredsRequest { DataSourceNameOneof = DataSourceNameOneof.From(new ProjectDataSourceName("[PROJECT]", "[DATA_SOURCE]")), }; CheckValidCredsResponse expectedResponse = new CheckValidCredsResponse { HasValidCreds = false, }; mockGrpcClient.Setup(x => x.CheckValidCreds(expectedRequest, It.IsAny<CallOptions>())) .Returns(expectedResponse); DataTransferServiceClient client = new DataTransferServiceClientImpl(mockGrpcClient.Object, null); DataSourceNameOneof name = DataSourceNameOneof.From(new ProjectDataSourceName("[PROJECT]", "[DATA_SOURCE]")); CheckValidCredsResponse response = client.CheckValidCreds(name); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task CheckValidCredsAsync() { Mock<DataTransferService.DataTransferServiceClient> mockGrpcClient = new Mock<DataTransferService.DataTransferServiceClient>(MockBehavior.Strict); CheckValidCredsRequest expectedRequest = new CheckValidCredsRequest { DataSourceNameOneof = DataSourceNameOneof.From(new ProjectDataSourceName("[PROJECT]", "[DATA_SOURCE]")), }; CheckValidCredsResponse expectedResponse = new CheckValidCredsResponse { HasValidCreds = false, }; mockGrpcClient.Setup(x => x.CheckValidCredsAsync(expectedRequest, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<CheckValidCredsResponse>(Task.FromResult(expectedResponse), null, null, null, null)); DataTransferServiceClient client = new DataTransferServiceClientImpl(mockGrpcClient.Object, null); DataSourceNameOneof name = DataSourceNameOneof.From(new ProjectDataSourceName("[PROJECT]", "[DATA_SOURCE]")); CheckValidCredsResponse response = await client.CheckValidCredsAsync(name); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public void CheckValidCreds2() { Mock<DataTransferService.DataTransferServiceClient> mockGrpcClient = new Mock<DataTransferService.DataTransferServiceClient>(MockBehavior.Strict); CheckValidCredsRequest request = new CheckValidCredsRequest { DataSourceNameOneof = DataSourceNameOneof.From(new ProjectDataSourceName("[PROJECT]", "[DATA_SOURCE]")), }; CheckValidCredsResponse expectedResponse = new CheckValidCredsResponse { HasValidCreds = false, }; mockGrpcClient.Setup(x => x.CheckValidCreds(request, It.IsAny<CallOptions>())) .Returns(expectedResponse); DataTransferServiceClient client = new DataTransferServiceClientImpl(mockGrpcClient.Object, null); CheckValidCredsResponse response = client.CheckValidCreds(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task CheckValidCredsAsync2() { Mock<DataTransferService.DataTransferServiceClient> mockGrpcClient = new Mock<DataTransferService.DataTransferServiceClient>(MockBehavior.Strict); CheckValidCredsRequest request = new CheckValidCredsRequest { DataSourceNameOneof = DataSourceNameOneof.From(new ProjectDataSourceName("[PROJECT]", "[DATA_SOURCE]")), }; CheckValidCredsResponse expectedResponse = new CheckValidCredsResponse { HasValidCreds = false, }; mockGrpcClient.Setup(x => x.CheckValidCredsAsync(request, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<CheckValidCredsResponse>(Task.FromResult(expectedResponse), null, null, null, null)); DataTransferServiceClient client = new DataTransferServiceClientImpl(mockGrpcClient.Object, null); CheckValidCredsResponse response = await client.CheckValidCredsAsync(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Globalization { public partial class CompareInfo { internal unsafe CompareInfo(CultureInfo culture) { _name = culture._name; InitSort(culture); } private void InitSort(CultureInfo culture) { _sortName = culture.SortName; const uint LCMAP_SORTHANDLE = 0x20000000; _name = culture._name; _sortName = culture.SortName; IntPtr handle; int ret = Interop.mincore.LCMapStringEx(_sortName, LCMAP_SORTHANDLE, null, 0, &handle, IntPtr.Size, null, null, IntPtr.Zero); _sortHandle = ret > 0 ? handle : IntPtr.Zero; } private static unsafe int FindStringOrdinal( uint dwFindStringOrdinalFlags, string stringSource, int offset, int cchSource, string value, int cchValue, bool bIgnoreCase) { fixed (char* pSource = stringSource) fixed (char* pValue = value) { int ret = Interop.mincore.FindStringOrdinal( dwFindStringOrdinalFlags, pSource + offset, cchSource, pValue, cchValue, bIgnoreCase ? 1 : 0); return ret < 0 ? ret : ret + offset; } } internal static int IndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase) { Debug.Assert(source != null); Debug.Assert(value != null); return FindStringOrdinal(FIND_FROMSTART, source, startIndex, count, value, value.Length, ignoreCase); } internal static int LastIndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase) { Debug.Assert(source != null); Debug.Assert(value != null); return FindStringOrdinal(FIND_FROMEND, source, startIndex - count + 1, count, value, value.Length, ignoreCase); } private unsafe int GetHashCodeOfStringCore(string source, CompareOptions options) { Debug.Assert(source != null); Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); if (source.Length == 0) { return 0; } int tmpHash = 0; fixed (char* pSource = source) { if (Interop.mincore.LCMapStringEx(_sortHandle != IntPtr.Zero ? null : _sortName, LCMAP_HASH | (uint)GetNativeCompareFlags(options), pSource, source.Length, &tmpHash, sizeof(int), null, null, _sortHandle) == 0) { Environment.FailFast("LCMapStringEx failed!"); } } return tmpHash; } private static unsafe int CompareStringOrdinalIgnoreCase(char* string1, int count1, char* string2, int count2) { // Use the OS to compare and then convert the result to expected value by subtracting 2 return Interop.mincore.CompareStringOrdinal(string1, count1, string2, count2, true) - 2; } private unsafe int CompareString(string string1, int offset1, int length1, string string2, int offset2, int length2, CompareOptions options) { Debug.Assert(string1 != null); Debug.Assert(string2 != null); Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); string localeName = _sortHandle != IntPtr.Zero ? null : _sortName; fixed (char* pLocaleName = localeName) fixed (char* pString1 = string1) fixed (char* pString2 = string2) { int result = Interop.mincore.CompareStringEx( pLocaleName, (uint)GetNativeCompareFlags(options), pString1 + offset1, length1, pString2 + offset2, length2, null, null, _sortHandle); if (result == 0) { Environment.FailFast("CompareStringEx failed"); } // Map CompareStringEx return value to -1, 0, 1. return result - 2; } } private unsafe int FindString( uint dwFindNLSStringFlags, string lpStringSource, int startSource, int cchSource, string lpStringValue, int startValue, int cchValue) { string localeName = _sortHandle != IntPtr.Zero ? null : _sortName; fixed (char* pLocaleName = localeName) fixed (char* pSource = lpStringSource) fixed (char* pValue = lpStringValue) { char* pS = pSource + startSource; char* pV = pValue + startValue; return Interop.mincore.FindNLSStringEx( pLocaleName, dwFindNLSStringFlags, pS, cchSource, pV, cchValue, null, null, null, _sortHandle); } } private int IndexOfCore(string source, string target, int startIndex, int count, CompareOptions options) { Debug.Assert(!string.IsNullOrEmpty(source)); Debug.Assert(target != null); Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0); // TODO: Consider moving this up to the relevent APIs we need to ensure this behavior for // and add a precondition that target is not empty. if (target.Length == 0) return startIndex; // keep Whidbey compatibility if ((options & CompareOptions.Ordinal) != 0) { return FastIndexOfString(source, target, startIndex, count, target.Length, findLastIndex: false); } else { int retValue = FindString(FIND_FROMSTART | (uint)GetNativeCompareFlags(options), source, startIndex, count, target, 0, target.Length); if (retValue >= 0) { return retValue + startIndex; } } return -1; } private int LastIndexOfCore(string source, string target, int startIndex, int count, CompareOptions options) { Debug.Assert(!string.IsNullOrEmpty(source)); Debug.Assert(target != null); Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0); // TODO: Consider moving this up to the relevent APIs we need to ensure this behavior for // and add a precondition that target is not empty. if (target.Length == 0) return startIndex; // keep Whidbey compatibility if ((options & CompareOptions.Ordinal) != 0) { return FastIndexOfString(source, target, startIndex, count, target.Length, findLastIndex: true); } else { int retValue = FindString(FIND_FROMEND | (uint)GetNativeCompareFlags(options), source, startIndex - count + 1, count, target, 0, target.Length); if (retValue >= 0) { return retValue + startIndex - (count - 1); } } return -1; } private bool StartsWith(string source, string prefix, CompareOptions options) { Debug.Assert(!string.IsNullOrEmpty(source)); Debug.Assert(!string.IsNullOrEmpty(prefix)); Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); return FindString(FIND_STARTSWITH | (uint)GetNativeCompareFlags(options), source, 0, source.Length, prefix, 0, prefix.Length) >= 0; } private bool EndsWith(string source, string suffix, CompareOptions options) { Debug.Assert(!string.IsNullOrEmpty(source)); Debug.Assert(!string.IsNullOrEmpty(suffix)); Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); return FindString(FIND_ENDSWITH | (uint)GetNativeCompareFlags(options), source, 0, source.Length, suffix, 0, suffix.Length) >= 0; } // PAL ends here [NonSerialized] private readonly IntPtr _sortHandle; private const uint LCMAP_HASH = 0x00040000; private const int FIND_STARTSWITH = 0x00100000; private const int FIND_ENDSWITH = 0x00200000; private const int FIND_FROMSTART = 0x00400000; private const int FIND_FROMEND = 0x00800000; // TODO: Instead of this method could we just have upstack code call IndexOfOrdinal with ignoreCase = false? private static unsafe int FastIndexOfString(string source, string target, int startIndex, int sourceCount, int targetCount, bool findLastIndex) { int retValue = -1; int sourceStartIndex = findLastIndex ? startIndex - sourceCount + 1 : startIndex; fixed (char* pSource = source, spTarget = target) { char* spSubSource = pSource + sourceStartIndex; if (findLastIndex) { int startPattern = (sourceCount - 1) - targetCount + 1; if (startPattern < 0) return -1; char patternChar0 = spTarget[0]; for (int ctrSrc = startPattern; ctrSrc >= 0; ctrSrc--) { if (spSubSource[ctrSrc] != patternChar0) continue; int ctrPat; for (ctrPat = 1; ctrPat < targetCount; ctrPat++) { if (spSubSource[ctrSrc + ctrPat] != spTarget[ctrPat]) break; } if (ctrPat == targetCount) { retValue = ctrSrc; break; } } if (retValue >= 0) { retValue += startIndex - sourceCount + 1; } } else { int endPattern = (sourceCount - 1) - targetCount + 1; if (endPattern < 0) return -1; char patternChar0 = spTarget[0]; for (int ctrSrc = 0; ctrSrc <= endPattern; ctrSrc++) { if (spSubSource[ctrSrc] != patternChar0) continue; int ctrPat; for (ctrPat = 1; ctrPat < targetCount; ctrPat++) { if (spSubSource[ctrSrc + ctrPat] != spTarget[ctrPat]) break; } if (ctrPat == targetCount) { retValue = ctrSrc; break; } } if (retValue >= 0) { retValue += startIndex; } } } return retValue; } private unsafe SortKey CreateSortKey(String source, CompareOptions options) { if (source == null) { throw new ArgumentNullException(nameof(source)); } Contract.EndContractBlock(); if ((options & ValidSortkeyCtorMaskOffFlags) != 0) { throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options)); } throw new NotImplementedException(); } private static unsafe bool IsSortable(char* text, int length) { // CompareInfo c = CultureInfo.InvariantCulture.CompareInfo; // return (InternalIsSortable(c.m_dataHandle, c.m_handleOrigin, c.m_sortName, text, text.Length)); throw new NotImplementedException(); } private const int COMPARE_OPTIONS_ORDINAL = 0x40000000; // Ordinal private const int NORM_IGNORECASE = 0x00000001; // Ignores case. (use LINGUISTIC_IGNORECASE instead) private const int NORM_IGNOREKANATYPE = 0x00010000; // Does not differentiate between Hiragana and Katakana characters. Corresponding Hiragana and Katakana will compare as equal. private const int NORM_IGNORENONSPACE = 0x00000002; // Ignores nonspacing. This flag also removes Japanese accent characters. (use LINGUISTIC_IGNOREDIACRITIC instead) private const int NORM_IGNORESYMBOLS = 0x00000004; // Ignores symbols. private const int NORM_IGNOREWIDTH = 0x00020000; // Does not differentiate between a single-byte character and the same character as a double-byte character. private const int NORM_LINGUISTIC_CASING = 0x08000000; // use linguistic rules for casing private const int SORT_STRINGSORT = 0x00001000; // Treats punctuation the same as symbols. private static int GetNativeCompareFlags(CompareOptions options) { // Use "linguistic casing" by default (load the culture's casing exception tables) int nativeCompareFlags = NORM_LINGUISTIC_CASING; if ((options & CompareOptions.IgnoreCase) != 0) { nativeCompareFlags |= NORM_IGNORECASE; } if ((options & CompareOptions.IgnoreKanaType) != 0) { nativeCompareFlags |= NORM_IGNOREKANATYPE; } if ((options & CompareOptions.IgnoreNonSpace) != 0) { nativeCompareFlags |= NORM_IGNORENONSPACE; } if ((options & CompareOptions.IgnoreSymbols) != 0) { nativeCompareFlags |= NORM_IGNORESYMBOLS; } if ((options & CompareOptions.IgnoreWidth) != 0) { nativeCompareFlags |= NORM_IGNOREWIDTH; } if ((options & CompareOptions.StringSort) != 0) { nativeCompareFlags |= SORT_STRINGSORT; } // TODO: Can we try for GetNativeCompareFlags to never // take Ordinal or OrdinalIgnoreCase. This value is not part of Win32, we just handle it special // in some places. // Suffix & Prefix shouldn't use this, make sure to turn off the NORM_LINGUISTIC_CASING flag if (options == CompareOptions.Ordinal) { nativeCompareFlags = COMPARE_OPTIONS_ORDINAL; } Debug.Assert(((options & ~(CompareOptions.IgnoreCase | CompareOptions.IgnoreKanaType | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreWidth | CompareOptions.StringSort)) == 0) || (options == CompareOptions.Ordinal), "[CompareInfo.GetNativeCompareFlags]Expected all flags to be handled"); return nativeCompareFlags; } private SortVersion GetSortVersion() { throw new NotImplementedException(); } } }
using Orleans.Serialization.Buffers; using Orleans.Serialization.Codecs; using Orleans.Serialization.Serializers; using Orleans.Serialization.WireProtocol; using Microsoft.Extensions.DependencyInjection; using System; using System.Buffers; using System.Collections.Generic; using System.Reflection; using System.Runtime.CompilerServices; using System.Threading; namespace Orleans.Serialization.GeneratedCodeHelpers { /// <summary> /// Utilities for use by generated code. /// </summary> public static class OrleansGeneratedCodeHelper { private static readonly ThreadLocal<RecursiveServiceResolutionState> ResolutionState = new ThreadLocal<RecursiveServiceResolutionState>(() => new RecursiveServiceResolutionState()); private sealed class RecursiveServiceResolutionState { private int _depth; public List<object> Callers { get; } = new List<object>(); public void Enter(object caller) { ++_depth; if (caller is object) { Callers.Add(caller); } } public void Exit() { if (--_depth <= 0) { Callers.Clear(); } } } /// <summary> /// Unwraps the provided service if it was wrapped. /// </summary> /// <typeparam name="TService">The service type.</typeparam> /// <param name="caller">The caller.</param> /// <param name="codecProvider">The codec provider.</param> /// <returns>The unwrapped service.</returns> public static TService GetService<TService>(object caller, ICodecProvider codecProvider) { var state = ResolutionState.Value; try { state.Enter(caller); foreach (var c in state.Callers) { if (c is TService s && !(c is IServiceHolder<TService>)) { return s; } } return Unwrap(ActivatorUtilities.GetServiceOrCreateInstance<TService>(codecProvider.Services)); } finally { state.Exit(); } static TService Unwrap(TService val) { while (val is IServiceHolder<TService> wrapping) { val = wrapping.Value; } return val; } } /// <summary> /// Unwraps the provided service if it was wrapped. /// </summary> /// <typeparam name="TService">The service type.</typeparam> /// <param name="caller">The caller.</param> /// <param name="service">The service.</param> /// <returns>The unwrapped service.</returns> public static TService UnwrapService<TService>(object caller, TService service) { while (service is IServiceHolder<TService> && caller is TService callerService) { return callerService; } var state = ResolutionState.Value; try { state.Enter(caller); foreach (var c in state.Callers) { if (c is TService s && !(c is IServiceHolder<TService>)) { return s; } } return Unwrap(service); } finally { state.Exit(); } static TService Unwrap(TService val) { while (val is IServiceHolder<TService> wrapping) { val = wrapping.Value; } return val; } } internal static object TryGetService(Type serviceType) { var state = ResolutionState.Value; foreach (var c in state.Callers) { var type = c?.GetType(); if (serviceType == type) { return c; } } return null; } /// <summary> /// Generated code helper method which throws an <see cref="ArgumentOutOfRangeException"/>. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] public static TArgument InvokableThrowArgumentOutOfRange<TArgument>(int index, int maxArgs) => throw new ArgumentOutOfRangeException($"The argument index value {index} must be between 0 and {maxArgs}"); /// <summary> /// Reads a field header. /// </summary> /// <typeparam name="TInput">The reader input type.</typeparam> /// <param name="reader">The reader.</param> /// <param name="header">The header.</param> /// <param name="id">The identifier.</param> /// <returns>The field id, if a new field header was written, otherwise <c>-1</c>.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int ReadHeader<TInput>(ref Reader<TInput> reader, ref Field header, int id) { reader.ReadFieldHeader(ref header); if (header.IsEndBaseOrEndObject) { return -1; } return (int)(id + header.FieldIdDelta); } /// <summary> /// Reads the header expecting an end base tag or end object tag. /// </summary> /// <typeparam name="TInput">The reader input type.</typeparam> /// <param name="reader">The reader.</param> /// <param name="header">The header.</param> /// <param name="id">The identifier.</param> /// <returns>The field id, if a new field header was written, otherwise <c>-1</c>.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int ReadHeaderExpectingEndBaseOrEndObject<TInput>(ref Reader<TInput> reader, ref Field header, int id) { reader.ReadFieldHeader(ref header); if (header.IsEndBaseOrEndObject) { return -1; } return (int)(id + header.FieldIdDelta); } /// <summary> /// Serializes an unexpected value. /// </summary> /// <typeparam name="TBufferWriter">The buffer writer type.</typeparam> /// <typeparam name="TField">The value type.</typeparam> /// <param name="writer">The writer.</param> /// <param name="fieldIdDelta">The field identifier delta.</param> /// <param name="expectedType">The expected type.</param> /// <param name="value">The value.</param> [MethodImpl(MethodImplOptions.NoInlining)] public static void SerializeUnexpectedType<TBufferWriter, TField>(ref Writer<TBufferWriter> writer, uint fieldIdDelta, Type expectedType, TField value) where TBufferWriter : IBufferWriter<byte> { var specificSerializer = writer.Session.CodecProvider.GetCodec(value.GetType()); specificSerializer.WriteField(ref writer, fieldIdDelta, expectedType, value); } /// <summary> /// Deserializes an unexpected value. /// </summary> /// <typeparam name="TInput">The reader input type.</typeparam> /// <typeparam name="TField">The value type.</typeparam> /// <param name="reader">The reader.</param> /// <param name="field">The field.</param> /// <returns>The value.</returns> [MethodImpl(MethodImplOptions.NoInlining)] public static TField DeserializeUnexpectedType<TInput, TField>(ref Reader<TInput> reader, Field field) { var specificSerializer = reader.Session.CodecProvider.GetCodec(field.FieldType); return (TField)specificSerializer.ReadValue(ref reader, field); } /// <summary> /// Gets the <see cref="MethodInfo"/> matching the provided values. /// </summary> /// <param name="interfaceType">Type of the interface.</param> /// <param name="methodName">Name of the method.</param> /// <param name="methodTypeParameters">The method type parameters.</param> /// <param name="parameterTypes">The parameter types.</param> /// <returns>The corresponding <see cref="MethodInfo"/>.</returns> [MethodImpl(MethodImplOptions.NoInlining)] public static MethodInfo GetMethodInfoOrDefault(Type interfaceType, string methodName, Type[] methodTypeParameters, Type[] parameterTypes) { if (interfaceType is null) { return null; } foreach (var method in interfaceType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) { if (method.Name != methodName) { continue; } if (!method.ContainsGenericParameters && methodTypeParameters is { Length: > 0 }) { continue; } if (method.ContainsGenericParameters && methodTypeParameters is null or { Length: 0 }) { continue; } var parameters = method.GetParameters(); if (parameters.Length != parameterTypes.Length) { continue; } for (int i = 0; i < parameters.Length; i++) { if (!parameters[0].ParameterType.Equals(parameterTypes[i])) { continue; } } return method; } foreach (var implemented in interfaceType.GetInterfaces()) { if (GetMethodInfoOrDefault(implemented, methodName, methodTypeParameters, parameterTypes) is { } method) { return method; } } return null; } } }
// 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.Linq; using Xunit; namespace Test { public class GroupByTests { private const int GroupFactor = 8; [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, GroupFactor - 1, GroupFactor, GroupFactor * 2 - 1, GroupFactor * 2 }), MemberType = typeof(UnorderedSources))] public static void GroupBy_Unordered(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; IntegerRangeSet groupsSeen = new IntegerRangeSet(0, Math.Min(count, GroupFactor)); foreach (IGrouping<int, int> group in query.GroupBy(x => x % GroupFactor)) { groupsSeen.Add(group.Key); IntegerRangeSet elementsSeen = new IntegerRangeSet(0, 1 + (count - (group.Key + 1)) / GroupFactor); foreach (int i in group) { Assert.Equal(group.Key, i % GroupFactor); elementsSeen.Add(i / GroupFactor); } elementsSeen.AssertComplete(); } groupsSeen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 16 }), MemberType = typeof(UnorderedSources))] public static void GroupBy_Unordered_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { GroupBy_Unordered(labeled, count); } [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, GroupFactor - 1, GroupFactor, GroupFactor * 2 - 1, GroupFactor * 2 }), MemberType = typeof(Sources))] public static void GroupBy(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; int groupsSeen = 0; foreach (IGrouping<int, int> group in query.GroupBy(x => x % GroupFactor)) { Assert.Equal(groupsSeen++, group.Key); int elementsSeen = group.Key; foreach (int i in group) { Assert.Equal(elementsSeen, i); elementsSeen += GroupFactor; } Assert.Equal(group.Key + (1 + (count - (group.Key + 1)) / GroupFactor) * GroupFactor, elementsSeen); } Assert.Equal(Math.Min(count, GroupFactor), groupsSeen); } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 16 }), MemberType = typeof(Sources))] public static void GroupBy_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { GroupBy(labeled, count); } [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, GroupFactor - 1, GroupFactor, GroupFactor * 2 - 1, GroupFactor * 2 }), MemberType = typeof(UnorderedSources))] public static void GroupBy_Unordered_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; IntegerRangeSet groupsSeen = new IntegerRangeSet(0, Math.Min(count, GroupFactor)); foreach (IGrouping<int, int> group in query.GroupBy(x => x % GroupFactor).ToList()) { groupsSeen.Add(group.Key); IntegerRangeSet elementsSeen = new IntegerRangeSet(0, 1 + (count - (group.Key + 1)) / GroupFactor); Assert.All(group, x => { Assert.Equal(group.Key, x % GroupFactor); elementsSeen.Add(x / GroupFactor); }); elementsSeen.AssertComplete(); } groupsSeen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 16 }), MemberType = typeof(UnorderedSources))] public static void GroupBy_Unordered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { GroupBy_Unordered_NotPipelined(labeled, count); } [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, GroupFactor - 1, GroupFactor, GroupFactor * 2 - 1, GroupFactor * 2 }), MemberType = typeof(Sources))] public static void GroupBy_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; int groupsSeen = 0; foreach (IGrouping<int, int> group in query.GroupBy(x => x % GroupFactor).ToList()) { Assert.Equal(groupsSeen++, group.Key); int elementsSeen = group.Key; Assert.All(group, x => { Assert.Equal(elementsSeen, x); elementsSeen += GroupFactor; }); Assert.Equal(group.Key + (1 + (count - (group.Key + 1)) / GroupFactor) * GroupFactor, elementsSeen); } Assert.Equal(Math.Min(count, GroupFactor), groupsSeen); } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 16 }), MemberType = typeof(Sources))] public static void GroupBy_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { GroupBy_NotPipelined(labeled, count); } [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, GroupFactor - 1, GroupFactor, GroupFactor * 2 - 1, GroupFactor * 2 }), MemberType = typeof(UnorderedSources))] public static void GroupBy_Unordered_CustomComparator(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; IntegerRangeSet groupsSeen = new IntegerRangeSet(0, Math.Min(count, GroupFactor)); foreach (IGrouping<int, int> group in query.GroupBy(x => x, new ModularCongruenceComparer(GroupFactor))) { groupsSeen.Add(group.Key % GroupFactor); IntegerRangeSet elementsSeen = new IntegerRangeSet(0, 1 + (count - (group.Key % GroupFactor + 1)) / GroupFactor); foreach (int i in group) { Assert.Equal(group.Key % GroupFactor, i % GroupFactor); elementsSeen.Add(i / GroupFactor); } elementsSeen.AssertComplete(); } groupsSeen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 16 }), MemberType = typeof(UnorderedSources))] public static void GroupBy_Unordered_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { GroupBy_Unordered(labeled, count); } [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, GroupFactor - 1, GroupFactor, GroupFactor * 2 - 1, GroupFactor * 2 }), MemberType = typeof(Sources))] // GroupBy doesn't select the first 'identical' key. Issue #1490 public static void GroupBy_CustomComparator(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; int groupsSeen = 0; foreach (IGrouping<int, int> group in query.GroupBy(x => x, new ModularCongruenceComparer(GroupFactor))) { int elementsSeen = groupsSeen; Assert.Equal(groupsSeen++, group.Key % GroupFactor); foreach (int i in group) { Assert.Equal(elementsSeen, i); elementsSeen += GroupFactor; } Assert.Equal(group.Key + (1 + (count - (group.Key + 1)) / GroupFactor) * GroupFactor, elementsSeen); } Assert.Equal(Math.Min(count, GroupFactor), groupsSeen); } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 16 }), MemberType = typeof(Sources))] public static void GroupBy_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { GroupBy(labeled, count); } [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, GroupFactor - 1, GroupFactor, GroupFactor * 2 - 1, GroupFactor * 2 }), MemberType = typeof(UnorderedSources))] public static void GroupBy_Unordered_ElementSelector(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; IntegerRangeSet groupsSeen = new IntegerRangeSet(0, Math.Min(count, GroupFactor)); foreach (IGrouping<int, int> group in query.GroupBy(x => x % GroupFactor, x => -x)) { groupsSeen.Add(group.Key); int expected = 1 + (count - (group.Key + 1)) / GroupFactor; IntegerRangeSet elementsSeen = new IntegerRangeSet(1 - expected, expected); Assert.All(group, x => { Assert.Equal(group.Key, -x % GroupFactor); elementsSeen.Add(x / GroupFactor); }); elementsSeen.AssertComplete(); } groupsSeen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 16 }), MemberType = typeof(UnorderedSources))] public static void GroupBy_Unordered_ElementSelector_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { GroupBy_Unordered_ElementSelector(labeled, count); } [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, GroupFactor - 1, GroupFactor, GroupFactor * 2 - 1, GroupFactor * 2 }), MemberType = typeof(Sources))] public static void GroupBy_ElementSelector(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; int groupsSeen = 0; foreach (IGrouping<int, int> group in query.GroupBy(x => x % GroupFactor, x => -x)) { Assert.Equal(groupsSeen++, group.Key); int elementsSeen = -group.Key; Assert.All(group, x => { Assert.Equal(elementsSeen, x); elementsSeen -= GroupFactor; }); Assert.Equal(-group.Key - (1 + (count - (group.Key + 1)) / GroupFactor) * GroupFactor, elementsSeen); } Assert.Equal(Math.Min(count, GroupFactor), groupsSeen); } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 16 }), MemberType = typeof(Sources))] public static void GroupBy_ElementSelector_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { GroupBy_ElementSelector(labeled, count); } [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, GroupFactor - 1, GroupFactor, GroupFactor * 2 - 1, GroupFactor * 2 }), MemberType = typeof(UnorderedSources))] public static void GroupBy_Unordered_ElementSelector_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; IntegerRangeSet groupsSeen = new IntegerRangeSet(0, Math.Min(count, GroupFactor)); foreach (IGrouping<int, int> group in query.GroupBy(x => x % GroupFactor, y => -y).ToList()) { groupsSeen.Add(group.Key); int expected = 1 + (count - (group.Key + 1)) / GroupFactor; IntegerRangeSet elementsSeen = new IntegerRangeSet(1 - expected, expected); Assert.All(group, x => { Assert.Equal(group.Key, -x % GroupFactor); elementsSeen.Add(x / GroupFactor); }); elementsSeen.AssertComplete(); } groupsSeen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 16 }), MemberType = typeof(UnorderedSources))] public static void GroupBy_Unordered_ElementSelector_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { GroupBy_Unordered_ElementSelector_NotPipelined(labeled, count); } [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, GroupFactor - 1, GroupFactor, GroupFactor * 2 - 1, GroupFactor * 2 }), MemberType = typeof(Sources))] public static void GroupBy_ElementSelector_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; int groupsSeen = 0; foreach (IGrouping<int, int> group in query.GroupBy(x => x % GroupFactor, y => -y).ToList()) { Assert.Equal(groupsSeen++, group.Key); int elementsSeen = -group.Key; Assert.All(group, x => { Assert.Equal(elementsSeen, x); elementsSeen -= GroupFactor; }); Assert.Equal(-group.Key - (1 + (count - (group.Key + 1)) / GroupFactor) * GroupFactor, elementsSeen); } Assert.Equal(Math.Min(count, GroupFactor), groupsSeen); } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 16 }), MemberType = typeof(Sources))] public static void GroupBy_ElementSelector_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { GroupBy_ElementSelector_NotPipelined(labeled, count); } [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, GroupFactor - 1, GroupFactor, GroupFactor * 2 - 1, GroupFactor * 2 }), MemberType = typeof(UnorderedSources))] public static void GroupBy_Unordered_ResultSelector(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; IntegerRangeSet groupsSeen = new IntegerRangeSet(0, Math.Min(count, GroupFactor)); foreach (var group in query.GroupBy(x => x % GroupFactor, (key, elements) => KeyValuePair.Create(key, elements))) { groupsSeen.Add(group.Key); IntegerRangeSet elementsSeen = new IntegerRangeSet(0, 1 + (count - (group.Key + 1)) / GroupFactor); Assert.All(group.Value, x => { Assert.Equal(group.Key, x % GroupFactor); elementsSeen.Add(x / GroupFactor); }); elementsSeen.AssertComplete(); } groupsSeen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 16 }), MemberType = typeof(UnorderedSources))] public static void GroupBy_Unordered_ResultSelector_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { GroupBy_Unordered_ResultSelector(labeled, count); } [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, GroupFactor - 1, GroupFactor, GroupFactor * 2 - 1, GroupFactor * 2 }), MemberType = typeof(Sources))] public static void GroupBy_ResultSelector(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; int groupsSeen = 0; foreach (var group in query.GroupBy(x => x % GroupFactor, (key, elements) => KeyValuePair.Create(key, elements))) { Assert.Equal(groupsSeen++, group.Key); int elementsSeen = group.Key; Assert.All(group.Value, x => { Assert.Equal(elementsSeen, x); elementsSeen += GroupFactor; }); Assert.Equal(group.Key + (1 + (count - (group.Key + 1)) / GroupFactor) * GroupFactor, elementsSeen); } Assert.Equal(Math.Min(count, GroupFactor), groupsSeen); } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 16 }), MemberType = typeof(Sources))] public static void GroupBy_ResultSelector_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { GroupBy_ResultSelector(labeled, count); } [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 7, 8, 15, 16 }), MemberType = typeof(UnorderedSources))] public static void GroupBy_Unordered_ResultSelector_CustomComparator(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; IntegerRangeSet groupsSeen = new IntegerRangeSet(0, Math.Min(count, GroupFactor)); foreach (var group in query.GroupBy(x => x, (key, elements) => KeyValuePair.Create(key, elements), new ModularCongruenceComparer(GroupFactor))) { groupsSeen.Add(group.Key % GroupFactor); IntegerRangeSet elementsSeen = new IntegerRangeSet(0, 1 + (count - (group.Key % GroupFactor + 1)) / GroupFactor); Assert.All(group.Value, x => { Assert.Equal(group.Key % GroupFactor, x % GroupFactor); elementsSeen.Add(x / GroupFactor); }); elementsSeen.AssertComplete(); } groupsSeen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 16 }), MemberType = typeof(UnorderedSources))] public static void GroupBy_Unordered_ResultSelector_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { GroupBy_Unordered_ResultSelector_CustomComparator(labeled, count); } [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, GroupFactor - 1, GroupFactor, GroupFactor * 2 - 1, GroupFactor * 2 }), MemberType = typeof(Sources))] public static void GroupBy_ResultSelector_CustomComparator(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; int groupsSeen = 0; foreach (var group in query.GroupBy(x => x, (key, elements) => KeyValuePair.Create(key, elements), new ModularCongruenceComparer(GroupFactor))) { int elementsSeen = groupsSeen; Assert.Equal(groupsSeen++, group.Key % GroupFactor); Assert.All(group.Value, x => { Assert.Equal(elementsSeen, x); elementsSeen += GroupFactor; }); Assert.Equal(group.Key + (1 + (count - (group.Key + 1)) / GroupFactor) * GroupFactor, elementsSeen); } Assert.Equal(Math.Min(count, GroupFactor), groupsSeen); } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 16 }), MemberType = typeof(Sources))] public static void GroupBy_ResultSelector_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { GroupBy_ResultSelector_CustomComparator(labeled, count); } [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 7, 8, 15, 16 }), MemberType = typeof(UnorderedSources))] public static void GroupBy_Unordered_ElementSelector_ResultSelector(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; IntegerRangeSet groupsSeen = new IntegerRangeSet(0, Math.Min(count, GroupFactor)); foreach (var group in query.GroupBy(x => x % GroupFactor, x => -x, (key, elements) => KeyValuePair.Create(key, elements))) { groupsSeen.Add(group.Key); int expected = 1 + (count - (group.Key + 1)) / GroupFactor; IntegerRangeSet elementsSeen = new IntegerRangeSet(1 - expected, expected); Assert.All(group.Value, x => { Assert.Equal(group.Key, -x % GroupFactor); elementsSeen.Add(x / GroupFactor); }); elementsSeen.AssertComplete(); } groupsSeen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 16 }), MemberType = typeof(UnorderedSources))] public static void GroupBy_Unordered_ElementSelector_ResultSelector_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { GroupBy_Unordered_ElementSelector_ResultSelector(labeled, count); } [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, GroupFactor - 1, GroupFactor, GroupFactor * 2 - 1, GroupFactor * 2 }), MemberType = typeof(Sources))] public static void GroupBy_ElementSelector_ResultSelector(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; int groupsSeen = 0; foreach (var group in query.GroupBy(x => x % GroupFactor, x => -x, (key, elements) => KeyValuePair.Create(key, elements))) { Assert.Equal(groupsSeen++, group.Key); int elementsSeen = -group.Key; Assert.All(group.Value, x => { Assert.Equal(elementsSeen, x); elementsSeen -= GroupFactor; }); Assert.Equal(-group.Key - (1 + (count - (group.Key + 1)) / GroupFactor) * GroupFactor, elementsSeen); } Assert.Equal(Math.Min(count, GroupFactor), groupsSeen); } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 16 }), MemberType = typeof(Sources))] public static void GroupBy_ElementSelector_ResultSelector_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { GroupBy_ElementSelector_ResultSelector(labeled, count); } [Fact] public static void GroupBy_ArgumentNullException() { Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).GroupBy(i => i)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupBy((Func<int, int>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).GroupBy(i => i, EqualityComparer<int>.Default)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupBy((Func<int, int>)null, EqualityComparer<int>.Default)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).GroupBy(i => i, i => i)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupBy((Func<int, int>)null, i => i)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupBy(i => i, (Func<int, int>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).GroupBy(i => i, i => i, EqualityComparer<int>.Default)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupBy((Func<int, int>)null, i => i, EqualityComparer<int>.Default)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupBy(i => i, (Func<int, int>)null, EqualityComparer<int>.Default)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).GroupBy(i => i, (i, j) => i)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupBy((Func<int, int>)null, (i, j) => i)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupBy(i => i, (Func<int, IEnumerable<int>, int>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).GroupBy(i => i, (i, j) => i, EqualityComparer<int>.Default)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupBy((Func<int, int>)null, (i, j) => i, EqualityComparer<int>.Default)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupBy(i => i, (Func<int, IEnumerable<int>, int>)null, EqualityComparer<int>.Default)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).GroupBy(i => i, i => i, (i, j) => i)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupBy((Func<int, int>)null, i => i, (i, j) => i)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupBy(i => i, (Func<int, int>)null, (i, j) => i)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupBy(i => i, i => i, (Func<int, IEnumerable<int>, int>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).GroupBy(i => i, i => i, (i, j) => i, EqualityComparer<int>.Default)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupBy((Func<int, int>)null, i => i, (i, j) => i, EqualityComparer<int>.Default)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupBy(i => i, (Func<int, int>)null, (i, j) => i, EqualityComparer<int>.Default)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupBy(i => i, i => i, (Func<int, IEnumerable<int>, int>)null, EqualityComparer<int>.Default)); } } }
/*************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. This code is licensed under the Visual Studio SDK license terms. THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. ***************************************************************************/ using System; using System.IO; using System.Windows.Forms; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VsSDK.UnitTestLibrary; namespace Microsoft.VisualStudio.Project.Samples.NestedProject.UnitTests { static class MockServicesProvider { private static GenericMockFactory solutionBuildManager; private static GenericMockFactory solutionFactory; private static GenericMockFactory vsShellFactory; private static GenericMockFactory uiShellFactory; private static GenericMockFactory trackSelFactory; private static GenericMockFactory runningDocFactory; private static GenericMockFactory windowFrameFactory; private static GenericMockFactory qeqsFactory; private static GenericMockFactory localRegistryFactory; private static GenericMockFactory registerProjectFactory; private static GenericMockFactory fileChangeEx; #region SolutionBuildManager Getters /// <summary> /// Returns a SVsSolutionBuildManager that does not implement any methods /// </summary> /// <returns></returns> internal static BaseMock GetSolutionBuildManagerInstance() { if(solutionBuildManager == null) { solutionBuildManager = new GenericMockFactory("SolutionBuildManager", new Type[] { typeof(IVsSolutionBuildManager2), typeof(IVsSolutionBuildManager3) }); } BaseMock buildManager = solutionBuildManager.GetInstance(); return buildManager; } /// <summary> /// Returns a SVsSolutionBuildManager that implements IVsSolutionBuildManager2 and IVsSolutionBuildManager3 /// </summary> /// <returns></returns> internal static BaseMock GetSolutionBuildManagerInstance0() { BaseMock buildManager = GetSolutionBuildManagerInstance(); string name = string.Format("{0}.{1}", typeof(IVsSolutionBuildManager2).FullName, "AdviseUpdateSolutionEvents"); buildManager.AddMethodCallback(name, new EventHandler<CallbackArgs>(AdviseUpdateSolutionEventsCallBack)); name = string.Format("{0}.{1}", typeof(IVsSolutionBuildManager3).FullName, "AdviseUpdateSolutionEvents3"); buildManager.AddMethodCallback(name, new EventHandler<CallbackArgs>(AdviseUpdateSolutionEvents3CallBack)); return buildManager; } #endregion #region SolutionFactory Getters /// <summary> /// Returns an IVsUiShell that does not implement any methods /// </summary> /// <returns></returns> internal static BaseMock GetSolutionFactoryInstance() { if(solutionFactory == null) { solutionFactory = new GenericMockFactory("MockSolution", new Type[] { typeof(IVsSolution) }); } BaseMock solution = solutionFactory.GetInstance(); return solution; } #endregion #region VsShell Getters /// <summary> /// Returns an IVsShell that does not implement any methods /// </summary> /// <returns></returns> internal static BaseMock GetVsShellInstance() { if(vsShellFactory == null) { vsShellFactory = new GenericMockFactory("VsShell", new Type[] { typeof(IVsShell) }); } BaseMock shell = vsShellFactory.GetInstance(); return shell; } /// <summary> /// Returns an IVsShell that implements GetProperty /// </summary> /// <returns></returns> internal static BaseMock GetVsShellInstance0() { BaseMock vsShell = GetVsShellInstance(); string name = string.Format("{0}.{1}", typeof(IVsShell).FullName, "GetProperty"); vsShell.AddMethodCallback(name, new EventHandler<CallbackArgs>(GetPropertyCallBack)); return vsShell; } #endregion #region UiShell Getters /// <summary> /// Returns an IVsUiShell that does not implement any methods /// </summary> /// <returns></returns> internal static BaseMock GetUiShellInstance() { if(uiShellFactory == null) { uiShellFactory = new GenericMockFactory("UiShell", new Type[] { typeof(IVsUIShell), typeof(IVsUIShellOpenDocument) }); } BaseMock uiShell = uiShellFactory.GetInstance(); return uiShell; } /// <summary> /// Get an IVsUiShell that implements SetWaitCursor, SaveDocDataToFile, ShowMessageBox /// </summary> /// <returns></returns> internal static BaseMock GetUiShellInstance0() { BaseMock uiShell = GetUiShellInstance(); string name = string.Format("{0}.{1}", typeof(IVsUIShell).FullName, "SetWaitCursor"); uiShell.AddMethodCallback(name, new EventHandler<CallbackArgs>(SetWaitCursorCallBack)); name = string.Format("{0}.{1}", typeof(IVsUIShell).FullName, "SaveDocDataToFile"); uiShell.AddMethodCallback(name, new EventHandler<CallbackArgs>(SaveDocDataToFileCallBack)); name = string.Format("{0}.{1}", typeof(IVsUIShell).FullName, "ShowMessageBox"); uiShell.AddMethodCallback(name, new EventHandler<CallbackArgs>(ShowMessageBoxCallBack)); name = string.Format("{0}.{1}", typeof(IVsUIShellOpenDocument).FullName, "OpenCopyOfStandardEditor"); uiShell.AddMethodCallback(name, new EventHandler<CallbackArgs>(OpenCopyOfStandardEditorCallBack)); return uiShell; } #endregion #region TrackSelection Getters /// <summary> /// Get an ITrackSelection mock object which implements the OnSelectChange method /// </summary> /// <returns></returns> internal static BaseMock GetTrackSelectionInstance() { if(trackSelFactory == null) { trackSelFactory = new GenericMockFactory("MockTrackSelection", new Type[] { typeof(ITrackSelection) }); } BaseMock trackSel = trackSelFactory.GetInstance(); string name = string.Format("{0}.{1}", typeof(ITrackSelection).FullName, "OnSelectChange"); trackSel.AddMethodCallback(name, new EventHandler<CallbackArgs>(OnSelectChangeCallBack)); return trackSel; } #endregion #region RunningDocumentTable Getters /// <summary> /// Gets the IVsRunningDocumentTable mock object which implements FindAndLockIncrement, /// NotifyDocumentChanged and UnlockDocument /// </summary> /// <returns></returns> internal static BaseMock GetRunningDocTableInstance() { if(null == runningDocFactory) { runningDocFactory = new GenericMockFactory("RunningDocumentTable", new Type[] { typeof(IVsRunningDocumentTable) }); } BaseMock runningDoc = runningDocFactory.GetInstance(); string name = string.Format("{0}.{1}", typeof(IVsRunningDocumentTable).FullName, "FindAndLockDocument"); runningDoc.AddMethodCallback(name, new EventHandler<CallbackArgs>(FindAndLockDocumentCallBack)); name = string.Format("{0}.{1}", typeof(IVsRunningDocumentTable).FullName, "NotifyDocumentChanged"); runningDoc.AddMethodReturnValues(name, new object[] { VSConstants.S_OK }); name = string.Format("{0}.{1}", typeof(IVsRunningDocumentTable).FullName, "UnlockDocument"); runningDoc.AddMethodReturnValues(name, new object[] { VSConstants.S_OK }); return runningDoc; } #endregion #region Window Frame Getters /// <summary> /// Gets an IVsWindowFrame mock object which implements the SetProperty method /// </summary> /// <returns></returns> internal static BaseMock GetWindowFrameInstance() { if(null == windowFrameFactory) { windowFrameFactory = new GenericMockFactory("WindowFrame", new Type[] { typeof(IVsWindowFrame) }); } BaseMock windowFrame = windowFrameFactory.GetInstance(); string name = string.Format("{0}.{1}", typeof(IVsWindowFrame).FullName, "SetProperty"); windowFrame.AddMethodReturnValues(name, new object[] { VSConstants.S_OK }); return windowFrame; } #endregion #region QueryEditQuerySave Getters /// <summary> /// Gets an IVsQueryEditQuerySave2 mock object which implements QuerySaveFile and QueryEditFiles methods /// </summary> /// <returns></returns> internal static BaseMock GetQueryEditQuerySaveInstance() { if(null == qeqsFactory) { qeqsFactory = new GenericMockFactory("QueryEditQuerySave", new Type[] { typeof(IVsQueryEditQuerySave2) }); } BaseMock qeqs = qeqsFactory.GetInstance(); string name = string.Format("{0}.{1}", typeof(IVsQueryEditQuerySave2).FullName, "QuerySaveFile"); qeqs.AddMethodCallback(name, new EventHandler<CallbackArgs>(QuerySaveFileCallBack)); name = string.Format("{0}.{1}", typeof(IVsQueryEditQuerySave2).FullName, "QueryEditFiles"); qeqs.AddMethodCallback(name, new EventHandler<CallbackArgs>(QueryEditFilesCallBack)); return qeqs; } #endregion #region LocalRegistry Getters /// <summary> /// Gets an IVsLocalRegistry mock object /// </summary> /// <returns></returns> internal static BaseMock GetLocalRegistryInstance() { if(null == localRegistryFactory) { localRegistryFactory = new GenericMockFactory("MockLocalRegistry", new Type[] { typeof(ILocalRegistry), typeof(ILocalRegistry3) }); } BaseMock localRegistry = localRegistryFactory.GetInstance(); string name = string.Format("{0}.{1}", typeof(IVsWindowFrame).FullName, "SetProperty"); localRegistry.AddMethodReturnValues(name, new object[] { VSConstants.S_OK }); name = string.Format("{0}.{1}", typeof(ILocalRegistry3).FullName, "GetLocalRegistryRoot"); localRegistry.AddMethodCallback(name, new EventHandler<CallbackArgs>(GetLocalRegistryRoot)); return localRegistry; } #endregion #region RegisterProjectservice Getters /// <summary> /// Gets an IVsRegisterProject service mock object /// </summary> /// <returns></returns> internal static BaseMock GetRegisterProjectInstance() { if(null == registerProjectFactory) { registerProjectFactory = new GenericMockFactory("MockRegisterProject", new Type[] { typeof(IVsRegisterProjectTypes) }); } BaseMock mock = registerProjectFactory.GetInstance(); return mock; } #endregion #region RegisterProjectservice Getters /// <summary> /// Gets an IVsFileChnageEx service mock object /// </summary> /// <returns></returns> internal static BaseMock GetIVsFileChangeEx() { if (null == fileChangeEx) { fileChangeEx = new GenericMockFactory("MockIVsFileChangeEx", new Type[] { typeof(IVsFileChangeEx) }); } BaseMock mock = fileChangeEx.GetInstance(); return mock; } #endregion #region Callbacks private static void AdviseUpdateSolutionEventsCallBack(object caller, CallbackArgs arguments) { arguments.ReturnValue = VSConstants.S_OK; } private static void AdviseUpdateSolutionEvents3CallBack(object caller, CallbackArgs arguments) { arguments.ReturnValue = VSConstants.S_OK; } private static void GetPropertyCallBack(object caller, CallbackArgs arguments) { __VSSPROPID propertyID = (__VSSPROPID)arguments.GetParameter(0); switch(propertyID) { case __VSSPROPID.VSSPROPID_IsInCommandLineMode: // fake that we are running in command line mode in order to load normally (security) arguments.SetParameter(1, true); break; default: break; } arguments.ReturnValue = VSConstants.S_OK; } private static void SetWaitCursorCallBack(object caller, CallbackArgs arguments) { arguments.ReturnValue = VSConstants.S_OK; } private static void SaveDocDataToFileCallBack(object caller, CallbackArgs arguments) { arguments.ReturnValue = VSConstants.S_OK; VSSAVEFLAGS dwSave = (VSSAVEFLAGS)arguments.GetParameter(0); IPersistFileFormat editorInstance = (IPersistFileFormat)arguments.GetParameter(1); string fileName = (string)arguments.GetParameter(2); //Call Save on the EditorInstance depending on the Save Flags switch(dwSave) { case VSSAVEFLAGS.VSSAVE_Save: case VSSAVEFLAGS.VSSAVE_SilentSave: editorInstance.Save(fileName, 0, 0); arguments.SetParameter(3, fileName); // setting pbstrMkDocumentNew arguments.SetParameter(4, 0); // setting pfSaveCanceled break; case VSSAVEFLAGS.VSSAVE_SaveAs: string newFileName = Environment.GetEnvironmentVariable("SystemDrive") + Path.DirectorySeparatorChar + "NewTempFile.rtf"; editorInstance.Save(newFileName, 1, 0); //Call Save with new file and remember=1 arguments.SetParameter(3, newFileName); // setting pbstrMkDocumentNew arguments.SetParameter(4, 0); // setting pfSaveCanceled break; case VSSAVEFLAGS.VSSAVE_SaveCopyAs: newFileName = Environment.GetEnvironmentVariable("SystemDrive") + Path.DirectorySeparatorChar + "NewTempFile.rtf"; editorInstance.Save(newFileName, 0, 0); //Call Save with new file and remember=0 arguments.SetParameter(3, newFileName); // setting pbstrMkDocumentNew arguments.SetParameter(4, 0); // setting pfSaveCanceled break; } } private static void OnSelectChangeCallBack(object caller, CallbackArgs arguments) { arguments.ReturnValue = VSConstants.S_OK; } private static void FindAndLockDocumentCallBack(object caller, CallbackArgs arguments) { arguments.ReturnValue = VSConstants.S_OK; arguments.SetParameter(2, null); //setting IVsHierarchy arguments.SetParameter(3, (uint)1); //Setting itemID arguments.SetParameter(4, IntPtr.Zero); //Setting DocData arguments.SetParameter(5, (uint)1); //Setting docCookie } private static void QuerySaveFileCallBack(object caller, CallbackArgs arguments) { arguments.ReturnValue = VSConstants.S_OK; arguments.SetParameter(3, (uint)tagVSQuerySaveResult.QSR_SaveOK); //set result } private static void QueryEditFilesCallBack(object caller, CallbackArgs arguments) { arguments.ReturnValue = VSConstants.S_OK; arguments.SetParameter(5, (uint)tagVSQueryEditResult.QER_EditOK); //setting result arguments.SetParameter(6, (uint)0); //setting outFlags } private static void ShowMessageBoxCallBack(object caller, CallbackArgs arguments) { arguments.ReturnValue = VSConstants.S_OK; arguments.SetParameter(10, (int)DialogResult.Yes); } private static void OpenCopyOfStandardEditorCallBack(object caller, CallbackArgs arguments) { arguments.ReturnValue = VSConstants.S_OK; arguments.SetParameter(2, (IVsWindowFrame)GetWindowFrameInstance()); } private static void GetLocalRegistryRoot(object caller, CallbackArgs arguments) { // this is required for fetch MSBuildPath key value arguments.SetParameter(0, @"SOFTWARE\Microsoft\VisualStudio\9.0"); // pbstrRoot arguments.ReturnValue = VSConstants.S_OK; } #endregion } }
using System; using System.Text; namespace ICSharpCode.SharpZipLib.Tar { /// <summary> /// This class encapsulates the Tar Entry Header used in Tar Archives. /// The class also holds a number of tar constants, used mostly in headers. /// </summary> /// <remarks> /// The tar format and its POSIX successor PAX have a long history which makes for compatability /// issues when creating and reading files. /// /// This is further complicated by a large number of programs with variations on formats /// One common issue is the handling of names longer than 100 characters. /// GNU style long names are currently supported. /// /// This is the ustar (Posix 1003.1) header. /// /// struct header /// { /// char t_name[100]; // 0 Filename /// char t_mode[8]; // 100 Permissions /// char t_uid[8]; // 108 Numerical User ID /// char t_gid[8]; // 116 Numerical Group ID /// char t_size[12]; // 124 Filesize /// char t_mtime[12]; // 136 st_mtime /// char t_chksum[8]; // 148 Checksum /// char t_typeflag; // 156 Type of File /// char t_linkname[100]; // 157 Target of Links /// char t_magic[6]; // 257 "ustar" or other... /// char t_version[2]; // 263 Version fixed to 00 /// char t_uname[32]; // 265 User Name /// char t_gname[32]; // 297 Group Name /// char t_devmajor[8]; // 329 Major for devices /// char t_devminor[8]; // 337 Minor for devices /// char t_prefix[155]; // 345 Prefix for t_name /// char t_mfill[12]; // 500 Filler up to 512 /// }; /// </remarks> public class TarHeader : ICloneable { #region Constants /// <summary> /// The length of the name field in a header buffer. /// </summary> public const int NAMELEN = 100; /// <summary> /// The length of the mode field in a header buffer. /// </summary> public const int MODELEN = 8; /// <summary> /// The length of the user id field in a header buffer. /// </summary> public const int UIDLEN = 8; /// <summary> /// The length of the group id field in a header buffer. /// </summary> public const int GIDLEN = 8; /// <summary> /// The length of the checksum field in a header buffer. /// </summary> public const int CHKSUMLEN = 8; /// <summary> /// Offset of checksum in a header buffer. /// </summary> public const int CHKSUMOFS = 148; /// <summary> /// The length of the size field in a header buffer. /// </summary> public const int SIZELEN = 12; /// <summary> /// The length of the magic field in a header buffer. /// </summary> public const int MAGICLEN = 6; /// <summary> /// The length of the version field in a header buffer. /// </summary> public const int VERSIONLEN = 2; /// <summary> /// The length of the modification time field in a header buffer. /// </summary> public const int MODTIMELEN = 12; /// <summary> /// The length of the user name field in a header buffer. /// </summary> public const int UNAMELEN = 32; /// <summary> /// The length of the group name field in a header buffer. /// </summary> public const int GNAMELEN = 32; /// <summary> /// The length of the devices field in a header buffer. /// </summary> public const int DEVLEN = 8; /// <summary> /// The length of the name prefix field in a header buffer. /// </summary> public const int PREFIXLEN = 155; // // LF_ constants represent the "type" of an entry // /// <summary> /// The "old way" of indicating a normal file. /// </summary> public const byte LF_OLDNORM = 0; /// <summary> /// Normal file type. /// </summary> public const byte LF_NORMAL = (byte)'0'; /// <summary> /// Link file type. /// </summary> public const byte LF_LINK = (byte)'1'; /// <summary> /// Symbolic link file type. /// </summary> public const byte LF_SYMLINK = (byte)'2'; /// <summary> /// Character device file type. /// </summary> public const byte LF_CHR = (byte)'3'; /// <summary> /// Block device file type. /// </summary> public const byte LF_BLK = (byte)'4'; /// <summary> /// Directory file type. /// </summary> public const byte LF_DIR = (byte)'5'; /// <summary> /// FIFO (pipe) file type. /// </summary> public const byte LF_FIFO = (byte)'6'; /// <summary> /// Contiguous file type. /// </summary> public const byte LF_CONTIG = (byte)'7'; /// <summary> /// Posix.1 2001 global extended header /// </summary> public const byte LF_GHDR = (byte)'g'; /// <summary> /// Posix.1 2001 extended header /// </summary> public const byte LF_XHDR = (byte)'x'; // POSIX allows for upper case ascii type as extensions /// <summary> /// Solaris access control list file type /// </summary> public const byte LF_ACL = (byte)'A'; /// <summary> /// GNU dir dump file type /// This is a dir entry that contains the names of files that were in the /// dir at the time the dump was made /// </summary> public const byte LF_GNU_DUMPDIR = (byte)'D'; /// <summary> /// Solaris Extended Attribute File /// </summary> public const byte LF_EXTATTR = (byte)'E'; /// <summary> /// Inode (metadata only) no file content /// </summary> public const byte LF_META = (byte)'I'; /// <summary> /// Identifies the next file on the tape as having a long link name /// </summary> public const byte LF_GNU_LONGLINK = (byte)'K'; /// <summary> /// Identifies the next file on the tape as having a long name /// </summary> public const byte LF_GNU_LONGNAME = (byte)'L'; /// <summary> /// Continuation of a file that began on another volume /// </summary> public const byte LF_GNU_MULTIVOL = (byte)'M'; /// <summary> /// For storing filenames that dont fit in the main header (old GNU) /// </summary> public const byte LF_GNU_NAMES = (byte)'N'; /// <summary> /// GNU Sparse file /// </summary> public const byte LF_GNU_SPARSE = (byte)'S'; /// <summary> /// GNU Tape/volume header ignore on extraction /// </summary> public const byte LF_GNU_VOLHDR = (byte)'V'; /// <summary> /// The magic tag representing a POSIX tar archive. (includes trailing NULL) /// </summary> public const string TMAGIC = "ustar "; /// <summary> /// The magic tag representing an old GNU tar archive where version is included in magic and overwrites it /// </summary> public const string GNU_TMAGIC = "ustar "; const long timeConversionFactor = 10000000L; // 1 tick == 100 nanoseconds readonly static DateTime dateTime1970 = new DateTime(1970, 1, 1, 0, 0, 0, 0); #endregion #region Constructors /// <summary> /// Initialise a default TarHeader instance /// </summary> public TarHeader() { Magic = TMAGIC; Version = " "; Name = ""; LinkName = ""; UserId = defaultUserId; GroupId = defaultGroupId; UserName = defaultUser; GroupName = defaultGroupName; Size = 0; } #endregion #region Properties /// <summary> /// Get/set the name for this tar entry. /// </summary> /// <exception cref="ArgumentNullException">Thrown when attempting to set the property to null.</exception> public string Name { get { return name; } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } name = value; } } /// <summary> /// Get the name of this entry. /// </summary> /// <returns>The entry's name.</returns> [Obsolete("Use the Name property instead", true)] public string GetName() { return name; } /// <summary> /// Get/set the entry's Unix style permission mode. /// </summary> public int Mode { get { return mode; } set { mode = value; } } /// <summary> /// The entry's user id. /// </summary> /// <remarks> /// This is only directly relevant to unix systems. /// The default is zero. /// </remarks> public int UserId { get { return userId; } set { userId = value; } } /// <summary> /// Get/set the entry's group id. /// </summary> /// <remarks> /// This is only directly relevant to linux/unix systems. /// The default value is zero. /// </remarks> public int GroupId { get { return groupId; } set { groupId = value; } } /// <summary> /// Get/set the entry's size. /// </summary> /// <exception cref="ArgumentOutOfRangeException">Thrown when setting the size to less than zero.</exception> public long Size { get { return size; } set { if (value < 0) { throw new ArgumentOutOfRangeException(nameof(value), "Cannot be less than zero"); } size = value; } } /// <summary> /// Get/set the entry's modification time. /// </summary> /// <remarks> /// The modification time is only accurate to within a second. /// </remarks> /// <exception cref="ArgumentOutOfRangeException">Thrown when setting the date time to less than 1/1/1970.</exception> public DateTime ModTime { get { return modTime; } set { if (value < dateTime1970) { throw new ArgumentOutOfRangeException(nameof(value), "ModTime cannot be before Jan 1st 1970"); } modTime = new DateTime(value.Year, value.Month, value.Day, value.Hour, value.Minute, value.Second); } } /// <summary> /// Get the entry's checksum. This is only valid/updated after writing or reading an entry. /// </summary> public int Checksum { get { return checksum; } } /// <summary> /// Get value of true if the header checksum is valid, false otherwise. /// </summary> public bool IsChecksumValid { get { return isChecksumValid; } } /// <summary> /// Get/set the entry's type flag. /// </summary> public byte TypeFlag { get { return typeFlag; } set { typeFlag = value; } } /// <summary> /// The entry's link name. /// </summary> /// <exception cref="ArgumentNullException">Thrown when attempting to set LinkName to null.</exception> public string LinkName { get { return linkName; } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } linkName = value; } } /// <summary> /// Get/set the entry's magic tag. /// </summary> /// <exception cref="ArgumentNullException">Thrown when attempting to set Magic to null.</exception> public string Magic { get { return magic; } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } magic = value; } } /// <summary> /// The entry's version. /// </summary> /// <exception cref="ArgumentNullException">Thrown when attempting to set Version to null.</exception> public string Version { get { return version; } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } version = value; } } /// <summary> /// The entry's user name. /// </summary> public string UserName { get { return userName; } set { if (value != null) { userName = value.Substring(0, Math.Min(UNAMELEN, value.Length)); } else { string currentUser = Environment.UserName; if (currentUser.Length > UNAMELEN) { currentUser = currentUser.Substring(0, UNAMELEN); } userName = currentUser; } } } /// <summary> /// Get/set the entry's group name. /// </summary> /// <remarks> /// This is only directly relevant to unix systems. /// </remarks> public string GroupName { get { return groupName; } set { if (value == null) { groupName = "None"; } else { groupName = value; } } } /// <summary> /// Get/set the entry's major device number. /// </summary> public int DevMajor { get { return devMajor; } set { devMajor = value; } } /// <summary> /// Get/set the entry's minor device number. /// </summary> public int DevMinor { get { return devMinor; } set { devMinor = value; } } #endregion #region ICloneable Members /// <summary> /// Create a new <see cref="TarHeader"/> that is a copy of the current instance. /// </summary> /// <returns>A new <see cref="Object"/> that is a copy of the current instance.</returns> public object Clone() { return MemberwiseClone(); } #endregion /// <summary> /// Parse TarHeader information from a header buffer. /// </summary> /// <param name = "header"> /// The tar entry header buffer to get information from. /// </param> public void ParseBuffer(byte[] header) { if (header == null) { throw new ArgumentNullException(nameof(header)); } int offset = 0; name = ParseName(header, offset, NAMELEN).ToString(); offset += NAMELEN; mode = (int)ParseOctal(header, offset, MODELEN); offset += MODELEN; UserId = (int)ParseOctal(header, offset, UIDLEN); offset += UIDLEN; GroupId = (int)ParseOctal(header, offset, GIDLEN); offset += GIDLEN; Size = ParseBinaryOrOctal(header, offset, SIZELEN); offset += SIZELEN; ModTime = GetDateTimeFromCTime(ParseOctal(header, offset, MODTIMELEN)); offset += MODTIMELEN; checksum = (int)ParseOctal(header, offset, CHKSUMLEN); offset += CHKSUMLEN; TypeFlag = header[offset++]; LinkName = ParseName(header, offset, NAMELEN).ToString(); offset += NAMELEN; Magic = ParseName(header, offset, MAGICLEN).ToString(); offset += MAGICLEN; if (Magic == "ustar") { Version = ParseName(header, offset, VERSIONLEN).ToString(); offset += VERSIONLEN; UserName = ParseName(header, offset, UNAMELEN).ToString(); offset += UNAMELEN; GroupName = ParseName(header, offset, GNAMELEN).ToString(); offset += GNAMELEN; DevMajor = (int) ParseOctal(header, offset, DEVLEN); offset += DEVLEN; DevMinor = (int) ParseOctal(header, offset, DEVLEN); offset += DEVLEN; string prefix = ParseName(header, offset, PREFIXLEN).ToString(); if (!string.IsNullOrEmpty(prefix)) Name = prefix + '/' + Name; } isChecksumValid = Checksum == TarHeader.MakeCheckSum(header); } /// <summary> /// 'Write' header information to buffer provided, updating the <see cref="Checksum">check sum</see>. /// </summary> /// <param name="outBuffer">output buffer for header information</param> public void WriteHeader(byte[] outBuffer) { if (outBuffer == null) { throw new ArgumentNullException(nameof(outBuffer)); } int offset = 0; offset = GetNameBytes(Name, outBuffer, offset, NAMELEN); offset = GetOctalBytes(mode, outBuffer, offset, MODELEN); offset = GetOctalBytes(UserId, outBuffer, offset, UIDLEN); offset = GetOctalBytes(GroupId, outBuffer, offset, GIDLEN); offset = GetBinaryOrOctalBytes(Size, outBuffer, offset, SIZELEN); offset = GetOctalBytes(GetCTime(ModTime), outBuffer, offset, MODTIMELEN); int csOffset = offset; for (int c = 0; c < CHKSUMLEN; ++c) { outBuffer[offset++] = (byte)' '; } outBuffer[offset++] = TypeFlag; offset = GetNameBytes(LinkName, outBuffer, offset, NAMELEN); offset = GetAsciiBytes(Magic, 0, outBuffer, offset, MAGICLEN); offset = GetNameBytes(Version, outBuffer, offset, VERSIONLEN); offset = GetNameBytes(UserName, outBuffer, offset, UNAMELEN); offset = GetNameBytes(GroupName, outBuffer, offset, GNAMELEN); if ((TypeFlag == LF_CHR) || (TypeFlag == LF_BLK)) { offset = GetOctalBytes(DevMajor, outBuffer, offset, DEVLEN); offset = GetOctalBytes(DevMinor, outBuffer, offset, DEVLEN); } for (; offset < outBuffer.Length;) { outBuffer[offset++] = 0; } checksum = ComputeCheckSum(outBuffer); GetCheckSumOctalBytes(checksum, outBuffer, csOffset, CHKSUMLEN); isChecksumValid = true; } /// <summary> /// Get a hash code for the current object. /// </summary> /// <returns>A hash code for the current object.</returns> public override int GetHashCode() { return Name.GetHashCode(); } /// <summary> /// Determines if this instance is equal to the specified object. /// </summary> /// <param name="obj">The object to compare with.</param> /// <returns>true if the objects are equal, false otherwise.</returns> public override bool Equals(object obj) { var localHeader = obj as TarHeader; bool result; if (localHeader != null) { result = (name == localHeader.name) && (mode == localHeader.mode) && (UserId == localHeader.UserId) && (GroupId == localHeader.GroupId) && (Size == localHeader.Size) && (ModTime == localHeader.ModTime) && (Checksum == localHeader.Checksum) && (TypeFlag == localHeader.TypeFlag) && (LinkName == localHeader.LinkName) && (Magic == localHeader.Magic) && (Version == localHeader.Version) && (UserName == localHeader.UserName) && (GroupName == localHeader.GroupName) && (DevMajor == localHeader.DevMajor) && (DevMinor == localHeader.DevMinor); } else { result = false; } return result; } /// <summary> /// Set defaults for values used when constructing a TarHeader instance. /// </summary> /// <param name="userId">Value to apply as a default for userId.</param> /// <param name="userName">Value to apply as a default for userName.</param> /// <param name="groupId">Value to apply as a default for groupId.</param> /// <param name="groupName">Value to apply as a default for groupName.</param> static internal void SetValueDefaults(int userId, string userName, int groupId, string groupName) { defaultUserId = userIdAsSet = userId; defaultUser = userNameAsSet = userName; defaultGroupId = groupIdAsSet = groupId; defaultGroupName = groupNameAsSet = groupName; } static internal void RestoreSetValues() { defaultUserId = userIdAsSet; defaultUser = userNameAsSet; defaultGroupId = groupIdAsSet; defaultGroupName = groupNameAsSet; } // Return value that may be stored in octal or binary. Length must exceed 8. // static private long ParseBinaryOrOctal(byte[] header, int offset, int length) { if (header[offset] >= 0x80) { // File sizes over 8GB are stored in 8 right-justified bytes of binary indicated by setting the high-order bit of the leftmost byte of a numeric field. long result = 0; for (int pos = length - 8; pos < length; pos++) { result = result << 8 | header[offset + pos]; } return result; } return ParseOctal(header, offset, length); } /// <summary> /// Parse an octal string from a header buffer. /// </summary> /// <param name = "header">The header buffer from which to parse.</param> /// <param name = "offset">The offset into the buffer from which to parse.</param> /// <param name = "length">The number of header bytes to parse.</param> /// <returns>The long equivalent of the octal string.</returns> static public long ParseOctal(byte[] header, int offset, int length) { if (header == null) { throw new ArgumentNullException(nameof(header)); } long result = 0; bool stillPadding = true; int end = offset + length; for (int i = offset; i < end; ++i) { if (header[i] == 0) { break; } if (header[i] == (byte)' ' || header[i] == '0') { if (stillPadding) { continue; } if (header[i] == (byte)' ') { break; } } stillPadding = false; result = (result << 3) + (header[i] - '0'); } return result; } /// <summary> /// Parse a name from a header buffer. /// </summary> /// <param name="header"> /// The header buffer from which to parse. /// </param> /// <param name="offset"> /// The offset into the buffer from which to parse. /// </param> /// <param name="length"> /// The number of header bytes to parse. /// </param> /// <returns> /// The name parsed. /// </returns> static public StringBuilder ParseName(byte[] header, int offset, int length) { if (header == null) { throw new ArgumentNullException(nameof(header)); } if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset), "Cannot be less than zero"); } if (length < 0) { throw new ArgumentOutOfRangeException(nameof(length), "Cannot be less than zero"); } if (offset + length > header.Length) { throw new ArgumentException("Exceeds header size", nameof(length)); } var result = new StringBuilder(length); for (int i = offset; i < offset + length; ++i) { if (header[i] == 0) { break; } result.Append((char)header[i]); } return result; } /// <summary> /// Add <paramref name="name">name</paramref> to the buffer as a collection of bytes /// </summary> /// <param name="name">The name to add</param> /// <param name="nameOffset">The offset of the first character</param> /// <param name="buffer">The buffer to add to</param> /// <param name="bufferOffset">The index of the first byte to add</param> /// <param name="length">The number of characters/bytes to add</param> /// <returns>The next free index in the <paramref name="buffer"/></returns> public static int GetNameBytes(StringBuilder name, int nameOffset, byte[] buffer, int bufferOffset, int length) { if (name == null) { throw new ArgumentNullException(nameof(name)); } if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } return GetNameBytes(name.ToString(), nameOffset, buffer, bufferOffset, length); } /// <summary> /// Add <paramref name="name">name</paramref> to the buffer as a collection of bytes /// </summary> /// <param name="name">The name to add</param> /// <param name="nameOffset">The offset of the first character</param> /// <param name="buffer">The buffer to add to</param> /// <param name="bufferOffset">The index of the first byte to add</param> /// <param name="length">The number of characters/bytes to add</param> /// <returns>The next free index in the <paramref name="buffer"/></returns> public static int GetNameBytes(string name, int nameOffset, byte[] buffer, int bufferOffset, int length) { if (name == null) { throw new ArgumentNullException(nameof(name)); } if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } int i; for (i = 0 ; i < length && nameOffset + i < name.Length; ++i) { buffer[bufferOffset + i] = (byte)name[nameOffset + i]; } for (; i < length; ++i) { buffer[bufferOffset + i] = 0; } return bufferOffset + length; } /// <summary> /// Add an entry name to the buffer /// </summary> /// <param name="name"> /// The name to add /// </param> /// <param name="buffer"> /// The buffer to add to /// </param> /// <param name="offset"> /// The offset into the buffer from which to start adding /// </param> /// <param name="length"> /// The number of header bytes to add /// </param> /// <returns> /// The index of the next free byte in the buffer /// </returns> public static int GetNameBytes(StringBuilder name, byte[] buffer, int offset, int length) { if (name == null) { throw new ArgumentNullException(nameof(name)); } if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } return GetNameBytes(name.ToString(), 0, buffer, offset, length); } /// <summary> /// Add an entry name to the buffer /// </summary> /// <param name="name">The name to add</param> /// <param name="buffer">The buffer to add to</param> /// <param name="offset">The offset into the buffer from which to start adding</param> /// <param name="length">The number of header bytes to add</param> /// <returns>The index of the next free byte in the buffer</returns> public static int GetNameBytes(string name, byte[] buffer, int offset, int length) { if (name == null) { throw new ArgumentNullException(nameof(name)); } if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } return GetNameBytes(name, 0, buffer, offset, length); } /// <summary> /// Add a string to a buffer as a collection of ascii bytes. /// </summary> /// <param name="toAdd">The string to add</param> /// <param name="nameOffset">The offset of the first character to add.</param> /// <param name="buffer">The buffer to add to.</param> /// <param name="bufferOffset">The offset to start adding at.</param> /// <param name="length">The number of ascii characters to add.</param> /// <returns>The next free index in the buffer.</returns> public static int GetAsciiBytes(string toAdd, int nameOffset, byte[] buffer, int bufferOffset, int length) { if (toAdd == null) { throw new ArgumentNullException(nameof(toAdd)); } if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } for (int i = 0; i < length && nameOffset + i < toAdd.Length; ++i) { buffer[bufferOffset + i] = (byte)toAdd[nameOffset + i]; } return bufferOffset + length; } /// <summary> /// Put an octal representation of a value into a buffer /// </summary> /// <param name = "value"> /// the value to be converted to octal /// </param> /// <param name = "buffer"> /// buffer to store the octal string /// </param> /// <param name = "offset"> /// The offset into the buffer where the value starts /// </param> /// <param name = "length"> /// The length of the octal string to create /// </param> /// <returns> /// The offset of the character next byte after the octal string /// </returns> public static int GetOctalBytes(long value, byte[] buffer, int offset, int length) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } int localIndex = length - 1; // Either a space or null is valid here. We use NULL as per GNUTar buffer[offset + localIndex] = 0; --localIndex; if (value > 0) { for (long v = value; (localIndex >= 0) && (v > 0); --localIndex) { buffer[offset + localIndex] = (byte)((byte)'0' + (byte)(v & 7)); v >>= 3; } } for (; localIndex >= 0; --localIndex) { buffer[offset + localIndex] = (byte)'0'; } return offset + length; } /// <summary> /// Put an octal or binary representation of a value into a buffer /// </summary> /// <param name = "value">Value to be convert to octal</param> /// <param name = "buffer">The buffer to update</param> /// <param name = "offset">The offset into the buffer to store the value</param> /// <param name = "length">The length of the octal string. Must be 12.</param> /// <returns>Index of next byte</returns> private static int GetBinaryOrOctalBytes(long value, byte[] buffer, int offset, int length) { if (value > 0x1FFFFFFFF) { // Octal 77777777777 (11 digits) // Put value as binary, right-justified into the buffer. Set high order bit of left-most byte. for (int pos = length - 1; pos > 0; pos--) { buffer[offset + pos] = (byte)value; value = value >> 8; } buffer[offset] = 0x80; return offset + length; } return GetOctalBytes(value, buffer, offset, length); } /// <summary> /// Add the checksum integer to header buffer. /// </summary> /// <param name = "value"></param> /// <param name = "buffer">The header buffer to set the checksum for</param> /// <param name = "offset">The offset into the buffer for the checksum</param> /// <param name = "length">The number of header bytes to update. /// It's formatted differently from the other fields: it has 6 digits, a /// null, then a space -- rather than digits, a space, then a null. /// The final space is already there, from checksumming /// </param> /// <returns>The modified buffer offset</returns> static void GetCheckSumOctalBytes(long value, byte[] buffer, int offset, int length) { GetOctalBytes(value, buffer, offset, length - 1); } /// <summary> /// Compute the checksum for a tar entry header. /// The checksum field must be all spaces prior to this happening /// </summary> /// <param name = "buffer">The tar entry's header buffer.</param> /// <returns>The computed checksum.</returns> static int ComputeCheckSum(byte[] buffer) { int sum = 0; for (int i = 0; i < buffer.Length; ++i) { sum += buffer[i]; } return sum; } /// <summary> /// Make a checksum for a tar entry ignoring the checksum contents. /// </summary> /// <param name = "buffer">The tar entry's header buffer.</param> /// <returns>The checksum for the buffer</returns> static int MakeCheckSum(byte[] buffer) { int sum = 0; for (int i = 0; i < CHKSUMOFS; ++i) { sum += buffer[i]; } for (int i = 0; i < CHKSUMLEN; ++i) { sum += (byte)' '; } for (int i = CHKSUMOFS + CHKSUMLEN; i < buffer.Length; ++i) { sum += buffer[i]; } return sum; } static int GetCTime(DateTime dateTime) { return unchecked((int)((dateTime.Ticks - dateTime1970.Ticks) / timeConversionFactor)); } static DateTime GetDateTimeFromCTime(long ticks) { DateTime result; try { result = new DateTime(dateTime1970.Ticks + ticks * timeConversionFactor); } catch (ArgumentOutOfRangeException) { result = dateTime1970; } return result; } #region Instance Fields string name; int mode; int userId; int groupId; long size; DateTime modTime; int checksum; bool isChecksumValid; byte typeFlag; string linkName; string magic; string version; string userName; string groupName; int devMajor; int devMinor; #endregion #region Class Fields // Values used during recursive operations. static internal int userIdAsSet; static internal int groupIdAsSet; static internal string userNameAsSet; static internal string groupNameAsSet = "None"; static internal int defaultUserId; static internal int defaultGroupId; static internal string defaultGroupName = "None"; static internal string defaultUser; #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.Diagnostics; using System.Text; namespace System.IO { public static partial class Path { public static readonly char DirectorySeparatorChar = '\\'; public static readonly char VolumeSeparatorChar = ':'; public static readonly char PathSeparator = ';'; private const string DirectorySeparatorCharAsString = "\\"; private static readonly char[] InvalidFileNameChars = { '\"', '<', '>', '|', '\0', (char)1, (char)2, (char)3, (char)4, (char)5, (char)6, (char)7, (char)8, (char)9, (char)10, (char)11, (char)12, (char)13, (char)14, (char)15, (char)16, (char)17, (char)18, (char)19, (char)20, (char)21, (char)22, (char)23, (char)24, (char)25, (char)26, (char)27, (char)28, (char)29, (char)30, (char)31, ':', '*', '?', '\\', '/' }; // The max total path is 260, and the max individual component length is 255. // For example, D:\<256 char file name> isn't legal, even though it's under 260 chars. internal static readonly int MaxPath = 260; internal static readonly int MaxLongPath = short.MaxValue; private static bool IsDirectoryOrVolumeSeparator(char c) { return PathInternal.IsDirectorySeparator(c) || VolumeSeparatorChar == c; } // Expands the given path to a fully qualified path. [System.Security.SecuritySafeCritical] public static string GetFullPath(string path) { if (path == null) throw new ArgumentNullException("path"); string fullPath = NormalizeAndValidatePath(path); // Emulate FileIOPermissions checks, retained for compatibility (normal invalid characters have already been checked) if (PathInternal.HasWildCardCharacters(fullPath)) throw new ArgumentException(SR.Argument_InvalidPathChars, "path"); return fullPath; } /// <summary> /// Checks for known bad extended paths (paths that start with \\?\) /// </summary> /// <returns>'true' if the path passes validity checks.</returns> private static bool ValidateExtendedPath(string path) { if (path.Length == PathInternal.ExtendedPathPrefix.Length) { // Effectively empty and therefore invalid return false; } if (path.StartsWith(PathInternal.UncExtendedPathPrefix, StringComparison.Ordinal)) { // UNC specific checks if (path.Length == PathInternal.UncExtendedPathPrefix.Length || path[PathInternal.UncExtendedPathPrefix.Length] == DirectorySeparatorChar) { // Effectively empty and therefore invalid (\\?\UNC\ or \\?\UNC\\) return false; } int serverShareSeparator = path.IndexOf(DirectorySeparatorChar, PathInternal.UncExtendedPathPrefix.Length); if (serverShareSeparator == -1 || serverShareSeparator == path.Length - 1) { // Need at least a Server\Share return false; } } // Segments can't be empty "\\" or contain *just* "." or ".." char twoBack = '?'; char oneBack = DirectorySeparatorChar; char currentCharacter; bool periodSegment = false; for (int i = PathInternal.ExtendedPathPrefix.Length; i < path.Length; i++) { currentCharacter = path[i]; switch (currentCharacter) { case '\\': if (oneBack == DirectorySeparatorChar || periodSegment) throw new ArgumentException(SR.Arg_PathIllegal); periodSegment = false; break; case '.': periodSegment = (oneBack == DirectorySeparatorChar || (twoBack == DirectorySeparatorChar && oneBack == '.')); break; default: periodSegment = false; break; } twoBack = oneBack; oneBack = currentCharacter; } if (periodSegment) { return false; } return true; } /// <summary> /// Normalize the path and check for bad characters or other invalid syntax. /// </summary> /// <remarks> /// The legacy NormalizePath /// </remarks> private static string NormalizeAndValidatePath(string path) { Debug.Assert(path != null, "path can't be null"); // Embedded null characters are the only invalid character case we want to check up front. // This is because the nulls will signal the end of the string to Win32 and therefore have // unpredictable results. Other invalid characters we give a chance to be normalized out. if (path.IndexOf('\0') != -1) throw new ArgumentException(SR.Argument_InvalidPathChars, "path"); // Toss out paths with colons that aren't a valid drive specifier. // Cannot start with a colon and can only be of the form "C:" or "\\?\C:". // (Note that we used to explicitly check "http:" and "file:"- these are caught by this check now.) int startIndex = PathInternal.PathStartSkip(path); bool isExtended = path.Length >= PathInternal.ExtendedPathPrefix.Length + startIndex && path.IndexOf(PathInternal.ExtendedPathPrefix, startIndex, PathInternal.ExtendedPathPrefix.Length, StringComparison.Ordinal) >= 0; if (isExtended) { startIndex += PathInternal.ExtendedPathPrefix.Length; } // Move past the colon startIndex += 2; if ((path.Length > 0 && path[0] == VolumeSeparatorChar) || (path.Length >= startIndex && path[startIndex - 1] == VolumeSeparatorChar && !PathInternal.IsValidDriveChar(path[startIndex - 2])) || (path.Length > startIndex && path.IndexOf(VolumeSeparatorChar, startIndex) != -1)) { throw new NotSupportedException(SR.Argument_PathFormatNotSupported); } if (isExtended) { // If the path is in extended syntax, we don't need to normalize, but we still do some basic validity checks if (!ValidateExtendedPath(path)) { throw new ArgumentException(SR.Arg_PathIllegal); } // \\?\GLOBALROOT gives access to devices out of the scope of the current user, we // don't want to allow this for security reasons. // https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247.aspx#nt_namespaces if (path.StartsWith(@"\\?\globalroot", StringComparison.OrdinalIgnoreCase)) throw new ArgumentException(SR.Arg_PathGlobalRoot); // Look for illegal path characters. PathInternal.CheckInvalidPathChars(path); return path; } else { // Technically this doesn't matter but we used to throw for this case if (String.IsNullOrWhiteSpace(path)) throw new ArgumentException(SR.Arg_PathIllegal); return PathHelper.Normalize(path, checkInvalidCharacters: true, expandShortPaths: true); } } [System.Security.SecuritySafeCritical] public static string GetTempPath() { StringBuilder sb = StringBuilderCache.Acquire(MaxPath); uint r = Interop.mincore.GetTempPathW(MaxPath, sb); if (r == 0) throw Win32Marshal.GetExceptionForLastWin32Error(); return GetFullPath(StringBuilderCache.GetStringAndRelease(sb)); } [System.Security.SecurityCritical] private static string InternalGetTempFileName(bool checkHost) { // checkHost was originally intended for file security checks, but is ignored. string path = GetTempPath(); StringBuilder sb = StringBuilderCache.Acquire(MaxPath); uint r = Interop.mincore.GetTempFileNameW(path, "tmp", 0, sb); if (r == 0) throw Win32Marshal.GetExceptionForLastWin32Error(); return StringBuilderCache.GetStringAndRelease(sb); } // Tests if the given path contains a root. A path is considered rooted // if it starts with a backslash ("\") or a drive letter and a colon (":"). public static bool IsPathRooted(string path) { if (path != null) { PathInternal.CheckInvalidPathChars(path); int length = path.Length; if ((length >= 1 && PathInternal.IsDirectorySeparator(path[0])) || (length >= 2 && path[1] == VolumeSeparatorChar)) return true; } return false; } // Returns the root portion of the given path. The resulting string // consists of those rightmost characters of the path that constitute the // root of the path. Possible patterns for the resulting string are: An // empty string (a relative path on the current drive), "\" (an absolute // path on the current drive), "X:" (a relative path on a given drive, // where X is the drive letter), "X:\" (an absolute path on a given drive), // and "\\server\share" (a UNC path for a given server and share name). // The resulting string is null if path is null. public static string GetPathRoot(string path) { if (path == null) return null; PathInternal.CheckInvalidPathChars(path); // Need to return the normalized directory separator path = PathInternal.NormalizeDirectorySeparators(path); int pathRoot = PathInternal.GetRootLength(path); return pathRoot <= 0 ? string.Empty : path.Substring(0, pathRoot); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace Samples.RegistrationList.Web.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using Nop.Core.Domain.Common; using Nop.Core.Domain.Customers; using Nop.Core.Domain.Discounts; using Nop.Core.Domain.Payments; using Nop.Core.Domain.Shipping; using Nop.Core.Domain.Tax; namespace Nop.Core.Domain.Orders { /// <summary> /// Represents an order /// </summary> public partial class Order : BaseEntity { private ICollection<DiscountUsageHistory> _discountUsageHistory; private ICollection<GiftCardUsageHistory> _giftCardUsageHistory; private ICollection<OrderNote> _orderNotes; private ICollection<OrderItem> _orderItems; private ICollection<Shipment> _shipments; #region Utilities protected virtual SortedDictionary<decimal, decimal> ParseTaxRates(string taxRatesStr) { var taxRatesDictionary = new SortedDictionary<decimal, decimal>(); if (String.IsNullOrEmpty(taxRatesStr)) return taxRatesDictionary; string[] lines = taxRatesStr.Split(new [] { ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (string line in lines) { if (String.IsNullOrEmpty(line.Trim())) continue; string[] taxes = line.Split(new [] { ':' }); if (taxes.Length == 2) { try { decimal taxRate = decimal.Parse(taxes[0].Trim(), CultureInfo.InvariantCulture); decimal taxValue = decimal.Parse(taxes[1].Trim(), CultureInfo.InvariantCulture); taxRatesDictionary.Add(taxRate, taxValue); } catch (Exception exc) { Debug.WriteLine(exc.ToString()); } } } //add at least one tax rate (0%) if (taxRatesDictionary.Count == 0) taxRatesDictionary.Add(decimal.Zero, decimal.Zero); return taxRatesDictionary; } #endregion #region Properties /// <summary> /// Gets or sets the order identifier /// </summary> public Guid OrderGuid { get; set; } /// <summary> /// Gets or sets the store identifier /// </summary> public int StoreId { get; set; } /// <summary> /// Gets or sets the customer identifier /// </summary> public int CustomerId { get; set; } /// <summary> /// Gets or sets the billing address identifier /// </summary> public int BillingAddressId { get; set; } /// <summary> /// Gets or sets the shipping address identifier /// </summary> public int? ShippingAddressId { get; set; } /// <summary> /// Gets or sets a value indicating whether a customer chose "pick up in store" shipping option /// </summary> public bool PickUpInStore { get; set; } /// <summary> /// Gets or sets an order status identifier /// </summary> public int OrderStatusId { get; set; } /// <summary> /// Gets or sets the shipping status identifier /// </summary> public int ShippingStatusId { get; set; } /// <summary> /// Gets or sets the payment status identifier /// </summary> public int PaymentStatusId { get; set; } /// <summary> /// Gets or sets the payment method system name /// </summary> public string PaymentMethodSystemName { get; set; } /// <summary> /// Gets or sets the customer currency code (at the moment of order placing) /// </summary> public string CustomerCurrencyCode { get; set; } /// <summary> /// Gets or sets the currency rate /// </summary> public decimal CurrencyRate { get; set; } /// <summary> /// Gets or sets the customer tax display type identifier /// </summary> public int CustomerTaxDisplayTypeId { get; set; } /// <summary> /// Gets or sets the VAT number (the European Union Value Added Tax) /// </summary> public string VatNumber { get; set; } /// <summary> /// Gets or sets the order subtotal (incl tax) /// </summary> public decimal OrderSubtotalInclTax { get; set; } /// <summary> /// Gets or sets the order subtotal (excl tax) /// </summary> public decimal OrderSubtotalExclTax { get; set; } /// <summary> /// Gets or sets the order subtotal discount (incl tax) /// </summary> public decimal OrderSubTotalDiscountInclTax { get; set; } /// <summary> /// Gets or sets the order subtotal discount (excl tax) /// </summary> public decimal OrderSubTotalDiscountExclTax { get; set; } /// <summary> /// Gets or sets the order shipping (incl tax) /// </summary> public decimal OrderShippingInclTax { get; set; } /// <summary> /// Gets or sets the order shipping (excl tax) /// </summary> public decimal OrderShippingExclTax { get; set; } /// <summary> /// Gets or sets the payment method additional fee (incl tax) /// </summary> public decimal PaymentMethodAdditionalFeeInclTax { get; set; } /// <summary> /// Gets or sets the payment method additional fee (excl tax) /// </summary> public decimal PaymentMethodAdditionalFeeExclTax { get; set; } /// <summary> /// Gets or sets the tax rates /// </summary> public string TaxRates { get; set; } /// <summary> /// Gets or sets the order tax /// </summary> public decimal OrderTax { get; set; } /// <summary> /// Gets or sets the order discount (applied to order total) /// </summary> public decimal OrderDiscount { get; set; } /// <summary> /// Gets or sets the order total /// </summary> public decimal OrderTotal { get; set; } /// <summary> /// Gets or sets the refunded amount /// </summary> public decimal RefundedAmount { get; set; } /// <summary> /// Gets or sets the value indicating whether reward points were earned for this order /// </summary> public bool RewardPointsWereAdded { get; set; } /// <summary> /// Gets or sets the checkout attribute description /// </summary> public string CheckoutAttributeDescription { get; set; } /// <summary> /// Gets or sets the checkout attributes in XML format /// </summary> public string CheckoutAttributesXml { get; set; } /// <summary> /// Gets or sets the customer language identifier /// </summary> public int CustomerLanguageId { get; set; } /// <summary> /// Gets or sets the affiliate identifier /// </summary> public int AffiliateId { get; set; } /// <summary> /// Gets or sets the customer IP address /// </summary> public string CustomerIp { get; set; } /// <summary> /// Gets or sets a value indicating whether storing of credit card number is allowed /// </summary> public bool AllowStoringCreditCardNumber { get; set; } /// <summary> /// Gets or sets the card type /// </summary> public string CardType { get; set; } /// <summary> /// Gets or sets the card name /// </summary> public string CardName { get; set; } /// <summary> /// Gets or sets the card number /// </summary> public string CardNumber { get; set; } /// <summary> /// Gets or sets the masked credit card number /// </summary> public string MaskedCreditCardNumber { get; set; } /// <summary> /// Gets or sets the card CVV2 /// </summary> public string CardCvv2 { get; set; } /// <summary> /// Gets or sets the card expiration month /// </summary> public string CardExpirationMonth { get; set; } /// <summary> /// Gets or sets the card expiration year /// </summary> public string CardExpirationYear { get; set; } /// <summary> /// Gets or sets the authorization transaction identifier /// </summary> public string AuthorizationTransactionId { get; set; } /// <summary> /// Gets or sets the authorization transaction code /// </summary> public string AuthorizationTransactionCode { get; set; } /// <summary> /// Gets or sets the authorization transaction result /// </summary> public string AuthorizationTransactionResult { get; set; } /// <summary> /// Gets or sets the capture transaction identifier /// </summary> public string CaptureTransactionId { get; set; } /// <summary> /// Gets or sets the capture transaction result /// </summary> public string CaptureTransactionResult { get; set; } /// <summary> /// Gets or sets the subscription transaction identifier /// </summary> public string SubscriptionTransactionId { get; set; } /// <summary> /// Gets or sets the paid date and time /// </summary> public DateTime? PaidDateUtc { get; set; } /// <summary> /// Gets or sets the shipping method /// </summary> public string ShippingMethod { get; set; } /// <summary> /// Gets or sets the shipping rate computation method identifier /// </summary> public string ShippingRateComputationMethodSystemName { get; set; } /// <summary> /// Gets or sets the serialized CustomValues (values from ProcessPaymentRequest) /// </summary> public string CustomValuesXml { get; set; } /// <summary> /// Gets or sets a value indicating whether the entity has been deleted /// </summary> public bool Deleted { get; set; } /// <summary> /// Gets or sets the date and time of order creation /// </summary> public DateTime CreatedOnUtc { get; set; } #endregion #region Navigation properties /// <summary> /// Gets or sets the customer /// </summary> public virtual Customer Customer { get; set; } /// <summary> /// Gets or sets the billing address /// </summary> public virtual Address BillingAddress { get; set; } /// <summary> /// Gets or sets the shipping address /// </summary> public virtual Address ShippingAddress { get; set; } /// <summary> /// Gets or sets the reward points history record /// </summary> public virtual RewardPointsHistory RedeemedRewardPointsEntry { get; set; } /// <summary> /// Gets or sets discount usage history /// </summary> public virtual ICollection<DiscountUsageHistory> DiscountUsageHistory { get { return _discountUsageHistory ?? (_discountUsageHistory = new List<DiscountUsageHistory>()); } protected set { _discountUsageHistory = value; } } /// <summary> /// Gets or sets gift card usage history (gift card that were used with this order) /// </summary> public virtual ICollection<GiftCardUsageHistory> GiftCardUsageHistory { get { return _giftCardUsageHistory ?? (_giftCardUsageHistory = new List<GiftCardUsageHistory>()); } protected set { _giftCardUsageHistory = value; } } /// <summary> /// Gets or sets order notes /// </summary> public virtual ICollection<OrderNote> OrderNotes { get { return _orderNotes ?? (_orderNotes = new List<OrderNote>()); } protected set { _orderNotes = value; } } /// <summary> /// Gets or sets order items /// </summary> public virtual ICollection<OrderItem> OrderItems { get { return _orderItems ?? (_orderItems = new List<OrderItem>()); } protected set { _orderItems = value; } } /// <summary> /// Gets or sets shipments /// </summary> public virtual ICollection<Shipment> Shipments { get { return _shipments ?? (_shipments = new List<Shipment>()); } protected set { _shipments = value; } } #endregion #region Custom properties /// <summary> /// Gets or sets the order status /// </summary> public OrderStatus OrderStatus { get { return (OrderStatus)this.OrderStatusId; } set { this.OrderStatusId = (int)value; } } /// <summary> /// Gets or sets the payment status /// </summary> public PaymentStatus PaymentStatus { get { return (PaymentStatus)this.PaymentStatusId; } set { this.PaymentStatusId = (int)value; } } /// <summary> /// Gets or sets the shipping status /// </summary> public ShippingStatus ShippingStatus { get { return (ShippingStatus)this.ShippingStatusId; } set { this.ShippingStatusId = (int)value; } } /// <summary> /// Gets or sets the customer tax display type /// </summary> public TaxDisplayType CustomerTaxDisplayType { get { return (TaxDisplayType)this.CustomerTaxDisplayTypeId; } set { this.CustomerTaxDisplayTypeId = (int)value; } } /// <summary> /// Gets the applied tax rates /// </summary> public SortedDictionary<decimal, decimal> TaxRatesDictionary { get { return ParseTaxRates(this.TaxRates); } } #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; using System.Runtime.InteropServices; using Point = Windows.Foundation.Point; using Windows.Foundation; #pragma warning disable 436 // Redefining types from Windows.Foundation namespace Windows.UI.Xaml.Media { // // Matrix is the managed projection of Windows.UI.Xaml.Media.Matrix. Any changes to the layout of // this type must be exactly mirrored on the native WinRT side as well. // // Note that this type is owned by the Jupiter team. Please contact them before making any // changes here. // [StructLayout(LayoutKind.Sequential)] public struct Matrix : IFormattable { public Matrix(double m11, double m12, double m21, double m22, double offsetX, double offsetY) { _m11 = m11; _m12 = m12; _m21 = m21; _m22 = m22; _offsetX = offsetX; _offsetY = offsetY; } // the transform is identity by default private static Matrix s_identity = CreateIdentity(); public double M11 { get { return _m11; } set { _m11 = value; } } public double M12 { get { return _m12; } set { _m12 = value; } } public double M21 { get { return _m21; } set { _m21 = value; } } public double M22 { get { return _m22; } set { _m22 = value; } } public double OffsetX { get { return _offsetX; } set { _offsetX = value; } } public double OffsetY { get { return _offsetY; } set { _offsetY = value; } } public static Matrix Identity { get { return s_identity; } } public bool IsIdentity { get { return (_m11 == 1 && _m12 == 0 && _m21 == 0 && _m22 == 1 && _offsetX == 0 && _offsetY == 0); } } public override string ToString() { // Delegate to the internal method which implements all ToString calls. return ConvertToString(null /* format string */, null /* format provider */); } public string ToString(IFormatProvider provider) { // Delegate to the internal method which implements all ToString calls. return ConvertToString(null /* format string */, provider); } string IFormattable.ToString(string format, IFormatProvider provider) { // Delegate to the internal method which implements all ToString calls. return ConvertToString(format, provider); } private string ConvertToString(string format, IFormatProvider provider) { if (IsIdentity) { return "Identity"; } // Helper to get the numeric list separator for a given culture. char separator = TokenizerHelper.GetNumericListSeparator(provider); return string.Format(provider, "{1:" + format + "}{0}{2:" + format + "}{0}{3:" + format + "}{0}{4:" + format + "}{0}{5:" + format + "}{0}{6:" + format + "}", separator, _m11, _m12, _m21, _m22, _offsetX, _offsetY); } public Point Transform(Point point) { float x = (float)point.X; float y = (float)point.Y; this.MultiplyPoint(ref x, ref y); Point point2 = new Point(x, y); return point2; } public override int GetHashCode() { // Perform field-by-field XOR of HashCodes return M11.GetHashCode() ^ M12.GetHashCode() ^ M21.GetHashCode() ^ M22.GetHashCode() ^ OffsetX.GetHashCode() ^ OffsetY.GetHashCode(); } public override bool Equals(object o) { return o is Matrix && Matrix.Equals(this, (Matrix)o); } public bool Equals(Matrix value) { return Matrix.Equals(this, value); } public static bool operator ==(Matrix matrix1, Matrix matrix2) { return matrix1.M11 == matrix2.M11 && matrix1.M12 == matrix2.M12 && matrix1.M21 == matrix2.M21 && matrix1.M22 == matrix2.M22 && matrix1.OffsetX == matrix2.OffsetX && matrix1.OffsetY == matrix2.OffsetY; } public static bool operator !=(Matrix matrix1, Matrix matrix2) { return !(matrix1 == matrix2); } private static Matrix CreateIdentity() { Matrix matrix = new Matrix(); matrix.SetMatrix(1, 0, 0, 1, 0, 0); return matrix; } private void SetMatrix(double m11, double m12, double m21, double m22, double offsetX, double offsetY) { _m11 = m11; _m12 = m12; _m21 = m21; _m22 = m22; _offsetX = offsetX; _offsetY = offsetY; } private void MultiplyPoint(ref float x, ref float y) { double num = (y * _m21) + _offsetX; double num2 = (x * _m12) + _offsetY; x *= (float)_m11; x += (float)num; y *= (float)_m22; y += (float)num2; } private static bool Equals(Matrix matrix1, Matrix matrix2) { return matrix1.M11.Equals(matrix2.M11) && matrix1.M12.Equals(matrix2.M12) && matrix1.M21.Equals(matrix2.M21) && matrix1.M22.Equals(matrix2.M22) && matrix1.OffsetX.Equals(matrix2.OffsetX) && matrix1.OffsetY.Equals(matrix2.OffsetY); } private double _m11; private double _m12; private double _m21; private double _m22; private double _offsetX; private double _offsetY; } } #pragma warning restore 436
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; using System.Xml; using System.Xml.XPath; using System.Xml.Xsl; namespace MS.Internal.Xml.XPath { internal sealed class LogicalExpr : ValueQuery { Operator.Op op; Query opnd1; Query opnd2; public LogicalExpr(Operator.Op op, Query opnd1, Query opnd2) { Debug.Assert( Operator.Op.LT == op || Operator.Op.GT == op || Operator.Op.LE == op || Operator.Op.GE == op || Operator.Op.EQ == op || Operator.Op.NE == op ); this.op = op; this.opnd1 = opnd1; this.opnd2 = opnd2; } private LogicalExpr(LogicalExpr other) : base(other) { this.op = other.op; this.opnd1 = Clone(other.opnd1); this.opnd2 = Clone(other.opnd2); } public override void SetXsltContext(XsltContext context) { opnd1.SetXsltContext(context); opnd2.SetXsltContext(context); } public override object Evaluate(XPathNodeIterator nodeIterator) { Operator.Op op = this.op; object val1 = this.opnd1.Evaluate(nodeIterator); object val2 = this.opnd2.Evaluate(nodeIterator); int type1 = (int)GetXPathType(val1); int type2 = (int)GetXPathType(val2); if (type1 < type2) { op = Operator.InvertOperator(op); object valTemp = val1; val1 = val2; val2 = valTemp; int typeTmp = type1; type1 = type2; type2 = typeTmp; } if (op == Operator.Op.EQ || op == Operator.Op.NE) { return CompXsltE[type1][type2](op, val1, val2); } else { return CompXsltO[type1][type2](op, val1, val2); } } delegate bool cmpXslt(Operator.Op op, object val1, object val2); // Number, String, Boolean, NodeSet, Navigator private static readonly cmpXslt[][] CompXsltE = { new cmpXslt[] { new cmpXslt(cmpNumberNumber), null , null , null , null }, new cmpXslt[] { new cmpXslt(cmpStringNumber), new cmpXslt(cmpStringStringE), null , null , null }, new cmpXslt[] { new cmpXslt(cmpBoolNumberE ), new cmpXslt(cmpBoolStringE ), new cmpXslt(cmpBoolBoolE ), null , null }, new cmpXslt[] { new cmpXslt(cmpQueryNumber ), new cmpXslt(cmpQueryStringE ), new cmpXslt(cmpQueryBoolE ), new cmpXslt(cmpQueryQueryE ), null }, new cmpXslt[] { new cmpXslt(cmpRtfNumber ), new cmpXslt(cmpRtfStringE ), new cmpXslt(cmpRtfBoolE ), new cmpXslt(cmpRtfQueryE ), new cmpXslt(cmpRtfRtfE) }, }; private static readonly cmpXslt[][] CompXsltO = { new cmpXslt[] { new cmpXslt(cmpNumberNumber), null , null , null , null }, new cmpXslt[] { new cmpXslt(cmpStringNumber), new cmpXslt(cmpStringStringO), null , null , null }, new cmpXslt[] { new cmpXslt(cmpBoolNumberO ), new cmpXslt(cmpBoolStringO ), new cmpXslt(cmpBoolBoolO ), null , null }, new cmpXslt[] { new cmpXslt(cmpQueryNumber ), new cmpXslt(cmpQueryStringO ), new cmpXslt(cmpQueryBoolO ), new cmpXslt(cmpQueryQueryO ), null }, new cmpXslt[] { new cmpXslt(cmpRtfNumber ), new cmpXslt(cmpRtfStringO ), new cmpXslt(cmpRtfBoolO ), new cmpXslt(cmpRtfQueryO ), new cmpXslt(cmpRtfRtfO) }, }; /*cmpXslt:*/ static bool cmpQueryQueryE(Operator.Op op, object val1, object val2) { Debug.Assert(op == Operator.Op.EQ || op == Operator.Op.NE); bool isEQ = (op == Operator.Op.EQ); NodeSet n1 = new NodeSet(val1); NodeSet n2 = new NodeSet(val2); while (true) { if (!n1.MoveNext()) { return false; } if (!n2.MoveNext()) { return false; } string str1 = n1.Value; do { if ((str1 == n2.Value) == isEQ) { return true; } } while (n2.MoveNext()); n2.Reset(); } } /*cmpXslt:*/ static bool cmpQueryQueryO(Operator.Op op, object val1, object val2) { Debug.Assert( op == Operator.Op.LT || op == Operator.Op.GT || op == Operator.Op.LE || op == Operator.Op.GE ); NodeSet n1 = new NodeSet(val1); NodeSet n2 = new NodeSet(val2); while (true) { if (!n1.MoveNext()) { return false; } if (!n2.MoveNext()) { return false; } double num1 = NumberFunctions.Number(n1.Value); do { if (cmpNumberNumber(op, num1, NumberFunctions.Number(n2.Value))) { return true; } } while (n2.MoveNext()); n2.Reset(); } } static bool cmpQueryNumber(Operator.Op op, object val1, object val2) { NodeSet n1 = new NodeSet(val1); double n2 = (double)val2; while (n1.MoveNext()) { if (cmpNumberNumber(op, NumberFunctions.Number(n1.Value), n2)) { return true; } } return false; } static bool cmpQueryStringE(Operator.Op op, object val1, object val2) { NodeSet n1 = new NodeSet(val1); string n2 = (string)val2; while (n1.MoveNext()) { if (cmpStringStringE(op, n1.Value, n2)) { return true; } } return false; } static bool cmpQueryStringO(Operator.Op op, object val1, object val2) { NodeSet n1 = new NodeSet(val1); double n2 = NumberFunctions.Number((string)val2); while (n1.MoveNext()) { if (cmpNumberNumberO(op, NumberFunctions.Number(n1.Value), n2)) { return true; } } return false; } static bool cmpRtfQueryE(Operator.Op op, object val1, object val2) { string n1 = Rtf(val1); NodeSet n2 = new NodeSet(val2); while (n2.MoveNext()) { if (cmpStringStringE(op, n1, n2.Value)) { return true; } } return false; } static bool cmpRtfQueryO(Operator.Op op, object val1, object val2) { double n1 = NumberFunctions.Number(Rtf(val1)); NodeSet n2 = new NodeSet(val2); while (n2.MoveNext()) { if (cmpNumberNumberO(op, n1, NumberFunctions.Number(n2.Value))) { return true; } } return false; } static bool cmpQueryBoolE(Operator.Op op, object val1, object val2) { NodeSet n1 = new NodeSet(val1); bool b1 = n1.MoveNext(); bool b2 = (bool)val2; return cmpBoolBoolE(op, b1, b2); } static bool cmpQueryBoolO(Operator.Op op, object val1, object val2) { NodeSet n1 = new NodeSet(val1); double d1 = n1.MoveNext() ? 1.0 : 0; double d2 = NumberFunctions.Number((bool)val2); return cmpNumberNumberO(op, d1, d2); } static bool cmpBoolBoolE(Operator.Op op, bool n1, bool n2) { Debug.Assert(op == Operator.Op.EQ || op == Operator.Op.NE, "Unexpected Operator.op code in cmpBoolBoolE()" ); return (op == Operator.Op.EQ) == (n1 == n2); } static bool cmpBoolBoolE(Operator.Op op, object val1, object val2) { bool n1 = (bool)val1; bool n2 = (bool)val2; return cmpBoolBoolE(op, n1, n2); } static bool cmpBoolBoolO(Operator.Op op, object val1, object val2) { double n1 = NumberFunctions.Number((bool)val1); double n2 = NumberFunctions.Number((bool)val2); return cmpNumberNumberO(op, n1, n2); } static bool cmpBoolNumberE(Operator.Op op, object val1, object val2) { bool n1 = (bool)val1; bool n2 = BooleanFunctions.toBoolean((double)val2); return cmpBoolBoolE(op, n1, n2); } static bool cmpBoolNumberO(Operator.Op op, object val1, object val2) { double n1 = NumberFunctions.Number((bool)val1); double n2 = (double)val2; return cmpNumberNumberO(op, n1, n2); } static bool cmpBoolStringE(Operator.Op op, object val1, object val2) { bool n1 = (bool)val1; bool n2 = BooleanFunctions.toBoolean((string)val2); return cmpBoolBoolE(op, n1, n2); } static bool cmpRtfBoolE(Operator.Op op, object val1, object val2) { bool n1 = BooleanFunctions.toBoolean(Rtf(val1)); bool n2 = (bool)val2; return cmpBoolBoolE(op, n1, n2); } static bool cmpBoolStringO(Operator.Op op, object val1, object val2) { return cmpNumberNumberO(op, NumberFunctions.Number((bool)val1), NumberFunctions.Number((string)val2) ); } static bool cmpRtfBoolO(Operator.Op op, object val1, object val2) { return cmpNumberNumberO(op, NumberFunctions.Number(Rtf(val1)), NumberFunctions.Number((bool)val2) ); } static bool cmpNumberNumber(Operator.Op op, double n1, double n2) { switch (op) { case Operator.Op.LT: return (n1 < n2); case Operator.Op.GT: return (n1 > n2); case Operator.Op.LE: return (n1 <= n2); case Operator.Op.GE: return (n1 >= n2); case Operator.Op.EQ: return (n1 == n2); case Operator.Op.NE: return (n1 != n2); } Debug.Assert(false, "Unexpected Operator.op code in cmpNumberNumber()"); return false; } static bool cmpNumberNumberO(Operator.Op op, double n1, double n2) { switch (op) { case Operator.Op.LT: return (n1 < n2); case Operator.Op.GT: return (n1 > n2); case Operator.Op.LE: return (n1 <= n2); case Operator.Op.GE: return (n1 >= n2); } Debug.Assert(false, "Unexpected Operator.op code in cmpNumberNumber()"); return false; } static bool cmpNumberNumber(Operator.Op op, object val1, object val2) { double n1 = (double)val1; double n2 = (double)val2; return cmpNumberNumber(op, n1, n2); } static bool cmpStringNumber(Operator.Op op, object val1, object val2) { double n2 = (double)val2; double n1 = NumberFunctions.Number((string)val1); return cmpNumberNumber(op, n1, n2); } static bool cmpRtfNumber(Operator.Op op, object val1, object val2) { double n2 = (double)val2; double n1 = NumberFunctions.Number(Rtf(val1)); return cmpNumberNumber(op, n1, n2); } static bool cmpStringStringE(Operator.Op op, string n1, string n2) { Debug.Assert(op == Operator.Op.EQ || op == Operator.Op.NE, "Unexpected Operator.op code in cmpStringStringE()" ); return (op == Operator.Op.EQ) == (n1 == n2); } static bool cmpStringStringE(Operator.Op op, object val1, object val2) { string n1 = (string)val1; string n2 = (string)val2; return cmpStringStringE(op, n1, n2); } static bool cmpRtfStringE(Operator.Op op, object val1, object val2) { string n1 = Rtf(val1); string n2 = (string)val2; return cmpStringStringE(op, n1, n2); } static bool cmpRtfRtfE(Operator.Op op, object val1, object val2) { string n1 = Rtf(val1); string n2 = Rtf(val2); return cmpStringStringE(op, n1, n2); } static bool cmpStringStringO(Operator.Op op, object val1, object val2) { double n1 = NumberFunctions.Number((string)val1); double n2 = NumberFunctions.Number((string)val2); return cmpNumberNumberO(op, n1, n2); } static bool cmpRtfStringO(Operator.Op op, object val1, object val2) { double n1 = NumberFunctions.Number(Rtf(val1)); double n2 = NumberFunctions.Number((string)val2); return cmpNumberNumberO(op, n1, n2); } static bool cmpRtfRtfO(Operator.Op op, object val1, object val2) { double n1 = NumberFunctions.Number(Rtf(val1)); double n2 = NumberFunctions.Number(Rtf(val2)); return cmpNumberNumberO(op, n1, n2); } public override XPathNodeIterator Clone() { return new LogicalExpr(this); } private struct NodeSet { private Query opnd; private XPathNavigator current; public NodeSet(object opnd) { this.opnd = (Query)opnd; current = null; } public bool MoveNext() { current = opnd.Advance(); return current != null; } public void Reset() { opnd.Reset(); } public string Value { get { return this.current.Value; } } } private static string Rtf(object o) { return ((XPathNavigator)o).Value; } public override XPathResultType StaticType { get { return XPathResultType.Boolean; } } public override void PrintQuery(XmlWriter w) { w.WriteStartElement(this.GetType().Name); w.WriteAttributeString("op", op.ToString()); opnd1.PrintQuery(w); opnd2.PrintQuery(w); w.WriteEndElement(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void HorizontalAddDouble() { var test = new HorizontalBinaryOpTest__HorizontalAddDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class HorizontalBinaryOpTest__HorizontalAddDouble { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Double> _fld1; public Vector128<Double> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); return testStruct; } public void RunStructFldScenario(HorizontalBinaryOpTest__HorizontalAddDouble testClass) { var result = Sse3.HorizontalAdd(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(HorizontalBinaryOpTest__HorizontalAddDouble testClass) { fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) { var result = Sse3.HorizontalAdd( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Double[] _data2 = new Double[Op2ElementCount]; private static Vector128<Double> _clsVar1; private static Vector128<Double> _clsVar2; private Vector128<Double> _fld1; private Vector128<Double> _fld2; private DataTable _dataTable; static HorizontalBinaryOpTest__HorizontalAddDouble() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); } public HorizontalBinaryOpTest__HorizontalAddDouble() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new DataTable(_data1, _data2, new Double[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse3.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse3.HorizontalAdd( Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse3.HorizontalAdd( Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse3.HorizontalAdd( Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse3).GetMethod(nameof(Sse3.HorizontalAdd), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse3).GetMethod(nameof(Sse3.HorizontalAdd), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse3).GetMethod(nameof(Sse3.HorizontalAdd), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse3.HorizontalAdd( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Double>* pClsVar1 = &_clsVar1) fixed (Vector128<Double>* pClsVar2 = &_clsVar2) { var result = Sse3.HorizontalAdd( Sse2.LoadVector128((Double*)(pClsVar1)), Sse2.LoadVector128((Double*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr); var result = Sse3.HorizontalAdd(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse3.HorizontalAdd(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse3.HorizontalAdd(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new HorizontalBinaryOpTest__HorizontalAddDouble(); var result = Sse3.HorizontalAdd(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new HorizontalBinaryOpTest__HorizontalAddDouble(); fixed (Vector128<Double>* pFld1 = &test._fld1) fixed (Vector128<Double>* pFld2 = &test._fld2) { var result = Sse3.HorizontalAdd( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse3.HorizontalAdd(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) { var result = Sse3.HorizontalAdd( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse3.HorizontalAdd(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse3.HorizontalAdd( Sse2.LoadVector128((Double*)(&test._fld1)), Sse2.LoadVector128((Double*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Double> op1, Vector128<Double> op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var outer = 0; outer < (LargestVectorSize / 16); outer++) { for (var inner = 0; inner < (8 / sizeof(Double)); inner++) { var i1 = (outer * (16 / sizeof(Double))) + inner; var i2 = i1 + (8 / sizeof(Double)); var i3 = (outer * (16 / sizeof(Double))) + (inner * 2); if (BitConverter.DoubleToInt64Bits(result[i1]) != BitConverter.DoubleToInt64Bits(left[i3] + left[i3 + 1])) { succeeded = false; break; } if (BitConverter.DoubleToInt64Bits(result[i2]) != BitConverter.DoubleToInt64Bits(right[i3] + right[i3 + 1])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse3)}.{nameof(Sse3.HorizontalAdd)}<Double>(Vector128<Double>, Vector128<Double>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// // Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // 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. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !SILVERLIGHT && !__IOS__ && !__ANDROID__ && !NETSTANDARD1_3 namespace NLog.Internal { using System; using System.Collections.Generic; using System.IO; using NLog.Common; /// <summary> /// Watches multiple files at the same time and raises an event whenever /// a single change is detected in any of those files. /// </summary> internal sealed class MultiFileWatcher : IDisposable { private readonly Dictionary<string, FileSystemWatcher> _watcherMap = new Dictionary<string, FileSystemWatcher>(); /// <summary> /// The types of changes to watch for. /// </summary> public NotifyFilters NotifyFilters { get; set; } /// <summary> /// Occurs when a change is detected in one of the monitored files. /// </summary> public event FileSystemEventHandler FileChanged; public MultiFileWatcher() : this(NotifyFilters.LastWrite | NotifyFilters.CreationTime | NotifyFilters.Size | NotifyFilters.Security | NotifyFilters.Attributes) { } public MultiFileWatcher(NotifyFilters notifyFilters) { NotifyFilters = notifyFilters; } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { FileChanged = null; // Release event listeners StopWatching(); GC.SuppressFinalize(this); } /// <summary> /// Stops watching all files. /// </summary> public void StopWatching() { lock (_watcherMap) { foreach (FileSystemWatcher watcher in _watcherMap.Values) { StopWatching(watcher); } _watcherMap.Clear(); } } /// <summary> /// Stops watching the specified file. /// </summary> /// <param name="fileName"></param> public void StopWatching(string fileName) { lock (_watcherMap) { FileSystemWatcher watcher; if (_watcherMap.TryGetValue(fileName, out watcher)) { StopWatching(watcher); _watcherMap.Remove(fileName); } } } /// <summary> /// Watches the specified files for changes. /// </summary> /// <param name="fileNames">The file names.</param> public void Watch(IEnumerable<string> fileNames) { if (fileNames == null) { return; } foreach (string s in fileNames) { Watch(s); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Watcher is released in Dispose()")] internal void Watch(string fileName) { var directory = Path.GetDirectoryName(fileName); if (!Directory.Exists(directory)) { InternalLogger.Warn("Cannot watch file {0} for changes as directory {1} doesn't exist", fileName, directory); return; } var fileFilter = Path.GetFileName(fileName); lock (_watcherMap) { if (_watcherMap.ContainsKey(fileName)) return; FileSystemWatcher watcher = null; try { watcher = new FileSystemWatcher { Path = directory, Filter = fileFilter, NotifyFilter = NotifyFilters }; watcher.Created += OnFileChanged; watcher.Changed += OnFileChanged; watcher.Deleted += OnFileChanged; watcher.Renamed += OnFileChanged; watcher.Error += OnWatcherError; watcher.EnableRaisingEvents = true; InternalLogger.Debug("Watching path '{0}' filter '{1}' for changes.", watcher.Path, watcher.Filter); _watcherMap.Add(fileName, watcher); } catch (Exception ex) { InternalLogger.Error(ex, "Failed Watching path '{0}' with file '{1}' for changes.", directory, fileName); if (ex.MustBeRethrown()) throw; if (watcher != null) { StopWatching(watcher); } } } } private void StopWatching(FileSystemWatcher watcher) { try { InternalLogger.Debug("Stopping file watching for path '{0}' filter '{1}'", watcher.Path, watcher.Filter); watcher.EnableRaisingEvents = false; watcher.Created -= OnFileChanged; watcher.Changed -= OnFileChanged; watcher.Deleted -= OnFileChanged; watcher.Renamed -= OnFileChanged; watcher.Error -= OnWatcherError; watcher.Dispose(); } catch (Exception ex) { InternalLogger.Error(ex, "Failed to stop file watcher for path '{0}' filter '{1}'", watcher.Path, watcher.Filter); if (ex.MustBeRethrown()) throw; } } private void OnWatcherError(object source, ErrorEventArgs e) { var watcherPath = string.Empty; var watcher = source as FileSystemWatcher; if (watcher != null) watcherPath = watcher.Path; var exception = e.GetException(); if (exception != null) InternalLogger.Warn(exception, "Error Watching Path {0}", watcherPath); else InternalLogger.Warn("Error Watching Path {0}", watcherPath); } private void OnFileChanged(object source, FileSystemEventArgs e) { var changed = FileChanged; if (changed != null) { try { changed(source, e); } catch (Exception ex) { InternalLogger.Error(ex, "Error Handling File Changed"); if (ex.MustBeRethrownImmediately()) throw; } } } } } #endif